Upload folder using huggingface_hub (part 11)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+19
- .venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/INSTALLERAdded+1
- .venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/LICENSEAdded+1060
- .venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/METADATAAdded+1383
- .venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/RECORDAdded
- .venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/REQUESTEDAdded
- .venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/WHEELAdded+6
- .venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/entry_points.txtAdded+3
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_indexing.pyAdded+692
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_interval.pyAdded+922
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_interval_range.pyAdded+390
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_interval_tree.pyAdded+208
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_join.pyAdded+44
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_pickle.pyAdded+10
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_setops.pyAdded+208
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/__init__.pyAdded
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/conftest.pyAdded+27
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_analytics.pyAdded+263
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_astype.pyAdded+30
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_compat.pyAdded+122
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_constructors.pyAdded+872
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_conversion.pyAdded+208
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_copy.pyAdded+96
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_drop.pyAdded+188
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_duplicates.pyAdded+357
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_equivalence.pyAdded+284
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_formats.pyAdded+207
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_get_level_values.pyAdded+133
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_get_set.pyAdded+380
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_indexing.pyAdded+1031
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_integrity.pyAdded+289
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_isin.pyAdded+104
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_join.pyAdded+270
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_lexsort.pyAdded+46
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_missing.pyAdded+111
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_monotonic.pyAdded+188
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_names.pyAdded+201
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_partial_indexing.pyAdded+148
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_pickle.pyAdded+10
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_reindex.pyAdded+174
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_reshape.pyAdded+224
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_setops.pyAdded+778
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_sorting.pyAdded+346
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_take.pyAdded+78
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_util.pyAdded+63
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/numeric/__init__.pyAdded
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/numeric/test_astype.pyAdded+95
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/numeric/test_indexing.pyAdded+623
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/numeric/test_join.pyAdded+368
- .venv/lib/python3.12/site-packages/pandas/tests/indexes/numeric/test_numeric.pyAdded+550
129 unmodified lines130131132129 unmodified lines.venv/lib/python3.12/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text129 unmodified lines130131132133134135136137138139140141142143144145146147148149150151129 unmodified lines.venv/lib/python3.12/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/propcache/_helpers_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_acero.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_azurefs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_compute.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_csv.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_dataset.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_dataset_parquet.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_dataset_parquet_encryption.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_feather.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_flight.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_fs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_gcsfs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_hdfs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_json.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_orc.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_parquet.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_parquet_encryption.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_s3fs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/pyarrow/_substrait.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1uv1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060BSD 3-Clause License
Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development TeamAll rights reserved.
Copyright (c) 2011-2026, Open source contributors.
Redistribution and use in source and binary forms, with or withoutmodification, 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, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.Copyright (c) 2010-2019 Keith GoodmanCopyright (c) 2019 Bottleneck DevelopersAll rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, 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, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSEARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BELIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, ORCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OFSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESSINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER INCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THEPOSSIBILITY OF SUCH DAMAGE.Copyright 2017- Paul Ganssle <paul@ganssle.io>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 asall contributions that have been re-licensed (see AUTHORS file for the list ofcontributors who have re-licensed their code).--------------------------------------------------------------------------------dateutil - Extensions to the standard Python datetime module.
Copyright (c) 2003-2011 - Gustavo Niemeyer <gustavo@niemeyer.net>Copyright (c) 2012-2014 - Tomi Pieviläinen <tomi.pievilainen@iki.fi>Copyright (c) 2014-2016 - Yaron de Leeuw <me@jarondl.net>Copyright (c) 2015- - Paul Ganssle <paul@ganssle.io>Copyright (c) 2015- - dateutil contributors (see AUTHORS file)
All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, 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 NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER ORCONTRIBUTORS 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, ORPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, 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.# MIT License
Copyright (c) 2019 Hadley Wickham; RStudio; and Evan Miller
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.Based on http://opensource.org/licenses/MIT
This is a template. Complete and ship as file LICENSE the following 2lines (only)
YEAR:COPYRIGHT HOLDER:
and specify as
License: MIT + file LICENSE
Copyright (c) <YEAR>, <COPYRIGHT HOLDER>
Permission is hereby granted, free of charge, to any person obtaininga copy of this software and associated documentation files (the"Software"), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:
The above copyright notice and this permission notice shall beincluded 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 OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ANDNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BELIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTIONOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTIONWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.The MIT License
Copyright (c) 2008- Attractive Chaos <attractor@live.co.uk>
Permission is hereby granted, free of charge, to any person obtaininga copy of this software and associated documentation files (the"Software"), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:
The above copyright notice and this permission notice shall beincluded 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 OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ANDNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERSBE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN ANACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.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 obtaininga copy of this software and associated documentation files (the"Software"), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:
The above copyright notice and this permission notice shall beincluded 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 OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANYCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THESOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.----------------------------------------------------------------------
Authors/contributors include:
A. WilcoxAda WorcesterAlex DowadAlex SuykovAlexander MonakovAndre McCurdyAndrew KelleyAnthony G. BasileAric BelsitoArvid PiccianiBartosz BrachaczekBenjamin PetersonBobby BinghamBoris BrezillonBrent CookChris SpiegelClément VasseurDaniel MicayDaniel SabogalDaurnimatorDavid CarlierDavid EdelsohnDenys VlasenkoDmitry IvanovDmitry V. LevinDrew DeVaultEmil Renner BerthingFangrui SongFelix FietkauFelix JandaGianluca AnzolinHauke MehrtensHe XHiltjo PosthumaIsaac DunhamJaydeep PatilJens GustedtJeremy HuntworkJo-Philipp WichJoakim SindholtJohn SpencerJulien RamseierJustin CormackKaarle RitvanenKhem RajKylie McClainLeah NeukirchenLuca BarbatoLuka PerkovM Farkas-Dyck (Strake)Mahesh BodapatiMarkus WichmannMasanori OginoMichael ClarkMichael ForneyMikhail KremnyovNatanael CopaNicholas J. KainorcPascal CuoqPatrick OppenlanderPetr HosekPetr SkocikPierre CarrierReini UrbanRich FelkerRichard PenningtonRyan FairfaxSamuel HollandSegev FinerShizsinSolar DesignerStefan KristianssonStefan O'RearSzabolcs NagyTimo TeräsTrutz BehnValentin OchsWill DietzWilliam HaddonWilliam Pitcock
Portions of this software are derived from third-party works licensedunder terms compatible with the above MIT license:
The TRE regular expression implementation (src/regex/reg* andsrc/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensedunder a 2-clause BSD license (license text in the source files). Theincluded version has been heavily modified by Rich Felker in 2012, inthe interests of size, simplicity, and namespace cleanliness.
Much of the math library code (src/math/* and src/complex/*) isCopyright © 1993,2004 Sun Microsystems orCopyright © 2003-2011 David Schultz orCopyright © 2003-2009 Steven G. Kargl orCopyright © 2003-2009 Bruce D. Evans orCopyright © 2008 Stephen L. Moshier orCopyright © 2017-2018 Arm Limitedand labelled as such in comments in the individual source files. Allhave been licensed under extremely permissive terms.
The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008The Android Open Source Project and is licensed under a two-clause BSDlicense. It was taken from Bionic libc, used on Android.
The AArch64 memcpy and memset code (src/string/aarch64/*) areCopyright © 1999-2019, Arm Limited.
The implementation of DES for crypt (src/crypt/crypt_des.c) isCopyright © 1994 David Burren. It is licensed under a BSD license.
The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) wasoriginally written by Solar Designer and placed into the publicdomain. The code also comes with a fallback permissive license for usein jurisdictions that may not recognize the public domain.
The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011Valentin Ochs and is licensed under an MIT-style license.
The x86_64 port was written by Nicholas J. Kain and is licensed underthe standard MIT terms.
The mips and microblaze ports were originally written by RichardPennington for use in the ellcc project. The original code was adaptedby Rich Felker for build system and code conventions during upstreamintegration. It is licensed under the standard MIT terms.
The mips64 port was contributed by Imagination Technologies and islicensed 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 licensedunder the standard MIT terms.
All other files which have no copyright comments are original worksproduced specifically for use as part of this library, written eitherby Rich Felker, the main author of the library, or by one or morecontibutors listed above. Details on authorship of individual filescan be found in the git version control history of the project. Theomission of copyright and license comments in each file is in theinterest 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 intoapplications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omitthe copyright notice and permission notice otherwise required by thelicense, and to use these files without any requirement ofattribution. These files include substantial contributions from:
Bobby BinghamJohn SpencerNicholas J. KainRich FelkerRichard PenningtonStefan KristianssonSzabolcs Nagy
all of whom have explicitly granted such permission.
This file previously contained text expressing a belief that most ofthe files covered by the above exception were sufficiently trivial notto be subject to copyright, resulting in confusion over whether itnegated the permissions granted in the license. In the spirit ofpermissive licensing, and of not having licensing issues being anobstacle to adoption, that text has been removed.Copyright (c) 2005-2023, NumPy Developers.All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet:
* 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 NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHTOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOTLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANYTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 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 withoutmodification, 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" ANDANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.A. HISTORY OF THE SOFTWARE==========================
Python was created in the early 1990s by Guido van Rossum at StichtingMathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlandsas a successor of a language called ABC. Guido remains Python'sprincipal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation forNational Research Initiatives (CNRI, see https://www.cnri.reston.va.us)in Reston, Virginia where he released several versions of thesoftware.
In May 2000, Guido and the Python core development team moved toBeOpen.com to form the BeOpen PythonLabs team. In October of the sameyear, the PythonLabs team moved to Digital Creations, which becameZope Corporation. In 2001, the Python Software Foundation (PSF, seehttps://www.python.org/psf/) was formed, a non-profit organizationcreated 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 forthe Open Source Definition). Historically, most, but not all, Pythonreleases have also been GPL-compatible; the table below summarizesthe 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'sdirection to make these releases possible.
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON===============================================================
Python software and documentation are licensed under thePython Software Foundation License Version 2.
Starting with Python 3.8.6, examples, recipes, and other code inthe documentation are dual licensed under the PSF License Version 2and 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 andotherwise using this software ("Python") in source or binary form andits associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF herebygrants 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 versionprepared by Licensee.
3. In the event Licensee prepares a derivative work that is based onor incorporates Python or any part thereof, and wants to makethe derivative work available to others as provided herein, thenLicensee hereby agrees to include in any such work a brief summary ofthe changes made to Python.
4. PSF is making Python available to Licensee on an "AS IS"basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS ORIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO ANDDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESSFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOTINFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHONFOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS ASA 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 materialbreach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create anyrelationship of agency, partnership, or joint venture between PSF andLicensee. This License Agreement does not grant permission to use PSFtrademarks or trade name in a trademark sense to endorse or promoteproducts or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python, Licenseeagrees to be bound by the terms and conditions of this LicenseAgreement.
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 anoffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and theIndividual or Organization ("Licensee") accessing and otherwise usingthis software in source or binary form and its associateddocumentation ("the Software").
2. Subject to the terms and conditions of this BeOpen Python LicenseAgreement, BeOpen hereby grants Licensee a non-exclusive,royalty-free, world-wide license to reproduce, analyze, test, performand/or display publicly, prepare derivative works, distribute, andotherwise use the Software alone or in any derivative version,provided, however, that the BeOpen Python License is retained in theSoftware, 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 ORIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO ANDDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESSFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOTINFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THESOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSSAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANYDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a materialbreach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in allrespects by the law of the State of California, excluding conflict oflaw provisions. Nothing in this License Agreement shall be deemed tocreate any relationship of agency, partnership, or joint venturebetween BeOpen and Licensee. This License Agreement does not grantpermission to use BeOpen trademarks or trade names in a trademarksense to endorse or promote products or services of Licensee, or anythird party. As an exception, the "BeOpen Python" logos available athttp://www.pythonlabs.com/logos.html may be used according to thepermissions granted on that web page.
7. By copying, installing or otherwise using the software, Licenseeagrees to be bound by the terms and conditions of this LicenseAgreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1---------------------------------------
1. This LICENSE AGREEMENT is between the Corporation for NationalResearch 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 insource or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRIhereby grants Licensee a nonexclusive, royalty-free, world-widelicense to reproduce, analyze, test, perform and/or display publicly,prepare derivative works, distribute, and otherwise use Python 1.6.1alone or in any derivative version, provided, however, that CNRI'sLicense Agreement and CNRI's notice of copyright, i.e., "Copyright (c)1995-2001 Corporation for National Research Initiatives; All RightsReserved" are retained in Python 1.6.1 alone or in any derivativeversion prepared by Licensee. Alternately, in lieu of CNRI's LicenseAgreement, Licensee may substitute the following text (omitting thequotes): "Python 1.6.1 is made available subject to the terms andconditions in CNRI's License Agreement. This Agreement together withPython 1.6.1 may be located on the internet using the followingunique, persistent identifier (known as a handle): 1895.22/1013. ThisAgreement may also be obtained from a proxy server on the internetusing the following URL: http://hdl.handle.net/1895.22/1013".
3. In the event Licensee prepares a derivative work that is based onor incorporates Python 1.6.1 or any part thereof, and wants to makethe derivative work available to others as provided herein, thenLicensee hereby agrees to include in any such work a brief summary ofthe 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 ORIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO ANDDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESSFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOTINFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS ASA 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 materialbreach of its terms and conditions.
7. This License Agreement shall be governed by the federalintellectual property law of the United States, including withoutlimitation the federal copyright law, and, to the extent suchU.S. federal law does not apply, by the law of the Commonwealth ofVirginia, excluding Virginia's conflict of law provisions.Notwithstanding the foregoing, with regard to derivative works basedon Python 1.6.1 that incorporate non-separable material that waspreviously distributed under the GNU General Public License (GPL), thelaw of the Commonwealth of Virginia shall govern this LicenseAgreement only as to issues arising under or with respect toParagraphs 4, 5, and 7 of this License Agreement. Nothing in thisLicense Agreement shall be deemed to create any relationship ofagency, partnership, or joint venture between CNRI and Licensee. ThisLicense Agreement does not grant permission to use CNRI trademarks ortrade name in a trademark sense to endorse or promote products orservices 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 bebound 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 itsdocumentation for any purpose and without fee is hereby granted,provided that the above copyright notice appear in all copies and thatboth that copyright notice and this permission notice appear insupporting documentation, and that the name of Stichting MathematischCentrum or CWI not be used in advertising or publicity pertaining todistribution of the software without specific, written priorpermission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TOTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY ANDFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLEFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGESWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN ANACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUTOF 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 anypurpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITHREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITYAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROMLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OROTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ORPERFORMANCE OF THIS SOFTWARE.Copyright (c) 2014, Al SweigartAll rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, 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, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.Copyright (c) 2017 Anthony Sottile
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 INTHE SOFTWARE.Copyright (c) 2015-2019 Jared Hobbs
Permission is hereby granted, free of charge, to any person obtaining a copy ofthis software and associated documentation files (the "Software"), to deal inthe Software without restriction, including without limitation the rights touse, copy, modify, merge, publish, distribute, sublicense, and/or sell copiesof the Software, and to permit persons to whom the Software is furnished to doso, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.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 withoutmodification, are permitted provided that the following conditions are met:* Redistributions of source code must retain the above copyrightnotice, this list of conditions and the following disclaimer.* Redistributions in binary form must reproduce the above copyrightnotice, this list of conditions and the following disclaimer in thedocumentation and/or other materials provided with the distribution.* Neither the name of ESN, Electronic Arts Inc. nor thenames of its contributors may be used to endorse or promote productsderived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ANDANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL ELECTRONIC ARTS INC. BE LIABLEFOR 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 ANDON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, 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 libraryhttps://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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383Metadata-Version: 2.1Name: pandasVersion: 3.0.5Summary: Powerful data structures for data analysis, time series, and statisticsAuthor-Email: The Pandas Development Team <pandas-dev@python.org>License: 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. 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.Copyright 2017- Paul Ganssle <paul@ganssle.io> 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 <gustavo@niemeyer.net> Copyright (c) 2012-2014 - Tomi Pieviläinen <tomi.pievilainen@iki.fi> Copyright (c) 2014-2016 - Yaron de Leeuw <me@jarondl.net> Copyright (c) 2015- - Paul Ganssle <paul@ganssle.io> 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.# 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. 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) <YEAR>, <COPYRIGHT HOLDER> 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. The MIT License Copyright (c) 2008- Attractive Chaos <attractor@live.co.uk> 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.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.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. 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.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. 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.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.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.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.Classifier: Development Status :: 5 - Production/StableClassifier: Environment :: ConsoleClassifier: Intended Audience :: Science/ResearchClassifier: License :: OSI Approved :: BSD LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: CythonClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: Scientific/EngineeringProject-URL: homepage, https://pandas.pydata.orgProject-URL: documentation, https://pandas.pydata.org/docs/Project-URL: repository, https://github.com/pandas-dev/pandasRequires-Python: >=3.11Requires-Dist: numpy>=1.26.0; python_version < "3.14"Requires-Dist: numpy>=2.3.3; python_version >= "3.14"Requires-Dist: python-dateutil>=2.8.2Requires-Dist: tzdata; sys_platform == "win32"Requires-Dist: tzdata; sys_platform == "emscripten"Provides-Extra: testRequires-Dist: hypothesis>=6.116.0; extra == "test"Requires-Dist: pytest<9.1,>=8.3.4; extra == "test"Requires-Dist: pytest-xdist>=3.6.1; extra == "test"Provides-Extra: pyarrowRequires-Dist: pyarrow>=13.0.0; extra == "pyarrow"Provides-Extra: performanceRequires-Dist: bottleneck>=1.4.2; extra == "performance"Requires-Dist: numba>=0.60.0; extra == "performance"Requires-Dist: numexpr>=2.10.2; extra == "performance"Provides-Extra: computationRequires-Dist: scipy>=1.14.1; extra == "computation"Requires-Dist: xarray>=2024.10.0; extra == "computation"Provides-Extra: fssRequires-Dist: fsspec>=2024.10.0; extra == "fss"Provides-Extra: awsRequires-Dist: s3fs>=2024.10.0; extra == "aws"Provides-Extra: gcpRequires-Dist: gcsfs>=2024.10.0; extra == "gcp"Provides-Extra: excelRequires-Dist: odfpy>=1.4.1; extra == "excel"Requires-Dist: openpyxl>=3.1.5; extra == "excel"Requires-Dist: python-calamine>=0.3.0; extra == "excel"Requires-Dist: pyxlsb>=1.0.10; extra == "excel"Requires-Dist: xlrd>=2.0.1; extra == "excel"Requires-Dist: xlsxwriter>=3.2.0; extra == "excel"Provides-Extra: parquetRequires-Dist: pyarrow>=13.0.0; extra == "parquet"Provides-Extra: featherRequires-Dist: pyarrow>=13.0.0; extra == "feather"Provides-Extra: icebergRequires-Dist: pyiceberg>=0.8.1; extra == "iceberg"Provides-Extra: hdf5Requires-Dist: tables>=3.10.1; extra == "hdf5"Provides-Extra: spssRequires-Dist: pyreadstat>=1.2.8; extra == "spss"Provides-Extra: postgresqlRequires-Dist: SQLAlchemy>=2.0.36; extra == "postgresql"Requires-Dist: psycopg2>=2.9.10; extra == "postgresql"Requires-Dist: adbc-driver-postgresql>=1.2.0; extra == "postgresql"Provides-Extra: mysqlRequires-Dist: SQLAlchemy>=2.0.36; extra == "mysql"Requires-Dist: pymysql>=1.1.1; extra == "mysql"Provides-Extra: sql-otherRequires-Dist: SQLAlchemy>=2.0.36; extra == "sql-other"Requires-Dist: adbc-driver-postgresql>=1.2.0; extra == "sql-other"Requires-Dist: adbc-driver-sqlite>=1.2.0; extra == "sql-other"Provides-Extra: htmlRequires-Dist: beautifulsoup4>=4.12.3; extra == "html"Requires-Dist: html5lib>=1.1; extra == "html"Requires-Dist: lxml>=5.3.0; extra == "html"Provides-Extra: xmlRequires-Dist: lxml>=5.3.0; extra == "xml"Provides-Extra: plotRequires-Dist: matplotlib>=3.9.3; extra == "plot"Provides-Extra: output-formattingRequires-Dist: jinja2>=3.1.5; extra == "output-formatting"Requires-Dist: tabulate>=0.9.0; extra == "output-formatting"Provides-Extra: clipboardRequires-Dist: PyQt5>=5.15.9; extra == "clipboard"Requires-Dist: qtpy>=2.4.2; extra == "clipboard"Provides-Extra: compressionRequires-Dist: zstandard>=0.23.0; extra == "compression"Provides-Extra: timezoneRequires-Dist: pytz>=2020.1; extra == "timezone"Provides-Extra: allRequires-Dist: adbc-driver-postgresql>=1.2.0; extra == "all"Requires-Dist: adbc-driver-sqlite>=1.2.0; extra == "all"Requires-Dist: beautifulsoup4>=4.12.3; extra == "all"Requires-Dist: bottleneck>=1.4.2; extra == "all"Requires-Dist: fastparquet>=2024.11.0; extra == "all"Requires-Dist: fsspec>=2024.10.0; extra == "all"Requires-Dist: gcsfs>=2024.10.0; extra == "all"Requires-Dist: html5lib>=1.1; extra == "all"Requires-Dist: hypothesis>=6.116.0; extra == "all"Requires-Dist: jinja2>=3.1.5; extra == "all"Requires-Dist: lxml>=5.3.0; extra == "all"Requires-Dist: matplotlib>=3.9.3; extra == "all"Requires-Dist: numba>=0.60.0; extra == "all"Requires-Dist: numexpr>=2.10.2; extra == "all"Requires-Dist: odfpy>=1.4.1; extra == "all"Requires-Dist: openpyxl>=3.1.5; extra == "all"Requires-Dist: psycopg2>=2.9.10; extra == "all"Requires-Dist: pyarrow>=13.0.0; extra == "all"Requires-Dist: pyiceberg>=0.8.1; extra == "all"Requires-Dist: pymysql>=1.1.1; extra == "all"Requires-Dist: PyQt5>=5.15.9; extra == "all"Requires-Dist: pyreadstat>=1.2.8; extra == "all"Requires-Dist: pytest>=8.3.4; extra == "all"Requires-Dist: pytest-xdist>=3.6.1; extra == "all"Requires-Dist: python-calamine>=0.3.0; extra == "all"Requires-Dist: pytz>=2020.1; extra == "all"Requires-Dist: pyxlsb>=1.0.10; extra == "all"Requires-Dist: qtpy>=2.4.2; extra == "all"Requires-Dist: scipy>=1.14.1; extra == "all"Requires-Dist: s3fs>=2024.10.0; extra == "all"Requires-Dist: SQLAlchemy>=2.0.36; extra == "all"Requires-Dist: tables>=3.10.1; extra == "all"Requires-Dist: tabulate>=0.9.0; extra == "all"Requires-Dist: xarray>=2024.10.0; extra == "all"Requires-Dist: xlrd>=2.0.1; extra == "all"Requires-Dist: xlsxwriter>=3.2.0; extra == "all"Requires-Dist: zstandard>=0.23.0; extra == "all"Description-Content-Type: text/markdown
<picture align="center"> <source media="(prefers-color-scheme: dark)" srcset="https://pandas.pydata.org/static/img/pandas_white.svg"> <img alt="Pandas Logo" src="https://pandas.pydata.org/static/img/pandas.svg"></picture>
-----------------
# pandas: A Powerful Python Data Analysis Toolkit
| | || --- | --- || Testing | [](https://github.com/pandas-dev/pandas/actions/workflows/unit-tests.yml) [](https://codecov.io/gh/pandas-dev/pandas) || Package | [](https://pypi.org/project/pandas/) [](https://pypi.org/project/pandas/) [](https://anaconda.org/conda-forge/pandas) [](https://anaconda.org/conda-forge/pandas) || Meta | [](https://numfocus.org) [](https://doi.org/10.5281/zenodo.3509134) [](https://github.com/pandas-dev/pandas/blob/main/LICENSE) [](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) [](https://insights.linuxfoundation.org/project/pandas-dev-pandas) |
## What is it?
**pandas** is a Python package that provides fast, flexible, and expressive datastructures designed to make working with "relational" or "labeled" data botheasy and intuitive. It aims to be the fundamental high-level building block fordoing practical, **real-world** data analysis in Python. Additionally, it hasthe broader goal of becoming **the most powerful and flexible open-source dataanalysis/manipulation tool available in any language**. It is already well onits 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 FeaturesHere 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 itThe 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 [PythonPackage Index (PyPI)](https://pypi.org/project/pandas) and on [Conda](https://anaconda.org/conda-forge/pandas).
```sh# condaconda install -c conda-forge pandas```
```sh# or PyPIpip 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 fulldetails, 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.readthedocs.io/en/latest/) (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 sourcesTo install pandas from source you need [Cython](https://cython.org/) in addition to the normaldependencies above. Cython can be installed from PyPI:
```shpip install cython```
In the `pandas` directory (same one where you found this file aftercloning the git repo), execute:
```shpip install .```
or for installing in [development mode](https://pip.pypa.io/en/latest/cli/pip_install/#install-editable):
```shpython -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)
## DocumentationThe official documentation is hosted on [PyData.org](https://pandas.pydata.org/pandas-docs/stable/).
## BackgroundWork on ``pandas`` started at [AQR](https://www.aqr.com/) (a quantitative hedge fund) in 2008 andhas 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 DevelopmentMost 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
[](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)**.
If you are simply looking to start working with the pandas codebase, navigate to the [GitHub "issues" tab](https://github.com/pandas-dev/pandas/issues) and start looking through interesting issues. There are a number of issues listed under [Docs](https://github.com/pandas-dev/pandas/issues?q=is%3Aissue%20state%3Aopen%20label%3ADocs%20sort%3Aupdated-desc) and [good first issue](https://github.com/pandas-dev/pandas/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22good%20first%20issue%22%20sort%3Aupdated-desc) where you could start out.
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)
<hr>
[Go to Top](#table-of-contents)123456Wheel-Version: 1.0Generator: mesonRoot-Is-Purelib: falseTag: cp312-cp312-manylinux_2_24_x86_64Tag: cp312-cp312-manylinux_2_28_x86_64
123[pandas_plotting_backends]matplotlib = pandas:plotting._matplotlib
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692import re
import numpy as npimport pytest
from pandas.errors import InvalidIndexError
from pandas import ( NA, CategoricalIndex, DatetimeIndex, Index, Interval, IntervalIndex, MultiIndex, NaT, Timedelta, Timestamp, array, date_range, interval_range, isna, period_range, timedelta_range,)import pandas._testing as tm
class TestGetItem: def test_getitem(self, closed): idx = IntervalIndex.from_arrays((0, 1, np.nan), (1, 2, np.nan), closed=closed) assert idx[0] == Interval(0.0, 1.0, closed=closed) assert idx[1] == Interval(1.0, 2.0, closed=closed) assert isna(idx[2])
result = idx[0:1] expected = IntervalIndex.from_arrays((0.0,), (1.0,), closed=closed) tm.assert_index_equal(result, expected)
result = idx[0:2] expected = IntervalIndex.from_arrays((0.0, 1), (1.0, 2.0), closed=closed) tm.assert_index_equal(result, expected)
result = idx[1:3] expected = IntervalIndex.from_arrays( (1.0, np.nan), (2.0, np.nan), closed=closed ) tm.assert_index_equal(result, expected)
def test_getitem_2d_deprecated(self): # GH#30588 multi-dim indexing is deprecated, but raising is also acceptable idx = IntervalIndex.from_breaks(range(11), closed="right") with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"): idx[:, None] with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"): # GH#44051 idx[True] with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"): # GH#44051 idx[False]
class TestWhere: def test_where(self, listlike_box): klass = listlike_box
idx = IntervalIndex.from_breaks(range(11), closed="right") cond = [True] * len(idx) expected = idx result = expected.where(klass(cond)) tm.assert_index_equal(result, expected)
cond = [False] + [True] * len(idx[1:]) expected = IntervalIndex([np.nan, *idx[1:].tolist()]) result = idx.where(klass(cond)) tm.assert_index_equal(result, expected)
class TestTake: def test_take(self, closed): index = IntervalIndex.from_breaks(range(11), closed=closed)
result = index.take(range(10)) tm.assert_index_equal(result, index)
result = index.take([0, 0, 1]) expected = IntervalIndex.from_arrays([0, 0, 1], [1, 1, 2], closed=closed) tm.assert_index_equal(result, expected)
class TestGetLoc: @pytest.mark.parametrize("side", ["right", "left", "both", "neither"]) def test_get_loc_interval(self, closed, side): idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
for bound in [[0, 1], [1, 2], [2, 3], [3, 4], [0, 2], [2.5, 3], [-1, 4]]: # if get_loc is supplied an interval, it should only search # for exact matches, not overlaps or covers, else KeyError. msg = re.escape(f"Interval({bound[0]}, {bound[1]}, closed='{side}')") if closed == side: if bound == [0, 1]: assert idx.get_loc(Interval(0, 1, closed=side)) == 0 elif bound == [2, 3]: assert idx.get_loc(Interval(2, 3, closed=side)) == 1 else: with pytest.raises(KeyError, match=msg): idx.get_loc(Interval(*bound, closed=side)) else: with pytest.raises(KeyError, match=msg): idx.get_loc(Interval(*bound, closed=side))
@pytest.mark.parametrize("scalar", [-0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5]) def test_get_loc_scalar(self, closed, scalar): # correct = {side: {query: answer}}. # If query is not in the dict, that query should raise a KeyError correct = { "right": {0.5: 0, 1: 0, 2.5: 1, 3: 1}, "left": {0: 0, 0.5: 0, 2: 1, 2.5: 1}, "both": {0: 0, 0.5: 0, 1: 0, 2: 1, 2.5: 1, 3: 1}, "neither": {0.5: 0, 2.5: 1}, }
idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
# if get_loc is supplied a scalar, it should return the index of # the interval which contains the scalar, or KeyError. if scalar in correct[closed].keys(): assert idx.get_loc(scalar) == correct[closed][scalar] else: with pytest.raises(KeyError, match=str(scalar)): idx.get_loc(scalar)
@pytest.mark.parametrize("scalar", [-1, 0, 0.5, 3, 4.5, 5, 6]) def test_get_loc_length_one_scalar(self, scalar, closed): # GH 20921 index = IntervalIndex.from_tuples([(0, 5)], closed=closed) if scalar in index[0]: result = index.get_loc(scalar) assert result == 0 else: with pytest.raises(KeyError, match=str(scalar)): index.get_loc(scalar)
@pytest.mark.parametrize("left, right", [(0, 5), (-1, 4), (-1, 6), (6, 7)]) def test_get_loc_length_one_interval(self, left, right, closed, other_closed): # GH 20921 index = IntervalIndex.from_tuples([(0, 5)], closed=closed) interval = Interval(left, right, closed=other_closed) if interval == index[0]: result = index.get_loc(interval) assert result == 0 else: with pytest.raises( KeyError, match=re.escape(f"Interval({left}, {right}, closed='{other_closed}')"), ): index.get_loc(interval)
# Make consistent with test_interval_new.py (see #16316, #16386) @pytest.mark.parametrize( "breaks", [ date_range("20180101", periods=4), date_range("20180101", periods=4, tz="US/Eastern"), timedelta_range("0 days", periods=4), ], ids=lambda x: str(x.dtype), ) def test_get_loc_datetimelike_nonoverlapping(self, breaks): # GH 20636 # nonoverlapping = IntervalIndex method and no i8 conversion index = IntervalIndex.from_breaks(breaks)
value = index[0].mid result = index.get_loc(value) expected = 0 assert result == expected
interval = Interval(index[0].left, index[0].right) result = index.get_loc(interval) expected = 0 assert result == expected
@pytest.mark.parametrize( "arrays", [ (date_range("20180101", periods=4), date_range("20180103", periods=4)), ( date_range("20180101", periods=4, tz="US/Eastern"), date_range("20180103", periods=4, tz="US/Eastern"), ), ( timedelta_range("0 days", periods=4), timedelta_range("2 days", periods=4), ), ], ids=lambda x: str(x[0].dtype), ) def test_get_loc_datetimelike_overlapping(self, arrays): # GH 20636 index = IntervalIndex.from_arrays(*arrays)
value = index[0].mid + Timedelta("12 hours") result = index.get_loc(value) expected = slice(0, 2, None) assert result == expected
interval = Interval(index[0].left, index[0].right) result = index.get_loc(interval) expected = 0 assert result == expected
@pytest.mark.parametrize( "values", [ date_range("2018-01-04", periods=4, freq="-1D"), date_range("2018-01-04", periods=4, freq="-1D", tz="US/Eastern"), timedelta_range("3 days", periods=4, freq="-1D"), np.arange(3.0, -1.0, -1.0), np.arange(3, -1, -1), ], ids=lambda x: str(x.dtype), ) def test_get_loc_decreasing(self, values): # GH 25860 index = IntervalIndex.from_arrays(values[1:], values[:-1]) result = index.get_loc(index[0]) expected = 0 assert result == expected
@pytest.mark.parametrize("key", [[5], (2, 3)]) def test_get_loc_non_scalar_errors(self, key): # GH 31117 idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)])
msg = str(key) with pytest.raises(InvalidIndexError, match=msg): idx.get_loc(key)
def test_get_indexer_with_nans(self): # GH#41831 index = IntervalIndex([np.nan, Interval(1, 2), np.nan])
expected = np.array([True, False, True]) for key in [None, np.nan, NA]: assert key in index result = index.get_loc(key) tm.assert_numpy_array_equal(result, expected)
for key in [NaT, np.timedelta64("NaT", "ns"), np.datetime64("NaT", "ns")]: with pytest.raises(KeyError, match=str(key)): index.get_loc(key)
class TestGetIndexer: @pytest.mark.parametrize( "query, expected", [ ([Interval(2, 4, closed="right")], [1]), ([Interval(2, 4, closed="left")], [-1]), ([Interval(2, 4, closed="both")], [-1]), ([Interval(2, 4, closed="neither")], [-1]), ([Interval(1, 4, closed="right")], [-1]), ([Interval(0, 4, closed="right")], [-1]), ([Interval(0.5, 1.5, closed="right")], [-1]), ([Interval(2, 4, closed="right"), Interval(0, 1, closed="right")], [1, -1]), ([Interval(2, 4, closed="right"), Interval(2, 4, closed="right")], [1, 1]), ([Interval(5, 7, closed="right"), Interval(2, 4, closed="right")], [2, 1]), ([Interval(2, 4, closed="right"), Interval(2, 4, closed="left")], [1, -1]), ], ) def test_get_indexer_with_interval(self, query, expected): tuples = [(0, 2), (2, 4), (5, 7)] index = IntervalIndex.from_tuples(tuples, closed="right")
result = index.get_indexer(query) expected = np.array(expected, dtype="intp") tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize( "query, expected", [ ([-0.5], [-1]), ([0], [-1]), ([0.5], [0]), ([1], [0]), ([1.5], [1]), ([2], [1]), ([2.5], [-1]), ([3], [-1]), ([3.5], [2]), ([4], [2]), ([4.5], [-1]), ([1, 2], [0, 1]), ([1, 2, 3], [0, 1, -1]), ([1, 2, 3, 4], [0, 1, -1, 2]), ([1, 2, 3, 4, 2], [0, 1, -1, 2, 1]), ], ) def test_get_indexer_with_int_and_float(self, query, expected): tuples = [(0, 1), (1, 2), (3, 4)] index = IntervalIndex.from_tuples(tuples, closed="right")
result = index.get_indexer(query) expected = np.array(expected, dtype="intp") tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("item", [[3], np.arange(0.5, 5, 0.5)]) def test_get_indexer_length_one(self, item, closed): # GH 17284 index = IntervalIndex.from_tuples([(0, 5)], closed=closed) result = index.get_indexer(item) expected = np.array([0] * len(item), dtype="intp") tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("size", [1, 5]) def test_get_indexer_length_one_interval(self, size, closed): # GH 17284 index = IntervalIndex.from_tuples([(0, 5)], closed=closed) result = index.get_indexer([Interval(0, 5, closed)] * size) expected = np.array([0] * size, dtype="intp") tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize( "target", [ IntervalIndex.from_tuples([(7, 8), (1, 2), (3, 4), (0, 1)]), IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4), np.nan]), IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)], closed="both"), [-1, 0, 0.5, 1, 2, 2.5, np.nan], ["foo", "foo", "bar", "baz"], ], ) def test_get_indexer_categorical(self, target, ordered): # GH 30063: categorical and non-categorical results should be consistent index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)]) categorical_target = CategoricalIndex(target, ordered=ordered)
result = index.get_indexer(categorical_target) expected = index.get_indexer(target) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.filterwarnings( "ignore:invalid value encountered in cast:RuntimeWarning" ) def test_get_indexer_categorical_with_nans(self): # GH#41934 nans in both index and in target ii = IntervalIndex.from_breaks(range(5)) ii2 = ii.append(IntervalIndex([np.nan])) ci2 = CategoricalIndex(ii2)
result = ii2.get_indexer(ci2) expected = np.arange(5, dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
# not-all-matches result = ii2[1:].get_indexer(ci2[::-1]) expected = np.array([3, 2, 1, 0, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
# non-unique target, non-unique nans result = ii2.get_indexer(ci2.append(ci2)) expected = np.array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
def test_get_indexer_datetime(self): ii = IntervalIndex.from_breaks(date_range("2018-01-01", periods=4, unit="ns")) # TODO: with mismatched resolution get_indexer currently raises; # this should probably coerce? target = DatetimeIndex(["2018-01-02"], dtype="M8[ns]") result = ii.get_indexer(target) expected = np.array([0], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
result = ii.get_indexer(target.astype(str)) tm.assert_numpy_array_equal(result, expected)
# https://github.com/pandas-dev/pandas/issues/47772 result = ii.get_indexer(target.asi8) expected = np.array([-1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize( "tuples, closed", [ ([(0, 2), (1, 3), (3, 4)], "neither"), ([(0, 5), (1, 4), (6, 7)], "left"), ([(0, 1), (0, 1), (1, 2)], "right"), ([(0, 1), (2, 3), (3, 4)], "both"), ], ) def test_get_indexer_errors(self, tuples, closed): # IntervalIndex needs non-overlapping for uniqueness when querying index = IntervalIndex.from_tuples(tuples, closed=closed)
msg = ( "cannot handle overlapping indices; use " "IntervalIndex.get_indexer_non_unique" ) with pytest.raises(InvalidIndexError, match=msg): index.get_indexer([0, 2])
@pytest.mark.parametrize( "query, expected", [ ([-0.5], ([-1], [0])), ([0], ([0], [])), ([0.5], ([0], [])), ([1], ([0, 1], [])), ([1.5], ([0, 1], [])), ([2], ([0, 1, 2], [])), ([2.5], ([1, 2], [])), ([3], ([2], [])), ([3.5], ([2], [])), ([4], ([-1], [0])), ([4.5], ([-1], [0])), ([1, 2], ([0, 1, 0, 1, 2], [])), ([1, 2, 3], ([0, 1, 0, 1, 2, 2], [])), ([1, 2, 3, 4], ([0, 1, 0, 1, 2, 2, -1], [3])), ([1, 2, 3, 4, 2], ([0, 1, 0, 1, 2, 2, -1, 0, 1, 2], [3])), ], ) def test_get_indexer_non_unique_with_int_and_float(self, query, expected): tuples = [(0, 2.5), (1, 3), (2, 4)] index = IntervalIndex.from_tuples(tuples, closed="left")
result_indexer, result_missing = index.get_indexer_non_unique(query) expected_indexer = np.array(expected[0], dtype="intp") expected_missing = np.array(expected[1], dtype="intp")
tm.assert_numpy_array_equal(result_indexer, expected_indexer) tm.assert_numpy_array_equal(result_missing, expected_missing)
# TODO we may also want to test get_indexer for the case when # the intervals are duplicated, decreasing, non-monotonic, etc..
def test_get_indexer_non_monotonic(self): # GH 16410 idx1 = IntervalIndex.from_tuples([(2, 3), (4, 5), (0, 1)]) idx2 = IntervalIndex.from_tuples([(0, 1), (2, 3), (6, 7), (8, 9)]) result = idx1.get_indexer(idx2) expected = np.array([2, 0, -1, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
result = idx1.get_indexer(idx1[1:]) expected = np.array([1, 2], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
def test_get_indexer_with_nans(self): # GH#41831 index = IntervalIndex([np.nan, np.nan]) other = IntervalIndex([np.nan])
assert not index._index_as_unique
result = index.get_indexer_for(other) expected = np.array([0, 1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
def test_get_index_non_unique_non_monotonic(self): # GH#44084 (root cause) index = IntervalIndex.from_tuples( [(0.0, 1.0), (1.0, 2.0), (0.0, 1.0), (1.0, 2.0)] )
result, _ = index.get_indexer_non_unique([Interval(1.0, 2.0)]) expected = np.array([1, 3], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
def test_get_indexer_multiindex_with_intervals(self): # GH#44084 (MultiIndex case as reported) interval_index = IntervalIndex.from_tuples( [(2.0, 3.0), (0.0, 1.0), (1.0, 2.0)], name="interval" ) foo_index = Index([1, 2, 3], name="foo")
multi_index = MultiIndex.from_product([foo_index, interval_index])
result = multi_index.get_level_values("interval").get_indexer_for( [Interval(0.0, 1.0)] ) expected = np.array([1, 4, 7], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("box", [IntervalIndex, array, list]) def test_get_indexer_interval_index(self, box): # GH#30178 rng = period_range("2022-07-01", freq="D", periods=3) idx = box(interval_range(Timestamp("2022-07-01"), freq="3D", periods=3))
actual = rng.get_indexer(idx) expected = np.array([-1, -1, -1], dtype=np.intp) tm.assert_numpy_array_equal(actual, expected)
def test_get_indexer_read_only(self): idx = interval_range(start=0, end=5) arr = np.array([1, 2]) arr.flags.writeable = False result = idx.get_indexer(arr) expected = np.array([0, 1]) tm.assert_numpy_array_equal(result, expected, check_dtype=False)
result = idx.get_indexer_non_unique(arr)[0] tm.assert_numpy_array_equal(result, expected, check_dtype=False)
def test_get_indexer_non_unique_right(self): # GH#52245 data = [ Interval(Timestamp("2020-05-26"), Timestamp("2020-05-27")), Interval(Timestamp("2020-05-27"), Timestamp("2020-05-27")), ]
index = IntervalIndex(data)
result = index.get_indexer([index[0]]) expected = np.array([0], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
# GH#52245 OP is about drop so we test that here, but the underlying # problem is in get_indexer. result = index.drop(index[0]) expected = index[1:] tm.assert_index_equal(result, expected)
class TestSliceLocs: def test_slice_locs_with_interval(self): # increasing monotonically index = IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)])
assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3) assert index.slice_locs(start=Interval(0, 2)) == (0, 3) assert index.slice_locs(end=Interval(2, 4)) == (0, 3) assert index.slice_locs(end=Interval(0, 2)) == (0, 1) assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 1)
# decreasing monotonically index = IntervalIndex.from_tuples([(2, 4), (1, 3), (0, 2)])
assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (2, 1) assert index.slice_locs(start=Interval(0, 2)) == (2, 3) assert index.slice_locs(end=Interval(2, 4)) == (0, 1) assert index.slice_locs(end=Interval(0, 2)) == (0, 3) assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (0, 3)
# sorted duplicates index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4)])
assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3) assert index.slice_locs(start=Interval(0, 2)) == (0, 3) assert index.slice_locs(end=Interval(2, 4)) == (0, 3) assert index.slice_locs(end=Interval(0, 2)) == (0, 2) assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2)
# unsorted duplicates index = 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=Interval(0, 2), end=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=Interval(0, 2))
assert index.slice_locs(end=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=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=Interval(2, 4), end=Interval(0, 2))
# another unsorted duplicates index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4), (1, 3)])
assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3) assert index.slice_locs(start=Interval(0, 2)) == (0, 4) assert index.slice_locs(end=Interval(2, 4)) == (0, 3) assert index.slice_locs(end=Interval(0, 2)) == (0, 2) assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2)
def test_slice_locs_with_ints_and_floats_succeeds(self): # increasing non-overlapping index = 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 = 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 = 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 = date_range("2016-01-01", periods=9, tz=tz) idx = IntervalIndex.from_breaks(dti) mask = np.zeros(idx.shape, dtype=bool) mask[0:3] = True
result = idx.putmask(mask, idx[-1]) expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:])) tm.assert_index_equal(result, expected)
def test_putmask_td64(self): # GH#37968 dti = date_range("2016-01-01", periods=9, unit="ns") tdi = dti - dti[0] idx = IntervalIndex.from_breaks(tdi) mask = np.zeros(idx.shape, dtype=bool) mask[0:3] = True
result = idx.putmask(mask, idx[-1]) expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:])) tm.assert_index_equal(result, expected)
class TestContains: # .__contains__, not .contains
def test_contains_dunder(self): index = 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 Interval(0, 1, closed="right") in index assert Interval(0, 2, closed="right") not in index assert Interval(0, 0.5, closed="right") not in index assert Interval(3, 5, closed="right") not in index assert Interval(-1, 0, closed="left") not in index assert Interval(0, 1, closed="left") not in index assert Interval(0, 1, closed="both") not in index123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922from itertools import permutationsimport re
import numpy as npimport pytest
import pandas as pdfrom pandas import ( Index, Interval, IntervalIndex, Timedelta, Timestamp, date_range, interval_range, isna, notna, timedelta_range,)import pandas._testing as tmimport pandas.core.common as com
class TestIntervalIndex: index = IntervalIndex.from_arrays([0, 1], [1, 2])
def create_index(self, closed="right"): return IntervalIndex.from_breaks(range(11), closed=closed)
def create_index_with_nan(self, closed="right"): mask = [True, False] + [True] * 8 return 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, Index(np.arange(10, dtype=np.int64))) tm.assert_index_equal(index.right, Index(np.arange(1, 11, dtype=np.int64))) tm.assert_index_equal(index.mid, Index(np.arange(0.5, 10.5, dtype=np.float64)))
assert index.closed == closed
ivs = [ Interval(left, right, closed) for left, right in zip(range(10), range(1, 11)) ] 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 = 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 = [ Interval(left, right, closed) if notna(left) else np.nan for left, right in zip(expected_left, expected_right) ] 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], date_range("2017-01-01", "2017-01-04", unit="ns"), 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 = IntervalIndex.from_breaks(breaks, closed=closed) result = index.length expected = 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 = Index(iv.length if 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 = 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 = 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 = IntervalIndex.from_breaks(breaks, closed=closed) result = self.create_index(closed=closed).delete(0) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "data", [ interval_range(0, periods=10, closed="neither"), interval_range(1.7, periods=8, freq=2.5, closed="both"), interval_range(Timestamp("20170101"), periods=12, closed="left"), interval_range(Timedelta("1 day"), periods=6, closed="right"), ], ) def test_insert(self, data): item = data[0] idx_item = 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 = 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 = 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 = IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)], closed=closed) assert idx.is_unique is True
# unique overlapping - shared endpoints idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed) assert idx.is_unique is True
# unique nested idx = IntervalIndex.from_tuples([(-1, 1), (-2, 2)], closed=closed) assert idx.is_unique is True
# unique NaN idx = IntervalIndex.from_tuples([(np.nan, np.nan)], closed=closed) assert idx.is_unique is True
# non-unique NaN idx = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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", [ date_range("20180101", periods=4), date_range("20180101", periods=4, tz="US/Eastern"), timedelta_range("0 days", periods=4), ], ids=lambda x: str(x.dtype), ) def test_maybe_convert_i8(self, breaks): # GH 20636 index = IntervalIndex.from_breaks(breaks)
# intervalindex result = index._maybe_convert_i8(index) expected = IntervalIndex.from_breaks(breaks.asi8) tm.assert_index_equal(result, expected)
# interval interval = Interval(breaks[0], breaks[1]) result = index._maybe_convert_i8(interval) expected = Interval(breaks[0]._value, breaks[1]._value) assert result == expected
# datetimelike index result = index._maybe_convert_i8(breaks) expected = 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 = Index(breaks.asi8) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "breaks", [ date_range("2018-01-01", periods=5), timedelta_range("0 days", periods=5, unit="us"), ], ) def test_maybe_convert_i8_nat(self, breaks): # GH 20636 index = IntervalIndex.from_breaks(breaks)
to_convert = breaks._constructor([pd.NaT] * 3).as_unit("us") expected = 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 = 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 = Index(key, dtype=expected_dtype) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "make_key", [ IntervalIndex.from_breaks, lambda breaks: 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 = 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", permutations( [ date_range("20180101", periods=4), date_range("20180101", periods=4, tz="US/Eastern"), timedelta_range("0 days", periods=4), ], 2, ), ids=lambda x: str(x.dtype), ) @pytest.mark.parametrize( "make_key", [ IntervalIndex.from_breaks, lambda breaks: 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 = 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 = 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(Interval(0, 1))
def test_dropna(self, closed): expected = IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)], closed=closed)
ii = IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan], closed=closed) result = ii.dropna() tm.assert_index_equal(result, expected)
ii = 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 = 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 = 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 = Interval(0, 1) < self.index expected = np.array([False, True]) tm.assert_numpy_array_equal(actual, expected)
actual = Interval(0.5, 1.5) < self.index expected = np.array([False, True]) tm.assert_numpy_array_equal(actual, expected) actual = self.index > 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 == 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 = Index( [np.nan, Interval(0, 1, closed=closed), Interval(1, 2, closed=closed)] ) idx2 = 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): IntervalIndex.from_arrays( [np.nan, 0, 1], np.array([0, 1, 2]), closed=closed )
tm.assert_numpy_array_equal(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 = IntervalIndex([Interval(1, 2), np.nan, Interval(0, 1)])
result = index.sort_values() expected = IntervalIndex([Interval(0, 1), Interval(1, 2), np.nan]) tm.assert_index_equal(result, expected)
result = index.sort_values(ascending=False, na_position="first") expected = IntervalIndex([np.nan, Interval(1, 2), Interval(0, 1)]) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("tz", [None, "US/Eastern"]) def test_datetime(self, tz): start = Timestamp("2000-01-01", tz=tz) dates = date_range(start=start, periods=10) index = IntervalIndex.from_breaks(dates)
# test mid start = Timestamp("2000-01-01T12:00", tz=tz) expected = date_range(start=start, periods=9) tm.assert_index_equal(index.mid, expected)
# __contains__ doesn't check individual points assert Timestamp("2000-01-01", tz=tz) not in index assert Timestamp("2000-01-01T12", tz=tz) not in index assert Timestamp("2000-01-02", tz=tz) not in index iv_true = Interval( Timestamp("2000-01-02", tz=tz), Timestamp("2000-01-03", tz=tz) ) iv_false = Interval( Timestamp("1999-12-31", tz=tz), 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(Timestamp("2000-01-01", tz=tz)).any() assert index.contains(Timestamp("2000-01-01T12", tz=tz)).any() assert index.contains(Timestamp("2000-01-02", tz=tz)).any()
# test get_indexer start = Timestamp("1999-12-31T12:00", tz=tz) target = 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 = Timestamp("2000-01-08T18:00", tz=tz) target = 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 = IntervalIndex.from_arrays([0, 1], [1, 2], closed=closed) index2 = IntervalIndex.from_arrays([1, 2], [2, 3], closed=closed)
result = index1.append(index2) expected = 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 = 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 = 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 = IntervalIndex.from_tuples(tpls, closed=closed) assert idx.is_non_overlapping_monotonic is True
idx = 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 = IntervalIndex.from_tuples(tpls, closed=closed) assert idx.is_non_overlapping_monotonic is False
idx = 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 = IntervalIndex.from_tuples(tpls, closed=closed) assert idx.is_non_overlapping_monotonic is False
idx = 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 = IntervalIndex.from_breaks(range(4), closed=closed) assert idx.is_non_overlapping_monotonic is False else: idx = 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), (Timestamp("2018-01-01"), Timedelta("1 day"), pd.NaT), (Timedelta("0 days"), 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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)), zip( date_range("20170101", periods=10), date_range("20170101", periods=10), ), zip( timedelta_range("0 days", periods=10), timedelta_range("1 day", periods=10), ), ], ) def test_to_tuples(self, tuples): # GH 18756 tuples = list(tuples) idx = IntervalIndex.from_tuples(tuples) result = idx.to_tuples() expected = Index(com.asarray_tuplesafe(tuples)) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "tuples", [ [*list(zip(range(10), range(1, 11))), np.nan], [ *list( zip( date_range("20170101", periods=10), date_range("20170101", periods=10), ) ), np.nan, ], [ *list( zip( timedelta_range("0 days", periods=10), timedelta_range("1 day", periods=10), ) ), np.nan, ], ], ) @pytest.mark.parametrize("na_tuple", [True, False]) def test_to_tuples_na(self, tuples, na_tuple): # GH 18756 idx = IntervalIndex.from_tuples(tuples) result = idx.to_tuples(na_tuple=na_tuple)
# check the non-NA portion expected_notna = 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(isna(x) for x in result_na) else: assert isna(result_na)
def test_nbytes(self): # GH 19209 left = np.arange(0, 4, dtype="i8") right = np.arange(1, 5, dtype="i8")
result = 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 = interval_range(0, 5, closed=closed, name=name) result = index.set_closed(other_closed) expected = 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 = 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 = Interval( Timestamp("2017-01-01 00:00:00"), Timestamp("2018-01-01 00:00:00") ) year_2017_index = 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"): IntervalIndex.from_arrays(left, right)
def test_dir(): # GH#27571 dir(interval_index) should not raise index = 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 = IntervalIndex([Interval(0, 1), 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"], [Timestamp("2020-01-01", tz="Europe/London")] * 2])def test_searchsorted_invalid_argument(arg): values = IntervalIndex([Interval(0, 1), Interval(1, 2)]) msg = "'<' not supported between instances of 'pandas._libs.interval.Interval' and " with pytest.raises(TypeError, match=msg): values.searchsorted(arg)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390from datetime import timedelta
import numpy as npimport pytest
from pandas.core.dtypes.common import is_integer
from pandas import ( DateOffset, Interval, IntervalIndex, Timedelta, Timestamp, date_range, interval_range, timedelta_range,)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) expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
# defined from start/end/freq result = interval_range( start=start, end=end, freq=freq, name=name, closed=closed ) tm.assert_index_equal(result, expected)
# defined from start/periods/freq result = interval_range( start=start, periods=periods, freq=freq, name=name, closed=closed ) tm.assert_index_equal(result, expected)
# defined from end/periods/freq result = 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 = 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 = Timestamp("20180101", tz=tz), Timestamp("20181231", tz=tz) breaks = date_range(start=start, end=end, freq=freq) expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
# defined from start/end/freq result = interval_range( start=start, end=end, freq=freq, name=name, closed=closed ) tm.assert_index_equal(result, expected)
# defined from start/periods/freq result = interval_range( start=start, periods=periods, freq=freq, name=name, closed=closed ) tm.assert_index_equal(result, expected)
# defined from end/periods/freq result = 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 = 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 = Timedelta("0 days"), Timedelta("100 days") breaks = timedelta_range(start=start, end=end, freq=freq) expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
# defined from start/end/freq result = interval_range( start=start, end=end, freq=freq, name=name, closed=closed ) tm.assert_index_equal(result, expected)
# defined from start/periods/freq result = interval_range( start=start, periods=periods, freq=freq, name=name, closed=closed ) tm.assert_index_equal(result, expected)
# defined from end/periods/freq result = 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 = 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), (Timedelta("0D"), Timedelta("10D"), "2D4h", Timedelta("8D16h")), ( Timestamp("2018-01-01"), Timestamp("2018-02-09"), "MS", Timestamp("2018-02-01"), ), ( Timestamp("2018-01-01", tz="US/Eastern"), Timestamp("2018-01-20", tz="US/Eastern"), "5D12h", 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 = 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 = IntervalIndex.from_breaks(breaks)
result = interval_range(start=start, end=end, periods=4, freq=freq) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "start, mid, end", [ ( Timestamp("2018-03-10", tz="US/Eastern"), Timestamp("2018-03-10 23:30:00", tz="US/Eastern"), Timestamp("2018-03-12", tz="US/Eastern"), ), ( Timestamp("2018-11-03", tz="US/Eastern"), Timestamp("2018-11-04 00:30:00", tz="US/Eastern"), 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 = interval_range(start=start, end=end, periods=2) expected = 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 = 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 = 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 = 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 = 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 = 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 = Timestamp("2024-03-25") with pytest.raises(TypeError, match=msg): interval_range(ts, periods=10.5)
def test_constructor_coverage(self): # equivalent timestamp-like start/end start, end = Timestamp("2017-01-01"), Timestamp("2017-01-15") expected = interval_range(start=start, end=end)
result = interval_range(start=start.to_pydatetime(), end=end.to_pydatetime()) tm.assert_index_equal(result, expected)
result = interval_range(start=start.asm8, end=end.asm8) tm.assert_index_equal(result, expected)
# equivalent freq with timestamp equiv_freq = [ "D", Day(), Timedelta(days=1), timedelta(days=1), DateOffset(days=1), ] for freq in equiv_freq: result = interval_range(start=start, end=end, freq=freq) tm.assert_index_equal(result, expected)
# equivalent timedelta-like start/end start, end = Timedelta(days=1).as_unit("us"), Timedelta(days=10).as_unit("us") expected = interval_range(start=start, end=end)
result = interval_range(start=start.to_pytimedelta(), end=end.to_pytimedelta()) tm.assert_index_equal(result, expected)
result = interval_range(start=start.asm8, end=end.asm8) tm.assert_index_equal(result, expected)
# equivalent freq with timedelta equiv_freq = ["D", Day(), Timedelta(days=1), timedelta(days=1)] for freq in equiv_freq: result = 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): interval_range(start=0)
with pytest.raises(ValueError, match=msg): interval_range(end=5)
with pytest.raises(ValueError, match=msg): interval_range(periods=2)
with pytest.raises(ValueError, match=msg): interval_range()
# too many params with pytest.raises(ValueError, match=msg): 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): interval_range(start=0, end=Timestamp("20130101"), freq=2)
with pytest.raises(TypeError, match=msg): interval_range(start=0, end=Timedelta("1 day"), freq=2)
with pytest.raises(TypeError, match=msg): interval_range(start=0, end=10, freq="D")
with pytest.raises(TypeError, match=msg): interval_range(start=Timestamp("20130101"), end=10, freq="D")
with pytest.raises(TypeError, match=msg): interval_range( start=Timestamp("20130101"), end=Timedelta("1 day"), freq="D" )
with pytest.raises(TypeError, match=msg): interval_range( start=Timestamp("20130101"), end=Timestamp("20130110"), freq=2 )
with pytest.raises(TypeError, match=msg): interval_range(start=Timedelta("1 day"), end=10, freq="D")
with pytest.raises(TypeError, match=msg): interval_range( start=Timedelta("1 day"), end=Timestamp("20130110"), freq="D" )
with pytest.raises(TypeError, match=msg): interval_range(start=Timedelta("1 day"), end=Timedelta("10 days"), freq=2)
# invalid periods msg = "periods must be an integer, got foo" with pytest.raises(TypeError, match=msg): interval_range(start=0, periods="foo")
# invalid start msg = "start must be numeric or datetime-like, got foo" with pytest.raises(ValueError, match=msg): 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): interval_range(end=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): interval_range(start=0, end=10, freq="foo")
with pytest.raises(ValueError, match=msg): interval_range(start=Timestamp("20130101"), periods=10, freq="foo")
with pytest.raises(ValueError, match=msg): interval_range(end=Timedelta("1 day"), periods=10, freq="foo")
# mixed tz start = Timestamp("2017-01-01", tz="US/Eastern") end = 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): interval_range(start=start, end=end)
def test_float_freq(self): # GH 54477 result = interval_range(0, 1, freq=0.1) expected = IntervalIndex.from_breaks([0 + 0.1 * n for n in range(11)]) tm.assert_index_equal(result, expected)
result = interval_range(0, 1, freq=0.6) expected = IntervalIndex.from_breaks([0, 0.6]) tm.assert_index_equal(result, expected)
def test_interval_range_float32_start_int_freq(self): # GH 58964 result = interval_range(start=np.float32(0), end=2, freq=1) expected = IntervalIndex.from_tuples( [(0.0, 1.0), (1.0, 2.0)], dtype="interval[float64, right]" ) tm.assert_index_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208from itertools import permutations
import numpy as npimport pytest
from pandas._libs.interval import IntervalTreefrom pandas.compat import ( IS64, WASM,)
import pandas._testing as tm
def skipif_32bit(param): """ Skip parameters in a parametrize on 32bit systems. Specifically used here to skip leaf_size parameters related to GH 23440. """ marks = pytest.mark.skipif(not IS64, reason="GH 23440: int type mismatch on 32bit") return pytest.param(param, marks=marks)
@pytest.fixture(params=[skipif_32bit(1), skipif_32bit(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", [skipif_32bit(1), skipif_32bit(10), skipif_32bit(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
@pytest.mark.skipif(not IS64, reason="GH 23440") 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.xfail(WASM, reason="GH 23440") @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 == expected1234567891011121314151617181920212223242526272829303132333435363738394041424344import pytest
from pandas import ( IntervalIndex, MultiIndex, RangeIndex,)import pandas._testing as tm
@pytest.fixturedef range_index(): return RangeIndex(3, name="range_index")
@pytest.fixturedef interval_index(): return 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 = 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 = 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)12345678910from pandas import IntervalIndeximport 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 = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed) result = tm.round_trip_pickle(idx, temp_file) tm.assert_index_equal(result, idx)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208import numpy as npimport pytest
from pandas import ( Index, IntervalIndex, Timestamp, interval_range,)import pandas._testing as tm
def monotonic_index(start, end, dtype="int64", closed="right"): return IntervalIndex.from_breaks(np.arange(start, end, dtype=dtype), closed=closed)
def empty_index(dtype="int64", closed="right"): return 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 = IntervalIndex.from_tuples([(1, 2), (1, 3), (1, 4), (0, 2)]) other = IntervalIndex.from_tuples([(1, 2), (1, 3)]) expected = IntervalIndex.from_tuples([(1, 2), (1, 3)]) result = index.intersection(other) tm.assert_index_equal(result, expected)
# GH 26225 index = IntervalIndex.from_tuples([(0, 3), (0, 2)]) other = IntervalIndex.from_tuples([(0, 2), (1, 3)]) expected = IntervalIndex.from_tuples([(0, 2)]) result = index.intersection(other) tm.assert_index_equal(result, expected)
# GH 26225: duplicate nan element index = IntervalIndex([np.nan, np.nan]) other = IntervalIndex([np.nan]) expected = 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 = IntervalIndex.from_tuples([(1, 2), (1, 2), (2, 3), (3, 4)]) other = IntervalIndex.from_tuples([(1, 2), (2, 3)]) expected = IntervalIndex.from_tuples([(1, 2), (2, 3)]) result = index.intersection(other) tm.assert_index_equal(result, expected)
def test_difference(self, closed, sort): index = 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 = 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 = 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 = 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)(Index([1, 2, 3])) result = set_op(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 = interval_range(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)123456789101112131415161718192021222324252627import numpy as npimport pytest
from pandas import ( Index, MultiIndex,)
# Note: identical the "multi" entry in the top-level "index" fixture@pytest.fixturedef idx(): # a MultiIndex used to test the general functionality of the # general functionality of this object major_axis = Index(["foo", "bar", "baz", "qux"]) minor_axis = 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 = MultiIndex( levels=[major_axis, minor_axis], codes=[major_codes, minor_codes], names=index_names, verify_integrity=False, ) return mi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263import numpy as npimport pytest
import pandas as pdfrom pandas import ( Index, MultiIndex, date_range, period_range,)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 = Index(list(range(4))) minor_axis = 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 = 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 = MultiIndex.from_product([numbers, names], names=names) expected = 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 = date_range("2011-01-01", freq="ME", periods=3) dti_tz = date_range("2011-01-01", freq="ME", periods=3, tz="US/Eastern") pi = period_range("2011-01", freq="M", periods=3)
mi = 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 = 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)
other = 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 = 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(Index(["x", "y", "z"])), dti_tz.append(Index(["x", "y", "z"])), pi.append(Index(["x", "y", "z"])), ] ) tm.assert_index_equal(res, exp)
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 = 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)123456789101112131415161718192021222324252627282930import numpy as npimport 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")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122import numpy as npimport pytest
import pandas as pdfrom pandas import MultiIndeximport 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 = MultiIndex(levels=levels, codes=codes) mi2 = 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 = 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872from datetime import ( date, datetime,)import itertools
import numpy as npimport pytest
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
import pandas as pdfrom pandas import ( Index, MultiIndex, Series, Timestamp, date_range,)import pandas._testing as tm
def test_constructor_single_level(): result = MultiIndex( levels=[["foo", "bar", "baz", "qux"]], codes=[[0, 1, 2, 3]], names=["first"] ) assert isinstance(result, MultiIndex) expected = 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): MultiIndex(levels=[], codes=[])
msg = "Must pass both levels and codes" with pytest.raises(TypeError, match=msg): MultiIndex(levels=[]) with pytest.raises(TypeError, match=msg): 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): MultiIndex(levels=levels, codes=codes, names=names)
# With .rename() mi = 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): 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): MultiIndex(levels=[["a"], ["b"]], codes=[[0, 1, 2, 3], [0, 3, 4, 1]])
with pytest.raises(ValueError, match=label_error): 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): 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 = MultiIndex( levels=[[np.nan, None, pd.NaT, 128, 2]], codes=[[0, -1, 1, 2, 3, 4]] ) expected = MultiIndex( levels=[[np.nan, None, pd.NaT, 128, 2]], codes=[[-1, -1, -1, -1, 3, 4]] ) tm.assert_index_equal(result, expected)
result = MultiIndex( levels=[[np.nan, "s", pd.NaT, 128, None]], codes=[[0, -1, 1, 2, 3, 4]] ) expected = 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 = 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 = 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 = 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 = MultiIndex.from_arrays(arrays, names=idx.names) tm.assert_index_equal(result, idx)
# infer correctly result = MultiIndex.from_arrays([[pd.NaT, Timestamp("20130101")], ["a", "b"]]) assert result.levels[0].equals(Index([Timestamp("20130101")])) assert result.levels[1].equals(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 = 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): 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 = 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), ), ( date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern"), 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 = 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 = MultiIndex.from_arrays([Series(idx1), Series(idx2)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2)
tm.assert_index_equal(result, result2)
def test_from_arrays_index_datetimelike_mixed(): idx1 = date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern") idx2 = 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 = MultiIndex.from_arrays([idx1, idx2, idx3, idx4]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) tm.assert_index_equal(result.get_level_values(2), idx3) tm.assert_index_equal(result.get_level_values(3), idx4)
result2 = MultiIndex.from_arrays( [Series(idx1), Series(idx2), Series(idx3), Series(idx4)] ) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2) tm.assert_index_equal(result2.get_level_values(2), idx3) tm.assert_index_equal(result2.get_level_values(3), idx4)
tm.assert_index_equal(result, result2)
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 = 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 = MultiIndex.from_arrays([Series(idx1), Series(idx2)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2)
result3 = 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): MultiIndex.from_arrays(arrays=[])
# 1 level result = MultiIndex.from_arrays(arrays=[[]], names=["A"]) assert isinstance(result, MultiIndex) expected = 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 = MultiIndex.from_arrays(arrays=arrays, names=names) expected = 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): 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): MultiIndex.from_arrays([idx1, idx2])
def test_from_arrays_respects_none_names(): # GH27292 a = Series([1, 2, 3], name="foo") b = Series(["a", "b", "c"], name="bar")
result = MultiIndex.from_arrays([a, b], names=None) expected = 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): MultiIndex.from_tuples([])
expected = MultiIndex( levels=[[1, 3], [2, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"] )
# input tuples result = 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 = MultiIndex( levels=[[1, 3], [2, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"] )
result = 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 a list / sequence of tuple-likes." with pytest.raises(TypeError, match=msg): MultiIndex.from_tuples(0)
def test_from_tuples_empty(): # GH 16777 result = MultiIndex.from_tuples([], names=["a", "b"]) expected = MultiIndex.from_arrays(arrays=[[], []], names=["a", "b"]) tm.assert_index_equal(result, expected)
def test_from_tuples_index_values(idx): result = 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): Index(li, name="abc") with pytest.raises(ValueError, match=msg): 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 = 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 = 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): MultiIndex.from_product([])
def test_from_product_empty_one_level(): result = MultiIndex.from_product([[]], names=["A"]) expected = 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 = MultiIndex.from_product([first, second], names=names) expected = 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 = MultiIndex.from_product([[], lvl2, []], names=names) expected = 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 = r"Input must be a list / sequence of iterables|Input must be list-like" with pytest.raises(TypeError, match=msg): MultiIndex.from_product(iterables=invalid_input)
def test_from_product_datetimeindex(): dt_index = date_range("2000-01-01", periods=2) mi = MultiIndex.from_product([[1, 2], dt_index]) etalon = construct_1d_object_array_from_listlike( [ (1, Timestamp("2000-01-01")), (1, Timestamp("2000-01-02")), (2, Timestamp("2000-01-01")), (2, Timestamp("2000-01-02")), ] ) tm.assert_numpy_array_equal(mi.values, etalon)
def test_from_product_rangeindex(): # RangeIndex is preserved by factorize, so preserved in levels rng = Index(range(5)) other = ["a", "b"] mi = 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: 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 = 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 = 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 = 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 = MultiIndex.from_tuples(tuples, names=names)
# iterator as input result = 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): MultiIndex.from_product(0)
@pytest.mark.parametrize( "a, b, expected_names", [ ( Series([1, 2, 3], name="foo"), Series(["a", "b"], name="bar"), ["foo", "bar"], ), (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 = MultiIndex.from_product([a, b]) expected = 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 = Series([1, 2, 3], name="foo") b = Series(["a", "b"], name="bar")
result = MultiIndex.from_product([a, b], names=None) expected = 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 = MultiIndex.from_product([a, b])
a.setflags(write=False) result = 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 = Index(index) expected = Index( Index( [ ("foo", "one"), ("foo", "two"), ("bar", "one"), ("baz", "two"), ("qux", "one"), ("qux", "two"), ], dtype="object", ) ) tm.assert_index_equal(result, expected)
result = Index(index, name="A") expected = Index( 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 = MultiIndex.from_tuples( [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")], names=["L1", "L2"] ) result = 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": Series([1, 2, None], dtype="Int64"), "b": pd.Float64Dtype().__from_arrow__(pa.array([0.2, None, None])), } ) multi_indexed = MultiIndex.from_frame(df) expected = MultiIndex.from_arrays( [ 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", [ Series([1, 2, 3, 4]), [1, 2, 3, 4], [[1, 2], [3, 4], [5, 6]], 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"): MultiIndex.from_frame(non_frame)
def test_from_frame_dtype_fidelity(): # GH 22420 df = pd.DataFrame( { "dates": 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 = MultiIndex.from_arrays( [ 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 = 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) 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=MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]), ) mi = 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=MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]), ) with pytest.raises(ValueError, match=expected_error_msg): MultiIndex.from_frame(df, names=names)
def test_index_equal_empty_iterable(): # #16844 a = MultiIndex(levels=[[], []], codes=[[], []], names=["a", "b"]) b = 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 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.*"): 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.*"): 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 = date_range("2010/01/01", periods=6, freq="ME", tz="US/Eastern") idx = 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("today") date2 = datetime.today() date3 = Timestamp.today()
for d1, d2 in itertools.product([date1, date2, date3], [date1, date2, date3]): index = 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.today() index = 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 = 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 = MultiIndex.from_arrays([Series(index), 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.today()
arr = [v, v]
idx = Index(arr) assert idx.dtype == object
mi = MultiIndex.from_arrays([arr]) lev = mi.levels[0] assert lev.dtype == object
mi = MultiIndex.from_product([arr]) lev = mi.levels[0] assert lev.dtype == object
mi = 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 = 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 = Series( ["int64", exp], index=MultiIndex.from_tuples([("a", "b"), ("c", "d")]), dtype=object, ) tm.assert_series_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208import numpy as npimport pytest
from pandas.compat.numpy import np_version_gt2
import pandas as pdfrom pandas import ( DataFrame, MultiIndex, RangeIndex,)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)
if not np_version_gt2: # copy=False semantics are only supported in NumPy>=2. return
# 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 = MultiIndex.from_tuples(tuples) result = index.to_frame(index=False) expected = 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 = MultiIndex.from_tuples(tuples, names=["first", "second"]) result = index.to_frame(index=False) expected = 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 = MultiIndex.from_tuples(tuples) result = index.to_frame(index=False, name=["first", "second"]) expected = 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 = MultiIndex.from_product([range(5), pd.date_range("20130101", periods=3)]) result = index.to_frame(index=False) expected = 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 = 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 = 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 = 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 = 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 = 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 = DataFrame(data, index=index, columns=names) tm.assert_frame_equal(result, expected)
names = [None, 0] index = 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 = DataFrame(data, index=index, columns=[0, 0]) tm.assert_frame_equal(result, expected)
def test_to_frame_column_rangeindex(): mi = MultiIndex.from_arrays([[1, 2], ["a", "b"]]) result = mi.to_frame().columns expected = 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596from copy import ( copy, deepcopy,)
import pytest
from pandas import MultiIndeximport 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 = 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 = 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 = 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 = 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._id123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188import numpy as npimport pytest
import pandas as pdfrom pandas import ( Index, MultiIndex,)import pandas._testing as tm
def test_drop(idx): dropped = idx.drop([("foo", "two"), ("qux", "one")])
index = 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 = 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 = 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 = MultiIndex( levels=[Index(range(4)), Index(range(4)), 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 = MultiIndex( levels=[Index(range(4)), Index(range(4)), 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 = 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) with tm.assert_produces_warning(performance_warning): 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 = 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 = MultiIndex.from_tuples([(1, 2), (2, 3), (1, 2)]) result = mi.drop((1, 2)) expected = MultiIndex.from_tuples([(2, 3)]) tm.assert_index_equal(result, expected)
def test_single_level_drop_partially_missing_elements(): # GH 37820
mi = 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 = 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 = MultiIndex.from_tuples([(2,)], names=("b",)) result = index.droplevel([]) expected = Index([2], name="b") tm.assert_index_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357from itertools import product
import numpy as npimport pytest
from pandas._libs import ( hashtable, index as libindex,)
from pandas import ( NA, DatetimeIndex, Index, MultiIndex, Series,)import pandas._testing as tm
@pytest.fixturedef idx_dup(): # compare tests/indexes/multi/conftest.py major_axis = Index(["foo", "bar", "baz", "qux"]) minor_axis = 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 = 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 = MultiIndex.from_arrays([[1, 2, 1, 2], [1, 1, 1, 2]], names=names)
res = mi.unique() exp = MultiIndex.from_arrays([[1, 2, 2], [1, 1, 2]], names=mi.names) tm.assert_index_equal(res, exp)
mi = MultiIndex.from_arrays([list("aaaa"), list("abab")], names=names) res = mi.unique() exp = MultiIndex.from_arrays([list("aa"), list("ab")], names=mi.names) tm.assert_index_equal(res, exp)
mi = MultiIndex.from_arrays([list("aaaa"), list("aaaa")], names=names) res = mi.unique() exp = MultiIndex.from_arrays([["a"], ["a"]], names=mi.names) tm.assert_index_equal(res, exp)
# GH #20568 - empty MI mi = MultiIndex.from_arrays([[], []], names=names) res = mi.unique() tm.assert_index_equal(mi, res)
def test_unique_datetimelike(): idx1 = DatetimeIndex( ["2015-01-01", "2015-01-01", "2015-01-01", "2015-01-01", "NaT", "NaT"] ) idx2 = DatetimeIndex( ["2015-01-01", "2015-01-01", "2015-01-02", "2015-01-02", "NaT", "2015-01-01"], tz="Asia/Tokyo", ) result = MultiIndex.from_arrays([idx1, idx2]).unique()
eidx1 = DatetimeIndex(["2015-01-01", "2015-01-01", "NaT", "NaT"]) eidx2 = DatetimeIndex( ["2015-01-01", "2015-01-02", "NaT", "2015-01-01"], tz="Asia/Tokyo" ) exp = 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 = 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 = 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: \[[A', ]+\] on level 0" with pytest.raises(ValueError, match=msg): mi = MultiIndex([["A"] * 10, range(10)], [[0] * 10, range(10)])
# And that using set_levels with duplicate levels fails mi = MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]]) msg = r"Level values must be unique: \[[AB', ]+\] on level 0" with pytest.raises(ValueError, match=msg): mi.set_levels([["A", "B", "A", "A", "B"], [2, 1, 3, -2, 5]])
@pytest.mark.parametrize("names", [["a", "b", "a"], [1, 1, 2], [1, "a", 1]])def test_duplicate_level_names(names): # GH18872, GH19029 mi = MultiIndex.from_product([[0, 1]] * 3, names=names) assert mi.names == names
# With .rename() mi = 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 = 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 = 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 = 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 = 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 = 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 = 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 = MultiIndex(levels=levels, codes=codes) else: values = mi.values.tolist() mi = 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)
@pytest.mark.arm_slowdef test_duplicated_hashtable_impl(keep, monkeypatch): # GH 9125 n, k = 6, 10 levels = [np.arange(n), [str(i) for i in range(n)], 1000 + np.arange(n)] codes = [np.random.default_rng(2).choice(n, k * n) for _ in levels] with monkeypatch.context() as m: m.setattr(libindex, "_SIZE_CUTOFF", 50) mi = 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 = 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 = 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 = 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 = 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 = 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 = 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 = Series( [False, False, False, True, False, False, False, True, False, True], dtype=bool, ) result = 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 = Series([1, 2, NA, NA], dtype="Int64") vals_b = np.array([1, 2, 3, 3]) midx = MultiIndex.from_arrays([vals_a, vals_b], names=["a", "b"]) result = midx.unique()
exp_vals_a = Series([1, 2, NA], dtype="Int64") exp_vals_b = np.array([1, 2, 3]) expected = MultiIndex.from_arrays([exp_vals_a, exp_vals_b], names=["a", "b"]) tm.assert_index_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284import numpy as npimport pytest
from pandas.core.dtypes.common import is_any_real_numeric_dtype
import pandas as pdfrom pandas import ( Index, MultiIndex, Series,)import pandas._testing as tm
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 = 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(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 = Series(array_a) series_b = Series(array_b) series_c = Series(array_c) series_d = Series(array_d) with pytest.raises(ValueError, match="Lengths must match"): index_a == series_b
tm.assert_series_equal(index_a == series_a, Series(expected1)) tm.assert_series_equal(index_a == series_c, 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, MultiIndex): expected3 = np.array([False] * (len(index_a) - 2) + [True, False]) # assuming the 2nd to last item is unique in the data item = index_a[-2] tm.assert_numpy_array_equal(index_a == item, expected3) tm.assert_series_equal(series_a == item, Series(expected3))
def test_compare_tuple(): # GH#21517 mi = 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 = 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(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 = MultiIndex( levels=[Index(list(range(4))), Index(list(range(4))), 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 = 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 = Index(list(range(4))) minor_axis = 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 = 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 = Index(["foo", "bar", "baz", "qux"]) minor_axis = Index(["one", "two"])
major_codes = np.array([0, 0, 2, 2, 3, 3]) minor_codes = np.array([0, 1, 0, 1, 0, 1])
index = 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 = 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 = 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 = MultiIndex.from_tuples([(81.0, np.nan), (np.nan, np.nan)]) mi2 = MultiIndex.from_tuples([(np.nan, np.nan), (81.0, np.nan)]) assert not mi1.equals(mi2)
mi2 = MultiIndex.from_tuples([(81.0, np.nan), (np.nan, np.nan)]) assert mi1.equals(mi2)
def test_is_(): mi = 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 = MultiIndex.from_product([[0, 1]])
# Equality self-test: MultiIndex object vs self expected = Series([True, True]) result = Series(midx == midx) tm.assert_series_equal(result, expected)
# Greater than comparison: MultiIndex object vs self expected = Series([False, False]) result = Series(midx > midx) tm.assert_series_equal(result, expected)
def test_equals_ea_int_regular_int(): # GH#46026 mi1 = MultiIndex.from_arrays([Index([1, 2], dtype="Int64"), [3, 4]]) mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]]) assert not mi1.equals(mi2) assert not mi2.equals(mi1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import numpy as npimport pytest
import pandas as pdfrom pandas import ( Index, MultiIndex,)
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 = 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))
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 = [Index(["a/\u03c3", "b/\u03c3", "c/\u03c3"]), Index([0, 1])] codes = [np.arange(3).repeat(2), np.tile(np.arange(2), 3)] index = 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 = 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 = 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 = MultiIndex.from_tuples([("c" * 62,)])
expected = ( "MultiIndex([('cccccccccccccccccccccccccccccccccccccccc" "cccccccccccccccccccccc',)],\n )" ) assert str(data) == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133import numpy as np
import pandas as pdfrom pandas import ( CategoricalIndex, Index, MultiIndex, Timestamp, date_range,)import pandas._testing as tm
class TestGetLevelValues: def test_get_level_values_box_datetime64(self): dates = 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 = MultiIndex(levels=levels, codes=codes)
assert isinstance(index.get_level_values(0)[0], Timestamp)
def test_get_level_values(idx): result = idx.get_level_values(0) expected = 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 = MultiIndex( levels=[CategoricalIndex(["A", "B"]), CategoricalIndex([1, 2, 3])], codes=[np.array([0, 0, 0, 1, 1, 1]), np.array([0, 1, 2, 0, 1, 2])], )
exp = CategoricalIndex(["A", "A", "A", "B", "B", "B"]) tm.assert_index_equal(index.get_level_values(0), exp) exp = 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 = MultiIndex.from_arrays(arrays) result = index.get_level_values(0) expected = Index([np.nan, np.nan, np.nan], dtype=np.float64) tm.assert_index_equal(result, expected)
result = index.get_level_values(1) expected = 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 = MultiIndex.from_arrays(arrays) result = index.get_level_values(1) expected = Index([1, np.nan, 2]) tm.assert_index_equal(result, expected)
arrays = [["a", "b", "b"], [np.nan, np.nan, 2]] index = MultiIndex.from_arrays(arrays) result = index.get_level_values(1) expected = 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 = MultiIndex.from_arrays(arrays) result = index.get_level_values(0) expected = Index([np.nan, np.nan, np.nan]) tm.assert_index_equal(result, expected)
result = index.get_level_values(1) expected = Index(["a", np.nan, 1]) tm.assert_index_equal(result, expected)
arrays = [["a", "b", "b"], pd.DatetimeIndex([0, 1, pd.NaT])] index = 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 = MultiIndex.from_arrays(arrays) result = index.get_level_values(0) expected = 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. from pandas import ( Period, PeriodIndex, )
idx = MultiIndex.from_arrays( [PeriodIndex([Period("2019Q1"), Period("2019Q2")], name="b")] ) idx2 = 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(date_range("20200101", periods=3, freq="BME")) expected = idx.copy(deep=True) idx2 = Index([1, 2, 3]) midx = 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 = date_range(start=pd.to_datetime("1/1/2018"), periods=4, freq="YS") other_index = ["A"] multi_index = MultiIndex.from_product([datetime_index, other_index])
assert multi_index.get_level_values(0).freq == datetime_index.freq123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380import numpy as npimport pytest
from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pdfrom pandas import ( CategoricalIndex, MultiIndex,)import pandas._testing as tm
def assert_matching(actual, expected, check_dtype=False): # avoid specifying internal representation # as much as possible assert len(actual) == len(expected) for act, exp in zip(actual, expected, strict=True): act = np.asarray(act) exp = np.asarray(exp) tm.assert_numpy_array_equal(act, exp, check_dtype=check_dtype)
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 = 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 = 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 = 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. levels = idx.levels new_levels = [[lev + "a" for lev in level] for level in levels]
# level changing [w/o mutation] ind2 = idx.set_levels(new_levels) assert_matching(ind2.levels, new_levels) assert_matching(idx.levels, levels)
# level changing specific level [w/o mutation] ind2 = idx.set_levels(new_levels[0], level=0) assert_matching(ind2.levels, [new_levels[0], levels[1]]) assert_matching(idx.levels, levels)
ind2 = idx.set_levels(new_levels[1], level=1) assert_matching(ind2.levels, [levels[0], new_levels[1]]) assert_matching(idx.levels, levels)
# level changing multiple levels [w/o mutation] ind2 = idx.set_levels(new_levels, level=[0, 1]) assert_matching(ind2.levels, new_levels) assert_matching(idx.levels, levels)
# illegal level changing should not change levels # GH 13754 original_index = idx.copy() with pytest.raises(ValueError, match="^On"): idx.set_levels(["c"], level=0) assert_matching(idx.levels, original_index.levels, check_dtype=True)
with pytest.raises(ValueError, match="^On"): idx.set_codes([0, 1, 2, 3, 4, 5], level=0) assert_matching(idx.codes, original_index.codes, check_dtype=True)
with pytest.raises(TypeError, match="^Levels"): idx.set_levels("c", level=0) assert_matching(idx.levels, original_index.levels, check_dtype=True)
with pytest.raises(TypeError, match="^Codes"): idx.set_codes(1, level=0) assert_matching(idx.codes, original_index.codes, check_dtype=True)
def test_set_codes(idx): # side note - you probably wouldn't want to use levels and codes # directly like this - but it is possible. 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]
# changing codes w/o mutation ind2 = idx.set_codes(new_codes) assert_matching(ind2.codes, new_codes) assert_matching(idx.codes, codes)
# codes changing specific level w/o mutation ind2 = idx.set_codes(new_codes[0], level=0) assert_matching(ind2.codes, [new_codes[0], codes[1]]) assert_matching(idx.codes, codes)
ind2 = idx.set_codes(new_codes[1], level=1) assert_matching(ind2.codes, [codes[0], new_codes[1]]) assert_matching(idx.codes, codes)
# codes changing multiple levels w/o mutation ind2 = idx.set_codes(new_codes, level=[0, 1]) assert_matching(ind2.codes, new_codes) assert_matching(idx.codes, codes)
# label changing for levels of different magnitude of categories ind = MultiIndex.from_tuples([(0, i) for i in range(130)]) new_codes = range(129, -1, -1) expected = MultiIndex.from_tuples([(0, i) for i in new_codes])
# [w/o mutation] result = ind.set_codes(codes=new_codes, level=1) assert result.equals(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)
# 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 = MultiIndex(levels=[[0, 1]], codes=[[0, 1]], names=["first"]) m = 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 = MultiIndex.from_arrays([list("xyzx"), [0, 1, 2, 3]])
cidx = CategoricalIndex(list("bac"), ordered=ordered) result = index.set_levels(cidx, level=0) expected = 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 = 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 = 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") 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 = 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 = MultiIndex.from_arrays([expected_sizes, colors], names=["size", "color"]) tm.assert_index_equal(result, expected)
def test_set_empty_level(): # GH#48636 midx = MultiIndex.from_arrays([[]], names=["A"]) result = midx.set_levels(pd.DatetimeIndex([]), level=0) expected = MultiIndex.from_arrays([pd.DatetimeIndex([])], names=["A"]) tm.assert_index_equal(result, expected)
def test_set_levels_pos_args_removal(): # https://github.com/pandas-dev/pandas/issues/41485 idx = 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 = MultiIndex.from_arrays([[5, 6]]) result = midx.set_levels(levels=pd.Categorical([1, 2]), level=0) expected = MultiIndex.from_arrays([pd.Categorical([1, 2])]) tm.assert_index_equal(result, expected)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031from collections import namedtuplefrom datetime import timedeltaimport re
import numpy as npimport pytest
from pandas._libs import index as libindexfrom pandas.errors import InvalidIndexError
import pandas as pdfrom pandas import ( Categorical, DataFrame, Index, MultiIndex, date_range,)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 = DataFrame( np.random.default_rng(2).standard_normal((50, 4)), columns=Index(list("ABCD"), dtype=object), index=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 = DataFrame( np.random.default_rng(2).standard_normal((10, 4)), columns=Index(list("ABCD"), dtype=object), index=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 = DataFrame( np.ones((5, 5)), index=Index([f"i-{i}" for i in range(5)], name="a"), columns=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 = MultiIndex( levels=[Index(np.arange(4)), Index(np.arange(4)), 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 = "[Kk]ey length.*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 = 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 = 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 = MultiIndex.from_tuples([(np.nan, 6), (np.nan, 6), ("a", 4)]) right = MultiIndex.from_tuples([("a", 1), ("a", 1), ("d", 1)]) mask = np.array([True, True, False])
result = left.putmask(mask, right)
expected = 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 = MultiIndex.from_arrays( [pd.Series([1, 2, 3], dtype=any_numeric_ea_dtype), [10, 11, 12]] ) midx2 = MultiIndex.from_arrays( [pd.Series([5, 6, 7], dtype=any_numeric_ea_dtype), [-1, -2, -3]] ) result = midx.putmask([True, False, False], midx2) expected = 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 = MultiIndex.from_arrays( [pd.Series([1, 2, 3], dtype=any_numeric_ea_dtype), [10, 11, 12]] ) midx2 = MultiIndex.from_arrays( [pd.Series([5], dtype=any_numeric_ea_dtype), [-1]] ) result = midx.putmask([True, False, False], midx2) expected = 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 = Index(np.arange(4)) minor_axis = 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 = 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 = Index(list(range(10)) + list(range(10))) idx2 = 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 = 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 = MultiIndex.from_product( [ Categorical(["a", "b", "c"]), Categorical(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 = 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 = MultiIndex.from_product([[-1, 0, 1], [0, 2, 3, 4]]) mult_idx_2 = 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 = 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 = MultiIndex.from_product([[1, 3], [2, 4, 6], [5, 7]]) mult_idx_2 = 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 = MultiIndex.from_product([[1, 2]] * 4) mult_idx_2 = 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 = 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 = MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"]) idx2 = 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_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, Index])def test_getitem_bool_index_all(box): # GH#22533 ind1 = box([True] * 5) idx = 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 = MultiIndex.from_tuples([(10, 1), (30, 3)]) tm.assert_index_equal(idx[ind2], expected)
@pytest.mark.parametrize("box", [list, Index])def test_getitem_bool_index_single(box): # GH#22533 ind1 = box([True]) idx = MultiIndex.from_tuples([(10, 1)]) tm.assert_index_equal(idx[ind1], idx)
ind2 = box([False]) expected = 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 = MultiIndex( levels=[Index(np.arange(4)), Index(np.arange(4)), 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 = Index([2, 2, 2, 2]) result = index.get_loc(2) expected = slice(0, 4) assert result == expected
index = 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 = MultiIndex( levels=[Index(np.arange(4)), Index(np.arange(4)), 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 = 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 = 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 = 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 = [Index([False, True], dtype=dtype), np.arange(2, dtype="int64")] idx = 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 = MultiIndex.from_product(levels) assert idx.get_loc(tuple(key)) == 3
def test_get_loc_missing_nan(self): # GH 8569 idx = 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 = MultiIndex.from_product([[np.nan, 1]] * 2) expected = slice(0, 2, None) assert idx.get_loc(np.nan) == expected
idx = 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 = 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 = 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 = MultiIndex( levels=[["a"], [0, 7], [1]], codes=[[0, 0], [1, 0], [0, 0]], names=["x", "y", "z"], sortorder=0, ) key = ("a", 7)
with tm.assert_produces_warning(performance_warning): # 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 = 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 = 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)
class TestWhere: def test_where(self): i = 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 = 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 = 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 = MultiIndex( levels=[["C"], date_range("2012-01-01", periods=5)], codes=[[0, 0, 0, 0, 0, 0], [-1, 0, 1, 2, 3, 4]], names=[None, "B"], ) 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 = MultiIndex.from_arrays([[1, np.nan, 2]]) assert np.nan in idx
idx = 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 = 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 = 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 = 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 = 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 = MultiIndex.from_product( [ date_range("2019-01-01T00:15:33", periods=100, freq="h", name="date"), ["x"], [3], ] ) df = DataFrame({"foo": np.arange(len(idx))}, idx) result = df.loc[pd.IndexSlice["2019-1-2":, "x", :], "foo"] qidx = MultiIndex.from_product( [ 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 = 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 = 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 = 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 = 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_indexer_for_multiindex_with_nans(nulls_fixture): # GH37222 idx1 = MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"]) idx2 = 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 = 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 = 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")) == 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289import re
import numpy as npimport pytest
from pandas._libs import index as libindex
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
import pandas as pdfrom pandas import ( Index, IntervalIndex, MultiIndex, RangeIndex,)import pandas._testing as tm
def test_labels_dtypes(): # GH 8456 i = MultiIndex.from_tuples([("A", 1), ("A", 2)]) assert i.codes[0].dtype == "int8" assert i.codes[1].dtype == "int8"
i = MultiIndex.from_product([["a"], range(40)]) assert i.codes[1].dtype == "int8" i = MultiIndex.from_product([["a"], range(400)]) assert i.codes[1].dtype == "int16" i = MultiIndex.from_product([["a"], range(40000)]) assert i.codes[1].dtype == "int32"
i = 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 = 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 = 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) pidx = pd.PeriodIndex(ints, freq="D")
idx = MultiIndex.from_arrays([ints, pidx]) result = idx.values
outer = Index([x[0] for x in result]) tm.assert_index_equal(outer, 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 = Index([x[0] for x in result]) tm.assert_index_equal(outer, 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 = 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 = MultiIndex( levels=[major_axis, minor_axis], codes=[major_codes, minor_codes] )
assert index.is_unique is False
@pytest.mark.slowdef 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 = 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 = 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=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=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_hashtable_populated_attribute_error(monkeypatch): # GH 18165 monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 50) r = range(50) df = pd.DataFrame({"a": r, "b": r}, index=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 = 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=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 = 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 = 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, (RangeIndex, 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 == 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import numpy as npimport pytest
from pandas import MultiIndeximport pandas._testing as tm
def test_isin_nan(): idx = 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 = MultiIndex.from_tuples([(1, nulls_fixture)]) mi2 = 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 = 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 = MultiIndex.from_arrays([[], []]) result = idx.isin(values) assert len(result) == 0 assert result.dtype == np.bool_
def test_isin_level_kwarg(): idx = 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 = 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 = 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 = 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270import numpy as npimport pytest
from pandas import ( DataFrame, Index, Interval, MultiIndex, Series, StringDtype,)import pandas._testing as tm
@pytest.mark.parametrize("other", [["three", "one", "two"], ["one"], ["one", "three"]])def test_join_level(idx, other, join_type): other = 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 = Index(["three", "one", "two"]) result = index.join(idx, level="second") assert isinstance(result, 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 = MultiIndex.from_product([np.arange(4), np.arange(4)], names=["a", "b"]) idx = Index([1, 2, 5], name="b")
# inner jidx, lidx, ridx = midx.join(idx, how="inner", return_indexers=True) exp_idx = 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 = MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"]) midx2 = 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 = MultiIndex.from_product([[1, 2], [3, 4], [5, 6]], names=["a", "b", "c"]) midx2 = 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 = MultiIndex.from_tuples( [ (1, Interval(0.0, 1.0)), (1, Interval(1.0, 2.0)), (1, Interval(2.0, 5.0)), (2, Interval(0.0, 1.0)), (2, Interval(1.0, 3.0)), # interval limit is here at 3.0, not at 2.0 (2, Interval(3.0, 5.0)), ], names=["num", "interval"], )
idx_2 = MultiIndex.from_tuples( [ (1, Interval(2.0, 5.0)), (1, Interval(0.0, 1.0)), (1, Interval(1.0, 2.0)), (2, Interval(3.0, 5.0)), (2, Interval(0.0, 1.0)), (2, Interval(1.0, 3.0)), ], names=["num", "interval"], )
expected = MultiIndex.from_tuples( [ (1, Interval(0.0, 1.0)), (1, Interval(1.0, 2.0)), (1, Interval(2.0, 5.0)), (2, Interval(0.0, 1.0)), (2, Interval(1.0, 3.0)), (2, 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 = MultiIndex.from_arrays( [Series([1, 1, 3], dtype="Int64"), Series([1, 2, 3], dtype="Int64")], names=["a", "b"], ) midx2 = MultiIndex.from_arrays( [Series([1], dtype="Int64"), Series([3], dtype="Int64")], names=["a", "c"] ) result = midx.join(midx2, how="inner") expected = MultiIndex.from_arrays( [ Series([1, 1], dtype="Int64"), Series([1, 2], dtype="Int64"), Series([3, 3], dtype="Int64"), ], names=["a", "b", "c"], ) tm.assert_index_equal(result, expected)
def test_join_midx_string(): # GH#49277 midx = MultiIndex.from_arrays( [ Series(["a", "a", "c"], dtype=StringDtype()), Series(["a", "b", "c"], dtype=StringDtype()), ], names=["a", "b"], ) midx2 = MultiIndex.from_arrays( [Series(["a"], dtype=StringDtype()), Series(["c"], dtype=StringDtype())], names=["a", "c"], ) result = midx.join(midx2, how="inner") expected = MultiIndex.from_arrays( [ Series(["a", "a"], dtype=StringDtype()), Series(["a", "b"], dtype=StringDtype()), Series(["c", "c"], dtype=StringDtype()), ], names=["a", "b", "c"], ) tm.assert_index_equal(result, expected)
def test_join_multi_with_nan(): # GH29252 df1 = DataFrame( data={"col1": [1.1, 1.2]}, index=MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"]), ) df2 = DataFrame( data={"col2": [2.1, 2.2]}, index=MultiIndex.from_product([["A"], [np.nan, 2.0]], names=["id1", "id2"]), ) result = df1.join(df2) expected = DataFrame( data={"col1": [1.1, 1.2], "col2": [np.nan, 2.2]}, index=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 = MultiIndex.from_arrays([Series([1, 2], dtype=any_numeric_ea_dtype), [3, 4]]) midx2 = MultiIndex.from_arrays( [Series([1, val, val], dtype=any_numeric_ea_dtype), [3, 4, 4]] ) result = midx.join(midx2, how="outer") expected = MultiIndex.from_arrays( [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 = MultiIndex.from_arrays( [Series([1, 2], dtype=any_numeric_ea_dtype), [np.nan, np.nan]] ) midx2 = MultiIndex.from_arrays( [Series([1, 0, 0], dtype=any_numeric_ea_dtype), [np.nan, np.nan, np.nan]] ) result = midx.join(midx2, how="outer") expected = MultiIndex.from_arrays( [ 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 = MultiIndex.from_tuples([("a", "2019-02-01"), ("a", "2019-02-01")]) midx2 = MultiIndex.from_tuples([("a", "2019-01-31")]) result = midx.join(midx2, how="outer") expected = 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)12345678910111213141516171819202122232425262728293031323334353637383940414243444546from pandas import MultiIndex
class TestIsLexsorted: def test_is_lexsorted(self): levels = [[0, 1], [0, 1, 2]]
index = MultiIndex( levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]] ) assert index._is_lexsorted()
index = MultiIndex( levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]] ) assert not index._is_lexsorted()
index = 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 = MultiIndex( levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]], sortorder=2 ) assert index._lexsort_depth == 2
index = MultiIndex( levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]], sortorder=1 ) assert index._lexsort_depth == 1
index = MultiIndex( levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]], sortorder=0 ) assert index._lexsort_depth == 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import numpy as npimport pytest
import pandas as pdfrom pandas import MultiIndeximport 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 = MultiIndex.from_arrays( [ [1, np.nan, 3, np.nan, 5], [1, 2, np.nan, np.nan, 5], ["a", "b", "c", np.nan, "e"], ] )
exp = 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 = 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 = 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 = MultiIndex.from_arrays([["128", 2], ["128", 2]]) tm.assert_index_equal(idx.dropna(), expected) tm.assert_index_equal(idx.dropna(how="any"), expected)
expected = 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 = MultiIndex(levels=[["A", "B"], []], codes=[[1, 0], [-1, -1]], names=[0, 1]) idx1 = 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 = 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])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188import numpy as npimport pytest
from pandas import ( Index, MultiIndex,)
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 Index(mi.values).is_monotonic_increasing is False assert mi._is_strictly_monotonic_increasing is False assert Index(mi.values)._is_strictly_monotonic_increasing is False
def test_is_monotonic_increasing(): i = 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 Index(i.values).is_monotonic_increasing is True assert i._is_strictly_monotonic_increasing is True
i = 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 Index(i.values).is_monotonic_increasing is False assert Index(i.values)._is_strictly_monotonic_increasing is False
i = 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 Index(i.values).is_monotonic_increasing is False assert Index(i.values)._is_strictly_monotonic_increasing is False
i = 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 Index(i.values).is_monotonic_increasing is False assert Index(i.values)._is_strictly_monotonic_increasing is False
i = 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 Index(i.values).is_monotonic_increasing is True assert i._is_strictly_monotonic_increasing is True assert Index(i.values)._is_strictly_monotonic_increasing is True
# mixed levels, hits the TypeError i = 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 = MultiIndex.from_arrays([[], []]) assert i.is_monotonic_increasing is True assert Index(i.values).is_monotonic_increasing is True assert i._is_strictly_monotonic_increasing is True assert Index(i.values)._is_strictly_monotonic_increasing is True
def test_is_monotonic_decreasing(): i = 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 Index(i.values).is_monotonic_decreasing is True assert i._is_strictly_monotonic_decreasing is True
i = 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 Index(i.values).is_monotonic_decreasing is False assert Index(i.values)._is_strictly_monotonic_decreasing is False
i = 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 Index(i.values).is_monotonic_decreasing is False assert Index(i.values)._is_strictly_monotonic_decreasing is False
i = 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 Index(i.values).is_monotonic_decreasing is False assert Index(i.values)._is_strictly_monotonic_decreasing is False
# string ordering i = 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 Index(i.values).is_monotonic_decreasing is False assert i._is_strictly_monotonic_decreasing is False assert Index(i.values)._is_strictly_monotonic_decreasing is False
i = 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 Index(i.values).is_monotonic_decreasing is True assert i._is_strictly_monotonic_decreasing is True assert Index(i.values)._is_strictly_monotonic_decreasing is True
# mixed levels, hits the TypeError i = 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 = MultiIndex.from_arrays([[], []]) assert i.is_monotonic_decreasing is True assert Index(i.values).is_monotonic_decreasing is True assert i._is_strictly_monotonic_decreasing is True assert Index(i.values)._is_strictly_monotonic_decreasing is True
def test_is_strictly_monotonic_increasing(): idx = 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 = 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 = MultiIndex.from_tuples(values, names=["test"]) assert getattr(idx, attr) is False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201import pytest
import pandas as pdfrom pandas import MultiIndeximport 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 = 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 = 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"): MultiIndex( levels=[major_axis, minor_axis], codes=[major_codes, minor_codes], names=["first"], ) with pytest.raises(ValueError, match="^Length of names"): 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 = 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 = 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 = MultiIndex.from_arrays([[1, 2], [3, 4], [5, 6]], names=["x", "y", "x"]) result = getattr(mi, func)(rename_dict) expected = 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 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["x", "y"]) result = getattr(mi, func)(rename_dict) expected = 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 = 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"})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148import numpy as npimport pytest
from pandas import ( DataFrame, IndexSlice, MultiIndex, date_range,)import pandas._testing as tm
@pytest.fixturedef 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 = date_range("2016-01-01", "2016-01-03", freq="12h") abc = ["a", "b", "c"] mi = MultiIndex.from_product([dr, abc]) frame = 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[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 = 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[IndexSlice["2013-03":"2013-03", :], :] expected = df.iloc[118:180] tm.assert_frame_equal(result, expected)12345678910import pytest
from pandas import MultiIndex
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"): MultiIndex()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174import numpy as npimport pytest
import pandas as pdfrom pandas import ( Index, MultiIndex,)import pandas._testing as tm
def test_reindex(idx): result, indexer = idx.reindex(list(idx[:4])) assert isinstance(result, 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, 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 = 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 = 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 = 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 = 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 = 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 = MultiIndex.from_tuples([(0, 0), (1, 1), (1, 1), (2, 2)]) a = pd.Series(np.arange(4), index=idx) new_idx = 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 = MultiIndex.from_arrays(values) result, result_indexer = idx.reindex(np.array(["b"]), level=0) expected = 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 = MultiIndex.from_tuples(keys[:-1]) idx = 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_limit_arg_with_multiindex(): # GH21247
idx = MultiIndex.from_tuples([(3, "A"), (4, "A"), (4, "B")])
df = pd.Series([0.02, 0.01, 0.012], index=idx)
new_idx = 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 = MultiIndex.from_tuples([(("a", None), 1), (("b", None), 2)]) index2 = 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224from datetime import datetimeimport zoneinfo
import numpy as npimport pytest
import pandas as pdfrom pandas import ( Index, MultiIndex,)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 = Index([*list(idx.levels[0]), "abc"], name="first") tm.assert_index_equal(new_index.levels[0], exp0) assert new_index.names == ["first", "second"]
exp1 = 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.set_index(["1st", "2nd"], inplace=True) 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.set_index(["1st", "2nd"], inplace=True) # FIXME data types changes to float because # of intermediate nan insertion; tm.assert_frame_equal(left, right, check_dtype=False) 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), MultiIndex.from_tuples(idx[:-2]))
left.loc[("test", 17)] = 11 left.loc[("test", 18)] = 12
right = pd.Series(np.linspace(0, 12, 13), 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 = Index([1.1, 1.2, 1.3]) idx2 = pd.date_range("2011-01-01", freq="D", periods=3, tz="Asia/Tokyo") idx3 = Index(["A", "B", "C"])
midx_lv2 = MultiIndex.from_arrays([idx1, idx2]) midx_lv3 = 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 = Index([1.1, 1.2, 1.3, *expected_tuples]) tm.assert_index_equal(result, expected)
result = midx_lv2.append(idx1) expected = Index([*expected_tuples, 1.1, 1.2, 1.3]) tm.assert_index_equal(result, expected)
result = midx_lv2.append(midx_lv2) expected = MultiIndex.from_arrays([idx1.append(idx1), idx2.append(idx2)]) tm.assert_index_equal(result, expected)
result = midx_lv2.append(midx_lv3) tm.assert_index_equal(result, expected)
result = midx_lv3.append(midx_lv2) expected = 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 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) midx2 = MultiIndex.from_arrays([[3], [5]], names=["a", name]) result = midx.append(midx2) expected = 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 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) midx2 = MultiIndex.from_arrays([[3], [5]], names=["x", "y"]) result = midx.append(midx2) expected = MultiIndex.from_arrays([[1, 2, 3], [3, 4, 5]], names=None) 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 = MultiIndex.from_product([ivl1, ivl1]) mi2 = MultiIndex.from_product([ivl2, ivl2]) result = mi1.append(mi2) expected = 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 = MultiIndex.from_product([numbers, names], names=names) expected = 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))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778import numpy as npimport pytest
import pandas as pdfrom pandas import ( CategoricalIndex, DataFrame, Index, IntervalIndex, MultiIndex, Series,)import pandas._testing as tmfrom 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", [MultiIndex, np.array, Series, list])def test_intersection_base(idx, sort, klass): first = idx[2::-1] # first 3 elements reversed second = idx[:5]
if klass is not 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", [MultiIndex, np.array, Series, list])def test_union_base(idx, sort, klass): first = idx[::-1] second = idx[:5]
if klass is not 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, 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, 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 = 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 = MultiIndex.from_tuples(vals, sortorder=0, names=idx.names)
assert isinstance(result, 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 = 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 = 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 = MultiIndex.from_product([[1, 0], ["a", "b"]]) result = idx.difference([], sort=True) expected = MultiIndex.from_product([[0, 1], ["a", "b"]]) tm.assert_index_equal(result, expected)
def test_difference_sort_incomparable(): # GH-24959 idx = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]])
other = 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 = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]]) other = 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)
def test_union_with_regular_index(idx, using_infer_string): other = 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 = Index(range(3), name="foo")
result = idx.intersection(other, sort=sort) expected = 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 = 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 = 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 = MultiIndex.from_product([[1, 0], ["a", "b"]]) expected = 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 = 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 = MultiIndex.from_product([[1, 0], ["a", "b"]]) other = idx[:0] result = idx.union(other, sort=True) expected = 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 = 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 = 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 = 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 = MultiIndex.from_arrays([[]]) mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"]) result = mi.union(mi2) expected = MultiIndex.from_arrays([[1, 2], [3, 4]]) tm.assert_index_equal(result, expected)
def test_union_multiindex_empty_rangeindex(): # GH#41234 mi = 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 = MultiIndex.from_product([["a", "b"], [1, 2]]) idx2 = 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#? 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 = MultiIndex.from_arrays( [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None] ) midx2 = MultiIndex.from_arrays( [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]] ) result = midx.difference(midx2) expected = MultiIndex.from_arrays([Series([1], dtype=any_numeric_ea_dtype), [2]]) tm.assert_index_equal(result, expected)
result = midx.difference(midx.sort_values(ascending=False)) expected = MultiIndex.from_arrays( [Series([], dtype=any_numeric_ea_dtype), 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 = MultiIndex.from_arrays( [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None] ) midx2 = MultiIndex.from_arrays( [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]] ) result = midx.symmetric_difference(midx2) expected = MultiIndex.from_arrays( [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 = MultiIndex.from_tuples(tuples, names=["first", "second"]) right = MultiIndex.from_tuples( [("val1", "test1"), ("val1", "test1"), ("val2", "test2")], names=["first", "second"], ) result = left.intersection(right) expected = 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 = MultiIndex.from_tuples([], names=["a", "b"]) mi2 = MultiIndex.from_tuples([data], names=names) result = mi._maybe_match_names(mi2) assert result == expected
def test_intersection_equal_different_names(): # GH#30302 mi1 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["c", "b"]) mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])
result = mi1.intersection(mi2) expected = MultiIndex.from_arrays([[1, 2], [3, 4]], names=[None, "b"]) tm.assert_index_equal(result, expected)
def test_intersection_different_names(): # GH#38323 mi = MultiIndex.from_arrays([[1], [3]], names=["c", "b"]) mi2 = 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 = MultiIndex.from_arrays([[3, nulls_fixture, 4, nulls_fixture], [1, 2, 4, 2]]) mi2 = MultiIndex.from_arrays([[3, nulls_fixture, 3], [1, 2, 4]]) result = mi1.intersection(mi2) expected = 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 = MultiIndex.from_arrays([[1, nulls_fixture]]) mi2 = MultiIndex.from_arrays([[1, nulls_fixture, 3]]) result = mi1.union(mi2) expected = 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 = MultiIndex.from_arrays([pd.array([1.0, np.nan], dtype=dtype), [2, 3]]) mi2 = 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 = 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 = Series([val, 2], dtype=any_numeric_ea_dtype) arr2 = Series([2, 1], dtype=any_numeric_ea_dtype) midx = MultiIndex.from_arrays([arr1, [1, 2]], names=["a", None]) midx2 = MultiIndex.from_arrays([arr2, [2, 1]]) result = midx.union(midx2) if val == 4: expected = MultiIndex.from_arrays( [Series([1, 2, 4], dtype=any_numeric_ea_dtype), [1, 2, 1]] ) else: expected = MultiIndex.from_arrays( [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 = MultiIndex.from_arrays( [ Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype), Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype), ] ) mi2 = MultiIndex.from_arrays( [ Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), ] ) result = mi1.union(mi2) expected = MultiIndex.from_arrays( [ Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype), ] ) tm.assert_index_equal(result, expected)
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")def test_union_duplicates(index, request): # GH#38977 if index.empty or isinstance(index, (IntervalIndex, CategoricalIndex)): pytest.skip(f"No duplicates in an empty {type(index).__name__}")
values = index.unique().values.tolist() mi1 = MultiIndex.from_arrays([values, [1] * len(values)]) mi2 = 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 = Series([4, 1, 1], dtype=any_real_numeric_dtype) arr2 = Series([1, 4], dtype=any_real_numeric_dtype) midx = MultiIndex.from_arrays([arr1, [2, 1, 1]], names=["a", None]) midx2 = MultiIndex.from_arrays([arr2, [1, 2]], names=["a", None])
result = midx.union(midx2) expected = MultiIndex.from_arrays( ([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 = Series([4, pd.NA], dtype=any_numeric_ea_dtype) arr2 = Series([1, pd.NA], dtype=any_numeric_ea_dtype) midx = MultiIndex.from_arrays([arr1, [2, 1]], names=["a", None]) midx2 = MultiIndex.from_arrays([arr2, [1, 2]]) result = midx.union(midx2) expected = MultiIndex.from_arrays( [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 = MultiIndex.from_tuples([(1, "a"), (2, "b")], names=["x", "y"]) mi2 = MultiIndex.from_tuples([(2, "b"), (3, "c"), (2, "b")])
result = mi1.union(mi2) expected = 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 = MultiIndex(levels=levels1, codes=codes1, names=names) mi2 = 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 = DataFrame({"x": a, "y": other}) df2 = DataFrame({"x": b, "y": other})
expected = MultiIndex.from_arrays([a, other], names=["x", "y"])
res1 = MultiIndex.from_frame(df1).intersection( MultiIndex.from_frame(df2.sort_values(["x", "y"])) ) res2 = MultiIndex.from_frame(df1).intersection(MultiIndex.from_frame(df2)) res3 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection( MultiIndex.from_frame(df2) ) res4 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection( 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 = MultiIndex.from_arrays( [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None] ) midx2 = MultiIndex.from_arrays( [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]] ) result = midx.intersection(midx2) expected = MultiIndex.from_arrays([Series([2], dtype=any_numeric_ea_dtype), [1]]) tm.assert_index_equal(result, expected)
def test_union_with_na_when_constructing_dataframe(): # GH43222 series1 = Series( (1,), index=MultiIndex.from_arrays( [Series([None], dtype="str"), Series([None], dtype="str")] ), ) series2 = Series((10, 20), index=MultiIndex.from_tuples(((None, None), ("a", "b")))) result = DataFrame([series1, series2]) expected = DataFrame({(np.nan, np.nan): [1.0, 10.0], ("a", "b"): [np.nan, 20.0]}) tm.assert_frame_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346import numpy as npimport pytest
from pandas.errors import UnsortedIndexError
from pandas import ( CategoricalIndex, DataFrame, Index, MultiIndex, RangeIndex, Series, Timestamp,)import pandas._testing as tmfrom pandas.core.indexes.frozen import FrozenList
def test_sortlevel(idx): tuples = list(idx) np.random.default_rng(2).shuffle(tuples)
index = MultiIndex.from_tuples(tuples)
sorted_idx, _ = index.sortlevel(0) expected = 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 = 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 = 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 = MultiIndex.from_tuples(tuples)
sorted_idx, _ = index.sortlevel(0) expected = 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 = 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 = MultiIndex.from_tuples([(1, np.nan), (1, 1)]) result = midx.sortlevel(level=[0, 1], na_position="last")[0] expected = 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), (CategoricalIndex, 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 = MultiIndex.from_tuples( [("z", "a"), ("x", "a"), ("y", "b"), ("x", "b"), ("y", "a"), ("z", "b")], names=["one", "two"], ) df = 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")] df.sort_index(inplace=True) assert len(df.loc(axis=0)["z", :]) == 2
with pytest.raises(KeyError, match="'q'"): df.loc(axis=0)["q", :]
def test_unsortedindex_doc_examples(performance_warning): # https://pandas.pydata.org/pandas-docs/stable/advanced.html#sorting-a-multiindex dfm = 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"]) with tm.assert_produces_warning(performance_warning): 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 = 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 Index(mi.values).equals(Index(recons.values))
# cannot convert to lexsorted mi = 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 Index(mi.values).equals(Index(recons.values))
# cannot convert to lexsorted mi = 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 Index(mi.values).equals(Index(recons.values))
def test_reconstruct_remove_unused(): # xref to GH 2770 df = 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 = 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 = 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 = 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 = 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 = 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 = MultiIndex(levels=[["A", "B", "C"], ["D"]], codes=[[1, 0, 2], [-1, -1, 0]]) result = midx.sort_values() expected = 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 = MultiIndex.from_arrays( [ [1, Timestamp("2000-01-01")], [3, 4], ] ) match = "'<' not supported between instances of 'Timestamp' and 'int'" with pytest.raises(TypeError, match=match): mi.sort_values()
@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 = [ Series([1, 1, 2], dtype=dtype), Series([1, None, 3], dtype=dtype), ] index = MultiIndex.from_arrays(arrays) result = index.sort_values(na_position=na_position) if na_position == "first": arrays = [ Series([1, 1, 2], dtype=dtype), Series([None, 1, 3], dtype=dtype), ] else: arrays = [ Series([1, 1, 2], dtype=dtype), Series([1, None, 3], dtype=dtype), ] expected = MultiIndex.from_arrays(arrays) tm.assert_index_equal(result, expected)
def test_sort_unnecessary_warning(): # GH#55386 midx = 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 = MultiIndex.from_tuples([(1, 3), (2.5, 1), (np.nan, 2)]) tm.assert_index_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import numpy as npimport pytest
import pandas as pdimport 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, fill_value=True) 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 = "When allow_fill=True and fill_value is not None, 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 4" with pytest.raises(IndexError, match=msg): idx.take(np.array([1, -5]))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import numpy as npimport pytest
from pandas import ( Index, date_range,)import pandas._testing as tmfrom 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 = date_range("2000-01-01", periods=2) result1, result2 = (Index(y).day for y in cartesian_product([x, x])) expected1 = Index([1, 1, 2, 2], dtype=np.int32) expected2 = Index([1, 2, 1, 2], dtype=np.int32) tm.assert_index_equal(result1, expected1) tm.assert_index_equal(result2, expected2)
@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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import numpy as npimport pytest
from pandas import ( Index, to_datetime, to_timedelta,)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 = Index([0.0, 5.0, 10.0, 15.0, 20.0], dtype=np.float64) result = idx.astype("u8") expected = 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 = 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, Index) and result.dtype == object
def test_astype_float64_mixed_to_object(self): # mixed int-float idx = 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, 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 = Index([0, 1, 2], dtype=np.float64) result = idx.astype(dtype) expected = Index([0, 1, 2], dtype=dtype) tm.assert_index_equal(result, expected, exact=True)
idx = Index([0, 1.1, 2], dtype=np.float64) result = idx.astype(dtype) expected = 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 = Index([0, 1, 2], dtype=np.float64) result = idx.astype(dtype) assert isinstance(result, 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 = Index([0, 1.1, 2], dtype=np.float64)
result = idx.astype(dtype) if dtype[0] == "M": expected = to_datetime(idx.values) else: expected = 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 = 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 = Index([1.0, np.nan, 0.2], dtype="object") result = index.astype(float) expected = Index([1.0, np.nan, 0.2], dtype=np.float64) assert result.dtype == expected.dtype tm.assert_index_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623import numpy as npimport pytest
from pandas.errors import InvalidIndexError
from pandas import ( NA, Index, RangeIndex, Series, Timestamp,)import pandas._testing as tmfrom pandas.core.arrays import ( ArrowExtensionArray, FloatingArray,)
class TestGetLoc: def test_get_loc(self): index = Index([0, 1, 2]) assert index.get_loc(1) == 1
def test_get_loc_raises_bad_label(self): index = Index([0, 1, 2]) with pytest.raises(InvalidIndexError, match=r"\[1, 2\]"): index.get_loc([1, 2])
def test_get_loc_float64(self): idx = 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 = Index([np.nan, 1, 2], dtype=np.float64) assert idx.get_loc(1) == 1 assert idx.get_loc(np.nan) == 0
idx = 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 = 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 = 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], [Timestamp("2019-12-31")], ["test"]]) def test_get_loc_float_index_nan_with_method(self, vals): # GH#39382 idx = 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 = 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 = 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 = Index([1, 2, 3, 4, 5]) index2 = 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 = Index([1, 2, 3, 4, 5]) index2 = 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 = 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 = 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, 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 = 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))
def test_get_indexer_nearest_error(self): index = 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 = 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 = RangeIndex(4) else: numeric_index = Index(np.arange(4, dtype=idx_dtype))
other = 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 = Index([1, 2, 3]) right = 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 = Index([1, 2, 3]) right = 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 = 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 = 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 = Index(range(0, 20, 2), dtype=np.int64) target = 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 = 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 = 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 = Index( [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25], dtype=np.uint64, ) target = 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 = 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 = 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, NA), (NA, NA)]) def test_get_loc_masked(self, val, val2, any_numeric_ea_and_arrow_dtype): # GH#39133 idx = 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 = Index([1, 2, NA], dtype=any_numeric_ea_and_arrow_dtype) result = idx.get_loc(NA) assert result == 2
idx = Index([1, 2, NA, NA], dtype=any_numeric_ea_and_arrow_dtype) result = idx.get_loc(NA) tm.assert_numpy_array_equal(result, np.array([False, False, True, True]))
idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype) with pytest.raises(KeyError, match="NA"): idx.get_loc(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 = 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(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(NA) assert result == 2 result = idx.get_loc(np.nan) assert result == 3
idx = Index( FloatingArray(np.array([1, 2, 1.0]), mask=np.array([False, False, True])) ) result = idx.get_loc(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 = 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(NA) assert result == 2 else: with pytest.raises(KeyError, match="NA"): idx.get_loc(NA)
@pytest.mark.parametrize("val", [4, 2]) def test_get_indexer_masked_na(self, any_numeric_ea_and_arrow_dtype, val): # GH#39133 idx = Index([1, 2, NA, 3, val], dtype=any_numeric_ea_and_arrow_dtype) result = idx.get_indexer_for([1, 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 = Index([True, False, NA], dtype=dtype) result = idx.get_loc(False) assert result == 1 result = idx.get_loc(NA) assert result == 2
def test_get_indexer_arrow_dictionary_target(self): pa = pytest.importorskip("pyarrow") target = Index( ArrowExtensionArray( pa.array([1, 2], type=pa.dictionary(pa.int8(), pa.int8())) ) ) idx = Index([1])
result = idx.get_indexer(target) expected = np.array([0, -1], dtype=np.int64) 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.int64), np.array([1], dtype=np.int64), ) tm.assert_numpy_array_equal(result_1, expected_1) tm.assert_numpy_array_equal(result_2, expected_2)
class TestWhere: @pytest.mark.parametrize( "index", [ Index(np.arange(5, dtype="float64")), Index(range(0, 20, 2), dtype=np.int64), 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 = 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 = Index([0, 6, 2], dtype=np.uint64) mask = np.array([False, True, False]) other = np.array([1], dtype=np.int64)
expected = 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 = Index([1, np.nan]) cond = index.notna() other = Index(["a", "b"], dtype="string")
expected = 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 = 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 = Index([1.0, 2.0, 3.0], name="xxx", dtype=np.float64) result = idx.take(np.array([1, 0, -1])) expected = 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=True) expected = 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, fill_value=True) expected = Index([2.0, 1.0, 3.0], dtype=np.float64, name="xxx") tm.assert_index_equal(result, expected)
msg = ( "When allow_fill=True and fill_value is not None, 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 = Index([1, 2, 3], dtype=dtype, name="xxx") result = idx.take(np.array([1, 0, -1])) expected = Index([2, 1, 3], dtype=dtype, name="xxx") tm.assert_index_equal(result, expected)
name = type(idx).__name__ msg = f"Unable to fill values because {name} cannot contain NA"
# fill_value=True with pytest.raises(ValueError, match=msg): idx.take(np.array([1, 0, -1]), fill_value=True)
# allow_fill=False result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) expected = Index([2, 1, 3], dtype=dtype, name="xxx") tm.assert_index_equal(result, expected)
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 = Index([0, 1, 2, 3, 4], dtype=dtype) assert None not in index
def test_contains_float64_nans(self): index = Index([1.0, 2.0, np.nan], dtype=np.float64) assert np.nan in index
def test_contains_float64_not_nans(self): index = 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 = 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 = 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 = 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 = Index([np.nan, 1, 2]) assert index.slice_locs(1) == (1, 3) assert index.slice_locs(np.nan) == (0, 3)
index = Index([0, np.nan, np.nan, 1, 2]) assert index.slice_locs(np.nan) == (1, 5)
def test_slice_locs_na_raises(self): index = 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 = 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 = Index(range(6)) result = index.get_slice_bound(bound, side=side) assert result == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368import numpy as npimport pytest
import pandas._testing as tmfrom 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) 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)
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) 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.astype(object))
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.astype(object))
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.astype(object))
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.astype(object))
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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550import numpy as npimport pytest
import pandas as pdfrom pandas import ( Index, Series,)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 Index([1.5, 2, 3, 4, 5], dtype=dtype)
@pytest.fixture def float_index(self, dtype): return 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 = Index(index_data, dtype=dtype) tm.assert_index_equal(eval(repr(index)), 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, Index) else: assert type(b) is Index
def test_constructor_from_list_no_dtype(self): index = Index([1.5, 2.5, 3.5]) assert index.dtype == np.float64
def test_constructor(self, dtype): index_cls = 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 = 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, Index([1.5, 2, 3, 4, 5])) self.check_coerce(float_index, Index(np.arange(5) * 2.5))
result = 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, Index((np.arange(5) * 2.5), dtype=object), is_float_index=False ) self.check_coerce( mixed_index, 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): Index([1, 2, 3.5], dtype=any_int_numpy_dtype)
def test_equals_numeric(self): index_cls = 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", ( Index([1, 2], dtype=np.int64), Index([1.0, 2.0], dtype=object), Index([1, 2], dtype=object), ), ) def test_equals_numeric_other_index_type(self, other): idx = 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 = 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 = 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 = 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 = Index # GH 11343 idx = Index([1.0, np.nan, 3.0], dtype=float, name="x") # can't downcast exp = 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 = Index([1.0, "obj", 3.0], name="x") tm.assert_index_equal(idx.fillna("obj"), exp, exact=True)
def test_logical_compat(self, dtype): idx = 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 Index(range(0, 20, 2), dtype=dtype)
def test_is_monotonic(self): index_cls = 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 = 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 = Index(index.copy()) assert idx.identical(index)
same_values_different_type = Index(idx, dtype=object) assert not idx.identical(same_values_different_type)
idx = index.astype(dtype=object) idx = idx.rename("foo") same_values = Index(idx, dtype=object) assert same_values.identical(idx)
assert not idx.identical(index) assert 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): Index(data, dtype=dtype)
def test_view_index(self, simple_index): index = simple_index msg = ( "Cannot change data-type for array of references.|" "Cannot change data-type for object array.|" ) with pytest.raises(TypeError, match=msg): index.view(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 = Index([1, 2, 3]) assert index.dtype == np.int64
def test_constructor(self, dtype): index_cls = 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 = 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 [Index, index_cls]: for idx in [ cls([5, 0], dtype=dtype), cls(np.array([5, 0]), dtype=dtype), cls(Series([5, 0]), dtype=dtype), ]: tm.assert_index_equal(idx, expected)
def test_constructor_corner(self, dtype): index_cls = 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 = 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): 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 = Index([scalar]) expected = 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 = Index([scalar]) expected = Index([1], dtype=any_unsigned_int_numpy_dtype) tm.assert_index_equal(result, expected, exact=True)
def test_coerce_list(self): # coerce things arr = Index([1, 2, 3, 4]) assert isinstance(arr, Index)
# but not if explicit dtype passed arr = Index([1, 2, 3, 4], dtype=object) assert type(arr) is Index
class TestFloat16Index: # float 16 indexes not supported # GH 49535 def test_constructor(self): index_cls = 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: 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 = Series( [0, 1, 2, 3, 4, 5], index=[ 7606741985629028552, 17876870360202815256, 17876870360202815256, 13106359306506049338, 8991270399732411471, 8991270399732411472, ], )
result = series.loc[box([7606741985629028552, 17876870360202815256])]
expected = 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 = Index([1.0, 2, 3]) string_index = 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 = Index([1, 2, 3], dtype=np.uint64) result = idx.map(lambda x: -x) expected = 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 = 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 = Index([1000, 2000, 3000], dtype=np.int64) tm.assert_index_equal(result, expected)
def test_view_to_datetimelike(): # GH#55710 idx = 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).gitattributes+19
.venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/INSTALLERAdded+1
.venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/LICENSEAdded+1060
.venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/METADATAAdded+1383
.venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/RECORDAdded
.venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/REQUESTEDAdded
.venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/WHEELAdded+6
.venv/lib/python3.12/site-packages/pandas-3.0.5.dist-info/entry_points.txtAdded+3
.venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_indexing.pyAdded+692
.venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_interval.pyAdded+922
.venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_interval_range.pyAdded+390
.venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_interval_tree.pyAdded+208
.venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_join.pyAdded+44
.venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_pickle.pyAdded+10
.venv/lib/python3.12/site-packages/pandas/tests/indexes/interval/test_setops.pyAdded+208
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/__init__.pyAdded
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/conftest.pyAdded+27
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_analytics.pyAdded+263
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_astype.pyAdded+30
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_compat.pyAdded+122
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_constructors.pyAdded+872
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_conversion.pyAdded+208
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_copy.pyAdded+96
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_drop.pyAdded+188
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_duplicates.pyAdded+357
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_equivalence.pyAdded+284
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_formats.pyAdded+207
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_get_level_values.pyAdded+133
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_get_set.pyAdded+380
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_indexing.pyAdded+1031
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_integrity.pyAdded+289
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_isin.pyAdded+104
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_join.pyAdded+270
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_lexsort.pyAdded+46
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_missing.pyAdded+111
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_monotonic.pyAdded+188
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_names.pyAdded+201
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_partial_indexing.pyAdded+148
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_pickle.pyAdded+10
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_reindex.pyAdded+174
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_reshape.pyAdded+224
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_setops.pyAdded+778
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_sorting.pyAdded+346
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_take.pyAdded+78
.venv/lib/python3.12/site-packages/pandas/tests/indexes/multi/test_util.pyAdded+63
.venv/lib/python3.12/site-packages/pandas/tests/indexes/numeric/__init__.pyAdded
.venv/lib/python3.12/site-packages/pandas/tests/indexes/numeric/test_astype.pyAdded+95
.venv/lib/python3.12/site-packages/pandas/tests/indexes/numeric/test_indexing.pyAdded+623
.venv/lib/python3.12/site-packages/pandas/tests/indexes/numeric/test_join.pyAdded+368
.venv/lib/python3.12/site-packages/pandas/tests/indexes/numeric/test_numeric.pyAdded+550