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+45
- couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/INSTALLERAdded+1
- couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/LICENSEAdded+1060
- couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/METADATAAdded+1383
- couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/RECORDAdded
- couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/REQUESTEDAdded
- couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/WHEELAdded+6
- couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/entry_points.txtAdded+3
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_formats.pyAdded+592
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_iteration.pyAdded+33
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_logical_ops.pyAdded+510
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_missing.pyAdded+88
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_npfuncs.pyAdded+52
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_reductions.pyAdded+233
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_subclass.pyAdded+82
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_ufunc.pyAdded+475
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_unary.pyAdded+50
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_validate.pyAdded+26
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/__init__.pyAdded+23
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/conftest.pyAdded+132
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_api.pyAdded+216
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_case_justify.pyAdded+423
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_cat.pyAdded+444
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_extract.pyAdded+784
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_find_replace.pyAdded+1730
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_get_dummies.pyAdded+102
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_split_partition.pyAdded+772
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_string_array.pyAdded+126
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_strings.pyAdded+952
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_aggregation.pyAdded+93
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_algos.pyAdded+2083
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_col.pyAdded+392
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_common.pyAdded+273
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_downstream.pyAdded+299
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_errors.pyAdded+144
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_expressions.pyAdded+475
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_flags.pyAdded+48
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_multilevel.pyAdded+376
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_nanops.pyAdded+1333
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_optional_dependency.pyAdded+100
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_register_accessor.pyAdded+123
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_sorting.pyAdded+475
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_take.pyAdded+317
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/__init__.pyAdded
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_datetime.pyAdded
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_numeric.pyAdded+904
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_time.pyAdded+64
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_timedelta.pyAdded+389
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tseries/__init__.pyAdded
- couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tseries/frequencies/__init__.pyAdded
129 unmodified lines130131132129 unmodified linescouto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text129 unmodified lines130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177129 unmodified linescouto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libavif-a883386a.so.16.4.1 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libbrotlicommon-785b7a00.so.1.2.0 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libfreetype-d2d71ad9.so.6.20.6 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libharfbuzz-ef65cc8a.so.0.61321.0 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libjpeg-8296d2fa.so.62.4.0 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/liblcms2-545f6561.so.2.0.18 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/liblzma-3c942967.so.5.8.3 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libopenjp2-f3576751.so.2.5.4 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libpng16-65c953c0.so.16.56.0 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libtiff-f4bc73ff.so.6.2.0 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libwebp-67ee3789.so.7.2.0 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libxcb-bac6ebc8.so.1.1.0 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libzstd-6ea785c0.so.1.5.7 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_acero.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_azurefs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_compute.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_csv.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_dataset.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_dataset_parquet.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_dataset_parquet_encryption.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_feather.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_flight.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_fs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_gcsfs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_hdfs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_json.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_orc.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_parquet.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_parquet_encryption.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_s3fs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_substrait.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/lib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow.so.2400 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_acero.so.2400 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_compute.so.2400 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_dataset.so.2400 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_flight.so.2400 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python.so.2400 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python.so.2400.0.0 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python_flight.so filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python_flight.so.2400 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python_flight.so.2400.0.0 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_substrait.so.2400 filter=lfs diff=lfs merge=lfs -textcouto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libparquet.so.2400 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.4Summary: 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592from datetime import ( datetime, timedelta,)
import numpy as npimport pytest
import pandas as pdfrom pandas import ( Categorical, DataFrame, Index, Series, date_range, option_context, period_range, timedelta_range,)
class TestSeriesRepr: def test_multilevel_name_print_0(self): # GH#55415 None does not get printed, but 0 does # (matching DataFrame and flat index behavior) mi = pd.MultiIndex.from_product([range(2, 3), range(3, 4)], names=[0, None]) ser = Series(1.5, index=mi)
res = repr(ser) expected = "0 \n2 3 1.5\ndtype: float64" assert res == expected
def test_multilevel_name_print(self, lexsorted_two_level_string_multiindex): index = lexsorted_two_level_string_multiindex ser = Series(range(len(index)), index=index, name="sth") expected = [ "first second", "foo one 0", " two 1", " three 2", "bar one 3", " two 4", "baz two 5", " three 6", "qux one 7", " two 8", " three 9", "Name: sth, dtype: int64", ] expected = "\n".join(expected) assert repr(ser) == expected
def test_small_name_printing(self): # Test small Series. s = Series([0, 1, 2])
s.name = "test" assert "Name: test" in repr(s)
s.name = None assert "Name:" not in repr(s)
def test_big_name_printing(self): # Test big Series (diff code path). s = Series(range(1000))
s.name = "test" assert "Name: test" in repr(s)
s.name = None assert "Name:" not in repr(s)
def test_empty_name_printing(self): s = Series(index=date_range("20010101", "20020101"), name="test", dtype=object) assert "Name: test" in repr(s)
@pytest.mark.parametrize("args", [(), (0, -1)]) def test_float_range(self, args): str( Series( np.random.default_rng(2).standard_normal(1000), index=np.arange(1000, *args), ) )
def test_empty_object(self): # empty str(Series(dtype=object))
def test_string(self, string_series): str(string_series) str(string_series.astype(int))
# with NaNs string_series[5:7] = np.nan str(string_series)
def test_object(self, object_series): str(object_series)
def test_datetime(self, datetime_series): str(datetime_series) # with Nones ots = datetime_series.astype("O") ots[::2] = None repr(ots)
@pytest.mark.parametrize( "name", [ "", 1, 1.2, "foo", "\u03b1\u03b2\u03b3", "loooooooooooooooooooooooooooooooooooooooooooooooooooong", ("foo", "bar", "baz"), (1, 2), ("foo", 1, 2.3), ("\u03b1", "\u03b2", "\u03b3"), ("\u03b1", "bar"), ], ) def test_various_names(self, name, string_series): # various names string_series.name = name repr(string_series)
def test_tuple_name(self): biggie = Series( np.random.default_rng(2).standard_normal(1000), index=np.arange(1000), name=("foo", "bar", "baz"), ) repr(biggie)
@pytest.mark.parametrize("arg", [100, 1001]) def test_tidy_repr_name_0(self, arg): # tidy repr ser = Series(np.random.default_rng(2).standard_normal(arg), name=0) rep_str = repr(ser) assert "Name: 0" in rep_str
def test_newline(self, any_string_dtype): ser = Series( ["a\n\r\tb"], name="a\n\r\td", index=Index(["a\n\r\tf"], dtype=any_string_dtype), dtype=any_string_dtype, ) assert "\t" not in repr(ser) assert "\r" not in repr(ser) assert "a\n" not in repr(ser)
@pytest.mark.parametrize( "name, expected", [ ["foo", "Series([], Name: foo, dtype: int64)"], [None, "Series([], dtype: int64)"], ], ) def test_empty_int64(self, name, expected): # with empty series (#4651) s = Series([], dtype=np.int64, name=name) assert repr(s) == expected
def test_repr_bool_fails(self, capsys): s = Series( [ DataFrame(np.random.default_rng(2).standard_normal((2, 2))) for i in range(5) ] )
# It works (with no Cython exception barf)! repr(s)
captured = capsys.readouterr() assert captured.err == ""
def test_repr_name_iterable_indexable(self): s = Series([1, 2, 3], name=np.int64(3))
# it works! repr(s)
s.name = ("\u05d0",) * 2 repr(s)
def test_repr_max_rows(self): # GH 6863 with option_context("display.max_rows", None): str(Series(range(1001))) # should not raise exception
def test_unicode_string_with_unicode(self): df = Series(["\u05d0"], name="\u05d1") str(df)
ser = Series(["\u03c3"] * 10) repr(ser)
ser2 = Series(["\u05d0"] * 1000) ser2.name = "title1" repr(ser2)
def test_str_to_bytes_raises(self): # GH 26447 df = Series(["abc"], name="abc") msg = "^'str' object cannot be interpreted as an integer$" with pytest.raises(TypeError, match=msg): bytes(df)
def test_timeseries_repr_object_dtype(self): index = Index( [datetime(2000, 1, 1) + timedelta(i) for i in range(1000)], dtype=object ) ts = Series(np.random.default_rng(2).standard_normal(len(index)), index) repr(ts)
ts = Series( np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20) ) assert repr(ts).splitlines()[-1].startswith("Freq:")
ts2 = ts.iloc[np.random.default_rng(2).integers(0, len(ts) - 1, 400)] repr(ts2).splitlines()[-1]
def test_latex_repr(self): pytest.importorskip("jinja2") # uses Styler implementation result = r"""\begin{tabular}{ll}\toprule & 0 \\\midrule0 & $\alpha$ \\1 & b \\2 & c \\\bottomrule\end{tabular}""" with option_context( "styler.format.escape", None, "styler.render.repr", "latex" ): s = Series([r"$\alpha$", "b", "c"]) assert result == s._repr_latex_()
assert s._repr_latex_() is None
def test_index_repr_in_frame_with_nan(self): # see gh-25061 i = Index([1, np.nan]) s = Series([1, 2], index=i) exp = """1.0 1\nNaN 2\ndtype: int64"""
assert repr(s) == exp
def test_series_repr_nat(self): series = Series([0, 1000, 2000, pd.NaT._value], dtype="M8[ns]")
result = repr(series) expected = ( "0 1970-01-01 00:00:00.000000\n" "1 1970-01-01 00:00:00.000001\n" "2 1970-01-01 00:00:00.000002\n" "3 NaT\n" "dtype: datetime64[ns]" ) assert result == expected
def test_float_repr(self): # GH#35603 # check float format when cast to object ser = Series([1.0]).astype(object) expected = "0 1.0\ndtype: object" assert repr(ser) == expected
def test_different_null_objects(self): # GH#45263 ser = Series([1, 2, 3, 4], [True, None, np.nan, pd.NaT]) result = repr(ser) expected = "True 1\nNone 2\nNaN 3\nNaT 4\ndtype: int64" assert result == expected
def test_2d_extension_type(self): # GH#33770
# Define a stub extension type with just enough code to run Series.__repr__() class DtypeStub(pd.api.extensions.ExtensionDtype): @property def type(self): return np.ndarray
@property def name(self): return "DtypeStub"
class ExtTypeStub(pd.api.extensions.ExtensionArray): def __len__(self) -> int: return 2
def __getitem__(self, ix): return [ix == 1, ix == 0]
@property def dtype(self): return DtypeStub()
series = Series(ExtTypeStub(), copy=False) res = repr(series) # This line crashed before GH#33770 was fixed. expected = "\n".join( ["0 [False True]", "1 [True False]", "dtype: DtypeStub"] ) assert res == expected
class TestCategoricalRepr: def test_categorical_repr_unicode(self): # see gh-21002
class County: name = "San Sebastián" state = "PR"
def __repr__(self) -> str: return self.name + ", " + self.state
cat = Categorical([County() for _ in range(61)]) idx = Index(cat) ser = idx.to_series()
repr(ser) str(ser)
def test_categorical_repr(self, using_infer_string): a = Series(Categorical([1, 2, 3, 4])) exp = ( "0 1\n1 2\n2 3\n3 4\n" "dtype: category\nCategories (4, int64): [1, 2, 3, 4]" )
assert exp == a.__str__()
a = Series(Categorical(["a", "b"] * 25)) exp = ( "0 a\n1 b\n" " ..\n" "48 a\n49 b\n" "Length: 50, dtype: category\nCategories (2, object): ['a', 'b']" ) if using_infer_string: exp = exp.replace("object", "str") with option_context("display.max_rows", 5): assert exp == repr(a)
levs = list("abcdefghijklmnopqrstuvwxyz") a = Series(Categorical(["a", "b"], categories=levs, ordered=True)) exp = ( "0 a\n1 b\n" "dtype: category\n" "Categories (26, object): ['a' < 'b' < 'c' < 'd' ... " "'w' < 'x' < 'y' < 'z']" ) if using_infer_string: exp = exp.replace("object", "str") assert exp == a.__str__()
def test_categorical_series_repr(self): s = Series(Categorical([1, 2, 3])) exp = """0 11 22 3dtype: categoryCategories (3, int64): [1, 2, 3]"""
assert repr(s) == exp
s = Series(Categorical(np.arange(10))) exp = f"""0 01 12 23 34 45 56 67 78 89 9dtype: categoryCategories (10, {np.dtype(int)}): [0, 1, 2, 3, ..., 6, 7, 8, 9]"""
assert repr(s) == exp
def test_categorical_series_repr_ordered(self): s = Series(Categorical([1, 2, 3], ordered=True)) exp = """0 11 22 3dtype: categoryCategories (3, int64): [1 < 2 < 3]"""
assert repr(s) == exp
s = Series(Categorical(np.arange(10), ordered=True)) exp = f"""0 01 12 23 34 45 56 67 78 89 9dtype: categoryCategories (10, {np.dtype(int)}): [0 < 1 < 2 < 3 ... 6 < 7 < 8 < 9]"""
assert repr(s) == exp
def test_categorical_series_repr_datetime(self): idx = date_range("2011-01-01 09:00", freq="h", periods=5, unit="ns") s = Series(Categorical(idx)) exp = """0 2011-01-01 09:00:001 2011-01-01 10:00:002 2011-01-01 11:00:003 2011-01-01 12:00:004 2011-01-01 13:00:00dtype: categoryCategories (5, datetime64[ns]): [2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00]""" # noqa: E501
assert repr(s) == exp
idx = date_range( "2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern", unit="ns" ) s = Series(Categorical(idx)) exp = """0 2011-01-01 09:00:00-05:001 2011-01-01 10:00:00-05:002 2011-01-01 11:00:00-05:003 2011-01-01 12:00:00-05:004 2011-01-01 13:00:00-05:00dtype: categoryCategories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]""" # noqa: E501
assert repr(s) == exp
def test_categorical_series_repr_datetime_ordered(self): idx = date_range("2011-01-01 09:00", freq="h", periods=5, unit="ns") s = Series(Categorical(idx, ordered=True)) exp = """0 2011-01-01 09:00:001 2011-01-01 10:00:002 2011-01-01 11:00:003 2011-01-01 12:00:004 2011-01-01 13:00:00dtype: categoryCategories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 < 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
assert repr(s) == exp
idx = date_range( "2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern", unit="ns" ) s = Series(Categorical(idx, ordered=True)) exp = """0 2011-01-01 09:00:00-05:001 2011-01-01 10:00:00-05:002 2011-01-01 11:00:00-05:003 2011-01-01 12:00:00-05:004 2011-01-01 13:00:00-05:00dtype: categoryCategories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 < 2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 < 2011-01-01 13:00:00-05:00]""" # noqa: E501
assert repr(s) == exp
def test_categorical_series_repr_period(self): idx = period_range("2011-01-01 09:00", freq="h", periods=5) s = Series(Categorical(idx)) exp = """0 2011-01-01 09:001 2011-01-01 10:002 2011-01-01 11:003 2011-01-01 12:004 2011-01-01 13:00dtype: categoryCategories (5, period[h]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]""" # noqa: E501
assert repr(s) == exp
idx = period_range("2011-01", freq="M", periods=5) s = Series(Categorical(idx)) exp = """0 2011-011 2011-022 2011-033 2011-044 2011-05dtype: categoryCategories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]"""
assert repr(s) == exp
def test_categorical_series_repr_period_ordered(self): idx = period_range("2011-01-01 09:00", freq="h", periods=5) s = Series(Categorical(idx, ordered=True)) exp = """0 2011-01-01 09:001 2011-01-01 10:002 2011-01-01 11:003 2011-01-01 12:004 2011-01-01 13:00dtype: categoryCategories (5, period[h]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 < 2011-01-01 13:00]""" # noqa: E501
assert repr(s) == exp
idx = period_range("2011-01", freq="M", periods=5) s = Series(Categorical(idx, ordered=True)) exp = """0 2011-011 2011-022 2011-033 2011-044 2011-05dtype: categoryCategories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]"""
assert repr(s) == exp
def test_categorical_series_repr_timedelta(self): idx = timedelta_range("1 days", periods=5) s = Series(Categorical(idx)) exp = """0 1 days1 2 days2 3 days3 4 days4 5 daysdtype: categoryCategories (5, timedelta64[us]): [1 days, 2 days, 3 days, 4 days, 5 days]"""
assert repr(s) == exp
idx = timedelta_range("1 hours", periods=10) s = Series(Categorical(idx)) exp = """0 0 days 01:00:001 1 days 01:00:002 2 days 01:00:003 3 days 01:00:004 4 days 01:00:005 5 days 01:00:006 6 days 01:00:007 7 days 01:00:008 8 days 01:00:009 9 days 01:00:00dtype: categoryCategories (10, timedelta64[us]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00, 8 days 01:00:00, 9 days 01:00:00]""" # noqa: E501
assert repr(s) == exp
def test_categorical_series_repr_timedelta_ordered(self): idx = timedelta_range("1 days", periods=5) s = Series(Categorical(idx, ordered=True)) exp = """0 1 days1 2 days2 3 days3 4 days4 5 daysdtype: categoryCategories (5, timedelta64[us]): [1 days < 2 days < 3 days < 4 days < 5 days]"""
assert repr(s) == exp
idx = timedelta_range("1 hours", periods=10) s = Series(Categorical(idx, ordered=True)) exp = """0 0 days 01:00:001 1 days 01:00:002 2 days 01:00:003 3 days 01:00:004 4 days 01:00:005 5 days 01:00:006 6 days 01:00:007 7 days 01:00:008 8 days 01:00:009 9 days 01:00:00dtype: categoryCategories (10, timedelta64[us]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 < 3 days 01:00:00 ... 6 days 01:00:00 < 7 days 01:00:00 < 8 days 01:00:00 < 9 days 01:00:00]""" # noqa: E501
assert repr(s) == exp123456789101112131415161718192021222324252627282930313233class TestIteration: def test_keys(self, datetime_series): assert datetime_series.keys() is datetime_series.index
def test_iter_datetimes(self, datetime_series): for i, val in enumerate(datetime_series): assert val == datetime_series.iloc[i]
def test_iter_strings(self, string_series): for i, val in enumerate(string_series): assert val == string_series.iloc[i]
def test_iteritems_datetimes(self, datetime_series): for idx, val in datetime_series.items(): assert val == datetime_series[idx] # noqa: PLR1733
def test_iteritems_strings(self, string_series): for idx, val in string_series.items(): assert val == string_series[idx] # noqa: PLR1733
# assert is lazy (generators don't define reverse, lists do) assert not hasattr(string_series.items(), "reverse")
def test_items_datetimes(self, datetime_series): for idx, val in datetime_series.items(): assert val == datetime_series[idx] # noqa: PLR1733
def test_items_strings(self, string_series): for idx, val in string_series.items(): assert val == string_series[idx] # noqa: PLR1733
# assert is lazy (generators don't define reverse, lists do) assert not hasattr(string_series.items(), "reverse")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510from datetime import datetimeimport operator
import numpy as npimport pytest
from pandas import ( DataFrame, Index, Series, bdate_range,)import pandas._testing as tmfrom pandas.core import ops
class TestSeriesLogicalOps: @pytest.mark.parametrize("bool_op", [operator.and_, operator.or_, operator.xor]) def test_bool_operators_with_nas(self, bool_op): # boolean &, |, ^ should work with object arrays and propagate NAs ser = Series(bdate_range("1/1/2000", periods=10), dtype=object) ser[::2] = np.nan
mask = ser.isna() filled = ser.fillna(ser[0])
result = bool_op(ser < ser[9], ser > ser[3])
expected = bool_op(filled < filled[9], filled > filled[3]) expected[mask] = False tm.assert_series_equal(result, expected)
def test_logical_operators_bool_dtype_with_empty(self): # GH#9016: support bitwise op for integer types index = list("bca")
s_tft = Series([True, False, True], index=index) s_fff = Series([False, False, False], index=index) s_empty = Series([], dtype=object)
res = s_tft & s_empty expected = s_fff.sort_index() tm.assert_series_equal(res, expected)
res = s_tft | s_empty expected = s_tft.sort_index() tm.assert_series_equal(res, expected)
def test_logical_operators_int_dtype_with_int_dtype(self): # GH#9016: support bitwise op for integer types
s_0123 = Series(range(4), dtype="int64") s_3333 = Series([3] * 4) s_4444 = Series([4] * 4)
res = s_0123 & s_3333 expected = Series(range(4), dtype="int64") tm.assert_series_equal(res, expected)
res = s_0123 | s_4444 expected = Series(range(4, 8), dtype="int64") tm.assert_series_equal(res, expected)
s_1111 = Series([1] * 4, dtype="int8") res = s_0123 & s_1111 expected = Series([0, 1, 0, 1], dtype="int64") tm.assert_series_equal(res, expected)
res = s_0123.astype(np.int16) | s_1111.astype(np.int32) expected = Series([1, 1, 3, 3], dtype="int32") tm.assert_series_equal(res, expected)
def test_logical_operators_int_dtype_with_int_scalar(self): # GH#9016: support bitwise op for integer types s_0123 = Series(range(4), dtype="int64")
res = s_0123 & 0 expected = Series([0] * 4) tm.assert_series_equal(res, expected)
res = s_0123 & 1 expected = Series([0, 1, 0, 1]) tm.assert_series_equal(res, expected)
def test_logical_operators_int_dtype_with_float(self): # GH#9016: support bitwise op for integer types s_0123 = Series(range(4), dtype="int64")
err_msg = ( r"Logical ops \(and, or, xor\) between Pandas objects and " "dtype-less sequences" )
msg = "Cannot perform.+with a dtyped.+array and scalar of type" with pytest.raises(TypeError, match=msg): s_0123 & np.nan with pytest.raises(TypeError, match=msg): s_0123 & 3.14 msg = "unsupported operand type.+for &:" with pytest.raises(TypeError, match=err_msg): s_0123 & [0.1, 4, 3.14, 2] with pytest.raises(TypeError, match=msg): s_0123 & np.array([0.1, 4, 3.14, 2]) with pytest.raises(TypeError, match=msg): s_0123 & Series([0.1, 4, -3.14, 2])
def test_logical_operators_int_dtype_with_str(self): s_1111 = Series([1] * 4, dtype="int8")
err_msg = ( r"Logical ops \(and, or, xor\) between Pandas objects and " "dtype-less sequences" )
msg = "Cannot perform 'and_' with a dtyped.+array and scalar of type" with pytest.raises(TypeError, match=msg): s_1111 & "a" with pytest.raises(TypeError, match=err_msg): s_1111 & ["a", "b", "c", "d"]
def test_logical_operators_int_dtype_with_bool(self): # GH#9016: support bitwise op for integer types s_0123 = Series(range(4), dtype="int64")
expected = Series([False] * 4)
result = s_0123 & False tm.assert_series_equal(result, expected)
msg = ( r"Logical ops \(and, or, xor\) between Pandas objects and " "dtype-less sequences" ) with pytest.raises(TypeError, match=msg): s_0123 & [False]
with pytest.raises(TypeError, match=msg): s_0123 & (False,)
result = s_0123 ^ False expected = Series([False, True, True, True]) tm.assert_series_equal(result, expected)
def test_logical_operators_int_dtype_with_object(self): # GH#9016: support bitwise op for integer types s_0123 = Series(range(4), dtype="int64")
result = s_0123 & Series([False, np.nan, False, False]) expected = Series([False] * 4) tm.assert_series_equal(result, expected)
s_abNd = Series(["a", "b", np.nan, "d"]) with pytest.raises( TypeError, match="unsupported.* 'int' and 'str'|'rand_' not supported" ): s_0123 & s_abNd
def test_logical_operators_bool_dtype_with_int(self): index = list("bca")
s_tft = Series([True, False, True], index=index) s_fff = Series([False, False, False], index=index)
res = s_tft & 0 expected = s_fff tm.assert_series_equal(res, expected)
res = s_tft & 1 expected = s_tft tm.assert_series_equal(res, expected)
def test_logical_ops_bool_dtype_with_ndarray(self): # make sure we operate on ndarray the same as Series left = Series([True, True, True, False, True]) right = [True, False, None, True, np.nan]
msg = ( r"Logical ops \(and, or, xor\) between Pandas objects and " "dtype-less sequences" )
expected = Series([True, False, False, False, False]) with pytest.raises(TypeError, match=msg): left & right result = left & np.array(right) tm.assert_series_equal(result, expected) result = left & Index(right) tm.assert_series_equal(result, expected) result = left & Series(right) tm.assert_series_equal(result, expected)
expected = Series([True, True, True, True, True]) with pytest.raises(TypeError, match=msg): left | right result = left | np.array(right) tm.assert_series_equal(result, expected) result = left | Index(right) tm.assert_series_equal(result, expected) result = left | Series(right) tm.assert_series_equal(result, expected)
expected = Series([False, True, True, True, True]) with pytest.raises(TypeError, match=msg): left ^ right result = left ^ np.array(right) tm.assert_series_equal(result, expected) result = left ^ Index(right) tm.assert_series_equal(result, expected) result = left ^ Series(right) tm.assert_series_equal(result, expected)
def test_logical_operators_int_dtype_with_bool_dtype_and_reindex(self): # GH#9016: support bitwise op for integer types
index = list("bca")
s_tft = Series([True, False, True], index=index) s_tft = Series([True, False, True], index=index) s_tff = Series([True, False, False], index=index)
s_0123 = Series(range(4), dtype="int64")
# s_0123 will be all false now because of reindexing like s_tft expected = Series([False] * 7, index=[0, 1, 2, 3, "a", "b", "c"]) result = s_tft & s_0123 tm.assert_series_equal(result, expected)
# GH#52538: no longer to object type when reindex is needed; # matches DataFrame behavior msg = r"unsupported operand type\(s\) for &: 'float' and 'bool'" with pytest.raises(TypeError, match=msg): s_0123 & s_tft
s_a0b1c0 = Series([1], list("b"))
res = s_tft & s_a0b1c0 expected = s_tff.reindex(list("abc")) tm.assert_series_equal(res, expected)
res = s_tft | s_a0b1c0 expected = s_tft.reindex(list("abc")) tm.assert_series_equal(res, expected)
def test_scalar_na_logical_ops_corners(self): s = Series([2, 3, 4, 5, 6, 7, 8, 9, 10])
msg = "Cannot perform.+with a dtyped.+array and scalar of type" with pytest.raises(TypeError, match=msg): s & datetime(2005, 1, 1)
s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)]) s[::2] = np.nan
expected = Series(True, index=s.index) expected[::2] = False
msg = ( r"Logical ops \(and, or, xor\) between Pandas objects and " "dtype-less sequences" ) with pytest.raises(TypeError, match=msg): s & list(s)
def test_scalar_na_logical_ops_corners_aligns(self): s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)]) s[::2] = np.nan d = DataFrame({"A": s})
expected = DataFrame(False, index=range(9), columns=["A", *list(range(9))])
result = s & d tm.assert_frame_equal(result, expected)
result = d & s tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("op", [operator.and_, operator.or_, operator.xor]) def test_logical_ops_with_index(self, op): # GH#22092, GH#19792 ser = Series([True, True, False, False]) idx1 = Index([True, False, True, False]) idx2 = Index([1, 0, 1, 0])
expected = Series([op(ser[n], idx1[n]) for n in range(len(ser))])
result = op(ser, idx1) tm.assert_series_equal(result, expected)
expected = Series([op(ser[n], idx2[n]) for n in range(len(ser))], dtype=bool)
result = op(ser, idx2) tm.assert_series_equal(result, expected)
def test_reversed_xor_with_index_returns_series(self): # GH#22092, GH#19792 pre-2.0 these were aliased to setops ser = Series([True, True, False, False]) idx1 = Index([True, False, True, False], dtype=bool) idx2 = Index([1, 0, 1, 0])
expected = Series([False, True, True, False]) result = idx1 ^ ser tm.assert_series_equal(result, expected)
result = idx2 ^ ser tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "op", [ ops.rand_, ops.ror_, ], ) def test_reversed_logical_op_with_index_returns_series(self, op): # GH#22092, GH#19792 ser = Series([True, True, False, False]) idx1 = Index([True, False, True, False]) idx2 = Index([1, 0, 1, 0])
expected = Series(op(idx1.values, ser.values)) result = op(ser, idx1) tm.assert_series_equal(result, expected)
expected = op(ser, Series(idx2)) result = op(ser, idx2) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "op, expected", [ (ops.rand_, [False, False]), (ops.ror_, [True, True]), (ops.rxor, [True, True]), ], ) def test_reverse_ops_with_index(self, op, expected): # https://github.com/pandas-dev/pandas/pull/23628 # multi-set Index ops are buggy, so let's avoid duplicates... # GH#49503 ser = Series([True, False]) idx = Index([False, True])
result = op(ser, idx) expected = Series(expected) tm.assert_series_equal(result, expected)
def test_logical_ops_label_based(self, using_infer_string): # GH#4947 # logical ops should be label based
a = Series([True, False, True], list("bca")) b = Series([False, True, False], list("abc"))
expected = Series([False, True, False], list("abc")) result = a & b tm.assert_series_equal(result, expected)
expected = Series([True, True, False], list("abc")) result = a | b tm.assert_series_equal(result, expected)
expected = Series([True, False, False], list("abc")) result = a ^ b tm.assert_series_equal(result, expected)
# rhs is bigger a = Series([True, False, True], list("bca")) b = Series([False, True, False, True], list("abcd"))
expected = Series([False, True, False, False], list("abcd")) result = a & b tm.assert_series_equal(result, expected)
expected = Series([True, True, False, False], list("abcd")) result = a | b tm.assert_series_equal(result, expected)
# filling
# vs empty empty = Series([], dtype=object)
result = a & empty expected = Series([False, False, False], list("abc")) tm.assert_series_equal(result, expected)
result = a | empty expected = Series([True, True, False], list("abc")) tm.assert_series_equal(result, expected)
# vs non-matching result = a & Series([1], ["z"]) expected = Series([False, False, False, False], list("abcz")) tm.assert_series_equal(result, expected)
result = a | Series([1], ["z"]) expected = Series([True, True, False, False], list("abcz")) tm.assert_series_equal(result, expected)
# identity # we would like s[s|e] == s to hold for any e, whether empty or not for e in [ empty.copy(), Series([1], ["z"]), Series(np.nan, b.index), Series(np.nan, a.index), ]: result = a[a | e] tm.assert_series_equal(result, a[a])
for e in [Series(["z"])]: if using_infer_string: # TODO(infer_string) should this behave differently? # -> https://github.com/pandas-dev/pandas/issues/60234 with pytest.raises( TypeError, match="not supported for dtype|unsupported operand type" ): result = a[a | e] else: result = a[a | e] tm.assert_series_equal(result, a[a])
# vs scalars index = list("bca") t = Series([True, False, True])
for v in [True, 1, 2]: result = Series([True, False, True], index=index) | v expected = Series([True, True, True], index=index) tm.assert_series_equal(result, expected)
msg = "Cannot perform.+with a dtyped.+array and scalar of type" for v in [np.nan, "foo"]: with pytest.raises(TypeError, match=msg): t | v
for v in [False, 0]: result = Series([True, False, True], index=index) | v expected = Series([True, False, True], index=index) tm.assert_series_equal(result, expected)
for v in [True, 1]: result = Series([True, False, True], index=index) & v expected = Series([True, False, True], index=index) tm.assert_series_equal(result, expected)
for v in [False, 0]: result = Series([True, False, True], index=index) & v expected = Series([False, False, False], index=index) tm.assert_series_equal(result, expected) msg = "Cannot perform.+with a dtyped.+array and scalar of type" for v in [np.nan]: with pytest.raises(TypeError, match=msg): t & v
def test_logical_ops_df_compat(self): # GH#1134 s1 = Series([True, False, True], index=list("ABC"), name="x") s2 = Series([True, True, False], index=list("ABD"), name="x")
exp = Series([True, False, False, False], index=list("ABCD"), name="x") tm.assert_series_equal(s1 & s2, exp) tm.assert_series_equal(s2 & s1, exp)
# True | np.nan => True exp_or1 = Series([True, True, True, False], index=list("ABCD"), name="x") tm.assert_series_equal(s1 | s2, exp_or1) # np.nan | True => np.nan, filled with False exp_or = Series([True, True, False, False], index=list("ABCD"), name="x") tm.assert_series_equal(s2 | s1, exp_or)
# DataFrame doesn't fill nan with False tm.assert_frame_equal(s1.to_frame() & s2.to_frame(), exp.to_frame()) tm.assert_frame_equal(s2.to_frame() & s1.to_frame(), exp.to_frame())
exp = DataFrame({"x": [True, True, np.nan, np.nan]}, index=list("ABCD")) tm.assert_frame_equal(s1.to_frame() | s2.to_frame(), exp_or1.to_frame()) tm.assert_frame_equal(s2.to_frame() | s1.to_frame(), exp_or.to_frame())
# different length s3 = Series([True, False, True], index=list("ABC"), name="x") s4 = Series([True, True, True, True], index=list("ABCD"), name="x")
exp = Series([True, False, True, False], index=list("ABCD"), name="x") tm.assert_series_equal(s3 & s4, exp) tm.assert_series_equal(s4 & s3, exp)
# np.nan | True => np.nan, filled with False exp_or1 = Series([True, True, True, False], index=list("ABCD"), name="x") tm.assert_series_equal(s3 | s4, exp_or1) # True | np.nan => True exp_or = Series([True, True, True, True], index=list("ABCD"), name="x") tm.assert_series_equal(s4 | s3, exp_or)
tm.assert_frame_equal(s3.to_frame() & s4.to_frame(), exp.to_frame()) tm.assert_frame_equal(s4.to_frame() & s3.to_frame(), exp.to_frame())
tm.assert_frame_equal(s3.to_frame() | s4.to_frame(), exp_or1.to_frame()) tm.assert_frame_equal(s4.to_frame() | s3.to_frame(), exp_or.to_frame())
def test_int_dtype_different_index_not_bool(self): # GH 52500 ser1 = Series([1, 2, 3], index=[10, 11, 23], name="a") ser2 = Series([10, 20, 30], index=[11, 10, 23], name="a") result = np.bitwise_xor(ser1, ser2) expected = Series([21, 8, 29], index=[10, 11, 23], name="a") tm.assert_series_equal(result, expected)
result = ser1 ^ ser2 tm.assert_series_equal(result, expected)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788from datetime import timedelta
import numpy as npimport pytest
from pandas._libs import iNaT
import pandas as pdfrom pandas import ( Categorical, Index, NaT, Series, isna,)import pandas._testing as tm
class TestSeriesMissingData: def test_categorical_nan_handling(self): # NaNs are represented as -1 in labels s = Series(Categorical(["a", "b", np.nan, "a"])) tm.assert_index_equal(s.cat.categories, Index(["a", "b"])) tm.assert_numpy_array_equal( s.values.codes, np.array([0, 1, -1, 0], dtype=np.int8) )
def test_timedelta64_nan(self): td = Series([timedelta(days=i) for i in range(10)])
# nan ops on timedeltas td1 = td.copy() td1[0] = np.nan assert isna(td1[0]) assert td1[0]._value == iNaT td1[0] = td[0] assert not isna(td1[0])
# GH#16674 iNaT is treated as an integer when given by the user with pytest.raises(TypeError, match="Invalid value"): td1[1] = iNaT
td1[2] = NaT assert isna(td1[2]) assert td1[2]._value == iNaT td1[2] = td[2] assert not isna(td1[2])
# boolean setting # GH#2899 boolean setting td3 = np.timedelta64(timedelta(days=3)) td7 = np.timedelta64(timedelta(days=7)) td[(td > td3) & (td < td7)] = np.nan assert isna(td).sum() == 3
@pytest.mark.xfail( reason="Chained inequality raises when trying to define 'selector'" ) def test_logical_range_select(self, datetime_series): # NumPy limitation =( # https://github.com/pandas-dev/pandas/commit/9030dc021f07c76809848925cb34828f6c8484f3
selector = -0.5 <= datetime_series <= 0.5 expected = (datetime_series >= -0.5) & (datetime_series <= 0.5) tm.assert_series_equal(selector, expected)
def test_valid(self, datetime_series): ts = datetime_series.copy() ts.index = ts.index._with_freq(None) ts[::2] = np.nan
result = ts.dropna() assert len(result) == ts.count() tm.assert_series_equal(result, ts[1::2]) tm.assert_series_equal(result, ts[pd.notna(ts)])
def test_hasnans_uncached_for_series(): # GH#19700 # set float64 dtype to avoid upcast when setting nan idx = Index([0, 1], dtype="float64") assert idx.hasnans is False assert "hasnans" in idx._cache ser = idx.to_series() assert ser.hasnans is False assert not hasattr(ser, "_cache") ser.iloc[-1] = np.nan assert ser.hasnans is True12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Tests for np.foo applied to Series, not necessarily ufuncs."""
import numpy as npimport pytest
import pandas.util._test_decorators as td
from pandas import Seriesimport pandas._testing as tm
class TestPtp: def test_ptp(self): # GH#21614 N = 1000 arr = np.random.default_rng(2).standard_normal(N) ser = Series(arr) assert np.ptp(ser) == np.ptp(arr)
def test_numpy_unique(datetime_series): # it works! np.unique(datetime_series)
@pytest.mark.parametrize("index", [["a", "b", "c", "d", "e"], None])def test_numpy_argwhere(index): # GH#35331
s = Series(range(5), index=index, dtype=np.int64)
result = np.argwhere(s > 2).astype(np.int64) expected = np.array([[3], [4]], dtype=np.int64)
tm.assert_numpy_array_equal(result, expected)
@td.skip_if_no("pyarrow")def test_log_arrow_backed_missing_value(using_nan_is_na): # GH#56285 ser = Series([1, 2, None], dtype="float64[pyarrow]") if using_nan_is_na: result = np.log(ser) expected = np.log(Series([1, 2, None], dtype="float64[pyarrow]")) tm.assert_series_equal(result, expected) else: # we get cast to object which raises msg = "loop of ufunc does not support argument" with pytest.raises(TypeError, match=msg): np.log(ser)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233import numpy as npimport pytest
import pandas as pdfrom pandas import Seriesimport pandas._testing as tm
@pytest.mark.parametrize("operation, expected", [("min", "a"), ("max", "b")])def test_reductions_series_strings(operation, expected): # GH#31746 ser = Series(["a", "b"], dtype="string") res_operation_serie = getattr(ser, operation)() assert res_operation_serie == expected
@pytest.mark.parametrize("as_period", [True, False])def test_mode_extension_dtype(as_period): # GH#41927 preserve dt64tz dtype ser = Series([pd.Timestamp(1979, 4, n) for n in range(1, 5)])
if as_period: ser = ser.dt.to_period("D") else: ser = ser.dt.tz_localize("US/Central")
res = ser.mode() assert res.dtype == ser.dtype tm.assert_series_equal(res, ser)
def test_mode_nullable_dtype(any_numeric_ea_dtype): # GH#55340 ser = Series([1, 3, 2, pd.NA, 3, 2, pd.NA], dtype=any_numeric_ea_dtype) result = ser.mode(dropna=False) expected = Series([2, 3, pd.NA], dtype=any_numeric_ea_dtype) tm.assert_series_equal(result, expected)
result = ser.mode(dropna=True) expected = Series([2, 3], dtype=any_numeric_ea_dtype) tm.assert_series_equal(result, expected)
ser[-1] = pd.NA
result = ser.mode(dropna=True) expected = Series([2, 3], dtype=any_numeric_ea_dtype) tm.assert_series_equal(result, expected)
result = ser.mode(dropna=False) expected = Series([pd.NA], dtype=any_numeric_ea_dtype) tm.assert_series_equal(result, expected)
def test_mode_nullable_dtype_edge_case(any_numeric_ea_dtype): # GH##58926 ser = Series([1, 2, 3, 1], dtype=any_numeric_ea_dtype) result = ser.mode(dropna=False) expected = Series([1], dtype=any_numeric_ea_dtype) tm.assert_series_equal(result, expected)
ser2 = Series([1, 1, 2, 3, pd.NA], dtype=any_numeric_ea_dtype) result = ser2.mode(dropna=False) expected = Series([1], dtype=any_numeric_ea_dtype) tm.assert_series_equal(result, expected)
ser3 = Series([1, pd.NA, pd.NA], dtype=any_numeric_ea_dtype) result = ser3.mode(dropna=False) expected = Series([pd.NA], dtype=any_numeric_ea_dtype) tm.assert_series_equal(result, expected)
ser4 = Series([1, 1, pd.NA, pd.NA], dtype=any_numeric_ea_dtype) result = ser4.mode(dropna=False) expected = Series([1, pd.NA], dtype=any_numeric_ea_dtype) tm.assert_series_equal(result, expected)
def test_mode_infer_string(): # GH#56183 pytest.importorskip("pyarrow") ser = Series(["a", "b"], dtype=object) with pd.option_context("future.infer_string", True): result = ser.mode() expected = Series(["a", "b"], dtype=object) tm.assert_series_equal(result, expected)
def test_reductions_td64_with_nat(): # GH#8617 ser = Series([0, pd.NaT], dtype="m8[ns]") exp = ser[0] assert ser.median() == exp assert ser.min() == exp assert ser.max() == exp
def test_td64_sum_empty(skipna): # GH#37151 ser = Series([], dtype="timedelta64[ns]")
result = ser.sum(skipna=skipna) assert isinstance(result, pd.Timedelta) assert result == pd.Timedelta(0)
def test_td64_summation_overflow(): # GH#9442 ser = Series(pd.date_range("20130101", periods=100000, freq="h", unit="ns")) ser[0] += pd.Timedelta("1s 1ms")
# mean result = (ser - ser.min()).mean() expected = pd.Timedelta((pd.TimedeltaIndex(ser - ser.min()).asi8 / len(ser)).sum())
# the computation is converted to float so # might be some loss of precision assert np.allclose(result._value / 1000, expected._value / 1000)
# sum msg = "overflow in timedelta operation" with pytest.raises(ValueError, match=msg): (ser - ser.min()).sum()
s1 = ser[0:10000] with pytest.raises(ValueError, match=msg): (s1 - s1.min()).sum() s2 = ser[0:1000] (s2 - s2.min()).sum()
def test_prod_numpy16_bug(): ser = Series([1.0, 1.0, 1.0], index=range(3)) result = ser.prod()
assert not isinstance(result, Series)
@pytest.mark.parametrize("func", [np.any, np.all])@pytest.mark.parametrize("kwargs", [{"keepdims": True}, {"out": object()}])def test_validate_any_all_out_keepdims_raises(kwargs, func): ser = Series([1, 2]) param = next(iter(kwargs)) name = func.__name__
msg = ( f"the '{param}' parameter is not " "supported in the pandas " rf"implementation of {name}\(\)" ) with pytest.raises(ValueError, match=msg): func(ser, **kwargs)
def test_validate_sum_initial(): ser = Series([1, 2]) msg = ( r"the 'initial' parameter is not " r"supported in the pandas " r"implementation of sum\(\)" ) with pytest.raises(ValueError, match=msg): np.sum(ser, initial=10)
def test_validate_median_initial(): ser = Series([1, 2]) msg = ( r"the 'overwrite_input' parameter is not " r"supported in the pandas " r"implementation of median\(\)" ) with pytest.raises(ValueError, match=msg): # It seems like np.median doesn't dispatch, so we use the # method instead of the ufunc. ser.median(overwrite_input=True)
def test_validate_stat_keepdims(): ser = Series([1, 2]) msg = ( r"the 'keepdims' parameter is not " r"supported in the pandas " r"implementation of sum\(\)" ) with pytest.raises(ValueError, match=msg): np.sum(ser, keepdims=True)
def test_mean_with_convertible_string_raises(): # GH#44008 ser = Series(["1", "2"]) assert ser.sum() == "12"
msg = "Could not convert string '12' to numeric|does not support|Cannot perform" with pytest.raises(TypeError, match=msg): ser.mean()
df = ser.to_frame() msg = r"Could not convert \['12'\] to numeric|does not support|Cannot perform" with pytest.raises(TypeError, match=msg): df.mean()
def test_mean_dont_convert_j_to_complex(): # GH#36703 df = pd.DataFrame([{"db": "J", "numeric": 123}]) msg = r"Could not convert \['J'\] to numeric|does not support|Cannot perform" with pytest.raises(TypeError, match=msg): df.mean()
with pytest.raises(TypeError, match=msg): df.agg("mean")
msg = "Could not convert string 'J' to numeric|does not support|Cannot perform" with pytest.raises(TypeError, match=msg): df["db"].mean() msg = "Could not convert string 'J' to numeric|ufunc 'divide'|Cannot perform" with pytest.raises(TypeError, match=msg): np.mean(df["db"].astype("string").array)
def test_median_with_convertible_string_raises(): # GH#34671 this _could_ return a string "2", but definitely not float 2.0 msg = r"Cannot convert \['1' '2' '3'\] to numeric|does not support|Cannot perform" ser = Series(["1", "2", "3"]) with pytest.raises(TypeError, match=msg): ser.median()
msg = ( r"Cannot convert \[\['1' '2' '3'\]\] to numeric|does not support|Cannot perform" ) df = ser.to_frame() with pytest.raises(TypeError, match=msg): df.median()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import numpy as npimport pytest
import pandas as pdimport pandas._testing as tm
pytestmark = pytest.mark.filterwarnings( "ignore:Passing a BlockManager|Passing a SingleBlockManager:DeprecationWarning")
class TestSeriesSubclassing: @pytest.mark.parametrize( "idx_method, indexer, exp_data, exp_idx", [ ["loc", ["a", "b"], [1, 2], "ab"], ["iloc", [2, 3], [3, 4], "cd"], ], ) def test_indexing_sliced(self, idx_method, indexer, exp_data, exp_idx): s = tm.SubclassedSeries([1, 2, 3, 4], index=list("abcd")) res = getattr(s, idx_method)[indexer] exp = tm.SubclassedSeries(exp_data, index=list(exp_idx)) tm.assert_series_equal(res, exp)
def test_to_frame(self): s = tm.SubclassedSeries([1, 2, 3, 4], index=list("abcd"), name="xxx") res = s.to_frame() exp = tm.SubclassedDataFrame({"xxx": [1, 2, 3, 4]}, index=list("abcd")) tm.assert_frame_equal(res, exp)
def test_subclass_unstack(self): # GH 15564 s = tm.SubclassedSeries([1, 2, 3, 4], index=[list("aabb"), list("xyxy")])
res = s.unstack() exp = tm.SubclassedDataFrame({"x": [1, 3], "y": [2, 4]}, index=["a", "b"])
tm.assert_frame_equal(res, exp)
def test_subclass_empty_repr(self): sub_series = tm.SubclassedSeries() assert "SubclassedSeries" in repr(sub_series)
def test_asof(self): N = 3 rng = pd.date_range("1/1/1990", periods=N, freq="53s") s = tm.SubclassedSeries({"A": [np.nan, np.nan, np.nan]}, index=rng)
result = s.asof(rng[-2:]) assert isinstance(result, tm.SubclassedSeries)
def test_explode(self): s = tm.SubclassedSeries([[1, 2, 3], "foo", [], [3, 4]]) result = s.explode() assert isinstance(result, tm.SubclassedSeries)
def test_equals(self): # https://github.com/pandas-dev/pandas/pull/34402 # allow subclass in both directions s1 = pd.Series([1, 2, 3]) s2 = tm.SubclassedSeries([1, 2, 3]) assert s1.equals(s2) assert s2.equals(s1)
class SubclassedSeries(pd.Series): @property def _constructor(self): def _new(*args, **kwargs): # some constructor logic that accesses the Series' name if self.name == "test": return pd.Series(*args, **kwargs) return SubclassedSeries(*args, **kwargs)
return _new
def test_constructor_from_dict(): # https://github.com/pandas-dev/pandas/issues/52445 result = SubclassedSeries({"a": 1, "b": 2, "c": 3}) assert isinstance(result, SubclassedSeries)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475from collections import dequeimport reimport string
import numpy as npimport pytest
import pandas as pdimport pandas._testing as tmfrom pandas.arrays import SparseArray
@pytest.fixture(params=[np.add, np.logaddexp])def ufunc(request): # dunder op return request.param
@pytest.fixture( params=[pytest.param(True, marks=pytest.mark.fails_arm_wheels), False], ids=["sparse", "dense"],)def sparse(request): return request.param
@pytest.fixturedef arrays_for_binary_ufunc(): """ A pair of random, length-100 integer-dtype arrays, that are mostly 0. """ a1 = np.random.default_rng(2).integers(0, 10, 100, dtype="int64") a2 = np.random.default_rng(2).integers(0, 10, 100, dtype="int64") a1[::3] = 0 a2[::4] = 0 return a1, a2
@pytest.mark.parametrize("ufunc", [np.positive, np.floor, np.exp])def test_unary_ufunc(ufunc, sparse): # Test that ufunc(pd.Series) == pd.Series(ufunc) arr = np.random.default_rng(2).integers(0, 10, 10, dtype="int64") arr[::2] = 0 if sparse: arr = SparseArray(arr, dtype=pd.SparseDtype("int64", 0))
index = list(string.ascii_letters[:10]) name = "name" series = pd.Series(arr, index=index, name=name)
result = ufunc(series) expected = pd.Series(ufunc(arr), index=index, name=name) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("flip", [True, False], ids=["flipped", "straight"])def test_binary_ufunc_with_array(flip, sparse, ufunc, arrays_for_binary_ufunc): # Test that ufunc(pd.Series(a), array) == pd.Series(ufunc(a, b)) a1, a2 = arrays_for_binary_ufunc if sparse: a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0)) a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
name = "name" # op(pd.Series, array) preserves the name. series = pd.Series(a1, name=name) other = a2
array_args = (a1, a2) series_args = (series, other) # ufunc(series, array)
if flip: array_args = reversed(array_args) series_args = reversed(series_args) # ufunc(array, series)
expected = pd.Series(ufunc(*array_args), name=name) result = ufunc(*series_args) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("flip", [True, False], ids=["flipped", "straight"])def test_binary_ufunc_with_index(flip, sparse, ufunc, arrays_for_binary_ufunc): # Test that # * func(pd.Series(a), pd.Series(b)) == pd.Series(ufunc(a, b)) # * ufunc(Index, pd.Series) dispatches to pd.Series (returns a pd.Series) a1, a2 = arrays_for_binary_ufunc if sparse: a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0)) a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
name = "name" # op(pd.Series, array) preserves the name. series = pd.Series(a1, name=name)
other = pd.Index(a2, name=name).astype("int64")
array_args = (a1, a2) series_args = (series, other) # ufunc(series, array)
if flip: array_args = reversed(array_args) series_args = reversed(series_args) # ufunc(array, series)
expected = pd.Series(ufunc(*array_args), name=name) result = ufunc(*series_args) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("shuffle", [True, False], ids=["unaligned", "aligned"])@pytest.mark.parametrize("flip", [True, False], ids=["flipped", "straight"])def test_binary_ufunc_with_series( flip, shuffle, sparse, ufunc, arrays_for_binary_ufunc): # Test that # * func(pd.Series(a), pd.Series(b)) == pd.Series(ufunc(a, b)) # with alignment between the indices a1, a2 = arrays_for_binary_ufunc if sparse: a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0)) a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
name = "name" # op(pd.Series, array) preserves the name. series = pd.Series(a1, name=name) other = pd.Series(a2, name=name)
idx = np.random.default_rng(2).permutation(len(a1))
if shuffle: other = other.take(idx) if flip: index = other.align(series)[0].index else: index = series.align(other)[0].index else: index = series.index
array_args = (a1, a2) series_args = (series, other) # ufunc(series, array)
if flip: array_args = tuple(reversed(array_args)) series_args = tuple(reversed(series_args)) # ufunc(array, series)
expected = pd.Series(ufunc(*array_args), index=index, name=name) result = ufunc(*series_args) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("flip", [True, False])def test_binary_ufunc_scalar(ufunc, sparse, flip, arrays_for_binary_ufunc): # Test that # * ufunc(pd.Series, scalar) == pd.Series(ufunc(array, scalar)) # * ufunc(pd.Series, scalar) == ufunc(scalar, pd.Series) arr, _ = arrays_for_binary_ufunc if sparse: arr = SparseArray(arr) other = 2 series = pd.Series(arr, name="name")
series_args = (series, other) array_args = (arr, other)
if flip: series_args = tuple(reversed(series_args)) array_args = tuple(reversed(array_args))
expected = pd.Series(ufunc(*array_args), name="name") result = ufunc(*series_args)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("ufunc", [np.divmod]) # TODO: np.modf, np.frexp@pytest.mark.parametrize("shuffle", [True, False])@pytest.mark.filterwarnings("ignore:divide by zero:RuntimeWarning")def test_multiple_output_binary_ufuncs(ufunc, sparse, shuffle, arrays_for_binary_ufunc): # Test that # the same conditions from binary_ufunc_scalar apply to # ufuncs with multiple outputs.
a1, a2 = arrays_for_binary_ufunc # work around https://github.com/pandas-dev/pandas/issues/26987 a1[a1 == 0] = 1 a2[a2 == 0] = 1
if sparse: a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0)) a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
s1 = pd.Series(a1) s2 = pd.Series(a2)
if shuffle: # ensure we align before applying the ufunc s2 = s2.sample(frac=1)
expected = ufunc(a1, a2) assert isinstance(expected, tuple)
result = ufunc(s1, s2) assert isinstance(result, tuple) tm.assert_series_equal(result[0], pd.Series(expected[0])) tm.assert_series_equal(result[1], pd.Series(expected[1]))
def test_multiple_output_ufunc(sparse, arrays_for_binary_ufunc): # Test that the same conditions from unary input apply to multi-output # ufuncs arr, _ = arrays_for_binary_ufunc
if sparse: arr = SparseArray(arr)
series = pd.Series(arr, name="name") result = np.modf(series) expected = np.modf(arr)
assert isinstance(result, tuple) assert isinstance(expected, tuple)
tm.assert_series_equal(result[0], pd.Series(expected[0], name="name")) tm.assert_series_equal(result[1], pd.Series(expected[1], name="name"))
def test_binary_ufunc_drops_series_name(ufunc, sparse, arrays_for_binary_ufunc): # Drop the names when they differ. a1, a2 = arrays_for_binary_ufunc s1 = pd.Series(a1, name="a") s2 = pd.Series(a2, name="b")
result = ufunc(s1, s2) assert result.name is None
def test_object_series_ok(): class Dummy: def __init__(self, value) -> None: self.value = value
def __add__(self, other): return self.value + other.value
arr = np.array([Dummy(0), Dummy(1)]) ser = pd.Series(arr) tm.assert_series_equal(np.add(ser, ser), pd.Series(np.add(ser, arr))) tm.assert_series_equal(np.add(ser, Dummy(1)), pd.Series(np.add(ser, Dummy(1))))
@pytest.fixture( params=[ pd.array([1, 3, 2], dtype=np.int64), pd.array([1, 3, 2], dtype="Int64"), pd.array([1, 3, 2], dtype="Float32"), pd.array([1, 10, 2], dtype="Sparse[int]"), pd.to_datetime(["2000", "2010", "2001"]), pd.to_datetime(["2000", "2010", "2001"]).tz_localize("CET"), pd.to_datetime(["2000", "2010", "2001"]).to_period(freq="D"), pd.to_timedelta(["1 Day", "3 Days", "2 Days"]), pd.IntervalIndex([pd.Interval(0, 1), pd.Interval(2, 3), pd.Interval(1, 2)]), ], ids=lambda x: str(x.dtype),)def values_for_np_reduce(request): # min/max tests assume that these are monotonic increasing return request.param
class TestNumpyReductions: # TODO: cases with NAs, axis kwarg for DataFrame
def test_multiply(self, values_for_np_reduce, box_with_array, request): box = box_with_array values = values_for_np_reduce
with tm.assert_produces_warning(None): obj = box(values)
if isinstance(values, pd.core.arrays.SparseArray): mark = pytest.mark.xfail(reason="SparseArray has no 'prod'") request.applymarker(mark)
if values.dtype.kind in "iuf": result = np.multiply.reduce(obj) if box is pd.DataFrame: expected = obj.prod(numeric_only=False) tm.assert_series_equal(result, expected) elif box is pd.Index: # Index has no 'prod' expected = obj._values.prod() assert result == expected else: expected = obj.prod() assert result == expected else: msg = "|".join( [ "does not support operation", "unsupported operand type", "ufunc 'multiply' cannot use operands", ] ) with pytest.raises(TypeError, match=msg): np.multiply.reduce(obj)
def test_add(self, values_for_np_reduce, box_with_array): box = box_with_array values = values_for_np_reduce
with tm.assert_produces_warning(None): obj = box(values)
if values.dtype.kind in "miuf": result = np.add.reduce(obj) if box is pd.DataFrame: expected = obj.sum(numeric_only=False) tm.assert_series_equal(result, expected) elif box is pd.Index: # Index has no 'sum' expected = obj._values.sum() assert result == expected else: expected = obj.sum() assert result == expected else: msg = "|".join( [ "does not support operation", "unsupported operand type", "ufunc 'add' cannot use operands", ] ) with pytest.raises(TypeError, match=msg): np.add.reduce(obj)
def test_max(self, values_for_np_reduce, box_with_array, using_python_scalars): box = box_with_array values = values_for_np_reduce
same_type = True if box is pd.Index and values.dtype.kind in "if": # ATM Index casts to object, so we get python ints/floats same_type = False
with tm.assert_produces_warning(None): obj = box(values)
result = np.maximum.reduce(obj) if box is pd.DataFrame: # TODO: cases with axis kwarg expected = obj.max(numeric_only=False) tm.assert_series_equal(result, expected) else: expected = values[1] if using_python_scalars and values.dtype.kind in "if": expected = expected.item() assert result == expected if same_type: # check we have e.g. Timestamp instead of dt64 assert type(result) == type(expected)
def test_min(self, values_for_np_reduce, box_with_array, using_python_scalars): box = box_with_array values = values_for_np_reduce
same_type = True if box is pd.Index and values.dtype.kind in "if": # ATM Index casts to object, so we get python ints/floats same_type = False
with tm.assert_produces_warning(None): obj = box(values)
result = np.minimum.reduce(obj) if box is pd.DataFrame: expected = obj.min(numeric_only=False) tm.assert_series_equal(result, expected) else: expected = values[0] if using_python_scalars and values.dtype.kind in ["i", "f"]: expected = expected.item() assert result == expected if same_type: # check we have e.g. Timestamp instead of dt64 assert type(result) == type(expected)
@pytest.mark.parametrize("type_", [list, deque, tuple])def test_binary_ufunc_other_types(type_): a = pd.Series([1, 2, 3], name="name") b = type_([3, 4, 5])
result = np.add(a, b) expected = pd.Series(np.add(a.to_numpy(), b), name="name") tm.assert_series_equal(result, expected)
def test_object_dtype_ok(): class Thing: def __init__(self, value) -> None: self.value = value
def __add__(self, other): other = getattr(other, "value", other) return type(self)(self.value + other)
def __eq__(self, other) -> bool: return type(other) is Thing and self.value == other.value
def __repr__(self) -> str: return f"Thing({self.value})"
s = pd.Series([Thing(1), Thing(2)]) result = np.add(s, Thing(1)) expected = pd.Series([Thing(2), Thing(3)]) tm.assert_series_equal(result, expected)
def test_outer(): # https://github.com/pandas-dev/pandas/issues/27186 ser = pd.Series([1, 2, 3]) obj = np.array([1, 2, 3])
with pytest.raises(NotImplementedError, match="^$"): np.subtract.outer(ser, obj)
def test_np_matmul(): # GH26650 df1 = pd.DataFrame(data=[[-1, 1, 10]]) df2 = pd.DataFrame(data=[-1, 1, 10]) expected = pd.DataFrame(data=[102])
result = np.matmul(df1, df2) tm.assert_frame_equal(expected, result)
@pytest.mark.parametrize("box", [pd.Index, pd.Series])def test_np_matmul_1D(box, using_python_scalars): result = np.matmul(box([1, 2]), box([2, 3])) assert result == 8 if using_python_scalars: assert type(result) == int, type(result) else: assert type(result) == np.int64, type(result)
def test_array_ufuncs_for_many_arguments(): # GH39853 def add3(x, y, z): return x + y + z
ufunc = np.frompyfunc(add3, 3, 1) ser = pd.Series([1, 2])
result = ufunc(ser, ser, 1) expected = pd.Series([3, 5], dtype=object) tm.assert_series_equal(result, expected)
df = pd.DataFrame([[1, 2]])
msg = ( "Cannot apply ufunc <ufunc 'add3 (vectorized)'> " "to mixed DataFrame and Series inputs." ) with pytest.raises(NotImplementedError, match=re.escape(msg)): ufunc(ser, ser, df)
def test_np_trunc(): # This used to test np.fix, which is not a ufunc but is composed of # several ufunc calls under the hood with `out` and `where` keywords. But numpy # is deprecating that (or at least discussing deprecating) in favor of np.trunc, # which _is_ a ufunc without the out keyword usage. ser = pd.Series([-1.5, -0.5, 0.5, 1.5]) result = np.trunc(ser) expected = pd.Series([-1.0, -0.0, 0.0, 1.0]) tm.assert_series_equal(result, expected)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import pytest
from pandas import Seriesimport pandas._testing as tm
class TestSeriesUnaryOps: # __neg__, __pos__, __invert__
def test_neg(self): ser = Series(range(5), dtype="float64", name="series") tm.assert_series_equal(-ser, -1 * ser)
def test_invert(self): ser = Series(range(5), dtype="float64", name="series") tm.assert_series_equal(-(ser < 0), ~(ser < 0))
@pytest.mark.parametrize( "source, neg_target, abs_target", [ ([1, 2, 3], [-1, -2, -3], [1, 2, 3]), ([1, 2, None], [-1, -2, None], [1, 2, None]), ], ) def test_all_numeric_unary_operators( self, any_numeric_ea_dtype, source, neg_target, abs_target ): # GH38794 dtype = any_numeric_ea_dtype ser = Series(source, dtype=dtype) neg_result, pos_result, abs_result = -ser, +ser, abs(ser) if dtype.startswith("U"): neg_target = -Series(source, dtype=dtype) else: neg_target = Series(neg_target, dtype=dtype)
abs_target = Series(abs_target, dtype=dtype)
tm.assert_series_equal(neg_result, neg_target) tm.assert_series_equal(pos_result, ser) tm.assert_series_equal(abs_result, abs_target)
@pytest.mark.parametrize("op", ["__neg__", "__abs__"]) def test_unary_float_op_mask(self, float_ea_dtype, op): dtype = float_ea_dtype ser = Series([1.1, 2.2, 3.3], dtype=dtype) result = getattr(ser, op)() target = result.copy(deep=True) ser[0] = None tm.assert_series_equal(result, target)1234567891011121314151617181920212223242526import pytest
@pytest.mark.parametrize( "func", [ "reset_index", "_set_name", "sort_values", "sort_index", "rename", "dropna", "drop_duplicates", ],)@pytest.mark.parametrize("inplace", [1, "True", [1, 2, 3], 5.0])def test_validate_bool_args(string_series, func, inplace): """Tests for error handling related to data types of method arguments.""" msg = 'For argument "inplace" expected type bool' kwargs = {"inplace": inplace}
if func == "_set_name": kwargs["name"] = "hello"
with pytest.raises(ValueError, match=msg): getattr(string_series, func)(**kwargs)1234567891011121314151617181920212223import numpy as np
import pandas as pd
def is_object_or_nan_string_dtype(dtype): """ Check if string-like dtype is following NaN semantics, i.e. is object dtype or a NaN-variant of the StringDtype. """ return (isinstance(dtype, np.dtype) and dtype == "object") or ( dtype.na_value is np.nan )
def _convert_na_value(ser, expected): if ser.dtype != object: if ser.dtype.na_value is np.nan: expected = expected.fillna(np.nan) else: # GH#18463 expected = expected.fillna(pd.NA) return expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import pytest
from pandas import Seriesfrom pandas.core.strings.accessor import StringMethods
_any_string_method = [ ("cat", (), {"sep": ","}), ("cat", (Series(list("zyx")),), {"sep": ",", "join": "left"}), ("center", (10,), {}), ("contains", ("a",), {}), ("count", ("a",), {}), ("decode", ("UTF-8",), {}), ("encode", ("UTF-8",), {}), ("endswith", ("a",), {}), ("endswith", ((),), {}), ("endswith", (("a",),), {}), ("endswith", (("a", "b"),), {}), ("endswith", (("a", "MISSING"),), {}), ("endswith", ("a",), {"na": True}), ("endswith", ("a",), {"na": False}), ("extract", ("([a-z]*)",), {"expand": False}), ("extract", ("([a-z]*)",), {"expand": True}), ("extractall", ("([a-z]*)",), {}), ("find", ("a",), {}), ("findall", ("a",), {}), ("get", (0,), {}), # because "index" (and "rindex") fail intentionally # if the string is not found, search only for empty string ("index", ("",), {}), ("join", (",",), {}), ("ljust", (10,), {}), ("match", ("a",), {}), ("fullmatch", ("a",), {}), ("normalize", ("NFC",), {}), ("pad", (10,), {}), ("partition", (" ",), {"expand": False}), ("partition", (" ",), {"expand": True}), ("repeat", (3,), {}), ("replace", ("a", "z"), {}), ("rfind", ("a",), {}), ("rindex", ("",), {}), ("rjust", (10,), {}), ("rpartition", (" ",), {"expand": False}), ("rpartition", (" ",), {"expand": True}), ("slice", (0, 1), {}), ("slice_replace", (0, 1, "z"), {}), ("split", (" ",), {"expand": False}), ("split", (" ",), {"expand": True}), ("startswith", ("a",), {}), ("startswith", (("a",),), {}), ("startswith", (("a", "b"),), {}), ("startswith", (("a", "MISSING"),), {}), ("startswith", ((),), {}), ("startswith", ("a",), {"na": True}), ("startswith", ("a",), {"na": False}), ("removeprefix", ("a",), {}), ("removesuffix", ("a",), {}), # translating unicode points of "a" to "d" ("translate", ({97: 100},), {}), ("wrap", (2,), {}), ("zfill", (10,), {}), # methods without positional arguments: zip with empty tuple and empty dict *zip( [ "capitalize", "cat", "get_dummies", "isalnum", "isalpha", "isascii", "isdecimal", "isdigit", "islower", "isnumeric", "isspace", "istitle", "isupper", "len", "lower", "lstrip", "partition", "rpartition", "rsplit", "rstrip", "slice", "slice_replace", "split", "strip", "swapcase", "title", "upper", "casefold", ], [()] * 100, [{}] * 100, ),]ids, _, _ = zip(*_any_string_method) # use method name as fixture-idmissing_methods = {f for f in dir(StringMethods) if not f.startswith("_")} - set(ids)
# test that the above list captures all methods of StringMethodsassert not missing_methods
@pytest.fixture(params=_any_string_method, ids=ids)def any_string_method(request): """ Fixture for all public methods of `StringMethods`
This fixture returns a tuple of the method name and sample arguments necessary to call the method.
Returns ------- method_name : str The name of the method in `StringMethods` args : tuple Sample values for the positional arguments kwargs : dict Sample values for the keyword arguments
Examples -------- >>> def test_something(any_string_method): ... s = Series(["a", "b", np.nan, "d"]) ... ... method_name, args, kwargs = any_string_method ... method = getattr(s.str, method_name) ... # will not raise ... method(*args, **kwargs) """ return request.param123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216import weakref
import numpy as npimport pytest
from pandas import ( CategoricalDtype, DataFrame, Index, MultiIndex, Series, _testing as tm,)from pandas.core.strings.accessor import StringMethods
# subset of the full set from pandas/conftest.py_any_allowed_skipna_inferred_dtype = [ ("string", ["a", np.nan, "c"]), ("bytes", [b"a", np.nan, b"c"]), ("empty", [np.nan, np.nan, np.nan]), ("empty", []), ("mixed-integer", ["a", np.nan, 2]),]ids, _ = zip( *_any_allowed_skipna_inferred_dtype, strict=True) # use inferred type as id
@pytest.fixture(params=_any_allowed_skipna_inferred_dtype, ids=ids)def any_allowed_skipna_inferred_dtype(request): """ Fixture for all (inferred) dtypes allowed in StringMethods.__init__
The covered (inferred) types are: * 'string' * 'empty' * 'bytes' * 'mixed' * 'mixed-integer'
Returns ------- inferred_dtype : str The string for the inferred dtype from _libs.lib.infer_dtype values : np.ndarray An array of object dtype that will be inferred to have `inferred_dtype`
Examples -------- >>> from pandas._libs import lib >>> >>> def test_something(any_allowed_skipna_inferred_dtype): ... inferred_dtype, values = any_allowed_skipna_inferred_dtype ... # will pass ... assert lib.infer_dtype(values, skipna=True) == inferred_dtype ... ... # constructor for .str-accessor will also pass ... Series(values).str """ inferred_dtype, values = request.param values = np.array(values, dtype=object) # object dtype to avoid casting
# correctness of inference tested in tests/dtypes/test_inference.py return inferred_dtype, values
def test_api(any_string_dtype): # GH 6106, GH 9322 assert Series.str is StringMethods assert isinstance(Series([""], dtype=any_string_dtype).str, StringMethods)
def test_no_circular_reference(any_string_dtype): # GH 47667 ser = Series([""], dtype=any_string_dtype) ref = weakref.ref(ser) ser.str # Used to cache and cause circular reference del ser assert ref() is None
def test_api_mi_raises(): # GH 23679 mi = MultiIndex.from_arrays([["a", "b", "c"]]) msg = "Can only use .str accessor with Index, not MultiIndex" with pytest.raises(AttributeError, match=msg): mi.str assert not hasattr(mi, "str")
@pytest.mark.parametrize("dtype", [object, "category"])def test_api_per_dtype(index_or_series, dtype, any_skipna_inferred_dtype): # one instance of parametrized fixture box = index_or_series inferred_dtype, values = any_skipna_inferred_dtype
t = box(values, dtype=dtype) # explicit dtype to avoid casting
types_passing_constructor = [ "string", "unicode", "empty", "bytes", "mixed", "mixed-integer", ] if inferred_dtype in types_passing_constructor: # GH 6106 assert isinstance(t.str, StringMethods) else: # GH 9184, GH 23011, GH 23163 msg = "Can only use .str accessor with string values.*" with pytest.raises(AttributeError, match=msg): t.str assert not hasattr(t, "str")
@pytest.mark.parametrize("dtype", [object, "category"])def test_api_per_method( index_or_series, dtype, any_allowed_skipna_inferred_dtype, any_string_method, request, using_infer_string,): # this test does not check correctness of the different methods, # just that the methods work on the specified (inferred) dtypes, # and raise on all others box = index_or_series
# one instance of each parametrized fixture inferred_dtype, values = any_allowed_skipna_inferred_dtype method_name, args, kwargs = any_string_method
reason = None if box is Index and values.size == 0: if method_name in ["partition", "rpartition"] and kwargs.get("expand", True): raises = TypeError reason = "Method cannot deal with empty Index" elif method_name == "split" and kwargs.get("expand", None): raises = TypeError reason = "Split fails on empty Series when expand=True" elif method_name == "get_dummies": raises = ValueError reason = "Need to fortify get_dummies corner cases"
elif ( box is Index and inferred_dtype == "empty" and dtype == object and method_name == "get_dummies" ): raises = ValueError reason = "Need to fortify get_dummies corner cases"
if reason is not None: mark = pytest.mark.xfail(raises=raises, reason=reason) request.applymarker(mark)
t = box(values, dtype=dtype) # explicit dtype to avoid casting method = getattr(t.str, method_name)
if using_infer_string and dtype == "category": string_allowed = method_name not in ["decode"] else: string_allowed = True bytes_allowed = method_name in ["decode", "get", "len", "slice"] # as of v0.23.4, all methods except 'cat' are very lenient with the # allowed data types, just returning NaN for entries that error. # This could be changed with an 'errors'-kwarg to the `str`-accessor, # see discussion in GH 13877 mixed_allowed = method_name not in ["cat"]
allowed_types = ( ["empty"] + ["string", "unicode"] * string_allowed + ["bytes"] * bytes_allowed + ["mixed", "mixed-integer"] * mixed_allowed )
if inferred_dtype in allowed_types: # xref GH 23555, GH 23556 method(*args, **kwargs) # works! else: # GH 23011, GH 23163 msg = ( f"Cannot use .str.{method_name} with values of " f"inferred dtype {inferred_dtype!r}." "|a bytes-like object is required, not 'str'" ) with pytest.raises(TypeError, match=msg): method(*args, **kwargs)
def test_api_for_categorical(any_string_method, any_string_dtype): # https://github.com/pandas-dev/pandas/issues/10661 s = Series(list("aabb"), dtype=any_string_dtype) s = s + " " + s c = s.astype("category") c = c.astype(CategoricalDtype(c.dtype.categories.astype("object"))) assert isinstance(c.str, StringMethods)
method_name, args, kwargs = any_string_method
result = getattr(c.str, method_name)(*args, **kwargs) expected = getattr(s.astype("object").str, method_name)(*args, **kwargs)
if isinstance(result, DataFrame): tm.assert_frame_equal(result, expected) elif isinstance(result, Series): tm.assert_series_equal(result, expected) else: # str.cat(others=None) returns string, for example assert result == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423from datetime import datetimeimport operator
import numpy as npimport pytest
from pandas import ( Series, _testing as tm,)
def test_title(any_string_dtype): s = Series(["FOO", "BAR", np.nan, "Blah", "blurg"], dtype=any_string_dtype) result = s.str.title() expected = Series(["Foo", "Bar", np.nan, "Blah", "Blurg"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_title_mixed_object(): s = Series(["FOO", np.nan, "bar", True, datetime.today(), "blah", None, 1, 2.0]) result = s.str.title() expected = Series( ["Foo", np.nan, "Bar", np.nan, np.nan, "Blah", None, np.nan, np.nan], dtype=object, ) tm.assert_almost_equal(result, expected)
def test_lower_upper(any_string_dtype): s = Series(["om", np.nan, "nom", "nom"], dtype=any_string_dtype)
result = s.str.upper() expected = Series(["OM", np.nan, "NOM", "NOM"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
result = result.str.lower() tm.assert_series_equal(result, s)
def test_lower_upper_mixed_object(): s = Series(["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0])
result = s.str.upper() expected = Series( ["A", np.nan, "B", np.nan, np.nan, "FOO", None, np.nan, np.nan], dtype=object ) tm.assert_series_equal(result, expected)
result = s.str.lower() expected = Series( ["a", np.nan, "b", np.nan, np.nan, "foo", None, np.nan, np.nan], dtype=object ) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "data, expected", [ ( ["FOO", "BAR", np.nan, "Blah", "blurg"], ["Foo", "Bar", np.nan, "Blah", "Blurg"], ), (["a", "b", "c"], ["A", "B", "C"]), (["a b", "a bc. de"], ["A b", "A bc. de"]), ],)def test_capitalize(data, expected, any_string_dtype): s = Series(data, dtype=any_string_dtype) result = s.str.capitalize() expected = Series(expected, dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_capitalize_mixed_object(): s = Series(["FOO", np.nan, "bar", True, datetime.today(), "blah", None, 1, 2.0]) result = s.str.capitalize() expected = Series( ["Foo", np.nan, "Bar", np.nan, np.nan, "Blah", None, np.nan, np.nan], dtype=object, ) tm.assert_series_equal(result, expected)
def test_swapcase(any_string_dtype): s = Series(["FOO", "BAR", np.nan, "Blah", "blurg"], dtype=any_string_dtype) result = s.str.swapcase() expected = Series(["foo", "bar", np.nan, "bLAH", "BLURG"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_swapcase_mixed_object(): s = Series(["FOO", np.nan, "bar", True, datetime.today(), "Blah", None, 1, 2.0]) result = s.str.swapcase() expected = Series( ["foo", np.nan, "BAR", np.nan, np.nan, "bLAH", None, np.nan, np.nan], dtype=object, ) tm.assert_series_equal(result, expected)
def test_casefold(): # GH25405 expected = Series(["ss", np.nan, "case", "ssd"]) s = Series(["ß", np.nan, "case", "ßd"]) result = s.str.casefold()
tm.assert_series_equal(result, expected)
def test_casemethods(any_string_dtype): values = ["aaa", "bbb", "CCC", "Dddd", "eEEE"] s = Series(values, dtype=any_string_dtype) assert s.str.lower().tolist() == [v.lower() for v in values] assert s.str.upper().tolist() == [v.upper() for v in values] assert s.str.title().tolist() == [v.title() for v in values] assert s.str.capitalize().tolist() == [v.capitalize() for v in values] assert s.str.swapcase().tolist() == [v.swapcase() for v in values]
def test_pad(any_string_dtype): s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
result = s.str.pad(5, side="left") expected = Series( [" a", " b", np.nan, " c", np.nan, "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
result = s.str.pad(5, side="right") expected = Series( ["a ", "b ", np.nan, "c ", np.nan, "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
result = s.str.pad(5, side="both") expected = Series( [" a ", " b ", np.nan, " c ", np.nan, "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
def test_pad_mixed_object(): s = Series(["a", np.nan, "b", True, datetime.today(), "ee", None, 1, 2.0])
result = s.str.pad(5, side="left") expected = Series( [" a", np.nan, " b", np.nan, np.nan, " ee", None, np.nan, np.nan], dtype=object, ) tm.assert_series_equal(result, expected)
result = s.str.pad(5, side="right") expected = Series( ["a ", np.nan, "b ", np.nan, np.nan, "ee ", None, np.nan, np.nan], dtype=object, ) tm.assert_series_equal(result, expected)
result = s.str.pad(5, side="both") expected = Series( [" a ", np.nan, " b ", np.nan, np.nan, " ee ", None, np.nan, np.nan], dtype=object, ) tm.assert_series_equal(result, expected)
def test_pad_fillchar(any_string_dtype): s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
result = s.str.pad(5, side="left", fillchar="X") expected = Series( ["XXXXa", "XXXXb", np.nan, "XXXXc", np.nan, "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
result = s.str.pad(5, side="right", fillchar="X") expected = Series( ["aXXXX", "bXXXX", np.nan, "cXXXX", np.nan, "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
result = s.str.pad(5, side="both", fillchar="X") expected = Series( ["XXaXX", "XXbXX", np.nan, "XXcXX", np.nan, "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
def test_pad_fillchar_bad_arg_raises(any_string_dtype): s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
msg = "fillchar must be a character, not str" with pytest.raises(TypeError, match=msg): s.str.pad(5, fillchar="XY")
msg = "fillchar must be a character, not int" with pytest.raises(TypeError, match=msg): s.str.pad(5, fillchar=5)
@pytest.mark.parametrize("method_name", ["center", "ljust", "rjust", "zfill", "pad"])def test_pad_width_bad_arg_raises(method_name, any_string_dtype): # see gh-13598 s = Series(["1", "22", "a", "bb"], dtype=any_string_dtype) op = operator.methodcaller(method_name, "f")
msg = "width must be of integer type, not str" with pytest.raises(TypeError, match=msg): op(s.str)
def test_center_ljust_rjust(any_string_dtype): s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
result = s.str.center(5) expected = Series( [" a ", " b ", np.nan, " c ", np.nan, "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
result = s.str.ljust(5) expected = Series( ["a ", "b ", np.nan, "c ", np.nan, "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
result = s.str.rjust(5) expected = Series( [" a", " b", np.nan, " c", np.nan, "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
def test_center_ljust_rjust_mixed_object(): s = Series(["a", np.nan, "b", True, datetime.today(), "c", "eee", None, 1, 2.0])
result = s.str.center(5) expected = Series( [ " a ", np.nan, " b ", np.nan, np.nan, " c ", " eee ", None, np.nan, np.nan, ], dtype=object, ) tm.assert_series_equal(result, expected)
result = s.str.ljust(5) expected = Series( [ "a ", np.nan, "b ", np.nan, np.nan, "c ", "eee ", None, np.nan, np.nan, ], dtype=object, ) tm.assert_series_equal(result, expected)
result = s.str.rjust(5) expected = Series( [ " a", np.nan, " b", np.nan, np.nan, " c", " eee", None, np.nan, np.nan, ], dtype=object, ) tm.assert_series_equal(result, expected)
def test_center_ljust_rjust_fillchar(any_string_dtype): # GH#54533, GH#54792 s = Series(["a", "bb", "cccc", "ddddd", "eeeeee"], dtype=any_string_dtype)
result = s.str.center(5, fillchar="X") expected = Series( ["XXaXX", "XXbbX", "Xcccc", "ddddd", "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected) expected = np.array([v.center(5, "X") for v in np.array(s)], dtype=np.object_) tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
result = s.str.ljust(5, fillchar="X") expected = Series( ["aXXXX", "bbXXX", "ccccX", "ddddd", "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected) expected = np.array([v.ljust(5, "X") for v in np.array(s)], dtype=np.object_) tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
result = s.str.rjust(5, fillchar="X") expected = Series( ["XXXXa", "XXXbb", "Xcccc", "ddddd", "eeeeee"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected) expected = np.array([v.rjust(5, "X") for v in np.array(s)], dtype=np.object_) tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
def test_center_ljust_rjust_fillchar_bad_arg_raises(any_string_dtype): s = Series(["a", "bb", "cccc", "ddddd", "eeeeee"], dtype=any_string_dtype)
# If fillchar is not a character, normal str raises TypeError # 'aaa'.ljust(5, 'XY') # TypeError: must be char, not str template = "fillchar must be a character, not {dtype}"
with pytest.raises(TypeError, match=template.format(dtype="str")): s.str.center(5, fillchar="XY")
with pytest.raises(TypeError, match=template.format(dtype="str")): s.str.ljust(5, fillchar="XY")
with pytest.raises(TypeError, match=template.format(dtype="str")): s.str.rjust(5, fillchar="XY")
with pytest.raises(TypeError, match=template.format(dtype="int")): s.str.center(5, fillchar=1)
with pytest.raises(TypeError, match=template.format(dtype="int")): s.str.ljust(5, fillchar=1)
with pytest.raises(TypeError, match=template.format(dtype="int")): s.str.rjust(5, fillchar=1)
def test_zfill(any_string_dtype): s = Series(["1", "22", "aaa", "333", "45678"], dtype=any_string_dtype)
result = s.str.zfill(5) expected = Series( ["00001", "00022", "00aaa", "00333", "45678"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected) expected = np.array([v.zfill(5) for v in np.array(s)], dtype=np.object_) tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
result = s.str.zfill(3) expected = Series(["001", "022", "aaa", "333", "45678"], dtype=any_string_dtype) tm.assert_series_equal(result, expected) expected = np.array([v.zfill(3) for v in np.array(s)], dtype=np.object_) tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
s = Series(["1", np.nan, "aaa", np.nan, "45678"], dtype=any_string_dtype) result = s.str.zfill(5) expected = Series( ["00001", np.nan, "00aaa", np.nan, "45678"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
def test_wrap(any_string_dtype): # test values are: two words less than width, two words equal to width, # two words greater than width, one word less than width, one word # equal to width, one word greater than width, multiple tokens with # trailing whitespace equal to width s = Series( [ "hello world", "hello world!", "hello world!!", "abcdefabcde", "abcdefabcdef", "abcdefabcdefa", "ab ab ab ab ", "ab ab ab ab a", "\t", ], dtype=any_string_dtype, )
# expected values expected = Series( [ "hello world", "hello world!", "hello\nworld!!", "abcdefabcde", "abcdefabcdef", "abcdefabcdef\na", "ab ab ab ab", "ab ab ab ab\na", "", ], dtype=any_string_dtype, )
result = s.str.wrap(12, break_long_words=True) tm.assert_series_equal(result, expected)
def test_wrap_unicode(any_string_dtype): # test with pre and post whitespace (non-unicode), NaN, and non-ascii Unicode s = Series( [" pre ", np.nan, "\xac\u20ac\U00008000 abadcafe"], dtype=any_string_dtype ) expected = Series( [" pre", np.nan, "\xac\u20ac\U00008000 ab\nadcafe"], dtype=any_string_dtype ) result = s.str.wrap(6) tm.assert_series_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444from datetime import datetimeimport re
import numpy as npimport pytest
import pandas.util._test_decorators as td
from pandas import ( DataFrame, Index, MultiIndex, Series, _testing as tm, concat, option_context,)
@pytest.fixturedef index_or_series2(index_or_series): return index_or_series
@pytest.mark.parametrize("other", [None, Series, Index])def test_str_cat_name(index_or_series, other): # GH 21053 box = index_or_series values = ["a", "b"] if other: other = other(values) else: other = values result = box(values, name="name").str.cat(other, sep=",") assert result.name == "name"
@pytest.mark.parametrize( "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))])def test_str_cat(index_or_series, infer_string): with option_context("future.infer_string", infer_string): box = index_or_series # test_cat above tests "str_cat" from ndarray; # here testing "str.cat" from Series/Index to ndarray/list s = box(["a", "a", "b", "b", "c", np.nan])
# single array result = s.str.cat() expected = "aabbc" assert result == expected
result = s.str.cat(na_rep="-") expected = "aabbc-" assert result == expected
result = s.str.cat(sep="_", na_rep="NA") expected = "a_a_b_b_c_NA" assert result == expected
t = np.array(["a", np.nan, "b", "d", "foo", np.nan], dtype=object) expected = box(["aa", "a-", "bb", "bd", "cfoo", "--"])
# Series/Index with array result = s.str.cat(t, na_rep="-") tm.assert_equal(result, expected)
# Series/Index with list result = s.str.cat(list(t), na_rep="-") tm.assert_equal(result, expected)
# errors for incorrect lengths rgx = r"If `others` contains arrays or lists \(or other list-likes.*" z = Series(["1", "2", "3"])
with pytest.raises(ValueError, match=rgx): s.str.cat(z.values)
with pytest.raises(ValueError, match=rgx): s.str.cat(list(z))
def test_str_cat_raises_intuitive_error(index_or_series): # GH 11334 box = index_or_series s = box(["a", "b", "c", "d"]) message = "Did you mean to supply a `sep` keyword?" with pytest.raises(ValueError, match=message): s.str.cat("|") with pytest.raises(ValueError, match=message): s.str.cat(" ")
@pytest.mark.parametrize( "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))])@pytest.mark.parametrize("sep", ["", None])@pytest.mark.parametrize("dtype_target", ["object", "category"])@pytest.mark.parametrize("dtype_caller", ["object", "category"])def test_str_cat_categorical( index_or_series, dtype_caller, dtype_target, sep, infer_string): box = index_or_series
with option_context("future.infer_string", infer_string): s = Index(["a", "a", "b", "a"], dtype=dtype_caller) s = s if box == Index else Series(s, index=s, dtype=s.dtype) t = Index(["b", "a", "b", "c"], dtype=dtype_target)
expected = Index( ["ab", "aa", "bb", "ac"], dtype=object if dtype_caller == "object" else None ) expected = ( expected if box == Index else Series( expected, index=Index(s, dtype=dtype_caller), dtype=expected.dtype ) )
# Series/Index with unaligned Index -> t.values result = s.str.cat(t.values, sep=sep) tm.assert_equal(result, expected)
# Series/Index with Series having matching Index t = Series(t.values, index=Index(s, dtype=dtype_caller)) result = s.str.cat(t, sep=sep) tm.assert_equal(result, expected)
# Series/Index with Series.values result = s.str.cat(t.values, sep=sep) tm.assert_equal(result, expected)
# Series/Index with Series having different Index t = Series(t.values, index=t.values) expected = Index( ["aa", "aa", "bb", "bb", "aa"], dtype=object if dtype_caller == "object" else None, ) dtype = object if dtype_caller == "object" else s.dtype.categories.dtype expected = ( expected if box == Index else Series( expected, index=Index(expected.str[:1], dtype=dtype), dtype=expected.dtype, ) )
result = s.str.cat(t, sep=sep) tm.assert_equal(result, expected)
@pytest.mark.parametrize( "data", [[1, 2, 3], [0.1, 0.2, 0.3], [1, 2, "b"]], ids=["integers", "floats", "mixed"],)# without dtype=object, np.array would cast [1, 2, 'b'] to ['1', '2', 'b']@pytest.mark.parametrize( "box", [Series, Index, list, lambda x: np.array(x, dtype=object)], ids=["Series", "Index", "list", "np.array"],)def test_str_cat_wrong_dtype_raises(box, data): # GH 22722 s = Series(["a", "b", "c"]) t = box(data)
msg = "Concatenation requires list-likes containing only strings.*" with pytest.raises(TypeError, match=msg): # need to use outer and na_rep, as otherwise Index would not raise s.str.cat(t, join="outer", na_rep="-")
def test_str_cat_mixed_inputs(index_or_series): box = index_or_series s = Index(["a", "b", "c", "d"]) s = s if box == Index else Series(s, index=s)
t = Series(["A", "B", "C", "D"], index=s.values) d = concat([t, Series(s, index=s)], axis=1)
expected = Index(["aAa", "bBb", "cCc", "dDd"]) expected = expected if box == Index else Series(expected.values, index=s.values)
# Series/Index with DataFrame result = s.str.cat(d) tm.assert_equal(result, expected)
# Series/Index with two-dimensional ndarray result = s.str.cat(d.values) tm.assert_equal(result, expected)
# Series/Index with list of Series result = s.str.cat([t, s]) tm.assert_equal(result, expected)
# Series/Index with mixed list of Series/array result = s.str.cat([t, s.values]) tm.assert_equal(result, expected)
# Series/Index with list of Series; different indexes t.index = ["b", "c", "d", "a"] expected = box(["aDa", "bAb", "cBc", "dCd"]) expected = expected if box == Index else Series(expected.values, index=s.values) result = s.str.cat([t, s]) tm.assert_equal(result, expected)
# Series/Index with mixed list; different index result = s.str.cat([t, s.values]) tm.assert_equal(result, expected)
# Series/Index with DataFrame; different indexes d.index = ["b", "c", "d", "a"] expected = box(["aDd", "bAa", "cBb", "dCc"]) expected = expected if box == Index else Series(expected.values, index=s.values) result = s.str.cat(d) tm.assert_equal(result, expected)
# errors for incorrect lengths rgx = r"If `others` contains arrays or lists \(or other list-likes.*" z = Series(["1", "2", "3"]) e = concat([z, z], axis=1)
# two-dimensional ndarray with pytest.raises(ValueError, match=rgx): s.str.cat(e.values)
# list of list-likes with pytest.raises(ValueError, match=rgx): s.str.cat([z.values, s.values])
# mixed list of Series/list-like with pytest.raises(ValueError, match=rgx): s.str.cat([z.values, s])
# errors for incorrect arguments in list-like rgx = "others must be Series, Index, DataFrame,.*" # make sure None/NaN do not crash checks in _get_series_list u = Series(["a", np.nan, "c", None])
# mix of string and Series with pytest.raises(TypeError, match=rgx): s.str.cat([u, "u"])
# DataFrame in list with pytest.raises(TypeError, match=rgx): s.str.cat([u, d])
# 2-dim ndarray in list with pytest.raises(TypeError, match=rgx): s.str.cat([u, d.values])
# nested lists with pytest.raises(TypeError, match=rgx): s.str.cat([u, [u, d]])
# forbidden input type: set # GH 23009 with pytest.raises(TypeError, match=rgx): s.str.cat(set(u))
# forbidden input type: set in list # GH 23009 with pytest.raises(TypeError, match=rgx): s.str.cat([u, set(u)])
# other forbidden input type, e.g. int with pytest.raises(TypeError, match=rgx): s.str.cat(1)
# nested list-likes with pytest.raises(TypeError, match=rgx): s.str.cat(iter([t.values, list(s)]))
def test_str_cat_align_indexed(index_or_series, join_type): # https://github.com/pandas-dev/pandas/issues/18657 box = index_or_series
s = Series(["a", "b", "c", "d"], index=["a", "b", "c", "d"]) t = Series(["D", "A", "E", "B"], index=["d", "a", "e", "b"]) sa, ta = s.align(t, join=join_type) # result after manual alignment of inputs expected = sa.str.cat(ta, na_rep="-")
if box == Index: s = Index(s) sa = Index(sa) expected = Index(expected)
result = s.str.cat(t, join=join_type, na_rep="-") tm.assert_equal(result, expected)
def test_str_cat_align_mixed_inputs(join_type): s = Series(["a", "b", "c", "d"]) t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1]) d = concat([t, t], axis=1)
expected_outer = Series(["aaa", "bbb", "c--", "ddd", "-ee"]) expected = expected_outer.loc[s.index.join(t.index, how=join_type)]
# list of Series result = s.str.cat([t, t], join=join_type, na_rep="-") tm.assert_series_equal(result, expected)
# DataFrame result = s.str.cat(d, join=join_type, na_rep="-") tm.assert_series_equal(result, expected)
# mixed list of indexed/unindexed u = np.array(["A", "B", "C", "D"]) expected_outer = Series(["aaA", "bbB", "c-C", "ddD", "-e-"]) # joint index of rhs [t, u]; u will be forced have index of s rhs_idx = ( t.index.intersection(s.index) if join_type == "inner" else t.index.union(s.index) if join_type == "outer" else t.index.append(s.index.difference(t.index)) )
expected = expected_outer.loc[s.index.join(rhs_idx, how=join_type)] result = s.str.cat([t, u], join=join_type, na_rep="-") tm.assert_series_equal(result, expected)
with pytest.raises(TypeError, match="others must be Series,.*"): # nested lists are forbidden s.str.cat([t, list(u)], join=join_type)
# errors for incorrect lengths rgx = r"If `others` contains arrays or lists \(or other list-likes.*" z = Series(["1", "2", "3"]).values
# unindexed object of wrong length with pytest.raises(ValueError, match=rgx): s.str.cat(z, join=join_type)
# unindexed object of wrong length in list with pytest.raises(ValueError, match=rgx): s.str.cat([t, z], join=join_type)
def test_str_cat_datetime_index_unsorted(join_type): # https://github.com/pandas-dev/pandas/pull/62843 values = [datetime(2024, 1, 1), datetime(2024, 1, 2)] s = Series(["a", "b"], index=[values[1], values[0]]) others = Series(["c", "d"], index=[values[0], values[1]]) result = s.str.cat(others, join=join_type) if join_type in {"outer", "right"}: expected = Series(["bc", "ad"], index=[values[0], values[1]]) else: expected = Series(["ad", "bc"], index=[values[1], values[0]]) tm.assert_series_equal(result, expected)
def test_str_cat_all_na(index_or_series, index_or_series2): # GH 24044 box = index_or_series other = index_or_series2
# check that all NaNs in caller / target work s = Index(["a", "b", "c", "d"]) s = s if box == Index else Series(s, index=s) t = other([np.nan] * 4, dtype=object) # add index of s for alignment t = t if other == Index else Series(t, index=s)
# all-NA target if box == Series: expected = Series([np.nan] * 4, index=s.index, dtype=s.dtype) else: # box == Index # TODO: Strimg option, this should return string dtype expected = Index([np.nan] * 4, dtype=object) result = s.str.cat(t, join="left") tm.assert_equal(result, expected)
# all-NA caller (only for Series) if other == Series: expected = Series([np.nan] * 4, dtype=object, index=t.index) result = t.str.cat(s, join="left") tm.assert_series_equal(result, expected)
def test_str_cat_special_cases(): s = Series(["a", "b", "c", "d"]) t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
# iterator of elements with different types expected = Series(["aaa", "bbb", "c-c", "ddd", "-e-"]) result = s.str.cat(iter([t, s.values]), join="outer", na_rep="-") tm.assert_series_equal(result, expected)
# right-align with different indexes in others expected = Series(["aa-", "d-d"], index=[0, 3]) result = s.str.cat([t.loc[[0]], t.loc[[3]]], join="right", na_rep="-") tm.assert_series_equal(result, expected)
def test_cat_on_filtered_index(): df = DataFrame( index=MultiIndex.from_product( [[2011, 2012], [1, 2, 3]], names=["year", "month"] ) )
df = df.reset_index() df = df[df.month > 1]
str_year = df.year.astype("str") str_month = df.month.astype("str") str_both = str_year.str.cat(str_month, sep=" ")
assert str_both.loc[1] == "2011 2"
str_multiple = str_year.str.cat([str_month, str_month], sep=" ")
assert str_multiple.loc[1] == "2011 2 2"
@pytest.mark.parametrize("klass", [tuple, list, np.array, Series, Index])def test_cat_different_classes(klass): # https://github.com/pandas-dev/pandas/issues/33425 s = Series(["a", "b", "c"]) result = s.str.cat(klass(["x", "y", "z"])) expected = Series(["ax", "by", "cz"]) tm.assert_series_equal(result, expected)
def test_cat_on_series_dot_str(): # GH 28277 ps = Series(["AbC", "de", "FGHI", "j", "kLLLm"])
message = re.escape( "others must be Series, Index, DataFrame, np.ndarray " "or list-like (either containing only strings or " "containing only objects of type Series/Index/" "np.ndarray[1-dim])" ) with pytest.raises(TypeError, match=message): ps.str.cat(others=ps.str)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784from datetime import datetimeimport re
import numpy as npimport pytest
from pandas.core.dtypes.dtypes import ArrowDtype
from pandas import ( DataFrame, Index, MultiIndex, Series, _testing as tm,)
def test_extract_expand_kwarg_wrong_type_raises(any_string_dtype): # TODO: should this raise TypeError values = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype) with pytest.raises(ValueError, match="expand must be True or False"): values.str.extract(".*(BAD[_]+).*(BAD)", expand=None)
def test_extract_expand_kwarg(any_string_dtype): s = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype) expected = DataFrame(["BAD__", np.nan, np.nan], dtype=any_string_dtype)
result = s.str.extract(".*(BAD[_]+).*") tm.assert_frame_equal(result, expected)
result = s.str.extract(".*(BAD[_]+).*", expand=True) tm.assert_frame_equal(result, expected)
expected = DataFrame( [["BAD__", "BAD"], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype ) result = s.str.extract(".*(BAD[_]+).*(BAD)", expand=False) tm.assert_frame_equal(result, expected)
def test_extract_expand_False_mixed_object(): ser = Series( ["aBAD_BAD", np.nan, "BAD_b_BAD", True, datetime.today(), "foo", None, 1, 2.0] )
# two groups result = ser.str.extract(".*(BAD[_]+).*(BAD)", expand=False) er = [np.nan, np.nan] # empty row expected = DataFrame( [["BAD_", "BAD"], er, ["BAD_", "BAD"], er, er, er, er, er, er], dtype=object ) tm.assert_frame_equal(result, expected)
# single group result = ser.str.extract(".*(BAD[_]+).*BAD", expand=False) expected = Series( ["BAD_", np.nan, "BAD_", np.nan, np.nan, np.nan, None, np.nan, np.nan], dtype=object, ) tm.assert_series_equal(result, expected)
def test_extract_expand_index_raises(): # GH9980 # Index only works with one regex group since # multi-group would expand to a frame idx = Index(["A1", "A2", "A3", "A4", "B5"]) msg = "only one regex group is supported with Index" with pytest.raises(ValueError, match=msg): idx.str.extract("([AB])([123])", expand=False)
def test_extract_expand_no_capture_groups_raises(index_or_series, any_string_dtype): s_or_idx = index_or_series(["A1", "B2", "C3"], dtype=any_string_dtype) msg = "pattern contains no capture groups"
# no groups with pytest.raises(ValueError, match=msg): s_or_idx.str.extract("[ABC][123]", expand=False)
# only non-capturing groups with pytest.raises(ValueError, match=msg): s_or_idx.str.extract("(?:[AB]).*", expand=False)
def test_extract_expand_single_capture_group(index_or_series, any_string_dtype): # single group renames series/index properly s_or_idx = index_or_series(["A1", "A2"], dtype=any_string_dtype) result = s_or_idx.str.extract(r"(?P<uno>A)\d", expand=False)
expected = index_or_series(["A", "A"], name="uno", dtype=any_string_dtype) if index_or_series == Series: tm.assert_series_equal(result, expected) else: tm.assert_index_equal(result, expected)
def test_extract_expand_capture_groups(any_string_dtype): s = Series(["A1", "B2", "C3"], dtype=any_string_dtype) # one group, no matches result = s.str.extract("(_)", expand=False) expected = Series([np.nan, np.nan, np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
# two groups, no matches result = s.str.extract("(_)(_)", expand=False) expected = DataFrame( [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
# one group, some matches result = s.str.extract("([AB])[123]", expand=False) expected = Series(["A", "B", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
# two groups, some matches result = s.str.extract("([AB])([123])", expand=False) expected = DataFrame( [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
# one named group result = s.str.extract("(?P<letter>[AB])", expand=False) expected = Series(["A", "B", np.nan], name="letter", dtype=any_string_dtype) tm.assert_series_equal(result, expected)
# two named groups result = s.str.extract("(?P<letter>[AB])(?P<number>[123])", expand=False) expected = DataFrame( [["A", "1"], ["B", "2"], [np.nan, np.nan]], columns=["letter", "number"], dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
# mix named and unnamed groups result = s.str.extract("([AB])(?P<number>[123])", expand=False) expected = DataFrame( [["A", "1"], ["B", "2"], [np.nan, np.nan]], columns=[0, "number"], dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
# one normal group, one non-capturing group result = s.str.extract("([AB])(?:[123])", expand=False) expected = Series(["A", "B", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
# two normal groups, one non-capturing group s = Series(["A11", "B22", "C33"], dtype=any_string_dtype) result = s.str.extract("([AB])([123])(?:[123])", expand=False) expected = DataFrame( [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
# one optional group followed by one normal group s = Series(["A1", "B2", "3"], dtype=any_string_dtype) result = s.str.extract("(?P<letter>[AB])?(?P<number>[123])", expand=False) expected = DataFrame( [["A", "1"], ["B", "2"], [np.nan, "3"]], columns=["letter", "number"], dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
# one normal group followed by one optional group s = Series(["A1", "B2", "C"], dtype=any_string_dtype) result = s.str.extract("(?P<letter>[ABC])(?P<number>[123])?", expand=False) expected = DataFrame( [["A", "1"], ["B", "2"], ["C", np.nan]], columns=["letter", "number"], dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
def test_extract_expand_capture_groups_index(index, any_string_dtype): # https://github.com/pandas-dev/pandas/issues/6348 # not passing index to the extractor data = ["A1", "B2", "C"]
if len(index) == 0: pytest.skip("Test requires len(index) > 0") while len(index) < len(data): index = index.repeat(2)
index = index[: len(data)] ser = Series(data, index=index, dtype=any_string_dtype)
result = ser.str.extract(r"(\d)", expand=False) expected = Series(["1", "2", np.nan], index=index, dtype=any_string_dtype) tm.assert_series_equal(result, expected)
result = ser.str.extract(r"(?P<letter>\D)(?P<number>\d)?", expand=False) expected = DataFrame( [["A", "1"], ["B", "2"], ["C", np.nan]], columns=["letter", "number"], index=index, dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
def test_extract_single_series_name_is_preserved(any_string_dtype): s = Series(["a3", "b3", "c2"], name="bob", dtype=any_string_dtype) result = s.str.extract(r"(?P<sue>[a-z])", expand=False) expected = Series(["a", "b", "c"], name="sue", dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_extract_expand_True(any_string_dtype): # Contains tests like those in test_match and some others. s = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
result = s.str.extract(".*(BAD[_]+).*(BAD)", expand=True) expected = DataFrame( [["BAD__", "BAD"], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
def test_extract_expand_True_mixed_object(): er = [np.nan, np.nan] # empty row mixed = Series( [ "aBAD_BAD", np.nan, "BAD_b_BAD", True, datetime.today(), "foo", None, 1, 2.0, ] )
result = mixed.str.extract(".*(BAD[_]+).*(BAD)", expand=True) expected = DataFrame( [["BAD_", "BAD"], er, ["BAD_", "BAD"], er, er, er, er, er, er], dtype=object ) tm.assert_frame_equal(result, expected)
def test_extract_expand_True_single_capture_group_raises( index_or_series, any_string_dtype): # these should work for both Series and Index # no groups s_or_idx = index_or_series(["A1", "B2", "C3"], dtype=any_string_dtype) msg = "pattern contains no capture groups" with pytest.raises(ValueError, match=msg): s_or_idx.str.extract("[ABC][123]", expand=True)
# only non-capturing groups with pytest.raises(ValueError, match=msg): s_or_idx.str.extract("(?:[AB]).*", expand=True)
def test_extract_expand_True_single_capture_group(index_or_series, any_string_dtype): # single group renames series/index properly s_or_idx = index_or_series(["A1", "A2"], dtype=any_string_dtype) result = s_or_idx.str.extract(r"(?P<uno>A)\d", expand=True) expected = DataFrame({"uno": ["A", "A"]}, dtype=any_string_dtype) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("name", [None, "series_name"])def test_extract_series(name, any_string_dtype): # extract should give the same result whether or not the series has a name. s = Series(["A1", "B2", "C3"], name=name, dtype=any_string_dtype)
# one group, no matches result = s.str.extract("(_)", expand=True) expected = DataFrame([np.nan, np.nan, np.nan], dtype=any_string_dtype) tm.assert_frame_equal(result, expected)
# two groups, no matches result = s.str.extract("(_)(_)", expand=True) expected = DataFrame( [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
# one group, some matches result = s.str.extract("([AB])[123]", expand=True) expected = DataFrame(["A", "B", np.nan], dtype=any_string_dtype) tm.assert_frame_equal(result, expected)
# two groups, some matches result = s.str.extract("([AB])([123])", expand=True) expected = DataFrame( [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
# one named group result = s.str.extract("(?P<letter>[AB])", expand=True) expected = DataFrame({"letter": ["A", "B", np.nan]}, dtype=any_string_dtype) tm.assert_frame_equal(result, expected)
# two named groups result = s.str.extract("(?P<letter>[AB])(?P<number>[123])", expand=True) expected = DataFrame( [["A", "1"], ["B", "2"], [np.nan, np.nan]], columns=["letter", "number"], dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
# mix named and unnamed groups result = s.str.extract("([AB])(?P<number>[123])", expand=True) expected = DataFrame( [["A", "1"], ["B", "2"], [np.nan, np.nan]], columns=[0, "number"], dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
# one normal group, one non-capturing group result = s.str.extract("([AB])(?:[123])", expand=True) expected = DataFrame(["A", "B", np.nan], dtype=any_string_dtype) tm.assert_frame_equal(result, expected)
def test_extract_optional_groups(any_string_dtype): # two normal groups, one non-capturing group s = Series(["A11", "B22", "C33"], dtype=any_string_dtype) result = s.str.extract("([AB])([123])(?:[123])", expand=True) expected = DataFrame( [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
# one optional group followed by one normal group s = Series(["A1", "B2", "3"], dtype=any_string_dtype) result = s.str.extract("(?P<letter>[AB])?(?P<number>[123])", expand=True) expected = DataFrame( [["A", "1"], ["B", "2"], [np.nan, "3"]], columns=["letter", "number"], dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
# one normal group followed by one optional group s = Series(["A1", "B2", "C"], dtype=any_string_dtype) result = s.str.extract("(?P<letter>[ABC])(?P<number>[123])?", expand=True) expected = DataFrame( [["A", "1"], ["B", "2"], ["C", np.nan]], columns=["letter", "number"], dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
def test_extract_dataframe_capture_groups_index(index, any_string_dtype): # GH6348 # not passing index to the extractor
data = ["A1", "B2", "C"]
if len(index) < len(data): pytest.skip(f"Index needs more than {len(data)} values")
index = index[: len(data)] s = Series(data, index=index, dtype=any_string_dtype)
result = s.str.extract(r"(\d)", expand=True) expected = DataFrame(["1", "2", np.nan], index=index, dtype=any_string_dtype) tm.assert_frame_equal(result, expected)
result = s.str.extract(r"(?P<letter>\D)(?P<number>\d)?", expand=True) expected = DataFrame( [["A", "1"], ["B", "2"], ["C", np.nan]], columns=["letter", "number"], index=index, dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
def test_extract_single_group_returns_frame(any_string_dtype): # GH11386 extract should always return DataFrame, even when # there is only one group. Prior to v0.18.0, extract returned # Series when there was only one group in the regex. s = Series(["a3", "b3", "c2"], name="series_name", dtype=any_string_dtype) result = s.str.extract(r"(?P<letter>[a-z])", expand=True) expected = DataFrame({"letter": ["a", "b", "c"]}, dtype=any_string_dtype) tm.assert_frame_equal(result, expected)
def test_extractall(any_string_dtype): data = [ "dave@google.com", "tdhock5@gmail.com", "maudelaperriere@gmail.com", "rob@gmail.com some text steve@gmail.com", "a@b.com some text c@d.com and e@f.com", np.nan, "", ] expected_tuples = [ ("dave", "google", "com"), ("tdhock5", "gmail", "com"), ("maudelaperriere", "gmail", "com"), ("rob", "gmail", "com"), ("steve", "gmail", "com"), ("a", "b", "com"), ("c", "d", "com"), ("e", "f", "com"), ] pat = r""" (?P<user>[a-z0-9]+) @ (?P<domain>[a-z]+) \. (?P<tld>[a-z]{2,4}) """ expected_columns = ["user", "domain", "tld"] s = Series(data, dtype=any_string_dtype) # extractall should return a DataFrame with one row for each match, indexed by the # subject from which the match came. expected_index = MultiIndex.from_tuples( [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 0), (4, 1), (4, 2)], names=(None, "match"), ) expected = DataFrame( expected_tuples, expected_index, expected_columns, dtype=any_string_dtype ) result = s.str.extractall(pat, flags=re.VERBOSE) tm.assert_frame_equal(result, expected)
# The index of the input Series should be used to construct the index of the output # DataFrame: mi = MultiIndex.from_tuples( [ ("single", "Dave"), ("single", "Toby"), ("single", "Maude"), ("multiple", "robAndSteve"), ("multiple", "abcdef"), ("none", "missing"), ("none", "empty"), ] ) s = Series(data, index=mi, dtype=any_string_dtype) expected_index = MultiIndex.from_tuples( [ ("single", "Dave", 0), ("single", "Toby", 0), ("single", "Maude", 0), ("multiple", "robAndSteve", 0), ("multiple", "robAndSteve", 1), ("multiple", "abcdef", 0), ("multiple", "abcdef", 1), ("multiple", "abcdef", 2), ], names=(None, None, "match"), ) expected = DataFrame( expected_tuples, expected_index, expected_columns, dtype=any_string_dtype ) result = s.str.extractall(pat, flags=re.VERBOSE) tm.assert_frame_equal(result, expected)
# MultiIndexed subject with names. s = Series(data, index=mi, dtype=any_string_dtype) s.index.names = ("matches", "description") expected_index.names = ("matches", "description", "match") expected = DataFrame( expected_tuples, expected_index, expected_columns, dtype=any_string_dtype ) result = s.str.extractall(pat, flags=re.VERBOSE) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize( "pat,expected_names", [ # optional groups. ("(?P<letter>[AB])?(?P<number>[123])", ["letter", "number"]), # only one of two groups has a name. ("([AB])?(?P<number>[123])", [0, "number"]), ],)def test_extractall_column_names(pat, expected_names, any_string_dtype): s = Series(["", "A1", "32"], dtype=any_string_dtype)
result = s.str.extractall(pat) expected = DataFrame( [("A", "1"), (np.nan, "3"), (np.nan, "2")], index=MultiIndex.from_tuples([(1, 0), (2, 0), (2, 1)], names=(None, "match")), columns=expected_names, dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
def test_extractall_single_group(any_string_dtype): s = Series(["a3", "b3", "d4c2"], name="series_name", dtype=any_string_dtype) expected_index = MultiIndex.from_tuples( [(0, 0), (1, 0), (2, 0), (2, 1)], names=(None, "match") )
# extractall(one named group) returns DataFrame with one named column. result = s.str.extractall(r"(?P<letter>[a-z])") expected = DataFrame( {"letter": ["a", "b", "d", "c"]}, index=expected_index, dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
# extractall(one un-named group) returns DataFrame with one un-named column. result = s.str.extractall(r"([a-z])") expected = DataFrame( ["a", "b", "d", "c"], index=expected_index, dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
def test_extractall_single_group_with_quantifier(any_string_dtype): # GH#13382 # extractall(one un-named group with quantifier) returns DataFrame with one un-named # column. s = Series(["ab3", "abc3", "d4cd2"], name="series_name", dtype=any_string_dtype) result = s.str.extractall(r"([a-z]+)") expected = DataFrame( ["ab", "abc", "d", "cd"], index=MultiIndex.from_tuples( [(0, 0), (1, 0), (2, 0), (2, 1)], names=(None, "match") ), dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize( "data, names", [ ([], (None,)), ([], ("i1",)), ([], (None, "i2")), ([], ("i1", "i2")), (["a3", "b3", "d4c2"], (None,)), (["a3", "b3", "d4c2"], ("i1", "i2")), (["a3", "b3", "d4c2"], (None, "i2")), ],)def test_extractall_no_matches(data, names, any_string_dtype): # GH19075 extractall with no matches should return a valid MultiIndex n = len(data) if len(names) == 1: index = Index(range(n), name=names[0]) else: tuples = (tuple([i] * (n - 1)) for i in range(n)) index = MultiIndex.from_tuples(tuples, names=names) s = Series(data, name="series_name", index=index, dtype=any_string_dtype) expected_index = MultiIndex.from_tuples([], names=((*names, "match")))
# one un-named group. result = s.str.extractall("(z)") expected = DataFrame(columns=range(1), index=expected_index, dtype=any_string_dtype) tm.assert_frame_equal(result, expected, check_column_type=True)
# two un-named groups. result = s.str.extractall("(z)(z)") expected = DataFrame(columns=range(2), index=expected_index, dtype=any_string_dtype) tm.assert_frame_equal(result, expected, check_column_type=True)
# one named group. result = s.str.extractall("(?P<first>z)") expected = DataFrame( columns=["first"], index=expected_index, dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
# two named groups. result = s.str.extractall("(?P<first>z)(?P<second>z)") expected = DataFrame( columns=["first", "second"], index=expected_index, dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
# one named, one un-named. result = s.str.extractall("(z)(?P<second>z)") expected = DataFrame( columns=[0, "second"], index=expected_index, dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
def test_extractall_stringindex(any_string_dtype): s = Series(["a1a2", "b1", "c1"], name="xxx", dtype=any_string_dtype) result = s.str.extractall(r"[ab](?P<digit>\d)") expected = DataFrame( {"digit": ["1", "2", "1"]}, index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 0)], names=[None, "match"]), dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
# index should return the same result as the default index without name thus # index.name doesn't affect to the result if any_string_dtype == "object": for idx in [ Index(["a1a2", "b1", "c1"], dtype=object), Index(["a1a2", "b1", "c1"], name="xxx", dtype=object), ]: result = idx.str.extractall(r"[ab](?P<digit>\d)") tm.assert_frame_equal(result, expected)
s = Series( ["a1a2", "b1", "c1"], name="s_name", index=Index(["XX", "yy", "zz"], name="idx_name"), dtype=any_string_dtype, ) result = s.str.extractall(r"[ab](?P<digit>\d)") expected = DataFrame( {"digit": ["1", "2", "1"]}, index=MultiIndex.from_tuples( [("XX", 0), ("XX", 1), ("yy", 0)], names=["idx_name", "match"] ), dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
def test_extractall_no_capture_groups_raises(any_string_dtype): # Does not make sense to use extractall with a regex that has no capture groups. # (it returns DataFrame with one column for each capture group) s = Series(["a3", "b3", "d4c2"], name="series_name", dtype=any_string_dtype) with pytest.raises(ValueError, match="no capture groups"): s.str.extractall(r"[a-z]")
def test_extract_index_one_two_groups(): s = Series(["a3", "b3", "d4c2"], index=["A3", "B3", "D4"], name="series_name") r = s.index.str.extract(r"([A-Z])", expand=True) e = DataFrame(["A", "B", "D"]) tm.assert_frame_equal(r, e)
# Prior to v0.18.0, index.str.extract(regex with one group) # returned Index. With more than one group, extract raised an # error (GH9980). Now extract always returns DataFrame. r = s.index.str.extract(r"(?P<letter>[A-Z])(?P<digit>[0-9])", expand=True) e_list = [("A", "3"), ("B", "3"), ("D", "4")] e = DataFrame(e_list, columns=["letter", "digit"]) tm.assert_frame_equal(r, e)
def test_extractall_same_as_extract(any_string_dtype): s = Series(["a3", "b3", "c2"], name="series_name", dtype=any_string_dtype)
pattern_two_noname = r"([a-z])([0-9])" extract_two_noname = s.str.extract(pattern_two_noname, expand=True) has_multi_index = s.str.extractall(pattern_two_noname) no_multi_index = has_multi_index.xs(0, level="match") tm.assert_frame_equal(extract_two_noname, no_multi_index)
pattern_two_named = r"(?P<letter>[a-z])(?P<digit>[0-9])" extract_two_named = s.str.extract(pattern_two_named, expand=True) has_multi_index = s.str.extractall(pattern_two_named) no_multi_index = has_multi_index.xs(0, level="match") tm.assert_frame_equal(extract_two_named, no_multi_index)
pattern_one_named = r"(?P<group_name>[a-z])" extract_one_named = s.str.extract(pattern_one_named, expand=True) has_multi_index = s.str.extractall(pattern_one_named) no_multi_index = has_multi_index.xs(0, level="match") tm.assert_frame_equal(extract_one_named, no_multi_index)
pattern_one_noname = r"([a-z])" extract_one_noname = s.str.extract(pattern_one_noname, expand=True) has_multi_index = s.str.extractall(pattern_one_noname) no_multi_index = has_multi_index.xs(0, level="match") tm.assert_frame_equal(extract_one_noname, no_multi_index)
def test_extractall_same_as_extract_subject_index(any_string_dtype): # same as above tests, but s has a MultiIndex. mi = MultiIndex.from_tuples( [("A", "first"), ("B", "second"), ("C", "third")], names=("capital", "ordinal"), ) s = Series(["a3", "b3", "c2"], index=mi, name="series_name", dtype=any_string_dtype)
pattern_two_noname = r"([a-z])([0-9])" extract_two_noname = s.str.extract(pattern_two_noname, expand=True) has_match_index = s.str.extractall(pattern_two_noname) no_match_index = has_match_index.xs(0, level="match") tm.assert_frame_equal(extract_two_noname, no_match_index)
pattern_two_named = r"(?P<letter>[a-z])(?P<digit>[0-9])" extract_two_named = s.str.extract(pattern_two_named, expand=True) has_match_index = s.str.extractall(pattern_two_named) no_match_index = has_match_index.xs(0, level="match") tm.assert_frame_equal(extract_two_named, no_match_index)
pattern_one_named = r"(?P<group_name>[a-z])" extract_one_named = s.str.extract(pattern_one_named, expand=True) has_match_index = s.str.extractall(pattern_one_named) no_match_index = has_match_index.xs(0, level="match") tm.assert_frame_equal(extract_one_named, no_match_index)
pattern_one_noname = r"([a-z])" extract_one_noname = s.str.extract(pattern_one_noname, expand=True) has_match_index = s.str.extractall(pattern_one_noname) no_match_index = has_match_index.xs(0, level="match") tm.assert_frame_equal(extract_one_noname, no_match_index)
def test_extractall_preserves_dtype(): # Ensure that when extractall is called on a series with specific dtypes set, that # the dtype is preserved in the resulting DataFrame's column. pa = pytest.importorskip("pyarrow")
result = Series(["abc", "ab"], dtype=ArrowDtype(pa.string())).str.extractall("(ab)") assert result.dtypes[0] == "string[pyarrow]"
@pytest.mark.parametrize( "pat, expected_data", [ (r"(a(?=b))", [None, "a", None, None]), (r"((?<=a)b)", [None, "b", None, None]), (r"(a(?!b))", ["a", None, "a", None]), (r"((?<!b)a)", ["a", "a", None, None]), ("(ab)", [None, "ab", None, None]), ],)def test_extract_lookarounds(any_string_dtype, pat, expected_data): # https://github.com/pandas-dev/pandas/issues/60833 ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype) result = ser.str.extract(pat, expand=False) if any_string_dtype == "object": # object input will preserve None but any result with no matches gets NaN expected_data = [np.nan if e is None else e for e in expected_data] expected = Series([*expected_data, None], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "pat, expected_data", [ (r"(a(?=b))", {(1, 0): "a"}), (r"((?<=a)b)", {(1, 0): "b"}), (r"(a(?!b))", {(0, 0): "a", (0, 1): "a", (2, 0): "a"}), (r"((?<!b)a)", {(0, 0): "a", (0, 1): "a", (1, 0): "a"}), ("(ab)", {(1, 0): "ab"}), ],)def test_extractall_lookarounds(any_string_dtype, pat, expected_data): # https://github.com/pandas-dev/pandas/issues/60833 ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype) result = ser.str.extractall(pat) expected = Series(expected_data, dtype=any_string_dtype).to_frame() expected.index.names = [None, "match"] tm.assert_frame_equal(result, expected)
def test_extract_end_of_string(any_string_dtype): # https://github.com/pandas-dev/pandas/pull/63613 ser = Series(["aa", "abc", "bb\n"], dtype=any_string_dtype)
# with dollar sign result = ser.str.extract("([ab]+)$") expected = Series(["aa", np.nan, "bb"], dtype=any_string_dtype).to_frame() tm.assert_frame_equal(result, expected)
# with \Z (ensure this is translated to \z for pyarrow) result = ser.str.extract(r"([ab]+)\Z") expected = Series(["aa", np.nan, np.nan], dtype=any_string_dtype).to_frame() tm.assert_frame_equal(result, expected)
# ensure finding a literal \Z still works ser = Series([r"aa\Z", "abc", "bb\\Z\n"], dtype=any_string_dtype) result = ser.str.extract(r"([ab]+)\\Z") expected = Series(["aa", np.nan, "bb"], dtype=any_string_dtype).to_frame() tm.assert_frame_equal(result, expected)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730from datetime import datetimeimport re
import numpy as npimport pytest
from pandas._libs import libimport pandas.util._test_decorators as td
import pandas as pdfrom pandas import ( Series, StringDtype, _testing as tm,)from pandas.tests.strings import ( _convert_na_value, is_object_or_nan_string_dtype,)
# --------------------------------------------------------------------------------------# str.contains# --------------------------------------------------------------------------------------
def test_contains(any_string_dtype): values = np.array( ["foo", np.nan, "fooommm__foo", "mmm_", "foommm[_]+bar"], dtype=np.object_ ) values = Series(values, dtype=any_string_dtype) pat = "mmm[_]+"
result = values.str.contains(pat) if any_string_dtype == "str": # NaN propagates as False expected = Series([False, False, True, True, False], dtype=bool) else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series( np.array([False, np.nan, True, True, False], dtype=np.object_), dtype=expected_dtype, )
tm.assert_series_equal(result, expected)
result = values.str.contains(pat, regex=False) if any_string_dtype == "str": expected = Series([False, False, False, False, True], dtype=bool) else: expected = Series( np.array([False, np.nan, False, False, True], dtype=np.object_), dtype=expected_dtype, ) tm.assert_series_equal(result, expected)
values = Series( np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=object), dtype=any_string_dtype, ) result = values.str.contains(pat) expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series(np.array([False, False, True, True]), dtype=expected_dtype) tm.assert_series_equal(result, expected)
# case insensitive using regex values = Series( np.array(["Foo", "xYz", "fOOomMm__fOo", "MMM_"], dtype=object), dtype=any_string_dtype, )
result = values.str.contains("FOO|mmm", case=False) expected = Series(np.array([True, False, True, True]), dtype=expected_dtype) tm.assert_series_equal(result, expected)
# case insensitive without regex result = values.str.contains("foo", regex=False, case=False) expected = Series(np.array([True, False, True, False]), dtype=expected_dtype) tm.assert_series_equal(result, expected)
# unicode values = Series( np.array(["foo", np.nan, "fooommm__foo", "mmm_"], dtype=np.object_), dtype=any_string_dtype, ) pat = "mmm[_]+"
result = values.str.contains(pat) if any_string_dtype == "str": expected = Series([False, False, True, True], dtype=bool) else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series( np.array([False, np.nan, True, True], dtype=np.object_), dtype=expected_dtype, ) tm.assert_series_equal(result, expected)
result = values.str.contains(pat, na=False) expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series(np.array([False, False, True, True]), dtype=expected_dtype) tm.assert_series_equal(result, expected)
values = Series( np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=np.object_), dtype=any_string_dtype, ) result = values.str.contains(pat) expected = Series(np.array([False, False, True, True]), dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_contains_object_mixed(): mixed = Series( np.array( ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0], dtype=object, ) ) result = mixed.str.contains("o") expected = Series( np.array( [False, np.nan, False, np.nan, np.nan, True, None, np.nan, np.nan], dtype=np.object_, ) ) tm.assert_series_equal(result, expected)
def test_contains_na_kwarg_for_object_category(): # gh 22158
# na for category values = Series(["a", "b", "c", "a", np.nan], dtype="category") result = values.str.contains("a", na=True) expected = Series([True, False, False, True, True]) tm.assert_series_equal(result, expected)
result = values.str.contains("a", na=False) expected = Series([True, False, False, True, False]) tm.assert_series_equal(result, expected)
# na for objects values = Series(["a", "b", "c", "a", np.nan]) result = values.str.contains("a", na=True) expected = Series([True, False, False, True, True]) tm.assert_series_equal(result, expected)
result = values.str.contains("a", na=False) expected = Series([True, False, False, True, False]) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "na, expected", [ (None, pd.NA), (True, True), (False, False), (0, False), (3, True), (np.nan, pd.NA), ],)@pytest.mark.parametrize("regex", [True, False])def test_contains_na_kwarg_for_nullable_string_dtype( nullable_string_dtype, na, expected, regex): # https://github.com/pandas-dev/pandas/pull/41025#issuecomment-824062416
values = Series(["a", "b", "c", "a", np.nan], dtype=nullable_string_dtype)
if na in [0, 3] and na is not False: msg = f"na must be None, pd.NA, np.nan, True, or False; got {na}" with pytest.raises(ValueError, match=msg): values.str.contains("a", na=na, regex=regex) else: result = values.str.contains("a", na=na, regex=regex) expected = Series([True, False, False, True, expected], dtype="boolean") tm.assert_series_equal(result, expected)
def test_contains_moar(any_string_dtype): # PR #1179 s = Series( ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"], dtype=any_string_dtype, )
result = s.str.contains("a") if any_string_dtype == "str": # NaN propagates as False expected_dtype = bool na_value = False else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) na_value = np.nan expected = Series( [False, False, False, True, True, False, na_value, False, False, True], dtype=expected_dtype, ) tm.assert_series_equal(result, expected)
result = s.str.contains("a", case=False) expected = Series( [True, False, False, True, True, False, na_value, True, False, True], dtype=expected_dtype, ) tm.assert_series_equal(result, expected)
result = s.str.contains("Aa") expected = Series( [False, False, False, True, False, False, na_value, False, False, False], dtype=expected_dtype, ) tm.assert_series_equal(result, expected)
result = s.str.contains("ba") expected = Series( [False, False, False, True, False, False, na_value, False, False, False], dtype=expected_dtype, ) tm.assert_series_equal(result, expected)
result = s.str.contains("ba", case=False) expected = Series( [False, False, False, True, True, False, na_value, True, False, False], dtype=expected_dtype, ) tm.assert_series_equal(result, expected)
def test_contains_nan(any_string_dtype): # PR #14171 s = Series([np.nan, np.nan, np.nan], dtype=any_string_dtype)
result = s.str.contains("foo", na=False) expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series([False, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = s.str.contains("foo", na=True) expected = Series([True, True, True], dtype=expected_dtype) tm.assert_series_equal(result, expected)
msg = "na must be None, pd.NA, np.nan, True, or False; got foo" with pytest.raises(ValueError, match=msg): s.str.contains("foo", na="foo")
result = s.str.contains("foo") if any_string_dtype == "str": # NaN propagates as False expected = Series([False, False, False], dtype=bool) else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series([np.nan, np.nan, np.nan], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_contains_compiled_regex(any_string_dtype): # GH#61942 expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" )
ser = Series(["foo", "bar", "Baz"], dtype=any_string_dtype)
pat = re.compile("ba.") result = ser.str.contains(pat) expected = Series([False, True, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# TODO this currently works for pyarrow-backed dtypes but raises for python if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow": result = ser.str.contains(pat, case=False) expected = Series([False, True, True], dtype=expected_dtype) tm.assert_series_equal(result, expected) else: with pytest.raises( ValueError, match="cannot process flags argument with a compiled pattern" ): ser.str.contains(pat, case=False)
pat = re.compile("ba.", flags=re.IGNORECASE) result = ser.str.contains(pat) expected = Series([False, True, True], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# TODO should this be supported? with pytest.raises( ValueError, match="cannot process flags argument with a compiled pattern" ): ser.str.contains(pat, flags=re.IGNORECASE)
def test_contains_compiled_regex_flags(any_string_dtype): # ensure other (than ignorecase) flags are respected expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" )
ser = Series(["foobar", "foo\nbar", "Baz"], dtype=any_string_dtype)
pat = re.compile("^ba") result = ser.str.contains(pat) expected = Series([False, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
pat = re.compile("^ba", flags=re.MULTILINE) result = ser.str.contains(pat) expected = Series([False, True, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
pat = re.compile("^ba", flags=re.MULTILINE | re.IGNORECASE) result = ser.str.contains(pat) expected = Series([False, True, True], dtype=expected_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "pat, expected_data", [ (r"a(?=b)", [False, True, False, False]), (r"(?<=a)b", [False, True, False, False]), (r"a(?!b)", [True, False, True, False]), (r"(?<!b)a", [True, True, False, False]), ("ab", [False, True, False, False]), ],)@pytest.mark.parametrize("na", [lib.no_default, True, False, np.nan, None, pd.NA])def test_contains_lookarounds(any_string_dtype, pat, expected_data, na): # https://github.com/pandas-dev/pandas/issues/60833 if any_string_dtype == "object" and not isinstance(na, bool): expected_dtype = "object" else: expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) if any_string_dtype == "object": # The behavior here for `na=pd.NA` looks wrong. if (na is lib.no_default or pd.isna(na)) and na is not pd.NA: na_result = None else: na_result = na elif na is lib.no_default or pd.isna(na): if any_string_dtype == "str": na_result = False elif any_string_dtype == "string": na_result = pd.NA else: raise ValueError(f"Unrecognized string dtype {any_string_dtype}") else: na_result = na expected_data = expected_data.copy() expected_data.append(na_result) ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype) result = ser.str.contains(pat, regex=True, na=na) expected = Series(expected_data, dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_contains_end_of_string(any_string_dtype): # https://github.com/pandas-dev/pandas/pull/63613 expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" )
ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
# with dollar sign result = ser.str.contains("bar$") if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow": # pyarrow (RE2) only matches $ at the very end of the line expected = Series([False, True, False, False], dtype=expected_dtype) else: # python matches $ before or after an ending newline expected = Series([False, True, False, True], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# with \Z (ensure this is translated to \z for pyarrow) result = ser.str.contains(r"bar\Z") expected = Series([False, True, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# ensure finding a literal \Z still works ser = Series( ["bar", r"bar{}".format("\\"), r"bar\Z", r"bar\\Z", "bars", "bar\n"], dtype=any_string_dtype, )
result = ser.str.contains(r"bar\\Z") expected = Series([False, False, True, False, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = ser.str.contains(r"bar\\\Z") expected = Series([False, True, False, False, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = ser.str.contains(r"bar\\\\Z") expected = Series([False, False, False, True, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# --------------------------------------------------------------------------------------# str.startswith# --------------------------------------------------------------------------------------
def test_startswith_endswith_validate_na(any_string_dtype): # GH#59615 ser = Series( ["om", np.nan, "foo_nom", "nom", "bar_foo", np.nan, "foo"], dtype=any_string_dtype, ) msg = "na must be None, pd.NA, np.nan, True, or False; got baz" with pytest.raises(ValueError, match=msg): ser.str.startswith("kapow", na="baz") with pytest.raises(ValueError, match=msg): ser.str.endswith("bar", na="baz")
@pytest.mark.parametrize("pat", ["foo", ("foo", "baz")])@pytest.mark.parametrize("dtype", ["object", "category"])@pytest.mark.parametrize("null_value", [None, np.nan, pd.NA])@pytest.mark.parametrize("na", [True, False])def test_startswith(pat, dtype, null_value, na, using_infer_string): # add category dtype parametrizations for GH-36241 values = Series( ["om", null_value, "foo_nom", "nom", "bar_foo", null_value, "foo"], dtype=dtype, )
result = values.str.startswith(pat) exp = Series([False, np.nan, True, False, False, np.nan, True]) if dtype == "object" and null_value is pd.NA: # GH#18463 exp = exp.fillna(null_value) elif dtype == "object" and null_value is None: exp[exp.isna()] = None elif using_infer_string and dtype == "category": exp = exp.fillna(False).astype(bool) tm.assert_series_equal(result, exp)
result = values.str.startswith(pat, na=na) exp = Series([False, na, True, False, False, na, True]) tm.assert_series_equal(result, exp)
# mixed mixed = np.array( ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0], dtype=np.object_, ) rs = Series(mixed).str.startswith("f") xp = Series([False, np.nan, False, np.nan, np.nan, True, None, np.nan, np.nan]) tm.assert_series_equal(rs, xp)
@pytest.mark.parametrize("na", [None, True, False])def test_startswith_string_dtype(any_string_dtype, na): values = Series( ["om", None, "foo_nom", "nom", "bar_foo", None, "foo", "regex", "rege."], dtype=any_string_dtype, ) result = values.str.startswith("foo", na=na)
expected_dtype = ( (object if na is None else bool) if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) if any_string_dtype == "str": # NaN propagates as False expected_dtype = bool if na is None: na = False exp = Series( [False, na, True, False, False, na, True, False, False], dtype=expected_dtype ) tm.assert_series_equal(result, exp)
result = values.str.startswith("rege.", na=na) exp = Series( [False, na, False, False, False, na, False, False, True], dtype=expected_dtype ) tm.assert_series_equal(result, exp)
# --------------------------------------------------------------------------------------# str.endswith# --------------------------------------------------------------------------------------
@pytest.mark.parametrize("pat", ["foo", ("foo", "baz")])@pytest.mark.parametrize("dtype", ["object", "category"])@pytest.mark.parametrize("null_value", [None, np.nan, pd.NA])@pytest.mark.parametrize("na", [True, False])def test_endswith(pat, dtype, null_value, na, using_infer_string): # add category dtype parametrizations for GH-36241 values = Series( ["om", null_value, "foo_nom", "nom", "bar_foo", null_value, "foo"], dtype=dtype, )
result = values.str.endswith(pat) exp = Series([False, np.nan, False, False, True, np.nan, True]) if dtype == "object" and null_value is pd.NA: # GH#18463 exp = exp.fillna(null_value) elif dtype == "object" and null_value is None: exp[exp.isna()] = None elif using_infer_string and dtype == "category": exp = exp.fillna(False).astype(bool) tm.assert_series_equal(result, exp)
result = values.str.endswith(pat, na=na) exp = Series([False, na, False, False, True, na, True]) tm.assert_series_equal(result, exp)
# mixed mixed = np.array( ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0], dtype=object, ) rs = Series(mixed).str.endswith("f") xp = Series([False, np.nan, False, np.nan, np.nan, False, None, np.nan, np.nan]) tm.assert_series_equal(rs, xp)
@pytest.mark.parametrize("na", [None, True, False])def test_endswith_string_dtype(any_string_dtype, na): values = Series( ["om", None, "foo_nom", "nom", "bar_foo", None, "foo", "regex", "rege."], dtype=any_string_dtype, ) result = values.str.endswith("foo", na=na) expected_dtype = ( (object if na is None else bool) if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) if any_string_dtype == "str": # NaN propagates as False expected_dtype = bool if na is None: na = False exp = Series( [False, na, False, False, True, na, True, False, False], dtype=expected_dtype ) tm.assert_series_equal(result, exp)
result = values.str.endswith("rege.", na=na) exp = Series( [False, na, False, False, False, na, False, False, True], dtype=expected_dtype ) tm.assert_series_equal(result, exp)
# --------------------------------------------------------------------------------------# str.replace# --------------------------------------------------------------------------------------def test_replace_dict_invalid(any_string_dtype): # GH 51914 series = Series(data=["A", "B_junk", "C_gunk"], name="my_messy_col") msg = "repl cannot be used when pat is a dictionary"
with pytest.raises(ValueError, match=msg): series.str.replace(pat={"A": "a", "B": "b"}, repl="A")
def test_replace_dict(any_string_dtype): # GH 51914 series = Series(data=["A", "B", "C"], name="my_messy_col") new_series = series.str.replace(pat={"A": "a", "B": "b"}) expected = Series(data=["a", "b", "C"], name="my_messy_col") tm.assert_series_equal(new_series, expected)
def test_replace(any_string_dtype): ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
result = ser.str.replace("BAD[_]*", "", regex=True) expected = Series(["foobar", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_replace_max_replacements(any_string_dtype): ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
expected = Series(["foobarBAD", np.nan], dtype=any_string_dtype) result = ser.str.replace("BAD[_]*", "", n=1, regex=True) tm.assert_series_equal(result, expected)
expected = Series(["foo__barBAD", np.nan], dtype=any_string_dtype) result = ser.str.replace("BAD", "", n=1, regex=False) tm.assert_series_equal(result, expected)
def test_replace_mixed_object(): ser = Series( ["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0] ) result = Series(ser).str.replace("BAD[_]*", "", regex=True) expected = Series( ["a", np.nan, "b", np.nan, np.nan, "foo", None, np.nan, np.nan], dtype=object ) tm.assert_series_equal(result, expected)
def test_replace_unicode(any_string_dtype): ser = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype) expected = Series([b"abcd, \xc3\xa0".decode("utf-8")], dtype=any_string_dtype) result = ser.str.replace(r"(?<=\w),(?=\w)", ", ", flags=re.UNICODE, regex=True) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("repl", [None, 3, {"a": "b"}])@pytest.mark.parametrize("data", [["a", "b", None], ["a", "b", "c", "ad"]])def test_replace_wrong_repl_type_raises(any_string_dtype, index_or_series, repl, data): # https://github.com/pandas-dev/pandas/issues/13438 msg = "repl must be a string or callable" obj = index_or_series(data, dtype=any_string_dtype) with pytest.raises(TypeError, match=msg): obj.str.replace("a", repl)
def test_replace_callable(any_string_dtype): # GH 15055 ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
# test with callable repl = lambda m: m.group(0).swapcase() result = ser.str.replace("[a-z][A-Z]{2}", repl, n=2, regex=True) expected = Series(["foObaD__baRbaD", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "repl", [lambda: None, lambda m, x: None, lambda m, x, y=None: None])def test_replace_callable_raises(any_string_dtype, repl): # GH 15055 values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
# test with wrong number of arguments, raising an error msg = ( r"((takes)|(missing)) (?(2)from \d+ to )?\d+ " r"(?(3)required )positional arguments?" ) with pytest.raises(TypeError, match=msg): values.str.replace("a", repl, regex=True)
@pytest.mark.parametrize( "repl, expected_list", [ ( r"\g<three> \g<two> \g<one>", ["Three Two One", "Baz Bar Foo"], ), ( r"\3 \2 \1", ["Three Two One", "Baz Bar Foo"], ), ( r"\g<3> \g<2> \g<1>", ["Three Two One", "Baz Bar Foo"], ), ( r"\g<2>0", ["Two0", "Bar0"], ), ( r"\g<2>0 \1", ["Two0 One", "Bar0 Foo"], ), ], ids=[ "named_groups_full_swap", "numbered_groups_no_g_full_swap", "numbered_groups_full_swap", "single_group_with_literal", "mixed_group_reference_with_literal", ],)@pytest.mark.parametrize("use_compile", [True, False])def test_replace_named_groups_regex_swap( any_string_dtype, use_compile, repl, expected_list): # GH#57636 ser = Series(["One Two Three", "Foo Bar Baz"], dtype=any_string_dtype) pattern = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)" if use_compile: pattern = re.compile(pattern) result = ser.str.replace(pattern, repl, regex=True) expected = Series(expected_list, dtype=any_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "repl", [ r"\g<20>", r"\20", r"\40", r"\4", ],)@pytest.mark.parametrize("use_compile", [True, False])def test_replace_named_groups_regex_swap_expected_fail( any_string_dtype, repl, use_compile, request): # GH#57636 if ( not use_compile and r"\g" not in repl and isinstance(any_string_dtype, StringDtype) and any_string_dtype.storage == "pyarrow" ): # calls pyarrow method directly if repl == r"\20": mark = pytest.mark.xfail(reason="PyArrow interprets as group + literal") request.applymarker(mark)
pa = pytest.importorskip("pyarrow") error_type = pa.ArrowInvalid error_msg = r"only has \d parenthesized subexpressions" else: error_type = re.error error_msg = "invalid group reference"
pattern = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)" if use_compile: pattern = re.compile(pattern) ser = Series(["One Two Three", "Foo Bar Baz"], dtype=any_string_dtype)
with pytest.raises(error_type, match=error_msg): ser.str.replace(pattern, repl, regex=True)
@pytest.mark.parametrize( "pattern, repl", [ (r"(\w+) (\w+) (\w+)", r"\20"), (r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)", r"\20"), ],)def test_pyarrow_ambiguous_group_references(pyarrow_string_dtype, pattern, repl): # GH#62653 ser = Series(["One Two Three", "Foo Bar Baz"], dtype=pyarrow_string_dtype)
result = ser.str.replace(pattern, repl, regex=True) expected = Series(["Two0", "Bar0"], dtype=pyarrow_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "pattern, repl, expected_list", [ ( r"\[(?P<one>\d+)\]", r"(\1)", ["var.one(0)", "var.two(1)", "var.three(2)"], ), ( r"\[(\d+)\]", r"(\1)", ["var.one(0)", "var.two(1)", "var.three(2)"], ), ],)@td.skip_if_no("pyarrow")def test_pyarrow_backend_group_replacement(pattern, repl, expected_list): ser = Series(["var.one[0]", "var.two[1]", "var.three[2]"]).convert_dtypes( dtype_backend="pyarrow" ) result = ser.str.replace(pattern, repl, regex=True) expected = Series(expected_list).convert_dtypes(dtype_backend="pyarrow") tm.assert_series_equal(result, expected)
def test_replace_callable_named_groups(any_string_dtype): # test regex named groups ser = Series(["Foo Bar Baz", np.nan], dtype=any_string_dtype) pat = r"(?P<first>\w+) (?P<middle>\w+) (?P<last>\w+)" repl = lambda m: m.group("middle").swapcase() result = ser.str.replace(pat, repl, regex=True) expected = Series(["bAR", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_replace_compiled_regex(any_string_dtype): # GH 15446 ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
# test with compiled regex pat = re.compile(r"BAD_*") result = ser.str.replace(pat, "", regex=True) expected = Series(["foobar", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
result = ser.str.replace(pat, "", n=1, regex=True) expected = Series(["foobarBAD", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_replace_compiled_regex_mixed_object(): pat = re.compile(r"BAD_*") ser = Series( ["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0] ) result = Series(ser).str.replace(pat, "", regex=True) expected = Series( ["a", np.nan, "b", np.nan, np.nan, "foo", None, np.nan, np.nan], dtype=object ) tm.assert_series_equal(result, expected)
def test_replace_compiled_regex_unicode(any_string_dtype): ser = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype) expected = Series([b"abcd, \xc3\xa0".decode("utf-8")], dtype=any_string_dtype) pat = re.compile(r"(?<=\w),(?=\w)", flags=re.UNICODE) result = ser.str.replace(pat, ", ", regex=True) tm.assert_series_equal(result, expected)
def test_replace_compiled_regex_raises(any_string_dtype): # case and flags provided to str.replace will have no effect # and will produce warnings ser = Series(["fooBAD__barBAD__bad", np.nan], dtype=any_string_dtype) pat = re.compile(r"BAD_*")
msg = "case and flags cannot be set when pat is a compiled regex"
with pytest.raises(ValueError, match=msg): ser.str.replace(pat, "", flags=re.IGNORECASE, regex=True)
with pytest.raises(ValueError, match=msg): ser.str.replace(pat, "", case=False, regex=True)
with pytest.raises(ValueError, match=msg): ser.str.replace(pat, "", case=True, regex=True)
def test_replace_compiled_regex_callable(any_string_dtype): # test with callable ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype) repl = lambda m: m.group(0).swapcase() pat = re.compile("[a-z][A-Z]{2}") result = ser.str.replace(pat, repl, n=2, regex=True) expected = Series(["foObaD__baRbaD", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("regex,expected_val", [(True, "bao"), (False, "foo")])def test_replace_literal(regex, expected_val, any_string_dtype): # GH16808 literal replace (regex=False vs regex=True) ser = Series(["f.o", "foo", np.nan], dtype=any_string_dtype) expected = Series(["bao", expected_val, np.nan], dtype=any_string_dtype) result = ser.str.replace("f.", "ba", regex=regex) tm.assert_series_equal(result, expected)
def test_replace_literal_callable_raises(any_string_dtype): ser = Series([], dtype=any_string_dtype) repl = lambda m: m.group(0).swapcase()
msg = "Cannot use a callable replacement when regex=False" with pytest.raises(ValueError, match=msg): ser.str.replace("abc", repl, regex=False)
def test_replace_literal_compiled_raises(any_string_dtype): ser = Series([], dtype=any_string_dtype) pat = re.compile("[a-z][A-Z]{2}")
msg = "Cannot use a compiled regex as replacement pattern with regex=False" with pytest.raises(ValueError, match=msg): ser.str.replace(pat, "", regex=False)
def test_replace_moar(any_string_dtype): # PR #1179 ser = Series( ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"], dtype=any_string_dtype, )
result = ser.str.replace("A", "YYY") expected = Series( ["YYY", "B", "C", "YYYaba", "Baca", "", np.nan, "CYYYBYYY", "dog", "cat"], dtype=any_string_dtype, ) tm.assert_series_equal(result, expected)
result = ser.str.replace("A", "YYY", case=False) expected = Series( [ "YYY", "B", "C", "YYYYYYbYYY", "BYYYcYYY", "", np.nan, "CYYYBYYY", "dog", "cYYYt", ], dtype=any_string_dtype, ) tm.assert_series_equal(result, expected)
result = ser.str.replace("^.a|dog", "XX-XX ", case=False, regex=True) expected = Series( [ "A", "B", "C", "XX-XX ba", "XX-XX ca", "", np.nan, "XX-XX BA", "XX-XX ", "XX-XX t", ], dtype=any_string_dtype, ) tm.assert_series_equal(result, expected)
def test_replace_not_case_sensitive_not_regex(any_string_dtype): # https://github.com/pandas-dev/pandas/issues/41602 ser = Series(["A.", "a.", "Ab", "ab", np.nan], dtype=any_string_dtype)
result = ser.str.replace("a", "c", case=False, regex=False) expected = Series(["c.", "c.", "cb", "cb", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
result = ser.str.replace("a.", "c.", case=False, regex=False) expected = Series(["c.", "c.", "Ab", "ab", np.nan], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_replace_regex(any_string_dtype): # https://github.com/pandas-dev/pandas/pull/24809 s = Series(["a", "b", "ac", np.nan, ""], dtype=any_string_dtype) result = s.str.replace("^.$", "a", regex=True) expected = Series(["a", "a", "ac", np.nan, ""], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("regex", [True, False])def test_replace_regex_single_character(regex, any_string_dtype): # https://github.com/pandas-dev/pandas/pull/24809, enforced in 2.0 # GH 24804 s = Series(["a.b", ".", "b", np.nan, ""], dtype=any_string_dtype)
result = s.str.replace(".", "a", regex=regex) if regex: expected = Series(["aaa", "a", "a", np.nan, ""], dtype=any_string_dtype) else: expected = Series(["aab", "a", "b", np.nan, ""], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "pat, expected_data", [ (r"a(?=b)", ["aa", "xb", "ba", "bb"]), (r"(?<=a)b", ["aa", "ax", "ba", "bb"]), (r"a(?!b)", ["xx", "ab", "bx", "bb"]), (r"(?<!b)a", ["xx", "xb", "ba", "bb"]), ("ab", ["aa", "x", "ba", "bb"]), ],)def test_replace_lookarounds(any_string_dtype, pat, expected_data): # https://github.com/pandas-dev/pandas/issues/60833 ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype) result = ser.str.replace(pat, "x", regex=True) if any_string_dtype == "object": null_result = None elif any_string_dtype == "str": null_result = np.nan elif any_string_dtype == "string": null_result = pd.NA else: raise ValueError(f"Unrecognized dtype: {any_string_dtype}") expected = Series([*expected_data, null_result], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_replace_end_of_string(any_string_dtype): # https://github.com/pandas-dev/pandas/pull/63613 ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
# with dollar sign result = ser.str.replace("bar$", "x", regex=True) if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow": # pyarrow (RE2) only matches $ at the very end of the line expected = Series(["baz", "x", "bars", "bar\n"], dtype=any_string_dtype) else: # python matches $ before or after an ending newline expected = Series(["baz", "x", "bars", "x\n"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
# with \Z (ensure this is translated to \z for pyarrow) result = ser.str.replace(r"bar\Z", "x", regex=True) expected = Series(["baz", "x", "bars", "bar\n"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
# ensure finding a literal \Z still works ser = Series([r"bar\Z", "bar", "bars", "bar\n"], dtype=any_string_dtype) result = ser.str.replace(r"bar\\Z", "x", regex=True) expected = Series(["x", "bar", "bars", "bar\n"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_replace_empty_pattern(any_string_dtype): # https://github.com/pandas-dev/pandas/issues/64941 ser = Series(["abcd"], dtype=any_string_dtype)
result = ser.str.replace("", "") expected = Series(["abcd"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
result = ser.str.replace("", "X") expected = Series(["XaXbXcXdX"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
ser = Series([], dtype=any_string_dtype) result = ser.str.replace("", "X") expected = Series([], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
# --------------------------------------------------------------------------------------# str.match# --------------------------------------------------------------------------------------
def test_match(any_string_dtype): if any_string_dtype == "str": # NaN propagates as False expected_dtype = bool na_value = False else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) na_value = np.nan
values = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype) result = values.str.match(".*(BAD[_]+).*(BAD)") expected = Series([True, na_value, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
values = Series( ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype ) result = values.str.match(".*BAD[_]+.*BAD") expected = Series([True, True, na_value, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = values.str.match("BAD[_]+.*BAD") expected = Series([False, True, na_value, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
values = Series( ["fooBAD__barBAD", "^BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype ) result = values.str.match("^BAD[_]+.*BAD") expected = Series([False, False, na_value, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = values.str.match("\\^BAD[_]+.*BAD") expected = Series([False, True, na_value, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "pat", [r"^foo|bar", r"^bar|foo", r"^foo|bar$", r"^(foo)|bar"],)def test_match_anchored_alternation(any_string_dtype, pat): # GH#66069 ser = Series(["xbar", "bar", "foo", "xfoo"], dtype=any_string_dtype) result = ser.str.match(pat) expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series([False, True, True, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_match_mixed_object(): mixed = Series( [ "aBAD_BAD", np.nan, "BAD_b_BAD", True, datetime.today(), "foo", None, 1, 2.0, ] ) result = Series(mixed).str.match(".*(BAD[_]+).*(BAD)") expected = Series([True, np.nan, True, np.nan, np.nan, False, None, np.nan, np.nan]) assert isinstance(result, Series) tm.assert_series_equal(result, expected)
def test_match_na_kwarg(any_string_dtype): # GH #6609 s = Series(["a", "b", np.nan], dtype=any_string_dtype)
result = s.str.match("a", na=False) expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series([True, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = s.str.match("a") if any_string_dtype == "str": # NaN propagates as False expected_dtype = bool na_value = False else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) na_value = np.nan
expected = Series([True, False, na_value], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_match_case_kwarg(any_string_dtype): values = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype) result = values.str.match("ab", case=False) expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series([True, True, True, True], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_match_compiled_regex(any_string_dtype): # GH#61952 expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" )
values = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype)
result = values.str.match(re.compile("ab")) expected = Series([True, False, True, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
msg = ( "Cannot both specify 'case' and pass a compiled " "regexp object with conflicting case-sensitivity" ) with pytest.raises(ValueError, match=msg): values.str.match(re.compile("ab"), case=False)
result = values.str.match(re.compile("ab", flags=re.IGNORECASE)) expected = Series([True, True, True, True], dtype=expected_dtype) tm.assert_series_equal(result, expected)
msg = ( "Cannot both specify 'flags' and pass a compiled " "regexp object with conflicting flags" ) with pytest.raises(ValueError, match=msg): values.str.match(re.compile("ab"), flags=re.IGNORECASE)
# But if the flags match you're OK values.str.match(re.compile("ab", flags=re.IGNORECASE), flags=re.IGNORECASE)
@pytest.mark.parametrize( "pat, case, exp", [ ["ab", False, [True, False]], ["Ab", True, [False, False]], ["bc", True, [False, False]], ["a[a-z]{1}", False, [True, False]], ["A[a-z]{1}", True, [False, False]], # https://github.com/pandas-dev/pandas/issues/61072 ["(bc)|(ab)", True, [True, False]], ["((bc)|(ab))", True, [True, False]], ],)def test_str_match_extra_cases(any_string_dtype, pat, case, exp): ser = Series(["abc", "Xab"], dtype=any_string_dtype) result = ser.str.match(pat, case=case)
expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series(exp, dtype=expected_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "pat, expected_data", [ (r"a(?=b)", [False, True, False, False]), (r"(?<=a)b", [False, False, False, False]), (r"a(?!b)", [True, False, False, False]), (r"(?<!b)a", [True, True, False, False]), ("ab", [False, True, False, False]), ],)def test_match_lookarounds(any_string_dtype, pat, expected_data): # https://github.com/pandas-dev/pandas/issues/60833 if any_string_dtype == "object": expected_dtype, null_result = "object", None elif any_string_dtype == "str": expected_dtype, null_result = "bool", False elif any_string_dtype == "string": expected_dtype, null_result = "boolean", pd.NA else: raise ValueError(f"Unrecognized dtype: {any_string_dtype}") ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype) result = ser.str.match(pat) expected = Series([*expected_data, null_result], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_match_end_of_string(any_string_dtype): # https://github.com/pandas-dev/pandas/pull/63613 expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" )
ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
# with dollar sign result = ser.str.match("bar$") if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow": # pyarrow (RE2) only matches $ at the very end of the line expected = Series([False, True, False, False], dtype=expected_dtype) else: # python matches $ before or after an ending newline expected = Series([False, True, False, True], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# with \Z (ensure this is translated to \z for pyarrow) result = ser.str.match(r"bar\Z") expected = Series([False, True, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# ensure finding a literal \Z still works ser = Series([r"bar\Z", "bar", "bars", "bar\n"], dtype=any_string_dtype) result = ser.str.match(r"bar\\Z") expected = Series([True, False, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# --------------------------------------------------------------------------------------# str.fullmatch# --------------------------------------------------------------------------------------
def test_fullmatch(any_string_dtype): # GH 32806 ser = Series( ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype ) result = ser.str.fullmatch(".*BAD[_]+.*BAD") if any_string_dtype == "str": # NaN propagates as False expected = Series([True, False, False, False], dtype=bool) else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series([True, False, np.nan, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_fullmatch_dollar_literal(any_string_dtype): # GH 56652 ser = Series(["foo", "foo$foo", np.nan, "foo$"], dtype=any_string_dtype) result = ser.str.fullmatch("foo\\$") if any_string_dtype == "str": # NaN propagates as False expected = Series([False, False, False, True], dtype=bool) else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series([False, False, np.nan, True], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_fullmatch_na_kwarg(any_string_dtype): ser = Series( ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype ) result = ser.str.fullmatch(".*BAD[_]+.*BAD", na=False) expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series([True, False, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_fullmatch_case_kwarg(any_string_dtype): ser = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype) expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" )
expected = Series([True, False, False, False], dtype=expected_dtype)
result = ser.str.fullmatch("ab", case=True) tm.assert_series_equal(result, expected)
expected = Series([True, True, False, False], dtype=expected_dtype)
result = ser.str.fullmatch("ab", case=False) tm.assert_series_equal(result, expected)
result = ser.str.fullmatch("ab", flags=re.IGNORECASE) tm.assert_series_equal(result, expected)
def test_fullmatch_compiled_regex(any_string_dtype): # GH#61952 expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" )
values = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype)
result = values.str.fullmatch(re.compile("ab")) expected = Series([True, False, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# TODO this currently works for pyarrow-backed dtypes but raises for python if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow": result = values.str.fullmatch(re.compile("ab"), case=False) expected = Series([True, True, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected) else: with pytest.raises( ValueError, match="cannot process flags argument with a compiled pattern" ): values.str.fullmatch(re.compile("ab"), case=False)
result = values.str.fullmatch(re.compile("ab", flags=re.IGNORECASE)) expected = Series([True, True, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
with pytest.raises( ValueError, match="cannot process flags argument with a compiled pattern" ): values.str.fullmatch(re.compile("ab"), flags=re.IGNORECASE)
@pytest.mark.parametrize( "pat, case, na, exp", # Note: keep cases in sync with # pandas/tests/extension/test_arrow.py::test_str_fullmatch [ ["abc", False, None, [True, False, False, None]], ["Abc", True, None, [False, False, False, None]], ["bc", True, None, [False, False, False, None]], ["ab", False, None, [False, False, False, None]], ["a[a-z]{2}", False, None, [True, False, False, None]], ["A[a-z]{1}", True, None, [False, False, False, None]], # GH Issue: #56652 ["abc$", False, None, [True, False, False, None]], ["abc\\$", False, None, [False, True, False, None]], ["Abc$", True, None, [False, False, False, None]], ["Abc\\$", True, None, [False, False, False, None]], # https://github.com/pandas-dev/pandas/issues/61072 ["(abc)|(abx)", True, None, [True, False, False, None]], ["((abc)|(abx))", True, None, [True, False, False, None]], ],)def test_str_fullmatch_extra_cases(any_string_dtype, pat, case, na, exp): ser = Series(["abc", "abc$", "$abc", None], dtype=any_string_dtype) result = ser.str.fullmatch(pat, case=case, na=na)
if any_string_dtype == "str": # NaN propagates as False exp[-1] = False expected_dtype = bool else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series(exp, dtype=expected_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "pat", [(r"a(?=b)"), (r"(?<=a)b"), (r"a(?!b)"), (r"(?<!b)a"), ("ab")],)def test_fullmatch_lookarounds(any_string_dtype, pat): # https://github.com/pandas-dev/pandas/issues/60833 # Note: By definition, any match with a lookaround is not a full match. if any_string_dtype == "object": expected_dtype, null_result = "object", None elif any_string_dtype == "str": expected_dtype, null_result = "bool", False elif any_string_dtype == "string": expected_dtype, null_result = "boolean", pd.NA else: raise ValueError(f"Unrecognized dtype: {any_string_dtype}") ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype) result = ser.str.fullmatch(pat) expected = Series( [False, True if pat == "ab" else False, False, False, null_result], dtype=expected_dtype, ) tm.assert_series_equal(result, expected)
def test_fullmatch_end_of_string(any_string_dtype): # https://github.com/pandas-dev/pandas/pull/63613 expected_dtype = ( np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" )
ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
# with dollar sign (for fullmatch, no difference between python and pyarrow) result = ser.str.fullmatch("bar$") expected = Series([False, True, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# with \Z (ensure this is translated to \z for pyarrow) result = ser.str.fullmatch(r"bar\Z") tm.assert_series_equal(result, expected)
# ensure finding a literal \Z still works ser = Series([r"bar\Z", "bar", "bars", "bar\n"], dtype=any_string_dtype) result = ser.str.fullmatch(r"bar\\Z") expected = Series([True, False, False, False], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# --------------------------------------------------------------------------------------# str.findall# --------------------------------------------------------------------------------------
def test_findall(any_string_dtype): ser = Series(["fooBAD__barBAD", np.nan, "foo", "BAD"], dtype=any_string_dtype) result = ser.str.findall("BAD[_]*") expected = Series([["BAD__", "BAD"], np.nan, [], ["BAD"]]) expected = _convert_na_value(ser, expected) tm.assert_series_equal(result, expected)
def test_findall_mixed_object(): ser = Series( [ "fooBAD__barBAD", np.nan, "foo", True, datetime.today(), "BAD", None, 1, 2.0, ] )
result = ser.str.findall("BAD[_]*") expected = Series( [ ["BAD__", "BAD"], np.nan, [], np.nan, np.nan, ["BAD"], None, np.nan, np.nan, ] )
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "pat, expected_data", [ (r"a(?=b)", [[], ["a"], [], []]), (r"(?<=a)b", [[], ["b"], [], []]), (r"a(?!b)", [["a", "a"], [], ["a"], []]), (r"(?<!b)a", [["a", "a"], ["a"], [], []]), ("ab", [[], ["ab"], [], []]), ],)def test_findall_lookarounds(any_string_dtype, pat, expected_data): # https://github.com/pandas-dev/pandas/issues/60833 ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype) result = ser.str.findall(pat) if any_string_dtype == "object": null_result = None elif any_string_dtype == "str": null_result = np.nan elif any_string_dtype == "string": null_result = pd.NA else: raise ValueError(f"Unrecognized dtype: {any_string_dtype}") expected = Series([*expected_data, null_result]) tm.assert_series_equal(result, expected)
def test_findall_end_of_string(any_string_dtype): # https://github.com/pandas-dev/pandas/pull/63613 ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
# with dollar sign result = ser.str.findall("bar$") expected = Series([[], ["bar"], [], ["bar"]], dtype=object) tm.assert_series_equal(result, expected)
# with \Z (ensure this is translated to \z for pyarrow) result = ser.str.findall(r"bar\Z") expected = Series([[], ["bar"], [], []], dtype=object) tm.assert_series_equal(result, expected)
# ensure finding a literal \Z still works ser = Series([r"bar\Z", "bar", "bars", "bar\n"], dtype=any_string_dtype) result = ser.str.findall(r"bar\\Z") expected = Series([["bar\\Z"], [], [], []], dtype=object) tm.assert_series_equal(result, expected)
# --------------------------------------------------------------------------------------# str.find# --------------------------------------------------------------------------------------
def test_find(any_string_dtype): ser = Series( ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF", "XXXX"], dtype=any_string_dtype ) expected_dtype = ( np.int64 if is_object_or_nan_string_dtype(any_string_dtype) else "Int64" )
result = ser.str.find("EF") expected = Series([4, 3, 1, 0, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected) expected = np.array([v.find("EF") for v in np.array(ser)], dtype=np.int64) tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
result = ser.str.rfind("EF") expected = Series([4, 5, 7, 4, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected) expected = np.array([v.rfind("EF") for v in np.array(ser)], dtype=np.int64) tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
result = ser.str.find("EF", 3) expected = Series([4, 3, 7, 4, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected) expected = np.array([v.find("EF", 3) for v in np.array(ser)], dtype=np.int64) tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
result = ser.str.rfind("EF", 3) expected = Series([4, 5, 7, 4, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected) expected = np.array([v.rfind("EF", 3) for v in np.array(ser)], dtype=np.int64) tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
result = ser.str.find("EF", 3, 6) expected = Series([4, 3, -1, 4, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected) expected = np.array([v.find("EF", 3, 6) for v in np.array(ser)], dtype=np.int64) tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
result = ser.str.rfind("EF", 3, 6) expected = Series([4, 3, -1, 4, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected) expected = np.array([v.rfind("EF", 3, 6) for v in np.array(ser)], dtype=np.int64) tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
def test_find_bad_arg_raises(any_string_dtype): ser = Series([], dtype=any_string_dtype) with pytest.raises(TypeError, match="expected a string object, not int"): ser.str.find(0)
with pytest.raises(TypeError, match="expected a string object, not int"): ser.str.rfind(0)
def test_find_nan(any_string_dtype): ser = Series( ["ABCDEFG", np.nan, "DEFGHIJEF", np.nan, "XXXX"], dtype=any_string_dtype ) if is_object_or_nan_string_dtype(any_string_dtype): expected_dtype = np.float64 item = np.nan else: expected_dtype = "Int64" item = pd.NA
result = ser.str.find("EF") expected = Series([4, item, 1, item, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = ser.str.rfind("EF") expected = Series([4, item, 7, item, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = ser.str.find("EF", 3) expected = Series([4, item, 7, item, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = ser.str.rfind("EF", 3) expected = Series([4, item, 7, item, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = ser.str.find("EF", 3, 6) expected = Series([4, item, -1, item, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = ser.str.rfind("EF", 3, 6) expected = Series([4, item, -1, item, -1], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_find_multibyte_chars(any_string_dtype): # GH#64123 - str.find should return character offsets, not byte offsets ser = Series(["ga", "Áa", "永a", "🐍a"], dtype=any_string_dtype) expected_dtype = ( np.int64 if is_object_or_nan_string_dtype(any_string_dtype) else "Int64" )
result = ser.str.find("a") expected = Series([1, 1, 1, 1], dtype=expected_dtype) tm.assert_series_equal(result, expected)
result = ser.str.find("a", start=1) tm.assert_series_equal(result, expected)
# --------------------------------------------------------------------------------------# str.translate# --------------------------------------------------------------------------------------
@pytest.mark.parametrize( "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))])def test_translate(index_or_series, any_string_dtype, infer_string): obj = index_or_series( ["abcdefg", "abcc", "cdddfg", "cdefggg"], dtype=any_string_dtype ) table = str.maketrans("abc", "cde") result = obj.str.translate(table) expected = index_or_series( ["cdedefg", "cdee", "edddfg", "edefggg"], dtype=any_string_dtype ) tm.assert_equal(result, expected)
def test_translate_mixed_object(): # Series with non-string values s = Series(["a", "b", "c", 1.2]) table = str.maketrans("abc", "cde") expected = Series(["c", "d", "e", np.nan], dtype=object) result = s.str.translate(table) tm.assert_series_equal(result, expected)
# --------------------------------------------------------------------------------------
def test_flags_kwarg(any_string_dtype): data = { "Dave": "dave@google.com", "Steve": "steve@gmail.com", "Rob": "rob@gmail.com", "Wes": np.nan, } data = Series(data, dtype=any_string_dtype)
pat = r"([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})"
result = data.str.extract(pat, flags=re.IGNORECASE, expand=True) assert result.iloc[0].tolist() == ["dave", "google", "com"]
result = data.str.match(pat, flags=re.IGNORECASE) assert result.iloc[0]
result = data.str.fullmatch(pat, flags=re.IGNORECASE) assert result.iloc[0]
result = data.str.findall(pat, flags=re.IGNORECASE) assert result.iloc[0][0] == ("dave", "google", "com")
result = data.str.count(pat, flags=re.IGNORECASE) assert result.iloc[0] == 1
msg = "has match groups" with tm.assert_produces_warning(UserWarning, match=msg): result = data.str.contains(pat, flags=re.IGNORECASE) assert result.iloc[0]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import numpy as npimport pytest
import pandas.util._test_decorators as td
from pandas import ( DataFrame, Index, MultiIndex, Series, _testing as tm,)
def test_get_dummies(any_string_dtype): s = Series(["a|b", "a|c", np.nan], dtype=any_string_dtype) result = s.str.get_dummies("|") expected = DataFrame([[1, 1, 0], [1, 0, 1], [0, 0, 0]], columns=list("abc")) tm.assert_frame_equal(result, expected)
s = Series(["a;b", "a", 7], dtype=any_string_dtype) result = s.str.get_dummies(";") expected = DataFrame([[0, 1, 1], [0, 1, 0], [1, 0, 0]], columns=list("7ab")) tm.assert_frame_equal(result, expected)
def test_get_dummies_index(): # GH9980, GH8028 idx = Index(["a|b", "a|c", "b|c"]) result = idx.str.get_dummies("|")
expected = MultiIndex.from_tuples( [(1, 1, 0), (1, 0, 1), (0, 1, 1)], names=("a", "b", "c") ) tm.assert_index_equal(result, expected)
# GH#47872@pytest.mark.parametrize( "dtype", [ np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64, bool, "Int8", "Int16", "Int32", "Int64", "boolean", ],)def test_get_dummies_with_dtype(any_string_dtype, dtype): s = Series(["a|b", "a|c", np.nan], dtype=any_string_dtype) result = s.str.get_dummies("|", dtype=dtype) expected = DataFrame( [[1, 1, 0], [1, 0, 1], [0, 0, 0]], columns=list("abc"), dtype=dtype ) tm.assert_frame_equal(result, expected)
# GH#47872@td.skip_if_no("pyarrow")@pytest.mark.parametrize( "dtype", [ "int8[pyarrow]", "uint8[pyarrow]", "int16[pyarrow]", "uint16[pyarrow]", "int32[pyarrow]", "uint32[pyarrow]", "int64[pyarrow]", "uint64[pyarrow]", "bool[pyarrow]", ],)def test_get_dummies_with_pyarrow_dtype(any_string_dtype, dtype): s = Series(["a|b", "a|c", np.nan], dtype=any_string_dtype) result = s.str.get_dummies("|", dtype=dtype) expected = DataFrame( [[1, 1, 0], [1, 0, 1], [0, 0, 0]], columns=list("abc"), dtype=dtype, ) tm.assert_frame_equal(result, expected)
# GH#47872def test_get_dummies_with_str_dtype(any_string_dtype): s = Series(["a|b", "a|c", np.nan], dtype=any_string_dtype)
msg = "Only numeric or boolean dtypes are supported for 'dtype'" with pytest.raises(ValueError, match=msg): s.str.get_dummies("|", dtype=str)
with pytest.raises(ValueError, match=msg): s.str.get_dummies("|", dtype="datetime64[ns]")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772from datetime import datetimeimport re
import numpy as npimport pytest
import pandas as pdfrom pandas import ( DataFrame, Index, MultiIndex, Series, _testing as tm,)from pandas.tests.strings import ( _convert_na_value, is_object_or_nan_string_dtype,)
@pytest.mark.parametrize("method", ["split", "rsplit"])def test_split(any_string_dtype, method): values = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
result = getattr(values.str, method)("_") exp = Series([["a", "b", "c"], ["c", "d", "e"], np.nan, ["f", "g", "h"]]) exp = _convert_na_value(values, exp) tm.assert_series_equal(result, exp)
@pytest.mark.parametrize("method", ["split", "rsplit"])def test_split_more_than_one_char(any_string_dtype, method): # more than one char values = Series(["a__b__c", "c__d__e", np.nan, "f__g__h"], dtype=any_string_dtype) result = getattr(values.str, method)("__") exp = Series([["a", "b", "c"], ["c", "d", "e"], np.nan, ["f", "g", "h"]]) exp = _convert_na_value(values, exp) tm.assert_series_equal(result, exp)
result = getattr(values.str, method)("__", expand=False) tm.assert_series_equal(result, exp)
def test_split_more_regex_split(any_string_dtype): # regex split values = Series(["a,b_c", "c_d,e", np.nan, "f,g,h"], dtype=any_string_dtype) result = values.str.split("[,_]") exp = Series([["a", "b", "c"], ["c", "d", "e"], np.nan, ["f", "g", "h"]]) exp = _convert_na_value(values, exp) tm.assert_series_equal(result, exp)
def test_split_regex(any_string_dtype): # GH 43563 # explicit regex = True split values = Series("xxxjpgzzz.jpg", dtype=any_string_dtype) result = values.str.split(r"\.jpg", regex=True) exp = Series([["xxxjpgzzz", ""]]) tm.assert_series_equal(result, exp)
def test_split_regex_explicit(any_string_dtype): # explicit regex = True split with compiled regex regex_pat = re.compile(r".jpg") values = Series("xxxjpgzzz.jpg", dtype=any_string_dtype) result = values.str.split(regex_pat) exp = Series([["xx", "zzz", ""]]) tm.assert_series_equal(result, exp)
# explicit regex = False split result = values.str.split(r"\.jpg", regex=False) exp = Series([["xxxjpgzzz.jpg"]]) tm.assert_series_equal(result, exp)
# non explicit regex split, pattern length == 1 result = values.str.split(r".") exp = Series([["xxxjpgzzz", "jpg"]]) tm.assert_series_equal(result, exp)
# non explicit regex split, pattern length != 1 result = values.str.split(r".jpg") exp = Series([["xx", "zzz", ""]]) tm.assert_series_equal(result, exp)
# regex=False with pattern compiled regex raises error with pytest.raises( ValueError, match="Cannot use a compiled regex as replacement pattern with regex=False", ): values.str.split(regex_pat, regex=False)
@pytest.mark.parametrize("expand", [None, False])@pytest.mark.parametrize("method", ["split", "rsplit"])def test_split_object_mixed(expand, method): mixed = Series(["a_b_c", np.nan, "d_e_f", True, datetime.today(), None, 1, 2.0]) result = getattr(mixed.str, method)("_", expand=expand) exp = Series( [ ["a", "b", "c"], np.nan, ["d", "e", "f"], np.nan, np.nan, None, np.nan, np.nan, ] ) assert isinstance(result, Series) tm.assert_almost_equal(result, exp)
@pytest.mark.parametrize("method", ["split", "rsplit"])@pytest.mark.parametrize("n", [None, 0])def test_split_n(any_string_dtype, method, n): s = Series(["a b", pd.NA, "b c"], dtype=any_string_dtype) expected = Series([["a", "b"], pd.NA, ["b", "c"]]) result = getattr(s.str, method)(" ", n=n) expected = _convert_na_value(s, expected) tm.assert_series_equal(result, expected)
def test_rsplit(any_string_dtype): # regex split is not supported by rsplit values = Series(["a,b_c", "c_d,e", np.nan, "f,g,h"], dtype=any_string_dtype) result = values.str.rsplit("[,_]") exp = Series([["a,b_c"], ["c_d,e"], np.nan, ["f,g,h"]]) exp = _convert_na_value(values, exp) tm.assert_series_equal(result, exp)
def test_rsplit_max_number(any_string_dtype): # setting max number of splits, make sure it's from reverse values = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype) result = values.str.rsplit("_", n=1) exp = Series([["a_b", "c"], ["c_d", "e"], np.nan, ["f_g", "h"]]) exp = _convert_na_value(values, exp) tm.assert_series_equal(result, exp)
def test_split_blank_string(any_string_dtype): # expand blank split GH 20067 values = Series([""], name="test", dtype=any_string_dtype) result = values.str.split(expand=True) exp = DataFrame([[]], dtype=any_string_dtype) # NOTE: this is NOT an empty df tm.assert_frame_equal(result, exp)
def test_split_blank_string_with_non_empty(any_string_dtype): values = Series(["a b c", "a b", "", " "], name="test", dtype=any_string_dtype) result = values.str.split(expand=True) exp = DataFrame( [ ["a", "b", "c"], ["a", "b", None], [None, None, None], [None, None, None], ], dtype=any_string_dtype, ) tm.assert_frame_equal(result, exp)
@pytest.mark.parametrize("method", ["split", "rsplit"])def test_split_noargs(any_string_dtype, method): # #1859 s = Series(["Wes McKinney", "Travis Oliphant"], dtype=any_string_dtype) result = getattr(s.str, method)() expected = ["Travis", "Oliphant"] assert result[1] == expected
@pytest.mark.parametrize( "data, pat", [ (["bd asdf jfg", "kjasdflqw asdfnfk"], None), (["bd asdf jfg", "kjasdflqw asdfnfk"], "asdf"), (["bd_asdf_jfg", "kjasdflqw_asdfnfk"], "_"), ],)@pytest.mark.parametrize("n", [-1, 0])def test_split_maxsplit(data, pat, any_string_dtype, n): # re.split 0, str.split -1 s = Series(data, dtype=any_string_dtype)
result = s.str.split(pat=pat, n=n) xp = s.str.split(pat=pat) tm.assert_series_equal(result, xp)
@pytest.mark.parametrize( "data, pat, expected_val", [ ( ["split once", "split once too!"], None, "once too!", ), ( ["split_once", "split_once_too!"], "_", "once_too!", ), ],)def test_split_no_pat_with_nonzero_n(data, pat, expected_val, any_string_dtype): s = Series(data, dtype=any_string_dtype) result = s.str.split(pat=pat, n=1) expected = Series({0: ["split", "once"], 1: ["split", expected_val]}) tm.assert_series_equal(expected, result, check_index_type=False)
def test_split_to_dataframe_no_splits(any_string_dtype): s = Series(["nosplit", "alsonosplit"], dtype=any_string_dtype) result = s.str.split("_", expand=True) exp = DataFrame({0: Series(["nosplit", "alsonosplit"], dtype=any_string_dtype)}) tm.assert_frame_equal(result, exp)
def test_split_to_dataframe(any_string_dtype): s = Series(["some_equal_splits", "with_no_nans"], dtype=any_string_dtype) result = s.str.split("_", expand=True) exp = DataFrame( {0: ["some", "with"], 1: ["equal", "no"], 2: ["splits", "nans"]}, dtype=any_string_dtype, ) tm.assert_frame_equal(result, exp)
def test_split_to_dataframe_unequal_splits(any_string_dtype): s = Series( ["some_unequal_splits", "one_of_these_things_is_not"], dtype=any_string_dtype ) result = s.str.split("_", expand=True) exp = DataFrame( { 0: ["some", "one"], 1: ["unequal", "of"], 2: ["splits", "these"], 3: [None, "things"], 4: [None, "is"], 5: [None, "not"], }, dtype=any_string_dtype, ) tm.assert_frame_equal(result, exp)
def test_split_to_dataframe_with_index(any_string_dtype): s = Series( ["some_splits", "with_index"], index=["preserve", "me"], dtype=any_string_dtype ) result = s.str.split("_", expand=True) exp = DataFrame( {0: ["some", "with"], 1: ["splits", "index"]}, index=["preserve", "me"], dtype=any_string_dtype, ) tm.assert_frame_equal(result, exp)
with pytest.raises(ValueError, match="expand must be"): s.str.split("_", expand="not_a_boolean")
def test_split_to_multiindex_expand_no_splits(): # https://github.com/pandas-dev/pandas/issues/23677
idx = Index(["nosplit", "alsonosplit", np.nan]) result = idx.str.split("_", expand=True) exp = idx tm.assert_index_equal(result, exp) assert result.nlevels == 1
def test_split_to_multiindex_expand(): idx = Index(["some_equal_splits", "with_no_nans", np.nan, None]) result = idx.str.split("_", expand=True) exp = MultiIndex.from_tuples( [ ("some", "equal", "splits"), ("with", "no", "nans"), [np.nan, np.nan, np.nan], [None, None, None], ] ) tm.assert_index_equal(result, exp) assert result.nlevels == 3
def test_split_to_multiindex_expand_unequal_splits(): idx = Index(["some_unequal_splits", "one_of_these_things_is_not", np.nan, None]) result = idx.str.split("_", expand=True) exp = MultiIndex.from_tuples( [ ("some", "unequal", "splits", np.nan, np.nan, np.nan), ("one", "of", "these", "things", "is", "not"), (np.nan, np.nan, np.nan, np.nan, np.nan, np.nan), (None, None, None, None, None, None), ] ) tm.assert_index_equal(result, exp) assert result.nlevels == 6
with pytest.raises(ValueError, match="expand must be"): idx.str.split("_", expand="not_a_boolean")
@pytest.mark.parametrize( "pat, expected_data", [ (r"a(?=b)", [["aa"], ["", "b"], ["ba"], ["bb"]]), (r"(?<=a)b", [["aa"], ["a", ""], ["ba"], ["bb"]]), (r"a(?!b)", [["", "", ""], ["ab"], ["b", ""], ["bb"]]), (r"(?<!b)a", [["", "", ""], ["", "b"], ["ba"], ["bb"]]), ("ab", [["aa"], ["", ""], ["ba"], ["bb"]]), ],)def test_split_lookarounds(any_string_dtype, pat, expected_data): # https://github.com/pandas-dev/pandas/issues/60833 ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype) result = ser.str.split(pat, regex=True) if any_string_dtype == "object": null_result = None elif any_string_dtype == "str": null_result = np.nan elif any_string_dtype == "string": null_result = pd.NA else: raise ValueError(f"Unrecognized dtype: {any_string_dtype}") expected = Series([*expected_data, null_result]) tm.assert_series_equal(result, expected)
def test_split_regex_end_of_string(any_string_dtype): # https://github.com/pandas-dev/pandas/pull/63613 ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
# with dollar sign result = ser.str.split("r$", regex=True) expected = Series([["baz"], ["ba", ""], ["bars"], ["ba", "\n"]], dtype=object) tm.assert_series_equal(result, expected)
# with \Z (ensure this is translated to \z for pyarrow) result = ser.str.split(r"r\Z", regex=True) expected = Series([["baz"], ["ba", ""], ["bars"], ["bar\n"]], dtype=object) tm.assert_series_equal(result, expected)
# ensure finding a literal \Z still works ser = Series([r"bar\Z", "bar", r"bar\Zs", "bar\n"], dtype=any_string_dtype) result = ser.str.split(r"r\\Z", regex=True) expected = Series([["ba", ""], ["bar"], ["ba", "s"], ["bar\n"]], dtype=object) tm.assert_series_equal(result, expected)
def test_rsplit_to_dataframe_expand_no_splits(any_string_dtype): s = Series(["nosplit", "alsonosplit"], dtype=any_string_dtype) result = s.str.rsplit("_", expand=True) exp = DataFrame({0: Series(["nosplit", "alsonosplit"])}, dtype=any_string_dtype) tm.assert_frame_equal(result, exp)
def test_rsplit_to_dataframe_expand(any_string_dtype): s = Series(["some_equal_splits", "with_no_nans"], dtype=any_string_dtype) result = s.str.rsplit("_", expand=True) exp = DataFrame( {0: ["some", "with"], 1: ["equal", "no"], 2: ["splits", "nans"]}, dtype=any_string_dtype, ) tm.assert_frame_equal(result, exp)
result = s.str.rsplit("_", expand=True, n=2) exp = DataFrame( {0: ["some", "with"], 1: ["equal", "no"], 2: ["splits", "nans"]}, dtype=any_string_dtype, ) tm.assert_frame_equal(result, exp)
result = s.str.rsplit("_", expand=True, n=1) exp = DataFrame( {0: ["some_equal", "with_no"], 1: ["splits", "nans"]}, dtype=any_string_dtype ) tm.assert_frame_equal(result, exp)
def test_rsplit_to_dataframe_expand_with_index(any_string_dtype): s = Series( ["some_splits", "with_index"], index=["preserve", "me"], dtype=any_string_dtype ) result = s.str.rsplit("_", expand=True) exp = DataFrame( {0: ["some", "with"], 1: ["splits", "index"]}, index=["preserve", "me"], dtype=any_string_dtype, ) tm.assert_frame_equal(result, exp)
def test_rsplit_to_multiindex_expand_no_split(): idx = Index(["nosplit", "alsonosplit"]) result = idx.str.rsplit("_", expand=True) exp = idx tm.assert_index_equal(result, exp) assert result.nlevels == 1
def test_rsplit_to_multiindex_expand(): idx = Index(["some_equal_splits", "with_no_nans"]) result = idx.str.rsplit("_", expand=True) exp = MultiIndex.from_tuples([("some", "equal", "splits"), ("with", "no", "nans")]) tm.assert_index_equal(result, exp) assert result.nlevels == 3
def test_rsplit_to_multiindex_expand_n(): idx = Index(["some_equal_splits", "with_no_nans"]) result = idx.str.rsplit("_", expand=True, n=1) exp = MultiIndex.from_tuples([("some_equal", "splits"), ("with_no", "nans")]) tm.assert_index_equal(result, exp) assert result.nlevels == 2
def test_split_nan_expand(any_string_dtype): # gh-18450 s = Series(["foo,bar,baz", np.nan], dtype=any_string_dtype) result = s.str.split(",", expand=True) exp = DataFrame( [["foo", "bar", "baz"], [np.nan, np.nan, np.nan]], dtype=any_string_dtype ) tm.assert_frame_equal(result, exp)
# check that these are actually np.nan/pd.NA and not None # TODO see GH 18463 # tm.assert_frame_equal does not differentiate if is_object_or_nan_string_dtype(any_string_dtype): assert all(np.isnan(x) for x in result.iloc[1]) else: assert all(x is pd.NA for x in result.iloc[1])
def test_split_with_name_series(any_string_dtype): # GH 12617
# should preserve name s = Series(["a,b", "c,d"], name="xxx", dtype=any_string_dtype) res = s.str.split(",") exp = Series([["a", "b"], ["c", "d"]], name="xxx") tm.assert_series_equal(res, exp)
res = s.str.split(",", expand=True) exp = DataFrame([["a", "b"], ["c", "d"]], dtype=any_string_dtype) tm.assert_frame_equal(res, exp)
def test_split_with_name_index(): # GH 12617 idx = Index(["a,b", "c,d"], name="xxx") res = idx.str.split(",") exp = Index([["a", "b"], ["c", "d"]], name="xxx") assert res.nlevels == 1 tm.assert_index_equal(res, exp)
res = idx.str.split(",", expand=True) exp = MultiIndex.from_tuples([("a", "b"), ("c", "d")]) assert res.nlevels == 2 tm.assert_index_equal(res, exp)
@pytest.mark.parametrize( "method, exp", [ [ "partition", [ ("a", "__", "b__c"), ("c", "__", "d__e"), np.nan, ("f", "__", "g__h"), None, ], ], [ "rpartition", [ ("a__b", "__", "c"), ("c__d", "__", "e"), np.nan, ("f__g", "__", "h"), None, ], ], ],)def test_partition_series_more_than_one_char(method, exp, any_string_dtype): # https://github.com/pandas-dev/pandas/issues/23558 # more than one char s = Series(["a__b__c", "c__d__e", np.nan, "f__g__h", None], dtype=any_string_dtype) result = getattr(s.str, method)("__", expand=False) expected = Series(exp) expected = _convert_na_value(s, expected) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "method, exp", [ [ "partition", [("a", " ", "b c"), ("c", " ", "d e"), np.nan, ("f", " ", "g h"), None], ], [ "rpartition", [("a b", " ", "c"), ("c d", " ", "e"), np.nan, ("f g", " ", "h"), None], ], ],)def test_partition_series_none(any_string_dtype, method, exp): # https://github.com/pandas-dev/pandas/issues/23558 # None s = Series(["a b c", "c d e", np.nan, "f g h", None], dtype=any_string_dtype) result = getattr(s.str, method)(expand=False) expected = Series(exp) expected = _convert_na_value(s, expected) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "method, exp", [ [ "partition", [("abc", "", ""), ("cde", "", ""), np.nan, ("fgh", "", ""), None], ], [ "rpartition", [("", "", "abc"), ("", "", "cde"), np.nan, ("", "", "fgh"), None], ], ],)def test_partition_series_not_split(any_string_dtype, method, exp): # https://github.com/pandas-dev/pandas/issues/23558 # Not split s = Series(["abc", "cde", np.nan, "fgh", None], dtype=any_string_dtype) result = getattr(s.str, method)("_", expand=False) expected = Series(exp) expected = _convert_na_value(s, expected) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "method, exp", [ [ "partition", [("a", "_", "b_c"), ("c", "_", "d_e"), np.nan, ("f", "_", "g_h")], ], [ "rpartition", [("a_b", "_", "c"), ("c_d", "_", "e"), np.nan, ("f_g", "_", "h")], ], ],)def test_partition_series_unicode(any_string_dtype, method, exp): # https://github.com/pandas-dev/pandas/issues/23558 # unicode s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
result = getattr(s.str, method)("_", expand=False) expected = Series(exp) expected = _convert_na_value(s, expected) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("method", ["partition", "rpartition"])def test_partition_series_stdlib(any_string_dtype, method): # https://github.com/pandas-dev/pandas/issues/23558 # compare to standard lib s = Series(["A_B_C", "B_C_D", "E_F_G", "EFGHEF"], dtype=any_string_dtype) result = getattr(s.str, method)("_", expand=False).tolist() assert result == [getattr(v, method)("_") for v in s]
@pytest.mark.parametrize( "method, exp", [ [ "partition", [("a", "_", "b_c"), ("c", "_", "d_e"), ("f", "_", "g_h"), np.nan, None], ], [ "rpartition", [("a_b", "_", "c"), ("c_d", "_", "e"), ("f_g", "_", "h"), np.nan, None], ], ],)def test_partition_index(method, exp): # https://github.com/pandas-dev/pandas/issues/23558
values = Index(["a_b_c", "c_d_e", "f_g_h", np.nan, None])
result = getattr(values.str, method)("_", expand=False) exp = Index(np.array(exp, dtype=object), dtype=object) tm.assert_index_equal(result, exp) assert result.nlevels == 1
@pytest.mark.parametrize( "method, exp", [ [ "partition", { 0: ["a", "c", np.nan, "f", None], 1: ["_", "_", np.nan, "_", None], 2: ["b_c", "d_e", np.nan, "g_h", None], }, ], [ "rpartition", { 0: ["a_b", "c_d", np.nan, "f_g", None], 1: ["_", "_", np.nan, "_", None], 2: ["c", "e", np.nan, "h", None], }, ], ],)def test_partition_to_dataframe(any_string_dtype, method, exp): # https://github.com/pandas-dev/pandas/issues/23558
s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h", None], dtype=any_string_dtype) result = getattr(s.str, method)("_") expected = DataFrame( exp, dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize( "method, exp", [ [ "partition", { 0: ["a", "c", np.nan, "f", None], 1: ["_", "_", np.nan, "_", None], 2: ["b_c", "d_e", np.nan, "g_h", None], }, ], [ "rpartition", { 0: ["a_b", "c_d", np.nan, "f_g", None], 1: ["_", "_", np.nan, "_", None], 2: ["c", "e", np.nan, "h", None], }, ], ],)def test_partition_to_dataframe_from_series(any_string_dtype, method, exp): # https://github.com/pandas-dev/pandas/issues/23558 s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h", None], dtype=any_string_dtype) result = getattr(s.str, method)("_", expand=True) expected = DataFrame( exp, dtype=any_string_dtype, ) tm.assert_frame_equal(result, expected)
def test_partition_with_name(any_string_dtype): # GH 12617
s = Series(["a,b", "c,d"], name="xxx", dtype=any_string_dtype) result = s.str.partition(",") expected = DataFrame( {0: ["a", "c"], 1: [",", ","], 2: ["b", "d"]}, dtype=any_string_dtype ) tm.assert_frame_equal(result, expected)
def test_partition_with_name_expand(any_string_dtype): # GH 12617 # should preserve name s = Series(["a,b", "c,d"], name="xxx", dtype=any_string_dtype) result = s.str.partition(",", expand=False) expected = Series([("a", ",", "b"), ("c", ",", "d")], name="xxx") tm.assert_series_equal(result, expected)
def test_partition_index_with_name(): idx = Index(["a,b", "c,d"], name="xxx") result = idx.str.partition(",") expected = MultiIndex.from_tuples([("a", ",", "b"), ("c", ",", "d")]) assert result.nlevels == 3 tm.assert_index_equal(result, expected)
def test_partition_index_with_name_expand_false(): idx = Index(["a,b", "c,d"], name="xxx") # should preserve name result = idx.str.partition(",", expand=False) expected = Index(np.array([("a", ",", "b"), ("c", ",", "d")]), name="xxx") assert result.nlevels == 1 tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("method", ["partition", "rpartition"])def test_partition_sep_kwarg(any_string_dtype, method): # GH 22676; depr kwarg "pat" in favor of "sep" s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
expected = getattr(s.str, method)(sep="_") result = getattr(s.str, method)("_") tm.assert_frame_equal(result, expected)
def test_get(): ser = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"]) result = ser.str.split("_").str.get(1) expected = Series(["b", "d", np.nan, "g"], dtype=object) tm.assert_series_equal(result, expected)
def test_get_mixed_object(): ser = Series(["a_b_c", np.nan, "c_d_e", True, datetime.today(), None, 1, 2.0]) result = ser.str.split("_").str.get(1) expected = Series( ["b", np.nan, "d", np.nan, np.nan, None, np.nan, np.nan], dtype=object ) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("idx", [2, -3])def test_get_bounds(idx): ser = Series(["1_2_3_4_5", "6_7_8_9_10", "11_12"]) result = ser.str.split("_").str.get(idx) expected = Series(["3", "8", np.nan], dtype=object) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "idx, exp", [[2, [3, 3, np.nan, "b"]], [-1, [3, 3, np.nan, np.nan]]])def test_get_complex(idx, exp): # GH 20671, getting value not in dict raising `KeyError` ser = Series([(1, 2, 3), [1, 2, 3], {1, 2, 3}, {1: "a", 2: "b", 3: "c"}])
result = ser.str.get(idx) expected = Series(exp) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("to_type", [tuple, list, np.array])def test_get_complex_nested(to_type): ser = Series([to_type([to_type([1, 2])])])
result = ser.str.get(0) expected = Series([to_type([1, 2])]) tm.assert_series_equal(result, expected)
result = ser.str.get(1) expected = Series([np.nan]) tm.assert_series_equal(result, expected)
def test_get_strings(any_string_dtype): ser = Series(["a", "ab", np.nan, "abc"], dtype=any_string_dtype) result = ser.str.get(2) expected = Series([np.nan, np.nan, np.nan, "c"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import numpy as npimport pytest
from pandas._libs import lib
from pandas import ( NA, DataFrame, Series, _testing as tm,)
def test_string_array(nullable_string_dtype, any_string_method): method_name, args, kwargs = any_string_method
data = ["a", "bb", np.nan, "ccc"] a = Series(data, dtype=object) b = Series(data, dtype=nullable_string_dtype)
if method_name == "decode": with pytest.raises(TypeError, match="a bytes-like object is required"): getattr(b.str, method_name)(*args, **kwargs) return
expected = getattr(a.str, method_name)(*args, **kwargs) result = getattr(b.str, method_name)(*args, **kwargs)
if isinstance(expected, Series): if expected.dtype == "object" and lib.is_string_array( expected.dropna().values, ): assert result.dtype == nullable_string_dtype result = result.astype(object)
elif expected.dtype == "object" and lib.is_bool_array( expected.values, skipna=True ): assert result.dtype == "boolean" expected = expected.astype("boolean")
elif expected.dtype == "bool": assert result.dtype == "boolean" result = result.astype("bool")
elif expected.dtype == "float" and expected.isna().any(): assert result.dtype == "Int64" result = result.astype("float")
if expected.dtype == object: # GH#18463 expected[expected.isna()] = NA
elif isinstance(expected, DataFrame): columns = expected.select_dtypes(include="object").columns assert all(result[columns].dtypes == nullable_string_dtype) result[columns] = result[columns].astype(object) expected[columns] = expected[columns].fillna(NA) # GH#18463
tm.assert_equal(result, expected)
@pytest.mark.parametrize( "method,expected", [ ("count", [2, None]), ("find", [0, None]), ("index", [0, None]), ("rindex", [2, None]), ],)def test_string_array_numeric_integer_array(nullable_string_dtype, method, expected): s = Series(["aba", None], dtype=nullable_string_dtype) result = getattr(s.str, method)("a") expected = Series(expected, dtype="Int64") tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "method,expected", [ ("isdigit", [False, None, True]), ("isalpha", [True, None, False]), ("isascii", [True, None, True]), ("isalnum", [True, None, True]), ("isnumeric", [False, None, True]), ],)def test_string_array_boolean_array(nullable_string_dtype, method, expected): s = Series(["a", None, "1"], dtype=nullable_string_dtype) result = getattr(s.str, method)() expected = Series(expected, dtype="boolean") tm.assert_series_equal(result, expected)
def test_string_array_extract(nullable_string_dtype): # https://github.com/pandas-dev/pandas/issues/30969 # Only expand=False & multiple groups was failing
a = Series(["a1", "b2", "cc"], dtype=nullable_string_dtype) b = Series(["a1", "b2", "cc"], dtype="object") pat = r"(\w)(\d)"
result = a.str.extract(pat, expand=False) expected = b.str.extract(pat, expand=False) expected = expected.fillna(NA) # GH#18463 assert all(result.dtypes == nullable_string_dtype)
result = result.astype(object) tm.assert_equal(result, expected)
@pytest.mark.parametrize( "values, width, expected", [ (["a", "ab", "abc", None], 4, ["000a", "00ab", "0abc", None]), (["1", "-1", "+1", None], 4, ["0001", "-001", "+001", None]), (["1234", "-1234"], 3, ["1234", "-1234"]), ],)def test_string_array_zfill(nullable_string_dtype, values, width, expected): # GH #61485 s = Series(values, dtype=nullable_string_dtype) result = s.str.zfill(width) expected = Series(expected, dtype=nullable_string_dtype) tm.assert_series_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952from datetime import ( datetime, timedelta,)
import numpy as npimport pytest
from pandas.compat import pa_version_under21p0
from pandas import ( NA, DataFrame, Index, MultiIndex, Series, StringDtype, option_context,)import pandas._testing as tmfrom pandas.core.arrays._arrow_string_mixins import ArrowStringArrayMixinfrom pandas.core.strings.accessor import StringMethodsfrom pandas.tests.strings import is_object_or_nan_string_dtype
@pytest.mark.parametrize("pattern", [0, True, Series(["foo", "bar"])])def test_startswith_endswith_non_str_patterns(pattern): # GH3485 ser = Series(["foo", "bar"]) msg = f"expected a string or tuple, not {type(pattern).__name__}" with pytest.raises(TypeError, match=msg): ser.str.startswith(pattern) with pytest.raises(TypeError, match=msg): ser.str.endswith(pattern)
def test_iter_raises(): # GH 54173 ser = Series(["foo", "bar"]) with pytest.raises(TypeError, match="'StringMethods' object is not iterable"): iter(ser.str)
# test integer/float dtypes (inferred by constructor) and mixed
def test_count(any_string_dtype): ser = Series(["foo", "foofoo", np.nan, "foooofooofommmfoo"], dtype=any_string_dtype) result = ser.str.count("f[o]+") if is_object_or_nan_string_dtype(any_string_dtype): expected_dtype = np.float64 item = np.nan else: expected_dtype = "Int64" item = NA
expected = Series([1, 2, item, 4], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_count_mixed_object(): ser = Series( ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0], dtype=object, ) result = ser.str.count("a") expected = Series([1, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, np.nan]) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "pat, expected_data", [ (r"a(?=b)", [0, 1, 0, 0, None]), (r"(?<=a)b", [0, 1, 0, 0, None]), (r"a(?!b)", [2, 0, 1, 0, None]), (r"(?<!b)a", [2, 1, 0, 0, None]), ("ab", [0, 1, 0, 0, None]), ],)def test_count_lookarounds(any_string_dtype, pat, expected_data): # https://github.com/pandas-dev/pandas/issues/60833 expected_dtype = ( "float64" if is_object_or_nan_string_dtype(any_string_dtype) else "Int64" ) ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype) result = ser.str.count(pat) expected = Series(expected_data, dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_count_end_of_string(any_string_dtype): # https://github.com/pandas-dev/pandas/pull/63613 expected_dtype = ( "int64" if is_object_or_nan_string_dtype(any_string_dtype) else "Int64" )
ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
# with dollar sign result = ser.str.count("bar$") if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow": # pyarrow (RE2) only matches $ at the very end of the line expected = Series([0, 1, 0, 0], dtype=expected_dtype) else: # python matches $ before or after an ending newline expected = Series([0, 1, 0, 1], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# with \Z (ensure this is translated to \z for pyarrow) result = ser.str.count(r"bar\Z") expected = Series([0, 1, 0, 0], dtype=expected_dtype) tm.assert_series_equal(result, expected)
# ensure finding a literal \Z still works ser = Series([r"bar\Z", "bar", "bars", "bar\n"], dtype=any_string_dtype) result = ser.str.count(r"bar\\Z") expected = Series([1, 0, 0, 0], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_repeat(any_string_dtype): ser = Series(["a", "b", np.nan, "c", np.nan, "d"], dtype=any_string_dtype)
result = ser.str.repeat(3) expected = Series( ["aaa", "bbb", np.nan, "ccc", np.nan, "ddd"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
result = ser.str.repeat([1, 2, 3, 4, 5, 6]) expected = Series( ["a", "bb", np.nan, "cccc", np.nan, "dddddd"], dtype=any_string_dtype ) tm.assert_series_equal(result, expected)
def test_repeat_mixed_object(): ser = Series(["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0]) result = ser.str.repeat(3) expected = Series( ["aaa", np.nan, "bbb", np.nan, np.nan, "foofoofoo", None, np.nan, np.nan], dtype=object, ) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("arg, repeat", [[None, 4], ["b", None]])def test_repeat_with_null(any_string_dtype, arg, repeat): # GH: 31632 ser = Series(["a", arg], dtype=any_string_dtype) result = ser.str.repeat([3, repeat]) expected = Series(["aaa", None], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_empty_str_methods(any_string_dtype): empty_str = empty = Series(dtype=any_string_dtype) empty_inferred_str = Series(dtype="str") if is_object_or_nan_string_dtype(any_string_dtype): empty_int = Series(dtype="int64") empty_bool = Series(dtype=bool) else: empty_int = Series(dtype="Int64") empty_bool = Series(dtype="boolean") empty_object = Series(dtype=object) empty_bytes = Series(dtype=object) empty_df = DataFrame()
# GH7241 # (extract) on empty series
tm.assert_series_equal(empty_str, empty.str.cat(empty)) assert "" == empty.str.cat() tm.assert_series_equal(empty_str, empty.str.title()) tm.assert_series_equal(empty_int, empty.str.count("a")) tm.assert_series_equal(empty_bool, empty.str.contains("a")) tm.assert_series_equal(empty_bool, empty.str.startswith("a")) tm.assert_series_equal(empty_bool, empty.str.endswith("a")) tm.assert_series_equal(empty_str, empty.str.lower()) tm.assert_series_equal(empty_str, empty.str.upper()) tm.assert_series_equal(empty_str, empty.str.replace("a", "b")) tm.assert_series_equal(empty_str, empty.str.repeat(3)) tm.assert_series_equal(empty_bool, empty.str.match("^a")) tm.assert_frame_equal( DataFrame(columns=range(1), dtype=any_string_dtype), empty.str.extract("()", expand=True), ) tm.assert_frame_equal( DataFrame(columns=range(2), dtype=any_string_dtype), empty.str.extract("()()", expand=True), ) tm.assert_series_equal(empty_str, empty.str.extract("()", expand=False)) tm.assert_frame_equal( DataFrame(columns=range(2), dtype=any_string_dtype), empty.str.extract("()()", expand=False), ) tm.assert_frame_equal(empty_df.set_axis([], axis=1), empty.str.get_dummies()) tm.assert_series_equal(empty_str, empty_str.str.join("")) tm.assert_series_equal(empty_int, empty.str.len()) tm.assert_series_equal(empty_object, empty_str.str.findall("a")) tm.assert_series_equal(empty_int, empty.str.find("a")) tm.assert_series_equal(empty_int, empty.str.rfind("a")) tm.assert_series_equal(empty_str, empty.str.pad(42)) tm.assert_series_equal(empty_str, empty.str.center(42)) tm.assert_series_equal(empty_object, empty.str.split("a")) tm.assert_series_equal(empty_object, empty.str.rsplit("a")) tm.assert_series_equal(empty_object, empty.str.partition("a", expand=False)) tm.assert_frame_equal(empty_df, empty.str.partition("a")) tm.assert_series_equal(empty_object, empty.str.rpartition("a", expand=False)) tm.assert_frame_equal(empty_df, empty.str.rpartition("a")) tm.assert_series_equal(empty_str, empty.str.slice(stop=1)) tm.assert_series_equal(empty_str, empty.str.slice(step=1)) tm.assert_series_equal(empty_str, empty.str.strip()) tm.assert_series_equal(empty_str, empty.str.lstrip()) tm.assert_series_equal(empty_str, empty.str.rstrip()) tm.assert_series_equal(empty_str, empty.str.wrap(42)) tm.assert_series_equal(empty_str, empty.str.get(0)) tm.assert_series_equal(empty_inferred_str, empty_bytes.str.decode("ascii")) tm.assert_series_equal(empty_bytes, empty.str.encode("ascii")) # ismethods should always return boolean (GH 29624) tm.assert_series_equal(empty_bool, empty.str.isalnum()) tm.assert_series_equal(empty_bool, empty.str.isalpha()) tm.assert_series_equal(empty_bool, empty.str.isascii()) tm.assert_series_equal(empty_bool, empty.str.isdigit()) tm.assert_series_equal(empty_bool, empty.str.isspace()) tm.assert_series_equal(empty_bool, empty.str.islower()) tm.assert_series_equal(empty_bool, empty.str.isupper()) tm.assert_series_equal(empty_bool, empty.str.istitle()) tm.assert_series_equal(empty_bool, empty.str.isnumeric()) tm.assert_series_equal(empty_bool, empty.str.isdecimal()) tm.assert_series_equal(empty_str, empty.str.capitalize()) tm.assert_series_equal(empty_str, empty.str.swapcase()) tm.assert_series_equal(empty_str, empty.str.normalize("NFC"))
table = str.maketrans("a", "b") tm.assert_series_equal(empty_str, empty.str.translate(table))
@pytest.mark.parametrize( "method, expected", [ ("isascii", [True, True, True, True, True, True, True, True, True, True]), ("isalnum", [True, True, True, True, True, False, True, True, False, False]), ("isalpha", [True, True, True, False, False, False, True, False, False, False]), ( "isdigit", [False, False, False, True, False, False, False, True, False, False], ), ( "isnumeric", [False, False, False, True, False, False, False, True, False, False], ), ( "isspace", [False, False, False, False, False, False, False, False, False, True], ), ( "islower", [False, True, False, False, False, False, False, False, False, False], ), ( "isupper", [True, False, False, False, True, False, True, False, False, False], ), ( "istitle", [True, False, True, False, True, False, False, False, False, False], ), ],)def test_ismethods(method, expected, any_string_dtype): ser = Series( ["A", "b", "Xy", "4", "3A", "", "TT", "55", "-", " "], dtype=any_string_dtype ) expected_dtype = ( "bool" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series(expected, dtype=expected_dtype) result = getattr(ser.str, method)() tm.assert_series_equal(result, expected)
# compare with standard library expected_stdlib = [getattr(item, method)() for item in ser] assert list(result) == expected_stdlib
# with missing value ser.iloc[[1, 2, 3, 4]] = np.nan result = getattr(ser.str, method)() if ser.dtype == "object": expected = expected.astype(object) expected.iloc[[1, 2, 3, 4]] = np.nan elif ser.dtype == "str": # NaN propagates as False expected.iloc[[1, 2, 3, 4]] = False else: # nullable dtypes propagate NaN expected.iloc[[1, 2, 3, 4]] = np.nan
@pytest.mark.parametrize( "method, expected", [ ("isnumeric", [False, True, True, True, False, True, True, False]), ("isdecimal", [False, True, False, False, False, False, True, False]), ("isdigit", [False, True, True, False, False, False, True, False]), ],)def test_isnumeric_unicode(method, expected, any_string_dtype): # 0x00bc: ¼ VULGAR FRACTION ONE QUARTER # 0x2605: ★ not number # 0x1378: ፸ ETHIOPIC NUMBER SEVENTY # 0xFF13: 3 Em 3 # noqa: RUF003 ser = Series( ["A", "3", "³", "¼", "★", "፸", "3", "four"], # noqa: RUF001 dtype=any_string_dtype, ) expected_dtype = ( "bool" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series(expected, dtype=expected_dtype) if ( method == "isdigit" and isinstance(ser.dtype, StringDtype) and ser.dtype.storage == "pyarrow" and not pa_version_under21p0 ): # known difference in behavior between python and pyarrow unicode handling # pyarrow 21+ considers ¼ and ፸ as a digit, while python does not expected.iloc[3] = True expected.iloc[5] = True
result = getattr(ser.str, method)() tm.assert_series_equal(result, expected)
# compare with standard library # (only for non-pyarrow storage given the above differences) if any_string_dtype == "object" or ( isinstance(any_string_dtype, StringDtype) and any_string_dtype.storage == "python" ): expected = [getattr(item, method)() for item in ser] assert list(result) == expected
@pytest.mark.parametrize( "method, expected", [ ("isnumeric", [False, np.nan, True, False, np.nan, True, False]), ("isdecimal", [False, np.nan, False, False, np.nan, True, False]), ],)def test_isnumeric_unicode_missing(method, expected, any_string_dtype): values = ["A", np.nan, "¼", "★", np.nan, "3", "four"] # noqa: RUF001 ser = Series(values, dtype=any_string_dtype) if any_string_dtype == "str": # NaN propagates as False expected = Series(expected, dtype=object).fillna(False).astype(bool) else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series(expected, dtype=expected_dtype) result = getattr(ser.str, method)() tm.assert_series_equal(result, expected)
def test_split_join_roundtrip(any_string_dtype): ser = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype) result = ser.str.split("_").str.join("_") expected = ser.astype(object) tm.assert_series_equal(result, expected)
def test_split_join_roundtrip_mixed_object(): ser = Series( ["a_b", np.nan, "asdf_cas_asdf", True, datetime.today(), "foo", None, 1, 2.0] ) result = ser.str.split("_").str.join("_") expected = Series( ["a_b", np.nan, "asdf_cas_asdf", np.nan, np.nan, "foo", None, np.nan, np.nan], dtype=object, ) tm.assert_series_equal(result, expected)
def test_len(any_string_dtype): ser = Series( ["foo", "fooo", "fooooo", np.nan, "fooooooo", "foo\n", "あ"], dtype=any_string_dtype, ) result = ser.str.len() if is_object_or_nan_string_dtype(any_string_dtype): expected_dtype = "float64" item = np.nan else: expected_dtype = "Int64" item = NA expected = Series([3, 4, 6, item, 8, 4, 1], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_len_mixed(): ser = Series( ["a_b", np.nan, "asdf_cas_asdf", True, datetime.today(), "foo", None, 1, 2.0] ) result = ser.str.len() expected = Series([3, np.nan, 13, np.nan, np.nan, 3, np.nan, np.nan, np.nan]) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "method,sub,start,end,expected", [ ("index", "EF", None, None, [4, 3, 1, 0]), ("rindex", "EF", None, None, [4, 5, 7, 4]), ("index", "EF", 3, None, [4, 3, 7, 4]), ("rindex", "EF", 3, None, [4, 5, 7, 4]), ("index", "E", 4, 8, [4, 5, 7, 4]), ("rindex", "E", 0, 5, [4, 3, 1, 4]), ],)def test_index(method, sub, start, end, index_or_series, any_string_dtype, expected): obj = index_or_series( ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"], dtype=any_string_dtype ) expected_dtype = ( np.int64 if is_object_or_nan_string_dtype(any_string_dtype) else "Int64" ) expected = index_or_series(expected, dtype=expected_dtype)
result = getattr(obj.str, method)(sub, start, end)
if index_or_series is Series: tm.assert_series_equal(result, expected) else: tm.assert_index_equal(result, expected)
# compare with standard library expected = [getattr(item, method)(sub, start, end) for item in obj] assert list(result) == expected
def test_index_not_found_raises(index_or_series, any_string_dtype): obj = index_or_series( ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"], dtype=any_string_dtype ) with pytest.raises(ValueError, match="substring not found"): obj.str.index("DE")
@pytest.mark.parametrize("method", ["index", "rindex"])def test_index_wrong_type_raises(index_or_series, any_string_dtype, method): obj = index_or_series([], dtype=any_string_dtype) msg = "expected a string object, not int"
with pytest.raises(TypeError, match=msg): getattr(obj.str, method)(0)
@pytest.mark.parametrize( "method, exp", [ ["index", [1, 1, 0]], ["rindex", [3, 1, 2]], ],)def test_index_missing(any_string_dtype, method, exp): ser = Series(["abcb", "ab", "bcbe", np.nan], dtype=any_string_dtype) if is_object_or_nan_string_dtype(any_string_dtype): expected_dtype = np.float64 item = np.nan else: expected_dtype = "Int64" item = NA
result = getattr(ser.str, method)("b") expected = Series([*exp, item], dtype=expected_dtype) tm.assert_series_equal(result, expected)
def test_pipe_failures(any_string_dtype): # #2119 ser = Series(["A|B|C"], dtype=any_string_dtype)
result = ser.str.split("|") expected = Series([["A", "B", "C"]], dtype=object) tm.assert_series_equal(result, expected)
result = ser.str.replace("|", " ", regex=False) expected = Series(["A B C"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "start, stop, step, expected", [ (2, 5, None, ["foo", "bar", np.nan, "baz"]), (0, 3, -1, ["", "", np.nan, ""]), (None, None, -1, ["owtoofaa", "owtrabaa", np.nan, "xuqzabaa"]), (None, 2, -1, ["owtoo", "owtra", np.nan, "xuqza"]), (3, 10, 2, ["oto", "ato", np.nan, "aqx"]), (3, 0, -1, ["ofa", "aba", np.nan, "aba"]), ],)def test_slice(start, stop, step, expected, any_string_dtype): ser = Series(["aafootwo", "aabartwo", np.nan, "aabazqux"], dtype=any_string_dtype) result = ser.str.slice(start, stop, step) expected = Series(expected, dtype=any_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "start, stop, step, expected", [ (2, 5, None, ["foo", np.nan, "bar", np.nan, np.nan, None, np.nan, np.nan]), (4, 1, -1, ["oof", np.nan, "rab", np.nan, np.nan, None, np.nan, np.nan]), ],)def test_slice_mixed_object(start, stop, step, expected): ser = Series(["aafootwo", np.nan, "aabartwo", True, datetime.today(), None, 1, 2.0]) result = ser.str.slice(start, stop, step) expected = Series(expected, dtype=object) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "start,stop,repl,expected", [ (2, 3, None, ["shrt", "a it longer", "evnlongerthanthat", "", np.nan]), (2, 3, "z", ["shzrt", "a zit longer", "evznlongerthanthat", "z", np.nan]), (2, 2, "z", ["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]), (2, 1, "z", ["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]), (-1, None, "z", ["shorz", "a bit longez", "evenlongerthanthaz", "z", np.nan]), (None, -2, "z", ["zrt", "zer", "zat", "z", np.nan]), (6, 8, "z", ["shortz", "a bit znger", "evenlozerthanthat", "z", np.nan]), (-10, 3, "z", ["zrt", "a zit longer", "evenlongzerthanthat", "z", np.nan]), ],)def test_slice_replace(start, stop, repl, expected, any_string_dtype): ser = Series( ["short", "a bit longer", "evenlongerthanthat", "", np.nan], dtype=any_string_dtype, ) expected = Series(expected, dtype=any_string_dtype) result = ser.str.slice_replace(start, stop, repl) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "method, exp", [ ["strip", ["aa", "bb", np.nan, "cc"]], ["lstrip", ["aa ", "bb \n", np.nan, "cc "]], ["rstrip", [" aa", " bb", np.nan, "cc"]], ],)def test_strip_lstrip_rstrip(any_string_dtype, method, exp): ser = Series([" aa ", " bb \n", np.nan, "cc "], dtype=any_string_dtype)
result = getattr(ser.str, method)() expected = Series(exp, dtype=any_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "method, exp", [ ["strip", ["aa", np.nan, "bb"]], ["lstrip", ["aa ", np.nan, "bb \t\n"]], ["rstrip", [" aa", np.nan, " bb"]], ],)def test_strip_lstrip_rstrip_mixed_object(method, exp): ser = Series([" aa ", np.nan, " bb \t\n", True, datetime.today(), None, 1, 2.0])
result = getattr(ser.str, method)() expected = Series([*exp, np.nan, np.nan, None, np.nan, np.nan], dtype=object) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "method, exp", [ ["strip", ["ABC", " BNSD", "LDFJH "]], ["lstrip", ["ABCxx", " BNSD", "LDFJH xx"]], ["rstrip", ["xxABC", "xx BNSD", "LDFJH "]], ],)def test_strip_lstrip_rstrip_args(any_string_dtype, method, exp): ser = Series(["xxABCxx", "xx BNSD", "LDFJH xx"], dtype=any_string_dtype)
result = getattr(ser.str, method)("x") expected = Series(exp, dtype=any_string_dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "prefix, expected", [ ("a", ["b", " b c", "bc"]), ("ab", ["", "a b c", "bc"]), ("", ["ab", "a b c", "bc"]), ],)def test_removeprefix(any_string_dtype, prefix, expected): ser = Series(["ab", "a b c", "bc"], dtype=any_string_dtype) result = ser.str.removeprefix(prefix) ser_expected = Series(expected, dtype=any_string_dtype) tm.assert_series_equal(result, ser_expected)
@pytest.mark.parametrize( "suffix, expected", [ ("c", ["ab", "a b ", "b"]), ("bc", ["ab", "a b c", ""]), ("", ["ab", "a b c", "bc"]), ],)def test_removesuffix(any_string_dtype, suffix, expected): ser = Series(["ab", "a b c", "bc"], dtype=any_string_dtype) result = ser.str.removesuffix(suffix) ser_expected = Series(expected, dtype=any_string_dtype) tm.assert_series_equal(result, ser_expected)
def test_string_slice_get_syntax(any_string_dtype): ser = Series( ["YYY", "B", "C", "YYYYYYbYYY", "BYYYcYYY", np.nan, "CYYYBYYY", "dog", "cYYYt"], dtype=any_string_dtype, )
result = ser.str[0] expected = ser.str.get(0) tm.assert_series_equal(result, expected)
result = ser.str[:3] expected = ser.str.slice(stop=3) tm.assert_series_equal(result, expected)
result = ser.str[2::-1] expected = ser.str.slice(start=2, step=-1) tm.assert_series_equal(result, expected)
def test_string_slice_out_of_bounds_nested(): ser = Series([(1, 2), (1,), (3, 4, 5)]) result = ser.str[1] expected = Series([2, np.nan, 4]) tm.assert_series_equal(result, expected)
def test_string_slice_out_of_bounds(any_string_dtype): ser = Series(["foo", "b", "ba"], dtype=any_string_dtype) result = ser.str[1] expected = Series(["o", np.nan, "a"], dtype=any_string_dtype) tm.assert_series_equal(result, expected)
def test_encode_decode(any_string_dtype): ser = Series(["a", "b", "a\xe4"], dtype=any_string_dtype).str.encode("utf-8") result = ser.str.decode("utf-8") expected = Series(["a", "b", "a\xe4"], dtype="str") tm.assert_series_equal(result, expected)
def test_encode_errors_kwarg(any_string_dtype): ser = Series(["a", "b", "a\x9d"], dtype=any_string_dtype)
msg = ( r"'charmap' codec can't encode character '\\x9d' in position 1: " "character maps to <undefined>" ) with pytest.raises(UnicodeEncodeError, match=msg): ser.str.encode("cp1252")
result = ser.str.encode("cp1252", "ignore") expected = ser.map(lambda x: x.encode("cp1252", "ignore")) tm.assert_series_equal(result, expected)
def test_decode_errors_kwarg(): ser = Series([b"a", b"b", b"a\x9d"])
msg = ( "'charmap' codec can't decode byte 0x9d in position 1: " "character maps to <undefined>" ) with pytest.raises(UnicodeDecodeError, match=msg): ser.str.decode("cp1252")
result = ser.str.decode("cp1252", "ignore") expected = ser.map(lambda x: x.decode("cp1252", "ignore")).astype("str") tm.assert_series_equal(result, expected)
def test_decode_string_dtype(string_dtype): # https://github.com/pandas-dev/pandas/pull/60940 ser = Series([b"a", b"b"]) result = ser.str.decode("utf-8", dtype=string_dtype) expected = Series(["a", "b"], dtype=string_dtype) tm.assert_series_equal(result, expected)
def test_decode_object_dtype(object_dtype): # https://github.com/pandas-dev/pandas/pull/60940 ser = Series([b"a", rb"\ud800"]) result = ser.str.decode("utf-8", dtype=object_dtype) expected = Series(["a", r"\ud800"], dtype=object_dtype) tm.assert_series_equal(result, expected)
def test_decode_bad_dtype(): # https://github.com/pandas-dev/pandas/pull/60940 ser = Series([b"a", b"b"]) msg = "dtype must be string or object, got dtype='int64'" with pytest.raises(ValueError, match=msg): ser.str.decode("utf-8", dtype="int64")
@pytest.mark.parametrize( "form, expected", [ ("NFKC", ["ABC", "ABC", "123", np.nan, "アイエ"]), ("NFC", ["ABC", "ABC", "123", np.nan, "アイエ"]), # noqa: RUF001 ],)def test_normalize(form, expected, any_string_dtype): ser = Series( ["ABC", "ABC", "123", np.nan, "アイエ"], # noqa: RUF001 index=["a", "b", "c", "d", "e"], dtype=any_string_dtype, ) expected = Series(expected, index=["a", "b", "c", "d", "e"], dtype=any_string_dtype) result = ser.str.normalize(form) tm.assert_series_equal(result, expected)
def test_normalize_bad_arg_raises(any_string_dtype): ser = Series( ["ABC", "ABC", "123", np.nan, "アイエ"], # noqa: RUF001 index=["a", "b", "c", "d", "e"], dtype=any_string_dtype, ) with pytest.raises(ValueError, match="invalid normalization form"): ser.str.normalize("xxx")
def test_normalize_index(): idx = Index(["ABC", "123", "アイエ"]) # noqa: RUF001 expected = Index(["ABC", "123", "アイエ"]) result = idx.str.normalize("NFKC") tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "values,inferred_type", [ (["a", "b"], "string"), (["a", "b", 1], "mixed-integer"), (["a", "b", 1.3], "mixed"), (["a", "b", 1.3, 1], "mixed-integer"), (["aa", datetime(2011, 1, 1)], "mixed"), ],)def test_index_str_accessor_visibility(values, inferred_type, index_or_series): obj = index_or_series(values) if index_or_series is Index: assert obj.inferred_type == inferred_type
assert isinstance(obj.str, StringMethods)
@pytest.mark.parametrize( "values,inferred_type", [ ([1, np.nan], "floating"), ([datetime(2011, 1, 1)], "datetime64"), ([timedelta(1)], "timedelta64"), ],)def test_index_str_accessor_non_string_values_raises( values, inferred_type, index_or_series): obj = index_or_series(values) if index_or_series is Index: assert obj.inferred_type == inferred_type
msg = "Can only use .str accessor with string values" with pytest.raises(AttributeError, match=msg): obj.str
def test_index_str_accessor_multiindex_raises(): # MultiIndex has mixed dtype, but not allow to use accessor idx = MultiIndex.from_tuples([("a", "b"), ("a", "b")]) assert idx.inferred_type == "mixed"
msg = "Can only use .str accessor with Index, not MultiIndex" with pytest.raises(AttributeError, match=msg): idx.str
def test_str_accessor_no_new_attributes(any_string_dtype): # https://github.com/pandas-dev/pandas/issues/10673 ser = Series(list("aabbcde"), dtype=any_string_dtype) with pytest.raises(AttributeError, match="You cannot add any new attribute"): ser.str.xlabel = "a"
def test_cat_on_bytes_raises(): lhs = Series(np.array(list("abc"), "S1").astype(object)) rhs = Series(np.array(list("def"), "S1").astype(object)) msg = "Cannot use .str.cat with values of inferred dtype 'bytes'" with pytest.raises(TypeError, match=msg): lhs.str.cat(rhs)
def test_str_accessor_in_apply_func(): # https://github.com/pandas-dev/pandas/issues/38979 df = DataFrame(zip("abc", "def", strict=True)) expected = Series(["A/D", "B/E", "C/F"]) result = df.apply(lambda f: "/".join(f.str.upper()), axis=1) tm.assert_series_equal(result, expected)
def test_zfill(): # https://github.com/pandas-dev/pandas/issues/20868 value = Series(["-1", "1", "1000", 10, np.nan]) expected = Series(["-01", "001", "1000", np.nan, np.nan], dtype=object) tm.assert_series_equal(value.str.zfill(3), expected)
value = Series(["-2", "+5"]) expected = Series(["-0002", "+0005"]) tm.assert_series_equal(value.str.zfill(5), expected)
def test_zfill_with_non_integer_argument(): value = Series(["-2", "+5"]) wid = "a" msg = f"width must be of integer type, not {type(wid).__name__}" with pytest.raises(TypeError, match=msg): value.str.zfill(wid)
def test_zfill_with_leading_sign(): value = Series(["-cat", "-1", "+dog"]) expected = Series(["-0cat", "-0001", "+0dog"]) tm.assert_series_equal(value.str.zfill(5), expected)
def test_get_with_dict_label(): # GH47911 s = Series( [ {"name": "Hello", "value": "World"}, {"name": "Goodbye", "value": "Planet"}, {"value": "Sea"}, ] ) result = s.str.get("name") expected = Series(["Hello", "Goodbye", None], dtype=object) tm.assert_series_equal(result, expected) result = s.str.get("value") expected = Series(["World", "Planet", "Sea"], dtype=object) tm.assert_series_equal(result, expected)
def test_series_str_decode(): # GH 22613 result = Series([b"x", b"y"]).str.decode(encoding="UTF-8", errors="strict") expected = Series(["x", "y"], dtype="str") tm.assert_series_equal(result, expected)
def test_decode_with_dtype_none(): with option_context("future.infer_string", True): ser = Series([b"a", b"b", b"c"]) result = ser.str.decode("utf-8", dtype=None) expected = Series(["a", "b", "c"], dtype="str") tm.assert_series_equal(result, expected)
def test_setitem_with_different_string_storage(): # GH#52987 # Test setitem with values from different string storage type pytest.importorskip("pyarrow")
# Test Series[string[python]].__setitem__(Series[string[pyarrow]]) ser_python = Series(range(5), dtype="string[python]") ser_pyarrow = ser_python.astype("string[pyarrow]")
ser_python[:2] = ser_pyarrow[:2] expected = Series(["0", "1", "2", "3", "4"], dtype="string[python]") tm.assert_series_equal(ser_python, expected)
# Test Series[string[pyarrow]].__setitem__(Series[string[python]]) ser_pyarrow = Series(range(5), dtype="string[pyarrow]") ser_python = ser_pyarrow.astype("string[python]")
ser_pyarrow[:2] = ser_python[:2] expected = Series(["0", "1", "2", "3", "4"], dtype="string[pyarrow]") tm.assert_series_equal(ser_pyarrow, expected)
# Test with slice and missing values ser_python = Series(["a", "b", None, "d", "e"], dtype="string[python]") ser_pyarrow = Series(["X", "Y", None], dtype="string[pyarrow]")
ser_python[1:4] = ser_pyarrow expected = Series(["a", "X", "Y", NA, "e"], dtype="string[python]") tm.assert_series_equal(ser_python, expected)
@pytest.mark.parametrize( "pat, expected", [ # lookaround assertions (r"(?=abc)", True), (r"(?<=123)", True), (r"(?!xyz)", True), (r"(?<!\d)", True), (r"(?=a|b)(?<=c)", True), (r"abc", False), (r"\d+", False), (r"(abc)", False), (r"a|b", False), (r"a*", False), (r"", False), (r"\\(?=abc)", True), (r"(?=.*[A-Z])", True), (r"a(?=)", True), (r"(?![0-9])", True), (r"(?=(?!nested))", True), (r"test\(\?\=ing\)", False), (r"[(?=)]", False), (r"(?#(?=comment)", False), (r"(test # (?=comment))", True), (r"(?=test)+", False), (r"(?=test)*", False), (r"(?=test)?", False), (r"abc|(?=test)", True), (r"^(?=test)$", True), # backreferences (r"(abc)\1", True), (r"\b(\w+)\s+\1\b", True), (r"\b(?P<word>\w+)\s+(?P=word)\b", True), ],)def test_has_regex_unsupported_code(pat, expected): # https://github.com/pandas-dev/pandas/issues/60833 assert ArrowStringArrayMixin._has_unsupported_regex(pat) == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import numpy as npimport pytest
from pandas.core.apply import ( _make_unique_kwarg_list, maybe_mangle_lambdas,)
def test_maybe_mangle_lambdas_passthrough(): assert maybe_mangle_lambdas("mean") == "mean" assert maybe_mangle_lambdas(lambda x: x).__name__ == "<lambda>" # don't mangle single lambda. assert maybe_mangle_lambdas([lambda x: x])[0].__name__ == "<lambda>"
def test_maybe_mangle_lambdas_listlike(): aggfuncs = [lambda x: 1, lambda x: 2] result = maybe_mangle_lambdas(aggfuncs) assert result[0].__name__ == "<lambda_0>" assert result[1].__name__ == "<lambda_1>" assert aggfuncs[0](None) == result[0](None) assert aggfuncs[1](None) == result[1](None)
def test_maybe_mangle_lambdas(): func = {"A": [lambda x: 0, lambda x: 1]} result = maybe_mangle_lambdas(func) assert result["A"][0].__name__ == "<lambda_0>" assert result["A"][1].__name__ == "<lambda_1>"
def test_maybe_mangle_lambdas_args(): func = {"A": [lambda x, a, b=1: (0, a, b), lambda x: 1]} result = maybe_mangle_lambdas(func) assert result["A"][0].__name__ == "<lambda_0>" assert result["A"][1].__name__ == "<lambda_1>"
assert func["A"][0](0, 1) == (0, 1, 1) assert func["A"][0](0, 1, 2) == (0, 1, 2) assert func["A"][0](0, 2, b=3) == (0, 2, 3)
def test_maybe_mangle_lambdas_named(): func = {"C": np.mean, "D": {"foo": np.mean, "bar": np.mean}} result = maybe_mangle_lambdas(func) assert result == func
@pytest.mark.parametrize( "order, expected_reorder", [ ( [ ("height", "<lambda>"), ("height", "max"), ("weight", "max"), ("height", "<lambda>"), ("weight", "<lambda>"), ], [ ("height", "<lambda>_0"), ("height", "max"), ("weight", "max"), ("height", "<lambda>_1"), ("weight", "<lambda>"), ], ), ( [ ("col2", "min"), ("col1", "<lambda>"), ("col1", "<lambda>"), ("col1", "<lambda>"), ], [ ("col2", "min"), ("col1", "<lambda>_0"), ("col1", "<lambda>_1"), ("col1", "<lambda>_2"), ], ), ( [("col", "<lambda>"), ("col", "<lambda>"), ("col", "<lambda>")], [("col", "<lambda>_0"), ("col", "<lambda>_1"), ("col", "<lambda>_2")], ), ],)def test_make_unique(order, expected_reorder): # GH 27519, test if make_unique function reorders correctly result = _make_unique_kwarg_list(order)
assert result == expected_reorder1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083from datetime import datetimeimport struct
import numpy as npimport pytest
from pandas._libs import ( algos as libalgos, hashtable as ht,)
from pandas.core.dtypes.common import ( is_bool_dtype, is_complex_dtype, is_float_dtype, is_integer_dtype, is_object_dtype,)from pandas.core.dtypes.dtypes import ( CategoricalDtype, DatetimeTZDtype,)
import pandas as pdfrom pandas import ( Categorical, CategoricalIndex, DataFrame, DatetimeIndex, Index, IntervalIndex, MultiIndex, NaT, Period, PeriodIndex, Series, Timedelta, Timestamp, cut, date_range, timedelta_range, to_datetime, to_timedelta,)import pandas._testing as tmimport pandas.core.algorithms as algosfrom pandas.core.arrays import ( DatetimeArray, TimedeltaArray,)import pandas.core.common as com
class TestFactorize: def test_factorize_complex(self): # GH#17927 array = np.array([1, 2, 2 + 1j], dtype=complex) labels, uniques = algos.factorize(array)
expected_labels = np.array([0, 1, 2], dtype=np.intp) tm.assert_numpy_array_equal(labels, expected_labels)
expected_uniques = np.array([(1 + 0j), (2 + 0j), (2 + 1j)], dtype=complex) tm.assert_numpy_array_equal(uniques, expected_uniques)
def test_factorize(self, index_or_series_obj, sort): obj = index_or_series_obj result_codes, result_uniques = obj.factorize(sort=sort)
constructor = Index if isinstance(obj, MultiIndex): constructor = MultiIndex.from_tuples expected_arr = obj.unique() if expected_arr.dtype == np.float16: expected_arr = expected_arr.astype(np.float32) expected_uniques = constructor(expected_arr) if ( isinstance(obj, Index) and expected_uniques.dtype == bool and obj.dtype == object ): expected_uniques = expected_uniques.astype(object)
if sort: expected_uniques = expected_uniques.sort_values()
# construct an integer ndarray so that # `expected_uniques.take(expected_codes)` is equal to `obj` expected_uniques_list = list(expected_uniques) expected_codes = [expected_uniques_list.index(val) for val in obj] expected_codes = np.asarray(expected_codes, dtype=np.intp)
tm.assert_numpy_array_equal(result_codes, expected_codes) tm.assert_index_equal(result_uniques, expected_uniques, exact=True)
def test_series_factorize_use_na_sentinel_false(self): # GH#35667 values = np.array([1, 2, 1, np.nan]) ser = Series(values) codes, uniques = ser.factorize(use_na_sentinel=False)
expected_codes = np.array([0, 1, 0, 2], dtype=np.intp) expected_uniques = Index([1.0, 2.0, np.nan])
tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_index_equal(uniques, expected_uniques)
def test_basic(self): items = np.array(["a", "b", "b", "a", "a", "c", "c", "c"], dtype=object) codes, uniques = algos.factorize(items) tm.assert_numpy_array_equal(uniques, np.array(["a", "b", "c"], dtype=object))
codes, uniques = algos.factorize(items, sort=True) exp = np.array([0, 1, 1, 0, 0, 2, 2, 2], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) exp = np.array(["a", "b", "c"], dtype=object) tm.assert_numpy_array_equal(uniques, exp)
arr = np.arange(5, dtype=np.intp)[::-1]
codes, uniques = algos.factorize(arr) exp = np.array([0, 1, 2, 3, 4], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) exp = np.array([4, 3, 2, 1, 0], dtype=arr.dtype) tm.assert_numpy_array_equal(uniques, exp)
codes, uniques = algos.factorize(arr, sort=True) exp = np.array([4, 3, 2, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) exp = np.array([0, 1, 2, 3, 4], dtype=arr.dtype) tm.assert_numpy_array_equal(uniques, exp)
arr = np.arange(5.0)[::-1]
codes, uniques = algos.factorize(arr) exp = np.array([0, 1, 2, 3, 4], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) exp = np.array([4.0, 3.0, 2.0, 1.0, 0.0], dtype=arr.dtype) tm.assert_numpy_array_equal(uniques, exp)
codes, uniques = algos.factorize(arr, sort=True) exp = np.array([4, 3, 2, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) exp = np.array([0.0, 1.0, 2.0, 3.0, 4.0], dtype=arr.dtype) tm.assert_numpy_array_equal(uniques, exp)
def test_mixed(self): # doc example reshaping.rst x = Series(["A", "A", np.nan, "B", 3.14, np.inf]) codes, uniques = algos.factorize(x)
exp = np.array([0, 0, -1, 1, 2, 3], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) exp = Index(["A", "B", 3.14, np.inf]) tm.assert_index_equal(uniques, exp)
codes, uniques = algos.factorize(x, sort=True) exp = np.array([2, 2, -1, 3, 0, 1], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) exp = Index([3.14, np.inf, "A", "B"]) tm.assert_index_equal(uniques, exp)
def test_factorize_datetime64(self): # M8 v1 = Timestamp("20130101 09:00:00.00004") v2 = Timestamp("20130101") x = Series([v1, v1, v1, v2, v2, v1]) codes, uniques = algos.factorize(x)
exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) exp = DatetimeIndex([v1, v2]) tm.assert_index_equal(uniques, exp)
codes, uniques = algos.factorize(x, sort=True) exp = np.array([1, 1, 1, 0, 0, 1], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) exp = DatetimeIndex([v2, v1]) tm.assert_index_equal(uniques, exp)
def test_factorize_period(self): # period v1 = Period("201302", freq="M") v2 = Period("201303", freq="M") x = Series([v1, v1, v1, v2, v2, v1])
# periods are not 'sorted' as they are converted back into an index codes, uniques = algos.factorize(x) exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) tm.assert_index_equal(uniques, PeriodIndex([v1, v2]))
codes, uniques = algos.factorize(x, sort=True) exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) tm.assert_index_equal(uniques, PeriodIndex([v1, v2]))
def test_factorize_timedelta(self): # GH 5986 v1 = to_timedelta("1 day 1 min") v2 = to_timedelta("1 day") x = Series([v1, v2, v1, v1, v2, v2, v1]) codes, uniques = algos.factorize(x) exp = np.array([0, 1, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) tm.assert_index_equal(uniques, to_timedelta([v1, v2]))
codes, uniques = algos.factorize(x, sort=True) exp = np.array([1, 0, 1, 1, 0, 0, 1], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) tm.assert_index_equal(uniques, to_timedelta([v2, v1]))
def test_factorize_nan(self): # nan should map to na_sentinel, not reverse_indexer[na_sentinel] # rizer.factorize should not raise an exception if na_sentinel indexes # outside of reverse_indexer key = np.array([1, 2, 1, np.nan], dtype="O") rizer = ht.ObjectFactorizer(len(key)) for na_sentinel in (-1, 20): ids = rizer.factorize(key, na_sentinel=na_sentinel) expected = np.array([0, 1, 0, na_sentinel], dtype=np.intp) assert len(set(key)) == len(set(expected)) tm.assert_numpy_array_equal(pd.isna(key), expected == na_sentinel) tm.assert_numpy_array_equal(ids, expected)
def test_factorizer_with_mask(self): # GH#49549 data = np.array([1, 2, 3, 1, 1, 0], dtype="int64") mask = np.array([False, False, False, False, False, True]) rizer = ht.Int64Factorizer(len(data)) result = rizer.factorize(data, mask=mask) expected = np.array([0, 1, 2, 0, 0, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) expected_uniques = np.array([1, 2, 3], dtype="int64") tm.assert_numpy_array_equal(rizer.uniques.to_array(), expected_uniques)
def test_factorizer_object_with_nan(self): # GH#49549 data = np.array([1, 2, 3, 1, np.nan]) rizer = ht.ObjectFactorizer(len(data)) result = rizer.factorize(data.astype(object)) expected = np.array([0, 1, 2, 0, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) expected_uniques = np.array([1, 2, 3], dtype=object) tm.assert_numpy_array_equal(rizer.uniques.to_array(), expected_uniques)
@pytest.mark.parametrize( "data, expected_codes, expected_uniques", [ ( [(1, 1), (1, 2), (0, 0), (1, 2), "nonsense"], [0, 1, 2, 1, 3], [(1, 1), (1, 2), (0, 0), "nonsense"], ), ( [(1, 1), (1, 2), (0, 0), (1, 2), (1, 2, 3)], [0, 1, 2, 1, 3], [(1, 1), (1, 2), (0, 0), (1, 2, 3)], ), ([(1, 1), (1, 2), (0, 0), (1, 2)], [0, 1, 2, 1], [(1, 1), (1, 2), (0, 0)]), ], ) def test_factorize_tuple_list(self, data, expected_codes, expected_uniques): # GH9454 data = com.asarray_tuplesafe(data, dtype=object) codes, uniques = pd.factorize(data)
tm.assert_numpy_array_equal(codes, np.array(expected_codes, dtype=np.intp))
expected_uniques_array = com.asarray_tuplesafe(expected_uniques, dtype=object) tm.assert_numpy_array_equal(uniques, expected_uniques_array)
def test_complex_sorting(self): # gh 12666 - check no segfault x17 = np.array([complex(i) for i in range(17)], dtype=object)
msg = "'[<>]' not supported between instances of .*" with pytest.raises(TypeError, match=msg): algos.factorize(x17[::-1], sort=True)
def test_numeric_dtype_factorize(self, any_real_numpy_dtype): # GH41132 dtype = any_real_numpy_dtype data = np.array([1, 2, 2, 1], dtype=dtype) expected_codes = np.array([0, 1, 1, 0], dtype=np.intp) expected_uniques = np.array([1, 2], dtype=dtype)
codes, uniques = algos.factorize(data) tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_numpy_array_equal(uniques, expected_uniques)
def test_float64_factorize(self, writable): data = np.array([1.0, 1e8, 1.0, 1e-8, 1e8, 1.0], dtype=np.float64) data.setflags(write=writable) expected_codes = np.array([0, 1, 0, 2, 1, 0], dtype=np.intp) expected_uniques = np.array([1.0, 1e8, 1e-8], dtype=np.float64)
codes, uniques = algos.factorize(data) tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_numpy_array_equal(uniques, expected_uniques)
def test_uint64_factorize(self, writable): data = np.array([2**64 - 1, 1, 2**64 - 1], dtype=np.uint64) data.setflags(write=writable) expected_codes = np.array([0, 1, 0], dtype=np.intp) expected_uniques = np.array([2**64 - 1, 1], dtype=np.uint64)
codes, uniques = algos.factorize(data) tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_numpy_array_equal(uniques, expected_uniques)
def test_int64_factorize(self, writable): data = np.array([2**63 - 1, -(2**63), 2**63 - 1], dtype=np.int64) data.setflags(write=writable) expected_codes = np.array([0, 1, 0], dtype=np.intp) expected_uniques = np.array([2**63 - 1, -(2**63)], dtype=np.int64)
codes, uniques = algos.factorize(data) tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_numpy_array_equal(uniques, expected_uniques)
def test_string_factorize(self, writable): data = np.array(["a", "c", "a", "b", "c"], dtype=object) data.setflags(write=writable) expected_codes = np.array([0, 1, 0, 2, 1], dtype=np.intp) expected_uniques = np.array(["a", "c", "b"], dtype=object)
codes, uniques = algos.factorize(data) tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_numpy_array_equal(uniques, expected_uniques)
def test_object_factorize(self, writable): data = np.array(["a", "c", None, np.nan, "a", "b", NaT, "c"], dtype=object) data.setflags(write=writable) expected_codes = np.array([0, 1, -1, -1, 0, 2, -1, 1], dtype=np.intp) expected_uniques = np.array(["a", "c", "b"], dtype=object)
codes, uniques = algos.factorize(data) tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_numpy_array_equal(uniques, expected_uniques)
def test_datetime64_factorize(self, writable): # GH35650 Verify whether read-only datetime64 array can be factorized data = np.array([np.datetime64("2020-01-01T00:00:00.000")], dtype="M8[ns]") data.setflags(write=writable) expected_codes = np.array([0], dtype=np.intp) expected_uniques = np.array( ["2020-01-01T00:00:00.000000000"], dtype="datetime64[ns]" )
codes, uniques = pd.factorize(data) tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_numpy_array_equal(uniques, expected_uniques)
def test_factorize_rangeindex(self, sort): # increasing -> sort doesn't matter ri = pd.RangeIndex.from_range(range(10)) expected = np.arange(10, dtype=np.intp), ri
result = algos.factorize(ri, sort=sort) tm.assert_numpy_array_equal(result[0], expected[0]) tm.assert_index_equal(result[1], expected[1], exact=True)
result = ri.factorize(sort=sort) tm.assert_numpy_array_equal(result[0], expected[0]) tm.assert_index_equal(result[1], expected[1], exact=True)
def test_factorize_rangeindex_decreasing(self, sort): # decreasing -> sort matters ri = pd.RangeIndex.from_range(range(10)) expected = np.arange(10, dtype=np.intp), ri
ri2 = ri[::-1] expected = expected[0], ri2 if sort: expected = expected[0][::-1], expected[1][::-1]
result = algos.factorize(ri2, sort=sort) tm.assert_numpy_array_equal(result[0], expected[0]) tm.assert_index_equal(result[1], expected[1], exact=True)
result = ri2.factorize(sort=sort) tm.assert_numpy_array_equal(result[0], expected[0]) tm.assert_index_equal(result[1], expected[1], exact=True)
def test_deprecate_order(self): # gh 19727 - check warning is raised for deprecated keyword, order. # Test not valid once order keyword is removed. data = np.array([2**63, 1, 2**63], dtype=np.uint64) with pytest.raises(TypeError, match="got an unexpected keyword"): algos.factorize(data, order=True) with tm.assert_produces_warning(False): algos.factorize(data)
@pytest.mark.parametrize( "data", [ np.array([0, 1, 0], dtype="u8"), np.array([-(2**63), 1, -(2**63)], dtype="i8"), np.array(["__nan__", "foo", "__nan__"], dtype="object"), ], ) def test_parametrized_factorize_na_value_default(self, data): # arrays that include the NA default for that type, but isn't used. codes, uniques = algos.factorize(data) expected_uniques = data[[0, 1]] expected_codes = np.array([0, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_numpy_array_equal(uniques, expected_uniques)
@pytest.mark.parametrize( "data, na_value", [ (np.array([0, 1, 0, 2], dtype="u8"), 0), (np.array([1, 0, 1, 2], dtype="u8"), 1), (np.array([-(2**63), 1, -(2**63), 0], dtype="i8"), -(2**63)), (np.array([1, -(2**63), 1, 0], dtype="i8"), 1), (np.array(["a", "", "a", "b"], dtype=object), "a"), (np.array([(), ("a", 1), (), ("a", 2)], dtype=object), ()), (np.array([("a", 1), (), ("a", 1), ("a", 2)], dtype=object), ("a", 1)), ], ) def test_parametrized_factorize_na_value(self, data, na_value): codes, uniques = algos.factorize_array(data, na_value=na_value) expected_uniques = data[[1, 3]] expected_codes = np.array([-1, 0, -1, 1], dtype=np.intp) tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_numpy_array_equal(uniques, expected_uniques)
@pytest.mark.parametrize( "data, uniques", [ ( np.array(["b", "a", None, "b"], dtype=object), np.array(["b", "a"], dtype=object), ), ( pd.array([2, 1, pd.NA, 2], dtype="Int64"), pd.array([2, 1], dtype="Int64"), ), ], ids=["numpy_array", "extension_array"], ) def test_factorize_use_na_sentinel(self, sort, data, uniques): codes, uniques = algos.factorize(data, sort=sort, use_na_sentinel=True) if sort: expected_codes = np.array([1, 0, -1, 1], dtype=np.intp) expected_uniques = algos.safe_sort(uniques) else: expected_codes = np.array([0, 1, -1, 0], dtype=np.intp) expected_uniques = uniques tm.assert_numpy_array_equal(codes, expected_codes) if isinstance(data, np.ndarray): tm.assert_numpy_array_equal(uniques, expected_uniques) else: tm.assert_extension_array_equal(uniques, expected_uniques)
@pytest.mark.parametrize( "data, expected_codes, expected_uniques", [ ( ["a", None, "b", "a"], np.array([0, 1, 2, 0], dtype=np.dtype("intp")), np.array(["a", np.nan, "b"], dtype=object), ), ( ["a", np.nan, "b", "a"], np.array([0, 1, 2, 0], dtype=np.dtype("intp")), np.array(["a", np.nan, "b"], dtype=object), ), ], ) def test_object_factorize_use_na_sentinel_false( self, data, expected_codes, expected_uniques ): codes, uniques = algos.factorize( np.array(data, dtype=object), use_na_sentinel=False )
tm.assert_numpy_array_equal(uniques, expected_uniques, strict_nan=True) tm.assert_numpy_array_equal(codes, expected_codes, strict_nan=True)
@pytest.mark.parametrize( "data, expected_codes, expected_uniques", [ ( np.array([1, None, 1, 2], dtype=object), np.array([0, 1, 0, 2], dtype=np.dtype("intp")), np.array([1, np.nan, 2], dtype="O"), ), ( np.array([1, np.nan, 1, 2], dtype=np.float64), np.array([0, 1, 0, 2], dtype=np.dtype("intp")), np.array([1, np.nan, 2], dtype=np.float64), ), ], ) def test_int_factorize_use_na_sentinel_false( self, data, expected_codes, expected_uniques ): codes, uniques = algos.factorize(data, use_na_sentinel=False)
tm.assert_numpy_array_equal(uniques, expected_uniques, strict_nan=True) tm.assert_numpy_array_equal(codes, expected_codes, strict_nan=True)
@pytest.mark.parametrize( "data, expected_codes, expected_uniques", [ ( Index(Categorical(["a", "a", "b"])), np.array([0, 0, 1], dtype=np.intp), CategoricalIndex(["a", "b"], categories=["a", "b"], dtype="category"), ), ( Series(Categorical(["a", "a", "b"])), np.array([0, 0, 1], dtype=np.intp), CategoricalIndex(["a", "b"], categories=["a", "b"], dtype="category"), ), ( Series(DatetimeIndex(["2017", "2017"], tz="US/Eastern")), np.array([0, 0], dtype=np.intp), DatetimeIndex(["2017"], tz="US/Eastern"), ), ], ) def test_factorize_mixed_values(self, data, expected_codes, expected_uniques): # GH 19721 codes, uniques = algos.factorize(data) tm.assert_numpy_array_equal(codes, expected_codes) tm.assert_index_equal(uniques, expected_uniques)
def test_factorize_interval_non_nano(self, unit): # GH#56099 left = DatetimeIndex(["2016-01-01", np.nan, "2015-10-11"]).as_unit(unit) right = DatetimeIndex(["2016-01-02", np.nan, "2015-10-15"]).as_unit(unit) idx = IntervalIndex.from_arrays(left, right) codes, cats = idx.factorize() assert cats.dtype == f"interval[datetime64[{unit}], right]"
ts = Timestamp(0).as_unit(unit) idx2 = IntervalIndex.from_arrays(left - ts, right - ts) codes2, cats2 = idx2.factorize() assert cats2.dtype == f"interval[timedelta64[{unit}], right]"
idx3 = IntervalIndex.from_arrays( left.tz_localize("US/Pacific"), right.tz_localize("US/Pacific") ) codes3, cats3 = idx3.factorize() assert cats3.dtype == f"interval[datetime64[{unit}, US/Pacific], right]"
class TestUnique: def test_ints(self): arr = np.random.default_rng(2).integers(0, 100, size=50)
result = algos.unique(arr) assert isinstance(result, np.ndarray)
def test_objects(self): arr = np.random.default_rng(2).integers(0, 100, size=50).astype("O")
result = algos.unique(arr) assert isinstance(result, np.ndarray)
def test_object_refcount_bug(self): lst = np.array(["A", "B", "C", "D", "E"], dtype=object) for i in range(1000): len(algos.unique(lst))
def test_index_returned(self, index): # GH#57043 index = index.repeat(2) result = algos.unique(index)
# dict.fromkeys preserves the order unique_values = list(dict.fromkeys(index.values)) if isinstance(index, MultiIndex): expected = MultiIndex.from_tuples(unique_values, names=index.names) else: expected = Index(unique_values, dtype=index.dtype) if isinstance(index.dtype, DatetimeTZDtype): expected = expected.normalize() tm.assert_index_equal(result, expected, exact=True)
def test_factorize_multiindex_empty(self): # GH#57517 mi = MultiIndex.from_product( [Index([], name="a", dtype=object), Index([], name="i", dtype="f4")] ) codes, uniques = mi.factorize() exp_codes = np.array([], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp_codes) tm.assert_index_equal(uniques, mi[:0])
def test_dtype_preservation(self, any_numpy_dtype): # GH 15442 if any_numpy_dtype in (tm.BYTES_DTYPES + tm.STRING_DTYPES): data = [1, 2, 2] uniques = [1, 2] elif is_integer_dtype(any_numpy_dtype): data = [1, 2, 2] uniques = [1, 2] elif is_float_dtype(any_numpy_dtype): data = [1, 2, 2] uniques = [1.0, 2.0] elif is_complex_dtype(any_numpy_dtype): data = [complex(1, 0), complex(2, 0), complex(2, 0)] uniques = [complex(1, 0), complex(2, 0)] elif is_bool_dtype(any_numpy_dtype): data = [True, True, False] uniques = [True, False] elif is_object_dtype(any_numpy_dtype): data = ["A", "B", "B"] uniques = ["A", "B"] else: # datetime64[ns]/M8[ns]/timedelta64[ns]/m8[ns] tested elsewhere data = [1, 2, 2] uniques = [1, 2]
result = Series(data, dtype=any_numpy_dtype).unique() expected = np.array(uniques, dtype=any_numpy_dtype)
if any_numpy_dtype in tm.STRING_DTYPES: expected = expected.astype(object)
if expected.dtype.kind in ["m", "M"]: # We get TimedeltaArray/DatetimeArray assert isinstance(result, (DatetimeArray, TimedeltaArray)) result = np.array(result) tm.assert_numpy_array_equal(result, expected)
def test_datetime64_dtype_array_returned(self): # GH 9431 dt_arr = np.array( [ "2015-01-03T00:00:00.000000000", "2015-01-01T00:00:00.000000000", ], dtype="M8[ns]", )
dt_index = to_datetime( [ "2015-01-03T00:00:00.000000000", "2015-01-01T00:00:00.000000000", "2015-01-01T00:00:00.000000000", ] ) result = algos.unique(dt_index) expected = to_datetime(dt_arr) tm.assert_index_equal(result, expected, exact=True)
s = Series(dt_index) result = algos.unique(s) tm.assert_numpy_array_equal(result, dt_arr) assert result.dtype == dt_arr.dtype
arr = s.values result = algos.unique(arr) tm.assert_numpy_array_equal(result, dt_arr) assert result.dtype == dt_arr.dtype
def test_datetime_non_ns(self): a = np.array(["2000", "2000", "2001"], dtype="datetime64[s]") result = pd.unique(a) expected = np.array(["2000", "2001"], dtype="datetime64[s]") tm.assert_numpy_array_equal(result, expected)
def test_timedelta_non_ns(self): a = np.array(["2000", "2000", "2001"], dtype="timedelta64[s]") result = pd.unique(a) expected = np.array([2000, 2001], dtype="timedelta64[s]") tm.assert_numpy_array_equal(result, expected)
def test_timedelta64_dtype_array_returned(self): # GH 9431 td_arr = np.array([31200, 45678, 10000], dtype="m8[ns]")
td_index = to_timedelta([31200, 45678, 31200, 10000, 45678]) result = algos.unique(td_index) expected = to_timedelta(td_arr) tm.assert_index_equal(result, expected) assert result.dtype == expected.dtype
s = Series(td_index) result = algos.unique(s) tm.assert_numpy_array_equal(result, td_arr) assert result.dtype == td_arr.dtype
arr = s.values result = algos.unique(arr) tm.assert_numpy_array_equal(result, td_arr) assert result.dtype == td_arr.dtype
def test_uint64_overflow(self): s = Series([1, 2, 2**63, 2**63], dtype=np.uint64) exp = np.array([1, 2, 2**63], dtype=np.uint64) tm.assert_numpy_array_equal(algos.unique(s), exp)
def test_nan_in_object_array(self): duplicated_items = ["a", np.nan, "c", "c"] result = pd.unique(np.array(duplicated_items, dtype=object)) expected = np.array(["a", np.nan, "c"], dtype=object) tm.assert_numpy_array_equal(result, expected)
def test_categorical(self): # we are expecting to return in the order # of appearance expected = Categorical(list("bac"))
# we are expecting to return in the order # of the categories expected_o = Categorical(list("bac"), categories=list("abc"), ordered=True)
# GH 15939 c = Categorical(list("baabc")) result = c.unique() tm.assert_categorical_equal(result, expected)
result = algos.unique(c) tm.assert_categorical_equal(result, expected)
c = Categorical(list("baabc"), ordered=True) result = c.unique() tm.assert_categorical_equal(result, expected_o)
result = algos.unique(c) tm.assert_categorical_equal(result, expected_o)
# Series of categorical dtype s = Series(Categorical(list("baabc")), name="foo") result = s.unique() tm.assert_categorical_equal(result, expected)
result = pd.unique(s) tm.assert_categorical_equal(result, expected)
# CI -> return CI ci = CategoricalIndex(Categorical(list("baabc"), categories=list("abc"))) expected = CategoricalIndex(expected) result = ci.unique() tm.assert_index_equal(result, expected)
result = pd.unique(ci) tm.assert_index_equal(result, expected)
def test_datetime64tz_aware(self, unit): # GH 15939
dti = Index( [ Timestamp("20160101", tz="US/Eastern"), Timestamp("20160101", tz="US/Eastern"), ] ).as_unit(unit) ser = Series(dti)
result = ser.unique() expected = dti[:1]._data tm.assert_extension_array_equal(result, expected)
result = dti.unique() expected = dti[:1] tm.assert_index_equal(result, expected)
result = pd.unique(ser) expected = dti[:1]._data tm.assert_extension_array_equal(result, expected)
result = pd.unique(dti) expected = dti[:1] tm.assert_index_equal(result, expected)
def test_order_of_appearance(self): # 9346 # light testing of guarantee of order of appearance # these also are the doc-examples result = pd.unique(Series([2, 1, 3, 3])) tm.assert_numpy_array_equal(result, np.array([2, 1, 3], dtype="int64"))
result = pd.unique(Series([2] + [1] * 5)) tm.assert_numpy_array_equal(result, np.array([2, 1], dtype="int64"))
data = np.array(["a", "a", "b", "c"], dtype=object) result = pd.unique(data) expected = np.array(["a", "b", "c"], dtype=object) tm.assert_numpy_array_equal(result, expected)
result = pd.unique(Series(Categorical(list("aabc")))) expected = Categorical(list("abc")) tm.assert_categorical_equal(result, expected)
def test_order_of_appearance_dt64(self, unit): ser = Series([Timestamp("20160101"), Timestamp("20160101")]).dt.as_unit(unit) result = pd.unique(ser) expected = np.array(["2016-01-01T00:00:00.000000000"], dtype=f"M8[{unit}]") tm.assert_numpy_array_equal(result, expected)
def test_order_of_appearance_dt64tz(self, unit): dti = DatetimeIndex( [ Timestamp("20160101", tz="US/Eastern"), Timestamp("20160101", tz="US/Eastern"), ] ).as_unit(unit) result = pd.unique(dti) expected = DatetimeIndex( ["2016-01-01 00:00:00"], dtype=f"datetime64[{unit}, US/Eastern]", freq=None ) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "arg ,expected", [ (("1", "1", "2"), np.array(["1", "2"], dtype=object)), (("foo",), np.array(["foo"], dtype=object)), ], ) def test_tuple_with_strings(self, arg, expected): # see GH 17108 arg = com.asarray_tuplesafe(arg, dtype=object) result = pd.unique(arg) tm.assert_numpy_array_equal(result, expected)
def test_obj_none_preservation(self): # GH 20866 arr = np.array(["foo", None], dtype=object) result = pd.unique(arr) expected = np.array(["foo", None], dtype=object)
tm.assert_numpy_array_equal(result, expected, strict_nan=True)
def test_signed_zero(self): # GH 21866 a = np.array([-0.0, 0.0]) result = pd.unique(a) expected = np.array([-0.0]) # 0.0 and -0.0 are equivalent tm.assert_numpy_array_equal(result, expected)
def test_different_nans(self): # GH 21866 # create different nans from bit-patterns: NAN1 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000000))[0] NAN2 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000001))[0] assert NAN1 != NAN1 assert NAN2 != NAN2 a = np.array([NAN1, NAN2]) # NAN1 and NAN2 are equivalent result = pd.unique(a) expected = np.array([np.nan]) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("el_type", [np.float64, object]) def test_first_nan_kept(self, el_type): # GH 22295 # create different nans from bit-patterns: bits_for_nan1 = 0xFFF8000000000001 bits_for_nan2 = 0x7FF8000000000001 NAN1 = struct.unpack("d", struct.pack("=Q", bits_for_nan1))[0] NAN2 = struct.unpack("d", struct.pack("=Q", bits_for_nan2))[0] assert NAN1 != NAN1 assert NAN2 != NAN2 a = np.array([NAN1, NAN2], dtype=el_type) result = pd.unique(a) assert result.size == 1 # use bit patterns to identify which nan was kept: result_nan_bits = struct.unpack("=Q", struct.pack("d", result[0]))[0] assert result_nan_bits == bits_for_nan1
def test_do_not_mangle_na_values(self, unique_nulls_fixture, unique_nulls_fixture2): # GH 22295 if unique_nulls_fixture is unique_nulls_fixture2: return # skip it, values not unique a = np.array([unique_nulls_fixture, unique_nulls_fixture2], dtype=object) result = pd.unique(a) assert result.size == 2 assert a[0] is unique_nulls_fixture assert a[1] is unique_nulls_fixture2
def test_unique_masked(self, any_numeric_ea_dtype): # GH#48019 ser = Series([1, pd.NA, 2] * 3, dtype=any_numeric_ea_dtype) result = pd.unique(ser) expected = pd.array([1, pd.NA, 2], dtype=any_numeric_ea_dtype) tm.assert_extension_array_equal(result, expected)
def test_unique_NumpyExtensionArray(self): arr_complex = pd.array( [1 + 1j, 2, 3] ) # NumpyEADtype('complex128') => NumpyExtensionArray result = pd.unique(arr_complex) expected = pd.array([1 + 1j, 2 + 0j, 3 + 0j]) tm.assert_extension_array_equal(result, expected)
def test_nunique_ints(index_or_series_or_array): # GH#36327 values = index_or_series_or_array(np.random.default_rng(2).integers(0, 20, 30)) result = algos.nunique_ints(values) expected = len(algos.unique(values)) assert result == expected
class TestIsin: def test_invalid(self): msg = ( r"only list-like objects are allowed to be passed to isin\(\), " r"you passed a `int`" ) with pytest.raises(TypeError, match=msg): algos.isin(1, 1) with pytest.raises(TypeError, match=msg): algos.isin(1, [1]) with pytest.raises(TypeError, match=msg): algos.isin([1], 1)
def test_basic(self): result = algos.isin(np.array([1, 2]), [1]) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.isin(Series([1, 2]), [1]) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.isin(Series([1, 2]), Series([1])) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.isin(Series([1, 2]), {1}) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected)
arg = np.array(["a", "b"], dtype=object) result = algos.isin(arg, ["a"]) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.isin(Series(arg), Series(["a"])) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.isin(Series(arg), {"a"}) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.isin(arg, [1]) expected = np.array([False, False]) tm.assert_numpy_array_equal(result, expected)
def test_i8(self): arr = date_range("20130101", periods=3).values result = algos.isin(arr, [arr[0]]) expected = np.array([True, False, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.isin(arr, arr[0:2]) expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.isin(arr, set(arr[0:2])) expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected)
arr = timedelta_range("1 day", periods=3).values result = algos.isin(arr, [arr[0]]) expected = np.array([True, False, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.isin(arr, arr[0:2]) expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.isin(arr, set(arr[0:2])) expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("dtype1", ["m8[ns]", "M8[ns]", "M8[ns, UTC]", "period[D]"]) @pytest.mark.parametrize("dtype", ["i8", "f8", "u8"]) def test_isin_datetimelike_values_numeric_comps(self, dtype, dtype1): # Anything but object and we get all-False shortcut
dta = date_range("2013-01-01", periods=3)._values arr = Series(dta.view("i8")).array.view(dtype1)
comps = arr.view("i8").astype(dtype)
result = algos.isin(comps, arr) expected = np.zeros(comps.shape, dtype=bool) tm.assert_numpy_array_equal(result, expected)
def test_large(self): s = date_range("20000101", periods=2000000, freq="s").values result = algos.isin(s, s[0:2]) expected = np.zeros(len(s), dtype=bool) expected[0] = True expected[1] = True tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("dtype", ["m8[ns]", "M8[ns]", "M8[ns, UTC]", "period[D]"]) def test_isin_datetimelike_all_nat(self, dtype): # GH#56427 dta = date_range("2013-01-01", periods=3)._values arr = Series(dta.view("i8")).array.view(dtype)
arr[0] = NaT result = algos.isin(arr, [NaT]) expected = np.array([True, False, False], dtype=bool) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("dtype", ["m8[ns]", "M8[ns]", "M8[ns, UTC]"]) def test_isin_datetimelike_strings_returns_false(self, dtype): # GH#53111 dta = date_range("2013-01-01", periods=3)._values arr = Series(dta.view("i8")).array.view(dtype)
vals = [str(x) for x in arr] res = algos.isin(arr, vals) assert not res.any()
vals2 = np.array(vals, dtype=str) res2 = algos.isin(arr, vals2) assert not res2.any()
def test_isin_dt64tz_with_nat(self): # the all-NaT values used to get inferred to tznaive, which was evaluated # as non-matching GH#56427 dti = date_range("2016-01-01", periods=3, tz="UTC") ser = Series(dti) ser[0] = NaT
res = algos.isin(ser._values, [NaT]) exp = np.array([True, False, False], dtype=bool) tm.assert_numpy_array_equal(res, exp)
def test_categorical_from_codes(self): # GH 16639 vals = np.array([0, 1, 2, 0]) cats = ["a", "b", "c"] Sd = Series(Categorical([1]).from_codes(vals, cats)) St = Series(Categorical([1]).from_codes(np.array([0, 1]), cats)) expected = np.array([True, True, False, True]) result = algos.isin(Sd, St) tm.assert_numpy_array_equal(expected, result)
def test_categorical_isin(self): vals = np.array([0, 1, 2, 0]) cats = ["a", "b", "c"] cat = Categorical([1]).from_codes(vals, cats) other = Categorical([1]).from_codes(np.array([0, 1]), cats)
expected = np.array([True, True, False, True]) result = algos.isin(cat, other) tm.assert_numpy_array_equal(expected, result)
def test_same_nan_is_in(self): # GH 22160 # nan is special, because from " a is b" doesn't follow "a == b" # at least, isin() should follow python's "np.nan in [nan] == True" # casting to -> np.float64 -> another float-object somewhere on # the way could lead jeopardize this behavior comps = np.array([np.nan], dtype=object) # could be casted to float64 values = [np.nan] expected = np.array([True]) result = algos.isin(comps, values) tm.assert_numpy_array_equal(expected, result)
def test_same_nan_is_in_large(self): # https://github.com/pandas-dev/pandas/issues/22205 s = np.tile(1.0, 1_000_001) s[0] = np.nan result = algos.isin(s, np.array([np.nan, 1])) expected = np.ones(len(s), dtype=bool) tm.assert_numpy_array_equal(result, expected)
def test_same_nan_is_in_large_series(self): # https://github.com/pandas-dev/pandas/issues/22205 s = np.tile(1.0, 1_000_001) series = Series(s) s[0] = np.nan result = series.isin(np.array([np.nan, 1])) expected = Series(np.ones(len(s), dtype=bool)) tm.assert_series_equal(result, expected)
def test_same_object_is_in(self): # GH 22160 # there could be special treatment for nans # the user however could define a custom class # with similar behavior, then we at least should # fall back to usual python's behavior: "a in [a] == True" class LikeNan: def __eq__(self, other) -> bool: return False
def __hash__(self): return 0
a, b = LikeNan(), LikeNan()
arg = np.array([a], dtype=object)
# same object -> True tm.assert_numpy_array_equal(algos.isin(arg, [a]), np.array([True])) # different objects -> False tm.assert_numpy_array_equal(algos.isin(arg, [b]), np.array([False]))
def test_different_nans(self): # GH 22160 # all nans are handled as equivalent
comps = [float("nan")] values = [float("nan")] assert comps[0] is not values[0] # different nan-objects
# as list of python-objects: result = algos.isin(np.array(comps), values) tm.assert_numpy_array_equal(np.array([True]), result)
# as object-array: result = algos.isin( np.asarray(comps, dtype=object), np.asarray(values, dtype=object) ) tm.assert_numpy_array_equal(np.array([True]), result)
# as float64-array: result = algos.isin( np.asarray(comps, dtype=np.float64), np.asarray(values, dtype=np.float64) ) tm.assert_numpy_array_equal(np.array([True]), result)
def test_no_cast(self): # GH 22160 # ensure 42 is not casted to a string comps = np.array(["ss", 42], dtype=object) values = ["42"] expected = np.array([False, False])
result = algos.isin(comps, values) tm.assert_numpy_array_equal(expected, result)
@pytest.mark.parametrize("empty", [[], Series(dtype=object), np.array([])]) def test_empty(self, empty): # see gh-16991 vals = Index(["a", "b"]) expected = np.array([False, False])
result = algos.isin(vals, empty) tm.assert_numpy_array_equal(expected, result)
def test_different_nan_objects(self): # GH 22119 comps = np.array(["nan", np.nan * 1j, float("nan")], dtype=object) vals = np.array([float("nan")], dtype=object) expected = np.array([False, False, True]) result = algos.isin(comps, vals) tm.assert_numpy_array_equal(expected, result)
def test_different_nans_as_float64(self): # GH 21866 # create different nans from bit-patterns, # these nans will land in different buckets in the hash-table # if no special care is taken NAN1 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000000))[0] NAN2 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000001))[0] assert NAN1 != NAN1 assert NAN2 != NAN2
# check that NAN1 and NAN2 are equivalent: arr = np.array([NAN1, NAN2], dtype=np.float64) lookup1 = np.array([NAN1], dtype=np.float64) result = algos.isin(arr, lookup1) expected = np.array([True, True]) tm.assert_numpy_array_equal(result, expected)
lookup2 = np.array([NAN2], dtype=np.float64) result = algos.isin(arr, lookup2) expected = np.array([True, True]) tm.assert_numpy_array_equal(result, expected)
def test_isin_int_df_string_search(self): """Comparing df with int`s (1,2) with a string at isin() ("1") -> should not match values because int 1 is not equal str 1""" df = DataFrame({"values": [1, 2]}) result = df.isin(["1"]) expected_false = DataFrame({"values": [False, False]}) tm.assert_frame_equal(result, expected_false)
def test_isin_nan_df_string_search(self): """Comparing df with nan value (np.nan,2) with a string at isin() ("NaN") -> should not match values because np.nan is not equal str NaN""" df = DataFrame({"values": [np.nan, 2]}) result = df.isin(np.array(["NaN"], dtype=object)) expected_false = DataFrame({"values": [False, False]}) tm.assert_frame_equal(result, expected_false)
def test_isin_float_df_string_search(self): """Comparing df with floats (1.4245,2.32441) with a string at isin() ("1.4245") -> should not match values because float 1.4245 is not equal str 1.4245""" df = DataFrame({"values": [1.4245, 2.32441]}) result = df.isin(np.array(["1.4245"], dtype=object)) expected_false = DataFrame({"values": [False, False]}) tm.assert_frame_equal(result, expected_false)
def test_isin_unsigned_dtype(self): # GH#46485 ser = Series([1378774140726870442], dtype=np.uint64) result = ser.isin([1378774140726870528]) expected = Series(False) tm.assert_series_equal(result, expected)
class TestValueCounts: def test_value_counts(self): arr = np.random.default_rng(1234).standard_normal(4) factor = cut(arr, 4)
# assert isinstance(factor, n) result = algos.value_counts_internal(factor) breaks = [-1.606, -1.018, -0.431, 0.155, 0.741] index = IntervalIndex.from_breaks(breaks).astype(CategoricalDtype(ordered=True)) expected = Series([1, 0, 2, 1], index=index, name="count") tm.assert_series_equal(result.sort_index(), expected.sort_index())
def test_value_counts_bins(self): s = [1, 2, 3, 4] result = algos.value_counts_internal(s, bins=1) expected = Series( [4], index=IntervalIndex.from_tuples([(0.996, 4.0)]), name="count" ) tm.assert_series_equal(result, expected)
result = algos.value_counts_internal(s, bins=2, sort=False) expected = Series( [2, 2], index=IntervalIndex.from_tuples([(0.996, 2.5), (2.5, 4.0)]), name="count", ) tm.assert_series_equal(result, expected)
def test_value_counts_dtypes(self): result = algos.value_counts_internal(np.array([1, 1.0])) assert len(result) == 1
result = algos.value_counts_internal(np.array([1, 1.0]), bins=1) assert len(result) == 1
result = algos.value_counts_internal(Series([1, 1.0, "1"])) # object assert len(result) == 2
msg = "bins argument only works with numeric data" with pytest.raises(TypeError, match=msg): algos.value_counts_internal(np.array(["1", 1], dtype=object), bins=1)
def test_value_counts_nat(self): td = Series([np.timedelta64(10000, "ns"), NaT], dtype="timedelta64[ns]") dt = to_datetime(["NaT", "2014-01-01"])
for ser in [td, dt]: vc = algos.value_counts_internal(ser) vc_with_na = algos.value_counts_internal(ser, dropna=False) assert len(vc) == 1 assert len(vc_with_na) == 2
exp_dt = Series({Timestamp("2014-01-01 00:00:00"): 1}, name="count") result_dt = algos.value_counts_internal(dt) tm.assert_series_equal(result_dt, exp_dt)
exp_td = Series([1], index=[np.timedelta64(10000, "ns")], name="count") result_td = algos.value_counts_internal(td) tm.assert_series_equal(result_td, exp_td)
@pytest.mark.parametrize("dtype", [object, "M8[us]"]) def test_value_counts_datetime_outofbounds(self, dtype): # GH 13663 ser = Series( [ datetime(3000, 1, 1), datetime(5000, 1, 1), datetime(5000, 1, 1), datetime(6000, 1, 1), datetime(3000, 1, 1), datetime(3000, 1, 1), ], dtype=dtype, )
res = ser.value_counts()
exp_index = Index( [datetime(3000, 1, 1), datetime(5000, 1, 1), datetime(6000, 1, 1)], dtype=dtype, ) exp = Series([3, 2, 1], index=exp_index, name="count") tm.assert_series_equal(res, exp)
def test_categorical(self): s = Series(Categorical(list("aaabbc"))) result = s.value_counts() expected = Series( [3, 2, 1], index=CategoricalIndex(["a", "b", "c"]), name="count" )
tm.assert_series_equal(result, expected, check_index_type=True)
# preserve order? s = s.cat.as_ordered() result = s.value_counts() expected.index = expected.index.as_ordered() tm.assert_series_equal(result, expected, check_index_type=True)
def test_categorical_nans(self): s = Series(Categorical(list("aaaaabbbcc"))) # 4,3,2,1 (nan) s.iloc[1] = np.nan result = s.value_counts() expected = Series( [4, 3, 2], index=CategoricalIndex(["a", "b", "c"], categories=["a", "b", "c"]), name="count", ) tm.assert_series_equal(result, expected, check_index_type=True) result = s.value_counts(dropna=False) expected = Series( [4, 3, 2, 1], index=CategoricalIndex(["a", "b", "c", np.nan]), name="count" ) tm.assert_series_equal(result, expected, check_index_type=True)
# out of order s = Series( Categorical(list("aaaaabbbcc"), ordered=True, categories=["b", "a", "c"]) ) s.iloc[1] = np.nan result = s.value_counts() expected = Series( [4, 3, 2], index=CategoricalIndex( ["a", "b", "c"], categories=["b", "a", "c"], ordered=True, ), name="count", ) tm.assert_series_equal(result, expected, check_index_type=True)
result = s.value_counts(dropna=False) expected = Series( [4, 3, 2, 1], index=CategoricalIndex( ["a", "b", "c", np.nan], categories=["b", "a", "c"], ordered=True ), name="count", ) tm.assert_series_equal(result, expected, check_index_type=True)
def test_categorical_zeroes(self): # keep the `d` category with 0 s = Series(Categorical(list("bbbaac"), categories=list("abcd"), ordered=True)) result = s.value_counts() expected = Series( [3, 2, 1, 0], index=Categorical( ["b", "a", "c", "d"], categories=list("abcd"), ordered=True ), name="count", ) tm.assert_series_equal(result, expected, check_index_type=True)
def test_value_counts_dropna(self): # https://github.com/pandas-dev/pandas/issues/9443#issuecomment-73719328
tm.assert_series_equal( Series([True, True, False]).value_counts(dropna=True), Series([2, 1], index=[True, False], name="count"), ) tm.assert_series_equal( Series([True, True, False]).value_counts(dropna=False), Series([2, 1], index=[True, False], name="count"), )
tm.assert_series_equal( Series([True] * 3 + [False] * 2 + [None] * 5).value_counts(dropna=True), Series([3, 2], index=Index([True, False], dtype=object), name="count"), ) tm.assert_series_equal( Series([True] * 5 + [False] * 3 + [None] * 2).value_counts(dropna=False), Series([5, 3, 2], index=[True, False, None], name="count"), ) tm.assert_series_equal( Series([10.3, 5.0, 5.0]).value_counts(dropna=True), Series([2, 1], index=[5.0, 10.3], name="count"), ) tm.assert_series_equal( Series([10.3, 5.0, 5.0]).value_counts(dropna=False), Series([2, 1], index=[5.0, 10.3], name="count"), )
tm.assert_series_equal( Series([10.3, 5.0, 5.0, None]).value_counts(dropna=True), Series([2, 1], index=[5.0, 10.3], name="count"), )
result = Series([10.3, 10.3, 5.0, 5.0, 5.0, None]).value_counts(dropna=False) expected = Series([3, 2, 1], index=[5.0, 10.3, None], name="count") tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dtype", (np.float64, object, "M8[ns]")) def test_value_counts_normalized(self, dtype): # GH12558 s = Series([1] * 2 + [2] * 3 + [np.nan] * 5) s_typed = s.astype(dtype) result = s_typed.value_counts(normalize=True, dropna=False) expected = Series( [0.5, 0.3, 0.2], index=Series([np.nan, 2.0, 1.0], dtype=dtype), name="proportion", ) tm.assert_series_equal(result, expected)
result = s_typed.value_counts(normalize=True, dropna=True) expected = Series( [0.6, 0.4], index=Series([2.0, 1.0], dtype=dtype), name="proportion" ) tm.assert_series_equal(result, expected)
def test_value_counts_uint64(self): arr = np.array([2**63], dtype=np.uint64) expected = Series([1], index=[2**63], name="count") result = algos.value_counts_internal(arr)
tm.assert_series_equal(result, expected)
arr = np.array([-1, 2**63], dtype=object) expected = Series([1, 1], index=[-1, 2**63], name="count") result = algos.value_counts_internal(arr)
tm.assert_series_equal(result, expected)
def test_value_counts_series(self): # GH#54857 values = np.array([3, 1, 2, 3, 4, np.nan]) result = Series(values).value_counts(bins=3) expected = Series( [2, 2, 1], index=IntervalIndex.from_tuples( [(0.996, 2.0), (2.0, 3.0), (3.0, 4.0)], dtype="interval[float64, right]" ), name="count", ) tm.assert_series_equal(result, expected)
def test_value_counts_stability(self): # GH 63155 arr = np.random.default_rng(2).integers(0, 32, 64) result = algos.value_counts_internal(arr, sort=True)
value_counts = Series(arr).value_counts(sort=False) expected = value_counts.sort_values(ascending=False, kind="stable") tm.assert_series_equal(result, expected)
unstable_sorted = value_counts.sort_values(ascending=False, kind="quicksort") with pytest.raises(AssertionError): tm.assert_series_equal(result, unstable_sorted)
class TestDuplicated: def test_duplicated_with_nas(self): keys = np.array([0, 1, np.nan, 0, 2, np.nan], dtype=object)
result = algos.duplicated(keys) expected = np.array([False, False, False, True, False, True]) tm.assert_numpy_array_equal(result, expected)
result = algos.duplicated(keys, keep="first") expected = np.array([False, False, False, True, False, True]) tm.assert_numpy_array_equal(result, expected)
result = algos.duplicated(keys, keep="last") expected = np.array([True, False, True, False, False, False]) tm.assert_numpy_array_equal(result, expected)
result = algos.duplicated(keys, keep=False) expected = np.array([True, False, True, True, False, True]) tm.assert_numpy_array_equal(result, expected)
keys = np.empty(8, dtype=object) for i, t in enumerate( zip([0, 0, np.nan, np.nan] * 2, [0, np.nan, 0, np.nan] * 2, strict=True) ): keys[i] = t
result = algos.duplicated(keys) falses = [False] * 4 trues = [True] * 4 expected = np.array(falses + trues) tm.assert_numpy_array_equal(result, expected)
result = algos.duplicated(keys, keep="last") expected = np.array(trues + falses) tm.assert_numpy_array_equal(result, expected)
result = algos.duplicated(keys, keep=False) expected = np.array(trues + trues) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize( "case", [ np.array([1, 2, 1, 5, 3, 2, 4, 1, 5, 6]), np.array([1.1, 2.2, 1.1, np.nan, 3.3, 2.2, 4.4, 1.1, np.nan, 6.6]), np.array( [ 1 + 1j, 2 + 2j, 1 + 1j, 5 + 5j, 3 + 3j, 2 + 2j, 4 + 4j, 1 + 1j, 5 + 5j, 6 + 6j, ] ), np.array(["a", "b", "a", "e", "c", "b", "d", "a", "e", "f"], dtype=object), np.array([1, 2**63, 1, 3**5, 10, 2**63, 39, 1, 3**5, 7], dtype=np.uint64), ], ) def test_numeric_object_likes(self, case): exp_first = np.array( [False, False, True, False, False, True, False, True, True, False] ) exp_last = np.array( [True, True, True, True, False, False, False, False, False, False] ) exp_false = exp_first | exp_last
res_first = algos.duplicated(case, keep="first") tm.assert_numpy_array_equal(res_first, exp_first)
res_last = algos.duplicated(case, keep="last") tm.assert_numpy_array_equal(res_last, exp_last)
res_false = algos.duplicated(case, keep=False) tm.assert_numpy_array_equal(res_false, exp_false)
# index for idx in [Index(case), Index(case, dtype="category")]: res_first = idx.duplicated(keep="first") tm.assert_numpy_array_equal(res_first, exp_first)
res_last = idx.duplicated(keep="last") tm.assert_numpy_array_equal(res_last, exp_last)
res_false = idx.duplicated(keep=False) tm.assert_numpy_array_equal(res_false, exp_false)
# series for s in [Series(case), Series(case, dtype="category")]: res_first = s.duplicated(keep="first") tm.assert_series_equal(res_first, Series(exp_first))
res_last = s.duplicated(keep="last") tm.assert_series_equal(res_last, Series(exp_last))
res_false = s.duplicated(keep=False) tm.assert_series_equal(res_false, Series(exp_false))
def test_datetime_likes(self): dt = [ "2011-01-01", "2011-01-02", "2011-01-01", "NaT", "2011-01-03", "2011-01-02", "2011-01-04", "2011-01-01", "NaT", "2011-01-06", ] td = [ "1 days", "2 days", "1 days", "NaT", "3 days", "2 days", "4 days", "1 days", "NaT", "6 days", ]
cases = [ np.array([Timestamp(d) for d in dt]), np.array([Timestamp(d, tz="US/Eastern") for d in dt]), np.array([Period(d, freq="D") for d in dt]), np.array([np.datetime64(d, "ns") for d in dt]), np.array([Timedelta(d) for d in td]), ]
exp_first = np.array( [False, False, True, False, False, True, False, True, True, False] ) exp_last = np.array( [True, True, True, True, False, False, False, False, False, False] ) exp_false = exp_first | exp_last
for case in cases: res_first = algos.duplicated(case, keep="first") tm.assert_numpy_array_equal(res_first, exp_first)
res_last = algos.duplicated(case, keep="last") tm.assert_numpy_array_equal(res_last, exp_last)
res_false = algos.duplicated(case, keep=False) tm.assert_numpy_array_equal(res_false, exp_false)
# index for idx in [ Index(case), Index(case, dtype="category"), Index(case, dtype=object), ]: res_first = idx.duplicated(keep="first") tm.assert_numpy_array_equal(res_first, exp_first)
res_last = idx.duplicated(keep="last") tm.assert_numpy_array_equal(res_last, exp_last)
res_false = idx.duplicated(keep=False) tm.assert_numpy_array_equal(res_false, exp_false)
# series for s in [ Series(case), Series(case, dtype="category"), Series(case, dtype=object), ]: res_first = s.duplicated(keep="first") tm.assert_series_equal(res_first, Series(exp_first))
res_last = s.duplicated(keep="last") tm.assert_series_equal(res_last, Series(exp_last))
res_false = s.duplicated(keep=False) tm.assert_series_equal(res_false, Series(exp_false))
@pytest.mark.parametrize("case", [Index([1, 2, 3]), pd.RangeIndex(0, 3)]) def test_unique_index(self, case): assert case.is_unique is True tm.assert_numpy_array_equal(case.duplicated(), np.array([False, False, False]))
@pytest.mark.parametrize( "arr, uniques", [ ( [(0, 0), (0, 1), (1, 0), (1, 1), (0, 0), (0, 1), (1, 0), (1, 1)], [(0, 0), (0, 1), (1, 0), (1, 1)], ), ( [("b", "c"), ("a", "b"), ("a", "b"), ("b", "c")], [("b", "c"), ("a", "b")], ), ([("a", 1), ("b", 2), ("a", 3), ("a", 1)], [("a", 1), ("b", 2), ("a", 3)]), ], ) def test_unique_tuples(self, arr, uniques): # https://github.com/pandas-dev/pandas/issues/16519 expected = np.empty(len(uniques), dtype=object) expected[:] = uniques
msg = ( r"unique requires a Series, Index, ExtensionArray, np.ndarray " r"or NumpyExtensionArray got list" ) with pytest.raises(TypeError, match=msg): # GH#52986 pd.unique(arr)
res = pd.unique(com.asarray_tuplesafe(arr, dtype=object)) tm.assert_numpy_array_equal(res, expected)
@pytest.mark.parametrize( "array,expected", [ ( [1 + 1j, 0, 1, 1j, 1 + 2j, 1 + 2j], np.array([(1 + 1j), 0j, (1 + 0j), 1j, (1 + 2j)], dtype=complex), ) ], ) def test_unique_complex_numbers(self, array, expected): # GH 17927 msg = ( r"unique requires a Series, Index, ExtensionArray, np.ndarray " r"or NumpyExtensionArray got list" )
with pytest.raises(TypeError, match=msg): # GH#52986 pd.unique(array)
res = pd.unique(np.array(array)) tm.assert_numpy_array_equal(res, expected)
class TestHashTable: @pytest.mark.parametrize( "htable, data", [ ( ht.PyObjectHashTable, np.array([f"foo_{i}" for i in range(1000)], dtype=object), ), ( ht.StringHashTable, np.array([f"foo_{i}" for i in range(1000)], dtype=object), ), (ht.Float64HashTable, np.arange(1000, dtype=np.float64)), (ht.Int64HashTable, np.arange(1000, dtype=np.int64)), (ht.UInt64HashTable, np.arange(1000, dtype=np.uint64)), ], ) def test_hashtable_unique(self, htable, data, writable): # output of maker has guaranteed unique elements s = Series(data, dtype=data.dtype) if htable == ht.Float64HashTable: # add NaN for float column s.loc[500] = np.nan elif htable == ht.PyObjectHashTable: # use different NaN types for object column s.loc[500:502] = [np.nan, None, NaT]
# create duplicated selection s_duplicated = s.sample(frac=3, replace=True).reset_index(drop=True) s_duplicated.values.setflags(write=writable)
# drop_duplicates has own cython code (hash_table_func_helper.pxi) # and is tested separately; keeps first occurrence like ht.unique() expected_unique = s_duplicated.drop_duplicates(keep="first").values result_unique = htable().unique(s_duplicated.values) tm.assert_numpy_array_equal(result_unique, expected_unique)
# test return_inverse=True # reconstruction can only succeed if the inverse is correct result_unique, result_inverse = htable().unique( s_duplicated.values, return_inverse=True ) tm.assert_numpy_array_equal(result_unique, expected_unique) reconstr = result_unique[result_inverse] tm.assert_numpy_array_equal(reconstr, s_duplicated.values)
@pytest.mark.parametrize( "htable, data", [ ( ht.PyObjectHashTable, np.array([f"foo_{i}" for i in range(1000)], dtype=object), ), ( ht.StringHashTable, np.array([f"foo_{i}" for i in range(1000)], dtype=object), ), (ht.Float64HashTable, np.arange(1000, dtype=np.float64)), (ht.Int64HashTable, np.arange(1000, dtype=np.int64)), (ht.UInt64HashTable, np.arange(1000, dtype=np.uint64)), ], ) def test_hashtable_factorize(self, htable, writable, data): # output of maker has guaranteed unique elements s = Series(data, dtype=data.dtype) if htable == ht.Float64HashTable: # add NaN for float column s.loc[500] = np.nan elif htable == ht.PyObjectHashTable: # use different NaN types for object column s.loc[500:502] = [np.nan, None, NaT]
# create duplicated selection s_duplicated = s.sample(frac=3, replace=True).reset_index(drop=True) s_duplicated.values.setflags(write=writable) na_mask = s_duplicated.isna().values
result_unique, result_inverse = htable().factorize(s_duplicated.values)
# drop_duplicates has own cython code (hash_table_func_helper.pxi) # and is tested separately; keeps first occurrence like ht.factorize() # since factorize removes all NaNs, we do the same here expected_unique = s_duplicated.dropna().drop_duplicates().values tm.assert_numpy_array_equal(result_unique, expected_unique)
# reconstruction can only succeed if the inverse is correct. Since # factorize removes the NaNs, those have to be excluded here as well result_reconstruct = result_unique[result_inverse[~na_mask]] expected_reconstruct = s_duplicated.dropna().values tm.assert_numpy_array_equal(result_reconstruct, expected_reconstruct)
class TestRank: @pytest.mark.parametrize( "arr", [ [np.nan, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 3, np.nan], [4.0, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 4.0, np.nan], ], ) def test_scipy_compat(self, arr): sp_stats = pytest.importorskip("scipy.stats")
arr = np.array(arr)
mask = ~np.isfinite(arr) result = libalgos.rank_1d(arr) arr[mask] = np.inf exp = sp_stats.rankdata(arr) exp[mask] = np.nan tm.assert_almost_equal(result, exp)
def test_basic(self, writable, any_int_numpy_dtype): exp = np.array([1, 2], dtype=np.float64)
data = np.array([1, 100], dtype=any_int_numpy_dtype) data.setflags(write=writable) ser = Series(data) result = algos.rank(ser) tm.assert_numpy_array_equal(result, exp)
@pytest.mark.parametrize("dtype", [np.float64, np.uint64]) def test_uint64_overflow(self, dtype): exp = np.array([1, 2], dtype=np.float64)
s = Series([1, 2**63], dtype=dtype) tm.assert_numpy_array_equal(algos.rank(s), exp)
@pytest.mark.parametrize("method", ["average", "min", "max"]) def test_rank_tiny_values(self, method): # GH62036: regression test for ranking with tiny float values exp = np.array([4.0, 1.0, 3.0, np.nan, 2.0], dtype=np.float64) s = Series( [5.4954145e29, -9.791984e-21, 9.3715776e-26, pd.NA, 1.8790257e-28], dtype="Float64", ) s = s.astype(object) result = algos.rank(s, method=method) tm.assert_numpy_array_equal(result, exp)
def test_too_many_ndims(self): arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]) msg = "Array with ndim > 2 are not supported"
with pytest.raises(TypeError, match=msg): algos.rank(arr)
@pytest.mark.single_cpu def test_pct_max_many_rows(self): # GH 18271 values = np.arange(2**24 + 1) result = algos.rank(values, pct=True).max() assert result == 1
values = np.arange(2**25 + 2).reshape(2**24 + 1, 2) result = algos.rank(values, pct=True).max() assert result == 1
class TestMode: def test_no_mode(self): exp = Series([], dtype=np.float64, index=Index([], dtype=int)) result, _ = algos.mode(np.array([])) tm.assert_numpy_array_equal(result, exp.values)
def test_mode_single(self, any_real_numpy_dtype): # GH 15714 exp_single = [1] data_single = [1]
exp_multi = [1] data_multi = [1, 1]
ser = Series(data_single, dtype=any_real_numpy_dtype) exp = Series(exp_single, dtype=any_real_numpy_dtype) result, _ = algos.mode(ser.values) tm.assert_numpy_array_equal(result, exp.values) tm.assert_series_equal(ser.mode(), exp)
ser = Series(data_multi, dtype=any_real_numpy_dtype) exp = Series(exp_multi, dtype=any_real_numpy_dtype) result, _ = algos.mode(ser.values) tm.assert_numpy_array_equal(result, exp.values) tm.assert_series_equal(ser.mode(), exp)
def test_mode_obj_int(self): exp = Series([1], dtype=int) result, _ = algos.mode(exp.values) tm.assert_numpy_array_equal(result, exp.values)
exp = Series(["a", "b", "c"], dtype=object) result, _ = algos.mode(exp.values) tm.assert_numpy_array_equal(result, exp.values)
def test_number_mode(self, any_real_numpy_dtype): exp_single = [1] data_single = [1] * 5 + [2] * 3
exp_multi = [1, 3] data_multi = [1] * 5 + [2] * 3 + [3] * 5
ser = Series(data_single, dtype=any_real_numpy_dtype) exp = Series(exp_single, dtype=any_real_numpy_dtype) result, _ = algos.mode(ser.values) tm.assert_numpy_array_equal(result, exp.values) tm.assert_series_equal(ser.mode(), exp)
ser = Series(data_multi, dtype=any_real_numpy_dtype) exp = Series(exp_multi, dtype=any_real_numpy_dtype) result, _ = algos.mode(ser.values) tm.assert_numpy_array_equal(result, exp.values) tm.assert_series_equal(ser.mode(), exp)
def test_strobj_mode(self): exp = ["b"] data = ["a"] * 2 + ["b"] * 3
ser = Series(data, dtype="c") exp = Series(exp, dtype="c") result, _ = algos.mode(ser.values) tm.assert_numpy_array_equal(result, exp.values) tm.assert_series_equal(ser.mode(), exp)
@pytest.mark.parametrize("dt", [str, object]) def test_strobj_multi_char(self, dt, using_infer_string): exp = ["bar"] data = ["foo"] * 2 + ["bar"] * 3
ser = Series(data, dtype=dt) exp = Series(exp, dtype=dt) result, _ = algos.mode(ser.values) if using_infer_string and dt is str: tm.assert_extension_array_equal(result, exp.values) else: tm.assert_numpy_array_equal(result, exp.values) tm.assert_series_equal(ser.mode(), exp)
def test_datelike_mode(self): exp = Series(["1900-05-03", "2011-01-03", "2013-01-02"], dtype="M8[ns]") ser = Series(["2011-01-03", "2013-01-02", "1900-05-03"], dtype="M8[ns]") tm.assert_extension_array_equal(algos.mode(ser.values), exp._values) tm.assert_series_equal(ser.mode(), exp)
exp = Series(["2011-01-03", "2013-01-02"], dtype="M8[ns]") ser = Series( ["2011-01-03", "2013-01-02", "1900-05-03", "2011-01-03", "2013-01-02"], dtype="M8[ns]", ) tm.assert_extension_array_equal(algos.mode(ser.values), exp._values) tm.assert_series_equal(ser.mode(), exp)
def test_timedelta_mode(self): exp = Series(["-1 days", "0 days", "1 days"], dtype="timedelta64[ns]") ser = Series(["1 days", "-1 days", "0 days"], dtype="timedelta64[ns]") tm.assert_extension_array_equal(algos.mode(ser.values), exp._values) tm.assert_series_equal(ser.mode(), exp)
exp = Series(["2 min", "1 day"], dtype="timedelta64[ns]") ser = Series( ["1 day", "1 day", "-1 day", "-1 day 2 min", "2 min", "2 min"], dtype="timedelta64[ns]", ) tm.assert_extension_array_equal(algos.mode(ser.values), exp._values) tm.assert_series_equal(ser.mode(), exp)
def test_mixed_dtype(self): exp = Series(["foo"], dtype=object) ser = Series([1, "foo", "foo"]) result, _ = algos.mode(ser.values) tm.assert_numpy_array_equal(result, exp.values) tm.assert_series_equal(ser.mode(), exp)
def test_uint64_overflow(self): exp = Series([2**63], dtype=np.uint64) ser = Series([1, 2**63, 2**63], dtype=np.uint64) result, _ = algos.mode(ser.values) tm.assert_numpy_array_equal(result, exp.values) tm.assert_series_equal(ser.mode(), exp)
exp = Series([1, 2**63], dtype=np.uint64) ser = Series([1, 2**63], dtype=np.uint64) result, _ = algos.mode(ser.values) tm.assert_numpy_array_equal(result, exp.values) tm.assert_series_equal(ser.mode(), exp)
def test_categorical(self): c = Categorical([1, 2]) exp = c res = Series(c).mode()._values tm.assert_categorical_equal(res, exp)
c = Categorical([1, "a", "a"]) exp = Categorical(["a"], categories=[1, "a"]) res = Series(c).mode()._values tm.assert_categorical_equal(res, exp)
c = Categorical([1, 1, 2, 3, 3]) exp = Categorical([1, 3], categories=[1, 2, 3]) res = Series(c).mode()._values tm.assert_categorical_equal(res, exp)
def test_index(self): idx = Index([1, 2, 3]) exp = Series([1, 2, 3], dtype=np.int64) result, _ = algos.mode(idx) tm.assert_numpy_array_equal(result, exp.values)
idx = Index([1, "a", "a"]) exp = Series(["a"], dtype=object) result, _ = algos.mode(idx) tm.assert_numpy_array_equal(result, exp.values)
idx = Index([1, 1, 2, 3, 3]) exp = Series([1, 3], dtype=np.int64) result, _ = algos.mode(idx) tm.assert_numpy_array_equal(result, exp.values)
idx = Index( ["1 day", "1 day", "-1 day", "-1 day 2 min", "2 min", "2 min"], dtype="timedelta64[ns]", ) with pytest.raises(AttributeError, match="TimedeltaIndex"): # algos.mode expects Arraylike, does *not* unwrap TimedeltaIndex algos.mode(idx)
def test_ser_mode_with_name(self): # GH 46737 ser = Series([1, 1, 3], name="foo") result = ser.mode() expected = Series([1], name="foo") tm.assert_series_equal(result, expected)
class TestDiff: @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"]) def test_diff_datetimelike_nat(self, dtype): # NaT - NaT is NaT, not 0 arr = np.arange(12).astype(np.int64).view(dtype).reshape(3, 4) arr[:, 2] = arr.dtype.type("NaT", "ns") result = algos.diff(arr, 1, axis=0)
expected = np.ones(arr.shape, dtype="timedelta64[ns]") * 4 expected[:, 2] = np.timedelta64("NaT", "ns") expected[0, :] = np.timedelta64("NaT", "ns")
tm.assert_numpy_array_equal(result, expected)
result = algos.diff(arr.T, 1, axis=1) tm.assert_numpy_array_equal(result, expected.T)
def test_diff_ea_axis(self): dta = date_range("2016-01-01", periods=3, tz="US/Pacific")._data
msg = "cannot diff DatetimeArray on axis=1" with pytest.raises(ValueError, match=msg): algos.diff(dta, 1, axis=1)
@pytest.mark.parametrize("dtype", ["int8", "int16"]) def test_diff_low_precision_int(self, dtype): arr = np.array([0, 1, 1, 0, 0], dtype=dtype) result = algos.diff(arr, 1) expected = np.array([np.nan, 1, 0, -1, 0], dtype="float32") tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("op", [np.array, pd.array])def test_union_with_duplicates(op): # GH#36289 lvals = op([3, 1, 3, 4]) rvals = op([2, 3, 1, 1]) expected = op([3, 3, 1, 1, 4, 2]) if isinstance(expected, np.ndarray): result = algos.union_with_duplicates(lvals, rvals) tm.assert_numpy_array_equal(result, expected) else: result = algos.union_with_duplicates(lvals, rvals) tm.assert_extension_array_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392from collections.abc import Callableimport copyfrom datetime import datetimeimport operatorimport re
import numpy as npimport pytest
from pandas._libs.properties import cache_readonly
import pandas as pdimport pandas._testing as tmfrom pandas.api.typing import Expressionfrom pandas.tests.test_register_accessor import ensure_removed
@pytest.mark.parametrize( ("expr", "expected_values", "expected_str"), [ (pd.col("a"), [1, 2], "col('a')"), (pd.col("a") * 2, [2, 4], "col('a') * 2"), (pd.col("a").sum(), [3, 3], "col('a').sum()"), (pd.col("a") + 1, [2, 3], "col('a') + 1"), (1 + pd.col("a"), [2, 3], "1 + col('a')"), (pd.col("a") - 1, [0, 1], "col('a') - 1"), (1 - pd.col("a"), [0, -1], "1 - col('a')"), (pd.col("a") * 1, [1, 2], "col('a') * 1"), (1 * pd.col("a"), [1, 2], "1 * col('a')"), (2 ** pd.col("a"), [2, 4], "2 ** col('a')"), (pd.col("a") ** 2, [1, 4], "col('a') ** 2"), (pd.col("a") / 1, [1.0, 2.0], "col('a') / 1"), (1 / pd.col("a"), [1.0, 0.5], "1 / col('a')"), (pd.col("a") // 1, [1, 2], "col('a') // 1"), (1 // pd.col("a"), [1, 0], "1 // col('a')"), (pd.col("a") % 1, [0, 0], "col('a') % 1"), (1 % pd.col("a"), [0, 1], "1 % col('a')"), (pd.col("a") > 1, [False, True], "col('a') > 1"), (pd.col("a") >= 1, [True, True], "col('a') >= 1"), (pd.col("a") < 1, [False, False], "col('a') < 1"), (pd.col("a") <= 1, [True, False], "col('a') <= 1"), (pd.col("a") == 1, [True, False], "col('a') == 1"), (np.power(pd.col("a"), 2), [1, 4], "power(col('a'), 2)"), (np.divide(pd.col("a"), pd.col("a")), [1.0, 1.0], "divide(col('a'), col('a'))"), ( (pd.col("a") + 1) * (pd.col("b") + 2), [10, 18], "(col('a') + 1) * (col('b') + 2)", ), ( (pd.col("a") - 1).astype("bool"), [False, True], "(col('a') - 1).astype('bool')", ), # Unary operators (-pd.col("a"), [-1, -2], "-col('a')"), (+pd.col("a"), [1, 2], "+col('a')"), (-(pd.col("a") + 1), [-2, -3], "-(col('a') + 1)"), (-pd.col("a") * 2, [-2, -4], "(-col('a')) * 2"), (abs(pd.col("a")), [1, 2], "abs(col('a'))"), (abs(pd.col("a") - 2), [1, 0], "abs(col('a') - 2)"), ],)def test_col_simple( expr: Expression, expected_values: list[object], expected_str: str) -> None: # https://github.com/pandas-dev/pandas/pull/64267 df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) result = df.assign(c=expr) expected = pd.DataFrame({"a": [1, 2], "b": [3, 4], "c": expected_values}) tm.assert_frame_equal(result, expected) assert str(expr) == expected_str
@pytest.mark.parametrize( ("op", "expected_values", "expected_str"), [ (operator.iadd, [3, 4], "col('a') + 2"), (operator.iand, [0, 2], "col('a') & 2"), (operator.ifloordiv, [0, 1], "col('a') // 2"), (operator.imod, [1, 0], "col('a') % 2"), (operator.imul, [2, 4], "col('a') * 2"), (operator.ior, [3, 2], "col('a') | 2"), (operator.ipow, [1, 4], "col('a') ** 2"), (operator.isub, [-1, 0], "col('a') - 2"), (operator.itruediv, [0.5, 1.0], "col('a') / 2"), (operator.ixor, [3, 0], "col('a') ^ 2"), ],)def test_inplace_ops( op: Callable, expected_values: list[object], expected_str: str) -> None: # https://github.com/pandas-dev/pandas/pull/64267 df = pd.DataFrame({"a": [1, 2]}) expr = pd.col("a") expr = op(expr, 2) result = df.assign(c=expr) expected = pd.DataFrame({"a": [1, 2], "c": expected_values}) tm.assert_frame_equal(result, expected) assert str(expr) == expected_str
def test_matmul(): # https://github.com/pandas-dev/pandas/pull/64267 df = pd.DataFrame({"a": [1, 2]})
expr = pd.col("a") @ [3, 4] result = df.assign(c=expr) expected = pd.DataFrame({"a": [1, 2], "c": [11, 11]}) tm.assert_frame_equal(result, expected) assert str(expr) == "col('a') @ [3, 4]"
expr = [3, 4] @ pd.col("a") result = df.assign(c=expr) expected = pd.DataFrame({"a": [1, 2], "c": [11, 11]}) tm.assert_frame_equal(result, expected) assert str(expr) == "[3, 4] @ col('a')"
def test_frame_getitem() -> None: # https://github.com/pandas-dev/pandas/pull/63439 df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) expr = pd.col("a") == 2 result = df[expr] expected = df.iloc[[1]] tm.assert_frame_equal(result, expected)
def test_frame_setitem() -> None: # https://github.com/pandas-dev/pandas/pull/63439 df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) expr = pd.col("a") == 2
result = df.copy() result[expr] = 100 expected = pd.DataFrame({"a": [1, 100], "b": [3, 100]}) tm.assert_frame_equal(result, expected)
def test_frame_loc() -> None: # https://github.com/pandas-dev/pandas/pull/63439 df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) expr = pd.col("a") == 2 result = df.copy() result.loc[expr, "b"] = 100 expected = pd.DataFrame({"a": [1, 2], "b": [3, 100]}) tm.assert_frame_equal(result, expected)
def test_frame_iloc() -> None: # https://github.com/pandas-dev/pandas/pull/63439 df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) expr = pd.col("a") == 2 result = df.copy() result.iloc[expr, 1] = 100 expected = pd.DataFrame({"a": [1, 2], "b": [3, 100]}) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize( ("expr", "expected_values", "expected_str"), [ (pd.col("a").dt.year, [2020], "col('a').dt.year"), (pd.col("a").dt.strftime("%B"), ["January"], "col('a').dt.strftime('%B')"), (pd.col("b").str.upper(), ["FOO"], "col('b').str.upper()"), ],)def test_namespaces( expr: Expression, expected_values: list[object], expected_str: str) -> None: df = pd.DataFrame({"a": [datetime(2020, 1, 1)], "b": ["foo"]}) result = df.assign(c=expr) expected = pd.DataFrame( {"a": [datetime(2020, 1, 1)], "b": ["foo"], "c": expected_values} ) tm.assert_frame_equal(result, expected, check_dtype=False) assert str(expr) == expected_str
def test_invalid() -> None: df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}) with pytest.raises(ValueError, match=r"did you mean one of \['a', 'b'\] instead"): df.assign(c=pd.col("c").mean()) df = pd.DataFrame({f"col_{i}": [0] for i in range(11)}) msg = ( "did you mean one of " r"\['col_0', 'col_1', 'col_2', 'col_3', " "'col_4', 'col_5', 'col_6', 'col_7', " r"'col_8', 'col_9',\.\.\.\] instead" ) "" with pytest.raises(ValueError, match=msg): df.assign(c=pd.col("c").mean())
def test_custom_accessor() -> None: df = pd.DataFrame({"a": [1, 2, 3]})
class XYZAccessor: def __init__(self, pandas_obj): self._obj = pandas_obj
def mean(self): return self._obj.mean()
with ensure_removed(pd.Series, "xyz"): pd.api.extensions.register_series_accessor("xyz")(XYZAccessor) result = df.assign(b=pd.col("a").xyz.mean()) expected = pd.DataFrame({"a": [1, 2, 3], "b": [2.0, 2.0, 2.0]}) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize( ("expr", "expected_values", "expected_str"), [ ( pd.col("a") & pd.col("b"), [False, False, True, False], "col('a') & col('b')", ), ( pd.col("a") & True, [True, False, True, False], "col('a') & True", ), ( pd.col("a") | pd.col("b"), [True, True, True, True], "col('a') | col('b')", ), ( pd.col("a") | False, [True, False, True, False], "col('a') | False", ), ( pd.col("a") ^ pd.col("b"), [True, True, False, True], "col('a') ^ col('b')", ), ( pd.col("a") ^ True, [False, True, False, True], "col('a') ^ True", ), ( ~pd.col("a"), [False, True, False, True], "~col('a')", ), ],)def test_col_logical_ops( expr: Expression, expected_values: list[bool], expected_str: str) -> None: # https://github.com/pandas-dev/pandas/issues/63322 df = pd.DataFrame({"a": [True, False, True, False], "b": [False, True, True, True]}) result = df.assign(c=expr) expected = pd.DataFrame( { "a": [True, False, True, False], "b": [False, True, True, True], "c": expected_values, } ) tm.assert_frame_equal(result, expected) assert str(expr) == expected_str
# Test that the expression works with .loc result = df.loc[expr] expected = df[expected_values] tm.assert_frame_equal(result, expected)
def test_expression_getitem() -> None: # https://github.com/pandas-dev/pandas/pull/63439 df = pd.DataFrame({"a": [1, 2, 3]}) expr = pd.col("a")[1] expected_str = "col('a')[1]"
assert str(expr) == expected_str
result = df.assign(b=expr) expected = pd.DataFrame({"a": [1, 2, 3], "b": [2, 2, 2]}) tm.assert_frame_equal(result, expected)
def test_property() -> None: # https://github.com/pandas-dev/pandas/pull/63439 df = pd.DataFrame({"a": [1, 2, 3]}) expr = pd.col("a").index expected_str = "col('a').index"
assert str(expr) == expected_str
result = df.assign(b=expr) expected = pd.DataFrame({"a": [1, 2, 3], "b": [0, 1, 2]}) tm.assert_frame_equal(result, expected)
def test_cached_property() -> None: # https://github.com/pandas-dev/pandas/pull/63439 # Ensure test is valid assert isinstance(pd.Index.dtype, cache_readonly)
df = pd.DataFrame({"a": [1, 2, 3]}) expr = pd.col("a").index.dtype expected_str = "col('a').index.dtype" assert str(expr) == expected_str
result = df.assign(b=expr) expected = pd.DataFrame({"a": [1, 2, 3], "b": np.int64}) tm.assert_frame_equal(result, expected)
def test_qcut() -> None: # https://github.com/pandas-dev/pandas/pull/63439 df = pd.DataFrame({"a": [1, 2, 3]}) expr = pd.qcut(pd.col("a"), 3) expected_str = "qcut(x=col('a'), q=3, labels=None, retbins=False, precision=3)" assert str(expr) == expected_str, str(expr)
result = df.assign(b=expr) expected = pd.DataFrame({"a": [1, 2, 3], "b": pd.qcut(df["a"], 3)}) tm.assert_frame_equal(result, expected)
def test_where() -> None: # https://github.com/pandas-dev/pandas/pull/63439 df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) expr = pd.col("a").where(pd.col("b") == 5, 100) expected_str = "col('a').where(col('b') == 5, 100)" assert str(expr) == expected_str, str(expr)
result = df.assign(c=expr) expected = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [100, 2, 100]}) tm.assert_frame_equal(result, expected)
expr = pd.col("a").where(pd.col("b") == 5, pd.col("a") + 1) expected_str = "col('a').where(col('b') == 5, col('a') + 1)" assert str(expr) == expected_str, str(expr)
result = df.assign(c=expr) expected = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [2, 2, 4]}) tm.assert_frame_equal(result, expected)
# Unsupported opsdef test_bool(): with pytest.raises(TypeError, match="boolean value of an expression is ambiguous"): bool(pd.col("a"))
def test_iter(): with pytest.raises(TypeError, match="Expression objects are not iterable"): iter(pd.col("a"))
def test_contains(): # Python 3.14 changes the message from "is not iterable" to # "is not a container or iterable" with pytest.raises( TypeError, match="argument of type 'Expression' is not .*iterable" ): 1 in pd.col("a")
def test_copy(): with pytest.raises(TypeError, match="Expression objects are not copiable"): copy.copy(pd.col("a"))
def test_deepcopy(): with pytest.raises(TypeError, match="Expression objects are not copiable"): copy.deepcopy(pd.col("a"))
def test_divmod(): msg = re.escape("unsupported operand type(s) for divmod(): 'Expression' and 'int'") with pytest.raises(TypeError, match=msg): divmod(pd.col("a"), 2)
def test_len(): with pytest.raises(TypeError, match="object of type 'Expression' has no len()"): len(pd.col("a"))
def test_round(): msg = "type Expression doesn't define __round__ method" with pytest.raises(TypeError, match=msg): round(pd.col("a"), 2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273import collectionsfrom functools import partialimport stringimport subprocessimport sys
import numpy as npimport pytest
from pandas.compat import WASM
import pandas as pdfrom pandas import Seriesimport pandas._testing as tmfrom pandas.core import opsimport pandas.core.common as comfrom pandas.util.version import Version
class TestGetCallableName: def fn(self, x): return x
partial1 = partial(fn) partial2 = partial(partial1) lambda_ = lambda x: x
class SomeCall: def __call__(self): # This shouldn't actually get called below; SomeCall.__init__ # should. raise NotImplementedError
@pytest.mark.parametrize( "func, expected", [ (fn, "fn"), (partial1, "fn"), (partial2, "fn"), (lambda_, "<lambda>"), (SomeCall(), "SomeCall"), (1, None), ], ) def test_get_callable_name(self, func, expected): assert com.get_callable_name(func) == expected
class TestRandomState: def test_seed(self): seed = 5 assert com.random_state(seed).uniform() == np.random.RandomState(seed).uniform()
def test_object(self): seed = 10 state_obj = np.random.RandomState(seed) assert ( com.random_state(state_obj).uniform() == np.random.RandomState(seed).uniform() )
def test_default(self): assert com.random_state() is np.random
def test_array_like(self): state = np.random.default_rng(None).integers(0, 2**31, size=624, dtype="uint32") assert ( com.random_state(state).uniform() == np.random.RandomState(state).uniform() )
def test_bit_generators(self): seed = 3 assert ( com.random_state(np.random.MT19937(seed)).uniform() == np.random.RandomState(np.random.MT19937(seed)).uniform() )
seed = 11 assert ( com.random_state(np.random.PCG64(seed)).uniform() == np.random.RandomState(np.random.PCG64(seed)).uniform() )
@pytest.mark.parametrize("state", ["test", 5.5]) def test_error(self, state): msg = ( "random_state must be an integer, array-like, a BitGenerator, Generator, " "a numpy RandomState, or None" ) with pytest.raises(ValueError, match=msg): com.random_state(state)
@pytest.mark.parametrize("args, expected", [((1, 2, None), True), ((1, 2, 3), False)])def test_any_none(args, expected): assert com.any_none(*args) is expected
@pytest.mark.parametrize( "args, expected", [((1, 2, 3), True), ((1, 2, None), False), ((None, None, None), False)],)def test_all_not_none(args, expected): assert com.all_not_none(*args) is expected
@pytest.mark.parametrize( "left, right, expected", [ (Series([1], name="x"), Series([2], name="x"), "x"), (Series([1], name="x"), Series([2], name="y"), None), (Series([1]), Series([2], name="x"), None), (Series([1], name="x"), Series([2]), None), (Series([1], name="x"), [2], "x"), ([1], Series([2], name="y"), "y"), # matching NAs (Series([1], name=np.nan), pd.Index([], name=np.nan), np.nan), (Series([1], name=np.nan), pd.Index([], name=pd.NaT), None), (Series([1], name=pd.NA), pd.Index([], name=pd.NA), pd.NA), # tuple name GH#39757 ( Series([1], name=np.int64(1)), pd.Index([], name=(np.int64(1), np.int64(2))), None, ), ( Series([1], name=(np.int64(1), np.int64(2))), pd.Index([], name=(np.int64(1), np.int64(2))), (np.int64(1), np.int64(2)), ), pytest.param( Series([1], name=(np.float64("nan"), np.int64(2))), pd.Index([], name=(np.float64("nan"), np.int64(2))), (np.float64("nan"), np.int64(2)), marks=pytest.mark.xfail( reason="Not checking for matching NAs inside tuples." ), ), ],)def test_maybe_match_name(left, right, expected): res = ops.common._maybe_match_name(left, right) assert res is expected or res == expected
@pytest.mark.parametrize( "into, msg", [ ( # uninitialized defaultdict collections.defaultdict, r"to_dict\(\) only accepts initialized defaultdicts", ), ( # non-mapping subtypes,, instance [], "unsupported type: <class 'list'>", ), ( # non-mapping subtypes, class list, "unsupported type: <class 'list'>", ), ],)def test_standardize_mapping_type_error(into, msg): with pytest.raises(TypeError, match=msg): com.standardize_mapping(into)
def test_standardize_mapping(): fill = {"bad": "data"} assert com.standardize_mapping(fill) == dict
# Convert instance to type assert com.standardize_mapping({}) == dict
dd = collections.defaultdict(list) assert isinstance(com.standardize_mapping(dd), partial)
def test_git_version(): # GH 21295 git_version = pd.__git_version__ assert len(git_version) == 40 assert all(c in string.hexdigits for c in git_version)
def test_version_tag(): version = Version(pd.__version__) try: version > Version("0.0.1") except TypeError as err: raise ValueError( "No git tags exist, please sync tags between upstream and your repo" ) from err
@pytest.mark.parametrize("obj", [obj for obj in pd.__dict__.values() if callable(obj)])def test_serializable(obj, temp_file): # GH 35611 unpickled = tm.round_trip_pickle(obj, temp_file) assert type(obj) == type(unpickled)
class TestIsBoolIndexer: def test_non_bool_array_with_na(self): # in particular, this should not raise arr = np.array(["A", "B", np.nan], dtype=object) assert not com.is_bool_indexer(arr)
def test_list_subclass(self): # GH#42433
class MyList(list): pass
val = MyList(["a"])
assert not com.is_bool_indexer(val)
val = MyList([True]) assert com.is_bool_indexer(val)
def test_frozenlist(self): # GH#42461 data = {"col1": [1, 2], "col2": [3, 4]} df = pd.DataFrame(data=data)
frozen = df.index.names[1:] assert not com.is_bool_indexer(frozen)
result = df[frozen] expected = df[[]] tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("scalar", [1, True]) def test_numpyextensionarray(self, scalar): # GH 63391 arr = pd.arrays.NumpyExtensionArray(np.array([scalar])) assert com.is_bool_indexer(arr) is isinstance(scalar, bool)
@pytest.mark.parametrize("with_exception", [True, False])def test_temp_setattr(with_exception): # GH#45954 ser = Series(dtype=object) ser.name = "first" # Raise a ValueError in either case to satisfy pytest.raises match = "Inside exception raised" if with_exception else "Outside exception raised" with pytest.raises(ValueError, match=match): with com.temp_setattr(ser, "name", "second"): assert ser.name == "second" if with_exception: raise ValueError("Inside exception raised") raise ValueError("Outside exception raised") assert ser.name == "first"
@pytest.mark.skipif(WASM, reason="Can't start subprocesses in WASM")@pytest.mark.single_cpudef test_str_size(): # GH#21758 a = "a" expected = sys.getsizeof(a) pyexe = sys.executable.replace("\\", "/") call = [ pyexe, "-c", "a='a';import sys;sys.getsizeof(a);import pandas;print(sys.getsizeof(a));", ] result = subprocess.check_output(call).decode()[-4:-1].strip("\n") assert int(result) == int(expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299"""Testing that we work in the downstream packages"""
import arrayfrom functools import partialimport importlibimport subprocessimport sys
import numpy as npimport pytest
from pandas.errors import IntCastingNaNError
import pandas as pdfrom pandas import ( DataFrame, DatetimeIndex, Series, TimedeltaIndex,)import pandas._testing as tmfrom pandas.util.version import Version
@pytest.fixturedef df(): return DataFrame({"A": [1, 2, 3]})
def test_dask(df): # dask sets "compute.use_numexpr" to False, so catch the current value # and ensure to reset it afterwards to avoid impacting other tests olduse = pd.get_option("compute.use_numexpr")
try: pytest.importorskip("toolz") dd = pytest.importorskip("dask.dataframe")
ddf = dd.from_pandas(df, npartitions=3) assert ddf.A is not None assert ddf.compute() is not None finally: pd.set_option("compute.use_numexpr", olduse)
# TODO(CoW) see https://github.com/pandas-dev/pandas/pull/51082@pytest.mark.skip(reason="not implemented with CoW")def test_dask_ufunc(): # dask sets "compute.use_numexpr" to False, so catch the current value # and ensure to reset it afterwards to avoid impacting other tests olduse = pd.get_option("compute.use_numexpr")
try: da = pytest.importorskip("dask.array") dd = pytest.importorskip("dask.dataframe")
s = Series([1.5, 2.3, 3.7, 4.0]) ds = dd.from_pandas(s, npartitions=2)
result = da.log(ds).compute() expected = np.log(s) tm.assert_series_equal(result, expected) finally: pd.set_option("compute.use_numexpr", olduse)
def test_construct_dask_float_array_int_dtype_match_ndarray(): # GH#40110 make sure we treat a float-dtype dask array with the same # rules we would for an ndarray dd = pytest.importorskip("dask.dataframe")
arr = np.array([1, 2.5, 3]) darr = dd.from_array(arr)
res = Series(darr) expected = Series(arr) tm.assert_series_equal(res, expected)
# GH#49599 in 2.0 we raise instead of silently ignoring the dtype msg = "Trying to coerce float values to integers" with pytest.raises(ValueError, match=msg): Series(darr, dtype="i8")
msg = r"Cannot convert non-finite values \(NA or inf\) to integer" arr[2] = np.nan with pytest.raises(IntCastingNaNError, match=msg): Series(darr, dtype="i8") # which is the same as we get with a numpy input with pytest.raises(IntCastingNaNError, match=msg): Series(arr, dtype="i8")
def test_xarray(df): pytest.importorskip("xarray")
assert df.to_xarray() is not None
def test_xarray_cftimeindex_nearest(): # https://github.com/pydata/xarray/issues/3751 cftime = pytest.importorskip("cftime") xarray = pytest.importorskip("xarray")
times = xarray.date_range("0001", periods=2, use_cftime=True) key = cftime.DatetimeGregorian(2000, 1, 1) result = times.get_indexer([key], method="nearest") expected = 1 assert result == expected
@pytest.mark.single_cpudef test_oo_optimizable(): # GH 21071 subprocess.check_call([sys.executable, "-OO", "-c", "import pandas"])
@pytest.mark.single_cpudef test_oo_optimized_datetime_index_unpickle(): # GH 42866 subprocess.check_call( [ sys.executable, "-OO", "-c", ( "import pandas as pd, pickle; " "pickle.loads(pickle.dumps(pd.date_range('2021-01-01', periods=1)))" ), ] )
def test_statsmodels(): smf = pytest.importorskip("statsmodels.formula.api")
df = DataFrame( {"Lottery": range(5), "Literacy": range(5), "Pop1831": range(100, 105)} ) smf.ols("Lottery ~ Literacy + np.log(Pop1831)", data=df).fit()
def test_scikit_learn(): pytest.importorskip("sklearn") from sklearn import ( datasets, svm, )
digits = datasets.load_digits() clf = svm.SVC(gamma=0.001, C=100.0) clf.fit(digits.data[:-1], digits.target[:-1]) clf.predict(digits.data[-1:])
def test_seaborn(mpl_cleanup): seaborn = pytest.importorskip("seaborn") tips = DataFrame( {"day": pd.date_range("2023", freq="D", periods=5), "total_bill": range(5)} ) seaborn.stripplot(x="day", y="total_bill", data=tips)
def test_pandas_datareader(): pytest.importorskip("pandas_datareader")
@pytest.mark.filterwarnings("ignore:Passing a BlockManager:DeprecationWarning")def test_pyarrow(df): pyarrow = pytest.importorskip("pyarrow") table = pyarrow.Table.from_pandas(df) result = table.to_pandas() tm.assert_frame_equal(result, df)
def test_yaml_dump(df): # GH#42748 yaml = pytest.importorskip("yaml")
dumped = yaml.dump(df)
loaded = yaml.load(dumped, Loader=yaml.Loader) tm.assert_frame_equal(df, loaded)
loaded2 = yaml.load(dumped, Loader=yaml.UnsafeLoader) tm.assert_frame_equal(df, loaded2)
@pytest.mark.parametrize("dependency", ["numpy", "dateutil"])def test_missing_required_dependency(monkeypatch, dependency): # GH#61030 original_import = __import__ mock_error = ImportError(f"Mock error for {dependency}")
def mock_import(name, *args, **kwargs): if name == dependency: raise mock_error return original_import(name, *args, **kwargs)
monkeypatch.setattr("builtins.__import__", mock_import)
with pytest.raises(ImportError, match=dependency): importlib.reload(importlib.import_module("pandas"))
def test_frame_setitem_dask_array_into_new_col(request): # GH#47128
# dask sets "compute.use_numexpr" to False, so catch the current value # and ensure to reset it afterwards to avoid impacting other tests olduse = pd.get_option("compute.use_numexpr")
try: dask = pytest.importorskip("dask") da = pytest.importorskip("dask.array") if Version(dask.__version__) <= Version("2025.1.0") and Version( np.__version__ ) >= Version("2.1"): request.applymarker( pytest.mark.xfail(reason="loc.__setitem__ incorrectly mutated column c") )
dda = da.array([1, 2]) df = DataFrame({"a": ["a", "b"]}) df["b"] = dda df["c"] = dda df.loc[[False, True], "b"] = 100 result = df.loc[[1], :] expected = DataFrame({"a": ["b"], "b": [100], "c": [2]}, index=[1]) tm.assert_frame_equal(result, expected) finally: pd.set_option("compute.use_numexpr", olduse)
def test_pandas_priority(): # GH#48347
class MyClass: __pandas_priority__ = 5000
def __radd__(self, other): return self
left = MyClass() right = Series(range(3))
assert right.__add__(left) is NotImplemented assert right + left is left
@pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])@pytest.mark.parametrize( "box", [memoryview, partial(array.array, "i"), "dask", "xarray"])def test_from_obscure_array(dtype, box): # GH#24539 recognize e.g xarray, dask, ... # Note: we dont do this for PeriodArray bc _from_sequence won't accept # an array of integers # TODO: could check with arraylike of Period objects # GH#24539 recognize e.g xarray, dask, ... arr = np.array([1, 2, 3], dtype=np.int64) if box == "dask": da = pytest.importorskip("dask.array") data = da.array(arr) elif box == "xarray": xr = pytest.importorskip("xarray") data = xr.DataArray(arr) else: data = box(arr)
func = {"M8[ns]": pd.to_datetime, "m8[ns]": pd.to_timedelta}[dtype] result = func(arr).array expected = func(data).array tm.assert_equal(result, expected)
# Let's check the Indexes while we're here idx_cls = {"M8[ns]": DatetimeIndex, "m8[ns]": TimedeltaIndex}[dtype] result = idx_cls(arr) expected = idx_cls(data) tm.assert_index_equal(result, expected)
def test_xarray_coerce_unit(): # GH44053 xr = pytest.importorskip("xarray")
arr = xr.DataArray([1, 2, 3]) result = pd.to_datetime(arr, unit="ns") expected = DatetimeIndex( [ "1970-01-01 00:00:00.000000001", "1970-01-01 00:00:00.000000002", "1970-01-01 00:00:00.000000003", ], dtype="datetime64[ns]", freq=None, ) tm.assert_index_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import warnings
import pytest
from pandas.errors import ( AbstractMethodError, Pandas4Warning, Pandas5Warning, PandasChangeWarning, PandasDeprecationWarning, PandasPendingDeprecationWarning, UndefinedVariableError,)
import pandas as pdimport pandas._testing as tm
@pytest.mark.parametrize( "exc", [ "AttributeConflictWarning", "CSSWarning", "CategoricalConversionWarning", "ClosedFileError", "DataError", "DatabaseError", "DtypeWarning", "EmptyDataError", "IncompatibilityWarning", "IndexingError", "InvalidColumnName", "InvalidComparison", "InvalidVersion", "LossySetitemError", "MergeError", "NoBufferPresent", "NumExprClobberingError", "NumbaUtilError", "OptionError", "OutOfBoundsDatetime", "ParserError", "ParserWarning", "PerformanceWarning", "PossibleDataLossError", "PossiblePrecisionLoss", "PyperclipException", "SpecificationError", "UnsortedIndexError", "UnsupportedFunctionCall", "ValueLabelTypeMismatch", ],)def test_exception_importable(exc): from pandas import errors
err = getattr(errors, exc) assert err is not None
# check that we can raise on them
msg = "^$"
with pytest.raises(err, match=msg): raise err()
def test_catch_oob(): from pandas import errors
msg = "Cannot cast 1500-01-01 00:00:00 to unit='ns' without overflow" with pytest.raises(errors.OutOfBoundsDatetime, match=msg): pd.Timestamp("15000101").as_unit("ns")
@pytest.mark.parametrize("is_local", [True, False])def test_catch_undefined_variable_error(is_local): variable_name = "x" if is_local: msg = f"local variable '{variable_name}' is not defined" else: msg = f"name '{variable_name}' is not defined"
with pytest.raises(UndefinedVariableError, match=msg): raise UndefinedVariableError(variable_name, is_local)
class Foo: @classmethod def classmethod(cls): raise AbstractMethodError(cls, methodtype="classmethod")
@property def property(self): raise AbstractMethodError(self, methodtype="property")
def method(self): raise AbstractMethodError(self)
def test_AbstractMethodError_classmethod(): xpr = "This classmethod must be defined in the concrete class Foo" with pytest.raises(AbstractMethodError, match=xpr): Foo.classmethod()
xpr = "This property must be defined in the concrete class Foo" with pytest.raises(AbstractMethodError, match=xpr): Foo().property
xpr = "This method must be defined in the concrete class Foo" with pytest.raises(AbstractMethodError, match=xpr): Foo().method()
@pytest.mark.parametrize( "warn_category, catch_category", [ (Pandas4Warning, PandasChangeWarning), (Pandas4Warning, PandasDeprecationWarning), (Pandas5Warning, PandasChangeWarning), (Pandas5Warning, PandasPendingDeprecationWarning), ],)def test_pandas_warnings(warn_category, catch_category): # https://github.com/pandas-dev/pandas/pull/61468 with tm.assert_produces_warning(catch_category): warnings.warn("test", category=warn_category)
@pytest.mark.parametrize( "warn_category, filter_category", [ (Pandas4Warning, PandasChangeWarning), (Pandas4Warning, PandasDeprecationWarning), (Pandas5Warning, PandasChangeWarning), (Pandas5Warning, PandasPendingDeprecationWarning), ],)def test_pandas_warnings_filter(warn_category, filter_category): # https://github.com/pandas-dev/pandas/pull/61468 # Ensure users can suppress warnings. with tm.assert_produces_warning(None), warnings.catch_warnings(): warnings.filterwarnings(category=filter_category, action="ignore") warnings.warn("test", category=warn_category)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475import operatorimport re
import numpy as npimport pytest
from pandas.compat._optional import import_optional_dependency
from pandas import option_contextimport pandas._testing as tmfrom pandas.core.api import DataFramefrom pandas.core.computation import expressions as exprfrom pandas.util.version import Version
@pytest.fixturedef _frame(): return DataFrame( np.random.default_rng(2).standard_normal((10001, 4)), columns=list("ABCD"), dtype="float64", )
@pytest.fixturedef _frame2(): return DataFrame( np.random.default_rng(2).standard_normal((100, 4)), columns=list("ABCD"), dtype="float64", )
@pytest.fixturedef _mixed(_frame): return DataFrame( { "A": _frame["A"], "B": _frame["B"].astype("float32"), "C": _frame["C"].astype("int64"), "D": _frame["D"].astype("int32"), } )
@pytest.fixturedef _mixed2(_frame2): return DataFrame( { "A": _frame2["A"], "B": _frame2["B"].astype("float32"), "C": _frame2["C"].astype("int64"), "D": _frame2["D"].astype("int32"), } )
@pytest.fixturedef _integer(): return DataFrame( np.random.default_rng(2).integers(1, 100, size=(10001, 4)), columns=list("ABCD"), dtype="int64", )
@pytest.fixturedef _integer_integers(_integer): # integers to get a case with zeros return _integer * np.random.default_rng(2).integers(0, 2, size=np.shape(_integer))
@pytest.fixturedef _integer2(): return DataFrame( np.random.default_rng(2).integers(1, 100, size=(101, 4)), columns=list("ABCD"), dtype="int64", )
@pytest.fixturedef _array(_frame): return _frame["A"].to_numpy()
@pytest.fixturedef _array2(_frame2): return _frame2["A"].to_numpy()
@pytest.fixturedef _array_mixed(_mixed): return _mixed["D"].to_numpy()
@pytest.fixturedef _array_mixed2(_mixed2): return _mixed2["D"].to_numpy()
@pytest.mark.skipif(not expr.USE_NUMEXPR, reason="not using numexpr")class TestExpressions: @staticmethod def call_op(df, other, flex: bool, opname: str): if flex: op = lambda x, y: getattr(x, opname)(y) op.__name__ = opname else: op = getattr(operator, opname)
with option_context("compute.use_numexpr", False): expected = op(df, other)
expr.get_test_result()
result = op(df, other) return result, expected
@pytest.mark.parametrize( "fixture", [ "_integer", "_integer2", "_integer_integers", "_frame", "_frame2", "_mixed", "_mixed2", ], ) @pytest.mark.parametrize("flex", [True, False]) @pytest.mark.parametrize( "arith", ["add", "sub", "mul", "mod", "truediv", "floordiv"] ) def test_run_arithmetic(self, request, fixture, flex, arith, monkeypatch): df = request.getfixturevalue(fixture) with monkeypatch.context() as m: m.setattr(expr, "_MIN_ELEMENTS", 0) result, expected = self.call_op(df, df, flex, arith)
if arith == "truediv": assert all(x.kind == "f" for x in expected.dtypes.values) tm.assert_equal(expected, result)
for i in range(len(df.columns)): result, expected = self.call_op( df.iloc[:, i], df.iloc[:, i], flex, arith ) if arith == "truediv": assert expected.dtype.kind == "f" tm.assert_equal(expected, result)
@pytest.mark.parametrize( "fixture", [ "_integer", "_integer2", "_integer_integers", "_frame", "_frame2", "_mixed", "_mixed2", ], ) @pytest.mark.parametrize("flex", [True, False]) def test_run_binary(self, request, fixture, flex, comparison_op, monkeypatch): """ tests solely that the result is the same whether or not numexpr is enabled. Need to test whether the function does the correct thing elsewhere. """ df = request.getfixturevalue(fixture) arith = comparison_op.__name__ with option_context("compute.use_numexpr", False): other = df + 1
with monkeypatch.context() as m: m.setattr(expr, "_MIN_ELEMENTS", 0) expr.set_test_mode(True)
result, expected = self.call_op(df, other, flex, arith)
used_numexpr = expr.get_test_result() assert used_numexpr, "Did not use numexpr as expected." tm.assert_equal(expected, result)
for i in range(len(df.columns)): binary_comp = other.iloc[:, i] + 1 self.call_op(df.iloc[:, i], binary_comp, flex, "add")
def test_invalid(self): array = np.random.default_rng(2).standard_normal(1_000_001) array2 = np.random.default_rng(2).standard_normal(100)
# no op result = expr._can_use_numexpr(operator.add, None, array, array, "evaluate") assert not result
# min elements result = expr._can_use_numexpr(operator.add, "+", array2, array2, "evaluate") assert not result
# ok, we only check on first part of expression result = expr._can_use_numexpr(operator.add, "+", array, array2, "evaluate") assert result
@pytest.mark.filterwarnings("ignore:invalid value encountered in:RuntimeWarning") @pytest.mark.parametrize( "opname,op_str", [("add", "+"), ("sub", "-"), ("mul", "*"), ("truediv", "/"), ("pow", "**")], ) @pytest.mark.parametrize( "left_fix,right_fix", [("_array", "_array2"), ("_array_mixed", "_array_mixed2")] ) def test_binary_ops(self, request, opname, op_str, left_fix, right_fix): left = request.getfixturevalue(left_fix) right = request.getfixturevalue(right_fix)
def testit(left, right, opname, op_str): if opname == "pow": left = np.abs(left)
op = getattr(operator, opname)
# array has 0s result = expr.evaluate(op, left, left, use_numexpr=True) expected = expr.evaluate(op, left, left, use_numexpr=False) tm.assert_numpy_array_equal(result, expected)
result = expr._can_use_numexpr(op, op_str, right, right, "evaluate") assert not result
with option_context("compute.use_numexpr", False): testit(left, right, opname, op_str)
expr.set_numexpr_threads(1) testit(left, right, opname, op_str) expr.set_numexpr_threads() testit(left, right, opname, op_str)
@pytest.mark.parametrize( "left_fix,right_fix", [("_array", "_array2"), ("_array_mixed", "_array_mixed2")] ) def test_comparison_ops(self, request, comparison_op, left_fix, right_fix): left = request.getfixturevalue(left_fix) right = request.getfixturevalue(right_fix)
def testit(): f12 = left + 1 f22 = right + 1
op = comparison_op
result = expr.evaluate(op, left, f12, use_numexpr=True) expected = expr.evaluate(op, left, f12, use_numexpr=False) tm.assert_numpy_array_equal(result, expected)
result = expr._can_use_numexpr(op, op, right, f22, "evaluate") assert not result
with option_context("compute.use_numexpr", False): testit()
expr.set_numexpr_threads(1) testit() expr.set_numexpr_threads() testit()
@pytest.mark.parametrize("cond", [True, False]) @pytest.mark.parametrize("fixture", ["_frame", "_frame2", "_mixed", "_mixed2"]) def test_where(self, request, cond, fixture): df = request.getfixturevalue(fixture)
def testit(): c = np.empty(df.shape, dtype=np.bool_) c.fill(cond) result = expr.where(c, df.values, df.values + 1) expected = np.where(c, df.values, df.values + 1) tm.assert_numpy_array_equal(result, expected)
with option_context("compute.use_numexpr", False): testit()
expr.set_numexpr_threads(1) testit() expr.set_numexpr_threads() testit()
@pytest.mark.parametrize( "op_str,opname", [("/", "truediv"), ("//", "floordiv"), ("**", "pow")] ) def test_bool_ops_raise_on_arithmetic(self, op_str, opname): df = DataFrame( { "a": np.random.default_rng(2).random(10) > 0.5, "b": np.random.default_rng(2).random(10) > 0.5, } )
msg = f"operator '{opname}' not implemented for bool dtypes" f = getattr(operator, opname) err_msg = re.escape(msg)
with pytest.raises(NotImplementedError, match=err_msg): f(df, df)
with pytest.raises(NotImplementedError, match=err_msg): f(df.a, df.b)
with pytest.raises(NotImplementedError, match=err_msg): f(df.a, True)
with pytest.raises(NotImplementedError, match=err_msg): f(False, df.a)
with pytest.raises(NotImplementedError, match=err_msg): f(False, df)
with pytest.raises(NotImplementedError, match=err_msg): f(df, True)
@pytest.mark.parametrize( "op_str,opname", [("+", "add"), ("*", "mul"), ("-", "sub")] ) def test_bool_ops_warn_on_arithmetic(self, op_str, opname, monkeypatch): n = 10 df = DataFrame( { "a": np.random.default_rng(2).random(n) > 0.5, "b": np.random.default_rng(2).random(n) > 0.5, } )
subs = {"+": "|", "*": "&", "-": "^"} sub_funcs = {"|": "or_", "&": "and_", "^": "xor"}
f = getattr(operator, opname) fe = getattr(operator, sub_funcs[subs[op_str]])
if op_str == "-": # raises TypeError return
msg = "operator is not supported by numexpr" ne = import_optional_dependency("numexpr", errors="ignore") warning = ( UserWarning if ne and op_str in {"+", "*"} and Version(ne.__version__) < Version("2.13.1") else None ) with monkeypatch.context() as m: m.setattr(expr, "_MIN_ELEMENTS", 5) with option_context("compute.use_numexpr", True): with tm.assert_produces_warning(warning, match=msg): r = f(df, df) e = fe(df, df) tm.assert_frame_equal(r, e)
with tm.assert_produces_warning(warning, match=msg): r = f(df.a, df.b) e = fe(df.a, df.b) tm.assert_series_equal(r, e)
with tm.assert_produces_warning(warning, match=msg): r = f(df.a, True) e = fe(df.a, True) tm.assert_series_equal(r, e)
with tm.assert_produces_warning(warning, match=msg): r = f(False, df.a) e = fe(False, df.a) tm.assert_series_equal(r, e)
with tm.assert_produces_warning(warning, match=msg): r = f(False, df) e = fe(False, df) tm.assert_frame_equal(r, e)
with tm.assert_produces_warning(warning, match=msg): r = f(df, True) e = fe(df, True) tm.assert_frame_equal(r, e)
@pytest.mark.parametrize( "test_input,expected", [ ( DataFrame( [[0, 1, 2, "aa"], [0, 1, 2, "aa"]], columns=["a", "b", "c", "dtype"] ), DataFrame([[False, False], [False, False]], columns=["a", "dtype"]), ), ( DataFrame( [[0, 3, 2, "aa"], [0, 4, 2, "aa"], [0, 1, 1, "bb"]], columns=["a", "b", "c", "dtype"], ), DataFrame( [[False, False], [False, False], [False, False]], columns=["a", "dtype"], ), ), ], ) def test_bool_ops_column_name_dtype(self, test_input, expected): # GH 22383 - .ne fails if columns containing column name 'dtype' result = test_input.loc[:, ["a", "dtype"]].ne(test_input.loc[:, ["a", "dtype"]]) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize( "arith", ("add", "sub", "mul", "mod", "truediv", "floordiv") ) @pytest.mark.parametrize("axis", (0, 1)) def test_frame_series_axis(self, axis, arith, _frame, monkeypatch): # GH#26736 Dataframe.floordiv(Series, axis=1) fails
df = _frame if axis == 1: other = df.iloc[0, :] else: other = df.iloc[:, 0]
with monkeypatch.context() as m: m.setattr(expr, "_MIN_ELEMENTS", 0)
op_func = getattr(df, arith)
with option_context("compute.use_numexpr", False): expected = op_func(other, axis=axis)
result = op_func(other, axis=axis) tm.assert_frame_equal(expected, result)
@pytest.mark.parametrize( "op", [ "__mod__", "__rmod__", "__floordiv__", "__rfloordiv__", ], ) @pytest.mark.parametrize("scalar", [-5, 5]) def test_python_semantics_with_numexpr_installed( self, op, box_with_array, scalar, monkeypatch ): # https://github.com/pandas-dev/pandas/issues/36047 with monkeypatch.context() as m: m.setattr(expr, "_MIN_ELEMENTS", 0) data = np.arange(-50, 50) obj = box_with_array(data) method = getattr(obj, op) result = method(scalar)
# compare result with numpy with option_context("compute.use_numexpr", False): expected = method(scalar)
tm.assert_equal(result, expected)
# compare result element-wise with Python for i, elem in enumerate(data): if box_with_array == DataFrame: scalar_result = result.iloc[i, 0] else: scalar_result = result[i] try: expected = getattr(int(elem), op)(scalar) except ZeroDivisionError: pass else: assert scalar_result == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import pytest
import pandas as pd
class TestFlags: def test_equality(self): a = pd.DataFrame().set_flags(allows_duplicate_labels=True).flags b = pd.DataFrame().set_flags(allows_duplicate_labels=False).flags
assert a == a assert b == b assert a != b assert a != 2
def test_set(self): df = pd.DataFrame().set_flags(allows_duplicate_labels=True) a = df.flags a.allows_duplicate_labels = False assert a.allows_duplicate_labels is False a["allows_duplicate_labels"] = True assert a.allows_duplicate_labels is True
def test_repr(self): a = repr(pd.DataFrame({"A"}).set_flags(allows_duplicate_labels=True).flags) assert a == "<Flags(allows_duplicate_labels=True)>" a = repr(pd.DataFrame({"A"}).set_flags(allows_duplicate_labels=False).flags) assert a == "<Flags(allows_duplicate_labels=False)>"
def test_obj_ref(self): df = pd.DataFrame() flags = df.flags del df with pytest.raises(ValueError, match="object has been deleted"): flags.allows_duplicate_labels = True
def test_getitem(self): df = pd.DataFrame() flags = df.flags assert flags["allows_duplicate_labels"] is True flags["allows_duplicate_labels"] = False assert flags["allows_duplicate_labels"] is False
with pytest.raises(KeyError, match="a"): flags["a"]
with pytest.raises(ValueError, match="a"): flags["a"] = 10123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376import datetime
import numpy as npimport pytest
import pandas as pdfrom pandas import ( ArrowDtype, DataFrame, MultiIndex, Series,)import pandas._testing as tm
class TestMultiLevel: def test_reindex_level(self, multiindex_year_month_day_dataframe_random_data): # axis=0 ymd = multiindex_year_month_day_dataframe_random_data
month_sums = ymd.groupby("month").sum() result = month_sums.reindex(ymd.index, level=1) expected = ymd.groupby(level="month").transform("sum")
tm.assert_frame_equal(result, expected)
# Series result = month_sums["A"].reindex(ymd.index, level=1) expected = ymd["A"].groupby(level="month").transform("sum") tm.assert_series_equal(result, expected, check_names=False)
def test_reindex(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data
expected = frame.iloc[[0, 3]] reindexed = frame.loc[[("foo", "one"), ("bar", "one")]] tm.assert_frame_equal(reindexed, expected)
def test_reindex_preserve_levels( self, multiindex_year_month_day_dataframe_random_data ): ymd = multiindex_year_month_day_dataframe_random_data
new_index = ymd.index[::10] chunk = ymd.reindex(new_index) assert chunk.index.is_(new_index)
chunk = ymd.loc[new_index] assert chunk.index.equals(new_index)
ymdT = ymd.T chunk = ymdT.reindex(columns=new_index) assert chunk.columns.is_(new_index)
chunk = ymdT.loc[:, new_index] assert chunk.columns.equals(new_index)
def test_groupby_transform(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data
s = frame["A"] grouper = s.index.get_level_values(0)
grouped = s.groupby(grouper, group_keys=False)
applied = grouped.apply(lambda x: x * 2) expected = grouped.transform(lambda x: x * 2) result = applied.reindex(expected.index) tm.assert_series_equal(result, expected, check_names=False)
def test_groupby_corner(self): midx = MultiIndex( levels=[["foo"], ["bar"], ["baz"]], codes=[[0], [0], [0]], names=["one", "two", "three"], ) df = DataFrame( [np.random.default_rng(2).random(4)], columns=["a", "b", "c", "d"], index=midx, ) # should work df.groupby(level="three")
def test_setitem_with_expansion_multiindex_columns( self, multiindex_year_month_day_dataframe_random_data ): ymd = multiindex_year_month_day_dataframe_random_data
df = ymd[:5].T df[2000, 1, 10] = df[2000, 1, 7] assert isinstance(df.columns, MultiIndex) assert (df[2000, 1, 10] == df[2000, 1, 7]).all()
def test_alignment(self): x = Series( data=[1, 2, 3], index=MultiIndex.from_tuples([("A", 1), ("A", 2), ("B", 3)]) )
y = Series( data=[4, 5, 6], index=MultiIndex.from_tuples([("Z", 1), ("Z", 2), ("B", 3)]) )
res = x - y exp_index = x.index.union(y.index) exp = x.reindex(exp_index) - y.reindex(exp_index) tm.assert_series_equal(res, exp)
# hit non-monotonic code path res = x[::-1] - y[::-1] exp_index = x.index.union(y.index) exp = x.reindex(exp_index) - y.reindex(exp_index) tm.assert_series_equal(res, exp)
def test_groupby_multilevel(self, multiindex_year_month_day_dataframe_random_data): ymd = multiindex_year_month_day_dataframe_random_data
result = ymd.groupby(level=[0, 1]).mean()
k1 = ymd.index.get_level_values(0) k2 = ymd.index.get_level_values(1)
expected = ymd.groupby([k1, k2]).mean()
tm.assert_frame_equal(result, expected) assert result.index.names == ymd.index.names[:2]
result2 = ymd.groupby(level=ymd.index.names[:2]).mean() tm.assert_frame_equal(result, result2)
def test_multilevel_consolidate(self): index = MultiIndex.from_tuples( [("foo", "one"), ("foo", "two"), ("bar", "one"), ("bar", "two")] ) df = DataFrame( np.random.default_rng(2).standard_normal((4, 4)), index=index, columns=index ) df["Totals", ""] = df.sum(axis=1) df = df._consolidate()
def test_level_with_tuples(self): index = MultiIndex( levels=[[("foo", "bar", 0), ("foo", "baz", 0), ("foo", "qux", 0)], [0, 1]], codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], )
series = Series(np.random.default_rng(2).standard_normal(6), index=index) frame = DataFrame(np.random.default_rng(2).standard_normal((6, 4)), index=index)
result = series[("foo", "bar", 0)] result2 = series.loc[("foo", "bar", 0)] expected = series[:2] expected.index = expected.index.droplevel(0) tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected)
with pytest.raises(KeyError, match=r"^\(\('foo', 'bar', 0\), 2\)$"): series[("foo", "bar", 0), 2]
result = frame.loc[("foo", "bar", 0)] result2 = frame.xs(("foo", "bar", 0)) expected = frame[:2] expected.index = expected.index.droplevel(0) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected)
index = MultiIndex( levels=[[("foo", "bar"), ("foo", "baz"), ("foo", "qux")], [0, 1]], codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], )
series = Series(np.random.default_rng(2).standard_normal(6), index=index) frame = DataFrame(np.random.default_rng(2).standard_normal((6, 4)), index=index)
result = series[("foo", "bar")] result2 = series.loc[("foo", "bar")] expected = series[:2] expected.index = expected.index.droplevel(0) tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected)
result = frame.loc[("foo", "bar")] result2 = frame.xs(("foo", "bar")) expected = frame[:2] expected.index = expected.index.droplevel(0) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected)
def test_reindex_level_partial_selection(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data
result = frame.reindex(["foo", "qux"], level=0) expected = frame.iloc[[0, 1, 2, 7, 8, 9]] tm.assert_frame_equal(result, expected)
result = frame.T.reindex(["foo", "qux"], axis=1, level=0) tm.assert_frame_equal(result, expected.T)
result = frame.loc[["foo", "qux"]] tm.assert_frame_equal(result, expected)
result = frame["A"].loc[["foo", "qux"]] tm.assert_series_equal(result, expected["A"])
result = frame.T.loc[:, ["foo", "qux"]] tm.assert_frame_equal(result, expected.T)
@pytest.mark.parametrize("d", [4, "d"]) def test_empty_frame_groupby_dtypes_consistency(self, d): # GH 20888 group_keys = ["a", "b", "c"] df = DataFrame({"a": [1], "b": [2], "c": [3], "d": [d]})
g = df[df.a == 2].groupby(group_keys) result = g.first().index expected = MultiIndex( levels=[[1], [2], [3]], codes=[[], [], []], names=["a", "b", "c"] )
tm.assert_index_equal(result, expected)
def test_duplicate_groupby_issues(self): idx_tp = [ ("600809", "20061231"), ("600809", "20070331"), ("600809", "20070630"), ("600809", "20070331"), ] dt = ["demo", "demo", "demo", "demo"]
idx = MultiIndex.from_tuples(idx_tp, names=["STK_ID", "RPT_Date"]) s = Series(dt, index=idx)
result = s.groupby(s.index).first() assert len(result) == 3
def test_subsets_multiindex_dtype(self): # GH 20757 data = [["x", 1]] columns = [("a", "b", np.nan), ("a", "c", 0.0)] df = DataFrame(data, columns=MultiIndex.from_tuples(columns)) expected = df.dtypes.a.b result = df.a.b.dtypes tm.assert_series_equal(result, expected)
def test_datetime_object_multiindex(self): data_dic = { (0, datetime.date(2018, 3, 3)): {"A": 1, "B": 10}, (0, datetime.date(2018, 3, 4)): {"A": 2, "B": 11}, (1, datetime.date(2018, 3, 3)): {"A": 3, "B": 12}, (1, datetime.date(2018, 3, 4)): {"A": 4, "B": 13}, } result = DataFrame.from_dict(data_dic, orient="index") data = {"A": [1, 2, 3, 4], "B": [10, 11, 12, 13]} index = [ [0, 0, 1, 1], [ datetime.date(2018, 3, 3), datetime.date(2018, 3, 4), datetime.date(2018, 3, 3), datetime.date(2018, 3, 4), ], ] expected = DataFrame(data=data, index=index)
tm.assert_frame_equal(result, expected)
def test_multiindex_with_na(self): df = DataFrame( [ ["A", np.nan, 1.23, 4.56], ["A", "G", 1.23, 4.56], ["A", "D", 9.87, 10.54], ], columns=["pivot_0", "pivot_1", "col_1", "col_2"], ).set_index(["pivot_0", "pivot_1"])
df.at[("A", "F"), "col_2"] = 0.0
expected = DataFrame( [ ["A", np.nan, 1.23, 4.56], ["A", "G", 1.23, 4.56], ["A", "D", 9.87, 10.54], ["A", "F", np.nan, 0.0], ], columns=["pivot_0", "pivot_1", "col_1", "col_2"], ).set_index(["pivot_0", "pivot_1"])
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("na", [None, np.nan]) def test_multiindex_insert_level_with_na(self, na): # GH 59003 df = DataFrame([0], columns=[["A"], ["B"]]) df[na, "B"] = 1 tm.assert_frame_equal(df[na], DataFrame([1], columns=["B"]))
def test_multiindex_dt_with_nan(self): # GH#60388 df = DataFrame( [ [1, np.nan, 5, np.nan], [2, np.nan, 6, np.nan], [np.nan, 3, np.nan, 7], [np.nan, 4, np.nan, 8], ], index=Series(["a", "b", "c", "d"], dtype=object, name="sub"), columns=MultiIndex.from_product( [ ["value1", "value2"], [datetime.datetime(2024, 11, 1), datetime.datetime(2024, 11, 2)], ], names=[None, "Date"], ), ) df = df.reset_index() result = df[df.columns[0]] expected = Series(["a", "b", "c", "d"], name=("sub", np.nan)) tm.assert_series_equal(result, expected)
@pytest.mark.filterwarnings("ignore:Passing a BlockManager:DeprecationWarning") def test_multiindex_with_pyarrow_categorical(self): # GH#53051 pa = pytest.importorskip("pyarrow")
df = DataFrame( {"string_column": ["A", "B", "C"], "number_column": [1, 2, 3]} ).astype( { "string_column": ArrowDtype(pa.dictionary(pa.int32(), pa.string())), "number_column": "float[pyarrow]", } )
df = df.set_index(["string_column", "number_column"])
df_expected = DataFrame( index=MultiIndex.from_arrays( [["A", "B", "C"], [1, 2, 3]], names=["string_column", "number_column"] ) ) tm.assert_frame_equal( df, df_expected, check_index_type=False, check_column_type=False, )
class TestSorted: """everything you wanted to test about sorting"""
def test_sort_non_lexsorted(self): # degenerate case where we sort but don't # have a satisfying result :< # GH 15797 idx = MultiIndex( [["A", "B", "C"], ["c", "b", "a"]], [[0, 1, 2, 0, 1, 2], [0, 2, 1, 1, 0, 2]] )
df = DataFrame({"col": range(len(idx))}, index=idx, dtype="int64") assert df.index.is_monotonic_increasing is False
sorted = df.sort_index() assert sorted.index.is_monotonic_increasing is True
expected = DataFrame( {"col": [1, 4, 5, 2]}, index=MultiIndex.from_tuples( [("B", "a"), ("B", "c"), ("C", "a"), ("C", "b")] ), dtype="int64", ) result = sorted.loc[pd.IndexSlice["B":"C", "a":"c"], :] tm.assert_frame_equal(result, expected)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333from functools import partial
import numpy as npimport pytest
import pandas.util._test_decorators as td
from pandas.core.dtypes.common import is_integer_dtype
import pandas as pdfrom pandas import ( Series, isna,)import pandas._testing as tmfrom pandas.core import nanops
use_bn = nanops._USE_BOTTLENECK
@pytest.fixturedef disable_bottleneck(monkeypatch): with monkeypatch.context() as m: m.setattr(nanops, "_USE_BOTTLENECK", False) yield
@pytest.fixturedef arr_shape(): return 11, 7
@pytest.fixturedef arr_float(arr_shape): return np.random.default_rng(2).standard_normal(arr_shape)
@pytest.fixturedef arr_complex(arr_float): return arr_float + arr_float * 1j
@pytest.fixturedef arr_int(arr_shape): return np.random.default_rng(2).integers(-10, 10, arr_shape)
@pytest.fixturedef arr_bool(arr_shape): return np.random.default_rng(2).integers(0, 2, arr_shape) == 0
@pytest.fixturedef arr_str(arr_float): return np.abs(arr_float).astype("S")
@pytest.fixturedef arr_utf(arr_float): return np.abs(arr_float).astype("U")
@pytest.fixturedef arr_date(arr_shape): return np.random.default_rng(2).integers(0, 20000, arr_shape).astype("M8[ns]")
@pytest.fixturedef arr_tdelta(arr_shape): return np.random.default_rng(2).integers(0, 20000, arr_shape).astype("m8[ns]")
@pytest.fixturedef arr_nan(arr_shape): return np.tile(np.nan, arr_shape)
@pytest.fixturedef arr_float_nan(arr_float, arr_nan): return np.vstack([arr_float, arr_nan])
@pytest.fixturedef arr_nan_float1(arr_nan, arr_float): return np.vstack([arr_nan, arr_float])
@pytest.fixturedef arr_nan_nan(arr_nan): return np.vstack([arr_nan, arr_nan])
@pytest.fixturedef arr_inf(arr_float): return arr_float * np.inf
@pytest.fixturedef arr_float_inf(arr_float, arr_inf): return np.vstack([arr_float, arr_inf])
@pytest.fixturedef arr_nan_inf(arr_nan, arr_inf): return np.vstack([arr_nan, arr_inf])
@pytest.fixturedef arr_float_nan_inf(arr_float, arr_nan, arr_inf): return np.vstack([arr_float, arr_nan, arr_inf])
@pytest.fixturedef arr_nan_nan_inf(arr_nan, arr_inf): return np.vstack([arr_nan, arr_nan, arr_inf])
@pytest.fixturedef arr_obj( arr_float, arr_int, arr_bool, arr_complex, arr_str, arr_utf, arr_date, arr_tdelta): return np.vstack( [ arr_float.astype("O"), arr_int.astype("O"), arr_bool.astype("O"), arr_complex.astype("O"), arr_str.astype("O"), arr_utf.astype("O"), arr_date.astype("O"), arr_tdelta.astype("O"), ] )
@pytest.fixturedef arr_nan_nanj(arr_nan): with np.errstate(invalid="ignore"): return arr_nan + arr_nan * 1j
@pytest.fixturedef arr_complex_nan(arr_complex, arr_nan_nanj): with np.errstate(invalid="ignore"): return np.vstack([arr_complex, arr_nan_nanj])
@pytest.fixturedef arr_nan_infj(arr_inf): with np.errstate(invalid="ignore"): return arr_inf * 1j
@pytest.fixturedef arr_complex_nan_infj(arr_complex, arr_nan_infj): with np.errstate(invalid="ignore"): return np.vstack([arr_complex, arr_nan_infj])
@pytest.fixturedef arr_float_1d(arr_float): return arr_float[:, 0]
@pytest.fixturedef arr_nan_1d(arr_nan): return arr_nan[:, 0]
@pytest.fixturedef arr_float_nan_1d(arr_float_nan): return arr_float_nan[:, 0]
@pytest.fixturedef arr_float1_nan_1d(arr_float1_nan): return arr_float1_nan[:, 0]
@pytest.fixturedef arr_nan_float1_1d(arr_nan_float1): return arr_nan_float1[:, 0]
class TestnanopsDataFrame: def setup_method(self): nanops._USE_BOTTLENECK = False
arr_shape = (11, 7)
self.arr_float = np.random.default_rng(2).standard_normal(arr_shape) self.arr_float1 = np.random.default_rng(2).standard_normal(arr_shape) self.arr_complex = self.arr_float + self.arr_float1 * 1j self.arr_int = np.random.default_rng(2).integers(-10, 10, arr_shape) self.arr_bool = np.random.default_rng(2).integers(0, 2, arr_shape) == 0 self.arr_str = np.abs(self.arr_float).astype("S") self.arr_utf = np.abs(self.arr_float).astype("U") self.arr_date = ( np.random.default_rng(2).integers(0, 20000, arr_shape).astype("M8[ns]") ) self.arr_tdelta = ( np.random.default_rng(2).integers(0, 20000, arr_shape).astype("m8[ns]") )
self.arr_nan = np.tile(np.nan, arr_shape) self.arr_float_nan = np.vstack([self.arr_float, self.arr_nan]) self.arr_float1_nan = np.vstack([self.arr_float1, self.arr_nan]) self.arr_nan_float1 = np.vstack([self.arr_nan, self.arr_float1]) self.arr_nan_nan = np.vstack([self.arr_nan, self.arr_nan])
self.arr_inf = self.arr_float * np.inf self.arr_float_inf = np.vstack([self.arr_float, self.arr_inf])
self.arr_nan_inf = np.vstack([self.arr_nan, self.arr_inf]) self.arr_float_nan_inf = np.vstack([self.arr_float, self.arr_nan, self.arr_inf]) self.arr_nan_nan_inf = np.vstack([self.arr_nan, self.arr_nan, self.arr_inf]) self.arr_obj = np.vstack( [ self.arr_float.astype("O"), self.arr_int.astype("O"), self.arr_bool.astype("O"), self.arr_complex.astype("O"), self.arr_str.astype("O"), self.arr_utf.astype("O"), self.arr_date.astype("O"), self.arr_tdelta.astype("O"), ] )
with np.errstate(invalid="ignore"): self.arr_nan_nanj = self.arr_nan + self.arr_nan * 1j self.arr_complex_nan = np.vstack([self.arr_complex, self.arr_nan_nanj])
self.arr_nan_infj = self.arr_inf * 1j self.arr_complex_nan_infj = np.vstack([self.arr_complex, self.arr_nan_infj])
self.arr_float_2d = self.arr_float self.arr_float1_2d = self.arr_float1
self.arr_nan_2d = self.arr_nan self.arr_float_nan_2d = self.arr_float_nan self.arr_float1_nan_2d = self.arr_float1_nan self.arr_nan_float1_2d = self.arr_nan_float1
self.arr_float_1d = self.arr_float[:, 0] self.arr_float1_1d = self.arr_float1[:, 0]
self.arr_nan_1d = self.arr_nan[:, 0] self.arr_float_nan_1d = self.arr_float_nan[:, 0] self.arr_float1_nan_1d = self.arr_float1_nan[:, 0] self.arr_nan_float1_1d = self.arr_nan_float1[:, 0]
def teardown_method(self): nanops._USE_BOTTLENECK = use_bn
def check_results(self, targ, res, axis, check_dtype=True): res = getattr(res, "asm8", res)
if ( axis != 0 and hasattr(targ, "shape") and targ.ndim and targ.shape != res.shape ): res = np.split(res, [targ.shape[0]], axis=0)[0]
try: tm.assert_almost_equal(targ, res, check_dtype=check_dtype) except AssertionError: # handle timedelta dtypes if hasattr(targ, "dtype") and targ.dtype == "m8[ns]": raise
# There are sometimes rounding errors with # complex and object dtypes. # If it isn't one of those, re-raise the error. if not hasattr(res, "dtype") or res.dtype.kind not in ["c", "O"]: raise # convert object dtypes to something that can be split into # real and imaginary parts if res.dtype.kind == "O": if targ.dtype.kind != "O": res = res.astype(targ.dtype) else: cast_dtype = "c16" if hasattr(np, "complex128") else "f8" res = res.astype(cast_dtype) targ = targ.astype(cast_dtype) # there should never be a case where numpy returns an object # but nanops doesn't, so make that an exception elif targ.dtype.kind == "O": raise tm.assert_almost_equal(np.real(targ), np.real(res), check_dtype=check_dtype) tm.assert_almost_equal(np.imag(targ), np.imag(res), check_dtype=check_dtype)
def check_fun_data( self, testfunc, targfunc, testar, testarval, targarval, skipna, check_dtype=True, empty_targfunc=None, **kwargs, ): for axis in [*list(range(targarval.ndim)), None]: targartempval = targarval if skipna else testarval if skipna and empty_targfunc and isna(targartempval).all(): targ = empty_targfunc(targartempval, axis=axis, **kwargs) else: targ = targfunc(targartempval, axis=axis, **kwargs)
if targartempval.dtype == object and ( targfunc is np.any or targfunc is np.all ): # GH#12863 the numpy functions will retain e.g. floatiness if isinstance(targ, np.ndarray): targ = targ.astype(bool) else: targ = bool(targ)
if testfunc.__name__ in ["nanargmax", "nanargmin"] and ( testar.startswith("arr_nan") or (testar.endswith("nan") and (not skipna or axis == 1)) ): with pytest.raises(ValueError, match="Encountered .* NA value"): testfunc(testarval, axis=axis, skipna=skipna, **kwargs) return res = testfunc(testarval, axis=axis, skipna=skipna, **kwargs)
if ( isinstance(targ, np.complex128) and isinstance(res, float) and np.isnan(targ) and np.isnan(res) ): # GH#18463 targ = res
self.check_results(targ, res, axis, check_dtype=check_dtype) if skipna: res = testfunc(testarval, axis=axis, **kwargs) self.check_results(targ, res, axis, check_dtype=check_dtype) if axis is None: res = testfunc(testarval, skipna=skipna, **kwargs) self.check_results(targ, res, axis, check_dtype=check_dtype) if skipna and axis is None: res = testfunc(testarval, **kwargs) self.check_results(targ, res, axis, check_dtype=check_dtype)
if testarval.ndim <= 1: return
# Recurse on lower-dimension testarval2 = np.take(testarval, 0, axis=-1) targarval2 = np.take(targarval, 0, axis=-1) self.check_fun_data( testfunc, targfunc, testar, testarval2, targarval2, skipna=skipna, check_dtype=check_dtype, empty_targfunc=empty_targfunc, **kwargs, )
def check_fun( self, testfunc, targfunc, testar, skipna, empty_targfunc=None, **kwargs ): targar = testar if testar.endswith("_nan") and hasattr(self, testar[:-4]): targar = testar[:-4]
testarval = getattr(self, testar) targarval = getattr(self, targar) self.check_fun_data( testfunc, targfunc, testar, testarval, targarval, skipna=skipna, empty_targfunc=empty_targfunc, **kwargs, )
def check_funs( self, testfunc, targfunc, skipna, allow_complex=True, allow_all_nan=True, allow_date=True, allow_tdelta=True, allow_obj=True, **kwargs, ): self.check_fun(testfunc, targfunc, "arr_float", skipna, **kwargs) self.check_fun(testfunc, targfunc, "arr_float_nan", skipna, **kwargs) self.check_fun(testfunc, targfunc, "arr_int", skipna, **kwargs) self.check_fun(testfunc, targfunc, "arr_bool", skipna, **kwargs) objs = [ self.arr_float.astype("O"), self.arr_int.astype("O"), self.arr_bool.astype("O"), ]
if allow_all_nan: self.check_fun(testfunc, targfunc, "arr_nan", skipna, **kwargs)
if allow_complex: self.check_fun(testfunc, targfunc, "arr_complex", skipna, **kwargs) self.check_fun(testfunc, targfunc, "arr_complex_nan", skipna, **kwargs) if allow_all_nan: self.check_fun(testfunc, targfunc, "arr_nan_nanj", skipna, **kwargs) objs += [self.arr_complex.astype("O")]
if allow_date: targfunc(self.arr_date) self.check_fun(testfunc, targfunc, "arr_date", skipna, **kwargs) objs += [self.arr_date.astype("O")]
if allow_tdelta: try: targfunc(self.arr_tdelta) except TypeError: pass else: self.check_fun(testfunc, targfunc, "arr_tdelta", skipna, **kwargs) objs += [self.arr_tdelta.astype("O")]
if allow_obj: self.arr_obj = np.vstack(objs) # some nanops handle object dtypes better than their numpy # counterparts, so the numpy functions need to be given something # else if allow_obj == "convert": targfunc = partial( self._badobj_wrap, func=targfunc, allow_complex=allow_complex ) self.check_fun(testfunc, targfunc, "arr_obj", skipna, **kwargs)
def _badobj_wrap(self, value, func, allow_complex=True, **kwargs): if value.dtype.kind == "O": if allow_complex: value = value.astype("c16") else: value = value.astype("f8") return func(value, **kwargs)
@pytest.mark.parametrize( "nan_op,np_op", [(nanops.nanany, np.any), (nanops.nanall, np.all)] ) def test_nan_funcs(self, nan_op, np_op, skipna): self.check_funs(nan_op, np_op, skipna, allow_all_nan=False, allow_date=False)
def test_nansum(self, skipna): self.check_funs( nanops.nansum, np.sum, skipna, allow_date=False, check_dtype=False, empty_targfunc=np.nansum, )
def test_nanmean(self, skipna): self.check_funs( nanops.nanmean, np.mean, skipna, allow_obj=False, allow_date=False )
@pytest.mark.filterwarnings("ignore::RuntimeWarning") def test_nanmedian(self, skipna): self.check_funs( nanops.nanmedian, np.median, skipna, allow_complex=False, allow_date=False, allow_obj="convert", )
@pytest.mark.parametrize("ddof", range(3)) def test_nanvar(self, ddof, skipna): self.check_funs( nanops.nanvar, np.var, skipna, allow_complex=False, allow_date=False, allow_obj="convert", ddof=ddof, )
@pytest.mark.parametrize("ddof", range(3)) def test_nanstd(self, ddof, skipna): self.check_funs( nanops.nanstd, np.std, skipna, allow_complex=False, allow_date=False, allow_obj="convert", ddof=ddof, )
@pytest.mark.parametrize("ddof", range(3)) def test_nansem(self, ddof, skipna): sp_stats = pytest.importorskip("scipy.stats")
with np.errstate(invalid="ignore"): self.check_funs( nanops.nansem, sp_stats.sem, skipna, allow_complex=False, allow_date=False, allow_tdelta=False, allow_obj="convert", ddof=ddof, )
@pytest.mark.filterwarnings("ignore::RuntimeWarning") @pytest.mark.parametrize( "nan_op,np_op", [(nanops.nanmin, np.min), (nanops.nanmax, np.max)] ) def test_nanops_with_warnings(self, nan_op, np_op, skipna): self.check_funs(nan_op, np_op, skipna, allow_obj=False)
def _argminmax_wrap(self, value, axis=None, func=None): res = func(value, axis) nans = np.min(value, axis) nullnan = isna(nans) if res.ndim: res[nullnan] = -1 elif (hasattr(nullnan, "all") and nullnan.all()) or ( not hasattr(nullnan, "all") and nullnan ): res = -1 return res
@pytest.mark.filterwarnings("ignore::RuntimeWarning") def test_nanargmax(self, skipna): func = partial(self._argminmax_wrap, func=np.argmax) self.check_funs(nanops.nanargmax, func, skipna, allow_obj=False)
@pytest.mark.filterwarnings("ignore::RuntimeWarning") def test_nanargmin(self, skipna): func = partial(self._argminmax_wrap, func=np.argmin) self.check_funs(nanops.nanargmin, func, skipna, allow_obj=False)
def _skew_kurt_wrap(self, values, axis=None, func=None): if not isinstance(values.dtype.type, np.floating): values = values.astype("f8") result = func(values, axis=axis, bias=False) # fix for handling cases where all elements in an axis are the same if isinstance(result, np.ndarray): result[np.max(values, axis=axis) == np.min(values, axis=axis)] = 0 return result elif np.max(values) == np.min(values): return 0.0 return result
def test_nanskew(self, skipna): sp_stats = pytest.importorskip("scipy.stats")
func = partial(self._skew_kurt_wrap, func=sp_stats.skew) with np.errstate(invalid="ignore"): self.check_funs( nanops.nanskew, func, skipna, allow_complex=False, allow_date=False, allow_tdelta=False, )
def test_nankurt(self, skipna): sp_stats = pytest.importorskip("scipy.stats")
func1 = partial(sp_stats.kurtosis, fisher=True) func = partial(self._skew_kurt_wrap, func=func1) with np.errstate(invalid="ignore"): self.check_funs( nanops.nankurt, func, skipna, allow_complex=False, allow_date=False, allow_tdelta=False, )
def test_nanprod(self, skipna): self.check_funs( nanops.nanprod, np.prod, skipna, allow_date=False, allow_tdelta=False, empty_targfunc=np.nanprod, )
def check_nancorr_nancov_2d(self, checkfun, targ0, targ1, **kwargs): res00 = checkfun(self.arr_float_2d, self.arr_float1_2d, **kwargs) res01 = checkfun( self.arr_float_2d, self.arr_float1_2d, min_periods=len(self.arr_float_2d) - 1, **kwargs, ) tm.assert_almost_equal(targ0, res00) tm.assert_almost_equal(targ0, res01)
res10 = checkfun(self.arr_float_nan_2d, self.arr_float1_nan_2d, **kwargs) res11 = checkfun( self.arr_float_nan_2d, self.arr_float1_nan_2d, min_periods=len(self.arr_float_2d) - 1, **kwargs, ) tm.assert_almost_equal(targ1, res10) tm.assert_almost_equal(targ1, res11)
targ2 = np.nan res20 = checkfun(self.arr_nan_2d, self.arr_float1_2d, **kwargs) res21 = checkfun(self.arr_float_2d, self.arr_nan_2d, **kwargs) res22 = checkfun(self.arr_nan_2d, self.arr_nan_2d, **kwargs) res23 = checkfun(self.arr_float_nan_2d, self.arr_nan_float1_2d, **kwargs) res24 = checkfun( self.arr_float_nan_2d, self.arr_nan_float1_2d, min_periods=len(self.arr_float_2d) - 1, **kwargs, ) res25 = checkfun( self.arr_float_2d, self.arr_float1_2d, min_periods=len(self.arr_float_2d) + 1, **kwargs, ) tm.assert_almost_equal(targ2, res20) tm.assert_almost_equal(targ2, res21) tm.assert_almost_equal(targ2, res22) tm.assert_almost_equal(targ2, res23) tm.assert_almost_equal(targ2, res24) tm.assert_almost_equal(targ2, res25)
def check_nancorr_nancov_1d(self, checkfun, targ0, targ1, **kwargs): res00 = checkfun(self.arr_float_1d, self.arr_float1_1d, **kwargs) res01 = checkfun( self.arr_float_1d, self.arr_float1_1d, min_periods=len(self.arr_float_1d) - 1, **kwargs, ) tm.assert_almost_equal(targ0, res00) tm.assert_almost_equal(targ0, res01)
res10 = checkfun(self.arr_float_nan_1d, self.arr_float1_nan_1d, **kwargs) res11 = checkfun( self.arr_float_nan_1d, self.arr_float1_nan_1d, min_periods=len(self.arr_float_1d) - 1, **kwargs, ) tm.assert_almost_equal(targ1, res10) tm.assert_almost_equal(targ1, res11)
targ2 = np.nan res20 = checkfun(self.arr_nan_1d, self.arr_float1_1d, **kwargs) res21 = checkfun(self.arr_float_1d, self.arr_nan_1d, **kwargs) res22 = checkfun(self.arr_nan_1d, self.arr_nan_1d, **kwargs) res23 = checkfun(self.arr_float_nan_1d, self.arr_nan_float1_1d, **kwargs) res24 = checkfun( self.arr_float_nan_1d, self.arr_nan_float1_1d, min_periods=len(self.arr_float_1d) - 1, **kwargs, ) res25 = checkfun( self.arr_float_1d, self.arr_float1_1d, min_periods=len(self.arr_float_1d) + 1, **kwargs, ) tm.assert_almost_equal(targ2, res20) tm.assert_almost_equal(targ2, res21) tm.assert_almost_equal(targ2, res22) tm.assert_almost_equal(targ2, res23) tm.assert_almost_equal(targ2, res24) tm.assert_almost_equal(targ2, res25)
def test_nancorr(self): targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1] targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1) targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1] targ1 = np.corrcoef(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1] self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="pearson")
def test_nancorr_pearson(self): targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1] targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="pearson") targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1] targ1 = np.corrcoef(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1] self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="pearson")
def test_nancorr_kendall(self): sp_stats = pytest.importorskip("scipy.stats")
targ0 = sp_stats.kendalltau(self.arr_float_2d, self.arr_float1_2d)[0] targ1 = sp_stats.kendalltau(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0] self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="kendall") targ0 = sp_stats.kendalltau(self.arr_float_1d, self.arr_float1_1d)[0] targ1 = sp_stats.kendalltau(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0] self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="kendall")
def test_nancorr_spearman(self): sp_stats = pytest.importorskip("scipy.stats")
targ0 = sp_stats.spearmanr(self.arr_float_2d, self.arr_float1_2d)[0] targ1 = sp_stats.spearmanr(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0] self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="spearman") targ0 = sp_stats.spearmanr(self.arr_float_1d, self.arr_float1_1d)[0] targ1 = sp_stats.spearmanr(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0] self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="spearman")
def test_invalid_method(self): pytest.importorskip("scipy") targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1] targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] msg = "Unknown method 'foo', expected one of 'kendall', 'spearman'" with pytest.raises(ValueError, match=msg): self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="foo")
def test_nancov(self): targ0 = np.cov(self.arr_float_2d, self.arr_float1_2d)[0, 1] targ1 = np.cov(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1] self.check_nancorr_nancov_2d(nanops.nancov, targ0, targ1) targ0 = np.cov(self.arr_float_1d, self.arr_float1_1d)[0, 1] targ1 = np.cov(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1] self.check_nancorr_nancov_1d(nanops.nancov, targ0, targ1)
@pytest.mark.parametrize( "arr, correct", [ ("arr_complex", False), ("arr_int", False), ("arr_bool", False), ("arr_str", False), ("arr_utf", False), ("arr_complex_nan", False), ("arr_nan_nanj", False), ("arr_nan_infj", True), ("arr_complex_nan_infj", True), ],)def test_has_infs_non_float(request, arr, correct, disable_bottleneck): val = request.getfixturevalue(arr) while getattr(val, "ndim", True): res0 = nanops._has_infs(val) if correct: assert res0 else: assert not res0
if not hasattr(val, "ndim"): break
# Reduce dimension for next step in the loop val = np.take(val, 0, axis=-1)
@pytest.mark.parametrize( "arr, correct", [ ("arr_float", False), ("arr_nan", False), ("arr_float_nan", False), ("arr_nan_nan", False), ("arr_float_inf", True), ("arr_inf", True), ("arr_nan_inf", True), ("arr_float_nan_inf", True), ("arr_nan_nan_inf", True), ],)@pytest.mark.parametrize("astype", [None, "f4", "f2"])def test_has_infs_floats(request, arr, correct, astype, disable_bottleneck): val = request.getfixturevalue(arr) if astype is not None: val = val.astype(astype) while getattr(val, "ndim", True): res0 = nanops._has_infs(val) if correct: assert res0 else: assert not res0
if not hasattr(val, "ndim"): break
# Reduce dimension for next step in the loop val = np.take(val, 0, axis=-1)
@pytest.mark.parametrize( "fixture", ["arr_float", "arr_complex", "arr_int", "arr_bool", "arr_str", "arr_utf"])def test_bn_ok_dtype(fixture, request, disable_bottleneck): obj = request.getfixturevalue(fixture) assert nanops._bn_ok_dtype(obj.dtype, "test")
@pytest.mark.parametrize( "fixture", [ "arr_date", "arr_tdelta", "arr_obj", ],)def test_bn_not_ok_dtype(fixture, request, disable_bottleneck): obj = request.getfixturevalue(fixture) assert not nanops._bn_ok_dtype(obj.dtype, "test")
class TestEnsureNumeric: def test_numeric_values(self): # Test integer assert nanops._ensure_numeric(1) == 1
# Test float assert nanops._ensure_numeric(1.1) == 1.1
# Test complex assert nanops._ensure_numeric(1 + 2j) == 1 + 2j
def test_ndarray(self): # Test numeric ndarray values = np.array([1, 2, 3]) assert np.allclose(nanops._ensure_numeric(values), values)
# Test object ndarray o_values = values.astype(object) assert np.allclose(nanops._ensure_numeric(o_values), values)
# Test convertible string ndarray s_values = np.array(["1", "2", "3"], dtype=object) msg = r"Could not convert \['1' '2' '3'\] to numeric" with pytest.raises(TypeError, match=msg): nanops._ensure_numeric(s_values)
# Test non-convertible string ndarray s_values = np.array(["foo", "bar", "baz"], dtype=object) msg = r"Could not convert .* to numeric" with pytest.raises(TypeError, match=msg): nanops._ensure_numeric(s_values)
def test_convertable_values(self): with pytest.raises(TypeError, match="Could not convert string '1' to numeric"): nanops._ensure_numeric("1") with pytest.raises( TypeError, match="Could not convert string '1.1' to numeric" ): nanops._ensure_numeric("1.1") with pytest.raises( TypeError, match=r"Could not convert string '1\+1j' to numeric" ): nanops._ensure_numeric("1+1j")
def test_non_convertable_values(self): msg = "Could not convert string 'foo' to numeric" with pytest.raises(TypeError, match=msg): nanops._ensure_numeric("foo")
# with the wrong type, python raises TypeError for us msg = "argument must be a string or a number" with pytest.raises(TypeError, match=msg): nanops._ensure_numeric({}) with pytest.raises(TypeError, match=msg): nanops._ensure_numeric([])
class TestNanvarFixedValues: # xref GH10242 # Samples from a normal distribution. @pytest.fixture def variance(self): return 3.0
@pytest.fixture def samples(self, variance): return self.prng.normal(scale=variance**0.5, size=100000)
def test_nanvar_all_finite(self, samples, variance): actual_variance = nanops.nanvar(samples) tm.assert_almost_equal(actual_variance, variance, rtol=1e-2)
def test_nanvar_nans(self, samples, variance): samples_test = np.nan * np.ones(2 * samples.shape[0]) samples_test[::2] = samples
actual_variance = nanops.nanvar(samples_test, skipna=True) tm.assert_almost_equal(actual_variance, variance, rtol=1e-2)
actual_variance = nanops.nanvar(samples_test, skipna=False) tm.assert_almost_equal(actual_variance, np.nan, rtol=1e-2)
def test_nanstd_nans(self, samples, variance): samples_test = np.nan * np.ones(2 * samples.shape[0]) samples_test[::2] = samples
actual_std = nanops.nanstd(samples_test, skipna=True) tm.assert_almost_equal(actual_std, variance**0.5, rtol=1e-2)
actual_std = nanops.nanvar(samples_test, skipna=False) tm.assert_almost_equal(actual_std, np.nan, rtol=1e-2)
def test_nanvar_axis(self, samples, variance): # Generate some sample data. samples_unif = self.prng.uniform(size=samples.shape[0]) samples = np.vstack([samples, samples_unif])
actual_variance = nanops.nanvar(samples, axis=1) tm.assert_almost_equal( actual_variance, np.array([variance, 1.0 / 12]), rtol=1e-2 )
def test_nanvar_ddof(self): n = 5 samples = self.prng.uniform(size=(10000, n + 1)) samples[:, -1] = np.nan # Force use of our own algorithm.
variance_0 = nanops.nanvar(samples, axis=1, skipna=True, ddof=0).mean() variance_1 = nanops.nanvar(samples, axis=1, skipna=True, ddof=1).mean() variance_2 = nanops.nanvar(samples, axis=1, skipna=True, ddof=2).mean()
# The unbiased estimate. var = 1.0 / 12 tm.assert_almost_equal(variance_1, var, rtol=1e-2)
# The underestimated variance. tm.assert_almost_equal(variance_0, (n - 1.0) / n * var, rtol=1e-2)
# The overestimated variance. tm.assert_almost_equal(variance_2, (n - 1.0) / (n - 2.0) * var, rtol=1e-2)
@pytest.mark.parametrize("axis", range(2)) @pytest.mark.parametrize("ddof", range(3)) def test_ground_truth(self, axis, ddof): # Test against values that were precomputed with Numpy. samples = np.empty((4, 4)) samples[:3, :3] = np.array( [ [0.97303362, 0.21869576, 0.55560287], [0.72980153, 0.03109364, 0.99155171], [0.09317602, 0.60078248, 0.15871292], ] ) samples[3] = samples[:, 3] = np.nan
# Actual variances along axis=0, 1 for ddof=0, 1, 2 variance = np.array( [ [ [0.13762259, 0.05619224, 0.11568816], [0.20643388, 0.08428837, 0.17353224], [0.41286776, 0.16857673, 0.34706449], ], [ [0.09519783, 0.16435395, 0.05082054], [0.14279674, 0.24653093, 0.07623082], [0.28559348, 0.49306186, 0.15246163], ], ] )
# Test nanvar. var = nanops.nanvar(samples, skipna=True, axis=axis, ddof=ddof) tm.assert_almost_equal(var[:3], variance[axis, ddof]) assert np.isnan(var[3])
# Test nanstd. std = nanops.nanstd(samples, skipna=True, axis=axis, ddof=ddof) tm.assert_almost_equal(std[:3], variance[axis, ddof] ** 0.5) assert np.isnan(std[3])
@pytest.mark.parametrize("ddof", range(3)) @pytest.mark.parametrize("axis", [0, 1, None]) @pytest.mark.parametrize("method", ["var", "std", "sem"]) def test_complex_nanvar(self, ddof, axis, method): arr = self.prng.standard_normal((5, 4)) + self.prng.standard_normal((5, 4)) * 1j nanops_method = getattr(nanops, f"nan{method}") if method in {"var", "std"}: comparator_method = getattr(np, method) elif method == "sem": comparator_method = pytest.importorskip("scipy.stats").sem result = nanops_method(arr, axis=axis, ddof=ddof) expected = comparator_method(arr, axis=axis, ddof=ddof) tm.assert_almost_equal(result, expected)
@pytest.mark.parametrize("ddof", range(3)) def test_nanstd_roundoff(self, ddof): # Regression test for GH 10242 (test data taken from GH 10489). Ensure # that variance is stable. data = Series(766897346 * np.ones(10)) result = data.std(ddof=ddof) assert result == 0.0
@property def prng(self): return np.random.default_rng(2)
class TestNanskewFixedValues: # xref GH 11974 # Test data + skewness value (computed with scipy.stats.skew) @pytest.fixture def samples(self): return np.sin(np.linspace(0, 1, 200))
@pytest.fixture def actual_skew(self): return -0.1875895205961754
@pytest.mark.parametrize("val", [3075.2, 3075.3, 3075.5]) def test_constant_series(self, val): # xref GH 11974 data = val * np.ones(300) skew = nanops.nanskew(data) assert skew == 0.0
def test_all_finite(self): alpha, beta = 0.3, 0.1 left_tailed = self.prng.beta(alpha, beta, size=100) assert nanops.nanskew(left_tailed) < 0
alpha, beta = 0.1, 0.3 right_tailed = self.prng.beta(alpha, beta, size=100) assert nanops.nanskew(right_tailed) > 0
def test_ground_truth(self, samples, actual_skew): skew = nanops.nanskew(samples) tm.assert_almost_equal(skew, actual_skew)
def test_axis(self, samples, actual_skew): samples = np.vstack([samples, np.nan * np.ones(len(samples))]) skew = nanops.nanskew(samples, axis=1) tm.assert_almost_equal(skew, np.array([actual_skew, np.nan]))
def test_nans(self, samples): samples = np.hstack([samples, np.nan]) skew = nanops.nanskew(samples, skipna=False) assert np.isnan(skew)
def test_nans_skipna(self, samples, actual_skew): samples = np.hstack([samples, np.nan]) skew = nanops.nanskew(samples, skipna=True) tm.assert_almost_equal(skew, actual_skew)
@pytest.mark.parametrize( "initial_data, nobs", [ ([-2.05191341e-05, -4.10391103e-05], 27), ([-2.05191341e-10, -4.10391103e-10], 27), ([-2.05191341e-05, -4.10391103e-05], 10_000), ([-2.05191341e-10, -4.10391103e-10], 10_000), ], ) def test_low_variance(self, initial_data, nobs): st = pytest.importorskip("scipy.stats") data = np.zeros((nobs,), dtype=np.float64) data[: len(initial_data)] = initial_data skew = nanops.nanskew(data) expected = st.skew(data, bias=False) tm.assert_almost_equal(skew, expected)
@property def prng(self): return np.random.default_rng(2)
class TestNankurtFixedValues: # xref GH 11974 # Test data + kurtosis value (computed with scipy.stats.kurtosis) @pytest.fixture def samples(self): return np.sin(np.linspace(0, 1, 200))
@pytest.fixture def actual_kurt(self): return -1.2058303433799713
@pytest.mark.parametrize("val", [3075.2, 3075.3, 3075.5]) def test_constant_series(self, val): # xref GH 11974 data = val * np.ones(300) kurt = nanops.nankurt(data) tm.assert_equal(kurt, 0.0)
def test_all_finite(self): alpha, beta = 0.3, 0.1 left_tailed = self.prng.beta(alpha, beta, size=100) assert nanops.nankurt(left_tailed) < 2
alpha, beta = 0.1, 0.3 right_tailed = self.prng.beta(alpha, beta, size=100) assert nanops.nankurt(right_tailed) < 0
def test_ground_truth(self, samples, actual_kurt): kurt = nanops.nankurt(samples) tm.assert_almost_equal(kurt, actual_kurt)
def test_axis(self, samples, actual_kurt): samples = np.vstack([samples, np.nan * np.ones(len(samples))]) kurt = nanops.nankurt(samples, axis=1) tm.assert_almost_equal(kurt, np.array([actual_kurt, np.nan]))
def test_nans(self, samples): samples = np.hstack([samples, np.nan]) kurt = nanops.nankurt(samples, skipna=False) assert np.isnan(kurt)
def test_nans_skipna(self, samples, actual_kurt): samples = np.hstack([samples, np.nan]) kurt = nanops.nankurt(samples, skipna=True) tm.assert_almost_equal(kurt, actual_kurt)
@pytest.mark.parametrize( "initial_data, nobs", [ ([-2.05191341e-05, -4.10391103e-05], 27), ([-2.05191341e-10, -4.10391103e-10], 27), ([-2.05191341e-05, -4.10391103e-05], 10_000), ([-2.05191341e-10, -4.10391103e-10], 10_000), ], ) def test_low_variance(self, initial_data, nobs): # GH#57972 st = pytest.importorskip("scipy.stats") data = np.zeros((nobs,), dtype=np.float64) data[: len(initial_data)] = initial_data kurt = nanops.nankurt(data) expected = st.kurtosis(data, bias=False) tm.assert_almost_equal(kurt, expected)
@property def prng(self): return np.random.default_rng(2)
class TestDatetime64NaNOps: # Enabling mean changes the behavior of DataFrame.mean # See https://github.com/pandas-dev/pandas/issues/24752 def test_nanmean(self, unit): dti = pd.date_range("2016-01-01", periods=3).as_unit(unit) expected = dti[1]
for obj in [dti, dti._data]: result = nanops.nanmean(obj) assert result == expected
dti2 = dti.insert(1, pd.NaT)
for obj in [dti2, dti2._data]: result = nanops.nanmean(obj) assert result == expected
@pytest.mark.parametrize("constructor", ["M8", "m8"]) def test_nanmean_skipna_false(self, constructor, unit): dtype = f"{constructor}[{unit}]" arr = np.arange(12).astype(np.int64).view(dtype).reshape(4, 3)
arr[-1, -1] = "NaT"
result = nanops.nanmean(arr, skipna=False) assert np.isnat(result) assert result.dtype == dtype
result = nanops.nanmean(arr, axis=0, skipna=False) expected = np.array([4, 5, "NaT"], dtype=arr.dtype) tm.assert_numpy_array_equal(result, expected)
result = nanops.nanmean(arr, axis=1, skipna=False) expected = np.array([arr[0, 1], arr[1, 1], arr[2, 1], arr[-1, -1]]) tm.assert_numpy_array_equal(result, expected)
def test_use_bottleneck(): if nanops._BOTTLENECK_INSTALLED: with pd.option_context("use_bottleneck", True): assert pd.get_option("use_bottleneck")
with pd.option_context("use_bottleneck", False): assert not pd.get_option("use_bottleneck")
@pytest.mark.parametrize( "numpy_op, expected", [ (np.sum, 10), (np.nansum, 10), (np.mean, 2.5), (np.nanmean, 2.5), (np.median, 2.5), (np.nanmedian, 2.5), (np.min, 1), (np.max, 4), (np.nanmin, 1), (np.nanmax, 4), ],)def test_numpy_ops(numpy_op, expected): # GH8383 result = numpy_op(Series([1, 2, 3, 4])) assert result == expected
@pytest.mark.parametrize( "operation", [ nanops.nanany, nanops.nanall, nanops.nansum, nanops.nanmean, nanops.nanmedian, nanops.nanstd, nanops.nanvar, nanops.nansem, nanops.nanargmax, nanops.nanargmin, nanops.nanmax, nanops.nanmin, nanops.nanskew, nanops.nankurt, nanops.nanprod, ],)def test_nanops_independent_of_mask_param(operation): # GH22764 ser = Series([1, 2, np.nan, 3, np.nan, 4]) mask = ser.isna() median_expected = operation(ser._values) median_result = operation(ser._values, mask=mask) assert median_expected == median_result
@pytest.mark.parametrize("min_count", [-1, 0])def test_check_below_min_count_negative_or_zero_min_count(min_count): # GH35227 result = nanops.check_below_min_count((21, 37), None, min_count) expected_result = False assert result == expected_result
@pytest.mark.parametrize( "mask", [None, np.array([False, False, True]), np.array([True] + 9 * [False])])@pytest.mark.parametrize("min_count, expected_result", [(1, False), (101, True)])def test_check_below_min_count_positive_min_count(mask, min_count, expected_result): # GH35227 shape = (10, 10) result = nanops.check_below_min_count(shape, mask, min_count) assert result == expected_result
@td.skip_if_windows@td.skip_if_32bit@pytest.mark.parametrize("min_count, expected_result", [(1, False), (2812191852, True)])def test_check_below_min_count_large_shape(min_count, expected_result): # GH35227 large shape used to show that the issue is fixed shape = (2244367, 1253) result = nanops.check_below_min_count(shape, mask=None, min_count=min_count) assert result == expected_result
@pytest.mark.parametrize("func", ["nanmean", "nansum"])def test_check_bottleneck_disallow(any_real_numpy_dtype, func): # GH 42878 bottleneck sometimes produces unreliable results for mean and sum assert not nanops._bn_ok_dtype(np.dtype(any_real_numpy_dtype).type, func)
@pytest.mark.parametrize("val", [2**55, -(2**55), 20150515061816532])def test_nanmean_overflow(disable_bottleneck, val, using_python_scalars): # GH 10155 # In the previous implementation mean can overflow for int dtypes, it # is now consistent with numpy
ser = Series(val, index=range(500), dtype=np.int64) result = ser.mean() assert result == val if using_python_scalars: assert type(result) == float else: np_result = ser.values.mean() assert result == np_result assert result.dtype == np.float64
@pytest.mark.parametrize( "dtype", [ np.int16, np.int32, np.int64, np.float32, np.float64, getattr(np, "float128", None), ],)@pytest.mark.parametrize("method", ["mean", "std", "var", "skew", "kurt", "min", "max"])def test_returned_dtype(disable_bottleneck, dtype, method, using_python_scalars): if dtype is None: pytest.skip("np.float128 not available")
ser = Series(range(10), dtype=dtype) result = getattr(ser, method)() if using_python_scalars: if is_integer_dtype(dtype) and method in ["min", "max"]: assert isinstance(result, int) else: assert type(result) == float elif is_integer_dtype(dtype) and method not in ["min", "max"]: assert result.dtype == np.float64 else: assert result.dtype == dtype123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import sysimport types
import pytest
from pandas.compat._optional import ( VERSIONS, import_optional_dependency,)
import pandas._testing as tm
def test_import_optional(): match = "Import .*notapackage.* pip .* conda .* notapackage" with pytest.raises(ImportError, match=match) as exc_info: import_optional_dependency("notapackage") # The original exception should be there as context: assert isinstance(exc_info.value.__context__, ImportError)
result = import_optional_dependency("notapackage", errors="ignore") assert result is None
def test_xlrd_version_fallback(): pytest.importorskip("xlrd") import_optional_dependency("xlrd")
def test_bad_version(monkeypatch): name = "fakemodule" module = types.ModuleType(name) module.__version__ = "0.9.0" sys.modules[name] = module monkeypatch.setitem(VERSIONS, name, "1.0.0")
match = "Pandas requires .*1.0.0.* of .fakemodule.*'0.9.0'" with pytest.raises(ImportError, match=match): import_optional_dependency("fakemodule")
# Test min_version parameter result = import_optional_dependency("fakemodule", min_version="0.8") assert result is module
with tm.assert_produces_warning(UserWarning, match=match): result = import_optional_dependency("fakemodule", errors="warn") assert result is None
module.__version__ = "1.0.0" # exact match is OK result = import_optional_dependency("fakemodule") assert result is module
with pytest.raises(ImportError, match="Pandas requires version '1.1.0'"): import_optional_dependency("fakemodule", min_version="1.1.0")
with tm.assert_produces_warning(UserWarning, match="Pandas requires version"): result = import_optional_dependency( "fakemodule", errors="warn", min_version="1.1.0" ) assert result is None
result = import_optional_dependency( "fakemodule", errors="ignore", min_version="1.1.0" ) assert result is None
def test_submodule(monkeypatch): # Create a fake module with a submodule name = "fakemodule" module = types.ModuleType(name) module.__version__ = "0.9.0" sys.modules[name] = module sub_name = "submodule" submodule = types.ModuleType(sub_name) setattr(module, sub_name, submodule) sys.modules[f"{name}.{sub_name}"] = submodule monkeypatch.setitem(VERSIONS, name, "1.0.0")
match = "Pandas requires .*1.0.0.* of .fakemodule.*'0.9.0'" with pytest.raises(ImportError, match=match): import_optional_dependency("fakemodule.submodule")
with tm.assert_produces_warning(UserWarning, match=match): result = import_optional_dependency("fakemodule.submodule", errors="warn") assert result is None
module.__version__ = "1.0.0" # exact match is OK result = import_optional_dependency("fakemodule.submodule") assert result is submodule
def test_no_version_raises(monkeypatch): name = "fakemodule" module = types.ModuleType(name) sys.modules[name] = module monkeypatch.setitem(VERSIONS, name, "1.0.0")
with pytest.raises(ImportError, match="Can't determine .* fakemodule"): import_optional_dependency(name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123from collections.abc import Generatorimport contextlibimport weakref
import pytest
import pandas as pdimport pandas._testing as tmfrom pandas.core import accessor
def test_dirname_mixin() -> None: # GH37173
class X(accessor.DirNamesMixin): x = 1 y: int
def __init__(self) -> None: self.z = 3
result = [attr_name for attr_name in dir(X()) if not attr_name.startswith("_")]
assert result == ["x", "z"]
@contextlib.contextmanagerdef ensure_removed(obj, attr) -> Generator[None, None, None]: """Ensure that an attribute added to 'obj' during the test is removed when we're done """ try: yield finally: try: delattr(obj, attr) except AttributeError: pass obj._accessors.discard(attr)
class MyAccessor: def __init__(self, obj) -> None: self.obj = obj self.item = "item"
@property def prop(self): return self.item
def method(self): return self.item
@pytest.mark.parametrize( "obj, registrar", [ (pd.Series, pd.api.extensions.register_series_accessor), (pd.DataFrame, pd.api.extensions.register_dataframe_accessor), (pd.Index, pd.api.extensions.register_index_accessor), ],)def test_register(obj, registrar): with ensure_removed(obj, "mine"): before = set(dir(obj)) registrar("mine")(MyAccessor) o = obj([]) if obj is not pd.Series else obj([], dtype=object) assert o.mine.prop == "item" after = set(dir(obj)) assert (before ^ after) == {"mine"} assert "mine" in obj._accessors
def test_accessor_works(): with ensure_removed(pd.Series, "mine"): pd.api.extensions.register_series_accessor("mine")(MyAccessor)
s = pd.Series([1, 2]) assert s.mine.obj is s
assert s.mine.prop == "item" assert s.mine.method() == "item"
def test_overwrite_warns(): match = r".*MyAccessor.*fake.*Series.*" with tm.assert_produces_warning(UserWarning, match=match): with ensure_removed(pd.Series, "fake"): setattr(pd.Series, "fake", 123) pd.api.extensions.register_series_accessor("fake")(MyAccessor) s = pd.Series([1, 2]) assert s.fake.prop == "item"
def test_raises_attribute_error(): with ensure_removed(pd.Series, "bad"):
@pd.api.extensions.register_series_accessor("bad") class Bad: def __init__(self, data) -> None: raise AttributeError("whoops")
with pytest.raises(AttributeError, match="whoops"): pd.Series([], dtype=object).bad
@pytest.mark.parametrize( "klass, registrar", [ (pd.Series, pd.api.extensions.register_series_accessor), (pd.DataFrame, pd.api.extensions.register_dataframe_accessor), (pd.Index, pd.api.extensions.register_index_accessor), ],)def test_no_circular_reference(klass, registrar): # GH 41357 with ensure_removed(klass, "access"): registrar("access")(MyAccessor) obj = klass([0]) ref = weakref.ref(obj) assert obj.access.obj is obj del obj assert ref() is None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475from collections import defaultdictfrom datetime import datetimefrom itertools import product
import numpy as npimport pytest
from pandas import ( NA, DataFrame, MultiIndex, Series, array, concat, merge,)import pandas._testing as tmfrom pandas.core.algorithms import safe_sortimport pandas.core.common as comfrom pandas.core.sorting import ( _decons_group_index, get_group_index, is_int64_overflow_possible, lexsort_indexer, nargsort,)
@pytest.fixturedef left_right(): low, high, n = -1 << 10, 1 << 10, 1 << 20 left = DataFrame( np.random.default_rng(2).integers(low, high, (n, 7)), columns=list("ABCDEFG") ) left["left"] = left.sum(axis=1) right = left.sample( frac=1, random_state=np.random.default_rng(2), ignore_index=True ) right.columns = [*right.columns[:-1].tolist(), "right"] right["right"] *= -1 return left, right
class TestSorting: @pytest.mark.slow def test_int64_overflow(self): B = np.concatenate((np.arange(1000), np.arange(1000), np.arange(500))) A = np.arange(2500) df = DataFrame( { "A": A, "B": B, "C": A, "D": B, "E": A, "F": B, "G": A, "H": B, "values": np.random.default_rng(2).standard_normal(2500), } )
lg = df.groupby(["A", "B", "C", "D", "E", "F", "G", "H"]) rg = df.groupby(["H", "G", "F", "E", "D", "C", "B", "A"])
left = lg.sum()["values"] right = rg.sum()["values"]
exp_index, _ = left.index.sortlevel() tm.assert_index_equal(left.index, exp_index)
exp_index, _ = right.index.sortlevel(0) tm.assert_index_equal(right.index, exp_index)
tups = list(map(tuple, df[["A", "B", "C", "D", "E", "F", "G", "H"]].values)) tups = com.asarray_tuplesafe(tups)
expected = df.groupby(tups).sum()["values"]
for k, v in expected.items(): assert left[k] == right[k[::-1]] assert left[k] == v assert len(left) == len(right)
def test_int64_overflow_groupby_large_range(self): # GH9096 values = range(55109) data = DataFrame.from_dict({"a": values, "b": values, "c": values, "d": values}) grouped = data.groupby(["a", "b", "c", "d"]) assert len(grouped) == len(values)
@pytest.mark.slow @pytest.mark.parametrize("agg", ["mean", "median"]) def test_int64_overflow_groupby_large_df_shuffled(self, agg): rs = np.random.default_rng(2) arr = rs.integers(-1 << 12, 1 << 12, (1 << 15, 5)) i = rs.choice(len(arr), len(arr) * 4) arr = np.vstack((arr, arr[i])) # add some duplicate rows
i = rs.permutation(len(arr)) arr = arr[i] # shuffle rows
df = DataFrame(arr, columns=list("abcde")) df["jim"], df["joe"] = np.zeros((2, len(df))) gr = df.groupby(list("abcde"))
# verify this is testing what it is supposed to test! assert is_int64_overflow_possible( tuple(ping.ngroups for ping in gr._grouper.groupings) )
mi = MultiIndex.from_arrays( [ar.ravel() for ar in np.array_split(np.unique(arr, axis=0), 5, axis=1)], names=list("abcde"), )
res = DataFrame( np.zeros((len(mi), 2)), columns=["jim", "joe"], index=mi ).sort_index()
tm.assert_frame_equal(getattr(gr, agg)(), res)
@pytest.mark.parametrize( "order, na_position, exp", [ [ True, "last", list(range(5, 105)) + list(range(5)) + list(range(105, 110)), ], [ True, "first", list(range(5)) + list(range(105, 110)) + list(range(5, 105)), ], [ False, "last", list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110)), ], [ False, "first", list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1)), ], ], ) def test_lexsort_indexer(self, order, na_position, exp): keys = [[np.nan] * 5 + list(range(100)) + [np.nan] * 5] result = lexsort_indexer(keys, orders=order, na_position=na_position) tm.assert_numpy_array_equal(result, np.array(exp, dtype=np.intp))
@pytest.mark.parametrize( "ascending, na_position, exp", [ [ True, "last", list(range(5, 105)) + list(range(5)) + list(range(105, 110)), ], [ True, "first", list(range(5)) + list(range(105, 110)) + list(range(5, 105)), ], [ False, "last", list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110)), ], [ False, "first", list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1)), ], ], ) def test_nargsort(self, ascending, na_position, exp): # list places NaNs last, np.array(..., dtype="O") may not place NaNs first items = np.array([np.nan] * 5 + list(range(100)) + [np.nan] * 5, dtype="O")
# mergesort is the most difficult to get right because we want it to be # stable.
# According to numpy/core/tests/test_multiarray, """The number of # sorted items must be greater than ~50 to check the actual algorithm # because quick and merge sort fall over to insertion sort for small # arrays."""
result = nargsort( items, kind="mergesort", ascending=ascending, na_position=na_position ) tm.assert_numpy_array_equal(result, np.array(exp), check_dtype=False)
class TestMerge: def test_int64_overflow_outer_merge(self): # #2690, combinatorial explosion df1 = DataFrame( np.random.default_rng(2).standard_normal((1000, 7)), columns=[*list("ABCDEF"), "G1"], ) df2 = DataFrame( np.random.default_rng(3).standard_normal((1000, 7)), columns=[*list("ABCDEF"), "G2"], ) result = merge(df1, df2, how="outer") assert len(result) == 2000
@pytest.mark.slow def test_int64_overflow_check_sum_col(self, left_right): left, right = left_right
out = merge(left, right, how="outer") assert len(out) == len(left) tm.assert_series_equal(out["left"], -out["right"], check_names=False) result = out.iloc[:, :-2].sum(axis=1) tm.assert_series_equal(out["left"], result, check_names=False) assert result.name is None
@pytest.mark.slow def test_int64_overflow_how_merge(self, left_right, join_type): left, right = left_right
out = merge(left, right, how="outer") out.sort_values(out.columns.tolist(), inplace=True) tm.assert_frame_equal(out, merge(left, right, how=join_type, sort=True))
@pytest.mark.slow def test_int64_overflow_sort_false_order(self, left_right): left, right = left_right
# check that left merge w/ sort=False maintains left frame order out = merge(left, right, how="left", sort=False) tm.assert_frame_equal(left, out[left.columns.tolist()])
out = merge(right, left, how="left", sort=False) tm.assert_frame_equal(right, out[right.columns.tolist()])
@pytest.mark.slow def test_int64_overflow_one_to_many_none_match(self, join_type, sort): # one-2-many/none match how = join_type low, high, n = -1 << 10, 1 << 10, 1 << 11 left = DataFrame( np.random.default_rng(2).integers(low, high, (n, 7)).astype("int64"), columns=list("ABCDEFG"), )
# confirm that this is checking what it is supposed to check shape = left.apply(Series.nunique).values assert is_int64_overflow_possible(shape)
# add duplicates to left frame left = concat([left, left], ignore_index=True)
right = DataFrame( np.random.default_rng(3).integers(low, high, (n // 2, 7)).astype("int64"), columns=list("ABCDEFG"), )
# add duplicates & overlap with left to the right frame i = np.random.default_rng(4).choice(len(left), n) right = concat([right, right, left.iloc[i]], ignore_index=True)
left["left"] = np.random.default_rng(2).standard_normal(len(left)) right["right"] = np.random.default_rng(2).standard_normal(len(right))
# shuffle left & right frames left = left.sample( frac=1, ignore_index=True, random_state=np.random.default_rng(5) ) right = right.sample( frac=1, ignore_index=True, random_state=np.random.default_rng(6) )
# manually compute outer merge ldict, rdict = defaultdict(list), defaultdict(list)
for idx, row in left.set_index(list("ABCDEFG")).iterrows(): ldict[idx].append(row["left"])
for idx, row in right.set_index(list("ABCDEFG")).iterrows(): rdict[idx].append(row["right"])
vals = [] for k, lval in ldict.items(): rval = rdict.get(k, [np.nan]) for lv, rv in product(lval, rval): vals.append((*k, lv, rv))
for k, rval in rdict.items(): if k not in ldict: vals.extend((*k, np.nan, rv) for rv in rval)
out = DataFrame(vals, columns=[*list("ABCDEFG"), "left", "right"]) out = out.sort_values(out.columns.to_list(), ignore_index=True)
jmask = { "left": out["left"].notna(), "right": out["right"].notna(), "inner": out["left"].notna() & out["right"].notna(), "outer": np.ones(len(out), dtype="bool"), }
mask = jmask[how] frame = out[mask].sort_values(out.columns.to_list(), ignore_index=True) assert mask.all() ^ mask.any() or how == "outer"
res = merge(left, right, how=how, sort=sort) if sort: kcols = list("ABCDEFG") tm.assert_frame_equal( res[kcols], res[kcols].sort_values(kcols, kind="mergesort") )
# as in GH9092 dtypes break with outer/right join # 2021-12-18: dtype does not break anymore tm.assert_frame_equal( frame, res.sort_values(res.columns.to_list(), ignore_index=True) )
@pytest.mark.parametrize( "codes_list, shape", [ [ [ np.tile([0, 1, 2, 3, 0, 1, 2, 3], 100).astype(np.int64), np.tile([0, 2, 4, 3, 0, 1, 2, 3], 100).astype(np.int64), np.tile([5, 1, 0, 2, 3, 0, 5, 4], 100).astype(np.int64), ], (4, 5, 6), ], [ [ np.tile(np.arange(10000, dtype=np.int64), 5), np.tile(np.arange(10000, dtype=np.int64), 5), ], (10000, 10000), ], ],)def test_decons(codes_list, shape): group_index = get_group_index(codes_list, shape, sort=True, xnull=True) codes_list2 = _decons_group_index(group_index, shape)
for a, b in zip(codes_list, codes_list2, strict=True): tm.assert_numpy_array_equal(a, b)
class TestSafeSort: @pytest.mark.parametrize( "arg, exp", [ [[3, 1, 2, 0, 4], [0, 1, 2, 3, 4]], [ np.array(list("baaacb"), dtype=object), np.array(list("aaabbc"), dtype=object), ], [[], []], ], ) def test_basic_sort(self, arg, exp): result = safe_sort(np.array(arg)) expected = np.array(exp) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("verify", [True, False]) @pytest.mark.parametrize( "codes, exp_codes", [ [[0, 1, 1, 2, 3, 0, -1, 4], [3, 1, 1, 2, 0, 3, -1, 4]], [[], []], ], ) def test_codes(self, verify, codes, exp_codes): values = np.array([3, 1, 2, 0, 4]) expected = np.array([0, 1, 2, 3, 4])
result, result_codes = safe_sort( values, codes, use_na_sentinel=True, verify=verify ) expected_codes = np.array(exp_codes, dtype=np.intp) tm.assert_numpy_array_equal(result, expected) tm.assert_numpy_array_equal(result_codes, expected_codes)
def test_codes_out_of_bound(self): values = np.array([3, 1, 2, 0, 4]) expected = np.array([0, 1, 2, 3, 4])
# out of bound indices codes = [0, 101, 102, 2, 3, 0, 99, 4] result, result_codes = safe_sort(values, codes, use_na_sentinel=True) expected_codes = np.array([3, -1, -1, 2, 0, 3, -1, 4], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) tm.assert_numpy_array_equal(result_codes, expected_codes)
@pytest.mark.parametrize("codes", [[-1, -1], [2, -1], [2, 2]]) def test_codes_empty_array_out_of_bound(self, codes): empty_values = np.array([]) expected_codes = -np.ones_like(codes, dtype=np.intp) _, result_codes = safe_sort(empty_values, codes) tm.assert_numpy_array_equal(result_codes, expected_codes)
def test_mixed_integer(self): values = np.array(["b", 1, 0, "a", 0, "b"], dtype=object) result = safe_sort(values) expected = np.array([0, 0, 1, "a", "b", "b"], dtype=object) tm.assert_numpy_array_equal(result, expected)
def test_mixed_integer_with_codes(self): values = np.array(["b", 1, 0, "a"], dtype=object) codes = [0, 1, 2, 3, 0, -1, 1] result, result_codes = safe_sort(values, codes) expected = np.array([0, 1, "a", "b"], dtype=object) expected_codes = np.array([3, 1, 0, 2, 3, -1, 1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) tm.assert_numpy_array_equal(result_codes, expected_codes)
def test_unsortable(self): # GH 13714 arr = np.array([1, 2, datetime.now(), 0, 3], dtype=object) msg = "'[<>]' not supported between instances of .*" with pytest.raises(TypeError, match=msg): safe_sort(arr)
@pytest.mark.parametrize( "arg, codes, err, msg", [ [1, None, TypeError, "Only np.ndarray, ExtensionArray, and Index"], [np.array([0, 1, 2]), 1, TypeError, "Only list-like objects or None"], [np.array([0, 1, 2, 1]), [0, 1], ValueError, "values should be unique"], ], ) def test_exceptions(self, arg, codes, err, msg): with pytest.raises(err, match=msg): safe_sort(values=arg, codes=codes)
@pytest.mark.parametrize( "arg, exp", [[[1, 3, 2], [1, 2, 3]], [[1, 3, NA, 2], [1, 2, 3, NA]]] ) def test_extension_array(self, arg, exp): a = array(arg, dtype="Int64") result = safe_sort(a) expected = array(exp, dtype="Int64") tm.assert_extension_array_equal(result, expected)
@pytest.mark.parametrize("verify", [True, False]) def test_extension_array_codes(self, verify): a = array([1, 3, 2], dtype="Int64") result, codes = safe_sort(a, [0, 1, -1, 2], use_na_sentinel=True, verify=verify) expected_values = array([1, 2, 3], dtype="Int64") expected_codes = np.array([0, 2, -1, 1], dtype=np.intp) tm.assert_extension_array_equal(result, expected_values) tm.assert_numpy_array_equal(codes, expected_codes)
def test_mixed_str_null(nulls_fixture): values = np.array(["b", nulls_fixture, "a", "b"], dtype=object) result = safe_sort(values) expected = np.array(["a", "b", "b", nulls_fixture], dtype=object) tm.assert_numpy_array_equal(result, expected)
def test_safe_sort_multiindex(): # GH#48412 arr1 = Series([2, 1, NA, NA], dtype="Int64") arr2 = [2, 1, 3, 3] midx = MultiIndex.from_arrays([arr1, arr2]) result = safe_sort(midx) expected = MultiIndex.from_arrays( [Series([1, 2, NA, NA], dtype="Int64"), [1, 2, 3, 3]] ) tm.assert_index_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317from datetime import datetime
import numpy as npimport pytest
from pandas._libs import iNaT
from pandas import arrayimport pandas._testing as tmimport pandas.core.algorithms as algos
@pytest.fixture( params=[ (np.int8, np.int16(127), np.int8), (np.int8, np.int16(128), np.int16), (np.int32, 1, np.int32), (np.int32, 2.0, np.float64), (np.int32, 3.0 + 4.0j, np.complex128), (np.int32, True, np.object_), (np.int32, "", np.object_), (np.float64, 1, np.float64), (np.float64, 2.0, np.float64), (np.float64, 3.0 + 4.0j, np.complex128), (np.float64, True, np.object_), (np.float64, "", np.object_), (np.complex128, 1, np.complex128), (np.complex128, 2.0, np.complex128), (np.complex128, 3.0 + 4.0j, np.complex128), (np.complex128, True, np.object_), (np.complex128, "", np.object_), (np.bool_, 1, np.object_), (np.bool_, 2.0, np.object_), (np.bool_, 3.0 + 4.0j, np.object_), (np.bool_, True, np.bool_), (np.bool_, "", np.object_), ])def dtype_fill_out_dtype(request): return request.param
class TestTake: def test_1d_fill_nonna(self, dtype_fill_out_dtype): dtype, fill_value, out_dtype = dtype_fill_out_dtype data = np.random.default_rng(2).integers(0, 2, 4).astype(dtype) indexer = [2, 1, 0, -1]
result = algos.take_nd(data, indexer, fill_value=fill_value) assert (result[[0, 1, 2]] == data[[2, 1, 0]]).all() assert result[3] == fill_value assert result.dtype == out_dtype
indexer = [2, 1, 0, 1]
result = algos.take_nd(data, indexer, fill_value=fill_value) assert (result[[0, 1, 2, 3]] == data[indexer]).all() assert result.dtype == dtype
def test_2d_fill_nonna(self, dtype_fill_out_dtype): dtype, fill_value, out_dtype = dtype_fill_out_dtype data = np.random.default_rng(2).integers(0, 2, (5, 3)).astype(dtype) indexer = [2, 1, 0, -1]
result = algos.take_nd(data, indexer, axis=0, fill_value=fill_value) assert (result[[0, 1, 2], :] == data[[2, 1, 0], :]).all() assert (result[3, :] == fill_value).all() assert result.dtype == out_dtype
result = algos.take_nd(data, indexer, axis=1, fill_value=fill_value) assert (result[:, [0, 1, 2]] == data[:, [2, 1, 0]]).all() assert (result[:, 3] == fill_value).all() assert result.dtype == out_dtype
indexer = [2, 1, 0, 1] result = algos.take_nd(data, indexer, axis=0, fill_value=fill_value) assert (result[[0, 1, 2, 3], :] == data[indexer, :]).all() assert result.dtype == dtype
result = algos.take_nd(data, indexer, axis=1, fill_value=fill_value) assert (result[:, [0, 1, 2, 3]] == data[:, indexer]).all() assert result.dtype == dtype
def test_3d_fill_nonna(self, dtype_fill_out_dtype): dtype, fill_value, out_dtype = dtype_fill_out_dtype
data = np.random.default_rng(2).integers(0, 2, (5, 4, 3)).astype(dtype) indexer = [2, 1, 0, -1]
result = algos.take_nd(data, indexer, axis=0, fill_value=fill_value) assert (result[[0, 1, 2], :, :] == data[[2, 1, 0], :, :]).all() assert (result[3, :, :] == fill_value).all() assert result.dtype == out_dtype
result = algos.take_nd(data, indexer, axis=1, fill_value=fill_value) assert (result[:, [0, 1, 2], :] == data[:, [2, 1, 0], :]).all() assert (result[:, 3, :] == fill_value).all() assert result.dtype == out_dtype
result = algos.take_nd(data, indexer, axis=2, fill_value=fill_value) assert (result[:, :, [0, 1, 2]] == data[:, :, [2, 1, 0]]).all() assert (result[:, :, 3] == fill_value).all() assert result.dtype == out_dtype
indexer = [2, 1, 0, 1] result = algos.take_nd(data, indexer, axis=0, fill_value=fill_value) assert (result[[0, 1, 2, 3], :, :] == data[indexer, :, :]).all() assert result.dtype == dtype
result = algos.take_nd(data, indexer, axis=1, fill_value=fill_value) assert (result[:, [0, 1, 2, 3], :] == data[:, indexer, :]).all() assert result.dtype == dtype
result = algos.take_nd(data, indexer, axis=2, fill_value=fill_value) assert (result[:, :, [0, 1, 2, 3]] == data[:, :, indexer]).all() assert result.dtype == dtype
def test_1d_other_dtypes(self): arr = np.random.default_rng(2).standard_normal(10).astype(np.float32)
indexer = [1, 2, 3, -1] result = algos.take_nd(arr, indexer) expected = arr.take(indexer) expected[-1] = np.nan tm.assert_almost_equal(result, expected)
def test_2d_other_dtypes(self): arr = np.random.default_rng(2).standard_normal((10, 5)).astype(np.float32)
indexer = [1, 2, 3, -1]
# axis=0 result = algos.take_nd(arr, indexer, axis=0) expected = arr.take(indexer, axis=0) expected[-1] = np.nan tm.assert_almost_equal(result, expected)
# axis=1 result = algos.take_nd(arr, indexer, axis=1) expected = arr.take(indexer, axis=1) expected[:, -1] = np.nan tm.assert_almost_equal(result, expected)
def test_1d_bool(self): arr = np.array([0, 1, 0], dtype=bool)
result = algos.take_nd(arr, [0, 2, 2, 1]) expected = arr.take([0, 2, 2, 1]) tm.assert_numpy_array_equal(result, expected)
result = algos.take_nd(arr, [0, 2, -1]) assert result.dtype == np.object_
def test_2d_bool(self): arr = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 1]], dtype=bool)
result = algos.take_nd(arr, [0, 2, 2, 1]) expected = arr.take([0, 2, 2, 1], axis=0) tm.assert_numpy_array_equal(result, expected)
result = algos.take_nd(arr, [0, 2, 2, 1], axis=1) expected = arr.take([0, 2, 2, 1], axis=1) tm.assert_numpy_array_equal(result, expected)
result = algos.take_nd(arr, [0, 2, -1]) assert result.dtype == np.object_
def test_2d_float32(self): arr = np.random.default_rng(2).standard_normal((4, 3)).astype(np.float32) indexer = [0, 2, -1, 1, -1]
# axis=0 result = algos.take_nd(arr, indexer, axis=0)
expected = arr.take(indexer, axis=0) expected[[2, 4], :] = np.nan tm.assert_almost_equal(result, expected)
# axis=1 result = algos.take_nd(arr, indexer, axis=1) expected = arr.take(indexer, axis=1) expected[:, [2, 4]] = np.nan tm.assert_almost_equal(result, expected)
def test_2d_datetime64(self): # 2005/01/01 - 2006/01/01 arr = ( np.random.default_rng(2).integers(11_045_376, 11_360_736, (5, 3)) * 100_000_000_000 ) arr = arr.view(dtype="datetime64[ns]") indexer = [0, 2, -1, 1, -1]
# axis=0 result = algos.take_nd(arr, indexer, axis=0) expected = arr.take(indexer, axis=0) expected.view(np.int64)[[2, 4], :] = iNaT tm.assert_almost_equal(result, expected)
result = algos.take_nd(arr, indexer, axis=0, fill_value=datetime(2007, 1, 1)) expected = arr.take(indexer, axis=0) expected[[2, 4], :] = datetime(2007, 1, 1) tm.assert_almost_equal(result, expected)
# axis=1 result = algos.take_nd(arr, indexer, axis=1) expected = arr.take(indexer, axis=1) expected.view(np.int64)[:, [2, 4]] = iNaT tm.assert_almost_equal(result, expected)
result = algos.take_nd(arr, indexer, axis=1, fill_value=datetime(2007, 1, 1)) expected = arr.take(indexer, axis=1) expected[:, [2, 4]] = datetime(2007, 1, 1) tm.assert_almost_equal(result, expected)
def test_take_axis_0(self): arr = np.arange(12).reshape(4, 3) result = algos.take(arr, [0, -1]) expected = np.array([[0, 1, 2], [9, 10, 11]]) tm.assert_numpy_array_equal(result, expected)
# allow_fill=True result = algos.take(arr, [0, -1], allow_fill=True, fill_value=0) expected = np.array([[0, 1, 2], [0, 0, 0]]) tm.assert_numpy_array_equal(result, expected)
def test_take_axis_1(self): arr = np.arange(12).reshape(4, 3) result = algos.take(arr, [0, -1], axis=1) expected = np.array([[0, 2], [3, 5], [6, 8], [9, 11]]) tm.assert_numpy_array_equal(result, expected)
# allow_fill=True result = algos.take(arr, [0, -1], axis=1, allow_fill=True, fill_value=0) expected = np.array([[0, 0], [3, 0], [6, 0], [9, 0]]) tm.assert_numpy_array_equal(result, expected)
# GH#26976 make sure we validate along the correct axis with pytest.raises(IndexError, match="indices are out-of-bounds"): algos.take(arr, [0, 3], axis=1, allow_fill=True, fill_value=0)
def test_take_non_hashable_fill_value(self): arr = np.array([1, 2, 3]) indexer = np.array([1, -1]) with pytest.raises(ValueError, match="fill_value must be a scalar"): algos.take(arr, indexer, allow_fill=True, fill_value=[1])
# with object dtype it is allowed arr = np.array([1, 2, 3], dtype=object) result = algos.take(arr, indexer, allow_fill=True, fill_value=[1]) expected = np.array([2, [1]], dtype=object) tm.assert_numpy_array_equal(result, expected)
class TestExtensionTake: # The take method found in pd.api.extensions
def test_bounds_check_large(self): arr = np.array([1, 2])
msg = "indices are out-of-bounds" with pytest.raises(IndexError, match=msg): algos.take(arr, [2, 3], allow_fill=True)
msg = "index 2 is out of bounds for( axis 0 with)? size 2" with pytest.raises(IndexError, match=msg): algos.take(arr, [2, 3], allow_fill=False)
def test_bounds_check_small(self): arr = np.array([1, 2, 3], dtype=np.int64) indexer = [0, -1, -2]
msg = r"'indices' contains values less than allowed \(-2 < -1\)" with pytest.raises(ValueError, match=msg): algos.take(arr, indexer, allow_fill=True)
result = algos.take(arr, indexer) expected = np.array([1, 3, 2], dtype=np.int64) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("allow_fill", [True, False]) def test_take_empty(self, allow_fill): arr = np.array([], dtype=np.int64) # empty take is ok result = algos.take(arr, [], allow_fill=allow_fill) tm.assert_numpy_array_equal(arr, result)
msg = "|".join( [ "cannot do a non-empty take from an empty axes.", "indices are out-of-bounds", ] ) with pytest.raises(IndexError, match=msg): algos.take(arr, [0], allow_fill=allow_fill)
def test_take_na_empty(self): result = algos.take(np.array([]), [-1, -1], allow_fill=True, fill_value=0.0) expected = np.array([0.0, 0.0]) tm.assert_numpy_array_equal(result, expected)
def test_take_coerces_list(self): # GH#52981 coercing is deprecated, disabled in 3.0 arr = [1, 2, 3] msg = ( "pd.api.extensions.take requires a numpy.ndarray, ExtensionArray, " "Index, Series, or NumpyExtensionArray got list" ) with pytest.raises(TypeError, match=msg): algos.take(arr, [0, 0])
def test_take_NumpyExtensionArray(self): # GH#59177 arr = array([1 + 1j, 2, 3]) # NumpyEADtype('complex128') (NumpyExtensionArray) assert algos.take(arr, [2]) == 2 arr = array([1, 2, 3]) # Int64Dtype() (ExtensionArray) assert algos.take(arr, [2]) == 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904import decimal
import numpy as npfrom numpy import iinfoimport pytest
import pandas.util._test_decorators as td
import pandas as pdfrom pandas import ( ArrowDtype, DataFrame, Index, Series, option_context, to_numeric,)import pandas._testing as tm
@pytest.fixture(params=[None, "raise", "coerce"])def errors(request): return request.param
@pytest.fixture(params=[True, False])def signed(request): return request.param
@pytest.fixture(params=[lambda x: x, str], ids=["identity", "str"])def transform(request): return request.param
@pytest.fixture(params=[47393996303418497800, 100000000000000000000])def large_val(request): return request.param
@pytest.fixture(params=[True, False])def multiple_elts(request): return request.param
@pytest.fixture( params=[ (lambda x: Index(x, name="idx"), tm.assert_index_equal), (lambda x: Series(x, name="ser"), tm.assert_series_equal), (lambda x: np.array(Index(x).values), tm.assert_numpy_array_equal), ])def transform_assert_equal(request): return request.param
@pytest.mark.parametrize( "input_kwargs,result_kwargs", [ ({}, {"dtype": np.int64}), ({"errors": "coerce", "downcast": "integer"}, {"dtype": np.int8}), ],)def test_empty(input_kwargs, result_kwargs): # see gh-16302 ser = Series([], dtype=object) result = to_numeric(ser, **input_kwargs)
expected = Series([], **result_kwargs) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))])@pytest.mark.parametrize("last_val", ["7", 7])def test_series(last_val, infer_string): with option_context("future.infer_string", infer_string): ser = Series(["1", "-3.14", last_val]) result = to_numeric(ser)
expected = Series([1, -3.14, 7]) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "data", [ [1, 3, 4, 5], [1.0, 3.0, 4.0, 5.0], # Bool is regarded as numeric. [True, False, True, True], ],)def test_series_numeric(data): ser = Series(data, index=list("ABCD"), name="EFG")
result = to_numeric(ser) tm.assert_series_equal(result, ser)
@pytest.mark.parametrize( "data,msg", [ ([1, -3.14, "apple"], 'Unable to parse string "apple" at position 2'), ( ["orange", 1, -3.14, "apple"], 'Unable to parse string "orange" at position 0', ), ],)def test_error(data, msg): ser = Series(data)
with pytest.raises(ValueError, match=msg): to_numeric(ser, errors="raise")
def test_ignore_error(): ser = Series([1, -3.14, "apple"]) result = to_numeric(ser, errors="coerce")
expected = Series([1, -3.14, np.nan]) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "errors,exp", [ ("raise", 'Unable to parse string "apple" at position 2'), # Coerces to float. ("coerce", [1.0, 0.0, np.nan]), ],)def test_bool_handling(errors, exp): ser = Series([True, False, "apple"])
if isinstance(exp, str): with pytest.raises(ValueError, match=exp): to_numeric(ser, errors=errors) else: result = to_numeric(ser, errors=errors) expected = Series(exp)
tm.assert_series_equal(result, expected)
def test_list(): ser = ["1", "-3.14", "7"] res = to_numeric(ser)
expected = np.array([1, -3.14, 7]) tm.assert_numpy_array_equal(res, expected)
@pytest.mark.parametrize( "data,arr_kwargs", [ ([1, 3, 4, 5], {"dtype": np.int64}), ([1.0, 3.0, 4.0, 5.0], {}), # Boolean is regarded as numeric. ([True, False, True, True], {}), ],)def test_list_numeric(data, arr_kwargs): result = to_numeric(data) expected = np.array(data, **arr_kwargs) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("kwargs", [{"dtype": "O"}, {}])def test_numeric(kwargs): data = [1, -3.14, 7]
ser = Series(data, **kwargs) result = to_numeric(ser)
expected = Series(data) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "columns", [ # One column. "a", # Multiple columns. ["a", "b"], ],)def test_numeric_df_columns(columns): # see gh-14827 df = DataFrame( { "a": [1.2, decimal.Decimal("3.14"), decimal.Decimal("infinity"), "0.1"], "b": [1.0, 2.0, 3.0, 4.0], } )
expected = DataFrame({"a": [1.2, 3.14, np.inf, 0.1], "b": [1.0, 2.0, 3.0, 4.0]}) df[columns] = df[columns].apply(to_numeric)
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize( "data,exp_data", [ ( [[decimal.Decimal("3.14"), 1.0], decimal.Decimal("1.6"), 0.1], [[3.14, 1.0], 1.6, 0.1], ), ([np.array([decimal.Decimal("3.14"), 1.0]), 0.1], [[3.14, 1.0], 0.1]), ],)def test_numeric_embedded_arr_likes(data, exp_data): # Test to_numeric with embedded lists and arrays df = DataFrame({"a": data}) df["a"] = df["a"].apply(to_numeric)
expected = DataFrame({"a": exp_data}) tm.assert_frame_equal(df, expected)
def test_all_nan(): ser = Series(["a", "b", "c"]) result = to_numeric(ser, errors="coerce")
expected = Series([np.nan, np.nan, np.nan]) tm.assert_series_equal(result, expected)
def test_type_check(errors): # see gh-11776 df = DataFrame({"a": [1, -3.14, 7], "b": ["4", "5", "6"]}) kwargs = {"errors": errors} if errors is not None else {} with pytest.raises(TypeError, match="1-d array"): to_numeric(df, **kwargs)
@pytest.mark.parametrize("val", [1, 1.1, 20001])def test_scalar(val, signed, transform): val = -val if signed else val assert to_numeric(transform(val)) == float(val)
def test_really_large_scalar(large_val, signed, transform, errors): # see gh-24910 kwargs = {"errors": errors} if errors is not None else {} val = -large_val if signed else large_val
val = transform(val)
expected = float(val) if errors == "coerce" else int(val) tm.assert_almost_equal(to_numeric(val, **kwargs), expected)
def test_really_large_in_arr(large_val, signed, transform, multiple_elts, errors): # see gh-24910 kwargs = {"errors": errors} if errors is not None else {} val = -large_val if signed else large_val val = transform(val)
extra_elt = "string" arr = [val] + multiple_elts * [extra_elt]
coercing = errors == "coerce"
if errors in (None, "raise") and multiple_elts: msg = 'Unable to parse string "string" at position 1'
with pytest.raises(ValueError, match=msg): to_numeric(arr, **kwargs) else: result = to_numeric(arr, **kwargs)
exp_val = float(val) if (coercing) else int(val) expected = [exp_val]
if multiple_elts: if coercing: expected.append(np.nan) exp_dtype = float else: expected.append(extra_elt) exp_dtype = object else: exp_dtype = float if isinstance(exp_val, float) else object
tm.assert_almost_equal(result, np.array(expected, dtype=exp_dtype))
def test_really_large_in_arr_consistent(large_val, signed, multiple_elts, errors): # see gh-24910 # # Even if we discover that we have to hold float, does not mean # we should be lenient on subsequent elements that fail to be integer. kwargs = {"errors": errors} if errors is not None else {} arr = [str(-large_val if signed else large_val)]
if multiple_elts: arr.insert(0, large_val)
result = to_numeric(arr, **kwargs) expected = [float(i) if errors == "coerce" else int(i) for i in arr] exp_dtype = float if errors == "coerce" else object
tm.assert_almost_equal(result, np.array(expected, dtype=exp_dtype))
@pytest.mark.parametrize( "errors,checker", [ ("raise", 'Unable to parse string "fail" at position 0'), ("coerce", lambda x: np.isnan(x)), ],)def test_scalar_fail(errors, checker): scalar = "fail"
if isinstance(checker, str): with pytest.raises(ValueError, match=checker): to_numeric(scalar, errors=errors) else: assert checker(to_numeric(scalar, errors=errors))
@pytest.mark.parametrize("data", [[1, 2, 3], [1.0, np.nan, 3, np.nan]])def test_numeric_dtypes(data, transform_assert_equal): transform, assert_equal = transform_assert_equal data = transform(data)
result = to_numeric(data) assert_equal(result, data)
@pytest.mark.parametrize( "data,exp", [ (["1", "2", "3"], np.array([1, 2, 3], dtype="int64")), (["1.5", "2.7", "3.4"], np.array([1.5, 2.7, 3.4])), ],)def test_str(data, exp, transform_assert_equal): transform, assert_equal = transform_assert_equal result = to_numeric(transform(data))
expected = transform(exp) assert_equal(result, expected)
def test_datetime_like(tz_naive_fixture, transform_assert_equal): transform, assert_equal = transform_assert_equal idx = pd.date_range("20130101", periods=3, tz=tz_naive_fixture)
result = to_numeric(transform(idx)) expected = transform(idx.asi8) assert_equal(result, expected)
def test_timedelta(transform_assert_equal): transform, assert_equal = transform_assert_equal idx = pd.timedelta_range("1 days", periods=3, freq="D")
result = to_numeric(transform(idx)) expected = transform(idx.asi8) assert_equal(result, expected)
@pytest.mark.parametrize( "scalar", [ pd.Timedelta(1, "D"), pd.Timestamp("2017-01-01T12"), pd.Timestamp("2017-01-01T12", tz="US/Pacific"), ],)def test_timedelta_timestamp_scalar(scalar): # GH#59944 result = to_numeric(scalar) expected = to_numeric(Series(scalar))[0] assert result == expected
def test_period(request, transform_assert_equal): transform, assert_equal = transform_assert_equal
idx = pd.period_range("2011-01", periods=3, freq="M", name="") inp = transform(idx)
if not isinstance(inp, Index): request.applymarker( pytest.mark.xfail(reason="Missing PeriodDtype support in to_numeric") ) result = to_numeric(inp) expected = transform(idx.asi8) assert_equal(result, expected)
@pytest.mark.parametrize( "errors,expected", [ ("raise", "Invalid object type at position 0"), ("coerce", Series([np.nan, 1.0, np.nan])), ],)def test_non_hashable(errors, expected): # see gh-13324 ser = Series([[10.0, 2], 1.0, "apple"])
if isinstance(expected, str): with pytest.raises(TypeError, match=expected): to_numeric(ser, errors=errors) else: result = to_numeric(ser, errors=errors) tm.assert_series_equal(result, expected)
def test_downcast_invalid_cast(): # see gh-13352 data = ["1", 2, 3] invalid_downcast = "unsigned-integer" msg = "invalid downcasting method provided"
with pytest.raises(ValueError, match=msg): to_numeric(data, downcast=invalid_downcast)
def test_errors_invalid_value(): # see gh-26466 data = ["1", 2, 3] invalid_error_value = "invalid" msg = "invalid error value specified"
with pytest.raises(ValueError, match=msg): to_numeric(data, errors=invalid_error_value)
@pytest.mark.parametrize( "data", [ ["1", 2, 3], [1, 2, 3], np.array(["1970-01-02", "1970-01-03", "1970-01-04"], dtype="datetime64[D]"), ],)@pytest.mark.parametrize( "kwargs,exp_dtype", [ # Basic function tests. ({}, np.int64), ({"downcast": None}, np.int64), # Support below np.float32 is rare and far between. ({"downcast": "float"}, np.dtype(np.float32).char), # Basic dtype support. ({"downcast": "unsigned"}, np.dtype(np.typecodes["UnsignedInteger"][0])), ],)def test_downcast_basic(data, kwargs, exp_dtype): # see gh-13352 result = to_numeric(data, **kwargs) expected = np.array([1, 2, 3], dtype=exp_dtype) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("signed_downcast", ["integer", "signed"])@pytest.mark.parametrize( "data", [ ["1", 2, 3], [1, 2, 3], np.array(["1970-01-02", "1970-01-03", "1970-01-04"], dtype="datetime64[D]"), ],)def test_signed_downcast(data, signed_downcast): # see gh-13352 smallest_int_dtype = np.dtype(np.typecodes["Integer"][0]) expected = np.array([1, 2, 3], dtype=smallest_int_dtype)
res = to_numeric(data, downcast=signed_downcast) tm.assert_numpy_array_equal(res, expected)
def test_ignore_downcast_neg_to_unsigned(): # Cannot cast to an unsigned integer # because we have a negative number. data = ["-1", 2, 3] expected = np.array([-1, 2, 3], dtype=np.int64)
res = to_numeric(data, downcast="unsigned") tm.assert_numpy_array_equal(res, expected)
# Warning in 32 bit platforms@pytest.mark.parametrize("downcast", ["integer", "signed", "unsigned"])@pytest.mark.parametrize( "data,expected", [ (["1.1", 2, 3], np.array([1.1, 2, 3], dtype=np.float64)), ( [10000.0, 20000, 3000, 40000.36, 50000, 50000.00], np.array( [10000.0, 20000, 3000, 40000.36, 50000, 50000.00], dtype=np.float64 ), ), ],)def test_ignore_downcast_cannot_convert_float(data, expected, downcast): # Cannot cast to an integer (signed or unsigned) # because we have a float number. res = to_numeric(data, downcast=downcast) tm.assert_numpy_array_equal(res, expected)
@pytest.mark.parametrize( "downcast,expected_dtype", [("integer", np.int16), ("signed", np.int16), ("unsigned", np.uint16)],)def test_downcast_not8bit(downcast, expected_dtype): # the smallest integer dtype need not be np.(u)int8 data = ["256", 257, 258]
expected = np.array([256, 257, 258], dtype=expected_dtype) res = to_numeric(data, downcast=downcast) tm.assert_numpy_array_equal(res, expected)
@pytest.mark.parametrize( "dtype,downcast,min_max", [ ("int8", "integer", [iinfo(np.int8).min, iinfo(np.int8).max]), ("int16", "integer", [iinfo(np.int16).min, iinfo(np.int16).max]), ("int32", "integer", [iinfo(np.int32).min, iinfo(np.int32).max]), ("int64", "integer", [iinfo(np.int64).min, iinfo(np.int64).max]), ("uint8", "unsigned", [iinfo(np.uint8).min, iinfo(np.uint8).max]), ("uint16", "unsigned", [iinfo(np.uint16).min, iinfo(np.uint16).max]), ("uint32", "unsigned", [iinfo(np.uint32).min, iinfo(np.uint32).max]), ("uint64", "unsigned", [iinfo(np.uint64).min, iinfo(np.uint64).max]), ("int16", "integer", [iinfo(np.int8).min, iinfo(np.int8).max + 1]), ("int32", "integer", [iinfo(np.int16).min, iinfo(np.int16).max + 1]), ("int64", "integer", [iinfo(np.int32).min, iinfo(np.int32).max + 1]), ("int16", "integer", [iinfo(np.int8).min - 1, iinfo(np.int16).max]), ("int32", "integer", [iinfo(np.int16).min - 1, iinfo(np.int32).max]), ("int64", "integer", [iinfo(np.int32).min - 1, iinfo(np.int64).max]), ("uint16", "unsigned", [iinfo(np.uint8).min, iinfo(np.uint8).max + 1]), ("uint32", "unsigned", [iinfo(np.uint16).min, iinfo(np.uint16).max + 1]), ("uint64", "unsigned", [iinfo(np.uint32).min, iinfo(np.uint32).max + 1]), ],)def test_downcast_limits(dtype, downcast, min_max): # see gh-14404: test the limits of each downcast. series = to_numeric(Series(min_max), downcast=downcast) assert series.dtype == dtype
def test_downcast_float64_to_float32(): # GH-43693: Check float64 preservation when >= 16,777,217 series = Series([16777217.0, np.finfo(np.float64).max, np.nan], dtype=np.float64) result = to_numeric(series, downcast="float")
assert series.dtype == result.dtype
def test_downcast_uint64(): # see gh-14422: # BUG: to_numeric doesn't work uint64 numbers ser = Series([0, 9223372036854775808]) result = to_numeric(ser, downcast="unsigned") expected = Series([0, 9223372036854775808], dtype=np.uint64) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "data,exp_data", [ ( [200, 300, "", "NaN", 30000000000000000000], [200, 300, np.nan, np.nan, 30000000000000000000], ), ( ["12345678901234567890", "1234567890", "ITEM"], [12345678901234567890, 1234567890, np.nan], ), ],)def test_coerce_uint64_conflict(data, exp_data): # see gh-17007 and gh-17125 # # Still returns float despite the uint64-nan conflict, # which would normally force the casting to object. result = to_numeric(Series(data), errors="coerce") expected = Series(exp_data, dtype=float) tm.assert_series_equal(result, expected)
def test_non_coerce_uint64_conflict(): # see gh-17007 and gh-17125 # # For completeness. ser = Series(["12345678901234567890", "1234567890", "ITEM"])
with pytest.raises(ValueError, match="Unable to parse string"): to_numeric(ser, errors="raise")
@pytest.mark.parametrize("dc1", ["integer", "float", "unsigned"])@pytest.mark.parametrize("dc2", ["integer", "float", "unsigned"])def test_downcast_empty(dc1, dc2): # GH32493
tm.assert_numpy_array_equal( to_numeric([], downcast=dc1), to_numeric([], downcast=dc2), check_dtype=False, )
def test_failure_to_convert_uint64_string_to_NaN(): # GH 32394 result = to_numeric("uint64", errors="coerce") assert np.isnan(result)
ser = Series([32, 64, np.nan]) result = to_numeric(Series(["32", "64", "uint64"]), errors="coerce") tm.assert_series_equal(result, ser)
@pytest.mark.parametrize( "strrep", [ "243.164", "245.968", "249.585", "259.745", "265.742", "272.567", "279.196", "280.366", "275.034", "271.351", "272.889", "270.627", "280.828", "290.383", "308.153", "319.945", "336.0", "344.09", "351.385", "356.178", "359.82", "361.03", "367.701", "380.812", "387.98", "391.749", "391.171", "385.97", "385.345", "386.121", "390.996", "399.734", "413.073", "421.532", "430.221", "437.092", "439.746", "446.01", "451.191", "460.463", "469.779", "472.025", "479.49", "474.864", "467.54", "471.978", ],)def test_precision_float_conversion(strrep): # GH 31364 result = to_numeric(strrep)
assert result == float(strrep)
@pytest.mark.parametrize( "values, expected", [ (["1", "2", None], Series([1, 2, pd.NA], dtype="Int64")), (["1", "2", "3"], Series([1, 2, 3], dtype="Int64")), (["1", "2", 3], Series([1, 2, 3], dtype="Int64")), (["1", "2", 3.5], Series([1, 2, 3.5], dtype="Float64")), (["1", None, 3.5], Series([1, pd.NA, 3.5], dtype="Float64")), (["1", "2", "3.5"], Series([1, 2, 3.5], dtype="Float64")), ],)def test_to_numeric_from_nullable_string(values, nullable_string_dtype, expected): # https://github.com/pandas-dev/pandas/issues/37262 s = Series(values, dtype=nullable_string_dtype) result = to_numeric(s) tm.assert_series_equal(result, expected)
def test_to_numeric_from_nullable_string_coerce(nullable_string_dtype): # GH#52146 values = ["a", "1"] ser = Series(values, dtype=nullable_string_dtype) result = to_numeric(ser, errors="coerce") expected = Series([pd.NA, 1], dtype="Int64") tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "data, input_dtype, downcast, expected_dtype", ( ([1, 1], "Int64", "integer", "Int8"), ([1.0, pd.NA], "Float64", "integer", "Int8"), ([1.0, 1.1], "Float64", "integer", "Float64"), ([1, pd.NA], "Int64", "integer", "Int8"), ([450, 300], "Int64", "integer", "Int16"), ([1, 1], "Float64", "integer", "Int8"), ([np.iinfo(np.int64).max - 1, 1], "Int64", "integer", "Int64"), ([1, 1], "Int64", "signed", "Int8"), ([1.0, 1.0], "Float32", "signed", "Int8"), ([1.0, 1.1], "Float64", "signed", "Float64"), ([1, pd.NA], "Int64", "signed", "Int8"), ([450, -300], "Int64", "signed", "Int16"), ([np.iinfo(np.uint64).max - 1, 1], "UInt64", "signed", "UInt64"), ([1, 1], "Int64", "unsigned", "UInt8"), ([1.0, 1.0], "Float32", "unsigned", "UInt8"), ([1.0, 1.1], "Float64", "unsigned", "Float64"), ([1, pd.NA], "Int64", "unsigned", "UInt8"), ([450, -300], "Int64", "unsigned", "Int64"), ([-1, -1], "Int32", "unsigned", "Int32"), ([1, 1], "Float64", "float", "Float32"), ([1, 1.1], "Float64", "float", "Float32"), ([1, 1], "Float32", "float", "Float32"), ([1, 1.1], "Float32", "float", "Float32"), ),)def test_downcast_nullable_numeric(data, input_dtype, downcast, expected_dtype): arr = pd.array(data, dtype=input_dtype) result = to_numeric(arr, downcast=downcast) expected = pd.array(data, dtype=expected_dtype) tm.assert_extension_array_equal(result, expected)
def test_downcast_nullable_mask_is_copied(): # GH38974
arr = pd.array([1, 2, pd.NA], dtype="Int64")
result = to_numeric(arr, downcast="integer") expected = pd.array([1, 2, pd.NA], dtype="Int8") tm.assert_extension_array_equal(result, expected)
arr[1] = pd.NA # should not modify result tm.assert_extension_array_equal(result, expected)
def test_to_numeric_scientific_notation(): # GH 15898 result = to_numeric("1.7e+308") expected = np.float64(1.7e308) assert result == expected
@pytest.mark.parametrize("val", [9876543210.0, 2.0**128])def test_to_numeric_large_float_not_downcast_to_float_32(val): # GH 19729 expected = Series([val]) result = to_numeric(expected, downcast="float") tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "val, dtype", [(1, "Int64"), (1.5, "Float64"), (True, "boolean")])def test_to_numeric_dtype_backend(val, dtype): # GH#50505 ser = Series([val], dtype=object) result = to_numeric(ser, dtype_backend="numpy_nullable") expected = Series([val], dtype=dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "val, dtype", [ (1, "Int64"), (1.5, "Float64"), (True, "boolean"), (1, "int64[pyarrow]"), (1.5, "float64[pyarrow]"), (True, "bool[pyarrow]"), ],)def test_to_numeric_dtype_backend_na(val, dtype): # GH#50505 if "pyarrow" in dtype: pytest.importorskip("pyarrow") dtype_backend = "pyarrow" else: dtype_backend = "numpy_nullable" ser = Series([val, None], dtype=object) result = to_numeric(ser, dtype_backend=dtype_backend) expected = Series([val, pd.NA], dtype=dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "val, dtype, downcast", [ (1, "Int8", "integer"), (1.5, "Float32", "float"), (1, "Int8", "signed"), (1, "int8[pyarrow]", "integer"), (1.5, "float[pyarrow]", "float"), (1, "int8[pyarrow]", "signed"), ],)def test_to_numeric_dtype_backend_downcasting(val, dtype, downcast): # GH#50505 if "pyarrow" in dtype: pytest.importorskip("pyarrow") dtype_backend = "pyarrow" else: dtype_backend = "numpy_nullable" ser = Series([val, None], dtype=object) result = to_numeric(ser, dtype_backend=dtype_backend, downcast=downcast) expected = Series([val, pd.NA], dtype=dtype) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "smaller, dtype_backend", [["UInt8", "numpy_nullable"], ["uint8[pyarrow]", "pyarrow"]],)def test_to_numeric_dtype_backend_downcasting_uint(smaller, dtype_backend): # GH#50505 if dtype_backend == "pyarrow": pytest.importorskip("pyarrow") ser = Series([1, pd.NA], dtype="UInt64") result = to_numeric(ser, dtype_backend=dtype_backend, downcast="unsigned") expected = Series([1, pd.NA], dtype=smaller) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "dtype", [ "Int64", "UInt64", "Float64", "boolean", "int64[pyarrow]", "uint64[pyarrow]", "float64[pyarrow]", "bool[pyarrow]", ],)def test_to_numeric_dtype_backend_already_nullable(dtype): # GH#50505 if "pyarrow" in dtype: pytest.importorskip("pyarrow") ser = Series([1, pd.NA], dtype=dtype) result = to_numeric(ser, dtype_backend="numpy_nullable") expected = Series([1, pd.NA], dtype=dtype) tm.assert_series_equal(result, expected)
def test_to_numeric_dtype_backend_error(dtype_backend): # GH#50505 ser = Series(["a", "b", ""]) expected = ser.copy() with pytest.raises(ValueError, match="Unable to parse string"): to_numeric(ser, dtype_backend=dtype_backend)
result = to_numeric(ser, dtype_backend=dtype_backend, errors="coerce") if dtype_backend == "pyarrow": dtype = "double[pyarrow]" else: dtype = "Float64" expected = Series([pd.NA, pd.NA, pd.NA], dtype=dtype) tm.assert_series_equal(result, expected)
def test_invalid_dtype_backend(): ser = Series([1, 2, 3]) msg = ( "dtype_backend numpy is invalid, only 'numpy_nullable' and " "'pyarrow' are allowed." ) with pytest.raises(ValueError, match=msg): to_numeric(ser, dtype_backend="numpy")
def test_coerce_pyarrow_backend(): # GH 52588 pa = pytest.importorskip("pyarrow") ser = Series(list("12x"), dtype=ArrowDtype(pa.string())) result = to_numeric(ser, errors="coerce", dtype_backend="pyarrow") expected = Series([1, 2, None], dtype=ArrowDtype(pa.int64())) tm.assert_series_equal(result, expected)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364from datetime import timeimport locale
import numpy as npimport pytest
from pandas import Seriesimport pandas._testing as tmfrom pandas.core.tools.times import to_time
# The tests marked with this are locale-dependent.# They pass, except when the machine locale is zh_CN or it_IT.fails_on_non_english = pytest.mark.xfail( locale.getlocale()[0] in ("zh_CN", "it_IT"), reason="fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8", strict=False,)
class TestToTime: @pytest.mark.parametrize( "time_string", [ "14:15", "1415", pytest.param("2:15pm", marks=fails_on_non_english), pytest.param("0215pm", marks=fails_on_non_english), "14:15:00", "141500", pytest.param("2:15:00pm", marks=fails_on_non_english), pytest.param("021500pm", marks=fails_on_non_english), time(14, 15), ], ) def test_parsers_time(self, time_string): # GH#11818 assert to_time(time_string) == time(14, 15)
def test_odd_format(self): new_string = "14.15" assert to_time(new_string, format="%H.%M") == time(14, 15)
def test_arraylike(self): arg = ["14:15", "20:20"] expected_arr = [time(14, 15), time(20, 20)] assert to_time(arg) == expected_arr assert to_time(arg, format="%H:%M") == expected_arr assert to_time(arg, infer_time_format=True) == expected_arr assert to_time(arg, format="%I:%M%p", errors="coerce") == [None, None]
with pytest.raises(ValueError, match="errors must be"): to_time(arg, format="%I:%M%p", errors="ignore")
msg = "Cannot convert.+to a time with given format" with pytest.raises(ValueError, match=msg): to_time(arg, format="%I:%M%p", errors="raise")
tm.assert_series_equal( to_time(Series(arg, name="test")), Series(expected_arr, name="test") )
res = to_time(np.array(arg)) assert isinstance(res, list) assert res == expected_arr123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389from datetime import ( time, timedelta,)
import numpy as npimport pytest
from pandas.compat import ( IS64, WASM,)from pandas.errors import ( OutOfBoundsTimedelta, Pandas4Warning,)
import pandas as pdfrom pandas import ( Series, TimedeltaIndex, isna, to_timedelta,)import pandas._testing as tmfrom pandas.core.arrays import TimedeltaArray
class TestTimedeltas: def test_to_timedelta_mixed_unit_strings(self): # https://github.com/pandas-dev/pandas/pull/63196#issuecomment-3595743721 result = to_timedelta(["1 days 06:05:01.00003", "15.5us"])
expected = TimedeltaIndex([108_301_000_030_000, 15_500], dtype="m8[ns]") tm.assert_index_equal(result, expected)
def test_to_timedelta_all_nat_unit(self): # With all-NaT entries, we get "s" unit result = to_timedelta([None]) assert result.unit == "s"
result = TimedeltaIndex([None]) assert result.unit == "s"
def test_to_timedelta_month_raises(self): obj = np.timedelta64(1, "M")
msg = "Unit M is not supported." with pytest.raises(ValueError, match=msg): to_timedelta(obj) with pytest.raises(ValueError, match=msg): pd.Timedelta(obj) with pytest.raises(ValueError, match=msg): to_timedelta([obj]) with pytest.raises(ValueError, match=msg): TimedeltaIndex([obj])
def test_to_timedelta_none(self): # GH#23055 assert to_timedelta(None) is pd.NaT
def test_to_timedelta_dt64_raises(self): # Passing datetime64-dtype data to TimedeltaIndex is no longer # supported GH#29794 msg = r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]"
ser = Series([pd.NaT], dtype="M8[ns]") with pytest.raises(TypeError, match=msg): to_timedelta(ser) with pytest.raises(TypeError, match=msg): ser.to_frame().apply(to_timedelta)
def test_to_timedelta_readonly(self, writable): # GH#34857 arr = np.array([], dtype=object) arr.setflags(write=writable) result = to_timedelta(arr) expected = to_timedelta([]) tm.assert_index_equal(result, expected)
def test_to_timedelta_null(self): result = to_timedelta(["", ""]) assert isna(result).all()
def test_to_timedelta_same_np_timedelta64(self): # pass thru result = to_timedelta(np.array([np.timedelta64(1, "s")])) expected = pd.Index(np.array([np.timedelta64(1, "s")])) tm.assert_index_equal(result, expected)
def test_to_timedelta_series(self): # Series expected = Series( [timedelta(days=1), timedelta(days=1, seconds=1)], dtype="m8[us]" )
msg = "'d' is deprecated and will be removed in a future version." with tm.assert_produces_warning(Pandas4Warning, match=msg): result = to_timedelta(Series(["1d", "1days 00:00:01"])) tm.assert_series_equal(result, expected)
def test_to_timedelta_units(self): # with units result = TimedeltaIndex( [np.timedelta64(0, "ns"), np.timedelta64(10, "s").astype("m8[ns]")] ) expected = to_timedelta([0, 10], unit="s").as_unit("ns") tm.assert_index_equal(result, expected)
def test_to_timedelta_mixed_dtype(self): # https://github.com/pandas-dev/pandas/issues/64044 result = to_timedelta(np.array([0.5, 2]), unit="m") expected = TimedeltaIndex( ["0 days 00:00:30", "0 days 00:02:00"], dtype="timedelta64[ns]", freq=None ) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "dtype, unit", [ ["int64", "s"], ["int64", "m"], ["int64", "h"], ["timedelta64[s]", "s"], ["timedelta64[D]", "D"], ], ) def test_to_timedelta_units_dtypes(self, dtype, unit): # arrays of various dtypes arr = np.array([1] * 5, dtype=dtype) result = to_timedelta(arr, unit=unit) exp_dtype = "m8[s]" expected = TimedeltaIndex([np.timedelta64(1, unit)] * 5, dtype=exp_dtype) tm.assert_index_equal(result, expected)
def test_to_timedelta_oob_non_nano(self): arr = np.array([pd.NaT._value + 1], dtype="timedelta64[m]")
msg = ( "Cannot convert -9223372036854775807 minutes to " r"timedelta64\[s\] without overflow" ) with pytest.raises(OutOfBoundsTimedelta, match=msg): to_timedelta(arr)
with pytest.raises(OutOfBoundsTimedelta, match=msg): TimedeltaIndex(arr)
with pytest.raises(OutOfBoundsTimedelta, match=msg): TimedeltaArray._from_sequence(arr, dtype="m8[s]")
@pytest.mark.parametrize("box", [lambda x: x, pd.DataFrame]) @pytest.mark.parametrize("errors", ["raise", "coerce"]) def test_to_timedelta_dataframe(self, box, errors): # GH 11776 arg = box(np.arange(10).reshape(2, 5)) with pytest.raises(TypeError, match="1-d array"): to_timedelta(arg, errors=errors)
def test_to_timedelta_invalid_errors(self): # bad value for errors parameter msg = "errors must be one of" with pytest.raises(ValueError, match=msg): to_timedelta(["foo"], errors="never")
@pytest.mark.parametrize("arg", [[1, 2], 1]) def test_to_timedelta_invalid_unit(self, arg): # these will error msg = "invalid unit abbreviation: foo" with pytest.raises(ValueError, match=msg): to_timedelta(arg, unit="foo")
def test_to_timedelta_time(self): # time not supported ATM msg = ( "Value must be Timedelta, string, integer, float, timedelta or convertible" ) with pytest.raises(ValueError, match=msg): to_timedelta(time(second=1)) assert to_timedelta(time(second=1), errors="coerce") is pd.NaT
def test_to_timedelta_bad_value(self): msg = "Could not convert 'foo' to NumPy timedelta" with pytest.raises(ValueError, match=msg): to_timedelta(["foo", "bar"])
def test_to_timedelta_bad_value_coerce(self): tm.assert_index_equal( TimedeltaIndex([pd.NaT, pd.NaT]), to_timedelta(["foo", "bar"], errors="coerce"), )
tm.assert_index_equal( TimedeltaIndex(["1 day", pd.NaT, "1 min"]), to_timedelta(["1 day", "bar", "1 min"], errors="coerce"), )
@pytest.mark.parametrize( "val, errors", [ ("1M", True), ("1 M", True), ("1Y", True), ("1 Y", True), ("1y", True), ("1 y", True), ("1m", False), ("1 m", False), ("1 day", False), ("2day", False), ], ) def test_unambiguous_timedelta_values(self, val, errors): # GH36666 Deprecate use of strings denoting units with 'M', 'Y', 'm' or 'y' # in pd.to_timedelta msg = "Units 'M', 'Y' and 'y' do not represent unambiguous timedelta" if errors: with pytest.raises(ValueError, match=msg): to_timedelta(val) else: # check it doesn't raise to_timedelta(val)
def test_to_timedelta_via_apply(self): # GH 5458 expected = Series([np.timedelta64(1, "s")], dtype="m8[us]") result = Series(["00:00:01"]).apply(to_timedelta) tm.assert_series_equal(result, expected)
result = Series([to_timedelta("00:00:01")]) tm.assert_series_equal(result, expected)
def test_to_timedelta_inference_without_warning(self): # GH#41731 inference produces a warning in the Series constructor, # but _not_ in to_timedelta vals = ["00:00:01", pd.NaT] with tm.assert_produces_warning(None): result = to_timedelta(vals)
expected = TimedeltaIndex([pd.Timedelta(seconds=1), pd.NaT], dtype="m8[us]") tm.assert_index_equal(result, expected)
def test_to_timedelta_on_missing_values(self): # GH5438 timedelta_NaT = np.timedelta64("NaT", "ns")
actual = to_timedelta(Series(["00:00:01", np.nan])) expected = Series( [np.timedelta64(1000000000, "ns"), timedelta_NaT], dtype=f"{tm.ENDIAN}m8[us]", ) tm.assert_series_equal(actual, expected)
ser = Series(["00:00:01", pd.NaT], dtype="m8[us]") actual = to_timedelta(ser) tm.assert_series_equal(actual, expected)
@pytest.mark.parametrize("val", [np.nan, pd.NaT, pd.NA]) def test_to_timedelta_on_missing_values_scalar(self, val): actual = to_timedelta(val) assert actual._value == np.timedelta64("NaT", "ns").astype("int64")
@pytest.mark.parametrize("val", [np.nan, pd.NaT, pd.NA]) def test_to_timedelta_on_missing_values_list(self, val): actual = to_timedelta([val]) assert actual[0]._value == np.timedelta64("NaT", "ns").astype("int64")
@pytest.mark.skipif(WASM, reason="No fp exception support in WASM") @pytest.mark.xfail(not IS64, reason="Floating point error") def test_to_timedelta_float(self): # https://github.com/pandas-dev/pandas/issues/25077 arr = np.arange(0, 1, 1e-6)[-10:] result = to_timedelta(arr, unit="s") expected_asi8 = np.arange(999990000, 10**9, 1000, dtype="int64") tm.assert_numpy_array_equal(result.asi8, expected_asi8)
def test_to_timedelta_coerce_strings_unit(self): arr = np.array([1, 2, "error"], dtype=object) result = to_timedelta(arr, unit="ns", errors="coerce") expected = to_timedelta([1, 2, pd.NaT], unit="ns") tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "expected_val, result_val", [[timedelta(days=2), 2], [None, None]] ) def test_to_timedelta_nullable_int64_dtype(self, expected_val, result_val): # GH 35574 expected = Series([timedelta(days=1), expected_val], dtype="m8[s]") result = to_timedelta(Series([1, result_val], dtype="Int64"), unit="days")
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( ("input", "expected"), [ ("8:53:08.71800000001", "8:53:08.718"), ("8:53:08.718001", "8:53:08.718001"), ("8:53:08.7180000001", "8:53:08.7180000001"), ("-8:53:08.71800000001", "-8:53:08.718"), ("8:53:08.7180000089", "8:53:08.718000008"), ], ) @pytest.mark.parametrize("func", [pd.Timedelta, to_timedelta]) def test_to_timedelta_precision_over_nanos(self, input, expected, func): # GH: 36738 expected = pd.Timedelta(expected) result = func(input) assert result == expected
def test_to_timedelta_zerodim(self, fixed_now_ts): # ndarray.item() incorrectly returns int for dt64[ns] and td64[ns] dt64 = fixed_now_ts.to_datetime64() arg = np.array(dt64)
msg = ( "Value must be Timedelta, string, integer, float, timedelta " "or convertible, not datetime64" ) with pytest.raises(ValueError, match=msg): to_timedelta(arg)
arg2 = arg.view("m8[ns]") result = to_timedelta(arg2) assert isinstance(result, pd.Timedelta) assert result._value == dt64.view("i8")
def test_to_timedelta_numeric_ea(self, any_numeric_ea_dtype): # GH#48796 ser = Series([1, pd.NA], dtype=any_numeric_ea_dtype) result = to_timedelta(ser) expected = Series([pd.Timedelta(1, unit="ns"), pd.NaT]) tm.assert_series_equal(result, expected)
def test_to_timedelta_fraction(self): result = to_timedelta(1.0 / 3, unit="h") expected = pd.Timedelta("0 days 00:19:59.999999998") assert result == expected
def test_to_timedelta_unit_round_floats(self): # When the float is round, we give the requested unit # (or nearest-supported) like we do with integers arr = np.array([45.0], dtype=object) result = to_timedelta(arr, unit="s") expected = to_timedelta([45], unit="s") tm.assert_index_equal(result, expected)
arr2 = arr.astype(np.float64) result2 = to_timedelta(arr2, unit="s") tm.assert_index_equal(result2, expected)
def test_to_timedelta_unit_non_round_floats(self): # With non-round floats, we have to give nanosecond arr = np.array([45.5], dtype=object) result = to_timedelta(arr, unit="s") assert result.unit == "ns"
arr2 = arr.astype(np.float64) result2 = to_timedelta(arr2, unit="s") assert result2.unit == "ns"
def test_to_timedelta_unit_mixed_round_and_non_round_floats(self): # GH#65150 - round floats mixed with non-round floats should # respect the unit for all values expected = to_timedelta(["0 days 00:00:01", "0 days 00:00:01.01"]).as_unit("ns")
result = to_timedelta([1.0, 1.01], unit="s") tm.assert_index_equal(result, expected)
# Also test integers mixed with non-round floats result2 = to_timedelta([1, 1.01], unit="s") tm.assert_index_equal(result2, expected)
def test_from_numeric_arrow_dtype(any_numeric_ea_dtype): # GH 52425 pytest.importorskip("pyarrow") ser = Series([1, 2], dtype=f"{any_numeric_ea_dtype.lower()}[pyarrow]") result = to_timedelta(ser) expected = Series([1, 2], dtype="timedelta64[ns]") tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("unit", ["ns", "ms"])def test_from_timedelta_arrow_dtype(unit): # GH 54298 pytest.importorskip("pyarrow") expected = Series([timedelta(1)], dtype=f"duration[{unit}][pyarrow]") result = to_timedelta(expected) tm.assert_series_equal(result, expected).gitattributes+45
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/INSTALLERAdded+1
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/LICENSEAdded+1060
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/METADATAAdded+1383
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/RECORDAdded
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/REQUESTEDAdded
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/WHEELAdded+6
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/entry_points.txtAdded+3
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_formats.pyAdded+592
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_iteration.pyAdded+33
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_logical_ops.pyAdded+510
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_missing.pyAdded+88
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_npfuncs.pyAdded+52
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_reductions.pyAdded+233
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_subclass.pyAdded+82
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_ufunc.pyAdded+475
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_unary.pyAdded+50
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_validate.pyAdded+26
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/__init__.pyAdded+23
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/conftest.pyAdded+132
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_api.pyAdded+216
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_case_justify.pyAdded+423
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_cat.pyAdded+444
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_extract.pyAdded+784
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_find_replace.pyAdded+1730
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_get_dummies.pyAdded+102
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_split_partition.pyAdded+772
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_string_array.pyAdded+126
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_strings.pyAdded+952
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_aggregation.pyAdded+93
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_algos.pyAdded+2083
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_col.pyAdded+392
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_common.pyAdded+273
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_downstream.pyAdded+299
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_errors.pyAdded+144
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_expressions.pyAdded+475
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_flags.pyAdded+48
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_multilevel.pyAdded+376
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_nanops.pyAdded+1333
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_optional_dependency.pyAdded+100
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_register_accessor.pyAdded+123
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_sorting.pyAdded+475
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_take.pyAdded+317
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/__init__.pyAdded
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_datetime.pyAdded
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_numeric.pyAdded+904
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_time.pyAdded+64
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_timedelta.pyAdded+389
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tseries/__init__.pyAdded
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tseries/frequencies/__init__.pyAdded