couto commited on
Commit
98f2eaa
·
verified ·
1 Parent(s): df5cd20

Upload folder using huggingface_hub (part 11)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +45 -0
  2. couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/INSTALLER +1 -0
  3. couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/LICENSE +1060 -0
  4. couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/METADATA +1383 -0
  5. couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/RECORD +0 -0
  6. couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/REQUESTED +0 -0
  7. couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/WHEEL +6 -0
  8. couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/entry_points.txt +3 -0
  9. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_formats.py +592 -0
  10. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_iteration.py +33 -0
  11. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_logical_ops.py +510 -0
  12. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_missing.py +88 -0
  13. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_npfuncs.py +52 -0
  14. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_reductions.py +233 -0
  15. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_subclass.py +82 -0
  16. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_ufunc.py +475 -0
  17. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_unary.py +50 -0
  18. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_validate.py +26 -0
  19. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/__init__.py +23 -0
  20. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/conftest.py +132 -0
  21. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_api.py +216 -0
  22. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_case_justify.py +423 -0
  23. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_cat.py +444 -0
  24. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_extract.py +784 -0
  25. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_find_replace.py +1730 -0
  26. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_get_dummies.py +102 -0
  27. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_split_partition.py +772 -0
  28. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_string_array.py +126 -0
  29. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_strings.py +952 -0
  30. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_aggregation.py +93 -0
  31. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_algos.py +2083 -0
  32. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_col.py +392 -0
  33. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_common.py +273 -0
  34. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_downstream.py +299 -0
  35. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_errors.py +144 -0
  36. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_expressions.py +475 -0
  37. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_flags.py +48 -0
  38. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_multilevel.py +376 -0
  39. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_nanops.py +1333 -0
  40. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_optional_dependency.py +100 -0
  41. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_register_accessor.py +123 -0
  42. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_sorting.py +475 -0
  43. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_take.py +317 -0
  44. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/__init__.py +0 -0
  45. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_datetime.py +0 -0
  46. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_numeric.py +904 -0
  47. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_time.py +64 -0
  48. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_timedelta.py +389 -0
  49. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tseries/__init__.py +0 -0
  50. couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tseries/frequencies/__init__.py +0 -0
.gitattributes CHANGED
@@ -130,3 +130,48 @@ couto/12yd/.venv/lib/python3.12/site-packages/pandas/core/window/__pycache__/rol
130
  couto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
131
  couto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
132
  couto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  couto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/pytables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
131
  couto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/sql.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
132
  couto/12yd/.venv/lib/python3.12/site-packages/pandas/io/__pycache__/stata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
133
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libavif-a883386a.so.16.4.1 filter=lfs diff=lfs merge=lfs -text
134
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libbrotlicommon-785b7a00.so.1.2.0 filter=lfs diff=lfs merge=lfs -text
135
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libfreetype-d2d71ad9.so.6.20.6 filter=lfs diff=lfs merge=lfs -text
136
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libharfbuzz-ef65cc8a.so.0.61321.0 filter=lfs diff=lfs merge=lfs -text
137
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libjpeg-8296d2fa.so.62.4.0 filter=lfs diff=lfs merge=lfs -text
138
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/liblcms2-545f6561.so.2.0.18 filter=lfs diff=lfs merge=lfs -text
139
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/liblzma-3c942967.so.5.8.3 filter=lfs diff=lfs merge=lfs -text
140
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libopenjp2-f3576751.so.2.5.4 filter=lfs diff=lfs merge=lfs -text
141
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libpng16-65c953c0.so.16.56.0 filter=lfs diff=lfs merge=lfs -text
142
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libtiff-f4bc73ff.so.6.2.0 filter=lfs diff=lfs merge=lfs -text
143
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libwebp-67ee3789.so.7.2.0 filter=lfs diff=lfs merge=lfs -text
144
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libxcb-bac6ebc8.so.1.1.0 filter=lfs diff=lfs merge=lfs -text
145
+ couto/12yd/.venv/lib/python3.12/site-packages/pillow.libs/libzstd-6ea785c0.so.1.5.7 filter=lfs diff=lfs merge=lfs -text
146
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_acero.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
147
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_azurefs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
148
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_compute.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
149
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_csv.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
150
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_dataset.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
151
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_dataset_parquet.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
152
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_dataset_parquet_encryption.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
153
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_feather.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
154
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_flight.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
155
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_fs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
156
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_gcsfs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
157
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_hdfs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
158
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_json.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
159
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_orc.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
160
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_parquet.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
161
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_parquet_encryption.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
162
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_s3fs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
163
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/_substrait.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
164
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/lib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
165
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow.so.2400 filter=lfs diff=lfs merge=lfs -text
166
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_acero.so.2400 filter=lfs diff=lfs merge=lfs -text
167
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_compute.so.2400 filter=lfs diff=lfs merge=lfs -text
168
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_dataset.so.2400 filter=lfs diff=lfs merge=lfs -text
169
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_flight.so.2400 filter=lfs diff=lfs merge=lfs -text
170
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python.so filter=lfs diff=lfs merge=lfs -text
171
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python.so.2400 filter=lfs diff=lfs merge=lfs -text
172
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python.so.2400.0.0 filter=lfs diff=lfs merge=lfs -text
173
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python_flight.so filter=lfs diff=lfs merge=lfs -text
174
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python_flight.so.2400 filter=lfs diff=lfs merge=lfs -text
175
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_python_flight.so.2400.0.0 filter=lfs diff=lfs merge=lfs -text
176
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libarrow_substrait.so.2400 filter=lfs diff=lfs merge=lfs -text
177
+ couto/12yd/.venv/lib/python3.12/site-packages/pyarrow/libparquet.so.2400 filter=lfs diff=lfs merge=lfs -text
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/LICENSE ADDED
@@ -0,0 +1,1060 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team
4
+ All rights reserved.
5
+
6
+ Copyright (c) 2011-2026, Open source contributors.
7
+
8
+ Redistribution and use in source and binary forms, with or without
9
+ modification, are permitted provided that the following conditions are met:
10
+
11
+ * Redistributions of source code must retain the above copyright notice, this
12
+ list of conditions and the following disclaimer.
13
+
14
+ * Redistributions in binary form must reproduce the above copyright notice,
15
+ this list of conditions and the following disclaimer in the documentation
16
+ and/or other materials provided with the distribution.
17
+
18
+ * Neither the name of the copyright holder nor the names of its
19
+ contributors may be used to endorse or promote products derived from
20
+ this software without specific prior written permission.
21
+
22
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
26
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
+ Copyright (c) 2010-2019 Keith Goodman
33
+ Copyright (c) 2019 Bottleneck Developers
34
+ All rights reserved.
35
+
36
+ Redistribution and use in source and binary forms, with or without
37
+ modification, are permitted provided that the following conditions are met:
38
+
39
+ * Redistributions of source code must retain the above copyright notice,
40
+ this list of conditions and the following disclaimer.
41
+
42
+ * Redistributions in binary form must reproduce the above copyright
43
+ notice, this list of conditions and the following disclaimer in the
44
+ documentation and/or other materials provided with the distribution.
45
+
46
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
47
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
50
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
51
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
52
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
53
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
54
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
56
+ POSSIBILITY OF SUCH DAMAGE.Copyright 2017- Paul Ganssle <paul@ganssle.io>
57
+ Copyright 2017- dateutil contributors (see AUTHORS file)
58
+
59
+ Licensed under the Apache License, Version 2.0 (the "License");
60
+ you may not use this file except in compliance with the License.
61
+ You may obtain a copy of the License at
62
+
63
+ http://www.apache.org/licenses/LICENSE-2.0
64
+
65
+ Unless required by applicable law or agreed to in writing, software
66
+ distributed under the License is distributed on an "AS IS" BASIS,
67
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
68
+ See the License for the specific language governing permissions and
69
+ limitations under the License.
70
+
71
+ The above license applies to all contributions after 2017-12-01, as well as
72
+ all contributions that have been re-licensed (see AUTHORS file for the list of
73
+ contributors who have re-licensed their code).
74
+ --------------------------------------------------------------------------------
75
+ dateutil - Extensions to the standard Python datetime module.
76
+
77
+ Copyright (c) 2003-2011 - Gustavo Niemeyer <gustavo@niemeyer.net>
78
+ Copyright (c) 2012-2014 - Tomi Pieviläinen <tomi.pievilainen@iki.fi>
79
+ Copyright (c) 2014-2016 - Yaron de Leeuw <me@jarondl.net>
80
+ Copyright (c) 2015- - Paul Ganssle <paul@ganssle.io>
81
+ Copyright (c) 2015- - dateutil contributors (see AUTHORS file)
82
+
83
+ All rights reserved.
84
+
85
+ Redistribution and use in source and binary forms, with or without
86
+ modification, are permitted provided that the following conditions are met:
87
+
88
+ * Redistributions of source code must retain the above copyright notice,
89
+ this list of conditions and the following disclaimer.
90
+ * Redistributions in binary form must reproduce the above copyright notice,
91
+ this list of conditions and the following disclaimer in the documentation
92
+ and/or other materials provided with the distribution.
93
+ * Neither the name of the copyright holder nor the names of its
94
+ contributors may be used to endorse or promote products derived from
95
+ this software without specific prior written permission.
96
+
97
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
98
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
99
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
100
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
101
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
102
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
103
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
104
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
105
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
106
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
107
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
108
+
109
+ The above BSD License Applies to all code, even that also covered by Apache 2.0.# MIT License
110
+
111
+ Copyright (c) 2019 Hadley Wickham; RStudio; and Evan Miller
112
+
113
+ Permission is hereby granted, free of charge, to any person obtaining a copy
114
+ of this software and associated documentation files (the "Software"), to deal
115
+ in the Software without restriction, including without limitation the rights
116
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
117
+ copies of the Software, and to permit persons to whom the Software is
118
+ furnished to do so, subject to the following conditions:
119
+
120
+ The above copyright notice and this permission notice shall be included in all
121
+ copies or substantial portions of the Software.
122
+
123
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
124
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
125
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
126
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
127
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
128
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
129
+ SOFTWARE.
130
+ Based on http://opensource.org/licenses/MIT
131
+
132
+ This is a template. Complete and ship as file LICENSE the following 2
133
+ lines (only)
134
+
135
+ YEAR:
136
+ COPYRIGHT HOLDER:
137
+
138
+ and specify as
139
+
140
+ License: MIT + file LICENSE
141
+
142
+ Copyright (c) <YEAR>, <COPYRIGHT HOLDER>
143
+
144
+ Permission is hereby granted, free of charge, to any person obtaining
145
+ a copy of this software and associated documentation files (the
146
+ "Software"), to deal in the Software without restriction, including
147
+ without limitation the rights to use, copy, modify, merge, publish,
148
+ distribute, sublicense, and/or sell copies of the Software, and to
149
+ permit persons to whom the Software is furnished to do so, subject to
150
+ the following conditions:
151
+
152
+ The above copyright notice and this permission notice shall be
153
+ included in all copies or substantial portions of the Software.
154
+
155
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
156
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
157
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
158
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
159
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
160
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
161
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
162
+ The MIT License
163
+
164
+ Copyright (c) 2008- Attractive Chaos <attractor@live.co.uk>
165
+
166
+ Permission is hereby granted, free of charge, to any person obtaining
167
+ a copy of this software and associated documentation files (the
168
+ "Software"), to deal in the Software without restriction, including
169
+ without limitation the rights to use, copy, modify, merge, publish,
170
+ distribute, sublicense, and/or sell copies of the Software, and to
171
+ permit persons to whom the Software is furnished to do so, subject to
172
+ the following conditions:
173
+
174
+ The above copyright notice and this permission notice shall be
175
+ included in all copies or substantial portions of the Software.
176
+
177
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
178
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
179
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
180
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
181
+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
182
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
183
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
184
+ SOFTWARE.musl as a whole is licensed under the following standard MIT license:
185
+
186
+ ----------------------------------------------------------------------
187
+ Copyright © 2005-2020 Rich Felker, et al.
188
+
189
+ Permission is hereby granted, free of charge, to any person obtaining
190
+ a copy of this software and associated documentation files (the
191
+ "Software"), to deal in the Software without restriction, including
192
+ without limitation the rights to use, copy, modify, merge, publish,
193
+ distribute, sublicense, and/or sell copies of the Software, and to
194
+ permit persons to whom the Software is furnished to do so, subject to
195
+ the following conditions:
196
+
197
+ The above copyright notice and this permission notice shall be
198
+ included in all copies or substantial portions of the Software.
199
+
200
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
201
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
202
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
203
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
204
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
205
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
206
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
207
+ ----------------------------------------------------------------------
208
+
209
+ Authors/contributors include:
210
+
211
+ A. Wilcox
212
+ Ada Worcester
213
+ Alex Dowad
214
+ Alex Suykov
215
+ Alexander Monakov
216
+ Andre McCurdy
217
+ Andrew Kelley
218
+ Anthony G. Basile
219
+ Aric Belsito
220
+ Arvid Picciani
221
+ Bartosz Brachaczek
222
+ Benjamin Peterson
223
+ Bobby Bingham
224
+ Boris Brezillon
225
+ Brent Cook
226
+ Chris Spiegel
227
+ Clément Vasseur
228
+ Daniel Micay
229
+ Daniel Sabogal
230
+ Daurnimator
231
+ David Carlier
232
+ David Edelsohn
233
+ Denys Vlasenko
234
+ Dmitry Ivanov
235
+ Dmitry V. Levin
236
+ Drew DeVault
237
+ Emil Renner Berthing
238
+ Fangrui Song
239
+ Felix Fietkau
240
+ Felix Janda
241
+ Gianluca Anzolin
242
+ Hauke Mehrtens
243
+ He X
244
+ Hiltjo Posthuma
245
+ Isaac Dunham
246
+ Jaydeep Patil
247
+ Jens Gustedt
248
+ Jeremy Huntwork
249
+ Jo-Philipp Wich
250
+ Joakim Sindholt
251
+ John Spencer
252
+ Julien Ramseier
253
+ Justin Cormack
254
+ Kaarle Ritvanen
255
+ Khem Raj
256
+ Kylie McClain
257
+ Leah Neukirchen
258
+ Luca Barbato
259
+ Luka Perkov
260
+ M Farkas-Dyck (Strake)
261
+ Mahesh Bodapati
262
+ Markus Wichmann
263
+ Masanori Ogino
264
+ Michael Clark
265
+ Michael Forney
266
+ Mikhail Kremnyov
267
+ Natanael Copa
268
+ Nicholas J. Kain
269
+ orc
270
+ Pascal Cuoq
271
+ Patrick Oppenlander
272
+ Petr Hosek
273
+ Petr Skocik
274
+ Pierre Carrier
275
+ Reini Urban
276
+ Rich Felker
277
+ Richard Pennington
278
+ Ryan Fairfax
279
+ Samuel Holland
280
+ Segev Finer
281
+ Shiz
282
+ sin
283
+ Solar Designer
284
+ Stefan Kristiansson
285
+ Stefan O'Rear
286
+ Szabolcs Nagy
287
+ Timo Teräs
288
+ Trutz Behn
289
+ Valentin Ochs
290
+ Will Dietz
291
+ William Haddon
292
+ William Pitcock
293
+
294
+ Portions of this software are derived from third-party works licensed
295
+ under terms compatible with the above MIT license:
296
+
297
+ The TRE regular expression implementation (src/regex/reg* and
298
+ src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed
299
+ under a 2-clause BSD license (license text in the source files). The
300
+ included version has been heavily modified by Rich Felker in 2012, in
301
+ the interests of size, simplicity, and namespace cleanliness.
302
+
303
+ Much of the math library code (src/math/* and src/complex/*) is
304
+ Copyright © 1993,2004 Sun Microsystems or
305
+ Copyright © 2003-2011 David Schultz or
306
+ Copyright © 2003-2009 Steven G. Kargl or
307
+ Copyright © 2003-2009 Bruce D. Evans or
308
+ Copyright © 2008 Stephen L. Moshier or
309
+ Copyright © 2017-2018 Arm Limited
310
+ and labelled as such in comments in the individual source files. All
311
+ have been licensed under extremely permissive terms.
312
+
313
+ The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008
314
+ The Android Open Source Project and is licensed under a two-clause BSD
315
+ license. It was taken from Bionic libc, used on Android.
316
+
317
+ The AArch64 memcpy and memset code (src/string/aarch64/*) are
318
+ Copyright © 1999-2019, Arm Limited.
319
+
320
+ The implementation of DES for crypt (src/crypt/crypt_des.c) is
321
+ Copyright © 1994 David Burren. It is licensed under a BSD license.
322
+
323
+ The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was
324
+ originally written by Solar Designer and placed into the public
325
+ domain. The code also comes with a fallback permissive license for use
326
+ in jurisdictions that may not recognize the public domain.
327
+
328
+ The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011
329
+ Valentin Ochs and is licensed under an MIT-style license.
330
+
331
+ The x86_64 port was written by Nicholas J. Kain and is licensed under
332
+ the standard MIT terms.
333
+
334
+ The mips and microblaze ports were originally written by Richard
335
+ Pennington for use in the ellcc project. The original code was adapted
336
+ by Rich Felker for build system and code conventions during upstream
337
+ integration. It is licensed under the standard MIT terms.
338
+
339
+ The mips64 port was contributed by Imagination Technologies and is
340
+ licensed under the standard MIT terms.
341
+
342
+ The powerpc port was also originally written by Richard Pennington,
343
+ and later supplemented and integrated by John Spencer. It is licensed
344
+ under the standard MIT terms.
345
+
346
+ All other files which have no copyright comments are original works
347
+ produced specifically for use as part of this library, written either
348
+ by Rich Felker, the main author of the library, or by one or more
349
+ contibutors listed above. Details on authorship of individual files
350
+ can be found in the git version control history of the project. The
351
+ omission of copyright and license comments in each file is in the
352
+ interest of source tree size.
353
+
354
+ In addition, permission is hereby granted for all public header files
355
+ (include/* and arch/*/bits/*) and crt files intended to be linked into
356
+ applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit
357
+ the copyright notice and permission notice otherwise required by the
358
+ license, and to use these files without any requirement of
359
+ attribution. These files include substantial contributions from:
360
+
361
+ Bobby Bingham
362
+ John Spencer
363
+ Nicholas J. Kain
364
+ Rich Felker
365
+ Richard Pennington
366
+ Stefan Kristiansson
367
+ Szabolcs Nagy
368
+
369
+ all of whom have explicitly granted such permission.
370
+
371
+ This file previously contained text expressing a belief that most of
372
+ the files covered by the above exception were sufficiently trivial not
373
+ to be subject to copyright, resulting in confusion over whether it
374
+ negated the permissions granted in the license. In the spirit of
375
+ permissive licensing, and of not having licensing issues being an
376
+ obstacle to adoption, that text has been removed.Copyright (c) 2005-2023, NumPy Developers.
377
+ All rights reserved.
378
+
379
+ Redistribution and use in source and binary forms, with or without
380
+ modification, are permitted provided that the following conditions are
381
+ met:
382
+
383
+ * Redistributions of source code must retain the above copyright
384
+ notice, this list of conditions and the following disclaimer.
385
+
386
+ * Redistributions in binary form must reproduce the above
387
+ copyright notice, this list of conditions and the following
388
+ disclaimer in the documentation and/or other materials provided
389
+ with the distribution.
390
+
391
+ * Neither the name of the NumPy Developers nor the names of any
392
+ contributors may be used to endorse or promote products derived
393
+ from this software without specific prior written permission.
394
+
395
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
396
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
397
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
398
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
399
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
400
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
401
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
402
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
403
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
404
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
405
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
406
+ Apache License
407
+ Version 2.0, January 2004
408
+ http://www.apache.org/licenses/
409
+
410
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
411
+
412
+ 1. Definitions.
413
+
414
+ "License" shall mean the terms and conditions for use, reproduction,
415
+ and distribution as defined by Sections 1 through 9 of this document.
416
+
417
+ "Licensor" shall mean the copyright owner or entity authorized by
418
+ the copyright owner that is granting the License.
419
+
420
+ "Legal Entity" shall mean the union of the acting entity and all
421
+ other entities that control, are controlled by, or are under common
422
+ control with that entity. For the purposes of this definition,
423
+ "control" means (i) the power, direct or indirect, to cause the
424
+ direction or management of such entity, whether by contract or
425
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
426
+ outstanding shares, or (iii) beneficial ownership of such entity.
427
+
428
+ "You" (or "Your") shall mean an individual or Legal Entity
429
+ exercising permissions granted by this License.
430
+
431
+ "Source" form shall mean the preferred form for making modifications,
432
+ including but not limited to software source code, documentation
433
+ source, and configuration files.
434
+
435
+ "Object" form shall mean any form resulting from mechanical
436
+ transformation or translation of a Source form, including but
437
+ not limited to compiled object code, generated documentation,
438
+ and conversions to other media types.
439
+
440
+ "Work" shall mean the work of authorship, whether in Source or
441
+ Object form, made available under the License, as indicated by a
442
+ copyright notice that is included in or attached to the work
443
+ (an example is provided in the Appendix below).
444
+
445
+ "Derivative Works" shall mean any work, whether in Source or Object
446
+ form, that is based on (or derived from) the Work and for which the
447
+ editorial revisions, annotations, elaborations, or other modifications
448
+ represent, as a whole, an original work of authorship. For the purposes
449
+ of this License, Derivative Works shall not include works that remain
450
+ separable from, or merely link (or bind by name) to the interfaces of,
451
+ the Work and Derivative Works thereof.
452
+
453
+ "Contribution" shall mean any work of authorship, including
454
+ the original version of the Work and any modifications or additions
455
+ to that Work or Derivative Works thereof, that is intentionally
456
+ submitted to Licensor for inclusion in the Work by the copyright owner
457
+ or by an individual or Legal Entity authorized to submit on behalf of
458
+ the copyright owner. For the purposes of this definition, "submitted"
459
+ means any form of electronic, verbal, or written communication sent
460
+ to the Licensor or its representatives, including but not limited to
461
+ communication on electronic mailing lists, source code control systems,
462
+ and issue tracking systems that are managed by, or on behalf of, the
463
+ Licensor for the purpose of discussing and improving the Work, but
464
+ excluding communication that is conspicuously marked or otherwise
465
+ designated in writing by the copyright owner as "Not a Contribution."
466
+
467
+ "Contributor" shall mean Licensor and any individual or Legal Entity
468
+ on behalf of whom a Contribution has been received by Licensor and
469
+ subsequently incorporated within the Work.
470
+
471
+ 2. Grant of Copyright License. Subject to the terms and conditions of
472
+ this License, each Contributor hereby grants to You a perpetual,
473
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
474
+ copyright license to reproduce, prepare Derivative Works of,
475
+ publicly display, publicly perform, sublicense, and distribute the
476
+ Work and such Derivative Works in Source or Object form.
477
+
478
+ 3. Grant of Patent License. Subject to the terms and conditions of
479
+ this License, each Contributor hereby grants to You a perpetual,
480
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
481
+ (except as stated in this section) patent license to make, have made,
482
+ use, offer to sell, sell, import, and otherwise transfer the Work,
483
+ where such license applies only to those patent claims licensable
484
+ by such Contributor that are necessarily infringed by their
485
+ Contribution(s) alone or by combination of their Contribution(s)
486
+ with the Work to which such Contribution(s) was submitted. If You
487
+ institute patent litigation against any entity (including a
488
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
489
+ or a Contribution incorporated within the Work constitutes direct
490
+ or contributory patent infringement, then any patent licenses
491
+ granted to You under this License for that Work shall terminate
492
+ as of the date such litigation is filed.
493
+
494
+ 4. Redistribution. You may reproduce and distribute copies of the
495
+ Work or Derivative Works thereof in any medium, with or without
496
+ modifications, and in Source or Object form, provided that You
497
+ meet the following conditions:
498
+
499
+ (a) You must give any other recipients of the Work or
500
+ Derivative Works a copy of this License; and
501
+
502
+ (b) You must cause any modified files to carry prominent notices
503
+ stating that You changed the files; and
504
+
505
+ (c) You must retain, in the Source form of any Derivative Works
506
+ that You distribute, all copyright, patent, trademark, and
507
+ attribution notices from the Source form of the Work,
508
+ excluding those notices that do not pertain to any part of
509
+ the Derivative Works; and
510
+
511
+ (d) If the Work includes a "NOTICE" text file as part of its
512
+ distribution, then any Derivative Works that You distribute must
513
+ include a readable copy of the attribution notices contained
514
+ within such NOTICE file, excluding those notices that do not
515
+ pertain to any part of the Derivative Works, in at least one
516
+ of the following places: within a NOTICE text file distributed
517
+ as part of the Derivative Works; within the Source form or
518
+ documentation, if provided along with the Derivative Works; or,
519
+ within a display generated by the Derivative Works, if and
520
+ wherever such third-party notices normally appear. The contents
521
+ of the NOTICE file are for informational purposes only and
522
+ do not modify the License. You may add Your own attribution
523
+ notices within Derivative Works that You distribute, alongside
524
+ or as an addendum to the NOTICE text from the Work, provided
525
+ that such additional attribution notices cannot be construed
526
+ as modifying the License.
527
+
528
+ You may add Your own copyright statement to Your modifications and
529
+ may provide additional or different license terms and conditions
530
+ for use, reproduction, or distribution of Your modifications, or
531
+ for any such Derivative Works as a whole, provided Your use,
532
+ reproduction, and distribution of the Work otherwise complies with
533
+ the conditions stated in this License.
534
+
535
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
536
+ any Contribution intentionally submitted for inclusion in the Work
537
+ by You to the Licensor shall be under the terms and conditions of
538
+ this License, without any additional terms or conditions.
539
+ Notwithstanding the above, nothing herein shall supersede or modify
540
+ the terms of any separate license agreement you may have executed
541
+ with Licensor regarding such Contributions.
542
+
543
+ 6. Trademarks. This License does not grant permission to use the trade
544
+ names, trademarks, service marks, or product names of the Licensor,
545
+ except as required for reasonable and customary use in describing the
546
+ origin of the Work and reproducing the content of the NOTICE file.
547
+
548
+ 7. Disclaimer of Warranty. Unless required by applicable law or
549
+ agreed to in writing, Licensor provides the Work (and each
550
+ Contributor provides its Contributions) on an "AS IS" BASIS,
551
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
552
+ implied, including, without limitation, any warranties or conditions
553
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
554
+ PARTICULAR PURPOSE. You are solely responsible for determining the
555
+ appropriateness of using or redistributing the Work and assume any
556
+ risks associated with Your exercise of permissions under this License.
557
+
558
+ 8. Limitation of Liability. In no event and under no legal theory,
559
+ whether in tort (including negligence), contract, or otherwise,
560
+ unless required by applicable law (such as deliberate and grossly
561
+ negligent acts) or agreed to in writing, shall any Contributor be
562
+ liable to You for damages, including any direct, indirect, special,
563
+ incidental, or consequential damages of any character arising as a
564
+ result of this License or out of the use or inability to use the
565
+ Work (including but not limited to damages for loss of goodwill,
566
+ work stoppage, computer failure or malfunction, or any and all
567
+ other commercial damages or losses), even if such Contributor
568
+ has been advised of the possibility of such damages.
569
+
570
+ 9. Accepting Warranty or Additional Liability. While redistributing
571
+ the Work or Derivative Works thereof, You may choose to offer,
572
+ and charge a fee for, acceptance of support, warranty, indemnity,
573
+ or other liability obligations and/or rights consistent with this
574
+ License. However, in accepting such obligations, You may act only
575
+ on Your own behalf and on Your sole responsibility, not on behalf
576
+ of any other Contributor, and only if You agree to indemnify,
577
+ defend, and hold each Contributor harmless for any liability
578
+ incurred by, or claims asserted against, such Contributor by reason
579
+ of your accepting any such warranty or additional liability.
580
+
581
+ END OF TERMS AND CONDITIONS
582
+
583
+
584
+ Copyright (c) Donald Stufft and individual contributors.
585
+ All rights reserved.
586
+
587
+ Redistribution and use in source and binary forms, with or without
588
+ modification, are permitted provided that the following conditions are met:
589
+
590
+ 1. Redistributions of source code must retain the above copyright notice,
591
+ this list of conditions and the following disclaimer.
592
+
593
+ 2. Redistributions in binary form must reproduce the above copyright
594
+ notice, this list of conditions and the following disclaimer in the
595
+ documentation and/or other materials provided with the distribution.
596
+
597
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
598
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
599
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
600
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
601
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
602
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
603
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
604
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
605
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
606
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.A. HISTORY OF THE SOFTWARE
607
+ ==========================
608
+
609
+ Python was created in the early 1990s by Guido van Rossum at Stichting
610
+ Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
611
+ as a successor of a language called ABC. Guido remains Python's
612
+ principal author, although it includes many contributions from others.
613
+
614
+ In 1995, Guido continued his work on Python at the Corporation for
615
+ National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
616
+ in Reston, Virginia where he released several versions of the
617
+ software.
618
+
619
+ In May 2000, Guido and the Python core development team moved to
620
+ BeOpen.com to form the BeOpen PythonLabs team. In October of the same
621
+ year, the PythonLabs team moved to Digital Creations, which became
622
+ Zope Corporation. In 2001, the Python Software Foundation (PSF, see
623
+ https://www.python.org/psf/) was formed, a non-profit organization
624
+ created specifically to own Python-related Intellectual Property.
625
+ Zope Corporation was a sponsoring member of the PSF.
626
+
627
+ All Python releases are Open Source (see https://opensource.org for
628
+ the Open Source Definition). Historically, most, but not all, Python
629
+ releases have also been GPL-compatible; the table below summarizes
630
+ the various releases.
631
+
632
+ Release Derived Year Owner GPL-
633
+ from compatible? (1)
634
+
635
+ 0.9.0 thru 1.2 1991-1995 CWI yes
636
+ 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
637
+ 1.6 1.5.2 2000 CNRI no
638
+ 2.0 1.6 2000 BeOpen.com no
639
+ 1.6.1 1.6 2001 CNRI yes (2)
640
+ 2.1 2.0+1.6.1 2001 PSF no
641
+ 2.0.1 2.0+1.6.1 2001 PSF yes
642
+ 2.1.1 2.1+2.0.1 2001 PSF yes
643
+ 2.1.2 2.1.1 2002 PSF yes
644
+ 2.1.3 2.1.2 2002 PSF yes
645
+ 2.2 and above 2.1.1 2001-now PSF yes
646
+
647
+ Footnotes:
648
+
649
+ (1) GPL-compatible doesn't mean that we're distributing Python under
650
+ the GPL. All Python licenses, unlike the GPL, let you distribute
651
+ a modified version without making your changes open source. The
652
+ GPL-compatible licenses make it possible to combine Python with
653
+ other software that is released under the GPL; the others don't.
654
+
655
+ (2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
656
+ because its license has a choice of law clause. According to
657
+ CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
658
+ is "not incompatible" with the GPL.
659
+
660
+ Thanks to the many outside volunteers who have worked under Guido's
661
+ direction to make these releases possible.
662
+
663
+
664
+ B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
665
+ ===============================================================
666
+
667
+ Python software and documentation are licensed under the
668
+ Python Software Foundation License Version 2.
669
+
670
+ Starting with Python 3.8.6, examples, recipes, and other code in
671
+ the documentation are dual licensed under the PSF License Version 2
672
+ and the Zero-Clause BSD license.
673
+
674
+ Some software incorporated into Python is under different licenses.
675
+ The licenses are listed with code falling under that license.
676
+
677
+
678
+ PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
679
+ --------------------------------------------
680
+
681
+ 1. This LICENSE AGREEMENT is between the Python Software Foundation
682
+ ("PSF"), and the Individual or Organization ("Licensee") accessing and
683
+ otherwise using this software ("Python") in source or binary form and
684
+ its associated documentation.
685
+
686
+ 2. Subject to the terms and conditions of this License Agreement, PSF hereby
687
+ grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
688
+ analyze, test, perform and/or display publicly, prepare derivative works,
689
+ distribute, and otherwise use Python alone or in any derivative version,
690
+ provided, however, that PSF's License Agreement and PSF's notice of copyright,
691
+ i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
692
+ 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
693
+ All Rights Reserved" are retained in Python alone or in any derivative version
694
+ prepared by Licensee.
695
+
696
+ 3. In the event Licensee prepares a derivative work that is based on
697
+ or incorporates Python or any part thereof, and wants to make
698
+ the derivative work available to others as provided herein, then
699
+ Licensee hereby agrees to include in any such work a brief summary of
700
+ the changes made to Python.
701
+
702
+ 4. PSF is making Python available to Licensee on an "AS IS"
703
+ basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
704
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
705
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
706
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
707
+ INFRINGE ANY THIRD PARTY RIGHTS.
708
+
709
+ 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
710
+ FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
711
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
712
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
713
+
714
+ 6. This License Agreement will automatically terminate upon a material
715
+ breach of its terms and conditions.
716
+
717
+ 7. Nothing in this License Agreement shall be deemed to create any
718
+ relationship of agency, partnership, or joint venture between PSF and
719
+ Licensee. This License Agreement does not grant permission to use PSF
720
+ trademarks or trade name in a trademark sense to endorse or promote
721
+ products or services of Licensee, or any third party.
722
+
723
+ 8. By copying, installing or otherwise using Python, Licensee
724
+ agrees to be bound by the terms and conditions of this License
725
+ Agreement.
726
+
727
+
728
+ BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
729
+ -------------------------------------------
730
+
731
+ BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
732
+
733
+ 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
734
+ office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
735
+ Individual or Organization ("Licensee") accessing and otherwise using
736
+ this software in source or binary form and its associated
737
+ documentation ("the Software").
738
+
739
+ 2. Subject to the terms and conditions of this BeOpen Python License
740
+ Agreement, BeOpen hereby grants Licensee a non-exclusive,
741
+ royalty-free, world-wide license to reproduce, analyze, test, perform
742
+ and/or display publicly, prepare derivative works, distribute, and
743
+ otherwise use the Software alone or in any derivative version,
744
+ provided, however, that the BeOpen Python License is retained in the
745
+ Software, alone or in any derivative version prepared by Licensee.
746
+
747
+ 3. BeOpen is making the Software available to Licensee on an "AS IS"
748
+ basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
749
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
750
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
751
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
752
+ INFRINGE ANY THIRD PARTY RIGHTS.
753
+
754
+ 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
755
+ SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
756
+ AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
757
+ DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
758
+
759
+ 5. This License Agreement will automatically terminate upon a material
760
+ breach of its terms and conditions.
761
+
762
+ 6. This License Agreement shall be governed by and interpreted in all
763
+ respects by the law of the State of California, excluding conflict of
764
+ law provisions. Nothing in this License Agreement shall be deemed to
765
+ create any relationship of agency, partnership, or joint venture
766
+ between BeOpen and Licensee. This License Agreement does not grant
767
+ permission to use BeOpen trademarks or trade names in a trademark
768
+ sense to endorse or promote products or services of Licensee, or any
769
+ third party. As an exception, the "BeOpen Python" logos available at
770
+ http://www.pythonlabs.com/logos.html may be used according to the
771
+ permissions granted on that web page.
772
+
773
+ 7. By copying, installing or otherwise using the software, Licensee
774
+ agrees to be bound by the terms and conditions of this License
775
+ Agreement.
776
+
777
+
778
+ CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
779
+ ---------------------------------------
780
+
781
+ 1. This LICENSE AGREEMENT is between the Corporation for National
782
+ Research Initiatives, having an office at 1895 Preston White Drive,
783
+ Reston, VA 20191 ("CNRI"), and the Individual or Organization
784
+ ("Licensee") accessing and otherwise using Python 1.6.1 software in
785
+ source or binary form and its associated documentation.
786
+
787
+ 2. Subject to the terms and conditions of this License Agreement, CNRI
788
+ hereby grants Licensee a nonexclusive, royalty-free, world-wide
789
+ license to reproduce, analyze, test, perform and/or display publicly,
790
+ prepare derivative works, distribute, and otherwise use Python 1.6.1
791
+ alone or in any derivative version, provided, however, that CNRI's
792
+ License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
793
+ 1995-2001 Corporation for National Research Initiatives; All Rights
794
+ Reserved" are retained in Python 1.6.1 alone or in any derivative
795
+ version prepared by Licensee. Alternately, in lieu of CNRI's License
796
+ Agreement, Licensee may substitute the following text (omitting the
797
+ quotes): "Python 1.6.1 is made available subject to the terms and
798
+ conditions in CNRI's License Agreement. This Agreement together with
799
+ Python 1.6.1 may be located on the internet using the following
800
+ unique, persistent identifier (known as a handle): 1895.22/1013. This
801
+ Agreement may also be obtained from a proxy server on the internet
802
+ using the following URL: http://hdl.handle.net/1895.22/1013".
803
+
804
+ 3. In the event Licensee prepares a derivative work that is based on
805
+ or incorporates Python 1.6.1 or any part thereof, and wants to make
806
+ the derivative work available to others as provided herein, then
807
+ Licensee hereby agrees to include in any such work a brief summary of
808
+ the changes made to Python 1.6.1.
809
+
810
+ 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
811
+ basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
812
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
813
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
814
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
815
+ INFRINGE ANY THIRD PARTY RIGHTS.
816
+
817
+ 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
818
+ 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
819
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
820
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
821
+
822
+ 6. This License Agreement will automatically terminate upon a material
823
+ breach of its terms and conditions.
824
+
825
+ 7. This License Agreement shall be governed by the federal
826
+ intellectual property law of the United States, including without
827
+ limitation the federal copyright law, and, to the extent such
828
+ U.S. federal law does not apply, by the law of the Commonwealth of
829
+ Virginia, excluding Virginia's conflict of law provisions.
830
+ Notwithstanding the foregoing, with regard to derivative works based
831
+ on Python 1.6.1 that incorporate non-separable material that was
832
+ previously distributed under the GNU General Public License (GPL), the
833
+ law of the Commonwealth of Virginia shall govern this License
834
+ Agreement only as to issues arising under or with respect to
835
+ Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
836
+ License Agreement shall be deemed to create any relationship of
837
+ agency, partnership, or joint venture between CNRI and Licensee. This
838
+ License Agreement does not grant permission to use CNRI trademarks or
839
+ trade name in a trademark sense to endorse or promote products or
840
+ services of Licensee, or any third party.
841
+
842
+ 8. By clicking on the "ACCEPT" button where indicated, or by copying,
843
+ installing or otherwise using Python 1.6.1, Licensee agrees to be
844
+ bound by the terms and conditions of this License Agreement.
845
+
846
+ ACCEPT
847
+
848
+
849
+ CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
850
+ --------------------------------------------------
851
+
852
+ Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
853
+ The Netherlands. All rights reserved.
854
+
855
+ Permission to use, copy, modify, and distribute this software and its
856
+ documentation for any purpose and without fee is hereby granted,
857
+ provided that the above copyright notice appear in all copies and that
858
+ both that copyright notice and this permission notice appear in
859
+ supporting documentation, and that the name of Stichting Mathematisch
860
+ Centrum or CWI not be used in advertising or publicity pertaining to
861
+ distribution of the software without specific, written prior
862
+ permission.
863
+
864
+ STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
865
+ THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
866
+ FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
867
+ FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
868
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
869
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
870
+ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
871
+
872
+ ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
873
+ ----------------------------------------------------------------------
874
+
875
+ Permission to use, copy, modify, and/or distribute this software for any
876
+ purpose with or without fee is hereby granted.
877
+
878
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
879
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
880
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
881
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
882
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
883
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
884
+ PERFORMANCE OF THIS SOFTWARE.
885
+ Copyright (c) 2014, Al Sweigart
886
+ All rights reserved.
887
+
888
+ Redistribution and use in source and binary forms, with or without
889
+ modification, are permitted provided that the following conditions are met:
890
+
891
+ * Redistributions of source code must retain the above copyright notice, this
892
+ list of conditions and the following disclaimer.
893
+
894
+ * Redistributions in binary form must reproduce the above copyright notice,
895
+ this list of conditions and the following disclaimer in the documentation
896
+ and/or other materials provided with the distribution.
897
+
898
+ * Neither the name of the {organization} nor the names of its
899
+ contributors may be used to endorse or promote products derived from
900
+ this software without specific prior written permission.
901
+
902
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
903
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
904
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
905
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
906
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
907
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
908
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
909
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
910
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
911
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.Copyright (c) 2017 Anthony Sottile
912
+
913
+ Permission is hereby granted, free of charge, to any person obtaining a copy
914
+ of this software and associated documentation files (the "Software"), to deal
915
+ in the Software without restriction, including without limitation the rights
916
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
917
+ copies of the Software, and to permit persons to whom the Software is
918
+ furnished to do so, subject to the following conditions:
919
+
920
+ The above copyright notice and this permission notice shall be included in
921
+ all copies or substantial portions of the Software.
922
+
923
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
924
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
925
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
926
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
927
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
928
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
929
+ THE SOFTWARE.Copyright (c) 2015-2019 Jared Hobbs
930
+
931
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
932
+ this software and associated documentation files (the "Software"), to deal in
933
+ the Software without restriction, including without limitation the rights to
934
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
935
+ of the Software, and to permit persons to whom the Software is furnished to do
936
+ so, subject to the following conditions:
937
+
938
+ The above copyright notice and this permission notice shall be included in all
939
+ copies or substantial portions of the Software.
940
+
941
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
942
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
943
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
944
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
945
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
946
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
947
+ SOFTWARE.Developed by ESN, an Electronic Arts Inc. studio.
948
+ Copyright (c) 2014, Electronic Arts Inc.
949
+ All rights reserved.
950
+
951
+ Redistribution and use in source and binary forms, with or without
952
+ modification, are permitted provided that the following conditions are met:
953
+ * Redistributions of source code must retain the above copyright
954
+ notice, this list of conditions and the following disclaimer.
955
+ * Redistributions in binary form must reproduce the above copyright
956
+ notice, this list of conditions and the following disclaimer in the
957
+ documentation and/or other materials provided with the distribution.
958
+ * Neither the name of ESN, Electronic Arts Inc. nor the
959
+ names of its contributors may be used to endorse or promote products
960
+ derived from this software without specific prior written permission.
961
+
962
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
963
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
964
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
965
+ DISCLAIMED. IN NO EVENT SHALL ELECTRONIC ARTS INC. BE LIABLE
966
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
967
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
968
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
969
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
970
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
971
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
972
+
973
+ ----
974
+
975
+ Portions of code from MODP_ASCII - Ascii transformations (upper/lower, etc)
976
+ https://github.com/client9/stringencoders
977
+
978
+ Copyright 2005, 2006, 2007
979
+ Nick Galbreath -- nickg [at] modp [dot] com
980
+ All rights reserved.
981
+
982
+ Redistribution and use in source and binary forms, with or without
983
+ modification, are permitted provided that the following conditions are
984
+ met:
985
+
986
+ Redistributions of source code must retain the above copyright
987
+ notice, this list of conditions and the following disclaimer.
988
+
989
+ Redistributions in binary form must reproduce the above copyright
990
+ notice, this list of conditions and the following disclaimer in the
991
+ documentation and/or other materials provided with the distribution.
992
+
993
+ Neither the name of the modp.com nor the names of its
994
+ contributors may be used to endorse or promote products derived from
995
+ this software without specific prior written permission.
996
+
997
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
998
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
999
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1000
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1001
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1002
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1003
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1004
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1005
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1006
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1007
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1008
+
1009
+ This is the standard "new" BSD license:
1010
+ http://www.opensource.org/licenses/bsd-license.php
1011
+
1012
+ https://github.com/client9/stringencoders/blob/cfd5c1507325ae497ea9bacdacba12c0ffd79d30/COPYING
1013
+
1014
+ ----
1015
+
1016
+ Numeric decoder derived from from TCL library
1017
+ https://opensource.apple.com/source/tcl/tcl-14/tcl/license.terms
1018
+ * Copyright (c) 1988-1993 The Regents of the University of California.
1019
+ * Copyright (c) 1994 Sun Microsystems, Inc.
1020
+
1021
+ This software is copyrighted by the Regents of the University of
1022
+ California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
1023
+ Corporation and other parties. The following terms apply to all files
1024
+ associated with the software unless explicitly disclaimed in
1025
+ individual files.
1026
+
1027
+ The authors hereby grant permission to use, copy, modify, distribute,
1028
+ and license this software and its documentation for any purpose, provided
1029
+ that existing copyright notices are retained in all copies and that this
1030
+ notice is included verbatim in any distributions. No written agreement,
1031
+ license, or royalty fee is required for any of the authorized uses.
1032
+ Modifications to this software may be copyrighted by their authors
1033
+ and need not follow the licensing terms described here, provided that
1034
+ the new terms are clearly indicated on the first page of each file where
1035
+ they apply.
1036
+
1037
+ IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
1038
+ FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
1039
+ ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
1040
+ DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
1041
+ POSSIBILITY OF SUCH DAMAGE.
1042
+
1043
+ THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
1044
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
1045
+ FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
1046
+ IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
1047
+ NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
1048
+ MODIFICATIONS.
1049
+
1050
+ GOVERNMENT USE: If you are acquiring this software on behalf of the
1051
+ U.S. government, the Government shall have only "Restricted Rights"
1052
+ in the software and related documentation as defined in the Federal
1053
+ Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
1054
+ are acquiring the software on behalf of the Department of Defense, the
1055
+ software shall be classified as "Commercial Computer Software" and the
1056
+ Government shall have only "Restricted Rights" as defined in Clause
1057
+ 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the
1058
+ authors grant the U.S. Government and others acting in its behalf
1059
+ permission to use and distribute the software in accordance with the
1060
+ terms specified in this license.
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/METADATA ADDED
@@ -0,0 +1,1383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: pandas
3
+ Version: 3.0.4
4
+ Summary: Powerful data structures for data analysis, time series, and statistics
5
+ Author-Email: The Pandas Development Team <pandas-dev@python.org>
6
+ License: BSD 3-Clause License
7
+
8
+ Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team
9
+ All rights reserved.
10
+
11
+ Copyright (c) 2011-2026, Open source contributors.
12
+
13
+ Redistribution and use in source and binary forms, with or without
14
+ modification, are permitted provided that the following conditions are met:
15
+
16
+ * Redistributions of source code must retain the above copyright notice, this
17
+ list of conditions and the following disclaimer.
18
+
19
+ * Redistributions in binary form must reproduce the above copyright notice,
20
+ this list of conditions and the following disclaimer in the documentation
21
+ and/or other materials provided with the distribution.
22
+
23
+ * Neither the name of the copyright holder nor the names of its
24
+ contributors may be used to endorse or promote products derived from
25
+ this software without specific prior written permission.
26
+
27
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
28
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
30
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
31
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
33
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
34
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
35
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37
+ Copyright (c) 2010-2019 Keith Goodman
38
+ Copyright (c) 2019 Bottleneck Developers
39
+ All rights reserved.
40
+
41
+ Redistribution and use in source and binary forms, with or without
42
+ modification, are permitted provided that the following conditions are met:
43
+
44
+ * Redistributions of source code must retain the above copyright notice,
45
+ this list of conditions and the following disclaimer.
46
+
47
+ * Redistributions in binary form must reproduce the above copyright
48
+ notice, this list of conditions and the following disclaimer in the
49
+ documentation and/or other materials provided with the distribution.
50
+
51
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
52
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
55
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
56
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
57
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
58
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
59
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
60
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
61
+ POSSIBILITY OF SUCH DAMAGE.Copyright 2017- Paul Ganssle <paul@ganssle.io>
62
+ Copyright 2017- dateutil contributors (see AUTHORS file)
63
+
64
+ Licensed under the Apache License, Version 2.0 (the "License");
65
+ you may not use this file except in compliance with the License.
66
+ You may obtain a copy of the License at
67
+
68
+ http://www.apache.org/licenses/LICENSE-2.0
69
+
70
+ Unless required by applicable law or agreed to in writing, software
71
+ distributed under the License is distributed on an "AS IS" BASIS,
72
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
73
+ See the License for the specific language governing permissions and
74
+ limitations under the License.
75
+
76
+ The above license applies to all contributions after 2017-12-01, as well as
77
+ all contributions that have been re-licensed (see AUTHORS file for the list of
78
+ contributors who have re-licensed their code).
79
+ --------------------------------------------------------------------------------
80
+ dateutil - Extensions to the standard Python datetime module.
81
+
82
+ Copyright (c) 2003-2011 - Gustavo Niemeyer <gustavo@niemeyer.net>
83
+ Copyright (c) 2012-2014 - Tomi Pieviläinen <tomi.pievilainen@iki.fi>
84
+ Copyright (c) 2014-2016 - Yaron de Leeuw <me@jarondl.net>
85
+ Copyright (c) 2015- - Paul Ganssle <paul@ganssle.io>
86
+ Copyright (c) 2015- - dateutil contributors (see AUTHORS file)
87
+
88
+ All rights reserved.
89
+
90
+ Redistribution and use in source and binary forms, with or without
91
+ modification, are permitted provided that the following conditions are met:
92
+
93
+ * Redistributions of source code must retain the above copyright notice,
94
+ this list of conditions and the following disclaimer.
95
+ * Redistributions in binary form must reproduce the above copyright notice,
96
+ this list of conditions and the following disclaimer in the documentation
97
+ and/or other materials provided with the distribution.
98
+ * Neither the name of the copyright holder nor the names of its
99
+ contributors may be used to endorse or promote products derived from
100
+ this software without specific prior written permission.
101
+
102
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
103
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
104
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
105
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
106
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
107
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
108
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
109
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
110
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
111
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
112
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
113
+
114
+ The above BSD License Applies to all code, even that also covered by Apache 2.0.# MIT License
115
+
116
+ Copyright (c) 2019 Hadley Wickham; RStudio; and Evan Miller
117
+
118
+ Permission is hereby granted, free of charge, to any person obtaining a copy
119
+ of this software and associated documentation files (the "Software"), to deal
120
+ in the Software without restriction, including without limitation the rights
121
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
122
+ copies of the Software, and to permit persons to whom the Software is
123
+ furnished to do so, subject to the following conditions:
124
+
125
+ The above copyright notice and this permission notice shall be included in all
126
+ copies or substantial portions of the Software.
127
+
128
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
129
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
130
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
131
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
132
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
133
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
134
+ SOFTWARE.
135
+ Based on http://opensource.org/licenses/MIT
136
+
137
+ This is a template. Complete and ship as file LICENSE the following 2
138
+ lines (only)
139
+
140
+ YEAR:
141
+ COPYRIGHT HOLDER:
142
+
143
+ and specify as
144
+
145
+ License: MIT + file LICENSE
146
+
147
+ Copyright (c) <YEAR>, <COPYRIGHT HOLDER>
148
+
149
+ Permission is hereby granted, free of charge, to any person obtaining
150
+ a copy of this software and associated documentation files (the
151
+ "Software"), to deal in the Software without restriction, including
152
+ without limitation the rights to use, copy, modify, merge, publish,
153
+ distribute, sublicense, and/or sell copies of the Software, and to
154
+ permit persons to whom the Software is furnished to do so, subject to
155
+ the following conditions:
156
+
157
+ The above copyright notice and this permission notice shall be
158
+ included in all copies or substantial portions of the Software.
159
+
160
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
161
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
162
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
163
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
164
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
165
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
166
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
167
+ The MIT License
168
+
169
+ Copyright (c) 2008- Attractive Chaos <attractor@live.co.uk>
170
+
171
+ Permission is hereby granted, free of charge, to any person obtaining
172
+ a copy of this software and associated documentation files (the
173
+ "Software"), to deal in the Software without restriction, including
174
+ without limitation the rights to use, copy, modify, merge, publish,
175
+ distribute, sublicense, and/or sell copies of the Software, and to
176
+ permit persons to whom the Software is furnished to do so, subject to
177
+ the following conditions:
178
+
179
+ The above copyright notice and this permission notice shall be
180
+ included in all copies or substantial portions of the Software.
181
+
182
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
183
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
184
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
185
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
186
+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
187
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
188
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
189
+ SOFTWARE.musl as a whole is licensed under the following standard MIT license:
190
+
191
+ ----------------------------------------------------------------------
192
+ Copyright © 2005-2020 Rich Felker, et al.
193
+
194
+ Permission is hereby granted, free of charge, to any person obtaining
195
+ a copy of this software and associated documentation files (the
196
+ "Software"), to deal in the Software without restriction, including
197
+ without limitation the rights to use, copy, modify, merge, publish,
198
+ distribute, sublicense, and/or sell copies of the Software, and to
199
+ permit persons to whom the Software is furnished to do so, subject to
200
+ the following conditions:
201
+
202
+ The above copyright notice and this permission notice shall be
203
+ included in all copies or substantial portions of the Software.
204
+
205
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
206
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
207
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
208
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
209
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
210
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
211
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
212
+ ----------------------------------------------------------------------
213
+
214
+ Authors/contributors include:
215
+
216
+ A. Wilcox
217
+ Ada Worcester
218
+ Alex Dowad
219
+ Alex Suykov
220
+ Alexander Monakov
221
+ Andre McCurdy
222
+ Andrew Kelley
223
+ Anthony G. Basile
224
+ Aric Belsito
225
+ Arvid Picciani
226
+ Bartosz Brachaczek
227
+ Benjamin Peterson
228
+ Bobby Bingham
229
+ Boris Brezillon
230
+ Brent Cook
231
+ Chris Spiegel
232
+ Clément Vasseur
233
+ Daniel Micay
234
+ Daniel Sabogal
235
+ Daurnimator
236
+ David Carlier
237
+ David Edelsohn
238
+ Denys Vlasenko
239
+ Dmitry Ivanov
240
+ Dmitry V. Levin
241
+ Drew DeVault
242
+ Emil Renner Berthing
243
+ Fangrui Song
244
+ Felix Fietkau
245
+ Felix Janda
246
+ Gianluca Anzolin
247
+ Hauke Mehrtens
248
+ He X
249
+ Hiltjo Posthuma
250
+ Isaac Dunham
251
+ Jaydeep Patil
252
+ Jens Gustedt
253
+ Jeremy Huntwork
254
+ Jo-Philipp Wich
255
+ Joakim Sindholt
256
+ John Spencer
257
+ Julien Ramseier
258
+ Justin Cormack
259
+ Kaarle Ritvanen
260
+ Khem Raj
261
+ Kylie McClain
262
+ Leah Neukirchen
263
+ Luca Barbato
264
+ Luka Perkov
265
+ M Farkas-Dyck (Strake)
266
+ Mahesh Bodapati
267
+ Markus Wichmann
268
+ Masanori Ogino
269
+ Michael Clark
270
+ Michael Forney
271
+ Mikhail Kremnyov
272
+ Natanael Copa
273
+ Nicholas J. Kain
274
+ orc
275
+ Pascal Cuoq
276
+ Patrick Oppenlander
277
+ Petr Hosek
278
+ Petr Skocik
279
+ Pierre Carrier
280
+ Reini Urban
281
+ Rich Felker
282
+ Richard Pennington
283
+ Ryan Fairfax
284
+ Samuel Holland
285
+ Segev Finer
286
+ Shiz
287
+ sin
288
+ Solar Designer
289
+ Stefan Kristiansson
290
+ Stefan O'Rear
291
+ Szabolcs Nagy
292
+ Timo Teräs
293
+ Trutz Behn
294
+ Valentin Ochs
295
+ Will Dietz
296
+ William Haddon
297
+ William Pitcock
298
+
299
+ Portions of this software are derived from third-party works licensed
300
+ under terms compatible with the above MIT license:
301
+
302
+ The TRE regular expression implementation (src/regex/reg* and
303
+ src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed
304
+ under a 2-clause BSD license (license text in the source files). The
305
+ included version has been heavily modified by Rich Felker in 2012, in
306
+ the interests of size, simplicity, and namespace cleanliness.
307
+
308
+ Much of the math library code (src/math/* and src/complex/*) is
309
+ Copyright © 1993,2004 Sun Microsystems or
310
+ Copyright © 2003-2011 David Schultz or
311
+ Copyright © 2003-2009 Steven G. Kargl or
312
+ Copyright © 2003-2009 Bruce D. Evans or
313
+ Copyright © 2008 Stephen L. Moshier or
314
+ Copyright © 2017-2018 Arm Limited
315
+ and labelled as such in comments in the individual source files. All
316
+ have been licensed under extremely permissive terms.
317
+
318
+ The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008
319
+ The Android Open Source Project and is licensed under a two-clause BSD
320
+ license. It was taken from Bionic libc, used on Android.
321
+
322
+ The AArch64 memcpy and memset code (src/string/aarch64/*) are
323
+ Copyright © 1999-2019, Arm Limited.
324
+
325
+ The implementation of DES for crypt (src/crypt/crypt_des.c) is
326
+ Copyright © 1994 David Burren. It is licensed under a BSD license.
327
+
328
+ The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was
329
+ originally written by Solar Designer and placed into the public
330
+ domain. The code also comes with a fallback permissive license for use
331
+ in jurisdictions that may not recognize the public domain.
332
+
333
+ The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011
334
+ Valentin Ochs and is licensed under an MIT-style license.
335
+
336
+ The x86_64 port was written by Nicholas J. Kain and is licensed under
337
+ the standard MIT terms.
338
+
339
+ The mips and microblaze ports were originally written by Richard
340
+ Pennington for use in the ellcc project. The original code was adapted
341
+ by Rich Felker for build system and code conventions during upstream
342
+ integration. It is licensed under the standard MIT terms.
343
+
344
+ The mips64 port was contributed by Imagination Technologies and is
345
+ licensed under the standard MIT terms.
346
+
347
+ The powerpc port was also originally written by Richard Pennington,
348
+ and later supplemented and integrated by John Spencer. It is licensed
349
+ under the standard MIT terms.
350
+
351
+ All other files which have no copyright comments are original works
352
+ produced specifically for use as part of this library, written either
353
+ by Rich Felker, the main author of the library, or by one or more
354
+ contibutors listed above. Details on authorship of individual files
355
+ can be found in the git version control history of the project. The
356
+ omission of copyright and license comments in each file is in the
357
+ interest of source tree size.
358
+
359
+ In addition, permission is hereby granted for all public header files
360
+ (include/* and arch/*/bits/*) and crt files intended to be linked into
361
+ applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit
362
+ the copyright notice and permission notice otherwise required by the
363
+ license, and to use these files without any requirement of
364
+ attribution. These files include substantial contributions from:
365
+
366
+ Bobby Bingham
367
+ John Spencer
368
+ Nicholas J. Kain
369
+ Rich Felker
370
+ Richard Pennington
371
+ Stefan Kristiansson
372
+ Szabolcs Nagy
373
+
374
+ all of whom have explicitly granted such permission.
375
+
376
+ This file previously contained text expressing a belief that most of
377
+ the files covered by the above exception were sufficiently trivial not
378
+ to be subject to copyright, resulting in confusion over whether it
379
+ negated the permissions granted in the license. In the spirit of
380
+ permissive licensing, and of not having licensing issues being an
381
+ obstacle to adoption, that text has been removed.Copyright (c) 2005-2023, NumPy Developers.
382
+ All rights reserved.
383
+
384
+ Redistribution and use in source and binary forms, with or without
385
+ modification, are permitted provided that the following conditions are
386
+ met:
387
+
388
+ * Redistributions of source code must retain the above copyright
389
+ notice, this list of conditions and the following disclaimer.
390
+
391
+ * Redistributions in binary form must reproduce the above
392
+ copyright notice, this list of conditions and the following
393
+ disclaimer in the documentation and/or other materials provided
394
+ with the distribution.
395
+
396
+ * Neither the name of the NumPy Developers nor the names of any
397
+ contributors may be used to endorse or promote products derived
398
+ from this software without specific prior written permission.
399
+
400
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
401
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
402
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
403
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
404
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
405
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
406
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
407
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
408
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
409
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
410
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
411
+ Apache License
412
+ Version 2.0, January 2004
413
+ http://www.apache.org/licenses/
414
+
415
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
416
+
417
+ 1. Definitions.
418
+
419
+ "License" shall mean the terms and conditions for use, reproduction,
420
+ and distribution as defined by Sections 1 through 9 of this document.
421
+
422
+ "Licensor" shall mean the copyright owner or entity authorized by
423
+ the copyright owner that is granting the License.
424
+
425
+ "Legal Entity" shall mean the union of the acting entity and all
426
+ other entities that control, are controlled by, or are under common
427
+ control with that entity. For the purposes of this definition,
428
+ "control" means (i) the power, direct or indirect, to cause the
429
+ direction or management of such entity, whether by contract or
430
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
431
+ outstanding shares, or (iii) beneficial ownership of such entity.
432
+
433
+ "You" (or "Your") shall mean an individual or Legal Entity
434
+ exercising permissions granted by this License.
435
+
436
+ "Source" form shall mean the preferred form for making modifications,
437
+ including but not limited to software source code, documentation
438
+ source, and configuration files.
439
+
440
+ "Object" form shall mean any form resulting from mechanical
441
+ transformation or translation of a Source form, including but
442
+ not limited to compiled object code, generated documentation,
443
+ and conversions to other media types.
444
+
445
+ "Work" shall mean the work of authorship, whether in Source or
446
+ Object form, made available under the License, as indicated by a
447
+ copyright notice that is included in or attached to the work
448
+ (an example is provided in the Appendix below).
449
+
450
+ "Derivative Works" shall mean any work, whether in Source or Object
451
+ form, that is based on (or derived from) the Work and for which the
452
+ editorial revisions, annotations, elaborations, or other modifications
453
+ represent, as a whole, an original work of authorship. For the purposes
454
+ of this License, Derivative Works shall not include works that remain
455
+ separable from, or merely link (or bind by name) to the interfaces of,
456
+ the Work and Derivative Works thereof.
457
+
458
+ "Contribution" shall mean any work of authorship, including
459
+ the original version of the Work and any modifications or additions
460
+ to that Work or Derivative Works thereof, that is intentionally
461
+ submitted to Licensor for inclusion in the Work by the copyright owner
462
+ or by an individual or Legal Entity authorized to submit on behalf of
463
+ the copyright owner. For the purposes of this definition, "submitted"
464
+ means any form of electronic, verbal, or written communication sent
465
+ to the Licensor or its representatives, including but not limited to
466
+ communication on electronic mailing lists, source code control systems,
467
+ and issue tracking systems that are managed by, or on behalf of, the
468
+ Licensor for the purpose of discussing and improving the Work, but
469
+ excluding communication that is conspicuously marked or otherwise
470
+ designated in writing by the copyright owner as "Not a Contribution."
471
+
472
+ "Contributor" shall mean Licensor and any individual or Legal Entity
473
+ on behalf of whom a Contribution has been received by Licensor and
474
+ subsequently incorporated within the Work.
475
+
476
+ 2. Grant of Copyright License. Subject to the terms and conditions of
477
+ this License, each Contributor hereby grants to You a perpetual,
478
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
479
+ copyright license to reproduce, prepare Derivative Works of,
480
+ publicly display, publicly perform, sublicense, and distribute the
481
+ Work and such Derivative Works in Source or Object form.
482
+
483
+ 3. Grant of Patent License. Subject to the terms and conditions of
484
+ this License, each Contributor hereby grants to You a perpetual,
485
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
486
+ (except as stated in this section) patent license to make, have made,
487
+ use, offer to sell, sell, import, and otherwise transfer the Work,
488
+ where such license applies only to those patent claims licensable
489
+ by such Contributor that are necessarily infringed by their
490
+ Contribution(s) alone or by combination of their Contribution(s)
491
+ with the Work to which such Contribution(s) was submitted. If You
492
+ institute patent litigation against any entity (including a
493
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
494
+ or a Contribution incorporated within the Work constitutes direct
495
+ or contributory patent infringement, then any patent licenses
496
+ granted to You under this License for that Work shall terminate
497
+ as of the date such litigation is filed.
498
+
499
+ 4. Redistribution. You may reproduce and distribute copies of the
500
+ Work or Derivative Works thereof in any medium, with or without
501
+ modifications, and in Source or Object form, provided that You
502
+ meet the following conditions:
503
+
504
+ (a) You must give any other recipients of the Work or
505
+ Derivative Works a copy of this License; and
506
+
507
+ (b) You must cause any modified files to carry prominent notices
508
+ stating that You changed the files; and
509
+
510
+ (c) You must retain, in the Source form of any Derivative Works
511
+ that You distribute, all copyright, patent, trademark, and
512
+ attribution notices from the Source form of the Work,
513
+ excluding those notices that do not pertain to any part of
514
+ the Derivative Works; and
515
+
516
+ (d) If the Work includes a "NOTICE" text file as part of its
517
+ distribution, then any Derivative Works that You distribute must
518
+ include a readable copy of the attribution notices contained
519
+ within such NOTICE file, excluding those notices that do not
520
+ pertain to any part of the Derivative Works, in at least one
521
+ of the following places: within a NOTICE text file distributed
522
+ as part of the Derivative Works; within the Source form or
523
+ documentation, if provided along with the Derivative Works; or,
524
+ within a display generated by the Derivative Works, if and
525
+ wherever such third-party notices normally appear. The contents
526
+ of the NOTICE file are for informational purposes only and
527
+ do not modify the License. You may add Your own attribution
528
+ notices within Derivative Works that You distribute, alongside
529
+ or as an addendum to the NOTICE text from the Work, provided
530
+ that such additional attribution notices cannot be construed
531
+ as modifying the License.
532
+
533
+ You may add Your own copyright statement to Your modifications and
534
+ may provide additional or different license terms and conditions
535
+ for use, reproduction, or distribution of Your modifications, or
536
+ for any such Derivative Works as a whole, provided Your use,
537
+ reproduction, and distribution of the Work otherwise complies with
538
+ the conditions stated in this License.
539
+
540
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
541
+ any Contribution intentionally submitted for inclusion in the Work
542
+ by You to the Licensor shall be under the terms and conditions of
543
+ this License, without any additional terms or conditions.
544
+ Notwithstanding the above, nothing herein shall supersede or modify
545
+ the terms of any separate license agreement you may have executed
546
+ with Licensor regarding such Contributions.
547
+
548
+ 6. Trademarks. This License does not grant permission to use the trade
549
+ names, trademarks, service marks, or product names of the Licensor,
550
+ except as required for reasonable and customary use in describing the
551
+ origin of the Work and reproducing the content of the NOTICE file.
552
+
553
+ 7. Disclaimer of Warranty. Unless required by applicable law or
554
+ agreed to in writing, Licensor provides the Work (and each
555
+ Contributor provides its Contributions) on an "AS IS" BASIS,
556
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
557
+ implied, including, without limitation, any warranties or conditions
558
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
559
+ PARTICULAR PURPOSE. You are solely responsible for determining the
560
+ appropriateness of using or redistributing the Work and assume any
561
+ risks associated with Your exercise of permissions under this License.
562
+
563
+ 8. Limitation of Liability. In no event and under no legal theory,
564
+ whether in tort (including negligence), contract, or otherwise,
565
+ unless required by applicable law (such as deliberate and grossly
566
+ negligent acts) or agreed to in writing, shall any Contributor be
567
+ liable to You for damages, including any direct, indirect, special,
568
+ incidental, or consequential damages of any character arising as a
569
+ result of this License or out of the use or inability to use the
570
+ Work (including but not limited to damages for loss of goodwill,
571
+ work stoppage, computer failure or malfunction, or any and all
572
+ other commercial damages or losses), even if such Contributor
573
+ has been advised of the possibility of such damages.
574
+
575
+ 9. Accepting Warranty or Additional Liability. While redistributing
576
+ the Work or Derivative Works thereof, You may choose to offer,
577
+ and charge a fee for, acceptance of support, warranty, indemnity,
578
+ or other liability obligations and/or rights consistent with this
579
+ License. However, in accepting such obligations, You may act only
580
+ on Your own behalf and on Your sole responsibility, not on behalf
581
+ of any other Contributor, and only if You agree to indemnify,
582
+ defend, and hold each Contributor harmless for any liability
583
+ incurred by, or claims asserted against, such Contributor by reason
584
+ of your accepting any such warranty or additional liability.
585
+
586
+ END OF TERMS AND CONDITIONS
587
+
588
+
589
+ Copyright (c) Donald Stufft and individual contributors.
590
+ All rights reserved.
591
+
592
+ Redistribution and use in source and binary forms, with or without
593
+ modification, are permitted provided that the following conditions are met:
594
+
595
+ 1. Redistributions of source code must retain the above copyright notice,
596
+ this list of conditions and the following disclaimer.
597
+
598
+ 2. Redistributions in binary form must reproduce the above copyright
599
+ notice, this list of conditions and the following disclaimer in the
600
+ documentation and/or other materials provided with the distribution.
601
+
602
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
603
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
604
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
605
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
606
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
607
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
608
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
609
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
610
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
611
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.A. HISTORY OF THE SOFTWARE
612
+ ==========================
613
+
614
+ Python was created in the early 1990s by Guido van Rossum at Stichting
615
+ Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
616
+ as a successor of a language called ABC. Guido remains Python's
617
+ principal author, although it includes many contributions from others.
618
+
619
+ In 1995, Guido continued his work on Python at the Corporation for
620
+ National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
621
+ in Reston, Virginia where he released several versions of the
622
+ software.
623
+
624
+ In May 2000, Guido and the Python core development team moved to
625
+ BeOpen.com to form the BeOpen PythonLabs team. In October of the same
626
+ year, the PythonLabs team moved to Digital Creations, which became
627
+ Zope Corporation. In 2001, the Python Software Foundation (PSF, see
628
+ https://www.python.org/psf/) was formed, a non-profit organization
629
+ created specifically to own Python-related Intellectual Property.
630
+ Zope Corporation was a sponsoring member of the PSF.
631
+
632
+ All Python releases are Open Source (see https://opensource.org for
633
+ the Open Source Definition). Historically, most, but not all, Python
634
+ releases have also been GPL-compatible; the table below summarizes
635
+ the various releases.
636
+
637
+ Release Derived Year Owner GPL-
638
+ from compatible? (1)
639
+
640
+ 0.9.0 thru 1.2 1991-1995 CWI yes
641
+ 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
642
+ 1.6 1.5.2 2000 CNRI no
643
+ 2.0 1.6 2000 BeOpen.com no
644
+ 1.6.1 1.6 2001 CNRI yes (2)
645
+ 2.1 2.0+1.6.1 2001 PSF no
646
+ 2.0.1 2.0+1.6.1 2001 PSF yes
647
+ 2.1.1 2.1+2.0.1 2001 PSF yes
648
+ 2.1.2 2.1.1 2002 PSF yes
649
+ 2.1.3 2.1.2 2002 PSF yes
650
+ 2.2 and above 2.1.1 2001-now PSF yes
651
+
652
+ Footnotes:
653
+
654
+ (1) GPL-compatible doesn't mean that we're distributing Python under
655
+ the GPL. All Python licenses, unlike the GPL, let you distribute
656
+ a modified version without making your changes open source. The
657
+ GPL-compatible licenses make it possible to combine Python with
658
+ other software that is released under the GPL; the others don't.
659
+
660
+ (2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
661
+ because its license has a choice of law clause. According to
662
+ CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
663
+ is "not incompatible" with the GPL.
664
+
665
+ Thanks to the many outside volunteers who have worked under Guido's
666
+ direction to make these releases possible.
667
+
668
+
669
+ B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
670
+ ===============================================================
671
+
672
+ Python software and documentation are licensed under the
673
+ Python Software Foundation License Version 2.
674
+
675
+ Starting with Python 3.8.6, examples, recipes, and other code in
676
+ the documentation are dual licensed under the PSF License Version 2
677
+ and the Zero-Clause BSD license.
678
+
679
+ Some software incorporated into Python is under different licenses.
680
+ The licenses are listed with code falling under that license.
681
+
682
+
683
+ PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
684
+ --------------------------------------------
685
+
686
+ 1. This LICENSE AGREEMENT is between the Python Software Foundation
687
+ ("PSF"), and the Individual or Organization ("Licensee") accessing and
688
+ otherwise using this software ("Python") in source or binary form and
689
+ its associated documentation.
690
+
691
+ 2. Subject to the terms and conditions of this License Agreement, PSF hereby
692
+ grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
693
+ analyze, test, perform and/or display publicly, prepare derivative works,
694
+ distribute, and otherwise use Python alone or in any derivative version,
695
+ provided, however, that PSF's License Agreement and PSF's notice of copyright,
696
+ i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
697
+ 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
698
+ All Rights Reserved" are retained in Python alone or in any derivative version
699
+ prepared by Licensee.
700
+
701
+ 3. In the event Licensee prepares a derivative work that is based on
702
+ or incorporates Python or any part thereof, and wants to make
703
+ the derivative work available to others as provided herein, then
704
+ Licensee hereby agrees to include in any such work a brief summary of
705
+ the changes made to Python.
706
+
707
+ 4. PSF is making Python available to Licensee on an "AS IS"
708
+ basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
709
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
710
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
711
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
712
+ INFRINGE ANY THIRD PARTY RIGHTS.
713
+
714
+ 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
715
+ FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
716
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
717
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
718
+
719
+ 6. This License Agreement will automatically terminate upon a material
720
+ breach of its terms and conditions.
721
+
722
+ 7. Nothing in this License Agreement shall be deemed to create any
723
+ relationship of agency, partnership, or joint venture between PSF and
724
+ Licensee. This License Agreement does not grant permission to use PSF
725
+ trademarks or trade name in a trademark sense to endorse or promote
726
+ products or services of Licensee, or any third party.
727
+
728
+ 8. By copying, installing or otherwise using Python, Licensee
729
+ agrees to be bound by the terms and conditions of this License
730
+ Agreement.
731
+
732
+
733
+ BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
734
+ -------------------------------------------
735
+
736
+ BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
737
+
738
+ 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
739
+ office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
740
+ Individual or Organization ("Licensee") accessing and otherwise using
741
+ this software in source or binary form and its associated
742
+ documentation ("the Software").
743
+
744
+ 2. Subject to the terms and conditions of this BeOpen Python License
745
+ Agreement, BeOpen hereby grants Licensee a non-exclusive,
746
+ royalty-free, world-wide license to reproduce, analyze, test, perform
747
+ and/or display publicly, prepare derivative works, distribute, and
748
+ otherwise use the Software alone or in any derivative version,
749
+ provided, however, that the BeOpen Python License is retained in the
750
+ Software, alone or in any derivative version prepared by Licensee.
751
+
752
+ 3. BeOpen is making the Software available to Licensee on an "AS IS"
753
+ basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
754
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
755
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
756
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
757
+ INFRINGE ANY THIRD PARTY RIGHTS.
758
+
759
+ 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
760
+ SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
761
+ AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
762
+ DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
763
+
764
+ 5. This License Agreement will automatically terminate upon a material
765
+ breach of its terms and conditions.
766
+
767
+ 6. This License Agreement shall be governed by and interpreted in all
768
+ respects by the law of the State of California, excluding conflict of
769
+ law provisions. Nothing in this License Agreement shall be deemed to
770
+ create any relationship of agency, partnership, or joint venture
771
+ between BeOpen and Licensee. This License Agreement does not grant
772
+ permission to use BeOpen trademarks or trade names in a trademark
773
+ sense to endorse or promote products or services of Licensee, or any
774
+ third party. As an exception, the "BeOpen Python" logos available at
775
+ http://www.pythonlabs.com/logos.html may be used according to the
776
+ permissions granted on that web page.
777
+
778
+ 7. By copying, installing or otherwise using the software, Licensee
779
+ agrees to be bound by the terms and conditions of this License
780
+ Agreement.
781
+
782
+
783
+ CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
784
+ ---------------------------------------
785
+
786
+ 1. This LICENSE AGREEMENT is between the Corporation for National
787
+ Research Initiatives, having an office at 1895 Preston White Drive,
788
+ Reston, VA 20191 ("CNRI"), and the Individual or Organization
789
+ ("Licensee") accessing and otherwise using Python 1.6.1 software in
790
+ source or binary form and its associated documentation.
791
+
792
+ 2. Subject to the terms and conditions of this License Agreement, CNRI
793
+ hereby grants Licensee a nonexclusive, royalty-free, world-wide
794
+ license to reproduce, analyze, test, perform and/or display publicly,
795
+ prepare derivative works, distribute, and otherwise use Python 1.6.1
796
+ alone or in any derivative version, provided, however, that CNRI's
797
+ License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
798
+ 1995-2001 Corporation for National Research Initiatives; All Rights
799
+ Reserved" are retained in Python 1.6.1 alone or in any derivative
800
+ version prepared by Licensee. Alternately, in lieu of CNRI's License
801
+ Agreement, Licensee may substitute the following text (omitting the
802
+ quotes): "Python 1.6.1 is made available subject to the terms and
803
+ conditions in CNRI's License Agreement. This Agreement together with
804
+ Python 1.6.1 may be located on the internet using the following
805
+ unique, persistent identifier (known as a handle): 1895.22/1013. This
806
+ Agreement may also be obtained from a proxy server on the internet
807
+ using the following URL: http://hdl.handle.net/1895.22/1013".
808
+
809
+ 3. In the event Licensee prepares a derivative work that is based on
810
+ or incorporates Python 1.6.1 or any part thereof, and wants to make
811
+ the derivative work available to others as provided herein, then
812
+ Licensee hereby agrees to include in any such work a brief summary of
813
+ the changes made to Python 1.6.1.
814
+
815
+ 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
816
+ basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
817
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
818
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
819
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
820
+ INFRINGE ANY THIRD PARTY RIGHTS.
821
+
822
+ 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
823
+ 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
824
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
825
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
826
+
827
+ 6. This License Agreement will automatically terminate upon a material
828
+ breach of its terms and conditions.
829
+
830
+ 7. This License Agreement shall be governed by the federal
831
+ intellectual property law of the United States, including without
832
+ limitation the federal copyright law, and, to the extent such
833
+ U.S. federal law does not apply, by the law of the Commonwealth of
834
+ Virginia, excluding Virginia's conflict of law provisions.
835
+ Notwithstanding the foregoing, with regard to derivative works based
836
+ on Python 1.6.1 that incorporate non-separable material that was
837
+ previously distributed under the GNU General Public License (GPL), the
838
+ law of the Commonwealth of Virginia shall govern this License
839
+ Agreement only as to issues arising under or with respect to
840
+ Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
841
+ License Agreement shall be deemed to create any relationship of
842
+ agency, partnership, or joint venture between CNRI and Licensee. This
843
+ License Agreement does not grant permission to use CNRI trademarks or
844
+ trade name in a trademark sense to endorse or promote products or
845
+ services of Licensee, or any third party.
846
+
847
+ 8. By clicking on the "ACCEPT" button where indicated, or by copying,
848
+ installing or otherwise using Python 1.6.1, Licensee agrees to be
849
+ bound by the terms and conditions of this License Agreement.
850
+
851
+ ACCEPT
852
+
853
+
854
+ CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
855
+ --------------------------------------------------
856
+
857
+ Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
858
+ The Netherlands. All rights reserved.
859
+
860
+ Permission to use, copy, modify, and distribute this software and its
861
+ documentation for any purpose and without fee is hereby granted,
862
+ provided that the above copyright notice appear in all copies and that
863
+ both that copyright notice and this permission notice appear in
864
+ supporting documentation, and that the name of Stichting Mathematisch
865
+ Centrum or CWI not be used in advertising or publicity pertaining to
866
+ distribution of the software without specific, written prior
867
+ permission.
868
+
869
+ STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
870
+ THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
871
+ FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
872
+ FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
873
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
874
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
875
+ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
876
+
877
+ ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
878
+ ----------------------------------------------------------------------
879
+
880
+ Permission to use, copy, modify, and/or distribute this software for any
881
+ purpose with or without fee is hereby granted.
882
+
883
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
884
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
885
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
886
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
887
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
888
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
889
+ PERFORMANCE OF THIS SOFTWARE.
890
+ Copyright (c) 2014, Al Sweigart
891
+ All rights reserved.
892
+
893
+ Redistribution and use in source and binary forms, with or without
894
+ modification, are permitted provided that the following conditions are met:
895
+
896
+ * Redistributions of source code must retain the above copyright notice, this
897
+ list of conditions and the following disclaimer.
898
+
899
+ * Redistributions in binary form must reproduce the above copyright notice,
900
+ this list of conditions and the following disclaimer in the documentation
901
+ and/or other materials provided with the distribution.
902
+
903
+ * Neither the name of the {organization} nor the names of its
904
+ contributors may be used to endorse or promote products derived from
905
+ this software without specific prior written permission.
906
+
907
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
908
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
909
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
910
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
911
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
912
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
913
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
914
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
915
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
916
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.Copyright (c) 2017 Anthony Sottile
917
+
918
+ Permission is hereby granted, free of charge, to any person obtaining a copy
919
+ of this software and associated documentation files (the "Software"), to deal
920
+ in the Software without restriction, including without limitation the rights
921
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
922
+ copies of the Software, and to permit persons to whom the Software is
923
+ furnished to do so, subject to the following conditions:
924
+
925
+ The above copyright notice and this permission notice shall be included in
926
+ all copies or substantial portions of the Software.
927
+
928
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
929
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
930
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
931
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
932
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
933
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
934
+ THE SOFTWARE.Copyright (c) 2015-2019 Jared Hobbs
935
+
936
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
937
+ this software and associated documentation files (the "Software"), to deal in
938
+ the Software without restriction, including without limitation the rights to
939
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
940
+ of the Software, and to permit persons to whom the Software is furnished to do
941
+ so, subject to the following conditions:
942
+
943
+ The above copyright notice and this permission notice shall be included in all
944
+ copies or substantial portions of the Software.
945
+
946
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
947
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
948
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
949
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
950
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
951
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
952
+ SOFTWARE.Developed by ESN, an Electronic Arts Inc. studio.
953
+ Copyright (c) 2014, Electronic Arts Inc.
954
+ All rights reserved.
955
+
956
+ Redistribution and use in source and binary forms, with or without
957
+ modification, are permitted provided that the following conditions are met:
958
+ * Redistributions of source code must retain the above copyright
959
+ notice, this list of conditions and the following disclaimer.
960
+ * Redistributions in binary form must reproduce the above copyright
961
+ notice, this list of conditions and the following disclaimer in the
962
+ documentation and/or other materials provided with the distribution.
963
+ * Neither the name of ESN, Electronic Arts Inc. nor the
964
+ names of its contributors may be used to endorse or promote products
965
+ derived from this software without specific prior written permission.
966
+
967
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
968
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
969
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
970
+ DISCLAIMED. IN NO EVENT SHALL ELECTRONIC ARTS INC. BE LIABLE
971
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
972
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
973
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
974
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
975
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
976
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
977
+
978
+ ----
979
+
980
+ Portions of code from MODP_ASCII - Ascii transformations (upper/lower, etc)
981
+ https://github.com/client9/stringencoders
982
+
983
+ Copyright 2005, 2006, 2007
984
+ Nick Galbreath -- nickg [at] modp [dot] com
985
+ All rights reserved.
986
+
987
+ Redistribution and use in source and binary forms, with or without
988
+ modification, are permitted provided that the following conditions are
989
+ met:
990
+
991
+ Redistributions of source code must retain the above copyright
992
+ notice, this list of conditions and the following disclaimer.
993
+
994
+ Redistributions in binary form must reproduce the above copyright
995
+ notice, this list of conditions and the following disclaimer in the
996
+ documentation and/or other materials provided with the distribution.
997
+
998
+ Neither the name of the modp.com nor the names of its
999
+ contributors may be used to endorse or promote products derived from
1000
+ this software without specific prior written permission.
1001
+
1002
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1003
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1004
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1005
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1006
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1007
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1008
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1009
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1010
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1011
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1012
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1013
+
1014
+ This is the standard "new" BSD license:
1015
+ http://www.opensource.org/licenses/bsd-license.php
1016
+
1017
+ https://github.com/client9/stringencoders/blob/cfd5c1507325ae497ea9bacdacba12c0ffd79d30/COPYING
1018
+
1019
+ ----
1020
+
1021
+ Numeric decoder derived from from TCL library
1022
+ https://opensource.apple.com/source/tcl/tcl-14/tcl/license.terms
1023
+ * Copyright (c) 1988-1993 The Regents of the University of California.
1024
+ * Copyright (c) 1994 Sun Microsystems, Inc.
1025
+
1026
+ This software is copyrighted by the Regents of the University of
1027
+ California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
1028
+ Corporation and other parties. The following terms apply to all files
1029
+ associated with the software unless explicitly disclaimed in
1030
+ individual files.
1031
+
1032
+ The authors hereby grant permission to use, copy, modify, distribute,
1033
+ and license this software and its documentation for any purpose, provided
1034
+ that existing copyright notices are retained in all copies and that this
1035
+ notice is included verbatim in any distributions. No written agreement,
1036
+ license, or royalty fee is required for any of the authorized uses.
1037
+ Modifications to this software may be copyrighted by their authors
1038
+ and need not follow the licensing terms described here, provided that
1039
+ the new terms are clearly indicated on the first page of each file where
1040
+ they apply.
1041
+
1042
+ IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
1043
+ FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
1044
+ ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
1045
+ DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
1046
+ POSSIBILITY OF SUCH DAMAGE.
1047
+
1048
+ THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
1049
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
1050
+ FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
1051
+ IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
1052
+ NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
1053
+ MODIFICATIONS.
1054
+
1055
+ GOVERNMENT USE: If you are acquiring this software on behalf of the
1056
+ U.S. government, the Government shall have only "Restricted Rights"
1057
+ in the software and related documentation as defined in the Federal
1058
+ Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
1059
+ are acquiring the software on behalf of the Department of Defense, the
1060
+ software shall be classified as "Commercial Computer Software" and the
1061
+ Government shall have only "Restricted Rights" as defined in Clause
1062
+ 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the
1063
+ authors grant the U.S. Government and others acting in its behalf
1064
+ permission to use and distribute the software in accordance with the
1065
+ terms specified in this license.
1066
+ Classifier: Development Status :: 5 - Production/Stable
1067
+ Classifier: Environment :: Console
1068
+ Classifier: Intended Audience :: Science/Research
1069
+ Classifier: License :: OSI Approved :: BSD License
1070
+ Classifier: Operating System :: OS Independent
1071
+ Classifier: Programming Language :: Cython
1072
+ Classifier: Programming Language :: Python
1073
+ Classifier: Programming Language :: Python :: 3
1074
+ Classifier: Programming Language :: Python :: 3 :: Only
1075
+ Classifier: Programming Language :: Python :: 3.11
1076
+ Classifier: Programming Language :: Python :: 3.12
1077
+ Classifier: Programming Language :: Python :: 3.13
1078
+ Classifier: Programming Language :: Python :: 3.14
1079
+ Classifier: Topic :: Scientific/Engineering
1080
+ Project-URL: homepage, https://pandas.pydata.org
1081
+ Project-URL: documentation, https://pandas.pydata.org/docs/
1082
+ Project-URL: repository, https://github.com/pandas-dev/pandas
1083
+ Requires-Python: >=3.11
1084
+ Requires-Dist: numpy>=1.26.0; python_version < "3.14"
1085
+ Requires-Dist: numpy>=2.3.3; python_version >= "3.14"
1086
+ Requires-Dist: python-dateutil>=2.8.2
1087
+ Requires-Dist: tzdata; sys_platform == "win32"
1088
+ Requires-Dist: tzdata; sys_platform == "emscripten"
1089
+ Provides-Extra: test
1090
+ Requires-Dist: hypothesis>=6.116.0; extra == "test"
1091
+ Requires-Dist: pytest<9.1,>=8.3.4; extra == "test"
1092
+ Requires-Dist: pytest-xdist>=3.6.1; extra == "test"
1093
+ Provides-Extra: pyarrow
1094
+ Requires-Dist: pyarrow>=13.0.0; extra == "pyarrow"
1095
+ Provides-Extra: performance
1096
+ Requires-Dist: bottleneck>=1.4.2; extra == "performance"
1097
+ Requires-Dist: numba>=0.60.0; extra == "performance"
1098
+ Requires-Dist: numexpr>=2.10.2; extra == "performance"
1099
+ Provides-Extra: computation
1100
+ Requires-Dist: scipy>=1.14.1; extra == "computation"
1101
+ Requires-Dist: xarray>=2024.10.0; extra == "computation"
1102
+ Provides-Extra: fss
1103
+ Requires-Dist: fsspec>=2024.10.0; extra == "fss"
1104
+ Provides-Extra: aws
1105
+ Requires-Dist: s3fs>=2024.10.0; extra == "aws"
1106
+ Provides-Extra: gcp
1107
+ Requires-Dist: gcsfs>=2024.10.0; extra == "gcp"
1108
+ Provides-Extra: excel
1109
+ Requires-Dist: odfpy>=1.4.1; extra == "excel"
1110
+ Requires-Dist: openpyxl>=3.1.5; extra == "excel"
1111
+ Requires-Dist: python-calamine>=0.3.0; extra == "excel"
1112
+ Requires-Dist: pyxlsb>=1.0.10; extra == "excel"
1113
+ Requires-Dist: xlrd>=2.0.1; extra == "excel"
1114
+ Requires-Dist: xlsxwriter>=3.2.0; extra == "excel"
1115
+ Provides-Extra: parquet
1116
+ Requires-Dist: pyarrow>=13.0.0; extra == "parquet"
1117
+ Provides-Extra: feather
1118
+ Requires-Dist: pyarrow>=13.0.0; extra == "feather"
1119
+ Provides-Extra: iceberg
1120
+ Requires-Dist: pyiceberg>=0.8.1; extra == "iceberg"
1121
+ Provides-Extra: hdf5
1122
+ Requires-Dist: tables>=3.10.1; extra == "hdf5"
1123
+ Provides-Extra: spss
1124
+ Requires-Dist: pyreadstat>=1.2.8; extra == "spss"
1125
+ Provides-Extra: postgresql
1126
+ Requires-Dist: SQLAlchemy>=2.0.36; extra == "postgresql"
1127
+ Requires-Dist: psycopg2>=2.9.10; extra == "postgresql"
1128
+ Requires-Dist: adbc-driver-postgresql>=1.2.0; extra == "postgresql"
1129
+ Provides-Extra: mysql
1130
+ Requires-Dist: SQLAlchemy>=2.0.36; extra == "mysql"
1131
+ Requires-Dist: pymysql>=1.1.1; extra == "mysql"
1132
+ Provides-Extra: sql-other
1133
+ Requires-Dist: SQLAlchemy>=2.0.36; extra == "sql-other"
1134
+ Requires-Dist: adbc-driver-postgresql>=1.2.0; extra == "sql-other"
1135
+ Requires-Dist: adbc-driver-sqlite>=1.2.0; extra == "sql-other"
1136
+ Provides-Extra: html
1137
+ Requires-Dist: beautifulsoup4>=4.12.3; extra == "html"
1138
+ Requires-Dist: html5lib>=1.1; extra == "html"
1139
+ Requires-Dist: lxml>=5.3.0; extra == "html"
1140
+ Provides-Extra: xml
1141
+ Requires-Dist: lxml>=5.3.0; extra == "xml"
1142
+ Provides-Extra: plot
1143
+ Requires-Dist: matplotlib>=3.9.3; extra == "plot"
1144
+ Provides-Extra: output-formatting
1145
+ Requires-Dist: jinja2>=3.1.5; extra == "output-formatting"
1146
+ Requires-Dist: tabulate>=0.9.0; extra == "output-formatting"
1147
+ Provides-Extra: clipboard
1148
+ Requires-Dist: PyQt5>=5.15.9; extra == "clipboard"
1149
+ Requires-Dist: qtpy>=2.4.2; extra == "clipboard"
1150
+ Provides-Extra: compression
1151
+ Requires-Dist: zstandard>=0.23.0; extra == "compression"
1152
+ Provides-Extra: timezone
1153
+ Requires-Dist: pytz>=2020.1; extra == "timezone"
1154
+ Provides-Extra: all
1155
+ Requires-Dist: adbc-driver-postgresql>=1.2.0; extra == "all"
1156
+ Requires-Dist: adbc-driver-sqlite>=1.2.0; extra == "all"
1157
+ Requires-Dist: beautifulsoup4>=4.12.3; extra == "all"
1158
+ Requires-Dist: bottleneck>=1.4.2; extra == "all"
1159
+ Requires-Dist: fastparquet>=2024.11.0; extra == "all"
1160
+ Requires-Dist: fsspec>=2024.10.0; extra == "all"
1161
+ Requires-Dist: gcsfs>=2024.10.0; extra == "all"
1162
+ Requires-Dist: html5lib>=1.1; extra == "all"
1163
+ Requires-Dist: hypothesis>=6.116.0; extra == "all"
1164
+ Requires-Dist: jinja2>=3.1.5; extra == "all"
1165
+ Requires-Dist: lxml>=5.3.0; extra == "all"
1166
+ Requires-Dist: matplotlib>=3.9.3; extra == "all"
1167
+ Requires-Dist: numba>=0.60.0; extra == "all"
1168
+ Requires-Dist: numexpr>=2.10.2; extra == "all"
1169
+ Requires-Dist: odfpy>=1.4.1; extra == "all"
1170
+ Requires-Dist: openpyxl>=3.1.5; extra == "all"
1171
+ Requires-Dist: psycopg2>=2.9.10; extra == "all"
1172
+ Requires-Dist: pyarrow>=13.0.0; extra == "all"
1173
+ Requires-Dist: pyiceberg>=0.8.1; extra == "all"
1174
+ Requires-Dist: pymysql>=1.1.1; extra == "all"
1175
+ Requires-Dist: PyQt5>=5.15.9; extra == "all"
1176
+ Requires-Dist: pyreadstat>=1.2.8; extra == "all"
1177
+ Requires-Dist: pytest>=8.3.4; extra == "all"
1178
+ Requires-Dist: pytest-xdist>=3.6.1; extra == "all"
1179
+ Requires-Dist: python-calamine>=0.3.0; extra == "all"
1180
+ Requires-Dist: pytz>=2020.1; extra == "all"
1181
+ Requires-Dist: pyxlsb>=1.0.10; extra == "all"
1182
+ Requires-Dist: qtpy>=2.4.2; extra == "all"
1183
+ Requires-Dist: scipy>=1.14.1; extra == "all"
1184
+ Requires-Dist: s3fs>=2024.10.0; extra == "all"
1185
+ Requires-Dist: SQLAlchemy>=2.0.36; extra == "all"
1186
+ Requires-Dist: tables>=3.10.1; extra == "all"
1187
+ Requires-Dist: tabulate>=0.9.0; extra == "all"
1188
+ Requires-Dist: xarray>=2024.10.0; extra == "all"
1189
+ Requires-Dist: xlrd>=2.0.1; extra == "all"
1190
+ Requires-Dist: xlsxwriter>=3.2.0; extra == "all"
1191
+ Requires-Dist: zstandard>=0.23.0; extra == "all"
1192
+ Description-Content-Type: text/markdown
1193
+
1194
+ <picture align="center">
1195
+ <source media="(prefers-color-scheme: dark)" srcset="https://pandas.pydata.org/static/img/pandas_white.svg">
1196
+ <img alt="Pandas Logo" src="https://pandas.pydata.org/static/img/pandas.svg">
1197
+ </picture>
1198
+
1199
+ -----------------
1200
+
1201
+ # pandas: A Powerful Python Data Analysis Toolkit
1202
+
1203
+ | | |
1204
+ | --- | --- |
1205
+ | Testing | [![CI - Test](https://github.com/pandas-dev/pandas/actions/workflows/unit-tests.yml/badge.svg)](https://github.com/pandas-dev/pandas/actions/workflows/unit-tests.yml) [![Coverage](https://codecov.io/github/pandas-dev/pandas/coverage.svg?branch=main)](https://codecov.io/gh/pandas-dev/pandas) |
1206
+ | Package | [![PyPI Latest Release](https://img.shields.io/pypi/v/pandas.svg)](https://pypi.org/project/pandas/) [![PyPI Downloads](https://img.shields.io/pypi/dm/pandas.svg?label=PyPI%20downloads)](https://pypi.org/project/pandas/) [![Conda Latest Release](https://anaconda.org/conda-forge/pandas/badges/version.svg)](https://anaconda.org/conda-forge/pandas) [![Conda Downloads](https://img.shields.io/conda/dn/conda-forge/pandas.svg?label=Conda%20downloads)](https://anaconda.org/conda-forge/pandas) |
1207
+ | Meta | [![Powered by NumFOCUS](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](https://numfocus.org) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3509134.svg)](https://doi.org/10.5281/zenodo.3509134) [![License - BSD 3-Clause](https://img.shields.io/pypi/l/pandas.svg)](https://github.com/pandas-dev/pandas/blob/main/LICENSE) [![Slack](https://img.shields.io/badge/join_Slack-information-brightgreen.svg?logo=slack)](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) [![LFX Health Score](https://insights.linuxfoundation.org/api/badge/health-score?project=pandas-dev-pandas)](https://insights.linuxfoundation.org/project/pandas-dev-pandas) |
1208
+
1209
+
1210
+ ## What is it?
1211
+
1212
+ **pandas** is a Python package that provides fast, flexible, and expressive data
1213
+ structures designed to make working with "relational" or "labeled" data both
1214
+ easy and intuitive. It aims to be the fundamental high-level building block for
1215
+ doing practical, **real-world** data analysis in Python. Additionally, it has
1216
+ the broader goal of becoming **the most powerful and flexible open-source data
1217
+ analysis/manipulation tool available in any language**. It is already well on
1218
+ its way towards this goal.
1219
+
1220
+ ## Table of Contents
1221
+
1222
+ - [Main Features](#main-features)
1223
+ - [Where to get it](#where-to-get-it)
1224
+ - [Dependencies](#dependencies)
1225
+ - [Installation from sources](#installation-from-sources)
1226
+ - [License](#license)
1227
+ - [Documentation](#documentation)
1228
+ - [Background](#background)
1229
+ - [Getting Help](#getting-help)
1230
+ - [Discussion and Development](#discussion-and-development)
1231
+ - [Contributing to pandas](#contributing-to-pandas)
1232
+
1233
+ ## Main Features
1234
+ Here are just a few of the things that pandas does well:
1235
+
1236
+ - Easy handling of [**missing data**][missing-data] (represented as
1237
+ `NaN`, `NA`, or `NaT`) in floating point as well as non-floating point data
1238
+ - Size mutability: columns can be [**inserted and
1239
+ deleted**][insertion-deletion] from DataFrame and higher dimensional
1240
+ objects
1241
+ - Automatic and explicit [**data alignment**][alignment]: objects can
1242
+ be explicitly aligned to a set of labels, or the user can simply
1243
+ ignore the labels and let `Series`, `DataFrame`, etc. automatically
1244
+ align the data for you in computations
1245
+ - Powerful, flexible [**group by**][groupby] functionality to perform
1246
+ split-apply-combine operations on data sets, for both aggregating
1247
+ and transforming data
1248
+ - Make it [**easy to convert**][conversion] ragged,
1249
+ differently-indexed data in other Python and NumPy data structures
1250
+ into DataFrame objects
1251
+ - Intelligent label-based [**slicing**][slicing], [**fancy
1252
+ indexing**][fancy-indexing], and [**subsetting**][subsetting] of
1253
+ large data sets
1254
+ - Intuitive [**merging**][merging] and [**joining**][joining] data
1255
+ sets
1256
+ - Flexible [**reshaping**][reshape] and [**pivoting**][pivot-table] of
1257
+ data sets
1258
+ - [**Hierarchical**][mi] labeling of axes (possible to have multiple
1259
+ labels per tick)
1260
+ - Robust I/O tools for loading data from [**flat files**][flat-files]
1261
+ (CSV and delimited), [**Excel files**][excel], [**databases**][db],
1262
+ and saving/loading data from the ultrafast [**HDF5 format**][hdfstore]
1263
+ - [**Time series**][timeseries]-specific functionality: date range
1264
+ generation and frequency conversion, moving window statistics,
1265
+ date shifting and lagging
1266
+
1267
+
1268
+ [missing-data]: https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html
1269
+ [insertion-deletion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#column-selection-addition-deletion
1270
+ [alignment]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html?highlight=alignment#intro-to-data-structures
1271
+ [groupby]: https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#group-by-split-apply-combine
1272
+ [conversion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#dataframe
1273
+ [slicing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#slicing-ranges
1274
+ [fancy-indexing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced
1275
+ [subsetting]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing
1276
+ [merging]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#database-style-dataframe-or-named-series-joining-merging
1277
+ [joining]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#joining-on-index
1278
+ [reshape]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html
1279
+ [pivot-table]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html
1280
+ [mi]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#hierarchical-indexing-multiindex
1281
+ [flat-files]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#csv-text-files
1282
+ [excel]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#excel-files
1283
+ [db]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#sql-queries
1284
+ [hdfstore]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#hdf5-pytables
1285
+ [timeseries]: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#time-series-date-functionality
1286
+
1287
+ ## Where to get it
1288
+ The source code is currently hosted on GitHub at:
1289
+ https://github.com/pandas-dev/pandas
1290
+
1291
+ Binary installers for the latest released version are available at the [Python
1292
+ Package Index (PyPI)](https://pypi.org/project/pandas) and on [Conda](https://anaconda.org/conda-forge/pandas).
1293
+
1294
+ ```sh
1295
+ # conda
1296
+ conda install -c conda-forge pandas
1297
+ ```
1298
+
1299
+ ```sh
1300
+ # or PyPI
1301
+ pip install pandas
1302
+ ```
1303
+
1304
+ The list of changes to pandas between each release can be found
1305
+ [here](https://pandas.pydata.org/pandas-docs/stable/whatsnew/index.html). For full
1306
+ details, see the commit logs at https://github.com/pandas-dev/pandas.
1307
+
1308
+ ## Dependencies
1309
+ - [NumPy - Adds support for large, multi-dimensional arrays, matrices and high-level mathematical functions to operate on these arrays](https://www.numpy.org)
1310
+ - [python-dateutil - Provides powerful extensions to the standard datetime module](https://dateutil.readthedocs.io/en/stable/index.html)
1311
+ - [tzdata - Provides an IANA time zone database](https://tzdata.readthedocs.io/en/latest/) (Only required on Windows/Emscripten)
1312
+
1313
+ 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.
1314
+
1315
+ ## Installation from sources
1316
+ To install pandas from source you need [Cython](https://cython.org/) in addition to the normal
1317
+ dependencies above. Cython can be installed from PyPI:
1318
+
1319
+ ```sh
1320
+ pip install cython
1321
+ ```
1322
+
1323
+ In the `pandas` directory (same one where you found this file after
1324
+ cloning the git repo), execute:
1325
+
1326
+ ```sh
1327
+ pip install .
1328
+ ```
1329
+
1330
+ or for installing in [development mode](https://pip.pypa.io/en/latest/cli/pip_install/#install-editable):
1331
+
1332
+
1333
+ ```sh
1334
+ python -m pip install -ve . --no-build-isolation --config-settings editable-verbose=true
1335
+ ```
1336
+
1337
+ See the full instructions for [installing from source](https://pandas.pydata.org/docs/dev/development/contributing_environment.html).
1338
+
1339
+ ## License
1340
+ [BSD 3](LICENSE)
1341
+
1342
+ ## Documentation
1343
+ The official documentation is hosted on [PyData.org](https://pandas.pydata.org/pandas-docs/stable/).
1344
+
1345
+ ## Background
1346
+ Work on ``pandas`` started at [AQR](https://www.aqr.com/) (a quantitative hedge fund) in 2008 and
1347
+ has been under active development since then.
1348
+
1349
+ ## Getting Help
1350
+
1351
+ For usage questions, the best place to go to is [Stack Overflow](https://stackoverflow.com/questions/tagged/pandas).
1352
+ Further, general questions and discussions can also take place on the [pydata mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata).
1353
+
1354
+ ## Discussion and Development
1355
+ Most development discussions take place on GitHub in this repo, via the [GitHub issue tracker](https://github.com/pandas-dev/pandas/issues).
1356
+
1357
+ 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.
1358
+
1359
+ 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.
1360
+
1361
+ Additional information on the communication channels can be found on the [contributor community](https://pandas.pydata.org/docs/development/community.html) page.
1362
+
1363
+ ## Contributing to pandas
1364
+
1365
+ [![Open Source Helpers](https://www.codetriage.com/pandas-dev/pandas/badges/users.svg)](https://www.codetriage.com/pandas-dev/pandas)
1366
+
1367
+ All contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome.
1368
+
1369
+ A detailed overview on how to contribute can be found in the **[contributing guide](https://pandas.pydata.org/docs/dev/development/contributing.html)**.
1370
+
1371
+ 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.
1372
+
1373
+ 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).
1374
+
1375
+ 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!
1376
+
1377
+ 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).
1378
+
1379
+ 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)
1380
+
1381
+ <hr>
1382
+
1383
+ [Go to Top](#table-of-contents)
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/REQUESTED ADDED
File without changes
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: meson
3
+ Root-Is-Purelib: false
4
+ Tag: cp312-cp312-manylinux_2_24_x86_64
5
+ Tag: cp312-cp312-manylinux_2_28_x86_64
6
+
couto/12yd/.venv/lib/python3.12/site-packages/pandas-3.0.4.dist-info/entry_points.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [pandas_plotting_backends]
2
+ matplotlib = pandas:plotting._matplotlib
3
+
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_formats.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ datetime,
3
+ timedelta,
4
+ )
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ import pandas as pd
10
+ from pandas import (
11
+ Categorical,
12
+ DataFrame,
13
+ Index,
14
+ Series,
15
+ date_range,
16
+ option_context,
17
+ period_range,
18
+ timedelta_range,
19
+ )
20
+
21
+
22
+ class TestSeriesRepr:
23
+ def test_multilevel_name_print_0(self):
24
+ # GH#55415 None does not get printed, but 0 does
25
+ # (matching DataFrame and flat index behavior)
26
+ mi = pd.MultiIndex.from_product([range(2, 3), range(3, 4)], names=[0, None])
27
+ ser = Series(1.5, index=mi)
28
+
29
+ res = repr(ser)
30
+ expected = "0 \n2 3 1.5\ndtype: float64"
31
+ assert res == expected
32
+
33
+ def test_multilevel_name_print(self, lexsorted_two_level_string_multiindex):
34
+ index = lexsorted_two_level_string_multiindex
35
+ ser = Series(range(len(index)), index=index, name="sth")
36
+ expected = [
37
+ "first second",
38
+ "foo one 0",
39
+ " two 1",
40
+ " three 2",
41
+ "bar one 3",
42
+ " two 4",
43
+ "baz two 5",
44
+ " three 6",
45
+ "qux one 7",
46
+ " two 8",
47
+ " three 9",
48
+ "Name: sth, dtype: int64",
49
+ ]
50
+ expected = "\n".join(expected)
51
+ assert repr(ser) == expected
52
+
53
+ def test_small_name_printing(self):
54
+ # Test small Series.
55
+ s = Series([0, 1, 2])
56
+
57
+ s.name = "test"
58
+ assert "Name: test" in repr(s)
59
+
60
+ s.name = None
61
+ assert "Name:" not in repr(s)
62
+
63
+ def test_big_name_printing(self):
64
+ # Test big Series (diff code path).
65
+ s = Series(range(1000))
66
+
67
+ s.name = "test"
68
+ assert "Name: test" in repr(s)
69
+
70
+ s.name = None
71
+ assert "Name:" not in repr(s)
72
+
73
+ def test_empty_name_printing(self):
74
+ s = Series(index=date_range("20010101", "20020101"), name="test", dtype=object)
75
+ assert "Name: test" in repr(s)
76
+
77
+ @pytest.mark.parametrize("args", [(), (0, -1)])
78
+ def test_float_range(self, args):
79
+ str(
80
+ Series(
81
+ np.random.default_rng(2).standard_normal(1000),
82
+ index=np.arange(1000, *args),
83
+ )
84
+ )
85
+
86
+ def test_empty_object(self):
87
+ # empty
88
+ str(Series(dtype=object))
89
+
90
+ def test_string(self, string_series):
91
+ str(string_series)
92
+ str(string_series.astype(int))
93
+
94
+ # with NaNs
95
+ string_series[5:7] = np.nan
96
+ str(string_series)
97
+
98
+ def test_object(self, object_series):
99
+ str(object_series)
100
+
101
+ def test_datetime(self, datetime_series):
102
+ str(datetime_series)
103
+ # with Nones
104
+ ots = datetime_series.astype("O")
105
+ ots[::2] = None
106
+ repr(ots)
107
+
108
+ @pytest.mark.parametrize(
109
+ "name",
110
+ [
111
+ "",
112
+ 1,
113
+ 1.2,
114
+ "foo",
115
+ "\u03b1\u03b2\u03b3",
116
+ "loooooooooooooooooooooooooooooooooooooooooooooooooooong",
117
+ ("foo", "bar", "baz"),
118
+ (1, 2),
119
+ ("foo", 1, 2.3),
120
+ ("\u03b1", "\u03b2", "\u03b3"),
121
+ ("\u03b1", "bar"),
122
+ ],
123
+ )
124
+ def test_various_names(self, name, string_series):
125
+ # various names
126
+ string_series.name = name
127
+ repr(string_series)
128
+
129
+ def test_tuple_name(self):
130
+ biggie = Series(
131
+ np.random.default_rng(2).standard_normal(1000),
132
+ index=np.arange(1000),
133
+ name=("foo", "bar", "baz"),
134
+ )
135
+ repr(biggie)
136
+
137
+ @pytest.mark.parametrize("arg", [100, 1001])
138
+ def test_tidy_repr_name_0(self, arg):
139
+ # tidy repr
140
+ ser = Series(np.random.default_rng(2).standard_normal(arg), name=0)
141
+ rep_str = repr(ser)
142
+ assert "Name: 0" in rep_str
143
+
144
+ def test_newline(self, any_string_dtype):
145
+ ser = Series(
146
+ ["a\n\r\tb"],
147
+ name="a\n\r\td",
148
+ index=Index(["a\n\r\tf"], dtype=any_string_dtype),
149
+ dtype=any_string_dtype,
150
+ )
151
+ assert "\t" not in repr(ser)
152
+ assert "\r" not in repr(ser)
153
+ assert "a\n" not in repr(ser)
154
+
155
+ @pytest.mark.parametrize(
156
+ "name, expected",
157
+ [
158
+ ["foo", "Series([], Name: foo, dtype: int64)"],
159
+ [None, "Series([], dtype: int64)"],
160
+ ],
161
+ )
162
+ def test_empty_int64(self, name, expected):
163
+ # with empty series (#4651)
164
+ s = Series([], dtype=np.int64, name=name)
165
+ assert repr(s) == expected
166
+
167
+ def test_repr_bool_fails(self, capsys):
168
+ s = Series(
169
+ [
170
+ DataFrame(np.random.default_rng(2).standard_normal((2, 2)))
171
+ for i in range(5)
172
+ ]
173
+ )
174
+
175
+ # It works (with no Cython exception barf)!
176
+ repr(s)
177
+
178
+ captured = capsys.readouterr()
179
+ assert captured.err == ""
180
+
181
+ def test_repr_name_iterable_indexable(self):
182
+ s = Series([1, 2, 3], name=np.int64(3))
183
+
184
+ # it works!
185
+ repr(s)
186
+
187
+ s.name = ("\u05d0",) * 2
188
+ repr(s)
189
+
190
+ def test_repr_max_rows(self):
191
+ # GH 6863
192
+ with option_context("display.max_rows", None):
193
+ str(Series(range(1001))) # should not raise exception
194
+
195
+ def test_unicode_string_with_unicode(self):
196
+ df = Series(["\u05d0"], name="\u05d1")
197
+ str(df)
198
+
199
+ ser = Series(["\u03c3"] * 10)
200
+ repr(ser)
201
+
202
+ ser2 = Series(["\u05d0"] * 1000)
203
+ ser2.name = "title1"
204
+ repr(ser2)
205
+
206
+ def test_str_to_bytes_raises(self):
207
+ # GH 26447
208
+ df = Series(["abc"], name="abc")
209
+ msg = "^'str' object cannot be interpreted as an integer$"
210
+ with pytest.raises(TypeError, match=msg):
211
+ bytes(df)
212
+
213
+ def test_timeseries_repr_object_dtype(self):
214
+ index = Index(
215
+ [datetime(2000, 1, 1) + timedelta(i) for i in range(1000)], dtype=object
216
+ )
217
+ ts = Series(np.random.default_rng(2).standard_normal(len(index)), index)
218
+ repr(ts)
219
+
220
+ ts = Series(
221
+ np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20)
222
+ )
223
+ assert repr(ts).splitlines()[-1].startswith("Freq:")
224
+
225
+ ts2 = ts.iloc[np.random.default_rng(2).integers(0, len(ts) - 1, 400)]
226
+ repr(ts2).splitlines()[-1]
227
+
228
+ def test_latex_repr(self):
229
+ pytest.importorskip("jinja2") # uses Styler implementation
230
+ result = r"""\begin{tabular}{ll}
231
+ \toprule
232
+ & 0 \\
233
+ \midrule
234
+ 0 & $\alpha$ \\
235
+ 1 & b \\
236
+ 2 & c \\
237
+ \bottomrule
238
+ \end{tabular}
239
+ """
240
+ with option_context(
241
+ "styler.format.escape", None, "styler.render.repr", "latex"
242
+ ):
243
+ s = Series([r"$\alpha$", "b", "c"])
244
+ assert result == s._repr_latex_()
245
+
246
+ assert s._repr_latex_() is None
247
+
248
+ def test_index_repr_in_frame_with_nan(self):
249
+ # see gh-25061
250
+ i = Index([1, np.nan])
251
+ s = Series([1, 2], index=i)
252
+ exp = """1.0 1\nNaN 2\ndtype: int64"""
253
+
254
+ assert repr(s) == exp
255
+
256
+ def test_series_repr_nat(self):
257
+ series = Series([0, 1000, 2000, pd.NaT._value], dtype="M8[ns]")
258
+
259
+ result = repr(series)
260
+ expected = (
261
+ "0 1970-01-01 00:00:00.000000\n"
262
+ "1 1970-01-01 00:00:00.000001\n"
263
+ "2 1970-01-01 00:00:00.000002\n"
264
+ "3 NaT\n"
265
+ "dtype: datetime64[ns]"
266
+ )
267
+ assert result == expected
268
+
269
+ def test_float_repr(self):
270
+ # GH#35603
271
+ # check float format when cast to object
272
+ ser = Series([1.0]).astype(object)
273
+ expected = "0 1.0\ndtype: object"
274
+ assert repr(ser) == expected
275
+
276
+ def test_different_null_objects(self):
277
+ # GH#45263
278
+ ser = Series([1, 2, 3, 4], [True, None, np.nan, pd.NaT])
279
+ result = repr(ser)
280
+ expected = "True 1\nNone 2\nNaN 3\nNaT 4\ndtype: int64"
281
+ assert result == expected
282
+
283
+ def test_2d_extension_type(self):
284
+ # GH#33770
285
+
286
+ # Define a stub extension type with just enough code to run Series.__repr__()
287
+ class DtypeStub(pd.api.extensions.ExtensionDtype):
288
+ @property
289
+ def type(self):
290
+ return np.ndarray
291
+
292
+ @property
293
+ def name(self):
294
+ return "DtypeStub"
295
+
296
+ class ExtTypeStub(pd.api.extensions.ExtensionArray):
297
+ def __len__(self) -> int:
298
+ return 2
299
+
300
+ def __getitem__(self, ix):
301
+ return [ix == 1, ix == 0]
302
+
303
+ @property
304
+ def dtype(self):
305
+ return DtypeStub()
306
+
307
+ series = Series(ExtTypeStub(), copy=False)
308
+ res = repr(series) # This line crashed before GH#33770 was fixed.
309
+ expected = "\n".join(
310
+ ["0 [False True]", "1 [True False]", "dtype: DtypeStub"]
311
+ )
312
+ assert res == expected
313
+
314
+
315
+ class TestCategoricalRepr:
316
+ def test_categorical_repr_unicode(self):
317
+ # see gh-21002
318
+
319
+ class County:
320
+ name = "San Sebastián"
321
+ state = "PR"
322
+
323
+ def __repr__(self) -> str:
324
+ return self.name + ", " + self.state
325
+
326
+ cat = Categorical([County() for _ in range(61)])
327
+ idx = Index(cat)
328
+ ser = idx.to_series()
329
+
330
+ repr(ser)
331
+ str(ser)
332
+
333
+ def test_categorical_repr(self, using_infer_string):
334
+ a = Series(Categorical([1, 2, 3, 4]))
335
+ exp = (
336
+ "0 1\n1 2\n2 3\n3 4\n"
337
+ "dtype: category\nCategories (4, int64): [1, 2, 3, 4]"
338
+ )
339
+
340
+ assert exp == a.__str__()
341
+
342
+ a = Series(Categorical(["a", "b"] * 25))
343
+ exp = (
344
+ "0 a\n1 b\n"
345
+ " ..\n"
346
+ "48 a\n49 b\n"
347
+ "Length: 50, dtype: category\nCategories (2, object): ['a', 'b']"
348
+ )
349
+ if using_infer_string:
350
+ exp = exp.replace("object", "str")
351
+ with option_context("display.max_rows", 5):
352
+ assert exp == repr(a)
353
+
354
+ levs = list("abcdefghijklmnopqrstuvwxyz")
355
+ a = Series(Categorical(["a", "b"], categories=levs, ordered=True))
356
+ exp = (
357
+ "0 a\n1 b\n"
358
+ "dtype: category\n"
359
+ "Categories (26, object): ['a' < 'b' < 'c' < 'd' ... "
360
+ "'w' < 'x' < 'y' < 'z']"
361
+ )
362
+ if using_infer_string:
363
+ exp = exp.replace("object", "str")
364
+ assert exp == a.__str__()
365
+
366
+ def test_categorical_series_repr(self):
367
+ s = Series(Categorical([1, 2, 3]))
368
+ exp = """0 1
369
+ 1 2
370
+ 2 3
371
+ dtype: category
372
+ Categories (3, int64): [1, 2, 3]"""
373
+
374
+ assert repr(s) == exp
375
+
376
+ s = Series(Categorical(np.arange(10)))
377
+ exp = f"""0 0
378
+ 1 1
379
+ 2 2
380
+ 3 3
381
+ 4 4
382
+ 5 5
383
+ 6 6
384
+ 7 7
385
+ 8 8
386
+ 9 9
387
+ dtype: category
388
+ Categories (10, {np.dtype(int)}): [0, 1, 2, 3, ..., 6, 7, 8, 9]"""
389
+
390
+ assert repr(s) == exp
391
+
392
+ def test_categorical_series_repr_ordered(self):
393
+ s = Series(Categorical([1, 2, 3], ordered=True))
394
+ exp = """0 1
395
+ 1 2
396
+ 2 3
397
+ dtype: category
398
+ Categories (3, int64): [1 < 2 < 3]"""
399
+
400
+ assert repr(s) == exp
401
+
402
+ s = Series(Categorical(np.arange(10), ordered=True))
403
+ exp = f"""0 0
404
+ 1 1
405
+ 2 2
406
+ 3 3
407
+ 4 4
408
+ 5 5
409
+ 6 6
410
+ 7 7
411
+ 8 8
412
+ 9 9
413
+ dtype: category
414
+ Categories (10, {np.dtype(int)}): [0 < 1 < 2 < 3 ... 6 < 7 < 8 < 9]"""
415
+
416
+ assert repr(s) == exp
417
+
418
+ def test_categorical_series_repr_datetime(self):
419
+ idx = date_range("2011-01-01 09:00", freq="h", periods=5, unit="ns")
420
+ s = Series(Categorical(idx))
421
+ exp = """0 2011-01-01 09:00:00
422
+ 1 2011-01-01 10:00:00
423
+ 2 2011-01-01 11:00:00
424
+ 3 2011-01-01 12:00:00
425
+ 4 2011-01-01 13:00:00
426
+ dtype: category
427
+ Categories (5, datetime64[ns]): [2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00,
428
+ 2011-01-01 12:00:00, 2011-01-01 13:00:00]""" # noqa: E501
429
+
430
+ assert repr(s) == exp
431
+
432
+ idx = date_range(
433
+ "2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern", unit="ns"
434
+ )
435
+ s = Series(Categorical(idx))
436
+ exp = """0 2011-01-01 09:00:00-05:00
437
+ 1 2011-01-01 10:00:00-05:00
438
+ 2 2011-01-01 11:00:00-05:00
439
+ 3 2011-01-01 12:00:00-05:00
440
+ 4 2011-01-01 13:00:00-05:00
441
+ dtype: category
442
+ Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,
443
+ 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,
444
+ 2011-01-01 13:00:00-05:00]""" # noqa: E501
445
+
446
+ assert repr(s) == exp
447
+
448
+ def test_categorical_series_repr_datetime_ordered(self):
449
+ idx = date_range("2011-01-01 09:00", freq="h", periods=5, unit="ns")
450
+ s = Series(Categorical(idx, ordered=True))
451
+ exp = """0 2011-01-01 09:00:00
452
+ 1 2011-01-01 10:00:00
453
+ 2 2011-01-01 11:00:00
454
+ 3 2011-01-01 12:00:00
455
+ 4 2011-01-01 13:00:00
456
+ dtype: category
457
+ Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
458
+ 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
459
+
460
+ assert repr(s) == exp
461
+
462
+ idx = date_range(
463
+ "2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern", unit="ns"
464
+ )
465
+ s = Series(Categorical(idx, ordered=True))
466
+ exp = """0 2011-01-01 09:00:00-05:00
467
+ 1 2011-01-01 10:00:00-05:00
468
+ 2 2011-01-01 11:00:00-05:00
469
+ 3 2011-01-01 12:00:00-05:00
470
+ 4 2011-01-01 13:00:00-05:00
471
+ dtype: category
472
+ Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
473
+ 2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
474
+ 2011-01-01 13:00:00-05:00]""" # noqa: E501
475
+
476
+ assert repr(s) == exp
477
+
478
+ def test_categorical_series_repr_period(self):
479
+ idx = period_range("2011-01-01 09:00", freq="h", periods=5)
480
+ s = Series(Categorical(idx))
481
+ exp = """0 2011-01-01 09:00
482
+ 1 2011-01-01 10:00
483
+ 2 2011-01-01 11:00
484
+ 3 2011-01-01 12:00
485
+ 4 2011-01-01 13:00
486
+ dtype: category
487
+ Categories (5, period[h]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
488
+ 2011-01-01 13:00]""" # noqa: E501
489
+
490
+ assert repr(s) == exp
491
+
492
+ idx = period_range("2011-01", freq="M", periods=5)
493
+ s = Series(Categorical(idx))
494
+ exp = """0 2011-01
495
+ 1 2011-02
496
+ 2 2011-03
497
+ 3 2011-04
498
+ 4 2011-05
499
+ dtype: category
500
+ Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]"""
501
+
502
+ assert repr(s) == exp
503
+
504
+ def test_categorical_series_repr_period_ordered(self):
505
+ idx = period_range("2011-01-01 09:00", freq="h", periods=5)
506
+ s = Series(Categorical(idx, ordered=True))
507
+ exp = """0 2011-01-01 09:00
508
+ 1 2011-01-01 10:00
509
+ 2 2011-01-01 11:00
510
+ 3 2011-01-01 12:00
511
+ 4 2011-01-01 13:00
512
+ dtype: category
513
+ Categories (5, period[h]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
514
+ 2011-01-01 13:00]""" # noqa: E501
515
+
516
+ assert repr(s) == exp
517
+
518
+ idx = period_range("2011-01", freq="M", periods=5)
519
+ s = Series(Categorical(idx, ordered=True))
520
+ exp = """0 2011-01
521
+ 1 2011-02
522
+ 2 2011-03
523
+ 3 2011-04
524
+ 4 2011-05
525
+ dtype: category
526
+ Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]"""
527
+
528
+ assert repr(s) == exp
529
+
530
+ def test_categorical_series_repr_timedelta(self):
531
+ idx = timedelta_range("1 days", periods=5)
532
+ s = Series(Categorical(idx))
533
+ exp = """0 1 days
534
+ 1 2 days
535
+ 2 3 days
536
+ 3 4 days
537
+ 4 5 days
538
+ dtype: category
539
+ Categories (5, timedelta64[us]): [1 days, 2 days, 3 days, 4 days, 5 days]"""
540
+
541
+ assert repr(s) == exp
542
+
543
+ idx = timedelta_range("1 hours", periods=10)
544
+ s = Series(Categorical(idx))
545
+ exp = """0 0 days 01:00:00
546
+ 1 1 days 01:00:00
547
+ 2 2 days 01:00:00
548
+ 3 3 days 01:00:00
549
+ 4 4 days 01:00:00
550
+ 5 5 days 01:00:00
551
+ 6 6 days 01:00:00
552
+ 7 7 days 01:00:00
553
+ 8 8 days 01:00:00
554
+ 9 9 days 01:00:00
555
+ dtype: category
556
+ Categories (10, timedelta64[us]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
557
+ 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00,
558
+ 8 days 01:00:00, 9 days 01:00:00]""" # noqa: E501
559
+
560
+ assert repr(s) == exp
561
+
562
+ def test_categorical_series_repr_timedelta_ordered(self):
563
+ idx = timedelta_range("1 days", periods=5)
564
+ s = Series(Categorical(idx, ordered=True))
565
+ exp = """0 1 days
566
+ 1 2 days
567
+ 2 3 days
568
+ 3 4 days
569
+ 4 5 days
570
+ dtype: category
571
+ Categories (5, timedelta64[us]): [1 days < 2 days < 3 days < 4 days < 5 days]"""
572
+
573
+ assert repr(s) == exp
574
+
575
+ idx = timedelta_range("1 hours", periods=10)
576
+ s = Series(Categorical(idx, ordered=True))
577
+ exp = """0 0 days 01:00:00
578
+ 1 1 days 01:00:00
579
+ 2 2 days 01:00:00
580
+ 3 3 days 01:00:00
581
+ 4 4 days 01:00:00
582
+ 5 5 days 01:00:00
583
+ 6 6 days 01:00:00
584
+ 7 7 days 01:00:00
585
+ 8 8 days 01:00:00
586
+ 9 9 days 01:00:00
587
+ dtype: category
588
+ Categories (10, timedelta64[us]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
589
+ 3 days 01:00:00 ... 6 days 01:00:00 < 7 days 01:00:00 <
590
+ 8 days 01:00:00 < 9 days 01:00:00]""" # noqa: E501
591
+
592
+ assert repr(s) == exp
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_iteration.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class TestIteration:
2
+ def test_keys(self, datetime_series):
3
+ assert datetime_series.keys() is datetime_series.index
4
+
5
+ def test_iter_datetimes(self, datetime_series):
6
+ for i, val in enumerate(datetime_series):
7
+ assert val == datetime_series.iloc[i]
8
+
9
+ def test_iter_strings(self, string_series):
10
+ for i, val in enumerate(string_series):
11
+ assert val == string_series.iloc[i]
12
+
13
+ def test_iteritems_datetimes(self, datetime_series):
14
+ for idx, val in datetime_series.items():
15
+ assert val == datetime_series[idx] # noqa: PLR1733
16
+
17
+ def test_iteritems_strings(self, string_series):
18
+ for idx, val in string_series.items():
19
+ assert val == string_series[idx] # noqa: PLR1733
20
+
21
+ # assert is lazy (generators don't define reverse, lists do)
22
+ assert not hasattr(string_series.items(), "reverse")
23
+
24
+ def test_items_datetimes(self, datetime_series):
25
+ for idx, val in datetime_series.items():
26
+ assert val == datetime_series[idx] # noqa: PLR1733
27
+
28
+ def test_items_strings(self, string_series):
29
+ for idx, val in string_series.items():
30
+ assert val == string_series[idx] # noqa: PLR1733
31
+
32
+ # assert is lazy (generators don't define reverse, lists do)
33
+ assert not hasattr(string_series.items(), "reverse")
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_logical_ops.py ADDED
@@ -0,0 +1,510 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import operator
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas import (
8
+ DataFrame,
9
+ Index,
10
+ Series,
11
+ bdate_range,
12
+ )
13
+ import pandas._testing as tm
14
+ from pandas.core import ops
15
+
16
+
17
+ class TestSeriesLogicalOps:
18
+ @pytest.mark.parametrize("bool_op", [operator.and_, operator.or_, operator.xor])
19
+ def test_bool_operators_with_nas(self, bool_op):
20
+ # boolean &, |, ^ should work with object arrays and propagate NAs
21
+ ser = Series(bdate_range("1/1/2000", periods=10), dtype=object)
22
+ ser[::2] = np.nan
23
+
24
+ mask = ser.isna()
25
+ filled = ser.fillna(ser[0])
26
+
27
+ result = bool_op(ser < ser[9], ser > ser[3])
28
+
29
+ expected = bool_op(filled < filled[9], filled > filled[3])
30
+ expected[mask] = False
31
+ tm.assert_series_equal(result, expected)
32
+
33
+ def test_logical_operators_bool_dtype_with_empty(self):
34
+ # GH#9016: support bitwise op for integer types
35
+ index = list("bca")
36
+
37
+ s_tft = Series([True, False, True], index=index)
38
+ s_fff = Series([False, False, False], index=index)
39
+ s_empty = Series([], dtype=object)
40
+
41
+ res = s_tft & s_empty
42
+ expected = s_fff.sort_index()
43
+ tm.assert_series_equal(res, expected)
44
+
45
+ res = s_tft | s_empty
46
+ expected = s_tft.sort_index()
47
+ tm.assert_series_equal(res, expected)
48
+
49
+ def test_logical_operators_int_dtype_with_int_dtype(self):
50
+ # GH#9016: support bitwise op for integer types
51
+
52
+ s_0123 = Series(range(4), dtype="int64")
53
+ s_3333 = Series([3] * 4)
54
+ s_4444 = Series([4] * 4)
55
+
56
+ res = s_0123 & s_3333
57
+ expected = Series(range(4), dtype="int64")
58
+ tm.assert_series_equal(res, expected)
59
+
60
+ res = s_0123 | s_4444
61
+ expected = Series(range(4, 8), dtype="int64")
62
+ tm.assert_series_equal(res, expected)
63
+
64
+ s_1111 = Series([1] * 4, dtype="int8")
65
+ res = s_0123 & s_1111
66
+ expected = Series([0, 1, 0, 1], dtype="int64")
67
+ tm.assert_series_equal(res, expected)
68
+
69
+ res = s_0123.astype(np.int16) | s_1111.astype(np.int32)
70
+ expected = Series([1, 1, 3, 3], dtype="int32")
71
+ tm.assert_series_equal(res, expected)
72
+
73
+ def test_logical_operators_int_dtype_with_int_scalar(self):
74
+ # GH#9016: support bitwise op for integer types
75
+ s_0123 = Series(range(4), dtype="int64")
76
+
77
+ res = s_0123 & 0
78
+ expected = Series([0] * 4)
79
+ tm.assert_series_equal(res, expected)
80
+
81
+ res = s_0123 & 1
82
+ expected = Series([0, 1, 0, 1])
83
+ tm.assert_series_equal(res, expected)
84
+
85
+ def test_logical_operators_int_dtype_with_float(self):
86
+ # GH#9016: support bitwise op for integer types
87
+ s_0123 = Series(range(4), dtype="int64")
88
+
89
+ err_msg = (
90
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
91
+ "dtype-less sequences"
92
+ )
93
+
94
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
95
+ with pytest.raises(TypeError, match=msg):
96
+ s_0123 & np.nan
97
+ with pytest.raises(TypeError, match=msg):
98
+ s_0123 & 3.14
99
+ msg = "unsupported operand type.+for &:"
100
+ with pytest.raises(TypeError, match=err_msg):
101
+ s_0123 & [0.1, 4, 3.14, 2]
102
+ with pytest.raises(TypeError, match=msg):
103
+ s_0123 & np.array([0.1, 4, 3.14, 2])
104
+ with pytest.raises(TypeError, match=msg):
105
+ s_0123 & Series([0.1, 4, -3.14, 2])
106
+
107
+ def test_logical_operators_int_dtype_with_str(self):
108
+ s_1111 = Series([1] * 4, dtype="int8")
109
+
110
+ err_msg = (
111
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
112
+ "dtype-less sequences"
113
+ )
114
+
115
+ msg = "Cannot perform 'and_' with a dtyped.+array and scalar of type"
116
+ with pytest.raises(TypeError, match=msg):
117
+ s_1111 & "a"
118
+ with pytest.raises(TypeError, match=err_msg):
119
+ s_1111 & ["a", "b", "c", "d"]
120
+
121
+ def test_logical_operators_int_dtype_with_bool(self):
122
+ # GH#9016: support bitwise op for integer types
123
+ s_0123 = Series(range(4), dtype="int64")
124
+
125
+ expected = Series([False] * 4)
126
+
127
+ result = s_0123 & False
128
+ tm.assert_series_equal(result, expected)
129
+
130
+ msg = (
131
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
132
+ "dtype-less sequences"
133
+ )
134
+ with pytest.raises(TypeError, match=msg):
135
+ s_0123 & [False]
136
+
137
+ with pytest.raises(TypeError, match=msg):
138
+ s_0123 & (False,)
139
+
140
+ result = s_0123 ^ False
141
+ expected = Series([False, True, True, True])
142
+ tm.assert_series_equal(result, expected)
143
+
144
+ def test_logical_operators_int_dtype_with_object(self):
145
+ # GH#9016: support bitwise op for integer types
146
+ s_0123 = Series(range(4), dtype="int64")
147
+
148
+ result = s_0123 & Series([False, np.nan, False, False])
149
+ expected = Series([False] * 4)
150
+ tm.assert_series_equal(result, expected)
151
+
152
+ s_abNd = Series(["a", "b", np.nan, "d"])
153
+ with pytest.raises(
154
+ TypeError, match="unsupported.* 'int' and 'str'|'rand_' not supported"
155
+ ):
156
+ s_0123 & s_abNd
157
+
158
+ def test_logical_operators_bool_dtype_with_int(self):
159
+ index = list("bca")
160
+
161
+ s_tft = Series([True, False, True], index=index)
162
+ s_fff = Series([False, False, False], index=index)
163
+
164
+ res = s_tft & 0
165
+ expected = s_fff
166
+ tm.assert_series_equal(res, expected)
167
+
168
+ res = s_tft & 1
169
+ expected = s_tft
170
+ tm.assert_series_equal(res, expected)
171
+
172
+ def test_logical_ops_bool_dtype_with_ndarray(self):
173
+ # make sure we operate on ndarray the same as Series
174
+ left = Series([True, True, True, False, True])
175
+ right = [True, False, None, True, np.nan]
176
+
177
+ msg = (
178
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
179
+ "dtype-less sequences"
180
+ )
181
+
182
+ expected = Series([True, False, False, False, False])
183
+ with pytest.raises(TypeError, match=msg):
184
+ left & right
185
+ result = left & np.array(right)
186
+ tm.assert_series_equal(result, expected)
187
+ result = left & Index(right)
188
+ tm.assert_series_equal(result, expected)
189
+ result = left & Series(right)
190
+ tm.assert_series_equal(result, expected)
191
+
192
+ expected = Series([True, True, True, True, True])
193
+ with pytest.raises(TypeError, match=msg):
194
+ left | right
195
+ result = left | np.array(right)
196
+ tm.assert_series_equal(result, expected)
197
+ result = left | Index(right)
198
+ tm.assert_series_equal(result, expected)
199
+ result = left | Series(right)
200
+ tm.assert_series_equal(result, expected)
201
+
202
+ expected = Series([False, True, True, True, True])
203
+ with pytest.raises(TypeError, match=msg):
204
+ left ^ right
205
+ result = left ^ np.array(right)
206
+ tm.assert_series_equal(result, expected)
207
+ result = left ^ Index(right)
208
+ tm.assert_series_equal(result, expected)
209
+ result = left ^ Series(right)
210
+ tm.assert_series_equal(result, expected)
211
+
212
+ def test_logical_operators_int_dtype_with_bool_dtype_and_reindex(self):
213
+ # GH#9016: support bitwise op for integer types
214
+
215
+ index = list("bca")
216
+
217
+ s_tft = Series([True, False, True], index=index)
218
+ s_tft = Series([True, False, True], index=index)
219
+ s_tff = Series([True, False, False], index=index)
220
+
221
+ s_0123 = Series(range(4), dtype="int64")
222
+
223
+ # s_0123 will be all false now because of reindexing like s_tft
224
+ expected = Series([False] * 7, index=[0, 1, 2, 3, "a", "b", "c"])
225
+ result = s_tft & s_0123
226
+ tm.assert_series_equal(result, expected)
227
+
228
+ # GH#52538: no longer to object type when reindex is needed;
229
+ # matches DataFrame behavior
230
+ msg = r"unsupported operand type\(s\) for &: 'float' and 'bool'"
231
+ with pytest.raises(TypeError, match=msg):
232
+ s_0123 & s_tft
233
+
234
+ s_a0b1c0 = Series([1], list("b"))
235
+
236
+ res = s_tft & s_a0b1c0
237
+ expected = s_tff.reindex(list("abc"))
238
+ tm.assert_series_equal(res, expected)
239
+
240
+ res = s_tft | s_a0b1c0
241
+ expected = s_tft.reindex(list("abc"))
242
+ tm.assert_series_equal(res, expected)
243
+
244
+ def test_scalar_na_logical_ops_corners(self):
245
+ s = Series([2, 3, 4, 5, 6, 7, 8, 9, 10])
246
+
247
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
248
+ with pytest.raises(TypeError, match=msg):
249
+ s & datetime(2005, 1, 1)
250
+
251
+ s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)])
252
+ s[::2] = np.nan
253
+
254
+ expected = Series(True, index=s.index)
255
+ expected[::2] = False
256
+
257
+ msg = (
258
+ r"Logical ops \(and, or, xor\) between Pandas objects and "
259
+ "dtype-less sequences"
260
+ )
261
+ with pytest.raises(TypeError, match=msg):
262
+ s & list(s)
263
+
264
+ def test_scalar_na_logical_ops_corners_aligns(self):
265
+ s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)])
266
+ s[::2] = np.nan
267
+ d = DataFrame({"A": s})
268
+
269
+ expected = DataFrame(False, index=range(9), columns=["A", *list(range(9))])
270
+
271
+ result = s & d
272
+ tm.assert_frame_equal(result, expected)
273
+
274
+ result = d & s
275
+ tm.assert_frame_equal(result, expected)
276
+
277
+ @pytest.mark.parametrize("op", [operator.and_, operator.or_, operator.xor])
278
+ def test_logical_ops_with_index(self, op):
279
+ # GH#22092, GH#19792
280
+ ser = Series([True, True, False, False])
281
+ idx1 = Index([True, False, True, False])
282
+ idx2 = Index([1, 0, 1, 0])
283
+
284
+ expected = Series([op(ser[n], idx1[n]) for n in range(len(ser))])
285
+
286
+ result = op(ser, idx1)
287
+ tm.assert_series_equal(result, expected)
288
+
289
+ expected = Series([op(ser[n], idx2[n]) for n in range(len(ser))], dtype=bool)
290
+
291
+ result = op(ser, idx2)
292
+ tm.assert_series_equal(result, expected)
293
+
294
+ def test_reversed_xor_with_index_returns_series(self):
295
+ # GH#22092, GH#19792 pre-2.0 these were aliased to setops
296
+ ser = Series([True, True, False, False])
297
+ idx1 = Index([True, False, True, False], dtype=bool)
298
+ idx2 = Index([1, 0, 1, 0])
299
+
300
+ expected = Series([False, True, True, False])
301
+ result = idx1 ^ ser
302
+ tm.assert_series_equal(result, expected)
303
+
304
+ result = idx2 ^ ser
305
+ tm.assert_series_equal(result, expected)
306
+
307
+ @pytest.mark.parametrize(
308
+ "op",
309
+ [
310
+ ops.rand_,
311
+ ops.ror_,
312
+ ],
313
+ )
314
+ def test_reversed_logical_op_with_index_returns_series(self, op):
315
+ # GH#22092, GH#19792
316
+ ser = Series([True, True, False, False])
317
+ idx1 = Index([True, False, True, False])
318
+ idx2 = Index([1, 0, 1, 0])
319
+
320
+ expected = Series(op(idx1.values, ser.values))
321
+ result = op(ser, idx1)
322
+ tm.assert_series_equal(result, expected)
323
+
324
+ expected = op(ser, Series(idx2))
325
+ result = op(ser, idx2)
326
+ tm.assert_series_equal(result, expected)
327
+
328
+ @pytest.mark.parametrize(
329
+ "op, expected",
330
+ [
331
+ (ops.rand_, [False, False]),
332
+ (ops.ror_, [True, True]),
333
+ (ops.rxor, [True, True]),
334
+ ],
335
+ )
336
+ def test_reverse_ops_with_index(self, op, expected):
337
+ # https://github.com/pandas-dev/pandas/pull/23628
338
+ # multi-set Index ops are buggy, so let's avoid duplicates...
339
+ # GH#49503
340
+ ser = Series([True, False])
341
+ idx = Index([False, True])
342
+
343
+ result = op(ser, idx)
344
+ expected = Series(expected)
345
+ tm.assert_series_equal(result, expected)
346
+
347
+ def test_logical_ops_label_based(self, using_infer_string):
348
+ # GH#4947
349
+ # logical ops should be label based
350
+
351
+ a = Series([True, False, True], list("bca"))
352
+ b = Series([False, True, False], list("abc"))
353
+
354
+ expected = Series([False, True, False], list("abc"))
355
+ result = a & b
356
+ tm.assert_series_equal(result, expected)
357
+
358
+ expected = Series([True, True, False], list("abc"))
359
+ result = a | b
360
+ tm.assert_series_equal(result, expected)
361
+
362
+ expected = Series([True, False, False], list("abc"))
363
+ result = a ^ b
364
+ tm.assert_series_equal(result, expected)
365
+
366
+ # rhs is bigger
367
+ a = Series([True, False, True], list("bca"))
368
+ b = Series([False, True, False, True], list("abcd"))
369
+
370
+ expected = Series([False, True, False, False], list("abcd"))
371
+ result = a & b
372
+ tm.assert_series_equal(result, expected)
373
+
374
+ expected = Series([True, True, False, False], list("abcd"))
375
+ result = a | b
376
+ tm.assert_series_equal(result, expected)
377
+
378
+ # filling
379
+
380
+ # vs empty
381
+ empty = Series([], dtype=object)
382
+
383
+ result = a & empty
384
+ expected = Series([False, False, False], list("abc"))
385
+ tm.assert_series_equal(result, expected)
386
+
387
+ result = a | empty
388
+ expected = Series([True, True, False], list("abc"))
389
+ tm.assert_series_equal(result, expected)
390
+
391
+ # vs non-matching
392
+ result = a & Series([1], ["z"])
393
+ expected = Series([False, False, False, False], list("abcz"))
394
+ tm.assert_series_equal(result, expected)
395
+
396
+ result = a | Series([1], ["z"])
397
+ expected = Series([True, True, False, False], list("abcz"))
398
+ tm.assert_series_equal(result, expected)
399
+
400
+ # identity
401
+ # we would like s[s|e] == s to hold for any e, whether empty or not
402
+ for e in [
403
+ empty.copy(),
404
+ Series([1], ["z"]),
405
+ Series(np.nan, b.index),
406
+ Series(np.nan, a.index),
407
+ ]:
408
+ result = a[a | e]
409
+ tm.assert_series_equal(result, a[a])
410
+
411
+ for e in [Series(["z"])]:
412
+ if using_infer_string:
413
+ # TODO(infer_string) should this behave differently?
414
+ # -> https://github.com/pandas-dev/pandas/issues/60234
415
+ with pytest.raises(
416
+ TypeError, match="not supported for dtype|unsupported operand type"
417
+ ):
418
+ result = a[a | e]
419
+ else:
420
+ result = a[a | e]
421
+ tm.assert_series_equal(result, a[a])
422
+
423
+ # vs scalars
424
+ index = list("bca")
425
+ t = Series([True, False, True])
426
+
427
+ for v in [True, 1, 2]:
428
+ result = Series([True, False, True], index=index) | v
429
+ expected = Series([True, True, True], index=index)
430
+ tm.assert_series_equal(result, expected)
431
+
432
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
433
+ for v in [np.nan, "foo"]:
434
+ with pytest.raises(TypeError, match=msg):
435
+ t | v
436
+
437
+ for v in [False, 0]:
438
+ result = Series([True, False, True], index=index) | v
439
+ expected = Series([True, False, True], index=index)
440
+ tm.assert_series_equal(result, expected)
441
+
442
+ for v in [True, 1]:
443
+ result = Series([True, False, True], index=index) & v
444
+ expected = Series([True, False, True], index=index)
445
+ tm.assert_series_equal(result, expected)
446
+
447
+ for v in [False, 0]:
448
+ result = Series([True, False, True], index=index) & v
449
+ expected = Series([False, False, False], index=index)
450
+ tm.assert_series_equal(result, expected)
451
+ msg = "Cannot perform.+with a dtyped.+array and scalar of type"
452
+ for v in [np.nan]:
453
+ with pytest.raises(TypeError, match=msg):
454
+ t & v
455
+
456
+ def test_logical_ops_df_compat(self):
457
+ # GH#1134
458
+ s1 = Series([True, False, True], index=list("ABC"), name="x")
459
+ s2 = Series([True, True, False], index=list("ABD"), name="x")
460
+
461
+ exp = Series([True, False, False, False], index=list("ABCD"), name="x")
462
+ tm.assert_series_equal(s1 & s2, exp)
463
+ tm.assert_series_equal(s2 & s1, exp)
464
+
465
+ # True | np.nan => True
466
+ exp_or1 = Series([True, True, True, False], index=list("ABCD"), name="x")
467
+ tm.assert_series_equal(s1 | s2, exp_or1)
468
+ # np.nan | True => np.nan, filled with False
469
+ exp_or = Series([True, True, False, False], index=list("ABCD"), name="x")
470
+ tm.assert_series_equal(s2 | s1, exp_or)
471
+
472
+ # DataFrame doesn't fill nan with False
473
+ tm.assert_frame_equal(s1.to_frame() & s2.to_frame(), exp.to_frame())
474
+ tm.assert_frame_equal(s2.to_frame() & s1.to_frame(), exp.to_frame())
475
+
476
+ exp = DataFrame({"x": [True, True, np.nan, np.nan]}, index=list("ABCD"))
477
+ tm.assert_frame_equal(s1.to_frame() | s2.to_frame(), exp_or1.to_frame())
478
+ tm.assert_frame_equal(s2.to_frame() | s1.to_frame(), exp_or.to_frame())
479
+
480
+ # different length
481
+ s3 = Series([True, False, True], index=list("ABC"), name="x")
482
+ s4 = Series([True, True, True, True], index=list("ABCD"), name="x")
483
+
484
+ exp = Series([True, False, True, False], index=list("ABCD"), name="x")
485
+ tm.assert_series_equal(s3 & s4, exp)
486
+ tm.assert_series_equal(s4 & s3, exp)
487
+
488
+ # np.nan | True => np.nan, filled with False
489
+ exp_or1 = Series([True, True, True, False], index=list("ABCD"), name="x")
490
+ tm.assert_series_equal(s3 | s4, exp_or1)
491
+ # True | np.nan => True
492
+ exp_or = Series([True, True, True, True], index=list("ABCD"), name="x")
493
+ tm.assert_series_equal(s4 | s3, exp_or)
494
+
495
+ tm.assert_frame_equal(s3.to_frame() & s4.to_frame(), exp.to_frame())
496
+ tm.assert_frame_equal(s4.to_frame() & s3.to_frame(), exp.to_frame())
497
+
498
+ tm.assert_frame_equal(s3.to_frame() | s4.to_frame(), exp_or1.to_frame())
499
+ tm.assert_frame_equal(s4.to_frame() | s3.to_frame(), exp_or.to_frame())
500
+
501
+ def test_int_dtype_different_index_not_bool(self):
502
+ # GH 52500
503
+ ser1 = Series([1, 2, 3], index=[10, 11, 23], name="a")
504
+ ser2 = Series([10, 20, 30], index=[11, 10, 23], name="a")
505
+ result = np.bitwise_xor(ser1, ser2)
506
+ expected = Series([21, 8, 29], index=[10, 11, 23], name="a")
507
+ tm.assert_series_equal(result, expected)
508
+
509
+ result = ser1 ^ ser2
510
+ tm.assert_series_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_missing.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import timedelta
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas._libs import iNaT
7
+
8
+ import pandas as pd
9
+ from pandas import (
10
+ Categorical,
11
+ Index,
12
+ NaT,
13
+ Series,
14
+ isna,
15
+ )
16
+ import pandas._testing as tm
17
+
18
+
19
+ class TestSeriesMissingData:
20
+ def test_categorical_nan_handling(self):
21
+ # NaNs are represented as -1 in labels
22
+ s = Series(Categorical(["a", "b", np.nan, "a"]))
23
+ tm.assert_index_equal(s.cat.categories, Index(["a", "b"]))
24
+ tm.assert_numpy_array_equal(
25
+ s.values.codes, np.array([0, 1, -1, 0], dtype=np.int8)
26
+ )
27
+
28
+ def test_timedelta64_nan(self):
29
+ td = Series([timedelta(days=i) for i in range(10)])
30
+
31
+ # nan ops on timedeltas
32
+ td1 = td.copy()
33
+ td1[0] = np.nan
34
+ assert isna(td1[0])
35
+ assert td1[0]._value == iNaT
36
+ td1[0] = td[0]
37
+ assert not isna(td1[0])
38
+
39
+ # GH#16674 iNaT is treated as an integer when given by the user
40
+ with pytest.raises(TypeError, match="Invalid value"):
41
+ td1[1] = iNaT
42
+
43
+ td1[2] = NaT
44
+ assert isna(td1[2])
45
+ assert td1[2]._value == iNaT
46
+ td1[2] = td[2]
47
+ assert not isna(td1[2])
48
+
49
+ # boolean setting
50
+ # GH#2899 boolean setting
51
+ td3 = np.timedelta64(timedelta(days=3))
52
+ td7 = np.timedelta64(timedelta(days=7))
53
+ td[(td > td3) & (td < td7)] = np.nan
54
+ assert isna(td).sum() == 3
55
+
56
+ @pytest.mark.xfail(
57
+ reason="Chained inequality raises when trying to define 'selector'"
58
+ )
59
+ def test_logical_range_select(self, datetime_series):
60
+ # NumPy limitation =(
61
+ # https://github.com/pandas-dev/pandas/commit/9030dc021f07c76809848925cb34828f6c8484f3
62
+
63
+ selector = -0.5 <= datetime_series <= 0.5
64
+ expected = (datetime_series >= -0.5) & (datetime_series <= 0.5)
65
+ tm.assert_series_equal(selector, expected)
66
+
67
+ def test_valid(self, datetime_series):
68
+ ts = datetime_series.copy()
69
+ ts.index = ts.index._with_freq(None)
70
+ ts[::2] = np.nan
71
+
72
+ result = ts.dropna()
73
+ assert len(result) == ts.count()
74
+ tm.assert_series_equal(result, ts[1::2])
75
+ tm.assert_series_equal(result, ts[pd.notna(ts)])
76
+
77
+
78
+ def test_hasnans_uncached_for_series():
79
+ # GH#19700
80
+ # set float64 dtype to avoid upcast when setting nan
81
+ idx = Index([0, 1], dtype="float64")
82
+ assert idx.hasnans is False
83
+ assert "hasnans" in idx._cache
84
+ ser = idx.to_series()
85
+ assert ser.hasnans is False
86
+ assert not hasattr(ser, "_cache")
87
+ ser.iloc[-1] = np.nan
88
+ assert ser.hasnans is True
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_npfuncs.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for np.foo applied to Series, not necessarily ufuncs.
3
+ """
4
+
5
+ import numpy as np
6
+ import pytest
7
+
8
+ import pandas.util._test_decorators as td
9
+
10
+ from pandas import Series
11
+ import pandas._testing as tm
12
+
13
+
14
+ class TestPtp:
15
+ def test_ptp(self):
16
+ # GH#21614
17
+ N = 1000
18
+ arr = np.random.default_rng(2).standard_normal(N)
19
+ ser = Series(arr)
20
+ assert np.ptp(ser) == np.ptp(arr)
21
+
22
+
23
+ def test_numpy_unique(datetime_series):
24
+ # it works!
25
+ np.unique(datetime_series)
26
+
27
+
28
+ @pytest.mark.parametrize("index", [["a", "b", "c", "d", "e"], None])
29
+ def test_numpy_argwhere(index):
30
+ # GH#35331
31
+
32
+ s = Series(range(5), index=index, dtype=np.int64)
33
+
34
+ result = np.argwhere(s > 2).astype(np.int64)
35
+ expected = np.array([[3], [4]], dtype=np.int64)
36
+
37
+ tm.assert_numpy_array_equal(result, expected)
38
+
39
+
40
+ @td.skip_if_no("pyarrow")
41
+ def test_log_arrow_backed_missing_value(using_nan_is_na):
42
+ # GH#56285
43
+ ser = Series([1, 2, None], dtype="float64[pyarrow]")
44
+ if using_nan_is_na:
45
+ result = np.log(ser)
46
+ expected = np.log(Series([1, 2, None], dtype="float64[pyarrow]"))
47
+ tm.assert_series_equal(result, expected)
48
+ else:
49
+ # we get cast to object which raises
50
+ msg = "loop of ufunc does not support argument"
51
+ with pytest.raises(TypeError, match=msg):
52
+ np.log(ser)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_reductions.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas import Series
6
+ import pandas._testing as tm
7
+
8
+
9
+ @pytest.mark.parametrize("operation, expected", [("min", "a"), ("max", "b")])
10
+ def test_reductions_series_strings(operation, expected):
11
+ # GH#31746
12
+ ser = Series(["a", "b"], dtype="string")
13
+ res_operation_serie = getattr(ser, operation)()
14
+ assert res_operation_serie == expected
15
+
16
+
17
+ @pytest.mark.parametrize("as_period", [True, False])
18
+ def test_mode_extension_dtype(as_period):
19
+ # GH#41927 preserve dt64tz dtype
20
+ ser = Series([pd.Timestamp(1979, 4, n) for n in range(1, 5)])
21
+
22
+ if as_period:
23
+ ser = ser.dt.to_period("D")
24
+ else:
25
+ ser = ser.dt.tz_localize("US/Central")
26
+
27
+ res = ser.mode()
28
+ assert res.dtype == ser.dtype
29
+ tm.assert_series_equal(res, ser)
30
+
31
+
32
+ def test_mode_nullable_dtype(any_numeric_ea_dtype):
33
+ # GH#55340
34
+ ser = Series([1, 3, 2, pd.NA, 3, 2, pd.NA], dtype=any_numeric_ea_dtype)
35
+ result = ser.mode(dropna=False)
36
+ expected = Series([2, 3, pd.NA], dtype=any_numeric_ea_dtype)
37
+ tm.assert_series_equal(result, expected)
38
+
39
+ result = ser.mode(dropna=True)
40
+ expected = Series([2, 3], dtype=any_numeric_ea_dtype)
41
+ tm.assert_series_equal(result, expected)
42
+
43
+ ser[-1] = pd.NA
44
+
45
+ result = ser.mode(dropna=True)
46
+ expected = Series([2, 3], dtype=any_numeric_ea_dtype)
47
+ tm.assert_series_equal(result, expected)
48
+
49
+ result = ser.mode(dropna=False)
50
+ expected = Series([pd.NA], dtype=any_numeric_ea_dtype)
51
+ tm.assert_series_equal(result, expected)
52
+
53
+
54
+ def test_mode_nullable_dtype_edge_case(any_numeric_ea_dtype):
55
+ # GH##58926
56
+ ser = Series([1, 2, 3, 1], dtype=any_numeric_ea_dtype)
57
+ result = ser.mode(dropna=False)
58
+ expected = Series([1], dtype=any_numeric_ea_dtype)
59
+ tm.assert_series_equal(result, expected)
60
+
61
+ ser2 = Series([1, 1, 2, 3, pd.NA], dtype=any_numeric_ea_dtype)
62
+ result = ser2.mode(dropna=False)
63
+ expected = Series([1], dtype=any_numeric_ea_dtype)
64
+ tm.assert_series_equal(result, expected)
65
+
66
+ ser3 = Series([1, pd.NA, pd.NA], dtype=any_numeric_ea_dtype)
67
+ result = ser3.mode(dropna=False)
68
+ expected = Series([pd.NA], dtype=any_numeric_ea_dtype)
69
+ tm.assert_series_equal(result, expected)
70
+
71
+ ser4 = Series([1, 1, pd.NA, pd.NA], dtype=any_numeric_ea_dtype)
72
+ result = ser4.mode(dropna=False)
73
+ expected = Series([1, pd.NA], dtype=any_numeric_ea_dtype)
74
+ tm.assert_series_equal(result, expected)
75
+
76
+
77
+ def test_mode_infer_string():
78
+ # GH#56183
79
+ pytest.importorskip("pyarrow")
80
+ ser = Series(["a", "b"], dtype=object)
81
+ with pd.option_context("future.infer_string", True):
82
+ result = ser.mode()
83
+ expected = Series(["a", "b"], dtype=object)
84
+ tm.assert_series_equal(result, expected)
85
+
86
+
87
+ def test_reductions_td64_with_nat():
88
+ # GH#8617
89
+ ser = Series([0, pd.NaT], dtype="m8[ns]")
90
+ exp = ser[0]
91
+ assert ser.median() == exp
92
+ assert ser.min() == exp
93
+ assert ser.max() == exp
94
+
95
+
96
+ def test_td64_sum_empty(skipna):
97
+ # GH#37151
98
+ ser = Series([], dtype="timedelta64[ns]")
99
+
100
+ result = ser.sum(skipna=skipna)
101
+ assert isinstance(result, pd.Timedelta)
102
+ assert result == pd.Timedelta(0)
103
+
104
+
105
+ def test_td64_summation_overflow():
106
+ # GH#9442
107
+ ser = Series(pd.date_range("20130101", periods=100000, freq="h", unit="ns"))
108
+ ser[0] += pd.Timedelta("1s 1ms")
109
+
110
+ # mean
111
+ result = (ser - ser.min()).mean()
112
+ expected = pd.Timedelta((pd.TimedeltaIndex(ser - ser.min()).asi8 / len(ser)).sum())
113
+
114
+ # the computation is converted to float so
115
+ # might be some loss of precision
116
+ assert np.allclose(result._value / 1000, expected._value / 1000)
117
+
118
+ # sum
119
+ msg = "overflow in timedelta operation"
120
+ with pytest.raises(ValueError, match=msg):
121
+ (ser - ser.min()).sum()
122
+
123
+ s1 = ser[0:10000]
124
+ with pytest.raises(ValueError, match=msg):
125
+ (s1 - s1.min()).sum()
126
+ s2 = ser[0:1000]
127
+ (s2 - s2.min()).sum()
128
+
129
+
130
+ def test_prod_numpy16_bug():
131
+ ser = Series([1.0, 1.0, 1.0], index=range(3))
132
+ result = ser.prod()
133
+
134
+ assert not isinstance(result, Series)
135
+
136
+
137
+ @pytest.mark.parametrize("func", [np.any, np.all])
138
+ @pytest.mark.parametrize("kwargs", [{"keepdims": True}, {"out": object()}])
139
+ def test_validate_any_all_out_keepdims_raises(kwargs, func):
140
+ ser = Series([1, 2])
141
+ param = next(iter(kwargs))
142
+ name = func.__name__
143
+
144
+ msg = (
145
+ f"the '{param}' parameter is not "
146
+ "supported in the pandas "
147
+ rf"implementation of {name}\(\)"
148
+ )
149
+ with pytest.raises(ValueError, match=msg):
150
+ func(ser, **kwargs)
151
+
152
+
153
+ def test_validate_sum_initial():
154
+ ser = Series([1, 2])
155
+ msg = (
156
+ r"the 'initial' parameter is not "
157
+ r"supported in the pandas "
158
+ r"implementation of sum\(\)"
159
+ )
160
+ with pytest.raises(ValueError, match=msg):
161
+ np.sum(ser, initial=10)
162
+
163
+
164
+ def test_validate_median_initial():
165
+ ser = Series([1, 2])
166
+ msg = (
167
+ r"the 'overwrite_input' parameter is not "
168
+ r"supported in the pandas "
169
+ r"implementation of median\(\)"
170
+ )
171
+ with pytest.raises(ValueError, match=msg):
172
+ # It seems like np.median doesn't dispatch, so we use the
173
+ # method instead of the ufunc.
174
+ ser.median(overwrite_input=True)
175
+
176
+
177
+ def test_validate_stat_keepdims():
178
+ ser = Series([1, 2])
179
+ msg = (
180
+ r"the 'keepdims' parameter is not "
181
+ r"supported in the pandas "
182
+ r"implementation of sum\(\)"
183
+ )
184
+ with pytest.raises(ValueError, match=msg):
185
+ np.sum(ser, keepdims=True)
186
+
187
+
188
+ def test_mean_with_convertible_string_raises():
189
+ # GH#44008
190
+ ser = Series(["1", "2"])
191
+ assert ser.sum() == "12"
192
+
193
+ msg = "Could not convert string '12' to numeric|does not support|Cannot perform"
194
+ with pytest.raises(TypeError, match=msg):
195
+ ser.mean()
196
+
197
+ df = ser.to_frame()
198
+ msg = r"Could not convert \['12'\] to numeric|does not support|Cannot perform"
199
+ with pytest.raises(TypeError, match=msg):
200
+ df.mean()
201
+
202
+
203
+ def test_mean_dont_convert_j_to_complex():
204
+ # GH#36703
205
+ df = pd.DataFrame([{"db": "J", "numeric": 123}])
206
+ msg = r"Could not convert \['J'\] to numeric|does not support|Cannot perform"
207
+ with pytest.raises(TypeError, match=msg):
208
+ df.mean()
209
+
210
+ with pytest.raises(TypeError, match=msg):
211
+ df.agg("mean")
212
+
213
+ msg = "Could not convert string 'J' to numeric|does not support|Cannot perform"
214
+ with pytest.raises(TypeError, match=msg):
215
+ df["db"].mean()
216
+ msg = "Could not convert string 'J' to numeric|ufunc 'divide'|Cannot perform"
217
+ with pytest.raises(TypeError, match=msg):
218
+ np.mean(df["db"].astype("string").array)
219
+
220
+
221
+ def test_median_with_convertible_string_raises():
222
+ # GH#34671 this _could_ return a string "2", but definitely not float 2.0
223
+ msg = r"Cannot convert \['1' '2' '3'\] to numeric|does not support|Cannot perform"
224
+ ser = Series(["1", "2", "3"])
225
+ with pytest.raises(TypeError, match=msg):
226
+ ser.median()
227
+
228
+ msg = (
229
+ r"Cannot convert \[\['1' '2' '3'\]\] to numeric|does not support|Cannot perform"
230
+ )
231
+ df = ser.to_frame()
232
+ with pytest.raises(TypeError, match=msg):
233
+ df.median()
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_subclass.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ import pandas._testing as tm
6
+
7
+ pytestmark = pytest.mark.filterwarnings(
8
+ "ignore:Passing a BlockManager|Passing a SingleBlockManager:DeprecationWarning"
9
+ )
10
+
11
+
12
+ class TestSeriesSubclassing:
13
+ @pytest.mark.parametrize(
14
+ "idx_method, indexer, exp_data, exp_idx",
15
+ [
16
+ ["loc", ["a", "b"], [1, 2], "ab"],
17
+ ["iloc", [2, 3], [3, 4], "cd"],
18
+ ],
19
+ )
20
+ def test_indexing_sliced(self, idx_method, indexer, exp_data, exp_idx):
21
+ s = tm.SubclassedSeries([1, 2, 3, 4], index=list("abcd"))
22
+ res = getattr(s, idx_method)[indexer]
23
+ exp = tm.SubclassedSeries(exp_data, index=list(exp_idx))
24
+ tm.assert_series_equal(res, exp)
25
+
26
+ def test_to_frame(self):
27
+ s = tm.SubclassedSeries([1, 2, 3, 4], index=list("abcd"), name="xxx")
28
+ res = s.to_frame()
29
+ exp = tm.SubclassedDataFrame({"xxx": [1, 2, 3, 4]}, index=list("abcd"))
30
+ tm.assert_frame_equal(res, exp)
31
+
32
+ def test_subclass_unstack(self):
33
+ # GH 15564
34
+ s = tm.SubclassedSeries([1, 2, 3, 4], index=[list("aabb"), list("xyxy")])
35
+
36
+ res = s.unstack()
37
+ exp = tm.SubclassedDataFrame({"x": [1, 3], "y": [2, 4]}, index=["a", "b"])
38
+
39
+ tm.assert_frame_equal(res, exp)
40
+
41
+ def test_subclass_empty_repr(self):
42
+ sub_series = tm.SubclassedSeries()
43
+ assert "SubclassedSeries" in repr(sub_series)
44
+
45
+ def test_asof(self):
46
+ N = 3
47
+ rng = pd.date_range("1/1/1990", periods=N, freq="53s")
48
+ s = tm.SubclassedSeries({"A": [np.nan, np.nan, np.nan]}, index=rng)
49
+
50
+ result = s.asof(rng[-2:])
51
+ assert isinstance(result, tm.SubclassedSeries)
52
+
53
+ def test_explode(self):
54
+ s = tm.SubclassedSeries([[1, 2, 3], "foo", [], [3, 4]])
55
+ result = s.explode()
56
+ assert isinstance(result, tm.SubclassedSeries)
57
+
58
+ def test_equals(self):
59
+ # https://github.com/pandas-dev/pandas/pull/34402
60
+ # allow subclass in both directions
61
+ s1 = pd.Series([1, 2, 3])
62
+ s2 = tm.SubclassedSeries([1, 2, 3])
63
+ assert s1.equals(s2)
64
+ assert s2.equals(s1)
65
+
66
+
67
+ class SubclassedSeries(pd.Series):
68
+ @property
69
+ def _constructor(self):
70
+ def _new(*args, **kwargs):
71
+ # some constructor logic that accesses the Series' name
72
+ if self.name == "test":
73
+ return pd.Series(*args, **kwargs)
74
+ return SubclassedSeries(*args, **kwargs)
75
+
76
+ return _new
77
+
78
+
79
+ def test_constructor_from_dict():
80
+ # https://github.com/pandas-dev/pandas/issues/52445
81
+ result = SubclassedSeries({"a": 1, "b": 2, "c": 3})
82
+ assert isinstance(result, SubclassedSeries)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_ufunc.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ import re
3
+ import string
4
+
5
+ import numpy as np
6
+ import pytest
7
+
8
+ import pandas as pd
9
+ import pandas._testing as tm
10
+ from pandas.arrays import SparseArray
11
+
12
+
13
+ @pytest.fixture(params=[np.add, np.logaddexp])
14
+ def ufunc(request):
15
+ # dunder op
16
+ return request.param
17
+
18
+
19
+ @pytest.fixture(
20
+ params=[pytest.param(True, marks=pytest.mark.fails_arm_wheels), False],
21
+ ids=["sparse", "dense"],
22
+ )
23
+ def sparse(request):
24
+ return request.param
25
+
26
+
27
+ @pytest.fixture
28
+ def arrays_for_binary_ufunc():
29
+ """
30
+ A pair of random, length-100 integer-dtype arrays, that are mostly 0.
31
+ """
32
+ a1 = np.random.default_rng(2).integers(0, 10, 100, dtype="int64")
33
+ a2 = np.random.default_rng(2).integers(0, 10, 100, dtype="int64")
34
+ a1[::3] = 0
35
+ a2[::4] = 0
36
+ return a1, a2
37
+
38
+
39
+ @pytest.mark.parametrize("ufunc", [np.positive, np.floor, np.exp])
40
+ def test_unary_ufunc(ufunc, sparse):
41
+ # Test that ufunc(pd.Series) == pd.Series(ufunc)
42
+ arr = np.random.default_rng(2).integers(0, 10, 10, dtype="int64")
43
+ arr[::2] = 0
44
+ if sparse:
45
+ arr = SparseArray(arr, dtype=pd.SparseDtype("int64", 0))
46
+
47
+ index = list(string.ascii_letters[:10])
48
+ name = "name"
49
+ series = pd.Series(arr, index=index, name=name)
50
+
51
+ result = ufunc(series)
52
+ expected = pd.Series(ufunc(arr), index=index, name=name)
53
+ tm.assert_series_equal(result, expected)
54
+
55
+
56
+ @pytest.mark.parametrize("flip", [True, False], ids=["flipped", "straight"])
57
+ def test_binary_ufunc_with_array(flip, sparse, ufunc, arrays_for_binary_ufunc):
58
+ # Test that ufunc(pd.Series(a), array) == pd.Series(ufunc(a, b))
59
+ a1, a2 = arrays_for_binary_ufunc
60
+ if sparse:
61
+ a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0))
62
+ a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
63
+
64
+ name = "name" # op(pd.Series, array) preserves the name.
65
+ series = pd.Series(a1, name=name)
66
+ other = a2
67
+
68
+ array_args = (a1, a2)
69
+ series_args = (series, other) # ufunc(series, array)
70
+
71
+ if flip:
72
+ array_args = reversed(array_args)
73
+ series_args = reversed(series_args) # ufunc(array, series)
74
+
75
+ expected = pd.Series(ufunc(*array_args), name=name)
76
+ result = ufunc(*series_args)
77
+ tm.assert_series_equal(result, expected)
78
+
79
+
80
+ @pytest.mark.parametrize("flip", [True, False], ids=["flipped", "straight"])
81
+ def test_binary_ufunc_with_index(flip, sparse, ufunc, arrays_for_binary_ufunc):
82
+ # Test that
83
+ # * func(pd.Series(a), pd.Series(b)) == pd.Series(ufunc(a, b))
84
+ # * ufunc(Index, pd.Series) dispatches to pd.Series (returns a pd.Series)
85
+ a1, a2 = arrays_for_binary_ufunc
86
+ if sparse:
87
+ a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0))
88
+ a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
89
+
90
+ name = "name" # op(pd.Series, array) preserves the name.
91
+ series = pd.Series(a1, name=name)
92
+
93
+ other = pd.Index(a2, name=name).astype("int64")
94
+
95
+ array_args = (a1, a2)
96
+ series_args = (series, other) # ufunc(series, array)
97
+
98
+ if flip:
99
+ array_args = reversed(array_args)
100
+ series_args = reversed(series_args) # ufunc(array, series)
101
+
102
+ expected = pd.Series(ufunc(*array_args), name=name)
103
+ result = ufunc(*series_args)
104
+ tm.assert_series_equal(result, expected)
105
+
106
+
107
+ @pytest.mark.parametrize("shuffle", [True, False], ids=["unaligned", "aligned"])
108
+ @pytest.mark.parametrize("flip", [True, False], ids=["flipped", "straight"])
109
+ def test_binary_ufunc_with_series(
110
+ flip, shuffle, sparse, ufunc, arrays_for_binary_ufunc
111
+ ):
112
+ # Test that
113
+ # * func(pd.Series(a), pd.Series(b)) == pd.Series(ufunc(a, b))
114
+ # with alignment between the indices
115
+ a1, a2 = arrays_for_binary_ufunc
116
+ if sparse:
117
+ a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0))
118
+ a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
119
+
120
+ name = "name" # op(pd.Series, array) preserves the name.
121
+ series = pd.Series(a1, name=name)
122
+ other = pd.Series(a2, name=name)
123
+
124
+ idx = np.random.default_rng(2).permutation(len(a1))
125
+
126
+ if shuffle:
127
+ other = other.take(idx)
128
+ if flip:
129
+ index = other.align(series)[0].index
130
+ else:
131
+ index = series.align(other)[0].index
132
+ else:
133
+ index = series.index
134
+
135
+ array_args = (a1, a2)
136
+ series_args = (series, other) # ufunc(series, array)
137
+
138
+ if flip:
139
+ array_args = tuple(reversed(array_args))
140
+ series_args = tuple(reversed(series_args)) # ufunc(array, series)
141
+
142
+ expected = pd.Series(ufunc(*array_args), index=index, name=name)
143
+ result = ufunc(*series_args)
144
+ tm.assert_series_equal(result, expected)
145
+
146
+
147
+ @pytest.mark.parametrize("flip", [True, False])
148
+ def test_binary_ufunc_scalar(ufunc, sparse, flip, arrays_for_binary_ufunc):
149
+ # Test that
150
+ # * ufunc(pd.Series, scalar) == pd.Series(ufunc(array, scalar))
151
+ # * ufunc(pd.Series, scalar) == ufunc(scalar, pd.Series)
152
+ arr, _ = arrays_for_binary_ufunc
153
+ if sparse:
154
+ arr = SparseArray(arr)
155
+ other = 2
156
+ series = pd.Series(arr, name="name")
157
+
158
+ series_args = (series, other)
159
+ array_args = (arr, other)
160
+
161
+ if flip:
162
+ series_args = tuple(reversed(series_args))
163
+ array_args = tuple(reversed(array_args))
164
+
165
+ expected = pd.Series(ufunc(*array_args), name="name")
166
+ result = ufunc(*series_args)
167
+
168
+ tm.assert_series_equal(result, expected)
169
+
170
+
171
+ @pytest.mark.parametrize("ufunc", [np.divmod]) # TODO: np.modf, np.frexp
172
+ @pytest.mark.parametrize("shuffle", [True, False])
173
+ @pytest.mark.filterwarnings("ignore:divide by zero:RuntimeWarning")
174
+ def test_multiple_output_binary_ufuncs(ufunc, sparse, shuffle, arrays_for_binary_ufunc):
175
+ # Test that
176
+ # the same conditions from binary_ufunc_scalar apply to
177
+ # ufuncs with multiple outputs.
178
+
179
+ a1, a2 = arrays_for_binary_ufunc
180
+ # work around https://github.com/pandas-dev/pandas/issues/26987
181
+ a1[a1 == 0] = 1
182
+ a2[a2 == 0] = 1
183
+
184
+ if sparse:
185
+ a1 = SparseArray(a1, dtype=pd.SparseDtype("int64", 0))
186
+ a2 = SparseArray(a2, dtype=pd.SparseDtype("int64", 0))
187
+
188
+ s1 = pd.Series(a1)
189
+ s2 = pd.Series(a2)
190
+
191
+ if shuffle:
192
+ # ensure we align before applying the ufunc
193
+ s2 = s2.sample(frac=1)
194
+
195
+ expected = ufunc(a1, a2)
196
+ assert isinstance(expected, tuple)
197
+
198
+ result = ufunc(s1, s2)
199
+ assert isinstance(result, tuple)
200
+ tm.assert_series_equal(result[0], pd.Series(expected[0]))
201
+ tm.assert_series_equal(result[1], pd.Series(expected[1]))
202
+
203
+
204
+ def test_multiple_output_ufunc(sparse, arrays_for_binary_ufunc):
205
+ # Test that the same conditions from unary input apply to multi-output
206
+ # ufuncs
207
+ arr, _ = arrays_for_binary_ufunc
208
+
209
+ if sparse:
210
+ arr = SparseArray(arr)
211
+
212
+ series = pd.Series(arr, name="name")
213
+ result = np.modf(series)
214
+ expected = np.modf(arr)
215
+
216
+ assert isinstance(result, tuple)
217
+ assert isinstance(expected, tuple)
218
+
219
+ tm.assert_series_equal(result[0], pd.Series(expected[0], name="name"))
220
+ tm.assert_series_equal(result[1], pd.Series(expected[1], name="name"))
221
+
222
+
223
+ def test_binary_ufunc_drops_series_name(ufunc, sparse, arrays_for_binary_ufunc):
224
+ # Drop the names when they differ.
225
+ a1, a2 = arrays_for_binary_ufunc
226
+ s1 = pd.Series(a1, name="a")
227
+ s2 = pd.Series(a2, name="b")
228
+
229
+ result = ufunc(s1, s2)
230
+ assert result.name is None
231
+
232
+
233
+ def test_object_series_ok():
234
+ class Dummy:
235
+ def __init__(self, value) -> None:
236
+ self.value = value
237
+
238
+ def __add__(self, other):
239
+ return self.value + other.value
240
+
241
+ arr = np.array([Dummy(0), Dummy(1)])
242
+ ser = pd.Series(arr)
243
+ tm.assert_series_equal(np.add(ser, ser), pd.Series(np.add(ser, arr)))
244
+ tm.assert_series_equal(np.add(ser, Dummy(1)), pd.Series(np.add(ser, Dummy(1))))
245
+
246
+
247
+ @pytest.fixture(
248
+ params=[
249
+ pd.array([1, 3, 2], dtype=np.int64),
250
+ pd.array([1, 3, 2], dtype="Int64"),
251
+ pd.array([1, 3, 2], dtype="Float32"),
252
+ pd.array([1, 10, 2], dtype="Sparse[int]"),
253
+ pd.to_datetime(["2000", "2010", "2001"]),
254
+ pd.to_datetime(["2000", "2010", "2001"]).tz_localize("CET"),
255
+ pd.to_datetime(["2000", "2010", "2001"]).to_period(freq="D"),
256
+ pd.to_timedelta(["1 Day", "3 Days", "2 Days"]),
257
+ pd.IntervalIndex([pd.Interval(0, 1), pd.Interval(2, 3), pd.Interval(1, 2)]),
258
+ ],
259
+ ids=lambda x: str(x.dtype),
260
+ )
261
+ def values_for_np_reduce(request):
262
+ # min/max tests assume that these are monotonic increasing
263
+ return request.param
264
+
265
+
266
+ class TestNumpyReductions:
267
+ # TODO: cases with NAs, axis kwarg for DataFrame
268
+
269
+ def test_multiply(self, values_for_np_reduce, box_with_array, request):
270
+ box = box_with_array
271
+ values = values_for_np_reduce
272
+
273
+ with tm.assert_produces_warning(None):
274
+ obj = box(values)
275
+
276
+ if isinstance(values, pd.core.arrays.SparseArray):
277
+ mark = pytest.mark.xfail(reason="SparseArray has no 'prod'")
278
+ request.applymarker(mark)
279
+
280
+ if values.dtype.kind in "iuf":
281
+ result = np.multiply.reduce(obj)
282
+ if box is pd.DataFrame:
283
+ expected = obj.prod(numeric_only=False)
284
+ tm.assert_series_equal(result, expected)
285
+ elif box is pd.Index:
286
+ # Index has no 'prod'
287
+ expected = obj._values.prod()
288
+ assert result == expected
289
+ else:
290
+ expected = obj.prod()
291
+ assert result == expected
292
+ else:
293
+ msg = "|".join(
294
+ [
295
+ "does not support operation",
296
+ "unsupported operand type",
297
+ "ufunc 'multiply' cannot use operands",
298
+ ]
299
+ )
300
+ with pytest.raises(TypeError, match=msg):
301
+ np.multiply.reduce(obj)
302
+
303
+ def test_add(self, values_for_np_reduce, box_with_array):
304
+ box = box_with_array
305
+ values = values_for_np_reduce
306
+
307
+ with tm.assert_produces_warning(None):
308
+ obj = box(values)
309
+
310
+ if values.dtype.kind in "miuf":
311
+ result = np.add.reduce(obj)
312
+ if box is pd.DataFrame:
313
+ expected = obj.sum(numeric_only=False)
314
+ tm.assert_series_equal(result, expected)
315
+ elif box is pd.Index:
316
+ # Index has no 'sum'
317
+ expected = obj._values.sum()
318
+ assert result == expected
319
+ else:
320
+ expected = obj.sum()
321
+ assert result == expected
322
+ else:
323
+ msg = "|".join(
324
+ [
325
+ "does not support operation",
326
+ "unsupported operand type",
327
+ "ufunc 'add' cannot use operands",
328
+ ]
329
+ )
330
+ with pytest.raises(TypeError, match=msg):
331
+ np.add.reduce(obj)
332
+
333
+ def test_max(self, values_for_np_reduce, box_with_array, using_python_scalars):
334
+ box = box_with_array
335
+ values = values_for_np_reduce
336
+
337
+ same_type = True
338
+ if box is pd.Index and values.dtype.kind in "if":
339
+ # ATM Index casts to object, so we get python ints/floats
340
+ same_type = False
341
+
342
+ with tm.assert_produces_warning(None):
343
+ obj = box(values)
344
+
345
+ result = np.maximum.reduce(obj)
346
+ if box is pd.DataFrame:
347
+ # TODO: cases with axis kwarg
348
+ expected = obj.max(numeric_only=False)
349
+ tm.assert_series_equal(result, expected)
350
+ else:
351
+ expected = values[1]
352
+ if using_python_scalars and values.dtype.kind in "if":
353
+ expected = expected.item()
354
+ assert result == expected
355
+ if same_type:
356
+ # check we have e.g. Timestamp instead of dt64
357
+ assert type(result) == type(expected)
358
+
359
+ def test_min(self, values_for_np_reduce, box_with_array, using_python_scalars):
360
+ box = box_with_array
361
+ values = values_for_np_reduce
362
+
363
+ same_type = True
364
+ if box is pd.Index and values.dtype.kind in "if":
365
+ # ATM Index casts to object, so we get python ints/floats
366
+ same_type = False
367
+
368
+ with tm.assert_produces_warning(None):
369
+ obj = box(values)
370
+
371
+ result = np.minimum.reduce(obj)
372
+ if box is pd.DataFrame:
373
+ expected = obj.min(numeric_only=False)
374
+ tm.assert_series_equal(result, expected)
375
+ else:
376
+ expected = values[0]
377
+ if using_python_scalars and values.dtype.kind in ["i", "f"]:
378
+ expected = expected.item()
379
+ assert result == expected
380
+ if same_type:
381
+ # check we have e.g. Timestamp instead of dt64
382
+ assert type(result) == type(expected)
383
+
384
+
385
+ @pytest.mark.parametrize("type_", [list, deque, tuple])
386
+ def test_binary_ufunc_other_types(type_):
387
+ a = pd.Series([1, 2, 3], name="name")
388
+ b = type_([3, 4, 5])
389
+
390
+ result = np.add(a, b)
391
+ expected = pd.Series(np.add(a.to_numpy(), b), name="name")
392
+ tm.assert_series_equal(result, expected)
393
+
394
+
395
+ def test_object_dtype_ok():
396
+ class Thing:
397
+ def __init__(self, value) -> None:
398
+ self.value = value
399
+
400
+ def __add__(self, other):
401
+ other = getattr(other, "value", other)
402
+ return type(self)(self.value + other)
403
+
404
+ def __eq__(self, other) -> bool:
405
+ return type(other) is Thing and self.value == other.value
406
+
407
+ def __repr__(self) -> str:
408
+ return f"Thing({self.value})"
409
+
410
+ s = pd.Series([Thing(1), Thing(2)])
411
+ result = np.add(s, Thing(1))
412
+ expected = pd.Series([Thing(2), Thing(3)])
413
+ tm.assert_series_equal(result, expected)
414
+
415
+
416
+ def test_outer():
417
+ # https://github.com/pandas-dev/pandas/issues/27186
418
+ ser = pd.Series([1, 2, 3])
419
+ obj = np.array([1, 2, 3])
420
+
421
+ with pytest.raises(NotImplementedError, match="^$"):
422
+ np.subtract.outer(ser, obj)
423
+
424
+
425
+ def test_np_matmul():
426
+ # GH26650
427
+ df1 = pd.DataFrame(data=[[-1, 1, 10]])
428
+ df2 = pd.DataFrame(data=[-1, 1, 10])
429
+ expected = pd.DataFrame(data=[102])
430
+
431
+ result = np.matmul(df1, df2)
432
+ tm.assert_frame_equal(expected, result)
433
+
434
+
435
+ @pytest.mark.parametrize("box", [pd.Index, pd.Series])
436
+ def test_np_matmul_1D(box, using_python_scalars):
437
+ result = np.matmul(box([1, 2]), box([2, 3]))
438
+ assert result == 8
439
+ if using_python_scalars:
440
+ assert type(result) == int, type(result)
441
+ else:
442
+ assert type(result) == np.int64, type(result)
443
+
444
+
445
+ def test_array_ufuncs_for_many_arguments():
446
+ # GH39853
447
+ def add3(x, y, z):
448
+ return x + y + z
449
+
450
+ ufunc = np.frompyfunc(add3, 3, 1)
451
+ ser = pd.Series([1, 2])
452
+
453
+ result = ufunc(ser, ser, 1)
454
+ expected = pd.Series([3, 5], dtype=object)
455
+ tm.assert_series_equal(result, expected)
456
+
457
+ df = pd.DataFrame([[1, 2]])
458
+
459
+ msg = (
460
+ "Cannot apply ufunc <ufunc 'add3 (vectorized)'> "
461
+ "to mixed DataFrame and Series inputs."
462
+ )
463
+ with pytest.raises(NotImplementedError, match=re.escape(msg)):
464
+ ufunc(ser, ser, df)
465
+
466
+
467
+ def test_np_trunc():
468
+ # This used to test np.fix, which is not a ufunc but is composed of
469
+ # several ufunc calls under the hood with `out` and `where` keywords. But numpy
470
+ # is deprecating that (or at least discussing deprecating) in favor of np.trunc,
471
+ # which _is_ a ufunc without the out keyword usage.
472
+ ser = pd.Series([-1.5, -0.5, 0.5, 1.5])
473
+ result = np.trunc(ser)
474
+ expected = pd.Series([-1.0, -0.0, 0.0, 1.0])
475
+ tm.assert_series_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_unary.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas import Series
4
+ import pandas._testing as tm
5
+
6
+
7
+ class TestSeriesUnaryOps:
8
+ # __neg__, __pos__, __invert__
9
+
10
+ def test_neg(self):
11
+ ser = Series(range(5), dtype="float64", name="series")
12
+ tm.assert_series_equal(-ser, -1 * ser)
13
+
14
+ def test_invert(self):
15
+ ser = Series(range(5), dtype="float64", name="series")
16
+ tm.assert_series_equal(-(ser < 0), ~(ser < 0))
17
+
18
+ @pytest.mark.parametrize(
19
+ "source, neg_target, abs_target",
20
+ [
21
+ ([1, 2, 3], [-1, -2, -3], [1, 2, 3]),
22
+ ([1, 2, None], [-1, -2, None], [1, 2, None]),
23
+ ],
24
+ )
25
+ def test_all_numeric_unary_operators(
26
+ self, any_numeric_ea_dtype, source, neg_target, abs_target
27
+ ):
28
+ # GH38794
29
+ dtype = any_numeric_ea_dtype
30
+ ser = Series(source, dtype=dtype)
31
+ neg_result, pos_result, abs_result = -ser, +ser, abs(ser)
32
+ if dtype.startswith("U"):
33
+ neg_target = -Series(source, dtype=dtype)
34
+ else:
35
+ neg_target = Series(neg_target, dtype=dtype)
36
+
37
+ abs_target = Series(abs_target, dtype=dtype)
38
+
39
+ tm.assert_series_equal(neg_result, neg_target)
40
+ tm.assert_series_equal(pos_result, ser)
41
+ tm.assert_series_equal(abs_result, abs_target)
42
+
43
+ @pytest.mark.parametrize("op", ["__neg__", "__abs__"])
44
+ def test_unary_float_op_mask(self, float_ea_dtype, op):
45
+ dtype = float_ea_dtype
46
+ ser = Series([1.1, 2.2, 3.3], dtype=dtype)
47
+ result = getattr(ser, op)()
48
+ target = result.copy(deep=True)
49
+ ser[0] = None
50
+ tm.assert_series_equal(result, target)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/series/test_validate.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+
4
+ @pytest.mark.parametrize(
5
+ "func",
6
+ [
7
+ "reset_index",
8
+ "_set_name",
9
+ "sort_values",
10
+ "sort_index",
11
+ "rename",
12
+ "dropna",
13
+ "drop_duplicates",
14
+ ],
15
+ )
16
+ @pytest.mark.parametrize("inplace", [1, "True", [1, 2, 3], 5.0])
17
+ def test_validate_bool_args(string_series, func, inplace):
18
+ """Tests for error handling related to data types of method arguments."""
19
+ msg = 'For argument "inplace" expected type bool'
20
+ kwargs = {"inplace": inplace}
21
+
22
+ if func == "_set_name":
23
+ kwargs["name"] = "hello"
24
+
25
+ with pytest.raises(ValueError, match=msg):
26
+ getattr(string_series, func)(**kwargs)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import pandas as pd
4
+
5
+
6
+ def is_object_or_nan_string_dtype(dtype):
7
+ """
8
+ Check if string-like dtype is following NaN semantics, i.e. is object
9
+ dtype or a NaN-variant of the StringDtype.
10
+ """
11
+ return (isinstance(dtype, np.dtype) and dtype == "object") or (
12
+ dtype.na_value is np.nan
13
+ )
14
+
15
+
16
+ def _convert_na_value(ser, expected):
17
+ if ser.dtype != object:
18
+ if ser.dtype.na_value is np.nan:
19
+ expected = expected.fillna(np.nan)
20
+ else:
21
+ # GH#18463
22
+ expected = expected.fillna(pd.NA)
23
+ return expected
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/conftest.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas import Series
4
+ from pandas.core.strings.accessor import StringMethods
5
+
6
+ _any_string_method = [
7
+ ("cat", (), {"sep": ","}),
8
+ ("cat", (Series(list("zyx")),), {"sep": ",", "join": "left"}),
9
+ ("center", (10,), {}),
10
+ ("contains", ("a",), {}),
11
+ ("count", ("a",), {}),
12
+ ("decode", ("UTF-8",), {}),
13
+ ("encode", ("UTF-8",), {}),
14
+ ("endswith", ("a",), {}),
15
+ ("endswith", ((),), {}),
16
+ ("endswith", (("a",),), {}),
17
+ ("endswith", (("a", "b"),), {}),
18
+ ("endswith", (("a", "MISSING"),), {}),
19
+ ("endswith", ("a",), {"na": True}),
20
+ ("endswith", ("a",), {"na": False}),
21
+ ("extract", ("([a-z]*)",), {"expand": False}),
22
+ ("extract", ("([a-z]*)",), {"expand": True}),
23
+ ("extractall", ("([a-z]*)",), {}),
24
+ ("find", ("a",), {}),
25
+ ("findall", ("a",), {}),
26
+ ("get", (0,), {}),
27
+ # because "index" (and "rindex") fail intentionally
28
+ # if the string is not found, search only for empty string
29
+ ("index", ("",), {}),
30
+ ("join", (",",), {}),
31
+ ("ljust", (10,), {}),
32
+ ("match", ("a",), {}),
33
+ ("fullmatch", ("a",), {}),
34
+ ("normalize", ("NFC",), {}),
35
+ ("pad", (10,), {}),
36
+ ("partition", (" ",), {"expand": False}),
37
+ ("partition", (" ",), {"expand": True}),
38
+ ("repeat", (3,), {}),
39
+ ("replace", ("a", "z"), {}),
40
+ ("rfind", ("a",), {}),
41
+ ("rindex", ("",), {}),
42
+ ("rjust", (10,), {}),
43
+ ("rpartition", (" ",), {"expand": False}),
44
+ ("rpartition", (" ",), {"expand": True}),
45
+ ("slice", (0, 1), {}),
46
+ ("slice_replace", (0, 1, "z"), {}),
47
+ ("split", (" ",), {"expand": False}),
48
+ ("split", (" ",), {"expand": True}),
49
+ ("startswith", ("a",), {}),
50
+ ("startswith", (("a",),), {}),
51
+ ("startswith", (("a", "b"),), {}),
52
+ ("startswith", (("a", "MISSING"),), {}),
53
+ ("startswith", ((),), {}),
54
+ ("startswith", ("a",), {"na": True}),
55
+ ("startswith", ("a",), {"na": False}),
56
+ ("removeprefix", ("a",), {}),
57
+ ("removesuffix", ("a",), {}),
58
+ # translating unicode points of "a" to "d"
59
+ ("translate", ({97: 100},), {}),
60
+ ("wrap", (2,), {}),
61
+ ("zfill", (10,), {}),
62
+ # methods without positional arguments: zip with empty tuple and empty dict
63
+ *zip(
64
+ [
65
+ "capitalize",
66
+ "cat",
67
+ "get_dummies",
68
+ "isalnum",
69
+ "isalpha",
70
+ "isascii",
71
+ "isdecimal",
72
+ "isdigit",
73
+ "islower",
74
+ "isnumeric",
75
+ "isspace",
76
+ "istitle",
77
+ "isupper",
78
+ "len",
79
+ "lower",
80
+ "lstrip",
81
+ "partition",
82
+ "rpartition",
83
+ "rsplit",
84
+ "rstrip",
85
+ "slice",
86
+ "slice_replace",
87
+ "split",
88
+ "strip",
89
+ "swapcase",
90
+ "title",
91
+ "upper",
92
+ "casefold",
93
+ ],
94
+ [()] * 100,
95
+ [{}] * 100,
96
+ ),
97
+ ]
98
+ ids, _, _ = zip(*_any_string_method) # use method name as fixture-id
99
+ missing_methods = {f for f in dir(StringMethods) if not f.startswith("_")} - set(ids)
100
+
101
+ # test that the above list captures all methods of StringMethods
102
+ assert not missing_methods
103
+
104
+
105
+ @pytest.fixture(params=_any_string_method, ids=ids)
106
+ def any_string_method(request):
107
+ """
108
+ Fixture for all public methods of `StringMethods`
109
+
110
+ This fixture returns a tuple of the method name and sample arguments
111
+ necessary to call the method.
112
+
113
+ Returns
114
+ -------
115
+ method_name : str
116
+ The name of the method in `StringMethods`
117
+ args : tuple
118
+ Sample values for the positional arguments
119
+ kwargs : dict
120
+ Sample values for the keyword arguments
121
+
122
+ Examples
123
+ --------
124
+ >>> def test_something(any_string_method):
125
+ ... s = Series(["a", "b", np.nan, "d"])
126
+ ...
127
+ ... method_name, args, kwargs = any_string_method
128
+ ... method = getattr(s.str, method_name)
129
+ ... # will not raise
130
+ ... method(*args, **kwargs)
131
+ """
132
+ return request.param
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_api.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import weakref
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas import (
7
+ CategoricalDtype,
8
+ DataFrame,
9
+ Index,
10
+ MultiIndex,
11
+ Series,
12
+ _testing as tm,
13
+ )
14
+ from pandas.core.strings.accessor import StringMethods
15
+
16
+ # subset of the full set from pandas/conftest.py
17
+ _any_allowed_skipna_inferred_dtype = [
18
+ ("string", ["a", np.nan, "c"]),
19
+ ("bytes", [b"a", np.nan, b"c"]),
20
+ ("empty", [np.nan, np.nan, np.nan]),
21
+ ("empty", []),
22
+ ("mixed-integer", ["a", np.nan, 2]),
23
+ ]
24
+ ids, _ = zip(
25
+ *_any_allowed_skipna_inferred_dtype, strict=True
26
+ ) # use inferred type as id
27
+
28
+
29
+ @pytest.fixture(params=_any_allowed_skipna_inferred_dtype, ids=ids)
30
+ def any_allowed_skipna_inferred_dtype(request):
31
+ """
32
+ Fixture for all (inferred) dtypes allowed in StringMethods.__init__
33
+
34
+ The covered (inferred) types are:
35
+ * 'string'
36
+ * 'empty'
37
+ * 'bytes'
38
+ * 'mixed'
39
+ * 'mixed-integer'
40
+
41
+ Returns
42
+ -------
43
+ inferred_dtype : str
44
+ The string for the inferred dtype from _libs.lib.infer_dtype
45
+ values : np.ndarray
46
+ An array of object dtype that will be inferred to have
47
+ `inferred_dtype`
48
+
49
+ Examples
50
+ --------
51
+ >>> from pandas._libs import lib
52
+ >>>
53
+ >>> def test_something(any_allowed_skipna_inferred_dtype):
54
+ ... inferred_dtype, values = any_allowed_skipna_inferred_dtype
55
+ ... # will pass
56
+ ... assert lib.infer_dtype(values, skipna=True) == inferred_dtype
57
+ ...
58
+ ... # constructor for .str-accessor will also pass
59
+ ... Series(values).str
60
+ """
61
+ inferred_dtype, values = request.param
62
+ values = np.array(values, dtype=object) # object dtype to avoid casting
63
+
64
+ # correctness of inference tested in tests/dtypes/test_inference.py
65
+ return inferred_dtype, values
66
+
67
+
68
+ def test_api(any_string_dtype):
69
+ # GH 6106, GH 9322
70
+ assert Series.str is StringMethods
71
+ assert isinstance(Series([""], dtype=any_string_dtype).str, StringMethods)
72
+
73
+
74
+ def test_no_circular_reference(any_string_dtype):
75
+ # GH 47667
76
+ ser = Series([""], dtype=any_string_dtype)
77
+ ref = weakref.ref(ser)
78
+ ser.str # Used to cache and cause circular reference
79
+ del ser
80
+ assert ref() is None
81
+
82
+
83
+ def test_api_mi_raises():
84
+ # GH 23679
85
+ mi = MultiIndex.from_arrays([["a", "b", "c"]])
86
+ msg = "Can only use .str accessor with Index, not MultiIndex"
87
+ with pytest.raises(AttributeError, match=msg):
88
+ mi.str
89
+ assert not hasattr(mi, "str")
90
+
91
+
92
+ @pytest.mark.parametrize("dtype", [object, "category"])
93
+ def test_api_per_dtype(index_or_series, dtype, any_skipna_inferred_dtype):
94
+ # one instance of parametrized fixture
95
+ box = index_or_series
96
+ inferred_dtype, values = any_skipna_inferred_dtype
97
+
98
+ t = box(values, dtype=dtype) # explicit dtype to avoid casting
99
+
100
+ types_passing_constructor = [
101
+ "string",
102
+ "unicode",
103
+ "empty",
104
+ "bytes",
105
+ "mixed",
106
+ "mixed-integer",
107
+ ]
108
+ if inferred_dtype in types_passing_constructor:
109
+ # GH 6106
110
+ assert isinstance(t.str, StringMethods)
111
+ else:
112
+ # GH 9184, GH 23011, GH 23163
113
+ msg = "Can only use .str accessor with string values.*"
114
+ with pytest.raises(AttributeError, match=msg):
115
+ t.str
116
+ assert not hasattr(t, "str")
117
+
118
+
119
+ @pytest.mark.parametrize("dtype", [object, "category"])
120
+ def test_api_per_method(
121
+ index_or_series,
122
+ dtype,
123
+ any_allowed_skipna_inferred_dtype,
124
+ any_string_method,
125
+ request,
126
+ using_infer_string,
127
+ ):
128
+ # this test does not check correctness of the different methods,
129
+ # just that the methods work on the specified (inferred) dtypes,
130
+ # and raise on all others
131
+ box = index_or_series
132
+
133
+ # one instance of each parametrized fixture
134
+ inferred_dtype, values = any_allowed_skipna_inferred_dtype
135
+ method_name, args, kwargs = any_string_method
136
+
137
+ reason = None
138
+ if box is Index and values.size == 0:
139
+ if method_name in ["partition", "rpartition"] and kwargs.get("expand", True):
140
+ raises = TypeError
141
+ reason = "Method cannot deal with empty Index"
142
+ elif method_name == "split" and kwargs.get("expand", None):
143
+ raises = TypeError
144
+ reason = "Split fails on empty Series when expand=True"
145
+ elif method_name == "get_dummies":
146
+ raises = ValueError
147
+ reason = "Need to fortify get_dummies corner cases"
148
+
149
+ elif (
150
+ box is Index
151
+ and inferred_dtype == "empty"
152
+ and dtype == object
153
+ and method_name == "get_dummies"
154
+ ):
155
+ raises = ValueError
156
+ reason = "Need to fortify get_dummies corner cases"
157
+
158
+ if reason is not None:
159
+ mark = pytest.mark.xfail(raises=raises, reason=reason)
160
+ request.applymarker(mark)
161
+
162
+ t = box(values, dtype=dtype) # explicit dtype to avoid casting
163
+ method = getattr(t.str, method_name)
164
+
165
+ if using_infer_string and dtype == "category":
166
+ string_allowed = method_name not in ["decode"]
167
+ else:
168
+ string_allowed = True
169
+ bytes_allowed = method_name in ["decode", "get", "len", "slice"]
170
+ # as of v0.23.4, all methods except 'cat' are very lenient with the
171
+ # allowed data types, just returning NaN for entries that error.
172
+ # This could be changed with an 'errors'-kwarg to the `str`-accessor,
173
+ # see discussion in GH 13877
174
+ mixed_allowed = method_name not in ["cat"]
175
+
176
+ allowed_types = (
177
+ ["empty"]
178
+ + ["string", "unicode"] * string_allowed
179
+ + ["bytes"] * bytes_allowed
180
+ + ["mixed", "mixed-integer"] * mixed_allowed
181
+ )
182
+
183
+ if inferred_dtype in allowed_types:
184
+ # xref GH 23555, GH 23556
185
+ method(*args, **kwargs) # works!
186
+ else:
187
+ # GH 23011, GH 23163
188
+ msg = (
189
+ f"Cannot use .str.{method_name} with values of "
190
+ f"inferred dtype {inferred_dtype!r}."
191
+ "|a bytes-like object is required, not 'str'"
192
+ )
193
+ with pytest.raises(TypeError, match=msg):
194
+ method(*args, **kwargs)
195
+
196
+
197
+ def test_api_for_categorical(any_string_method, any_string_dtype):
198
+ # https://github.com/pandas-dev/pandas/issues/10661
199
+ s = Series(list("aabb"), dtype=any_string_dtype)
200
+ s = s + " " + s
201
+ c = s.astype("category")
202
+ c = c.astype(CategoricalDtype(c.dtype.categories.astype("object")))
203
+ assert isinstance(c.str, StringMethods)
204
+
205
+ method_name, args, kwargs = any_string_method
206
+
207
+ result = getattr(c.str, method_name)(*args, **kwargs)
208
+ expected = getattr(s.astype("object").str, method_name)(*args, **kwargs)
209
+
210
+ if isinstance(result, DataFrame):
211
+ tm.assert_frame_equal(result, expected)
212
+ elif isinstance(result, Series):
213
+ tm.assert_series_equal(result, expected)
214
+ else:
215
+ # str.cat(others=None) returns string, for example
216
+ assert result == expected
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_case_justify.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import operator
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas import (
8
+ Series,
9
+ _testing as tm,
10
+ )
11
+
12
+
13
+ def test_title(any_string_dtype):
14
+ s = Series(["FOO", "BAR", np.nan, "Blah", "blurg"], dtype=any_string_dtype)
15
+ result = s.str.title()
16
+ expected = Series(["Foo", "Bar", np.nan, "Blah", "Blurg"], dtype=any_string_dtype)
17
+ tm.assert_series_equal(result, expected)
18
+
19
+
20
+ def test_title_mixed_object():
21
+ s = Series(["FOO", np.nan, "bar", True, datetime.today(), "blah", None, 1, 2.0])
22
+ result = s.str.title()
23
+ expected = Series(
24
+ ["Foo", np.nan, "Bar", np.nan, np.nan, "Blah", None, np.nan, np.nan],
25
+ dtype=object,
26
+ )
27
+ tm.assert_almost_equal(result, expected)
28
+
29
+
30
+ def test_lower_upper(any_string_dtype):
31
+ s = Series(["om", np.nan, "nom", "nom"], dtype=any_string_dtype)
32
+
33
+ result = s.str.upper()
34
+ expected = Series(["OM", np.nan, "NOM", "NOM"], dtype=any_string_dtype)
35
+ tm.assert_series_equal(result, expected)
36
+
37
+ result = result.str.lower()
38
+ tm.assert_series_equal(result, s)
39
+
40
+
41
+ def test_lower_upper_mixed_object():
42
+ s = Series(["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0])
43
+
44
+ result = s.str.upper()
45
+ expected = Series(
46
+ ["A", np.nan, "B", np.nan, np.nan, "FOO", None, np.nan, np.nan], dtype=object
47
+ )
48
+ tm.assert_series_equal(result, expected)
49
+
50
+ result = s.str.lower()
51
+ expected = Series(
52
+ ["a", np.nan, "b", np.nan, np.nan, "foo", None, np.nan, np.nan], dtype=object
53
+ )
54
+ tm.assert_series_equal(result, expected)
55
+
56
+
57
+ @pytest.mark.parametrize(
58
+ "data, expected",
59
+ [
60
+ (
61
+ ["FOO", "BAR", np.nan, "Blah", "blurg"],
62
+ ["Foo", "Bar", np.nan, "Blah", "Blurg"],
63
+ ),
64
+ (["a", "b", "c"], ["A", "B", "C"]),
65
+ (["a b", "a bc. de"], ["A b", "A bc. de"]),
66
+ ],
67
+ )
68
+ def test_capitalize(data, expected, any_string_dtype):
69
+ s = Series(data, dtype=any_string_dtype)
70
+ result = s.str.capitalize()
71
+ expected = Series(expected, dtype=any_string_dtype)
72
+ tm.assert_series_equal(result, expected)
73
+
74
+
75
+ def test_capitalize_mixed_object():
76
+ s = Series(["FOO", np.nan, "bar", True, datetime.today(), "blah", None, 1, 2.0])
77
+ result = s.str.capitalize()
78
+ expected = Series(
79
+ ["Foo", np.nan, "Bar", np.nan, np.nan, "Blah", None, np.nan, np.nan],
80
+ dtype=object,
81
+ )
82
+ tm.assert_series_equal(result, expected)
83
+
84
+
85
+ def test_swapcase(any_string_dtype):
86
+ s = Series(["FOO", "BAR", np.nan, "Blah", "blurg"], dtype=any_string_dtype)
87
+ result = s.str.swapcase()
88
+ expected = Series(["foo", "bar", np.nan, "bLAH", "BLURG"], dtype=any_string_dtype)
89
+ tm.assert_series_equal(result, expected)
90
+
91
+
92
+ def test_swapcase_mixed_object():
93
+ s = Series(["FOO", np.nan, "bar", True, datetime.today(), "Blah", None, 1, 2.0])
94
+ result = s.str.swapcase()
95
+ expected = Series(
96
+ ["foo", np.nan, "BAR", np.nan, np.nan, "bLAH", None, np.nan, np.nan],
97
+ dtype=object,
98
+ )
99
+ tm.assert_series_equal(result, expected)
100
+
101
+
102
+ def test_casefold():
103
+ # GH25405
104
+ expected = Series(["ss", np.nan, "case", "ssd"])
105
+ s = Series(["ß", np.nan, "case", "ßd"])
106
+ result = s.str.casefold()
107
+
108
+ tm.assert_series_equal(result, expected)
109
+
110
+
111
+ def test_casemethods(any_string_dtype):
112
+ values = ["aaa", "bbb", "CCC", "Dddd", "eEEE"]
113
+ s = Series(values, dtype=any_string_dtype)
114
+ assert s.str.lower().tolist() == [v.lower() for v in values]
115
+ assert s.str.upper().tolist() == [v.upper() for v in values]
116
+ assert s.str.title().tolist() == [v.title() for v in values]
117
+ assert s.str.capitalize().tolist() == [v.capitalize() for v in values]
118
+ assert s.str.swapcase().tolist() == [v.swapcase() for v in values]
119
+
120
+
121
+ def test_pad(any_string_dtype):
122
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
123
+
124
+ result = s.str.pad(5, side="left")
125
+ expected = Series(
126
+ [" a", " b", np.nan, " c", np.nan, "eeeeee"], dtype=any_string_dtype
127
+ )
128
+ tm.assert_series_equal(result, expected)
129
+
130
+ result = s.str.pad(5, side="right")
131
+ expected = Series(
132
+ ["a ", "b ", np.nan, "c ", np.nan, "eeeeee"], dtype=any_string_dtype
133
+ )
134
+ tm.assert_series_equal(result, expected)
135
+
136
+ result = s.str.pad(5, side="both")
137
+ expected = Series(
138
+ [" a ", " b ", np.nan, " c ", np.nan, "eeeeee"], dtype=any_string_dtype
139
+ )
140
+ tm.assert_series_equal(result, expected)
141
+
142
+
143
+ def test_pad_mixed_object():
144
+ s = Series(["a", np.nan, "b", True, datetime.today(), "ee", None, 1, 2.0])
145
+
146
+ result = s.str.pad(5, side="left")
147
+ expected = Series(
148
+ [" a", np.nan, " b", np.nan, np.nan, " ee", None, np.nan, np.nan],
149
+ dtype=object,
150
+ )
151
+ tm.assert_series_equal(result, expected)
152
+
153
+ result = s.str.pad(5, side="right")
154
+ expected = Series(
155
+ ["a ", np.nan, "b ", np.nan, np.nan, "ee ", None, np.nan, np.nan],
156
+ dtype=object,
157
+ )
158
+ tm.assert_series_equal(result, expected)
159
+
160
+ result = s.str.pad(5, side="both")
161
+ expected = Series(
162
+ [" a ", np.nan, " b ", np.nan, np.nan, " ee ", None, np.nan, np.nan],
163
+ dtype=object,
164
+ )
165
+ tm.assert_series_equal(result, expected)
166
+
167
+
168
+ def test_pad_fillchar(any_string_dtype):
169
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
170
+
171
+ result = s.str.pad(5, side="left", fillchar="X")
172
+ expected = Series(
173
+ ["XXXXa", "XXXXb", np.nan, "XXXXc", np.nan, "eeeeee"], dtype=any_string_dtype
174
+ )
175
+ tm.assert_series_equal(result, expected)
176
+
177
+ result = s.str.pad(5, side="right", fillchar="X")
178
+ expected = Series(
179
+ ["aXXXX", "bXXXX", np.nan, "cXXXX", np.nan, "eeeeee"], dtype=any_string_dtype
180
+ )
181
+ tm.assert_series_equal(result, expected)
182
+
183
+ result = s.str.pad(5, side="both", fillchar="X")
184
+ expected = Series(
185
+ ["XXaXX", "XXbXX", np.nan, "XXcXX", np.nan, "eeeeee"], dtype=any_string_dtype
186
+ )
187
+ tm.assert_series_equal(result, expected)
188
+
189
+
190
+ def test_pad_fillchar_bad_arg_raises(any_string_dtype):
191
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
192
+
193
+ msg = "fillchar must be a character, not str"
194
+ with pytest.raises(TypeError, match=msg):
195
+ s.str.pad(5, fillchar="XY")
196
+
197
+ msg = "fillchar must be a character, not int"
198
+ with pytest.raises(TypeError, match=msg):
199
+ s.str.pad(5, fillchar=5)
200
+
201
+
202
+ @pytest.mark.parametrize("method_name", ["center", "ljust", "rjust", "zfill", "pad"])
203
+ def test_pad_width_bad_arg_raises(method_name, any_string_dtype):
204
+ # see gh-13598
205
+ s = Series(["1", "22", "a", "bb"], dtype=any_string_dtype)
206
+ op = operator.methodcaller(method_name, "f")
207
+
208
+ msg = "width must be of integer type, not str"
209
+ with pytest.raises(TypeError, match=msg):
210
+ op(s.str)
211
+
212
+
213
+ def test_center_ljust_rjust(any_string_dtype):
214
+ s = Series(["a", "b", np.nan, "c", np.nan, "eeeeee"], dtype=any_string_dtype)
215
+
216
+ result = s.str.center(5)
217
+ expected = Series(
218
+ [" a ", " b ", np.nan, " c ", np.nan, "eeeeee"], dtype=any_string_dtype
219
+ )
220
+ tm.assert_series_equal(result, expected)
221
+
222
+ result = s.str.ljust(5)
223
+ expected = Series(
224
+ ["a ", "b ", np.nan, "c ", np.nan, "eeeeee"], dtype=any_string_dtype
225
+ )
226
+ tm.assert_series_equal(result, expected)
227
+
228
+ result = s.str.rjust(5)
229
+ expected = Series(
230
+ [" a", " b", np.nan, " c", np.nan, "eeeeee"], dtype=any_string_dtype
231
+ )
232
+ tm.assert_series_equal(result, expected)
233
+
234
+
235
+ def test_center_ljust_rjust_mixed_object():
236
+ s = Series(["a", np.nan, "b", True, datetime.today(), "c", "eee", None, 1, 2.0])
237
+
238
+ result = s.str.center(5)
239
+ expected = Series(
240
+ [
241
+ " a ",
242
+ np.nan,
243
+ " b ",
244
+ np.nan,
245
+ np.nan,
246
+ " c ",
247
+ " eee ",
248
+ None,
249
+ np.nan,
250
+ np.nan,
251
+ ],
252
+ dtype=object,
253
+ )
254
+ tm.assert_series_equal(result, expected)
255
+
256
+ result = s.str.ljust(5)
257
+ expected = Series(
258
+ [
259
+ "a ",
260
+ np.nan,
261
+ "b ",
262
+ np.nan,
263
+ np.nan,
264
+ "c ",
265
+ "eee ",
266
+ None,
267
+ np.nan,
268
+ np.nan,
269
+ ],
270
+ dtype=object,
271
+ )
272
+ tm.assert_series_equal(result, expected)
273
+
274
+ result = s.str.rjust(5)
275
+ expected = Series(
276
+ [
277
+ " a",
278
+ np.nan,
279
+ " b",
280
+ np.nan,
281
+ np.nan,
282
+ " c",
283
+ " eee",
284
+ None,
285
+ np.nan,
286
+ np.nan,
287
+ ],
288
+ dtype=object,
289
+ )
290
+ tm.assert_series_equal(result, expected)
291
+
292
+
293
+ def test_center_ljust_rjust_fillchar(any_string_dtype):
294
+ # GH#54533, GH#54792
295
+ s = Series(["a", "bb", "cccc", "ddddd", "eeeeee"], dtype=any_string_dtype)
296
+
297
+ result = s.str.center(5, fillchar="X")
298
+ expected = Series(
299
+ ["XXaXX", "XXbbX", "Xcccc", "ddddd", "eeeeee"], dtype=any_string_dtype
300
+ )
301
+ tm.assert_series_equal(result, expected)
302
+ expected = np.array([v.center(5, "X") for v in np.array(s)], dtype=np.object_)
303
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
304
+
305
+ result = s.str.ljust(5, fillchar="X")
306
+ expected = Series(
307
+ ["aXXXX", "bbXXX", "ccccX", "ddddd", "eeeeee"], dtype=any_string_dtype
308
+ )
309
+ tm.assert_series_equal(result, expected)
310
+ expected = np.array([v.ljust(5, "X") for v in np.array(s)], dtype=np.object_)
311
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
312
+
313
+ result = s.str.rjust(5, fillchar="X")
314
+ expected = Series(
315
+ ["XXXXa", "XXXbb", "Xcccc", "ddddd", "eeeeee"], dtype=any_string_dtype
316
+ )
317
+ tm.assert_series_equal(result, expected)
318
+ expected = np.array([v.rjust(5, "X") for v in np.array(s)], dtype=np.object_)
319
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
320
+
321
+
322
+ def test_center_ljust_rjust_fillchar_bad_arg_raises(any_string_dtype):
323
+ s = Series(["a", "bb", "cccc", "ddddd", "eeeeee"], dtype=any_string_dtype)
324
+
325
+ # If fillchar is not a character, normal str raises TypeError
326
+ # 'aaa'.ljust(5, 'XY')
327
+ # TypeError: must be char, not str
328
+ template = "fillchar must be a character, not {dtype}"
329
+
330
+ with pytest.raises(TypeError, match=template.format(dtype="str")):
331
+ s.str.center(5, fillchar="XY")
332
+
333
+ with pytest.raises(TypeError, match=template.format(dtype="str")):
334
+ s.str.ljust(5, fillchar="XY")
335
+
336
+ with pytest.raises(TypeError, match=template.format(dtype="str")):
337
+ s.str.rjust(5, fillchar="XY")
338
+
339
+ with pytest.raises(TypeError, match=template.format(dtype="int")):
340
+ s.str.center(5, fillchar=1)
341
+
342
+ with pytest.raises(TypeError, match=template.format(dtype="int")):
343
+ s.str.ljust(5, fillchar=1)
344
+
345
+ with pytest.raises(TypeError, match=template.format(dtype="int")):
346
+ s.str.rjust(5, fillchar=1)
347
+
348
+
349
+ def test_zfill(any_string_dtype):
350
+ s = Series(["1", "22", "aaa", "333", "45678"], dtype=any_string_dtype)
351
+
352
+ result = s.str.zfill(5)
353
+ expected = Series(
354
+ ["00001", "00022", "00aaa", "00333", "45678"], dtype=any_string_dtype
355
+ )
356
+ tm.assert_series_equal(result, expected)
357
+ expected = np.array([v.zfill(5) for v in np.array(s)], dtype=np.object_)
358
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
359
+
360
+ result = s.str.zfill(3)
361
+ expected = Series(["001", "022", "aaa", "333", "45678"], dtype=any_string_dtype)
362
+ tm.assert_series_equal(result, expected)
363
+ expected = np.array([v.zfill(3) for v in np.array(s)], dtype=np.object_)
364
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.object_), expected)
365
+
366
+ s = Series(["1", np.nan, "aaa", np.nan, "45678"], dtype=any_string_dtype)
367
+ result = s.str.zfill(5)
368
+ expected = Series(
369
+ ["00001", np.nan, "00aaa", np.nan, "45678"], dtype=any_string_dtype
370
+ )
371
+ tm.assert_series_equal(result, expected)
372
+
373
+
374
+ def test_wrap(any_string_dtype):
375
+ # test values are: two words less than width, two words equal to width,
376
+ # two words greater than width, one word less than width, one word
377
+ # equal to width, one word greater than width, multiple tokens with
378
+ # trailing whitespace equal to width
379
+ s = Series(
380
+ [
381
+ "hello world",
382
+ "hello world!",
383
+ "hello world!!",
384
+ "abcdefabcde",
385
+ "abcdefabcdef",
386
+ "abcdefabcdefa",
387
+ "ab ab ab ab ",
388
+ "ab ab ab ab a",
389
+ "\t",
390
+ ],
391
+ dtype=any_string_dtype,
392
+ )
393
+
394
+ # expected values
395
+ expected = Series(
396
+ [
397
+ "hello world",
398
+ "hello world!",
399
+ "hello\nworld!!",
400
+ "abcdefabcde",
401
+ "abcdefabcdef",
402
+ "abcdefabcdef\na",
403
+ "ab ab ab ab",
404
+ "ab ab ab ab\na",
405
+ "",
406
+ ],
407
+ dtype=any_string_dtype,
408
+ )
409
+
410
+ result = s.str.wrap(12, break_long_words=True)
411
+ tm.assert_series_equal(result, expected)
412
+
413
+
414
+ def test_wrap_unicode(any_string_dtype):
415
+ # test with pre and post whitespace (non-unicode), NaN, and non-ascii Unicode
416
+ s = Series(
417
+ [" pre ", np.nan, "\xac\u20ac\U00008000 abadcafe"], dtype=any_string_dtype
418
+ )
419
+ expected = Series(
420
+ [" pre", np.nan, "\xac\u20ac\U00008000 ab\nadcafe"], dtype=any_string_dtype
421
+ )
422
+ result = s.str.wrap(6)
423
+ tm.assert_series_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_cat.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ import pandas.util._test_decorators as td
8
+
9
+ from pandas import (
10
+ DataFrame,
11
+ Index,
12
+ MultiIndex,
13
+ Series,
14
+ _testing as tm,
15
+ concat,
16
+ option_context,
17
+ )
18
+
19
+
20
+ @pytest.fixture
21
+ def index_or_series2(index_or_series):
22
+ return index_or_series
23
+
24
+
25
+ @pytest.mark.parametrize("other", [None, Series, Index])
26
+ def test_str_cat_name(index_or_series, other):
27
+ # GH 21053
28
+ box = index_or_series
29
+ values = ["a", "b"]
30
+ if other:
31
+ other = other(values)
32
+ else:
33
+ other = values
34
+ result = box(values, name="name").str.cat(other, sep=",")
35
+ assert result.name == "name"
36
+
37
+
38
+ @pytest.mark.parametrize(
39
+ "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
40
+ )
41
+ def test_str_cat(index_or_series, infer_string):
42
+ with option_context("future.infer_string", infer_string):
43
+ box = index_or_series
44
+ # test_cat above tests "str_cat" from ndarray;
45
+ # here testing "str.cat" from Series/Index to ndarray/list
46
+ s = box(["a", "a", "b", "b", "c", np.nan])
47
+
48
+ # single array
49
+ result = s.str.cat()
50
+ expected = "aabbc"
51
+ assert result == expected
52
+
53
+ result = s.str.cat(na_rep="-")
54
+ expected = "aabbc-"
55
+ assert result == expected
56
+
57
+ result = s.str.cat(sep="_", na_rep="NA")
58
+ expected = "a_a_b_b_c_NA"
59
+ assert result == expected
60
+
61
+ t = np.array(["a", np.nan, "b", "d", "foo", np.nan], dtype=object)
62
+ expected = box(["aa", "a-", "bb", "bd", "cfoo", "--"])
63
+
64
+ # Series/Index with array
65
+ result = s.str.cat(t, na_rep="-")
66
+ tm.assert_equal(result, expected)
67
+
68
+ # Series/Index with list
69
+ result = s.str.cat(list(t), na_rep="-")
70
+ tm.assert_equal(result, expected)
71
+
72
+ # errors for incorrect lengths
73
+ rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
74
+ z = Series(["1", "2", "3"])
75
+
76
+ with pytest.raises(ValueError, match=rgx):
77
+ s.str.cat(z.values)
78
+
79
+ with pytest.raises(ValueError, match=rgx):
80
+ s.str.cat(list(z))
81
+
82
+
83
+ def test_str_cat_raises_intuitive_error(index_or_series):
84
+ # GH 11334
85
+ box = index_or_series
86
+ s = box(["a", "b", "c", "d"])
87
+ message = "Did you mean to supply a `sep` keyword?"
88
+ with pytest.raises(ValueError, match=message):
89
+ s.str.cat("|")
90
+ with pytest.raises(ValueError, match=message):
91
+ s.str.cat(" ")
92
+
93
+
94
+ @pytest.mark.parametrize(
95
+ "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
96
+ )
97
+ @pytest.mark.parametrize("sep", ["", None])
98
+ @pytest.mark.parametrize("dtype_target", ["object", "category"])
99
+ @pytest.mark.parametrize("dtype_caller", ["object", "category"])
100
+ def test_str_cat_categorical(
101
+ index_or_series, dtype_caller, dtype_target, sep, infer_string
102
+ ):
103
+ box = index_or_series
104
+
105
+ with option_context("future.infer_string", infer_string):
106
+ s = Index(["a", "a", "b", "a"], dtype=dtype_caller)
107
+ s = s if box == Index else Series(s, index=s, dtype=s.dtype)
108
+ t = Index(["b", "a", "b", "c"], dtype=dtype_target)
109
+
110
+ expected = Index(
111
+ ["ab", "aa", "bb", "ac"], dtype=object if dtype_caller == "object" else None
112
+ )
113
+ expected = (
114
+ expected
115
+ if box == Index
116
+ else Series(
117
+ expected, index=Index(s, dtype=dtype_caller), dtype=expected.dtype
118
+ )
119
+ )
120
+
121
+ # Series/Index with unaligned Index -> t.values
122
+ result = s.str.cat(t.values, sep=sep)
123
+ tm.assert_equal(result, expected)
124
+
125
+ # Series/Index with Series having matching Index
126
+ t = Series(t.values, index=Index(s, dtype=dtype_caller))
127
+ result = s.str.cat(t, sep=sep)
128
+ tm.assert_equal(result, expected)
129
+
130
+ # Series/Index with Series.values
131
+ result = s.str.cat(t.values, sep=sep)
132
+ tm.assert_equal(result, expected)
133
+
134
+ # Series/Index with Series having different Index
135
+ t = Series(t.values, index=t.values)
136
+ expected = Index(
137
+ ["aa", "aa", "bb", "bb", "aa"],
138
+ dtype=object if dtype_caller == "object" else None,
139
+ )
140
+ dtype = object if dtype_caller == "object" else s.dtype.categories.dtype
141
+ expected = (
142
+ expected
143
+ if box == Index
144
+ else Series(
145
+ expected,
146
+ index=Index(expected.str[:1], dtype=dtype),
147
+ dtype=expected.dtype,
148
+ )
149
+ )
150
+
151
+ result = s.str.cat(t, sep=sep)
152
+ tm.assert_equal(result, expected)
153
+
154
+
155
+ @pytest.mark.parametrize(
156
+ "data",
157
+ [[1, 2, 3], [0.1, 0.2, 0.3], [1, 2, "b"]],
158
+ ids=["integers", "floats", "mixed"],
159
+ )
160
+ # without dtype=object, np.array would cast [1, 2, 'b'] to ['1', '2', 'b']
161
+ @pytest.mark.parametrize(
162
+ "box",
163
+ [Series, Index, list, lambda x: np.array(x, dtype=object)],
164
+ ids=["Series", "Index", "list", "np.array"],
165
+ )
166
+ def test_str_cat_wrong_dtype_raises(box, data):
167
+ # GH 22722
168
+ s = Series(["a", "b", "c"])
169
+ t = box(data)
170
+
171
+ msg = "Concatenation requires list-likes containing only strings.*"
172
+ with pytest.raises(TypeError, match=msg):
173
+ # need to use outer and na_rep, as otherwise Index would not raise
174
+ s.str.cat(t, join="outer", na_rep="-")
175
+
176
+
177
+ def test_str_cat_mixed_inputs(index_or_series):
178
+ box = index_or_series
179
+ s = Index(["a", "b", "c", "d"])
180
+ s = s if box == Index else Series(s, index=s)
181
+
182
+ t = Series(["A", "B", "C", "D"], index=s.values)
183
+ d = concat([t, Series(s, index=s)], axis=1)
184
+
185
+ expected = Index(["aAa", "bBb", "cCc", "dDd"])
186
+ expected = expected if box == Index else Series(expected.values, index=s.values)
187
+
188
+ # Series/Index with DataFrame
189
+ result = s.str.cat(d)
190
+ tm.assert_equal(result, expected)
191
+
192
+ # Series/Index with two-dimensional ndarray
193
+ result = s.str.cat(d.values)
194
+ tm.assert_equal(result, expected)
195
+
196
+ # Series/Index with list of Series
197
+ result = s.str.cat([t, s])
198
+ tm.assert_equal(result, expected)
199
+
200
+ # Series/Index with mixed list of Series/array
201
+ result = s.str.cat([t, s.values])
202
+ tm.assert_equal(result, expected)
203
+
204
+ # Series/Index with list of Series; different indexes
205
+ t.index = ["b", "c", "d", "a"]
206
+ expected = box(["aDa", "bAb", "cBc", "dCd"])
207
+ expected = expected if box == Index else Series(expected.values, index=s.values)
208
+ result = s.str.cat([t, s])
209
+ tm.assert_equal(result, expected)
210
+
211
+ # Series/Index with mixed list; different index
212
+ result = s.str.cat([t, s.values])
213
+ tm.assert_equal(result, expected)
214
+
215
+ # Series/Index with DataFrame; different indexes
216
+ d.index = ["b", "c", "d", "a"]
217
+ expected = box(["aDd", "bAa", "cBb", "dCc"])
218
+ expected = expected if box == Index else Series(expected.values, index=s.values)
219
+ result = s.str.cat(d)
220
+ tm.assert_equal(result, expected)
221
+
222
+ # errors for incorrect lengths
223
+ rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
224
+ z = Series(["1", "2", "3"])
225
+ e = concat([z, z], axis=1)
226
+
227
+ # two-dimensional ndarray
228
+ with pytest.raises(ValueError, match=rgx):
229
+ s.str.cat(e.values)
230
+
231
+ # list of list-likes
232
+ with pytest.raises(ValueError, match=rgx):
233
+ s.str.cat([z.values, s.values])
234
+
235
+ # mixed list of Series/list-like
236
+ with pytest.raises(ValueError, match=rgx):
237
+ s.str.cat([z.values, s])
238
+
239
+ # errors for incorrect arguments in list-like
240
+ rgx = "others must be Series, Index, DataFrame,.*"
241
+ # make sure None/NaN do not crash checks in _get_series_list
242
+ u = Series(["a", np.nan, "c", None])
243
+
244
+ # mix of string and Series
245
+ with pytest.raises(TypeError, match=rgx):
246
+ s.str.cat([u, "u"])
247
+
248
+ # DataFrame in list
249
+ with pytest.raises(TypeError, match=rgx):
250
+ s.str.cat([u, d])
251
+
252
+ # 2-dim ndarray in list
253
+ with pytest.raises(TypeError, match=rgx):
254
+ s.str.cat([u, d.values])
255
+
256
+ # nested lists
257
+ with pytest.raises(TypeError, match=rgx):
258
+ s.str.cat([u, [u, d]])
259
+
260
+ # forbidden input type: set
261
+ # GH 23009
262
+ with pytest.raises(TypeError, match=rgx):
263
+ s.str.cat(set(u))
264
+
265
+ # forbidden input type: set in list
266
+ # GH 23009
267
+ with pytest.raises(TypeError, match=rgx):
268
+ s.str.cat([u, set(u)])
269
+
270
+ # other forbidden input type, e.g. int
271
+ with pytest.raises(TypeError, match=rgx):
272
+ s.str.cat(1)
273
+
274
+ # nested list-likes
275
+ with pytest.raises(TypeError, match=rgx):
276
+ s.str.cat(iter([t.values, list(s)]))
277
+
278
+
279
+ def test_str_cat_align_indexed(index_or_series, join_type):
280
+ # https://github.com/pandas-dev/pandas/issues/18657
281
+ box = index_or_series
282
+
283
+ s = Series(["a", "b", "c", "d"], index=["a", "b", "c", "d"])
284
+ t = Series(["D", "A", "E", "B"], index=["d", "a", "e", "b"])
285
+ sa, ta = s.align(t, join=join_type)
286
+ # result after manual alignment of inputs
287
+ expected = sa.str.cat(ta, na_rep="-")
288
+
289
+ if box == Index:
290
+ s = Index(s)
291
+ sa = Index(sa)
292
+ expected = Index(expected)
293
+
294
+ result = s.str.cat(t, join=join_type, na_rep="-")
295
+ tm.assert_equal(result, expected)
296
+
297
+
298
+ def test_str_cat_align_mixed_inputs(join_type):
299
+ s = Series(["a", "b", "c", "d"])
300
+ t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
301
+ d = concat([t, t], axis=1)
302
+
303
+ expected_outer = Series(["aaa", "bbb", "c--", "ddd", "-ee"])
304
+ expected = expected_outer.loc[s.index.join(t.index, how=join_type)]
305
+
306
+ # list of Series
307
+ result = s.str.cat([t, t], join=join_type, na_rep="-")
308
+ tm.assert_series_equal(result, expected)
309
+
310
+ # DataFrame
311
+ result = s.str.cat(d, join=join_type, na_rep="-")
312
+ tm.assert_series_equal(result, expected)
313
+
314
+ # mixed list of indexed/unindexed
315
+ u = np.array(["A", "B", "C", "D"])
316
+ expected_outer = Series(["aaA", "bbB", "c-C", "ddD", "-e-"])
317
+ # joint index of rhs [t, u]; u will be forced have index of s
318
+ rhs_idx = (
319
+ t.index.intersection(s.index)
320
+ if join_type == "inner"
321
+ else t.index.union(s.index)
322
+ if join_type == "outer"
323
+ else t.index.append(s.index.difference(t.index))
324
+ )
325
+
326
+ expected = expected_outer.loc[s.index.join(rhs_idx, how=join_type)]
327
+ result = s.str.cat([t, u], join=join_type, na_rep="-")
328
+ tm.assert_series_equal(result, expected)
329
+
330
+ with pytest.raises(TypeError, match="others must be Series,.*"):
331
+ # nested lists are forbidden
332
+ s.str.cat([t, list(u)], join=join_type)
333
+
334
+ # errors for incorrect lengths
335
+ rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
336
+ z = Series(["1", "2", "3"]).values
337
+
338
+ # unindexed object of wrong length
339
+ with pytest.raises(ValueError, match=rgx):
340
+ s.str.cat(z, join=join_type)
341
+
342
+ # unindexed object of wrong length in list
343
+ with pytest.raises(ValueError, match=rgx):
344
+ s.str.cat([t, z], join=join_type)
345
+
346
+
347
+ def test_str_cat_datetime_index_unsorted(join_type):
348
+ # https://github.com/pandas-dev/pandas/pull/62843
349
+ values = [datetime(2024, 1, 1), datetime(2024, 1, 2)]
350
+ s = Series(["a", "b"], index=[values[1], values[0]])
351
+ others = Series(["c", "d"], index=[values[0], values[1]])
352
+ result = s.str.cat(others, join=join_type)
353
+ if join_type in {"outer", "right"}:
354
+ expected = Series(["bc", "ad"], index=[values[0], values[1]])
355
+ else:
356
+ expected = Series(["ad", "bc"], index=[values[1], values[0]])
357
+ tm.assert_series_equal(result, expected)
358
+
359
+
360
+ def test_str_cat_all_na(index_or_series, index_or_series2):
361
+ # GH 24044
362
+ box = index_or_series
363
+ other = index_or_series2
364
+
365
+ # check that all NaNs in caller / target work
366
+ s = Index(["a", "b", "c", "d"])
367
+ s = s if box == Index else Series(s, index=s)
368
+ t = other([np.nan] * 4, dtype=object)
369
+ # add index of s for alignment
370
+ t = t if other == Index else Series(t, index=s)
371
+
372
+ # all-NA target
373
+ if box == Series:
374
+ expected = Series([np.nan] * 4, index=s.index, dtype=s.dtype)
375
+ else: # box == Index
376
+ # TODO: Strimg option, this should return string dtype
377
+ expected = Index([np.nan] * 4, dtype=object)
378
+ result = s.str.cat(t, join="left")
379
+ tm.assert_equal(result, expected)
380
+
381
+ # all-NA caller (only for Series)
382
+ if other == Series:
383
+ expected = Series([np.nan] * 4, dtype=object, index=t.index)
384
+ result = t.str.cat(s, join="left")
385
+ tm.assert_series_equal(result, expected)
386
+
387
+
388
+ def test_str_cat_special_cases():
389
+ s = Series(["a", "b", "c", "d"])
390
+ t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
391
+
392
+ # iterator of elements with different types
393
+ expected = Series(["aaa", "bbb", "c-c", "ddd", "-e-"])
394
+ result = s.str.cat(iter([t, s.values]), join="outer", na_rep="-")
395
+ tm.assert_series_equal(result, expected)
396
+
397
+ # right-align with different indexes in others
398
+ expected = Series(["aa-", "d-d"], index=[0, 3])
399
+ result = s.str.cat([t.loc[[0]], t.loc[[3]]], join="right", na_rep="-")
400
+ tm.assert_series_equal(result, expected)
401
+
402
+
403
+ def test_cat_on_filtered_index():
404
+ df = DataFrame(
405
+ index=MultiIndex.from_product(
406
+ [[2011, 2012], [1, 2, 3]], names=["year", "month"]
407
+ )
408
+ )
409
+
410
+ df = df.reset_index()
411
+ df = df[df.month > 1]
412
+
413
+ str_year = df.year.astype("str")
414
+ str_month = df.month.astype("str")
415
+ str_both = str_year.str.cat(str_month, sep=" ")
416
+
417
+ assert str_both.loc[1] == "2011 2"
418
+
419
+ str_multiple = str_year.str.cat([str_month, str_month], sep=" ")
420
+
421
+ assert str_multiple.loc[1] == "2011 2 2"
422
+
423
+
424
+ @pytest.mark.parametrize("klass", [tuple, list, np.array, Series, Index])
425
+ def test_cat_different_classes(klass):
426
+ # https://github.com/pandas-dev/pandas/issues/33425
427
+ s = Series(["a", "b", "c"])
428
+ result = s.str.cat(klass(["x", "y", "z"]))
429
+ expected = Series(["ax", "by", "cz"])
430
+ tm.assert_series_equal(result, expected)
431
+
432
+
433
+ def test_cat_on_series_dot_str():
434
+ # GH 28277
435
+ ps = Series(["AbC", "de", "FGHI", "j", "kLLLm"])
436
+
437
+ message = re.escape(
438
+ "others must be Series, Index, DataFrame, np.ndarray "
439
+ "or list-like (either containing only strings or "
440
+ "containing only objects of type Series/Index/"
441
+ "np.ndarray[1-dim])"
442
+ )
443
+ with pytest.raises(TypeError, match=message):
444
+ ps.str.cat(others=ps.str)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_extract.py ADDED
@@ -0,0 +1,784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas.core.dtypes.dtypes import ArrowDtype
8
+
9
+ from pandas import (
10
+ DataFrame,
11
+ Index,
12
+ MultiIndex,
13
+ Series,
14
+ _testing as tm,
15
+ )
16
+
17
+
18
+ def test_extract_expand_kwarg_wrong_type_raises(any_string_dtype):
19
+ # TODO: should this raise TypeError
20
+ values = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
21
+ with pytest.raises(ValueError, match="expand must be True or False"):
22
+ values.str.extract(".*(BAD[_]+).*(BAD)", expand=None)
23
+
24
+
25
+ def test_extract_expand_kwarg(any_string_dtype):
26
+ s = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
27
+ expected = DataFrame(["BAD__", np.nan, np.nan], dtype=any_string_dtype)
28
+
29
+ result = s.str.extract(".*(BAD[_]+).*")
30
+ tm.assert_frame_equal(result, expected)
31
+
32
+ result = s.str.extract(".*(BAD[_]+).*", expand=True)
33
+ tm.assert_frame_equal(result, expected)
34
+
35
+ expected = DataFrame(
36
+ [["BAD__", "BAD"], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
37
+ )
38
+ result = s.str.extract(".*(BAD[_]+).*(BAD)", expand=False)
39
+ tm.assert_frame_equal(result, expected)
40
+
41
+
42
+ def test_extract_expand_False_mixed_object():
43
+ ser = Series(
44
+ ["aBAD_BAD", np.nan, "BAD_b_BAD", True, datetime.today(), "foo", None, 1, 2.0]
45
+ )
46
+
47
+ # two groups
48
+ result = ser.str.extract(".*(BAD[_]+).*(BAD)", expand=False)
49
+ er = [np.nan, np.nan] # empty row
50
+ expected = DataFrame(
51
+ [["BAD_", "BAD"], er, ["BAD_", "BAD"], er, er, er, er, er, er], dtype=object
52
+ )
53
+ tm.assert_frame_equal(result, expected)
54
+
55
+ # single group
56
+ result = ser.str.extract(".*(BAD[_]+).*BAD", expand=False)
57
+ expected = Series(
58
+ ["BAD_", np.nan, "BAD_", np.nan, np.nan, np.nan, None, np.nan, np.nan],
59
+ dtype=object,
60
+ )
61
+ tm.assert_series_equal(result, expected)
62
+
63
+
64
+ def test_extract_expand_index_raises():
65
+ # GH9980
66
+ # Index only works with one regex group since
67
+ # multi-group would expand to a frame
68
+ idx = Index(["A1", "A2", "A3", "A4", "B5"])
69
+ msg = "only one regex group is supported with Index"
70
+ with pytest.raises(ValueError, match=msg):
71
+ idx.str.extract("([AB])([123])", expand=False)
72
+
73
+
74
+ def test_extract_expand_no_capture_groups_raises(index_or_series, any_string_dtype):
75
+ s_or_idx = index_or_series(["A1", "B2", "C3"], dtype=any_string_dtype)
76
+ msg = "pattern contains no capture groups"
77
+
78
+ # no groups
79
+ with pytest.raises(ValueError, match=msg):
80
+ s_or_idx.str.extract("[ABC][123]", expand=False)
81
+
82
+ # only non-capturing groups
83
+ with pytest.raises(ValueError, match=msg):
84
+ s_or_idx.str.extract("(?:[AB]).*", expand=False)
85
+
86
+
87
+ def test_extract_expand_single_capture_group(index_or_series, any_string_dtype):
88
+ # single group renames series/index properly
89
+ s_or_idx = index_or_series(["A1", "A2"], dtype=any_string_dtype)
90
+ result = s_or_idx.str.extract(r"(?P<uno>A)\d", expand=False)
91
+
92
+ expected = index_or_series(["A", "A"], name="uno", dtype=any_string_dtype)
93
+ if index_or_series == Series:
94
+ tm.assert_series_equal(result, expected)
95
+ else:
96
+ tm.assert_index_equal(result, expected)
97
+
98
+
99
+ def test_extract_expand_capture_groups(any_string_dtype):
100
+ s = Series(["A1", "B2", "C3"], dtype=any_string_dtype)
101
+ # one group, no matches
102
+ result = s.str.extract("(_)", expand=False)
103
+ expected = Series([np.nan, np.nan, np.nan], dtype=any_string_dtype)
104
+ tm.assert_series_equal(result, expected)
105
+
106
+ # two groups, no matches
107
+ result = s.str.extract("(_)(_)", expand=False)
108
+ expected = DataFrame(
109
+ [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
110
+ )
111
+ tm.assert_frame_equal(result, expected)
112
+
113
+ # one group, some matches
114
+ result = s.str.extract("([AB])[123]", expand=False)
115
+ expected = Series(["A", "B", np.nan], dtype=any_string_dtype)
116
+ tm.assert_series_equal(result, expected)
117
+
118
+ # two groups, some matches
119
+ result = s.str.extract("([AB])([123])", expand=False)
120
+ expected = DataFrame(
121
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
122
+ )
123
+ tm.assert_frame_equal(result, expected)
124
+
125
+ # one named group
126
+ result = s.str.extract("(?P<letter>[AB])", expand=False)
127
+ expected = Series(["A", "B", np.nan], name="letter", dtype=any_string_dtype)
128
+ tm.assert_series_equal(result, expected)
129
+
130
+ # two named groups
131
+ result = s.str.extract("(?P<letter>[AB])(?P<number>[123])", expand=False)
132
+ expected = DataFrame(
133
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
134
+ columns=["letter", "number"],
135
+ dtype=any_string_dtype,
136
+ )
137
+ tm.assert_frame_equal(result, expected)
138
+
139
+ # mix named and unnamed groups
140
+ result = s.str.extract("([AB])(?P<number>[123])", expand=False)
141
+ expected = DataFrame(
142
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
143
+ columns=[0, "number"],
144
+ dtype=any_string_dtype,
145
+ )
146
+ tm.assert_frame_equal(result, expected)
147
+
148
+ # one normal group, one non-capturing group
149
+ result = s.str.extract("([AB])(?:[123])", expand=False)
150
+ expected = Series(["A", "B", np.nan], dtype=any_string_dtype)
151
+ tm.assert_series_equal(result, expected)
152
+
153
+ # two normal groups, one non-capturing group
154
+ s = Series(["A11", "B22", "C33"], dtype=any_string_dtype)
155
+ result = s.str.extract("([AB])([123])(?:[123])", expand=False)
156
+ expected = DataFrame(
157
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
158
+ )
159
+ tm.assert_frame_equal(result, expected)
160
+
161
+ # one optional group followed by one normal group
162
+ s = Series(["A1", "B2", "3"], dtype=any_string_dtype)
163
+ result = s.str.extract("(?P<letter>[AB])?(?P<number>[123])", expand=False)
164
+ expected = DataFrame(
165
+ [["A", "1"], ["B", "2"], [np.nan, "3"]],
166
+ columns=["letter", "number"],
167
+ dtype=any_string_dtype,
168
+ )
169
+ tm.assert_frame_equal(result, expected)
170
+
171
+ # one normal group followed by one optional group
172
+ s = Series(["A1", "B2", "C"], dtype=any_string_dtype)
173
+ result = s.str.extract("(?P<letter>[ABC])(?P<number>[123])?", expand=False)
174
+ expected = DataFrame(
175
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
176
+ columns=["letter", "number"],
177
+ dtype=any_string_dtype,
178
+ )
179
+ tm.assert_frame_equal(result, expected)
180
+
181
+
182
+ def test_extract_expand_capture_groups_index(index, any_string_dtype):
183
+ # https://github.com/pandas-dev/pandas/issues/6348
184
+ # not passing index to the extractor
185
+ data = ["A1", "B2", "C"]
186
+
187
+ if len(index) == 0:
188
+ pytest.skip("Test requires len(index) > 0")
189
+ while len(index) < len(data):
190
+ index = index.repeat(2)
191
+
192
+ index = index[: len(data)]
193
+ ser = Series(data, index=index, dtype=any_string_dtype)
194
+
195
+ result = ser.str.extract(r"(\d)", expand=False)
196
+ expected = Series(["1", "2", np.nan], index=index, dtype=any_string_dtype)
197
+ tm.assert_series_equal(result, expected)
198
+
199
+ result = ser.str.extract(r"(?P<letter>\D)(?P<number>\d)?", expand=False)
200
+ expected = DataFrame(
201
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
202
+ columns=["letter", "number"],
203
+ index=index,
204
+ dtype=any_string_dtype,
205
+ )
206
+ tm.assert_frame_equal(result, expected)
207
+
208
+
209
+ def test_extract_single_series_name_is_preserved(any_string_dtype):
210
+ s = Series(["a3", "b3", "c2"], name="bob", dtype=any_string_dtype)
211
+ result = s.str.extract(r"(?P<sue>[a-z])", expand=False)
212
+ expected = Series(["a", "b", "c"], name="sue", dtype=any_string_dtype)
213
+ tm.assert_series_equal(result, expected)
214
+
215
+
216
+ def test_extract_expand_True(any_string_dtype):
217
+ # Contains tests like those in test_match and some others.
218
+ s = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
219
+
220
+ result = s.str.extract(".*(BAD[_]+).*(BAD)", expand=True)
221
+ expected = DataFrame(
222
+ [["BAD__", "BAD"], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
223
+ )
224
+ tm.assert_frame_equal(result, expected)
225
+
226
+
227
+ def test_extract_expand_True_mixed_object():
228
+ er = [np.nan, np.nan] # empty row
229
+ mixed = Series(
230
+ [
231
+ "aBAD_BAD",
232
+ np.nan,
233
+ "BAD_b_BAD",
234
+ True,
235
+ datetime.today(),
236
+ "foo",
237
+ None,
238
+ 1,
239
+ 2.0,
240
+ ]
241
+ )
242
+
243
+ result = mixed.str.extract(".*(BAD[_]+).*(BAD)", expand=True)
244
+ expected = DataFrame(
245
+ [["BAD_", "BAD"], er, ["BAD_", "BAD"], er, er, er, er, er, er], dtype=object
246
+ )
247
+ tm.assert_frame_equal(result, expected)
248
+
249
+
250
+ def test_extract_expand_True_single_capture_group_raises(
251
+ index_or_series, any_string_dtype
252
+ ):
253
+ # these should work for both Series and Index
254
+ # no groups
255
+ s_or_idx = index_or_series(["A1", "B2", "C3"], dtype=any_string_dtype)
256
+ msg = "pattern contains no capture groups"
257
+ with pytest.raises(ValueError, match=msg):
258
+ s_or_idx.str.extract("[ABC][123]", expand=True)
259
+
260
+ # only non-capturing groups
261
+ with pytest.raises(ValueError, match=msg):
262
+ s_or_idx.str.extract("(?:[AB]).*", expand=True)
263
+
264
+
265
+ def test_extract_expand_True_single_capture_group(index_or_series, any_string_dtype):
266
+ # single group renames series/index properly
267
+ s_or_idx = index_or_series(["A1", "A2"], dtype=any_string_dtype)
268
+ result = s_or_idx.str.extract(r"(?P<uno>A)\d", expand=True)
269
+ expected = DataFrame({"uno": ["A", "A"]}, dtype=any_string_dtype)
270
+ tm.assert_frame_equal(result, expected)
271
+
272
+
273
+ @pytest.mark.parametrize("name", [None, "series_name"])
274
+ def test_extract_series(name, any_string_dtype):
275
+ # extract should give the same result whether or not the series has a name.
276
+ s = Series(["A1", "B2", "C3"], name=name, dtype=any_string_dtype)
277
+
278
+ # one group, no matches
279
+ result = s.str.extract("(_)", expand=True)
280
+ expected = DataFrame([np.nan, np.nan, np.nan], dtype=any_string_dtype)
281
+ tm.assert_frame_equal(result, expected)
282
+
283
+ # two groups, no matches
284
+ result = s.str.extract("(_)(_)", expand=True)
285
+ expected = DataFrame(
286
+ [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]], dtype=any_string_dtype
287
+ )
288
+ tm.assert_frame_equal(result, expected)
289
+
290
+ # one group, some matches
291
+ result = s.str.extract("([AB])[123]", expand=True)
292
+ expected = DataFrame(["A", "B", np.nan], dtype=any_string_dtype)
293
+ tm.assert_frame_equal(result, expected)
294
+
295
+ # two groups, some matches
296
+ result = s.str.extract("([AB])([123])", expand=True)
297
+ expected = DataFrame(
298
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
299
+ )
300
+ tm.assert_frame_equal(result, expected)
301
+
302
+ # one named group
303
+ result = s.str.extract("(?P<letter>[AB])", expand=True)
304
+ expected = DataFrame({"letter": ["A", "B", np.nan]}, dtype=any_string_dtype)
305
+ tm.assert_frame_equal(result, expected)
306
+
307
+ # two named groups
308
+ result = s.str.extract("(?P<letter>[AB])(?P<number>[123])", expand=True)
309
+ expected = DataFrame(
310
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
311
+ columns=["letter", "number"],
312
+ dtype=any_string_dtype,
313
+ )
314
+ tm.assert_frame_equal(result, expected)
315
+
316
+ # mix named and unnamed groups
317
+ result = s.str.extract("([AB])(?P<number>[123])", expand=True)
318
+ expected = DataFrame(
319
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]],
320
+ columns=[0, "number"],
321
+ dtype=any_string_dtype,
322
+ )
323
+ tm.assert_frame_equal(result, expected)
324
+
325
+ # one normal group, one non-capturing group
326
+ result = s.str.extract("([AB])(?:[123])", expand=True)
327
+ expected = DataFrame(["A", "B", np.nan], dtype=any_string_dtype)
328
+ tm.assert_frame_equal(result, expected)
329
+
330
+
331
+ def test_extract_optional_groups(any_string_dtype):
332
+ # two normal groups, one non-capturing group
333
+ s = Series(["A11", "B22", "C33"], dtype=any_string_dtype)
334
+ result = s.str.extract("([AB])([123])(?:[123])", expand=True)
335
+ expected = DataFrame(
336
+ [["A", "1"], ["B", "2"], [np.nan, np.nan]], dtype=any_string_dtype
337
+ )
338
+ tm.assert_frame_equal(result, expected)
339
+
340
+ # one optional group followed by one normal group
341
+ s = Series(["A1", "B2", "3"], dtype=any_string_dtype)
342
+ result = s.str.extract("(?P<letter>[AB])?(?P<number>[123])", expand=True)
343
+ expected = DataFrame(
344
+ [["A", "1"], ["B", "2"], [np.nan, "3"]],
345
+ columns=["letter", "number"],
346
+ dtype=any_string_dtype,
347
+ )
348
+ tm.assert_frame_equal(result, expected)
349
+
350
+ # one normal group followed by one optional group
351
+ s = Series(["A1", "B2", "C"], dtype=any_string_dtype)
352
+ result = s.str.extract("(?P<letter>[ABC])(?P<number>[123])?", expand=True)
353
+ expected = DataFrame(
354
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
355
+ columns=["letter", "number"],
356
+ dtype=any_string_dtype,
357
+ )
358
+ tm.assert_frame_equal(result, expected)
359
+
360
+
361
+ def test_extract_dataframe_capture_groups_index(index, any_string_dtype):
362
+ # GH6348
363
+ # not passing index to the extractor
364
+
365
+ data = ["A1", "B2", "C"]
366
+
367
+ if len(index) < len(data):
368
+ pytest.skip(f"Index needs more than {len(data)} values")
369
+
370
+ index = index[: len(data)]
371
+ s = Series(data, index=index, dtype=any_string_dtype)
372
+
373
+ result = s.str.extract(r"(\d)", expand=True)
374
+ expected = DataFrame(["1", "2", np.nan], index=index, dtype=any_string_dtype)
375
+ tm.assert_frame_equal(result, expected)
376
+
377
+ result = s.str.extract(r"(?P<letter>\D)(?P<number>\d)?", expand=True)
378
+ expected = DataFrame(
379
+ [["A", "1"], ["B", "2"], ["C", np.nan]],
380
+ columns=["letter", "number"],
381
+ index=index,
382
+ dtype=any_string_dtype,
383
+ )
384
+ tm.assert_frame_equal(result, expected)
385
+
386
+
387
+ def test_extract_single_group_returns_frame(any_string_dtype):
388
+ # GH11386 extract should always return DataFrame, even when
389
+ # there is only one group. Prior to v0.18.0, extract returned
390
+ # Series when there was only one group in the regex.
391
+ s = Series(["a3", "b3", "c2"], name="series_name", dtype=any_string_dtype)
392
+ result = s.str.extract(r"(?P<letter>[a-z])", expand=True)
393
+ expected = DataFrame({"letter": ["a", "b", "c"]}, dtype=any_string_dtype)
394
+ tm.assert_frame_equal(result, expected)
395
+
396
+
397
+ def test_extractall(any_string_dtype):
398
+ data = [
399
+ "dave@google.com",
400
+ "tdhock5@gmail.com",
401
+ "maudelaperriere@gmail.com",
402
+ "rob@gmail.com some text steve@gmail.com",
403
+ "a@b.com some text c@d.com and e@f.com",
404
+ np.nan,
405
+ "",
406
+ ]
407
+ expected_tuples = [
408
+ ("dave", "google", "com"),
409
+ ("tdhock5", "gmail", "com"),
410
+ ("maudelaperriere", "gmail", "com"),
411
+ ("rob", "gmail", "com"),
412
+ ("steve", "gmail", "com"),
413
+ ("a", "b", "com"),
414
+ ("c", "d", "com"),
415
+ ("e", "f", "com"),
416
+ ]
417
+ pat = r"""
418
+ (?P<user>[a-z0-9]+)
419
+ @
420
+ (?P<domain>[a-z]+)
421
+ \.
422
+ (?P<tld>[a-z]{2,4})
423
+ """
424
+ expected_columns = ["user", "domain", "tld"]
425
+ s = Series(data, dtype=any_string_dtype)
426
+ # extractall should return a DataFrame with one row for each match, indexed by the
427
+ # subject from which the match came.
428
+ expected_index = MultiIndex.from_tuples(
429
+ [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 0), (4, 1), (4, 2)],
430
+ names=(None, "match"),
431
+ )
432
+ expected = DataFrame(
433
+ expected_tuples, expected_index, expected_columns, dtype=any_string_dtype
434
+ )
435
+ result = s.str.extractall(pat, flags=re.VERBOSE)
436
+ tm.assert_frame_equal(result, expected)
437
+
438
+ # The index of the input Series should be used to construct the index of the output
439
+ # DataFrame:
440
+ mi = MultiIndex.from_tuples(
441
+ [
442
+ ("single", "Dave"),
443
+ ("single", "Toby"),
444
+ ("single", "Maude"),
445
+ ("multiple", "robAndSteve"),
446
+ ("multiple", "abcdef"),
447
+ ("none", "missing"),
448
+ ("none", "empty"),
449
+ ]
450
+ )
451
+ s = Series(data, index=mi, dtype=any_string_dtype)
452
+ expected_index = MultiIndex.from_tuples(
453
+ [
454
+ ("single", "Dave", 0),
455
+ ("single", "Toby", 0),
456
+ ("single", "Maude", 0),
457
+ ("multiple", "robAndSteve", 0),
458
+ ("multiple", "robAndSteve", 1),
459
+ ("multiple", "abcdef", 0),
460
+ ("multiple", "abcdef", 1),
461
+ ("multiple", "abcdef", 2),
462
+ ],
463
+ names=(None, None, "match"),
464
+ )
465
+ expected = DataFrame(
466
+ expected_tuples, expected_index, expected_columns, dtype=any_string_dtype
467
+ )
468
+ result = s.str.extractall(pat, flags=re.VERBOSE)
469
+ tm.assert_frame_equal(result, expected)
470
+
471
+ # MultiIndexed subject with names.
472
+ s = Series(data, index=mi, dtype=any_string_dtype)
473
+ s.index.names = ("matches", "description")
474
+ expected_index.names = ("matches", "description", "match")
475
+ expected = DataFrame(
476
+ expected_tuples, expected_index, expected_columns, dtype=any_string_dtype
477
+ )
478
+ result = s.str.extractall(pat, flags=re.VERBOSE)
479
+ tm.assert_frame_equal(result, expected)
480
+
481
+
482
+ @pytest.mark.parametrize(
483
+ "pat,expected_names",
484
+ [
485
+ # optional groups.
486
+ ("(?P<letter>[AB])?(?P<number>[123])", ["letter", "number"]),
487
+ # only one of two groups has a name.
488
+ ("([AB])?(?P<number>[123])", [0, "number"]),
489
+ ],
490
+ )
491
+ def test_extractall_column_names(pat, expected_names, any_string_dtype):
492
+ s = Series(["", "A1", "32"], dtype=any_string_dtype)
493
+
494
+ result = s.str.extractall(pat)
495
+ expected = DataFrame(
496
+ [("A", "1"), (np.nan, "3"), (np.nan, "2")],
497
+ index=MultiIndex.from_tuples([(1, 0), (2, 0), (2, 1)], names=(None, "match")),
498
+ columns=expected_names,
499
+ dtype=any_string_dtype,
500
+ )
501
+ tm.assert_frame_equal(result, expected)
502
+
503
+
504
+ def test_extractall_single_group(any_string_dtype):
505
+ s = Series(["a3", "b3", "d4c2"], name="series_name", dtype=any_string_dtype)
506
+ expected_index = MultiIndex.from_tuples(
507
+ [(0, 0), (1, 0), (2, 0), (2, 1)], names=(None, "match")
508
+ )
509
+
510
+ # extractall(one named group) returns DataFrame with one named column.
511
+ result = s.str.extractall(r"(?P<letter>[a-z])")
512
+ expected = DataFrame(
513
+ {"letter": ["a", "b", "d", "c"]}, index=expected_index, dtype=any_string_dtype
514
+ )
515
+ tm.assert_frame_equal(result, expected)
516
+
517
+ # extractall(one un-named group) returns DataFrame with one un-named column.
518
+ result = s.str.extractall(r"([a-z])")
519
+ expected = DataFrame(
520
+ ["a", "b", "d", "c"], index=expected_index, dtype=any_string_dtype
521
+ )
522
+ tm.assert_frame_equal(result, expected)
523
+
524
+
525
+ def test_extractall_single_group_with_quantifier(any_string_dtype):
526
+ # GH#13382
527
+ # extractall(one un-named group with quantifier) returns DataFrame with one un-named
528
+ # column.
529
+ s = Series(["ab3", "abc3", "d4cd2"], name="series_name", dtype=any_string_dtype)
530
+ result = s.str.extractall(r"([a-z]+)")
531
+ expected = DataFrame(
532
+ ["ab", "abc", "d", "cd"],
533
+ index=MultiIndex.from_tuples(
534
+ [(0, 0), (1, 0), (2, 0), (2, 1)], names=(None, "match")
535
+ ),
536
+ dtype=any_string_dtype,
537
+ )
538
+ tm.assert_frame_equal(result, expected)
539
+
540
+
541
+ @pytest.mark.parametrize(
542
+ "data, names",
543
+ [
544
+ ([], (None,)),
545
+ ([], ("i1",)),
546
+ ([], (None, "i2")),
547
+ ([], ("i1", "i2")),
548
+ (["a3", "b3", "d4c2"], (None,)),
549
+ (["a3", "b3", "d4c2"], ("i1", "i2")),
550
+ (["a3", "b3", "d4c2"], (None, "i2")),
551
+ ],
552
+ )
553
+ def test_extractall_no_matches(data, names, any_string_dtype):
554
+ # GH19075 extractall with no matches should return a valid MultiIndex
555
+ n = len(data)
556
+ if len(names) == 1:
557
+ index = Index(range(n), name=names[0])
558
+ else:
559
+ tuples = (tuple([i] * (n - 1)) for i in range(n))
560
+ index = MultiIndex.from_tuples(tuples, names=names)
561
+ s = Series(data, name="series_name", index=index, dtype=any_string_dtype)
562
+ expected_index = MultiIndex.from_tuples([], names=((*names, "match")))
563
+
564
+ # one un-named group.
565
+ result = s.str.extractall("(z)")
566
+ expected = DataFrame(columns=range(1), index=expected_index, dtype=any_string_dtype)
567
+ tm.assert_frame_equal(result, expected, check_column_type=True)
568
+
569
+ # two un-named groups.
570
+ result = s.str.extractall("(z)(z)")
571
+ expected = DataFrame(columns=range(2), index=expected_index, dtype=any_string_dtype)
572
+ tm.assert_frame_equal(result, expected, check_column_type=True)
573
+
574
+ # one named group.
575
+ result = s.str.extractall("(?P<first>z)")
576
+ expected = DataFrame(
577
+ columns=["first"], index=expected_index, dtype=any_string_dtype
578
+ )
579
+ tm.assert_frame_equal(result, expected)
580
+
581
+ # two named groups.
582
+ result = s.str.extractall("(?P<first>z)(?P<second>z)")
583
+ expected = DataFrame(
584
+ columns=["first", "second"], index=expected_index, dtype=any_string_dtype
585
+ )
586
+ tm.assert_frame_equal(result, expected)
587
+
588
+ # one named, one un-named.
589
+ result = s.str.extractall("(z)(?P<second>z)")
590
+ expected = DataFrame(
591
+ columns=[0, "second"], index=expected_index, dtype=any_string_dtype
592
+ )
593
+ tm.assert_frame_equal(result, expected)
594
+
595
+
596
+ def test_extractall_stringindex(any_string_dtype):
597
+ s = Series(["a1a2", "b1", "c1"], name="xxx", dtype=any_string_dtype)
598
+ result = s.str.extractall(r"[ab](?P<digit>\d)")
599
+ expected = DataFrame(
600
+ {"digit": ["1", "2", "1"]},
601
+ index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 0)], names=[None, "match"]),
602
+ dtype=any_string_dtype,
603
+ )
604
+ tm.assert_frame_equal(result, expected)
605
+
606
+ # index should return the same result as the default index without name thus
607
+ # index.name doesn't affect to the result
608
+ if any_string_dtype == "object":
609
+ for idx in [
610
+ Index(["a1a2", "b1", "c1"], dtype=object),
611
+ Index(["a1a2", "b1", "c1"], name="xxx", dtype=object),
612
+ ]:
613
+ result = idx.str.extractall(r"[ab](?P<digit>\d)")
614
+ tm.assert_frame_equal(result, expected)
615
+
616
+ s = Series(
617
+ ["a1a2", "b1", "c1"],
618
+ name="s_name",
619
+ index=Index(["XX", "yy", "zz"], name="idx_name"),
620
+ dtype=any_string_dtype,
621
+ )
622
+ result = s.str.extractall(r"[ab](?P<digit>\d)")
623
+ expected = DataFrame(
624
+ {"digit": ["1", "2", "1"]},
625
+ index=MultiIndex.from_tuples(
626
+ [("XX", 0), ("XX", 1), ("yy", 0)], names=["idx_name", "match"]
627
+ ),
628
+ dtype=any_string_dtype,
629
+ )
630
+ tm.assert_frame_equal(result, expected)
631
+
632
+
633
+ def test_extractall_no_capture_groups_raises(any_string_dtype):
634
+ # Does not make sense to use extractall with a regex that has no capture groups.
635
+ # (it returns DataFrame with one column for each capture group)
636
+ s = Series(["a3", "b3", "d4c2"], name="series_name", dtype=any_string_dtype)
637
+ with pytest.raises(ValueError, match="no capture groups"):
638
+ s.str.extractall(r"[a-z]")
639
+
640
+
641
+ def test_extract_index_one_two_groups():
642
+ s = Series(["a3", "b3", "d4c2"], index=["A3", "B3", "D4"], name="series_name")
643
+ r = s.index.str.extract(r"([A-Z])", expand=True)
644
+ e = DataFrame(["A", "B", "D"])
645
+ tm.assert_frame_equal(r, e)
646
+
647
+ # Prior to v0.18.0, index.str.extract(regex with one group)
648
+ # returned Index. With more than one group, extract raised an
649
+ # error (GH9980). Now extract always returns DataFrame.
650
+ r = s.index.str.extract(r"(?P<letter>[A-Z])(?P<digit>[0-9])", expand=True)
651
+ e_list = [("A", "3"), ("B", "3"), ("D", "4")]
652
+ e = DataFrame(e_list, columns=["letter", "digit"])
653
+ tm.assert_frame_equal(r, e)
654
+
655
+
656
+ def test_extractall_same_as_extract(any_string_dtype):
657
+ s = Series(["a3", "b3", "c2"], name="series_name", dtype=any_string_dtype)
658
+
659
+ pattern_two_noname = r"([a-z])([0-9])"
660
+ extract_two_noname = s.str.extract(pattern_two_noname, expand=True)
661
+ has_multi_index = s.str.extractall(pattern_two_noname)
662
+ no_multi_index = has_multi_index.xs(0, level="match")
663
+ tm.assert_frame_equal(extract_two_noname, no_multi_index)
664
+
665
+ pattern_two_named = r"(?P<letter>[a-z])(?P<digit>[0-9])"
666
+ extract_two_named = s.str.extract(pattern_two_named, expand=True)
667
+ has_multi_index = s.str.extractall(pattern_two_named)
668
+ no_multi_index = has_multi_index.xs(0, level="match")
669
+ tm.assert_frame_equal(extract_two_named, no_multi_index)
670
+
671
+ pattern_one_named = r"(?P<group_name>[a-z])"
672
+ extract_one_named = s.str.extract(pattern_one_named, expand=True)
673
+ has_multi_index = s.str.extractall(pattern_one_named)
674
+ no_multi_index = has_multi_index.xs(0, level="match")
675
+ tm.assert_frame_equal(extract_one_named, no_multi_index)
676
+
677
+ pattern_one_noname = r"([a-z])"
678
+ extract_one_noname = s.str.extract(pattern_one_noname, expand=True)
679
+ has_multi_index = s.str.extractall(pattern_one_noname)
680
+ no_multi_index = has_multi_index.xs(0, level="match")
681
+ tm.assert_frame_equal(extract_one_noname, no_multi_index)
682
+
683
+
684
+ def test_extractall_same_as_extract_subject_index(any_string_dtype):
685
+ # same as above tests, but s has a MultiIndex.
686
+ mi = MultiIndex.from_tuples(
687
+ [("A", "first"), ("B", "second"), ("C", "third")],
688
+ names=("capital", "ordinal"),
689
+ )
690
+ s = Series(["a3", "b3", "c2"], index=mi, name="series_name", dtype=any_string_dtype)
691
+
692
+ pattern_two_noname = r"([a-z])([0-9])"
693
+ extract_two_noname = s.str.extract(pattern_two_noname, expand=True)
694
+ has_match_index = s.str.extractall(pattern_two_noname)
695
+ no_match_index = has_match_index.xs(0, level="match")
696
+ tm.assert_frame_equal(extract_two_noname, no_match_index)
697
+
698
+ pattern_two_named = r"(?P<letter>[a-z])(?P<digit>[0-9])"
699
+ extract_two_named = s.str.extract(pattern_two_named, expand=True)
700
+ has_match_index = s.str.extractall(pattern_two_named)
701
+ no_match_index = has_match_index.xs(0, level="match")
702
+ tm.assert_frame_equal(extract_two_named, no_match_index)
703
+
704
+ pattern_one_named = r"(?P<group_name>[a-z])"
705
+ extract_one_named = s.str.extract(pattern_one_named, expand=True)
706
+ has_match_index = s.str.extractall(pattern_one_named)
707
+ no_match_index = has_match_index.xs(0, level="match")
708
+ tm.assert_frame_equal(extract_one_named, no_match_index)
709
+
710
+ pattern_one_noname = r"([a-z])"
711
+ extract_one_noname = s.str.extract(pattern_one_noname, expand=True)
712
+ has_match_index = s.str.extractall(pattern_one_noname)
713
+ no_match_index = has_match_index.xs(0, level="match")
714
+ tm.assert_frame_equal(extract_one_noname, no_match_index)
715
+
716
+
717
+ def test_extractall_preserves_dtype():
718
+ # Ensure that when extractall is called on a series with specific dtypes set, that
719
+ # the dtype is preserved in the resulting DataFrame's column.
720
+ pa = pytest.importorskip("pyarrow")
721
+
722
+ result = Series(["abc", "ab"], dtype=ArrowDtype(pa.string())).str.extractall("(ab)")
723
+ assert result.dtypes[0] == "string[pyarrow]"
724
+
725
+
726
+ @pytest.mark.parametrize(
727
+ "pat, expected_data",
728
+ [
729
+ (r"(a(?=b))", [None, "a", None, None]),
730
+ (r"((?<=a)b)", [None, "b", None, None]),
731
+ (r"(a(?!b))", ["a", None, "a", None]),
732
+ (r"((?<!b)a)", ["a", "a", None, None]),
733
+ ("(ab)", [None, "ab", None, None]),
734
+ ],
735
+ )
736
+ def test_extract_lookarounds(any_string_dtype, pat, expected_data):
737
+ # https://github.com/pandas-dev/pandas/issues/60833
738
+ ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype)
739
+ result = ser.str.extract(pat, expand=False)
740
+ if any_string_dtype == "object":
741
+ # object input will preserve None but any result with no matches gets NaN
742
+ expected_data = [np.nan if e is None else e for e in expected_data]
743
+ expected = Series([*expected_data, None], dtype=any_string_dtype)
744
+ tm.assert_series_equal(result, expected)
745
+
746
+
747
+ @pytest.mark.parametrize(
748
+ "pat, expected_data",
749
+ [
750
+ (r"(a(?=b))", {(1, 0): "a"}),
751
+ (r"((?<=a)b)", {(1, 0): "b"}),
752
+ (r"(a(?!b))", {(0, 0): "a", (0, 1): "a", (2, 0): "a"}),
753
+ (r"((?<!b)a)", {(0, 0): "a", (0, 1): "a", (1, 0): "a"}),
754
+ ("(ab)", {(1, 0): "ab"}),
755
+ ],
756
+ )
757
+ def test_extractall_lookarounds(any_string_dtype, pat, expected_data):
758
+ # https://github.com/pandas-dev/pandas/issues/60833
759
+ ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype)
760
+ result = ser.str.extractall(pat)
761
+ expected = Series(expected_data, dtype=any_string_dtype).to_frame()
762
+ expected.index.names = [None, "match"]
763
+ tm.assert_frame_equal(result, expected)
764
+
765
+
766
+ def test_extract_end_of_string(any_string_dtype):
767
+ # https://github.com/pandas-dev/pandas/pull/63613
768
+ ser = Series(["aa", "abc", "bb\n"], dtype=any_string_dtype)
769
+
770
+ # with dollar sign
771
+ result = ser.str.extract("([ab]+)$")
772
+ expected = Series(["aa", np.nan, "bb"], dtype=any_string_dtype).to_frame()
773
+ tm.assert_frame_equal(result, expected)
774
+
775
+ # with \Z (ensure this is translated to \z for pyarrow)
776
+ result = ser.str.extract(r"([ab]+)\Z")
777
+ expected = Series(["aa", np.nan, np.nan], dtype=any_string_dtype).to_frame()
778
+ tm.assert_frame_equal(result, expected)
779
+
780
+ # ensure finding a literal \Z still works
781
+ ser = Series([r"aa\Z", "abc", "bb\\Z\n"], dtype=any_string_dtype)
782
+ result = ser.str.extract(r"([ab]+)\\Z")
783
+ expected = Series(["aa", np.nan, "bb"], dtype=any_string_dtype).to_frame()
784
+ tm.assert_frame_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_find_replace.py ADDED
@@ -0,0 +1,1730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas._libs import lib
8
+ import pandas.util._test_decorators as td
9
+
10
+ import pandas as pd
11
+ from pandas import (
12
+ Series,
13
+ StringDtype,
14
+ _testing as tm,
15
+ )
16
+ from pandas.tests.strings import (
17
+ _convert_na_value,
18
+ is_object_or_nan_string_dtype,
19
+ )
20
+
21
+ # --------------------------------------------------------------------------------------
22
+ # str.contains
23
+ # --------------------------------------------------------------------------------------
24
+
25
+
26
+ def test_contains(any_string_dtype):
27
+ values = np.array(
28
+ ["foo", np.nan, "fooommm__foo", "mmm_", "foommm[_]+bar"], dtype=np.object_
29
+ )
30
+ values = Series(values, dtype=any_string_dtype)
31
+ pat = "mmm[_]+"
32
+
33
+ result = values.str.contains(pat)
34
+ if any_string_dtype == "str":
35
+ # NaN propagates as False
36
+ expected = Series([False, False, True, True, False], dtype=bool)
37
+ else:
38
+ expected_dtype = (
39
+ "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
40
+ )
41
+ expected = Series(
42
+ np.array([False, np.nan, True, True, False], dtype=np.object_),
43
+ dtype=expected_dtype,
44
+ )
45
+
46
+ tm.assert_series_equal(result, expected)
47
+
48
+ result = values.str.contains(pat, regex=False)
49
+ if any_string_dtype == "str":
50
+ expected = Series([False, False, False, False, True], dtype=bool)
51
+ else:
52
+ expected = Series(
53
+ np.array([False, np.nan, False, False, True], dtype=np.object_),
54
+ dtype=expected_dtype,
55
+ )
56
+ tm.assert_series_equal(result, expected)
57
+
58
+ values = Series(
59
+ np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=object),
60
+ dtype=any_string_dtype,
61
+ )
62
+ result = values.str.contains(pat)
63
+ expected_dtype = (
64
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
65
+ )
66
+ expected = Series(np.array([False, False, True, True]), dtype=expected_dtype)
67
+ tm.assert_series_equal(result, expected)
68
+
69
+ # case insensitive using regex
70
+ values = Series(
71
+ np.array(["Foo", "xYz", "fOOomMm__fOo", "MMM_"], dtype=object),
72
+ dtype=any_string_dtype,
73
+ )
74
+
75
+ result = values.str.contains("FOO|mmm", case=False)
76
+ expected = Series(np.array([True, False, True, True]), dtype=expected_dtype)
77
+ tm.assert_series_equal(result, expected)
78
+
79
+ # case insensitive without regex
80
+ result = values.str.contains("foo", regex=False, case=False)
81
+ expected = Series(np.array([True, False, True, False]), dtype=expected_dtype)
82
+ tm.assert_series_equal(result, expected)
83
+
84
+ # unicode
85
+ values = Series(
86
+ np.array(["foo", np.nan, "fooommm__foo", "mmm_"], dtype=np.object_),
87
+ dtype=any_string_dtype,
88
+ )
89
+ pat = "mmm[_]+"
90
+
91
+ result = values.str.contains(pat)
92
+ if any_string_dtype == "str":
93
+ expected = Series([False, False, True, True], dtype=bool)
94
+ else:
95
+ expected_dtype = (
96
+ "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
97
+ )
98
+ expected = Series(
99
+ np.array([False, np.nan, True, True], dtype=np.object_),
100
+ dtype=expected_dtype,
101
+ )
102
+ tm.assert_series_equal(result, expected)
103
+
104
+ result = values.str.contains(pat, na=False)
105
+ expected_dtype = (
106
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
107
+ )
108
+ expected = Series(np.array([False, False, True, True]), dtype=expected_dtype)
109
+ tm.assert_series_equal(result, expected)
110
+
111
+ values = Series(
112
+ np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=np.object_),
113
+ dtype=any_string_dtype,
114
+ )
115
+ result = values.str.contains(pat)
116
+ expected = Series(np.array([False, False, True, True]), dtype=expected_dtype)
117
+ tm.assert_series_equal(result, expected)
118
+
119
+
120
+ def test_contains_object_mixed():
121
+ mixed = Series(
122
+ np.array(
123
+ ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
124
+ dtype=object,
125
+ )
126
+ )
127
+ result = mixed.str.contains("o")
128
+ expected = Series(
129
+ np.array(
130
+ [False, np.nan, False, np.nan, np.nan, True, None, np.nan, np.nan],
131
+ dtype=np.object_,
132
+ )
133
+ )
134
+ tm.assert_series_equal(result, expected)
135
+
136
+
137
+ def test_contains_na_kwarg_for_object_category():
138
+ # gh 22158
139
+
140
+ # na for category
141
+ values = Series(["a", "b", "c", "a", np.nan], dtype="category")
142
+ result = values.str.contains("a", na=True)
143
+ expected = Series([True, False, False, True, True])
144
+ tm.assert_series_equal(result, expected)
145
+
146
+ result = values.str.contains("a", na=False)
147
+ expected = Series([True, False, False, True, False])
148
+ tm.assert_series_equal(result, expected)
149
+
150
+ # na for objects
151
+ values = Series(["a", "b", "c", "a", np.nan])
152
+ result = values.str.contains("a", na=True)
153
+ expected = Series([True, False, False, True, True])
154
+ tm.assert_series_equal(result, expected)
155
+
156
+ result = values.str.contains("a", na=False)
157
+ expected = Series([True, False, False, True, False])
158
+ tm.assert_series_equal(result, expected)
159
+
160
+
161
+ @pytest.mark.parametrize(
162
+ "na, expected",
163
+ [
164
+ (None, pd.NA),
165
+ (True, True),
166
+ (False, False),
167
+ (0, False),
168
+ (3, True),
169
+ (np.nan, pd.NA),
170
+ ],
171
+ )
172
+ @pytest.mark.parametrize("regex", [True, False])
173
+ def test_contains_na_kwarg_for_nullable_string_dtype(
174
+ nullable_string_dtype, na, expected, regex
175
+ ):
176
+ # https://github.com/pandas-dev/pandas/pull/41025#issuecomment-824062416
177
+
178
+ values = Series(["a", "b", "c", "a", np.nan], dtype=nullable_string_dtype)
179
+
180
+ if na in [0, 3] and na is not False:
181
+ msg = f"na must be None, pd.NA, np.nan, True, or False; got {na}"
182
+ with pytest.raises(ValueError, match=msg):
183
+ values.str.contains("a", na=na, regex=regex)
184
+ else:
185
+ result = values.str.contains("a", na=na, regex=regex)
186
+ expected = Series([True, False, False, True, expected], dtype="boolean")
187
+ tm.assert_series_equal(result, expected)
188
+
189
+
190
+ def test_contains_moar(any_string_dtype):
191
+ # PR #1179
192
+ s = Series(
193
+ ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"],
194
+ dtype=any_string_dtype,
195
+ )
196
+
197
+ result = s.str.contains("a")
198
+ if any_string_dtype == "str":
199
+ # NaN propagates as False
200
+ expected_dtype = bool
201
+ na_value = False
202
+ else:
203
+ expected_dtype = (
204
+ "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
205
+ )
206
+ na_value = np.nan
207
+ expected = Series(
208
+ [False, False, False, True, True, False, na_value, False, False, True],
209
+ dtype=expected_dtype,
210
+ )
211
+ tm.assert_series_equal(result, expected)
212
+
213
+ result = s.str.contains("a", case=False)
214
+ expected = Series(
215
+ [True, False, False, True, True, False, na_value, True, False, True],
216
+ dtype=expected_dtype,
217
+ )
218
+ tm.assert_series_equal(result, expected)
219
+
220
+ result = s.str.contains("Aa")
221
+ expected = Series(
222
+ [False, False, False, True, False, False, na_value, False, False, False],
223
+ dtype=expected_dtype,
224
+ )
225
+ tm.assert_series_equal(result, expected)
226
+
227
+ result = s.str.contains("ba")
228
+ expected = Series(
229
+ [False, False, False, True, False, False, na_value, False, False, False],
230
+ dtype=expected_dtype,
231
+ )
232
+ tm.assert_series_equal(result, expected)
233
+
234
+ result = s.str.contains("ba", case=False)
235
+ expected = Series(
236
+ [False, False, False, True, True, False, na_value, True, False, False],
237
+ dtype=expected_dtype,
238
+ )
239
+ tm.assert_series_equal(result, expected)
240
+
241
+
242
+ def test_contains_nan(any_string_dtype):
243
+ # PR #14171
244
+ s = Series([np.nan, np.nan, np.nan], dtype=any_string_dtype)
245
+
246
+ result = s.str.contains("foo", na=False)
247
+ expected_dtype = (
248
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
249
+ )
250
+ expected = Series([False, False, False], dtype=expected_dtype)
251
+ tm.assert_series_equal(result, expected)
252
+
253
+ result = s.str.contains("foo", na=True)
254
+ expected = Series([True, True, True], dtype=expected_dtype)
255
+ tm.assert_series_equal(result, expected)
256
+
257
+ msg = "na must be None, pd.NA, np.nan, True, or False; got foo"
258
+ with pytest.raises(ValueError, match=msg):
259
+ s.str.contains("foo", na="foo")
260
+
261
+ result = s.str.contains("foo")
262
+ if any_string_dtype == "str":
263
+ # NaN propagates as False
264
+ expected = Series([False, False, False], dtype=bool)
265
+ else:
266
+ expected_dtype = (
267
+ "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
268
+ )
269
+ expected = Series([np.nan, np.nan, np.nan], dtype=expected_dtype)
270
+ tm.assert_series_equal(result, expected)
271
+
272
+
273
+ def test_contains_compiled_regex(any_string_dtype):
274
+ # GH#61942
275
+ expected_dtype = (
276
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
277
+ )
278
+
279
+ ser = Series(["foo", "bar", "Baz"], dtype=any_string_dtype)
280
+
281
+ pat = re.compile("ba.")
282
+ result = ser.str.contains(pat)
283
+ expected = Series([False, True, False], dtype=expected_dtype)
284
+ tm.assert_series_equal(result, expected)
285
+
286
+ # TODO this currently works for pyarrow-backed dtypes but raises for python
287
+ if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow":
288
+ result = ser.str.contains(pat, case=False)
289
+ expected = Series([False, True, True], dtype=expected_dtype)
290
+ tm.assert_series_equal(result, expected)
291
+ else:
292
+ with pytest.raises(
293
+ ValueError, match="cannot process flags argument with a compiled pattern"
294
+ ):
295
+ ser.str.contains(pat, case=False)
296
+
297
+ pat = re.compile("ba.", flags=re.IGNORECASE)
298
+ result = ser.str.contains(pat)
299
+ expected = Series([False, True, True], dtype=expected_dtype)
300
+ tm.assert_series_equal(result, expected)
301
+
302
+ # TODO should this be supported?
303
+ with pytest.raises(
304
+ ValueError, match="cannot process flags argument with a compiled pattern"
305
+ ):
306
+ ser.str.contains(pat, flags=re.IGNORECASE)
307
+
308
+
309
+ def test_contains_compiled_regex_flags(any_string_dtype):
310
+ # ensure other (than ignorecase) flags are respected
311
+ expected_dtype = (
312
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
313
+ )
314
+
315
+ ser = Series(["foobar", "foo\nbar", "Baz"], dtype=any_string_dtype)
316
+
317
+ pat = re.compile("^ba")
318
+ result = ser.str.contains(pat)
319
+ expected = Series([False, False, False], dtype=expected_dtype)
320
+ tm.assert_series_equal(result, expected)
321
+
322
+ pat = re.compile("^ba", flags=re.MULTILINE)
323
+ result = ser.str.contains(pat)
324
+ expected = Series([False, True, False], dtype=expected_dtype)
325
+ tm.assert_series_equal(result, expected)
326
+
327
+ pat = re.compile("^ba", flags=re.MULTILINE | re.IGNORECASE)
328
+ result = ser.str.contains(pat)
329
+ expected = Series([False, True, True], dtype=expected_dtype)
330
+ tm.assert_series_equal(result, expected)
331
+
332
+
333
+ @pytest.mark.parametrize(
334
+ "pat, expected_data",
335
+ [
336
+ (r"a(?=b)", [False, True, False, False]),
337
+ (r"(?<=a)b", [False, True, False, False]),
338
+ (r"a(?!b)", [True, False, True, False]),
339
+ (r"(?<!b)a", [True, True, False, False]),
340
+ ("ab", [False, True, False, False]),
341
+ ],
342
+ )
343
+ @pytest.mark.parametrize("na", [lib.no_default, True, False, np.nan, None, pd.NA])
344
+ def test_contains_lookarounds(any_string_dtype, pat, expected_data, na):
345
+ # https://github.com/pandas-dev/pandas/issues/60833
346
+ if any_string_dtype == "object" and not isinstance(na, bool):
347
+ expected_dtype = "object"
348
+ else:
349
+ expected_dtype = (
350
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
351
+ )
352
+ if any_string_dtype == "object":
353
+ # The behavior here for `na=pd.NA` looks wrong.
354
+ if (na is lib.no_default or pd.isna(na)) and na is not pd.NA:
355
+ na_result = None
356
+ else:
357
+ na_result = na
358
+ elif na is lib.no_default or pd.isna(na):
359
+ if any_string_dtype == "str":
360
+ na_result = False
361
+ elif any_string_dtype == "string":
362
+ na_result = pd.NA
363
+ else:
364
+ raise ValueError(f"Unrecognized string dtype {any_string_dtype}")
365
+ else:
366
+ na_result = na
367
+ expected_data = expected_data.copy()
368
+ expected_data.append(na_result)
369
+ ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype)
370
+ result = ser.str.contains(pat, regex=True, na=na)
371
+ expected = Series(expected_data, dtype=expected_dtype)
372
+ tm.assert_series_equal(result, expected)
373
+
374
+
375
+ def test_contains_end_of_string(any_string_dtype):
376
+ # https://github.com/pandas-dev/pandas/pull/63613
377
+ expected_dtype = (
378
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
379
+ )
380
+
381
+ ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
382
+
383
+ # with dollar sign
384
+ result = ser.str.contains("bar$")
385
+ if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow":
386
+ # pyarrow (RE2) only matches $ at the very end of the line
387
+ expected = Series([False, True, False, False], dtype=expected_dtype)
388
+ else:
389
+ # python matches $ before or after an ending newline
390
+ expected = Series([False, True, False, True], dtype=expected_dtype)
391
+ tm.assert_series_equal(result, expected)
392
+
393
+ # with \Z (ensure this is translated to \z for pyarrow)
394
+ result = ser.str.contains(r"bar\Z")
395
+ expected = Series([False, True, False, False], dtype=expected_dtype)
396
+ tm.assert_series_equal(result, expected)
397
+
398
+ # ensure finding a literal \Z still works
399
+ ser = Series(
400
+ ["bar", r"bar{}".format("\\"), r"bar\Z", r"bar\\Z", "bars", "bar\n"],
401
+ dtype=any_string_dtype,
402
+ )
403
+
404
+ result = ser.str.contains(r"bar\\Z")
405
+ expected = Series([False, False, True, False, False, False], dtype=expected_dtype)
406
+ tm.assert_series_equal(result, expected)
407
+
408
+ result = ser.str.contains(r"bar\\\Z")
409
+ expected = Series([False, True, False, False, False, False], dtype=expected_dtype)
410
+ tm.assert_series_equal(result, expected)
411
+
412
+ result = ser.str.contains(r"bar\\\\Z")
413
+ expected = Series([False, False, False, True, False, False], dtype=expected_dtype)
414
+ tm.assert_series_equal(result, expected)
415
+
416
+
417
+ # --------------------------------------------------------------------------------------
418
+ # str.startswith
419
+ # --------------------------------------------------------------------------------------
420
+
421
+
422
+ def test_startswith_endswith_validate_na(any_string_dtype):
423
+ # GH#59615
424
+ ser = Series(
425
+ ["om", np.nan, "foo_nom", "nom", "bar_foo", np.nan, "foo"],
426
+ dtype=any_string_dtype,
427
+ )
428
+ msg = "na must be None, pd.NA, np.nan, True, or False; got baz"
429
+ with pytest.raises(ValueError, match=msg):
430
+ ser.str.startswith("kapow", na="baz")
431
+ with pytest.raises(ValueError, match=msg):
432
+ ser.str.endswith("bar", na="baz")
433
+
434
+
435
+ @pytest.mark.parametrize("pat", ["foo", ("foo", "baz")])
436
+ @pytest.mark.parametrize("dtype", ["object", "category"])
437
+ @pytest.mark.parametrize("null_value", [None, np.nan, pd.NA])
438
+ @pytest.mark.parametrize("na", [True, False])
439
+ def test_startswith(pat, dtype, null_value, na, using_infer_string):
440
+ # add category dtype parametrizations for GH-36241
441
+ values = Series(
442
+ ["om", null_value, "foo_nom", "nom", "bar_foo", null_value, "foo"],
443
+ dtype=dtype,
444
+ )
445
+
446
+ result = values.str.startswith(pat)
447
+ exp = Series([False, np.nan, True, False, False, np.nan, True])
448
+ if dtype == "object" and null_value is pd.NA:
449
+ # GH#18463
450
+ exp = exp.fillna(null_value)
451
+ elif dtype == "object" and null_value is None:
452
+ exp[exp.isna()] = None
453
+ elif using_infer_string and dtype == "category":
454
+ exp = exp.fillna(False).astype(bool)
455
+ tm.assert_series_equal(result, exp)
456
+
457
+ result = values.str.startswith(pat, na=na)
458
+ exp = Series([False, na, True, False, False, na, True])
459
+ tm.assert_series_equal(result, exp)
460
+
461
+ # mixed
462
+ mixed = np.array(
463
+ ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
464
+ dtype=np.object_,
465
+ )
466
+ rs = Series(mixed).str.startswith("f")
467
+ xp = Series([False, np.nan, False, np.nan, np.nan, True, None, np.nan, np.nan])
468
+ tm.assert_series_equal(rs, xp)
469
+
470
+
471
+ @pytest.mark.parametrize("na", [None, True, False])
472
+ def test_startswith_string_dtype(any_string_dtype, na):
473
+ values = Series(
474
+ ["om", None, "foo_nom", "nom", "bar_foo", None, "foo", "regex", "rege."],
475
+ dtype=any_string_dtype,
476
+ )
477
+ result = values.str.startswith("foo", na=na)
478
+
479
+ expected_dtype = (
480
+ (object if na is None else bool)
481
+ if is_object_or_nan_string_dtype(any_string_dtype)
482
+ else "boolean"
483
+ )
484
+ if any_string_dtype == "str":
485
+ # NaN propagates as False
486
+ expected_dtype = bool
487
+ if na is None:
488
+ na = False
489
+ exp = Series(
490
+ [False, na, True, False, False, na, True, False, False], dtype=expected_dtype
491
+ )
492
+ tm.assert_series_equal(result, exp)
493
+
494
+ result = values.str.startswith("rege.", na=na)
495
+ exp = Series(
496
+ [False, na, False, False, False, na, False, False, True], dtype=expected_dtype
497
+ )
498
+ tm.assert_series_equal(result, exp)
499
+
500
+
501
+ # --------------------------------------------------------------------------------------
502
+ # str.endswith
503
+ # --------------------------------------------------------------------------------------
504
+
505
+
506
+ @pytest.mark.parametrize("pat", ["foo", ("foo", "baz")])
507
+ @pytest.mark.parametrize("dtype", ["object", "category"])
508
+ @pytest.mark.parametrize("null_value", [None, np.nan, pd.NA])
509
+ @pytest.mark.parametrize("na", [True, False])
510
+ def test_endswith(pat, dtype, null_value, na, using_infer_string):
511
+ # add category dtype parametrizations for GH-36241
512
+ values = Series(
513
+ ["om", null_value, "foo_nom", "nom", "bar_foo", null_value, "foo"],
514
+ dtype=dtype,
515
+ )
516
+
517
+ result = values.str.endswith(pat)
518
+ exp = Series([False, np.nan, False, False, True, np.nan, True])
519
+ if dtype == "object" and null_value is pd.NA:
520
+ # GH#18463
521
+ exp = exp.fillna(null_value)
522
+ elif dtype == "object" and null_value is None:
523
+ exp[exp.isna()] = None
524
+ elif using_infer_string and dtype == "category":
525
+ exp = exp.fillna(False).astype(bool)
526
+ tm.assert_series_equal(result, exp)
527
+
528
+ result = values.str.endswith(pat, na=na)
529
+ exp = Series([False, na, False, False, True, na, True])
530
+ tm.assert_series_equal(result, exp)
531
+
532
+ # mixed
533
+ mixed = np.array(
534
+ ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
535
+ dtype=object,
536
+ )
537
+ rs = Series(mixed).str.endswith("f")
538
+ xp = Series([False, np.nan, False, np.nan, np.nan, False, None, np.nan, np.nan])
539
+ tm.assert_series_equal(rs, xp)
540
+
541
+
542
+ @pytest.mark.parametrize("na", [None, True, False])
543
+ def test_endswith_string_dtype(any_string_dtype, na):
544
+ values = Series(
545
+ ["om", None, "foo_nom", "nom", "bar_foo", None, "foo", "regex", "rege."],
546
+ dtype=any_string_dtype,
547
+ )
548
+ result = values.str.endswith("foo", na=na)
549
+ expected_dtype = (
550
+ (object if na is None else bool)
551
+ if is_object_or_nan_string_dtype(any_string_dtype)
552
+ else "boolean"
553
+ )
554
+ if any_string_dtype == "str":
555
+ # NaN propagates as False
556
+ expected_dtype = bool
557
+ if na is None:
558
+ na = False
559
+ exp = Series(
560
+ [False, na, False, False, True, na, True, False, False], dtype=expected_dtype
561
+ )
562
+ tm.assert_series_equal(result, exp)
563
+
564
+ result = values.str.endswith("rege.", na=na)
565
+ exp = Series(
566
+ [False, na, False, False, False, na, False, False, True], dtype=expected_dtype
567
+ )
568
+ tm.assert_series_equal(result, exp)
569
+
570
+
571
+ # --------------------------------------------------------------------------------------
572
+ # str.replace
573
+ # --------------------------------------------------------------------------------------
574
+ def test_replace_dict_invalid(any_string_dtype):
575
+ # GH 51914
576
+ series = Series(data=["A", "B_junk", "C_gunk"], name="my_messy_col")
577
+ msg = "repl cannot be used when pat is a dictionary"
578
+
579
+ with pytest.raises(ValueError, match=msg):
580
+ series.str.replace(pat={"A": "a", "B": "b"}, repl="A")
581
+
582
+
583
+ def test_replace_dict(any_string_dtype):
584
+ # GH 51914
585
+ series = Series(data=["A", "B", "C"], name="my_messy_col")
586
+ new_series = series.str.replace(pat={"A": "a", "B": "b"})
587
+ expected = Series(data=["a", "b", "C"], name="my_messy_col")
588
+ tm.assert_series_equal(new_series, expected)
589
+
590
+
591
+ def test_replace(any_string_dtype):
592
+ ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
593
+
594
+ result = ser.str.replace("BAD[_]*", "", regex=True)
595
+ expected = Series(["foobar", np.nan], dtype=any_string_dtype)
596
+ tm.assert_series_equal(result, expected)
597
+
598
+
599
+ def test_replace_max_replacements(any_string_dtype):
600
+ ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
601
+
602
+ expected = Series(["foobarBAD", np.nan], dtype=any_string_dtype)
603
+ result = ser.str.replace("BAD[_]*", "", n=1, regex=True)
604
+ tm.assert_series_equal(result, expected)
605
+
606
+ expected = Series(["foo__barBAD", np.nan], dtype=any_string_dtype)
607
+ result = ser.str.replace("BAD", "", n=1, regex=False)
608
+ tm.assert_series_equal(result, expected)
609
+
610
+
611
+ def test_replace_mixed_object():
612
+ ser = Series(
613
+ ["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0]
614
+ )
615
+ result = Series(ser).str.replace("BAD[_]*", "", regex=True)
616
+ expected = Series(
617
+ ["a", np.nan, "b", np.nan, np.nan, "foo", None, np.nan, np.nan], dtype=object
618
+ )
619
+ tm.assert_series_equal(result, expected)
620
+
621
+
622
+ def test_replace_unicode(any_string_dtype):
623
+ ser = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
624
+ expected = Series([b"abcd, \xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
625
+ result = ser.str.replace(r"(?<=\w),(?=\w)", ", ", flags=re.UNICODE, regex=True)
626
+ tm.assert_series_equal(result, expected)
627
+
628
+
629
+ @pytest.mark.parametrize("repl", [None, 3, {"a": "b"}])
630
+ @pytest.mark.parametrize("data", [["a", "b", None], ["a", "b", "c", "ad"]])
631
+ def test_replace_wrong_repl_type_raises(any_string_dtype, index_or_series, repl, data):
632
+ # https://github.com/pandas-dev/pandas/issues/13438
633
+ msg = "repl must be a string or callable"
634
+ obj = index_or_series(data, dtype=any_string_dtype)
635
+ with pytest.raises(TypeError, match=msg):
636
+ obj.str.replace("a", repl)
637
+
638
+
639
+ def test_replace_callable(any_string_dtype):
640
+ # GH 15055
641
+ ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
642
+
643
+ # test with callable
644
+ repl = lambda m: m.group(0).swapcase()
645
+ result = ser.str.replace("[a-z][A-Z]{2}", repl, n=2, regex=True)
646
+ expected = Series(["foObaD__baRbaD", np.nan], dtype=any_string_dtype)
647
+ tm.assert_series_equal(result, expected)
648
+
649
+
650
+ @pytest.mark.parametrize(
651
+ "repl", [lambda: None, lambda m, x: None, lambda m, x, y=None: None]
652
+ )
653
+ def test_replace_callable_raises(any_string_dtype, repl):
654
+ # GH 15055
655
+ values = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
656
+
657
+ # test with wrong number of arguments, raising an error
658
+ msg = (
659
+ r"((takes)|(missing)) (?(2)from \d+ to )?\d+ "
660
+ r"(?(3)required )positional arguments?"
661
+ )
662
+ with pytest.raises(TypeError, match=msg):
663
+ values.str.replace("a", repl, regex=True)
664
+
665
+
666
+ @pytest.mark.parametrize(
667
+ "repl, expected_list",
668
+ [
669
+ (
670
+ r"\g<three> \g<two> \g<one>",
671
+ ["Three Two One", "Baz Bar Foo"],
672
+ ),
673
+ (
674
+ r"\3 \2 \1",
675
+ ["Three Two One", "Baz Bar Foo"],
676
+ ),
677
+ (
678
+ r"\g<3> \g<2> \g<1>",
679
+ ["Three Two One", "Baz Bar Foo"],
680
+ ),
681
+ (
682
+ r"\g<2>0",
683
+ ["Two0", "Bar0"],
684
+ ),
685
+ (
686
+ r"\g<2>0 \1",
687
+ ["Two0 One", "Bar0 Foo"],
688
+ ),
689
+ ],
690
+ ids=[
691
+ "named_groups_full_swap",
692
+ "numbered_groups_no_g_full_swap",
693
+ "numbered_groups_full_swap",
694
+ "single_group_with_literal",
695
+ "mixed_group_reference_with_literal",
696
+ ],
697
+ )
698
+ @pytest.mark.parametrize("use_compile", [True, False])
699
+ def test_replace_named_groups_regex_swap(
700
+ any_string_dtype, use_compile, repl, expected_list
701
+ ):
702
+ # GH#57636
703
+ ser = Series(["One Two Three", "Foo Bar Baz"], dtype=any_string_dtype)
704
+ pattern = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)"
705
+ if use_compile:
706
+ pattern = re.compile(pattern)
707
+ result = ser.str.replace(pattern, repl, regex=True)
708
+ expected = Series(expected_list, dtype=any_string_dtype)
709
+ tm.assert_series_equal(result, expected)
710
+
711
+
712
+ @pytest.mark.parametrize(
713
+ "repl",
714
+ [
715
+ r"\g<20>",
716
+ r"\20",
717
+ r"\40",
718
+ r"\4",
719
+ ],
720
+ )
721
+ @pytest.mark.parametrize("use_compile", [True, False])
722
+ def test_replace_named_groups_regex_swap_expected_fail(
723
+ any_string_dtype, repl, use_compile, request
724
+ ):
725
+ # GH#57636
726
+ if (
727
+ not use_compile
728
+ and r"\g" not in repl
729
+ and isinstance(any_string_dtype, StringDtype)
730
+ and any_string_dtype.storage == "pyarrow"
731
+ ):
732
+ # calls pyarrow method directly
733
+ if repl == r"\20":
734
+ mark = pytest.mark.xfail(reason="PyArrow interprets as group + literal")
735
+ request.applymarker(mark)
736
+
737
+ pa = pytest.importorskip("pyarrow")
738
+ error_type = pa.ArrowInvalid
739
+ error_msg = r"only has \d parenthesized subexpressions"
740
+ else:
741
+ error_type = re.error
742
+ error_msg = "invalid group reference"
743
+
744
+ pattern = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)"
745
+ if use_compile:
746
+ pattern = re.compile(pattern)
747
+ ser = Series(["One Two Three", "Foo Bar Baz"], dtype=any_string_dtype)
748
+
749
+ with pytest.raises(error_type, match=error_msg):
750
+ ser.str.replace(pattern, repl, regex=True)
751
+
752
+
753
+ @pytest.mark.parametrize(
754
+ "pattern, repl",
755
+ [
756
+ (r"(\w+) (\w+) (\w+)", r"\20"),
757
+ (r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)", r"\20"),
758
+ ],
759
+ )
760
+ def test_pyarrow_ambiguous_group_references(pyarrow_string_dtype, pattern, repl):
761
+ # GH#62653
762
+ ser = Series(["One Two Three", "Foo Bar Baz"], dtype=pyarrow_string_dtype)
763
+
764
+ result = ser.str.replace(pattern, repl, regex=True)
765
+ expected = Series(["Two0", "Bar0"], dtype=pyarrow_string_dtype)
766
+ tm.assert_series_equal(result, expected)
767
+
768
+
769
+ @pytest.mark.parametrize(
770
+ "pattern, repl, expected_list",
771
+ [
772
+ (
773
+ r"\[(?P<one>\d+)\]",
774
+ r"(\1)",
775
+ ["var.one(0)", "var.two(1)", "var.three(2)"],
776
+ ),
777
+ (
778
+ r"\[(\d+)\]",
779
+ r"(\1)",
780
+ ["var.one(0)", "var.two(1)", "var.three(2)"],
781
+ ),
782
+ ],
783
+ )
784
+ @td.skip_if_no("pyarrow")
785
+ def test_pyarrow_backend_group_replacement(pattern, repl, expected_list):
786
+ ser = Series(["var.one[0]", "var.two[1]", "var.three[2]"]).convert_dtypes(
787
+ dtype_backend="pyarrow"
788
+ )
789
+ result = ser.str.replace(pattern, repl, regex=True)
790
+ expected = Series(expected_list).convert_dtypes(dtype_backend="pyarrow")
791
+ tm.assert_series_equal(result, expected)
792
+
793
+
794
+ def test_replace_callable_named_groups(any_string_dtype):
795
+ # test regex named groups
796
+ ser = Series(["Foo Bar Baz", np.nan], dtype=any_string_dtype)
797
+ pat = r"(?P<first>\w+) (?P<middle>\w+) (?P<last>\w+)"
798
+ repl = lambda m: m.group("middle").swapcase()
799
+ result = ser.str.replace(pat, repl, regex=True)
800
+ expected = Series(["bAR", np.nan], dtype=any_string_dtype)
801
+ tm.assert_series_equal(result, expected)
802
+
803
+
804
+ def test_replace_compiled_regex(any_string_dtype):
805
+ # GH 15446
806
+ ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
807
+
808
+ # test with compiled regex
809
+ pat = re.compile(r"BAD_*")
810
+ result = ser.str.replace(pat, "", regex=True)
811
+ expected = Series(["foobar", np.nan], dtype=any_string_dtype)
812
+ tm.assert_series_equal(result, expected)
813
+
814
+ result = ser.str.replace(pat, "", n=1, regex=True)
815
+ expected = Series(["foobarBAD", np.nan], dtype=any_string_dtype)
816
+ tm.assert_series_equal(result, expected)
817
+
818
+
819
+ def test_replace_compiled_regex_mixed_object():
820
+ pat = re.compile(r"BAD_*")
821
+ ser = Series(
822
+ ["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0]
823
+ )
824
+ result = Series(ser).str.replace(pat, "", regex=True)
825
+ expected = Series(
826
+ ["a", np.nan, "b", np.nan, np.nan, "foo", None, np.nan, np.nan], dtype=object
827
+ )
828
+ tm.assert_series_equal(result, expected)
829
+
830
+
831
+ def test_replace_compiled_regex_unicode(any_string_dtype):
832
+ ser = Series([b"abcd,\xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
833
+ expected = Series([b"abcd, \xc3\xa0".decode("utf-8")], dtype=any_string_dtype)
834
+ pat = re.compile(r"(?<=\w),(?=\w)", flags=re.UNICODE)
835
+ result = ser.str.replace(pat, ", ", regex=True)
836
+ tm.assert_series_equal(result, expected)
837
+
838
+
839
+ def test_replace_compiled_regex_raises(any_string_dtype):
840
+ # case and flags provided to str.replace will have no effect
841
+ # and will produce warnings
842
+ ser = Series(["fooBAD__barBAD__bad", np.nan], dtype=any_string_dtype)
843
+ pat = re.compile(r"BAD_*")
844
+
845
+ msg = "case and flags cannot be set when pat is a compiled regex"
846
+
847
+ with pytest.raises(ValueError, match=msg):
848
+ ser.str.replace(pat, "", flags=re.IGNORECASE, regex=True)
849
+
850
+ with pytest.raises(ValueError, match=msg):
851
+ ser.str.replace(pat, "", case=False, regex=True)
852
+
853
+ with pytest.raises(ValueError, match=msg):
854
+ ser.str.replace(pat, "", case=True, regex=True)
855
+
856
+
857
+ def test_replace_compiled_regex_callable(any_string_dtype):
858
+ # test with callable
859
+ ser = Series(["fooBAD__barBAD", np.nan], dtype=any_string_dtype)
860
+ repl = lambda m: m.group(0).swapcase()
861
+ pat = re.compile("[a-z][A-Z]{2}")
862
+ result = ser.str.replace(pat, repl, n=2, regex=True)
863
+ expected = Series(["foObaD__baRbaD", np.nan], dtype=any_string_dtype)
864
+ tm.assert_series_equal(result, expected)
865
+
866
+
867
+ @pytest.mark.parametrize("regex,expected_val", [(True, "bao"), (False, "foo")])
868
+ def test_replace_literal(regex, expected_val, any_string_dtype):
869
+ # GH16808 literal replace (regex=False vs regex=True)
870
+ ser = Series(["f.o", "foo", np.nan], dtype=any_string_dtype)
871
+ expected = Series(["bao", expected_val, np.nan], dtype=any_string_dtype)
872
+ result = ser.str.replace("f.", "ba", regex=regex)
873
+ tm.assert_series_equal(result, expected)
874
+
875
+
876
+ def test_replace_literal_callable_raises(any_string_dtype):
877
+ ser = Series([], dtype=any_string_dtype)
878
+ repl = lambda m: m.group(0).swapcase()
879
+
880
+ msg = "Cannot use a callable replacement when regex=False"
881
+ with pytest.raises(ValueError, match=msg):
882
+ ser.str.replace("abc", repl, regex=False)
883
+
884
+
885
+ def test_replace_literal_compiled_raises(any_string_dtype):
886
+ ser = Series([], dtype=any_string_dtype)
887
+ pat = re.compile("[a-z][A-Z]{2}")
888
+
889
+ msg = "Cannot use a compiled regex as replacement pattern with regex=False"
890
+ with pytest.raises(ValueError, match=msg):
891
+ ser.str.replace(pat, "", regex=False)
892
+
893
+
894
+ def test_replace_moar(any_string_dtype):
895
+ # PR #1179
896
+ ser = Series(
897
+ ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"],
898
+ dtype=any_string_dtype,
899
+ )
900
+
901
+ result = ser.str.replace("A", "YYY")
902
+ expected = Series(
903
+ ["YYY", "B", "C", "YYYaba", "Baca", "", np.nan, "CYYYBYYY", "dog", "cat"],
904
+ dtype=any_string_dtype,
905
+ )
906
+ tm.assert_series_equal(result, expected)
907
+
908
+ result = ser.str.replace("A", "YYY", case=False)
909
+ expected = Series(
910
+ [
911
+ "YYY",
912
+ "B",
913
+ "C",
914
+ "YYYYYYbYYY",
915
+ "BYYYcYYY",
916
+ "",
917
+ np.nan,
918
+ "CYYYBYYY",
919
+ "dog",
920
+ "cYYYt",
921
+ ],
922
+ dtype=any_string_dtype,
923
+ )
924
+ tm.assert_series_equal(result, expected)
925
+
926
+ result = ser.str.replace("^.a|dog", "XX-XX ", case=False, regex=True)
927
+ expected = Series(
928
+ [
929
+ "A",
930
+ "B",
931
+ "C",
932
+ "XX-XX ba",
933
+ "XX-XX ca",
934
+ "",
935
+ np.nan,
936
+ "XX-XX BA",
937
+ "XX-XX ",
938
+ "XX-XX t",
939
+ ],
940
+ dtype=any_string_dtype,
941
+ )
942
+ tm.assert_series_equal(result, expected)
943
+
944
+
945
+ def test_replace_not_case_sensitive_not_regex(any_string_dtype):
946
+ # https://github.com/pandas-dev/pandas/issues/41602
947
+ ser = Series(["A.", "a.", "Ab", "ab", np.nan], dtype=any_string_dtype)
948
+
949
+ result = ser.str.replace("a", "c", case=False, regex=False)
950
+ expected = Series(["c.", "c.", "cb", "cb", np.nan], dtype=any_string_dtype)
951
+ tm.assert_series_equal(result, expected)
952
+
953
+ result = ser.str.replace("a.", "c.", case=False, regex=False)
954
+ expected = Series(["c.", "c.", "Ab", "ab", np.nan], dtype=any_string_dtype)
955
+ tm.assert_series_equal(result, expected)
956
+
957
+
958
+ def test_replace_regex(any_string_dtype):
959
+ # https://github.com/pandas-dev/pandas/pull/24809
960
+ s = Series(["a", "b", "ac", np.nan, ""], dtype=any_string_dtype)
961
+ result = s.str.replace("^.$", "a", regex=True)
962
+ expected = Series(["a", "a", "ac", np.nan, ""], dtype=any_string_dtype)
963
+ tm.assert_series_equal(result, expected)
964
+
965
+
966
+ @pytest.mark.parametrize("regex", [True, False])
967
+ def test_replace_regex_single_character(regex, any_string_dtype):
968
+ # https://github.com/pandas-dev/pandas/pull/24809, enforced in 2.0
969
+ # GH 24804
970
+ s = Series(["a.b", ".", "b", np.nan, ""], dtype=any_string_dtype)
971
+
972
+ result = s.str.replace(".", "a", regex=regex)
973
+ if regex:
974
+ expected = Series(["aaa", "a", "a", np.nan, ""], dtype=any_string_dtype)
975
+ else:
976
+ expected = Series(["aab", "a", "b", np.nan, ""], dtype=any_string_dtype)
977
+ tm.assert_series_equal(result, expected)
978
+
979
+
980
+ @pytest.mark.parametrize(
981
+ "pat, expected_data",
982
+ [
983
+ (r"a(?=b)", ["aa", "xb", "ba", "bb"]),
984
+ (r"(?<=a)b", ["aa", "ax", "ba", "bb"]),
985
+ (r"a(?!b)", ["xx", "ab", "bx", "bb"]),
986
+ (r"(?<!b)a", ["xx", "xb", "ba", "bb"]),
987
+ ("ab", ["aa", "x", "ba", "bb"]),
988
+ ],
989
+ )
990
+ def test_replace_lookarounds(any_string_dtype, pat, expected_data):
991
+ # https://github.com/pandas-dev/pandas/issues/60833
992
+ ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype)
993
+ result = ser.str.replace(pat, "x", regex=True)
994
+ if any_string_dtype == "object":
995
+ null_result = None
996
+ elif any_string_dtype == "str":
997
+ null_result = np.nan
998
+ elif any_string_dtype == "string":
999
+ null_result = pd.NA
1000
+ else:
1001
+ raise ValueError(f"Unrecognized dtype: {any_string_dtype}")
1002
+ expected = Series([*expected_data, null_result], dtype=any_string_dtype)
1003
+ tm.assert_series_equal(result, expected)
1004
+
1005
+
1006
+ def test_replace_end_of_string(any_string_dtype):
1007
+ # https://github.com/pandas-dev/pandas/pull/63613
1008
+ ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
1009
+
1010
+ # with dollar sign
1011
+ result = ser.str.replace("bar$", "x", regex=True)
1012
+ if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow":
1013
+ # pyarrow (RE2) only matches $ at the very end of the line
1014
+ expected = Series(["baz", "x", "bars", "bar\n"], dtype=any_string_dtype)
1015
+ else:
1016
+ # python matches $ before or after an ending newline
1017
+ expected = Series(["baz", "x", "bars", "x\n"], dtype=any_string_dtype)
1018
+ tm.assert_series_equal(result, expected)
1019
+
1020
+ # with \Z (ensure this is translated to \z for pyarrow)
1021
+ result = ser.str.replace(r"bar\Z", "x", regex=True)
1022
+ expected = Series(["baz", "x", "bars", "bar\n"], dtype=any_string_dtype)
1023
+ tm.assert_series_equal(result, expected)
1024
+
1025
+ # ensure finding a literal \Z still works
1026
+ ser = Series([r"bar\Z", "bar", "bars", "bar\n"], dtype=any_string_dtype)
1027
+ result = ser.str.replace(r"bar\\Z", "x", regex=True)
1028
+ expected = Series(["x", "bar", "bars", "bar\n"], dtype=any_string_dtype)
1029
+ tm.assert_series_equal(result, expected)
1030
+
1031
+
1032
+ def test_replace_empty_pattern(any_string_dtype):
1033
+ # https://github.com/pandas-dev/pandas/issues/64941
1034
+ ser = Series(["abcd"], dtype=any_string_dtype)
1035
+
1036
+ result = ser.str.replace("", "")
1037
+ expected = Series(["abcd"], dtype=any_string_dtype)
1038
+ tm.assert_series_equal(result, expected)
1039
+
1040
+ result = ser.str.replace("", "X")
1041
+ expected = Series(["XaXbXcXdX"], dtype=any_string_dtype)
1042
+ tm.assert_series_equal(result, expected)
1043
+
1044
+ ser = Series([], dtype=any_string_dtype)
1045
+ result = ser.str.replace("", "X")
1046
+ expected = Series([], dtype=any_string_dtype)
1047
+ tm.assert_series_equal(result, expected)
1048
+
1049
+
1050
+ # --------------------------------------------------------------------------------------
1051
+ # str.match
1052
+ # --------------------------------------------------------------------------------------
1053
+
1054
+
1055
+ def test_match(any_string_dtype):
1056
+ if any_string_dtype == "str":
1057
+ # NaN propagates as False
1058
+ expected_dtype = bool
1059
+ na_value = False
1060
+ else:
1061
+ expected_dtype = (
1062
+ "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1063
+ )
1064
+ na_value = np.nan
1065
+
1066
+ values = Series(["fooBAD__barBAD", np.nan, "foo"], dtype=any_string_dtype)
1067
+ result = values.str.match(".*(BAD[_]+).*(BAD)")
1068
+ expected = Series([True, na_value, False], dtype=expected_dtype)
1069
+ tm.assert_series_equal(result, expected)
1070
+
1071
+ values = Series(
1072
+ ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
1073
+ )
1074
+ result = values.str.match(".*BAD[_]+.*BAD")
1075
+ expected = Series([True, True, na_value, False], dtype=expected_dtype)
1076
+ tm.assert_series_equal(result, expected)
1077
+
1078
+ result = values.str.match("BAD[_]+.*BAD")
1079
+ expected = Series([False, True, na_value, False], dtype=expected_dtype)
1080
+ tm.assert_series_equal(result, expected)
1081
+
1082
+ values = Series(
1083
+ ["fooBAD__barBAD", "^BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
1084
+ )
1085
+ result = values.str.match("^BAD[_]+.*BAD")
1086
+ expected = Series([False, False, na_value, False], dtype=expected_dtype)
1087
+ tm.assert_series_equal(result, expected)
1088
+
1089
+ result = values.str.match("\\^BAD[_]+.*BAD")
1090
+ expected = Series([False, True, na_value, False], dtype=expected_dtype)
1091
+ tm.assert_series_equal(result, expected)
1092
+
1093
+
1094
+ @pytest.mark.parametrize(
1095
+ "pat",
1096
+ [r"^foo|bar", r"^bar|foo", r"^foo|bar$", r"^(foo)|bar"],
1097
+ )
1098
+ def test_match_anchored_alternation(any_string_dtype, pat):
1099
+ # GH#66069
1100
+ ser = Series(["xbar", "bar", "foo", "xfoo"], dtype=any_string_dtype)
1101
+ result = ser.str.match(pat)
1102
+ expected_dtype = (
1103
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1104
+ )
1105
+ expected = Series([False, True, True, False], dtype=expected_dtype)
1106
+ tm.assert_series_equal(result, expected)
1107
+
1108
+
1109
+ def test_match_mixed_object():
1110
+ mixed = Series(
1111
+ [
1112
+ "aBAD_BAD",
1113
+ np.nan,
1114
+ "BAD_b_BAD",
1115
+ True,
1116
+ datetime.today(),
1117
+ "foo",
1118
+ None,
1119
+ 1,
1120
+ 2.0,
1121
+ ]
1122
+ )
1123
+ result = Series(mixed).str.match(".*(BAD[_]+).*(BAD)")
1124
+ expected = Series([True, np.nan, True, np.nan, np.nan, False, None, np.nan, np.nan])
1125
+ assert isinstance(result, Series)
1126
+ tm.assert_series_equal(result, expected)
1127
+
1128
+
1129
+ def test_match_na_kwarg(any_string_dtype):
1130
+ # GH #6609
1131
+ s = Series(["a", "b", np.nan], dtype=any_string_dtype)
1132
+
1133
+ result = s.str.match("a", na=False)
1134
+ expected_dtype = (
1135
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1136
+ )
1137
+ expected = Series([True, False, False], dtype=expected_dtype)
1138
+ tm.assert_series_equal(result, expected)
1139
+
1140
+ result = s.str.match("a")
1141
+ if any_string_dtype == "str":
1142
+ # NaN propagates as False
1143
+ expected_dtype = bool
1144
+ na_value = False
1145
+ else:
1146
+ expected_dtype = (
1147
+ "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1148
+ )
1149
+ na_value = np.nan
1150
+
1151
+ expected = Series([True, False, na_value], dtype=expected_dtype)
1152
+ tm.assert_series_equal(result, expected)
1153
+
1154
+
1155
+ def test_match_case_kwarg(any_string_dtype):
1156
+ values = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype)
1157
+ result = values.str.match("ab", case=False)
1158
+ expected_dtype = (
1159
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1160
+ )
1161
+ expected = Series([True, True, True, True], dtype=expected_dtype)
1162
+ tm.assert_series_equal(result, expected)
1163
+
1164
+
1165
+ def test_match_compiled_regex(any_string_dtype):
1166
+ # GH#61952
1167
+ expected_dtype = (
1168
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1169
+ )
1170
+
1171
+ values = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype)
1172
+
1173
+ result = values.str.match(re.compile("ab"))
1174
+ expected = Series([True, False, True, False], dtype=expected_dtype)
1175
+ tm.assert_series_equal(result, expected)
1176
+
1177
+ msg = (
1178
+ "Cannot both specify 'case' and pass a compiled "
1179
+ "regexp object with conflicting case-sensitivity"
1180
+ )
1181
+ with pytest.raises(ValueError, match=msg):
1182
+ values.str.match(re.compile("ab"), case=False)
1183
+
1184
+ result = values.str.match(re.compile("ab", flags=re.IGNORECASE))
1185
+ expected = Series([True, True, True, True], dtype=expected_dtype)
1186
+ tm.assert_series_equal(result, expected)
1187
+
1188
+ msg = (
1189
+ "Cannot both specify 'flags' and pass a compiled "
1190
+ "regexp object with conflicting flags"
1191
+ )
1192
+ with pytest.raises(ValueError, match=msg):
1193
+ values.str.match(re.compile("ab"), flags=re.IGNORECASE)
1194
+
1195
+ # But if the flags match you're OK
1196
+ values.str.match(re.compile("ab", flags=re.IGNORECASE), flags=re.IGNORECASE)
1197
+
1198
+
1199
+ @pytest.mark.parametrize(
1200
+ "pat, case, exp",
1201
+ [
1202
+ ["ab", False, [True, False]],
1203
+ ["Ab", True, [False, False]],
1204
+ ["bc", True, [False, False]],
1205
+ ["a[a-z]{1}", False, [True, False]],
1206
+ ["A[a-z]{1}", True, [False, False]],
1207
+ # https://github.com/pandas-dev/pandas/issues/61072
1208
+ ["(bc)|(ab)", True, [True, False]],
1209
+ ["((bc)|(ab))", True, [True, False]],
1210
+ ],
1211
+ )
1212
+ def test_str_match_extra_cases(any_string_dtype, pat, case, exp):
1213
+ ser = Series(["abc", "Xab"], dtype=any_string_dtype)
1214
+ result = ser.str.match(pat, case=case)
1215
+
1216
+ expected_dtype = (
1217
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1218
+ )
1219
+ expected = Series(exp, dtype=expected_dtype)
1220
+ tm.assert_series_equal(result, expected)
1221
+
1222
+
1223
+ @pytest.mark.parametrize(
1224
+ "pat, expected_data",
1225
+ [
1226
+ (r"a(?=b)", [False, True, False, False]),
1227
+ (r"(?<=a)b", [False, False, False, False]),
1228
+ (r"a(?!b)", [True, False, False, False]),
1229
+ (r"(?<!b)a", [True, True, False, False]),
1230
+ ("ab", [False, True, False, False]),
1231
+ ],
1232
+ )
1233
+ def test_match_lookarounds(any_string_dtype, pat, expected_data):
1234
+ # https://github.com/pandas-dev/pandas/issues/60833
1235
+ if any_string_dtype == "object":
1236
+ expected_dtype, null_result = "object", None
1237
+ elif any_string_dtype == "str":
1238
+ expected_dtype, null_result = "bool", False
1239
+ elif any_string_dtype == "string":
1240
+ expected_dtype, null_result = "boolean", pd.NA
1241
+ else:
1242
+ raise ValueError(f"Unrecognized dtype: {any_string_dtype}")
1243
+ ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype)
1244
+ result = ser.str.match(pat)
1245
+ expected = Series([*expected_data, null_result], dtype=expected_dtype)
1246
+ tm.assert_series_equal(result, expected)
1247
+
1248
+
1249
+ def test_match_end_of_string(any_string_dtype):
1250
+ # https://github.com/pandas-dev/pandas/pull/63613
1251
+ expected_dtype = (
1252
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1253
+ )
1254
+
1255
+ ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
1256
+
1257
+ # with dollar sign
1258
+ result = ser.str.match("bar$")
1259
+ if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow":
1260
+ # pyarrow (RE2) only matches $ at the very end of the line
1261
+ expected = Series([False, True, False, False], dtype=expected_dtype)
1262
+ else:
1263
+ # python matches $ before or after an ending newline
1264
+ expected = Series([False, True, False, True], dtype=expected_dtype)
1265
+ tm.assert_series_equal(result, expected)
1266
+
1267
+ # with \Z (ensure this is translated to \z for pyarrow)
1268
+ result = ser.str.match(r"bar\Z")
1269
+ expected = Series([False, True, False, False], dtype=expected_dtype)
1270
+ tm.assert_series_equal(result, expected)
1271
+
1272
+ # ensure finding a literal \Z still works
1273
+ ser = Series([r"bar\Z", "bar", "bars", "bar\n"], dtype=any_string_dtype)
1274
+ result = ser.str.match(r"bar\\Z")
1275
+ expected = Series([True, False, False, False], dtype=expected_dtype)
1276
+ tm.assert_series_equal(result, expected)
1277
+
1278
+
1279
+ # --------------------------------------------------------------------------------------
1280
+ # str.fullmatch
1281
+ # --------------------------------------------------------------------------------------
1282
+
1283
+
1284
+ def test_fullmatch(any_string_dtype):
1285
+ # GH 32806
1286
+ ser = Series(
1287
+ ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
1288
+ )
1289
+ result = ser.str.fullmatch(".*BAD[_]+.*BAD")
1290
+ if any_string_dtype == "str":
1291
+ # NaN propagates as False
1292
+ expected = Series([True, False, False, False], dtype=bool)
1293
+ else:
1294
+ expected_dtype = (
1295
+ "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1296
+ )
1297
+ expected = Series([True, False, np.nan, False], dtype=expected_dtype)
1298
+ tm.assert_series_equal(result, expected)
1299
+
1300
+
1301
+ def test_fullmatch_dollar_literal(any_string_dtype):
1302
+ # GH 56652
1303
+ ser = Series(["foo", "foo$foo", np.nan, "foo$"], dtype=any_string_dtype)
1304
+ result = ser.str.fullmatch("foo\\$")
1305
+ if any_string_dtype == "str":
1306
+ # NaN propagates as False
1307
+ expected = Series([False, False, False, True], dtype=bool)
1308
+ else:
1309
+ expected_dtype = (
1310
+ "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1311
+ )
1312
+ expected = Series([False, False, np.nan, True], dtype=expected_dtype)
1313
+ tm.assert_series_equal(result, expected)
1314
+
1315
+
1316
+ def test_fullmatch_na_kwarg(any_string_dtype):
1317
+ ser = Series(
1318
+ ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype=any_string_dtype
1319
+ )
1320
+ result = ser.str.fullmatch(".*BAD[_]+.*BAD", na=False)
1321
+ expected_dtype = (
1322
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1323
+ )
1324
+ expected = Series([True, False, False, False], dtype=expected_dtype)
1325
+ tm.assert_series_equal(result, expected)
1326
+
1327
+
1328
+ def test_fullmatch_case_kwarg(any_string_dtype):
1329
+ ser = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype)
1330
+ expected_dtype = (
1331
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1332
+ )
1333
+
1334
+ expected = Series([True, False, False, False], dtype=expected_dtype)
1335
+
1336
+ result = ser.str.fullmatch("ab", case=True)
1337
+ tm.assert_series_equal(result, expected)
1338
+
1339
+ expected = Series([True, True, False, False], dtype=expected_dtype)
1340
+
1341
+ result = ser.str.fullmatch("ab", case=False)
1342
+ tm.assert_series_equal(result, expected)
1343
+
1344
+ result = ser.str.fullmatch("ab", flags=re.IGNORECASE)
1345
+ tm.assert_series_equal(result, expected)
1346
+
1347
+
1348
+ def test_fullmatch_compiled_regex(any_string_dtype):
1349
+ # GH#61952
1350
+ expected_dtype = (
1351
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1352
+ )
1353
+
1354
+ values = Series(["ab", "AB", "abc", "ABC"], dtype=any_string_dtype)
1355
+
1356
+ result = values.str.fullmatch(re.compile("ab"))
1357
+ expected = Series([True, False, False, False], dtype=expected_dtype)
1358
+ tm.assert_series_equal(result, expected)
1359
+
1360
+ # TODO this currently works for pyarrow-backed dtypes but raises for python
1361
+ if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow":
1362
+ result = values.str.fullmatch(re.compile("ab"), case=False)
1363
+ expected = Series([True, True, False, False], dtype=expected_dtype)
1364
+ tm.assert_series_equal(result, expected)
1365
+ else:
1366
+ with pytest.raises(
1367
+ ValueError, match="cannot process flags argument with a compiled pattern"
1368
+ ):
1369
+ values.str.fullmatch(re.compile("ab"), case=False)
1370
+
1371
+ result = values.str.fullmatch(re.compile("ab", flags=re.IGNORECASE))
1372
+ expected = Series([True, True, False, False], dtype=expected_dtype)
1373
+ tm.assert_series_equal(result, expected)
1374
+
1375
+ with pytest.raises(
1376
+ ValueError, match="cannot process flags argument with a compiled pattern"
1377
+ ):
1378
+ values.str.fullmatch(re.compile("ab"), flags=re.IGNORECASE)
1379
+
1380
+
1381
+ @pytest.mark.parametrize(
1382
+ "pat, case, na, exp",
1383
+ # Note: keep cases in sync with
1384
+ # pandas/tests/extension/test_arrow.py::test_str_fullmatch
1385
+ [
1386
+ ["abc", False, None, [True, False, False, None]],
1387
+ ["Abc", True, None, [False, False, False, None]],
1388
+ ["bc", True, None, [False, False, False, None]],
1389
+ ["ab", False, None, [False, False, False, None]],
1390
+ ["a[a-z]{2}", False, None, [True, False, False, None]],
1391
+ ["A[a-z]{1}", True, None, [False, False, False, None]],
1392
+ # GH Issue: #56652
1393
+ ["abc$", False, None, [True, False, False, None]],
1394
+ ["abc\\$", False, None, [False, True, False, None]],
1395
+ ["Abc$", True, None, [False, False, False, None]],
1396
+ ["Abc\\$", True, None, [False, False, False, None]],
1397
+ # https://github.com/pandas-dev/pandas/issues/61072
1398
+ ["(abc)|(abx)", True, None, [True, False, False, None]],
1399
+ ["((abc)|(abx))", True, None, [True, False, False, None]],
1400
+ ],
1401
+ )
1402
+ def test_str_fullmatch_extra_cases(any_string_dtype, pat, case, na, exp):
1403
+ ser = Series(["abc", "abc$", "$abc", None], dtype=any_string_dtype)
1404
+ result = ser.str.fullmatch(pat, case=case, na=na)
1405
+
1406
+ if any_string_dtype == "str":
1407
+ # NaN propagates as False
1408
+ exp[-1] = False
1409
+ expected_dtype = bool
1410
+ else:
1411
+ expected_dtype = (
1412
+ "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1413
+ )
1414
+ expected = Series(exp, dtype=expected_dtype)
1415
+ tm.assert_series_equal(result, expected)
1416
+
1417
+
1418
+ @pytest.mark.parametrize(
1419
+ "pat",
1420
+ [(r"a(?=b)"), (r"(?<=a)b"), (r"a(?!b)"), (r"(?<!b)a"), ("ab")],
1421
+ )
1422
+ def test_fullmatch_lookarounds(any_string_dtype, pat):
1423
+ # https://github.com/pandas-dev/pandas/issues/60833
1424
+ # Note: By definition, any match with a lookaround is not a full match.
1425
+ if any_string_dtype == "object":
1426
+ expected_dtype, null_result = "object", None
1427
+ elif any_string_dtype == "str":
1428
+ expected_dtype, null_result = "bool", False
1429
+ elif any_string_dtype == "string":
1430
+ expected_dtype, null_result = "boolean", pd.NA
1431
+ else:
1432
+ raise ValueError(f"Unrecognized dtype: {any_string_dtype}")
1433
+ ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype)
1434
+ result = ser.str.fullmatch(pat)
1435
+ expected = Series(
1436
+ [False, True if pat == "ab" else False, False, False, null_result],
1437
+ dtype=expected_dtype,
1438
+ )
1439
+ tm.assert_series_equal(result, expected)
1440
+
1441
+
1442
+ def test_fullmatch_end_of_string(any_string_dtype):
1443
+ # https://github.com/pandas-dev/pandas/pull/63613
1444
+ expected_dtype = (
1445
+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
1446
+ )
1447
+
1448
+ ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
1449
+
1450
+ # with dollar sign (for fullmatch, no difference between python and pyarrow)
1451
+ result = ser.str.fullmatch("bar$")
1452
+ expected = Series([False, True, False, False], dtype=expected_dtype)
1453
+ tm.assert_series_equal(result, expected)
1454
+
1455
+ # with \Z (ensure this is translated to \z for pyarrow)
1456
+ result = ser.str.fullmatch(r"bar\Z")
1457
+ tm.assert_series_equal(result, expected)
1458
+
1459
+ # ensure finding a literal \Z still works
1460
+ ser = Series([r"bar\Z", "bar", "bars", "bar\n"], dtype=any_string_dtype)
1461
+ result = ser.str.fullmatch(r"bar\\Z")
1462
+ expected = Series([True, False, False, False], dtype=expected_dtype)
1463
+ tm.assert_series_equal(result, expected)
1464
+
1465
+
1466
+ # --------------------------------------------------------------------------------------
1467
+ # str.findall
1468
+ # --------------------------------------------------------------------------------------
1469
+
1470
+
1471
+ def test_findall(any_string_dtype):
1472
+ ser = Series(["fooBAD__barBAD", np.nan, "foo", "BAD"], dtype=any_string_dtype)
1473
+ result = ser.str.findall("BAD[_]*")
1474
+ expected = Series([["BAD__", "BAD"], np.nan, [], ["BAD"]])
1475
+ expected = _convert_na_value(ser, expected)
1476
+ tm.assert_series_equal(result, expected)
1477
+
1478
+
1479
+ def test_findall_mixed_object():
1480
+ ser = Series(
1481
+ [
1482
+ "fooBAD__barBAD",
1483
+ np.nan,
1484
+ "foo",
1485
+ True,
1486
+ datetime.today(),
1487
+ "BAD",
1488
+ None,
1489
+ 1,
1490
+ 2.0,
1491
+ ]
1492
+ )
1493
+
1494
+ result = ser.str.findall("BAD[_]*")
1495
+ expected = Series(
1496
+ [
1497
+ ["BAD__", "BAD"],
1498
+ np.nan,
1499
+ [],
1500
+ np.nan,
1501
+ np.nan,
1502
+ ["BAD"],
1503
+ None,
1504
+ np.nan,
1505
+ np.nan,
1506
+ ]
1507
+ )
1508
+
1509
+ tm.assert_series_equal(result, expected)
1510
+
1511
+
1512
+ @pytest.mark.parametrize(
1513
+ "pat, expected_data",
1514
+ [
1515
+ (r"a(?=b)", [[], ["a"], [], []]),
1516
+ (r"(?<=a)b", [[], ["b"], [], []]),
1517
+ (r"a(?!b)", [["a", "a"], [], ["a"], []]),
1518
+ (r"(?<!b)a", [["a", "a"], ["a"], [], []]),
1519
+ ("ab", [[], ["ab"], [], []]),
1520
+ ],
1521
+ )
1522
+ def test_findall_lookarounds(any_string_dtype, pat, expected_data):
1523
+ # https://github.com/pandas-dev/pandas/issues/60833
1524
+ ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype)
1525
+ result = ser.str.findall(pat)
1526
+ if any_string_dtype == "object":
1527
+ null_result = None
1528
+ elif any_string_dtype == "str":
1529
+ null_result = np.nan
1530
+ elif any_string_dtype == "string":
1531
+ null_result = pd.NA
1532
+ else:
1533
+ raise ValueError(f"Unrecognized dtype: {any_string_dtype}")
1534
+ expected = Series([*expected_data, null_result])
1535
+ tm.assert_series_equal(result, expected)
1536
+
1537
+
1538
+ def test_findall_end_of_string(any_string_dtype):
1539
+ # https://github.com/pandas-dev/pandas/pull/63613
1540
+ ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
1541
+
1542
+ # with dollar sign
1543
+ result = ser.str.findall("bar$")
1544
+ expected = Series([[], ["bar"], [], ["bar"]], dtype=object)
1545
+ tm.assert_series_equal(result, expected)
1546
+
1547
+ # with \Z (ensure this is translated to \z for pyarrow)
1548
+ result = ser.str.findall(r"bar\Z")
1549
+ expected = Series([[], ["bar"], [], []], dtype=object)
1550
+ tm.assert_series_equal(result, expected)
1551
+
1552
+ # ensure finding a literal \Z still works
1553
+ ser = Series([r"bar\Z", "bar", "bars", "bar\n"], dtype=any_string_dtype)
1554
+ result = ser.str.findall(r"bar\\Z")
1555
+ expected = Series([["bar\\Z"], [], [], []], dtype=object)
1556
+ tm.assert_series_equal(result, expected)
1557
+
1558
+
1559
+ # --------------------------------------------------------------------------------------
1560
+ # str.find
1561
+ # --------------------------------------------------------------------------------------
1562
+
1563
+
1564
+ def test_find(any_string_dtype):
1565
+ ser = Series(
1566
+ ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF", "XXXX"], dtype=any_string_dtype
1567
+ )
1568
+ expected_dtype = (
1569
+ np.int64 if is_object_or_nan_string_dtype(any_string_dtype) else "Int64"
1570
+ )
1571
+
1572
+ result = ser.str.find("EF")
1573
+ expected = Series([4, 3, 1, 0, -1], dtype=expected_dtype)
1574
+ tm.assert_series_equal(result, expected)
1575
+ expected = np.array([v.find("EF") for v in np.array(ser)], dtype=np.int64)
1576
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
1577
+
1578
+ result = ser.str.rfind("EF")
1579
+ expected = Series([4, 5, 7, 4, -1], dtype=expected_dtype)
1580
+ tm.assert_series_equal(result, expected)
1581
+ expected = np.array([v.rfind("EF") for v in np.array(ser)], dtype=np.int64)
1582
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
1583
+
1584
+ result = ser.str.find("EF", 3)
1585
+ expected = Series([4, 3, 7, 4, -1], dtype=expected_dtype)
1586
+ tm.assert_series_equal(result, expected)
1587
+ expected = np.array([v.find("EF", 3) for v in np.array(ser)], dtype=np.int64)
1588
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
1589
+
1590
+ result = ser.str.rfind("EF", 3)
1591
+ expected = Series([4, 5, 7, 4, -1], dtype=expected_dtype)
1592
+ tm.assert_series_equal(result, expected)
1593
+ expected = np.array([v.rfind("EF", 3) for v in np.array(ser)], dtype=np.int64)
1594
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
1595
+
1596
+ result = ser.str.find("EF", 3, 6)
1597
+ expected = Series([4, 3, -1, 4, -1], dtype=expected_dtype)
1598
+ tm.assert_series_equal(result, expected)
1599
+ expected = np.array([v.find("EF", 3, 6) for v in np.array(ser)], dtype=np.int64)
1600
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
1601
+
1602
+ result = ser.str.rfind("EF", 3, 6)
1603
+ expected = Series([4, 3, -1, 4, -1], dtype=expected_dtype)
1604
+ tm.assert_series_equal(result, expected)
1605
+ expected = np.array([v.rfind("EF", 3, 6) for v in np.array(ser)], dtype=np.int64)
1606
+ tm.assert_numpy_array_equal(np.array(result, dtype=np.int64), expected)
1607
+
1608
+
1609
+ def test_find_bad_arg_raises(any_string_dtype):
1610
+ ser = Series([], dtype=any_string_dtype)
1611
+ with pytest.raises(TypeError, match="expected a string object, not int"):
1612
+ ser.str.find(0)
1613
+
1614
+ with pytest.raises(TypeError, match="expected a string object, not int"):
1615
+ ser.str.rfind(0)
1616
+
1617
+
1618
+ def test_find_nan(any_string_dtype):
1619
+ ser = Series(
1620
+ ["ABCDEFG", np.nan, "DEFGHIJEF", np.nan, "XXXX"], dtype=any_string_dtype
1621
+ )
1622
+ if is_object_or_nan_string_dtype(any_string_dtype):
1623
+ expected_dtype = np.float64
1624
+ item = np.nan
1625
+ else:
1626
+ expected_dtype = "Int64"
1627
+ item = pd.NA
1628
+
1629
+ result = ser.str.find("EF")
1630
+ expected = Series([4, item, 1, item, -1], dtype=expected_dtype)
1631
+ tm.assert_series_equal(result, expected)
1632
+
1633
+ result = ser.str.rfind("EF")
1634
+ expected = Series([4, item, 7, item, -1], dtype=expected_dtype)
1635
+ tm.assert_series_equal(result, expected)
1636
+
1637
+ result = ser.str.find("EF", 3)
1638
+ expected = Series([4, item, 7, item, -1], dtype=expected_dtype)
1639
+ tm.assert_series_equal(result, expected)
1640
+
1641
+ result = ser.str.rfind("EF", 3)
1642
+ expected = Series([4, item, 7, item, -1], dtype=expected_dtype)
1643
+ tm.assert_series_equal(result, expected)
1644
+
1645
+ result = ser.str.find("EF", 3, 6)
1646
+ expected = Series([4, item, -1, item, -1], dtype=expected_dtype)
1647
+ tm.assert_series_equal(result, expected)
1648
+
1649
+ result = ser.str.rfind("EF", 3, 6)
1650
+ expected = Series([4, item, -1, item, -1], dtype=expected_dtype)
1651
+ tm.assert_series_equal(result, expected)
1652
+
1653
+
1654
+ def test_find_multibyte_chars(any_string_dtype):
1655
+ # GH#64123 - str.find should return character offsets, not byte offsets
1656
+ ser = Series(["ga", "Áa", "永a", "🐍a"], dtype=any_string_dtype)
1657
+ expected_dtype = (
1658
+ np.int64 if is_object_or_nan_string_dtype(any_string_dtype) else "Int64"
1659
+ )
1660
+
1661
+ result = ser.str.find("a")
1662
+ expected = Series([1, 1, 1, 1], dtype=expected_dtype)
1663
+ tm.assert_series_equal(result, expected)
1664
+
1665
+ result = ser.str.find("a", start=1)
1666
+ tm.assert_series_equal(result, expected)
1667
+
1668
+
1669
+ # --------------------------------------------------------------------------------------
1670
+ # str.translate
1671
+ # --------------------------------------------------------------------------------------
1672
+
1673
+
1674
+ @pytest.mark.parametrize(
1675
+ "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
1676
+ )
1677
+ def test_translate(index_or_series, any_string_dtype, infer_string):
1678
+ obj = index_or_series(
1679
+ ["abcdefg", "abcc", "cdddfg", "cdefggg"], dtype=any_string_dtype
1680
+ )
1681
+ table = str.maketrans("abc", "cde")
1682
+ result = obj.str.translate(table)
1683
+ expected = index_or_series(
1684
+ ["cdedefg", "cdee", "edddfg", "edefggg"], dtype=any_string_dtype
1685
+ )
1686
+ tm.assert_equal(result, expected)
1687
+
1688
+
1689
+ def test_translate_mixed_object():
1690
+ # Series with non-string values
1691
+ s = Series(["a", "b", "c", 1.2])
1692
+ table = str.maketrans("abc", "cde")
1693
+ expected = Series(["c", "d", "e", np.nan], dtype=object)
1694
+ result = s.str.translate(table)
1695
+ tm.assert_series_equal(result, expected)
1696
+
1697
+
1698
+ # --------------------------------------------------------------------------------------
1699
+
1700
+
1701
+ def test_flags_kwarg(any_string_dtype):
1702
+ data = {
1703
+ "Dave": "dave@google.com",
1704
+ "Steve": "steve@gmail.com",
1705
+ "Rob": "rob@gmail.com",
1706
+ "Wes": np.nan,
1707
+ }
1708
+ data = Series(data, dtype=any_string_dtype)
1709
+
1710
+ pat = r"([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})"
1711
+
1712
+ result = data.str.extract(pat, flags=re.IGNORECASE, expand=True)
1713
+ assert result.iloc[0].tolist() == ["dave", "google", "com"]
1714
+
1715
+ result = data.str.match(pat, flags=re.IGNORECASE)
1716
+ assert result.iloc[0]
1717
+
1718
+ result = data.str.fullmatch(pat, flags=re.IGNORECASE)
1719
+ assert result.iloc[0]
1720
+
1721
+ result = data.str.findall(pat, flags=re.IGNORECASE)
1722
+ assert result.iloc[0][0] == ("dave", "google", "com")
1723
+
1724
+ result = data.str.count(pat, flags=re.IGNORECASE)
1725
+ assert result.iloc[0] == 1
1726
+
1727
+ msg = "has match groups"
1728
+ with tm.assert_produces_warning(UserWarning, match=msg):
1729
+ result = data.str.contains(pat, flags=re.IGNORECASE)
1730
+ assert result.iloc[0]
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_get_dummies.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas.util._test_decorators as td
5
+
6
+ from pandas import (
7
+ DataFrame,
8
+ Index,
9
+ MultiIndex,
10
+ Series,
11
+ _testing as tm,
12
+ )
13
+
14
+
15
+ def test_get_dummies(any_string_dtype):
16
+ s = Series(["a|b", "a|c", np.nan], dtype=any_string_dtype)
17
+ result = s.str.get_dummies("|")
18
+ expected = DataFrame([[1, 1, 0], [1, 0, 1], [0, 0, 0]], columns=list("abc"))
19
+ tm.assert_frame_equal(result, expected)
20
+
21
+ s = Series(["a;b", "a", 7], dtype=any_string_dtype)
22
+ result = s.str.get_dummies(";")
23
+ expected = DataFrame([[0, 1, 1], [0, 1, 0], [1, 0, 0]], columns=list("7ab"))
24
+ tm.assert_frame_equal(result, expected)
25
+
26
+
27
+ def test_get_dummies_index():
28
+ # GH9980, GH8028
29
+ idx = Index(["a|b", "a|c", "b|c"])
30
+ result = idx.str.get_dummies("|")
31
+
32
+ expected = MultiIndex.from_tuples(
33
+ [(1, 1, 0), (1, 0, 1), (0, 1, 1)], names=("a", "b", "c")
34
+ )
35
+ tm.assert_index_equal(result, expected)
36
+
37
+
38
+ # GH#47872
39
+ @pytest.mark.parametrize(
40
+ "dtype",
41
+ [
42
+ np.uint8,
43
+ np.int16,
44
+ np.uint16,
45
+ np.int32,
46
+ np.uint32,
47
+ np.int64,
48
+ np.uint64,
49
+ bool,
50
+ "Int8",
51
+ "Int16",
52
+ "Int32",
53
+ "Int64",
54
+ "boolean",
55
+ ],
56
+ )
57
+ def test_get_dummies_with_dtype(any_string_dtype, dtype):
58
+ s = Series(["a|b", "a|c", np.nan], dtype=any_string_dtype)
59
+ result = s.str.get_dummies("|", dtype=dtype)
60
+ expected = DataFrame(
61
+ [[1, 1, 0], [1, 0, 1], [0, 0, 0]], columns=list("abc"), dtype=dtype
62
+ )
63
+ tm.assert_frame_equal(result, expected)
64
+
65
+
66
+ # GH#47872
67
+ @td.skip_if_no("pyarrow")
68
+ @pytest.mark.parametrize(
69
+ "dtype",
70
+ [
71
+ "int8[pyarrow]",
72
+ "uint8[pyarrow]",
73
+ "int16[pyarrow]",
74
+ "uint16[pyarrow]",
75
+ "int32[pyarrow]",
76
+ "uint32[pyarrow]",
77
+ "int64[pyarrow]",
78
+ "uint64[pyarrow]",
79
+ "bool[pyarrow]",
80
+ ],
81
+ )
82
+ def test_get_dummies_with_pyarrow_dtype(any_string_dtype, dtype):
83
+ s = Series(["a|b", "a|c", np.nan], dtype=any_string_dtype)
84
+ result = s.str.get_dummies("|", dtype=dtype)
85
+ expected = DataFrame(
86
+ [[1, 1, 0], [1, 0, 1], [0, 0, 0]],
87
+ columns=list("abc"),
88
+ dtype=dtype,
89
+ )
90
+ tm.assert_frame_equal(result, expected)
91
+
92
+
93
+ # GH#47872
94
+ def test_get_dummies_with_str_dtype(any_string_dtype):
95
+ s = Series(["a|b", "a|c", np.nan], dtype=any_string_dtype)
96
+
97
+ msg = "Only numeric or boolean dtypes are supported for 'dtype'"
98
+ with pytest.raises(ValueError, match=msg):
99
+ s.str.get_dummies("|", dtype=str)
100
+
101
+ with pytest.raises(ValueError, match=msg):
102
+ s.str.get_dummies("|", dtype="datetime64[ns]")
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_split_partition.py ADDED
@@ -0,0 +1,772 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ import pandas as pd
8
+ from pandas import (
9
+ DataFrame,
10
+ Index,
11
+ MultiIndex,
12
+ Series,
13
+ _testing as tm,
14
+ )
15
+ from pandas.tests.strings import (
16
+ _convert_na_value,
17
+ is_object_or_nan_string_dtype,
18
+ )
19
+
20
+
21
+ @pytest.mark.parametrize("method", ["split", "rsplit"])
22
+ def test_split(any_string_dtype, method):
23
+ values = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
24
+
25
+ result = getattr(values.str, method)("_")
26
+ exp = Series([["a", "b", "c"], ["c", "d", "e"], np.nan, ["f", "g", "h"]])
27
+ exp = _convert_na_value(values, exp)
28
+ tm.assert_series_equal(result, exp)
29
+
30
+
31
+ @pytest.mark.parametrize("method", ["split", "rsplit"])
32
+ def test_split_more_than_one_char(any_string_dtype, method):
33
+ # more than one char
34
+ values = Series(["a__b__c", "c__d__e", np.nan, "f__g__h"], dtype=any_string_dtype)
35
+ result = getattr(values.str, method)("__")
36
+ exp = Series([["a", "b", "c"], ["c", "d", "e"], np.nan, ["f", "g", "h"]])
37
+ exp = _convert_na_value(values, exp)
38
+ tm.assert_series_equal(result, exp)
39
+
40
+ result = getattr(values.str, method)("__", expand=False)
41
+ tm.assert_series_equal(result, exp)
42
+
43
+
44
+ def test_split_more_regex_split(any_string_dtype):
45
+ # regex split
46
+ values = Series(["a,b_c", "c_d,e", np.nan, "f,g,h"], dtype=any_string_dtype)
47
+ result = values.str.split("[,_]")
48
+ exp = Series([["a", "b", "c"], ["c", "d", "e"], np.nan, ["f", "g", "h"]])
49
+ exp = _convert_na_value(values, exp)
50
+ tm.assert_series_equal(result, exp)
51
+
52
+
53
+ def test_split_regex(any_string_dtype):
54
+ # GH 43563
55
+ # explicit regex = True split
56
+ values = Series("xxxjpgzzz.jpg", dtype=any_string_dtype)
57
+ result = values.str.split(r"\.jpg", regex=True)
58
+ exp = Series([["xxxjpgzzz", ""]])
59
+ tm.assert_series_equal(result, exp)
60
+
61
+
62
+ def test_split_regex_explicit(any_string_dtype):
63
+ # explicit regex = True split with compiled regex
64
+ regex_pat = re.compile(r".jpg")
65
+ values = Series("xxxjpgzzz.jpg", dtype=any_string_dtype)
66
+ result = values.str.split(regex_pat)
67
+ exp = Series([["xx", "zzz", ""]])
68
+ tm.assert_series_equal(result, exp)
69
+
70
+ # explicit regex = False split
71
+ result = values.str.split(r"\.jpg", regex=False)
72
+ exp = Series([["xxxjpgzzz.jpg"]])
73
+ tm.assert_series_equal(result, exp)
74
+
75
+ # non explicit regex split, pattern length == 1
76
+ result = values.str.split(r".")
77
+ exp = Series([["xxxjpgzzz", "jpg"]])
78
+ tm.assert_series_equal(result, exp)
79
+
80
+ # non explicit regex split, pattern length != 1
81
+ result = values.str.split(r".jpg")
82
+ exp = Series([["xx", "zzz", ""]])
83
+ tm.assert_series_equal(result, exp)
84
+
85
+ # regex=False with pattern compiled regex raises error
86
+ with pytest.raises(
87
+ ValueError,
88
+ match="Cannot use a compiled regex as replacement pattern with regex=False",
89
+ ):
90
+ values.str.split(regex_pat, regex=False)
91
+
92
+
93
+ @pytest.mark.parametrize("expand", [None, False])
94
+ @pytest.mark.parametrize("method", ["split", "rsplit"])
95
+ def test_split_object_mixed(expand, method):
96
+ mixed = Series(["a_b_c", np.nan, "d_e_f", True, datetime.today(), None, 1, 2.0])
97
+ result = getattr(mixed.str, method)("_", expand=expand)
98
+ exp = Series(
99
+ [
100
+ ["a", "b", "c"],
101
+ np.nan,
102
+ ["d", "e", "f"],
103
+ np.nan,
104
+ np.nan,
105
+ None,
106
+ np.nan,
107
+ np.nan,
108
+ ]
109
+ )
110
+ assert isinstance(result, Series)
111
+ tm.assert_almost_equal(result, exp)
112
+
113
+
114
+ @pytest.mark.parametrize("method", ["split", "rsplit"])
115
+ @pytest.mark.parametrize("n", [None, 0])
116
+ def test_split_n(any_string_dtype, method, n):
117
+ s = Series(["a b", pd.NA, "b c"], dtype=any_string_dtype)
118
+ expected = Series([["a", "b"], pd.NA, ["b", "c"]])
119
+ result = getattr(s.str, method)(" ", n=n)
120
+ expected = _convert_na_value(s, expected)
121
+ tm.assert_series_equal(result, expected)
122
+
123
+
124
+ def test_rsplit(any_string_dtype):
125
+ # regex split is not supported by rsplit
126
+ values = Series(["a,b_c", "c_d,e", np.nan, "f,g,h"], dtype=any_string_dtype)
127
+ result = values.str.rsplit("[,_]")
128
+ exp = Series([["a,b_c"], ["c_d,e"], np.nan, ["f,g,h"]])
129
+ exp = _convert_na_value(values, exp)
130
+ tm.assert_series_equal(result, exp)
131
+
132
+
133
+ def test_rsplit_max_number(any_string_dtype):
134
+ # setting max number of splits, make sure it's from reverse
135
+ values = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
136
+ result = values.str.rsplit("_", n=1)
137
+ exp = Series([["a_b", "c"], ["c_d", "e"], np.nan, ["f_g", "h"]])
138
+ exp = _convert_na_value(values, exp)
139
+ tm.assert_series_equal(result, exp)
140
+
141
+
142
+ def test_split_blank_string(any_string_dtype):
143
+ # expand blank split GH 20067
144
+ values = Series([""], name="test", dtype=any_string_dtype)
145
+ result = values.str.split(expand=True)
146
+ exp = DataFrame([[]], dtype=any_string_dtype) # NOTE: this is NOT an empty df
147
+ tm.assert_frame_equal(result, exp)
148
+
149
+
150
+ def test_split_blank_string_with_non_empty(any_string_dtype):
151
+ values = Series(["a b c", "a b", "", " "], name="test", dtype=any_string_dtype)
152
+ result = values.str.split(expand=True)
153
+ exp = DataFrame(
154
+ [
155
+ ["a", "b", "c"],
156
+ ["a", "b", None],
157
+ [None, None, None],
158
+ [None, None, None],
159
+ ],
160
+ dtype=any_string_dtype,
161
+ )
162
+ tm.assert_frame_equal(result, exp)
163
+
164
+
165
+ @pytest.mark.parametrize("method", ["split", "rsplit"])
166
+ def test_split_noargs(any_string_dtype, method):
167
+ # #1859
168
+ s = Series(["Wes McKinney", "Travis Oliphant"], dtype=any_string_dtype)
169
+ result = getattr(s.str, method)()
170
+ expected = ["Travis", "Oliphant"]
171
+ assert result[1] == expected
172
+
173
+
174
+ @pytest.mark.parametrize(
175
+ "data, pat",
176
+ [
177
+ (["bd asdf jfg", "kjasdflqw asdfnfk"], None),
178
+ (["bd asdf jfg", "kjasdflqw asdfnfk"], "asdf"),
179
+ (["bd_asdf_jfg", "kjasdflqw_asdfnfk"], "_"),
180
+ ],
181
+ )
182
+ @pytest.mark.parametrize("n", [-1, 0])
183
+ def test_split_maxsplit(data, pat, any_string_dtype, n):
184
+ # re.split 0, str.split -1
185
+ s = Series(data, dtype=any_string_dtype)
186
+
187
+ result = s.str.split(pat=pat, n=n)
188
+ xp = s.str.split(pat=pat)
189
+ tm.assert_series_equal(result, xp)
190
+
191
+
192
+ @pytest.mark.parametrize(
193
+ "data, pat, expected_val",
194
+ [
195
+ (
196
+ ["split once", "split once too!"],
197
+ None,
198
+ "once too!",
199
+ ),
200
+ (
201
+ ["split_once", "split_once_too!"],
202
+ "_",
203
+ "once_too!",
204
+ ),
205
+ ],
206
+ )
207
+ def test_split_no_pat_with_nonzero_n(data, pat, expected_val, any_string_dtype):
208
+ s = Series(data, dtype=any_string_dtype)
209
+ result = s.str.split(pat=pat, n=1)
210
+ expected = Series({0: ["split", "once"], 1: ["split", expected_val]})
211
+ tm.assert_series_equal(expected, result, check_index_type=False)
212
+
213
+
214
+ def test_split_to_dataframe_no_splits(any_string_dtype):
215
+ s = Series(["nosplit", "alsonosplit"], dtype=any_string_dtype)
216
+ result = s.str.split("_", expand=True)
217
+ exp = DataFrame({0: Series(["nosplit", "alsonosplit"], dtype=any_string_dtype)})
218
+ tm.assert_frame_equal(result, exp)
219
+
220
+
221
+ def test_split_to_dataframe(any_string_dtype):
222
+ s = Series(["some_equal_splits", "with_no_nans"], dtype=any_string_dtype)
223
+ result = s.str.split("_", expand=True)
224
+ exp = DataFrame(
225
+ {0: ["some", "with"], 1: ["equal", "no"], 2: ["splits", "nans"]},
226
+ dtype=any_string_dtype,
227
+ )
228
+ tm.assert_frame_equal(result, exp)
229
+
230
+
231
+ def test_split_to_dataframe_unequal_splits(any_string_dtype):
232
+ s = Series(
233
+ ["some_unequal_splits", "one_of_these_things_is_not"], dtype=any_string_dtype
234
+ )
235
+ result = s.str.split("_", expand=True)
236
+ exp = DataFrame(
237
+ {
238
+ 0: ["some", "one"],
239
+ 1: ["unequal", "of"],
240
+ 2: ["splits", "these"],
241
+ 3: [None, "things"],
242
+ 4: [None, "is"],
243
+ 5: [None, "not"],
244
+ },
245
+ dtype=any_string_dtype,
246
+ )
247
+ tm.assert_frame_equal(result, exp)
248
+
249
+
250
+ def test_split_to_dataframe_with_index(any_string_dtype):
251
+ s = Series(
252
+ ["some_splits", "with_index"], index=["preserve", "me"], dtype=any_string_dtype
253
+ )
254
+ result = s.str.split("_", expand=True)
255
+ exp = DataFrame(
256
+ {0: ["some", "with"], 1: ["splits", "index"]},
257
+ index=["preserve", "me"],
258
+ dtype=any_string_dtype,
259
+ )
260
+ tm.assert_frame_equal(result, exp)
261
+
262
+ with pytest.raises(ValueError, match="expand must be"):
263
+ s.str.split("_", expand="not_a_boolean")
264
+
265
+
266
+ def test_split_to_multiindex_expand_no_splits():
267
+ # https://github.com/pandas-dev/pandas/issues/23677
268
+
269
+ idx = Index(["nosplit", "alsonosplit", np.nan])
270
+ result = idx.str.split("_", expand=True)
271
+ exp = idx
272
+ tm.assert_index_equal(result, exp)
273
+ assert result.nlevels == 1
274
+
275
+
276
+ def test_split_to_multiindex_expand():
277
+ idx = Index(["some_equal_splits", "with_no_nans", np.nan, None])
278
+ result = idx.str.split("_", expand=True)
279
+ exp = MultiIndex.from_tuples(
280
+ [
281
+ ("some", "equal", "splits"),
282
+ ("with", "no", "nans"),
283
+ [np.nan, np.nan, np.nan],
284
+ [None, None, None],
285
+ ]
286
+ )
287
+ tm.assert_index_equal(result, exp)
288
+ assert result.nlevels == 3
289
+
290
+
291
+ def test_split_to_multiindex_expand_unequal_splits():
292
+ idx = Index(["some_unequal_splits", "one_of_these_things_is_not", np.nan, None])
293
+ result = idx.str.split("_", expand=True)
294
+ exp = MultiIndex.from_tuples(
295
+ [
296
+ ("some", "unequal", "splits", np.nan, np.nan, np.nan),
297
+ ("one", "of", "these", "things", "is", "not"),
298
+ (np.nan, np.nan, np.nan, np.nan, np.nan, np.nan),
299
+ (None, None, None, None, None, None),
300
+ ]
301
+ )
302
+ tm.assert_index_equal(result, exp)
303
+ assert result.nlevels == 6
304
+
305
+ with pytest.raises(ValueError, match="expand must be"):
306
+ idx.str.split("_", expand="not_a_boolean")
307
+
308
+
309
+ @pytest.mark.parametrize(
310
+ "pat, expected_data",
311
+ [
312
+ (r"a(?=b)", [["aa"], ["", "b"], ["ba"], ["bb"]]),
313
+ (r"(?<=a)b", [["aa"], ["a", ""], ["ba"], ["bb"]]),
314
+ (r"a(?!b)", [["", "", ""], ["ab"], ["b", ""], ["bb"]]),
315
+ (r"(?<!b)a", [["", "", ""], ["", "b"], ["ba"], ["bb"]]),
316
+ ("ab", [["aa"], ["", ""], ["ba"], ["bb"]]),
317
+ ],
318
+ )
319
+ def test_split_lookarounds(any_string_dtype, pat, expected_data):
320
+ # https://github.com/pandas-dev/pandas/issues/60833
321
+ ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype)
322
+ result = ser.str.split(pat, regex=True)
323
+ if any_string_dtype == "object":
324
+ null_result = None
325
+ elif any_string_dtype == "str":
326
+ null_result = np.nan
327
+ elif any_string_dtype == "string":
328
+ null_result = pd.NA
329
+ else:
330
+ raise ValueError(f"Unrecognized dtype: {any_string_dtype}")
331
+ expected = Series([*expected_data, null_result])
332
+ tm.assert_series_equal(result, expected)
333
+
334
+
335
+ def test_split_regex_end_of_string(any_string_dtype):
336
+ # https://github.com/pandas-dev/pandas/pull/63613
337
+ ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
338
+
339
+ # with dollar sign
340
+ result = ser.str.split("r$", regex=True)
341
+ expected = Series([["baz"], ["ba", ""], ["bars"], ["ba", "\n"]], dtype=object)
342
+ tm.assert_series_equal(result, expected)
343
+
344
+ # with \Z (ensure this is translated to \z for pyarrow)
345
+ result = ser.str.split(r"r\Z", regex=True)
346
+ expected = Series([["baz"], ["ba", ""], ["bars"], ["bar\n"]], dtype=object)
347
+ tm.assert_series_equal(result, expected)
348
+
349
+ # ensure finding a literal \Z still works
350
+ ser = Series([r"bar\Z", "bar", r"bar\Zs", "bar\n"], dtype=any_string_dtype)
351
+ result = ser.str.split(r"r\\Z", regex=True)
352
+ expected = Series([["ba", ""], ["bar"], ["ba", "s"], ["bar\n"]], dtype=object)
353
+ tm.assert_series_equal(result, expected)
354
+
355
+
356
+ def test_rsplit_to_dataframe_expand_no_splits(any_string_dtype):
357
+ s = Series(["nosplit", "alsonosplit"], dtype=any_string_dtype)
358
+ result = s.str.rsplit("_", expand=True)
359
+ exp = DataFrame({0: Series(["nosplit", "alsonosplit"])}, dtype=any_string_dtype)
360
+ tm.assert_frame_equal(result, exp)
361
+
362
+
363
+ def test_rsplit_to_dataframe_expand(any_string_dtype):
364
+ s = Series(["some_equal_splits", "with_no_nans"], dtype=any_string_dtype)
365
+ result = s.str.rsplit("_", expand=True)
366
+ exp = DataFrame(
367
+ {0: ["some", "with"], 1: ["equal", "no"], 2: ["splits", "nans"]},
368
+ dtype=any_string_dtype,
369
+ )
370
+ tm.assert_frame_equal(result, exp)
371
+
372
+ result = s.str.rsplit("_", expand=True, n=2)
373
+ exp = DataFrame(
374
+ {0: ["some", "with"], 1: ["equal", "no"], 2: ["splits", "nans"]},
375
+ dtype=any_string_dtype,
376
+ )
377
+ tm.assert_frame_equal(result, exp)
378
+
379
+ result = s.str.rsplit("_", expand=True, n=1)
380
+ exp = DataFrame(
381
+ {0: ["some_equal", "with_no"], 1: ["splits", "nans"]}, dtype=any_string_dtype
382
+ )
383
+ tm.assert_frame_equal(result, exp)
384
+
385
+
386
+ def test_rsplit_to_dataframe_expand_with_index(any_string_dtype):
387
+ s = Series(
388
+ ["some_splits", "with_index"], index=["preserve", "me"], dtype=any_string_dtype
389
+ )
390
+ result = s.str.rsplit("_", expand=True)
391
+ exp = DataFrame(
392
+ {0: ["some", "with"], 1: ["splits", "index"]},
393
+ index=["preserve", "me"],
394
+ dtype=any_string_dtype,
395
+ )
396
+ tm.assert_frame_equal(result, exp)
397
+
398
+
399
+ def test_rsplit_to_multiindex_expand_no_split():
400
+ idx = Index(["nosplit", "alsonosplit"])
401
+ result = idx.str.rsplit("_", expand=True)
402
+ exp = idx
403
+ tm.assert_index_equal(result, exp)
404
+ assert result.nlevels == 1
405
+
406
+
407
+ def test_rsplit_to_multiindex_expand():
408
+ idx = Index(["some_equal_splits", "with_no_nans"])
409
+ result = idx.str.rsplit("_", expand=True)
410
+ exp = MultiIndex.from_tuples([("some", "equal", "splits"), ("with", "no", "nans")])
411
+ tm.assert_index_equal(result, exp)
412
+ assert result.nlevels == 3
413
+
414
+
415
+ def test_rsplit_to_multiindex_expand_n():
416
+ idx = Index(["some_equal_splits", "with_no_nans"])
417
+ result = idx.str.rsplit("_", expand=True, n=1)
418
+ exp = MultiIndex.from_tuples([("some_equal", "splits"), ("with_no", "nans")])
419
+ tm.assert_index_equal(result, exp)
420
+ assert result.nlevels == 2
421
+
422
+
423
+ def test_split_nan_expand(any_string_dtype):
424
+ # gh-18450
425
+ s = Series(["foo,bar,baz", np.nan], dtype=any_string_dtype)
426
+ result = s.str.split(",", expand=True)
427
+ exp = DataFrame(
428
+ [["foo", "bar", "baz"], [np.nan, np.nan, np.nan]], dtype=any_string_dtype
429
+ )
430
+ tm.assert_frame_equal(result, exp)
431
+
432
+ # check that these are actually np.nan/pd.NA and not None
433
+ # TODO see GH 18463
434
+ # tm.assert_frame_equal does not differentiate
435
+ if is_object_or_nan_string_dtype(any_string_dtype):
436
+ assert all(np.isnan(x) for x in result.iloc[1])
437
+ else:
438
+ assert all(x is pd.NA for x in result.iloc[1])
439
+
440
+
441
+ def test_split_with_name_series(any_string_dtype):
442
+ # GH 12617
443
+
444
+ # should preserve name
445
+ s = Series(["a,b", "c,d"], name="xxx", dtype=any_string_dtype)
446
+ res = s.str.split(",")
447
+ exp = Series([["a", "b"], ["c", "d"]], name="xxx")
448
+ tm.assert_series_equal(res, exp)
449
+
450
+ res = s.str.split(",", expand=True)
451
+ exp = DataFrame([["a", "b"], ["c", "d"]], dtype=any_string_dtype)
452
+ tm.assert_frame_equal(res, exp)
453
+
454
+
455
+ def test_split_with_name_index():
456
+ # GH 12617
457
+ idx = Index(["a,b", "c,d"], name="xxx")
458
+ res = idx.str.split(",")
459
+ exp = Index([["a", "b"], ["c", "d"]], name="xxx")
460
+ assert res.nlevels == 1
461
+ tm.assert_index_equal(res, exp)
462
+
463
+ res = idx.str.split(",", expand=True)
464
+ exp = MultiIndex.from_tuples([("a", "b"), ("c", "d")])
465
+ assert res.nlevels == 2
466
+ tm.assert_index_equal(res, exp)
467
+
468
+
469
+ @pytest.mark.parametrize(
470
+ "method, exp",
471
+ [
472
+ [
473
+ "partition",
474
+ [
475
+ ("a", "__", "b__c"),
476
+ ("c", "__", "d__e"),
477
+ np.nan,
478
+ ("f", "__", "g__h"),
479
+ None,
480
+ ],
481
+ ],
482
+ [
483
+ "rpartition",
484
+ [
485
+ ("a__b", "__", "c"),
486
+ ("c__d", "__", "e"),
487
+ np.nan,
488
+ ("f__g", "__", "h"),
489
+ None,
490
+ ],
491
+ ],
492
+ ],
493
+ )
494
+ def test_partition_series_more_than_one_char(method, exp, any_string_dtype):
495
+ # https://github.com/pandas-dev/pandas/issues/23558
496
+ # more than one char
497
+ s = Series(["a__b__c", "c__d__e", np.nan, "f__g__h", None], dtype=any_string_dtype)
498
+ result = getattr(s.str, method)("__", expand=False)
499
+ expected = Series(exp)
500
+ expected = _convert_na_value(s, expected)
501
+ tm.assert_series_equal(result, expected)
502
+
503
+
504
+ @pytest.mark.parametrize(
505
+ "method, exp",
506
+ [
507
+ [
508
+ "partition",
509
+ [("a", " ", "b c"), ("c", " ", "d e"), np.nan, ("f", " ", "g h"), None],
510
+ ],
511
+ [
512
+ "rpartition",
513
+ [("a b", " ", "c"), ("c d", " ", "e"), np.nan, ("f g", " ", "h"), None],
514
+ ],
515
+ ],
516
+ )
517
+ def test_partition_series_none(any_string_dtype, method, exp):
518
+ # https://github.com/pandas-dev/pandas/issues/23558
519
+ # None
520
+ s = Series(["a b c", "c d e", np.nan, "f g h", None], dtype=any_string_dtype)
521
+ result = getattr(s.str, method)(expand=False)
522
+ expected = Series(exp)
523
+ expected = _convert_na_value(s, expected)
524
+ tm.assert_series_equal(result, expected)
525
+
526
+
527
+ @pytest.mark.parametrize(
528
+ "method, exp",
529
+ [
530
+ [
531
+ "partition",
532
+ [("abc", "", ""), ("cde", "", ""), np.nan, ("fgh", "", ""), None],
533
+ ],
534
+ [
535
+ "rpartition",
536
+ [("", "", "abc"), ("", "", "cde"), np.nan, ("", "", "fgh"), None],
537
+ ],
538
+ ],
539
+ )
540
+ def test_partition_series_not_split(any_string_dtype, method, exp):
541
+ # https://github.com/pandas-dev/pandas/issues/23558
542
+ # Not split
543
+ s = Series(["abc", "cde", np.nan, "fgh", None], dtype=any_string_dtype)
544
+ result = getattr(s.str, method)("_", expand=False)
545
+ expected = Series(exp)
546
+ expected = _convert_na_value(s, expected)
547
+ tm.assert_series_equal(result, expected)
548
+
549
+
550
+ @pytest.mark.parametrize(
551
+ "method, exp",
552
+ [
553
+ [
554
+ "partition",
555
+ [("a", "_", "b_c"), ("c", "_", "d_e"), np.nan, ("f", "_", "g_h")],
556
+ ],
557
+ [
558
+ "rpartition",
559
+ [("a_b", "_", "c"), ("c_d", "_", "e"), np.nan, ("f_g", "_", "h")],
560
+ ],
561
+ ],
562
+ )
563
+ def test_partition_series_unicode(any_string_dtype, method, exp):
564
+ # https://github.com/pandas-dev/pandas/issues/23558
565
+ # unicode
566
+ s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
567
+
568
+ result = getattr(s.str, method)("_", expand=False)
569
+ expected = Series(exp)
570
+ expected = _convert_na_value(s, expected)
571
+ tm.assert_series_equal(result, expected)
572
+
573
+
574
+ @pytest.mark.parametrize("method", ["partition", "rpartition"])
575
+ def test_partition_series_stdlib(any_string_dtype, method):
576
+ # https://github.com/pandas-dev/pandas/issues/23558
577
+ # compare to standard lib
578
+ s = Series(["A_B_C", "B_C_D", "E_F_G", "EFGHEF"], dtype=any_string_dtype)
579
+ result = getattr(s.str, method)("_", expand=False).tolist()
580
+ assert result == [getattr(v, method)("_") for v in s]
581
+
582
+
583
+ @pytest.mark.parametrize(
584
+ "method, exp",
585
+ [
586
+ [
587
+ "partition",
588
+ [("a", "_", "b_c"), ("c", "_", "d_e"), ("f", "_", "g_h"), np.nan, None],
589
+ ],
590
+ [
591
+ "rpartition",
592
+ [("a_b", "_", "c"), ("c_d", "_", "e"), ("f_g", "_", "h"), np.nan, None],
593
+ ],
594
+ ],
595
+ )
596
+ def test_partition_index(method, exp):
597
+ # https://github.com/pandas-dev/pandas/issues/23558
598
+
599
+ values = Index(["a_b_c", "c_d_e", "f_g_h", np.nan, None])
600
+
601
+ result = getattr(values.str, method)("_", expand=False)
602
+ exp = Index(np.array(exp, dtype=object), dtype=object)
603
+ tm.assert_index_equal(result, exp)
604
+ assert result.nlevels == 1
605
+
606
+
607
+ @pytest.mark.parametrize(
608
+ "method, exp",
609
+ [
610
+ [
611
+ "partition",
612
+ {
613
+ 0: ["a", "c", np.nan, "f", None],
614
+ 1: ["_", "_", np.nan, "_", None],
615
+ 2: ["b_c", "d_e", np.nan, "g_h", None],
616
+ },
617
+ ],
618
+ [
619
+ "rpartition",
620
+ {
621
+ 0: ["a_b", "c_d", np.nan, "f_g", None],
622
+ 1: ["_", "_", np.nan, "_", None],
623
+ 2: ["c", "e", np.nan, "h", None],
624
+ },
625
+ ],
626
+ ],
627
+ )
628
+ def test_partition_to_dataframe(any_string_dtype, method, exp):
629
+ # https://github.com/pandas-dev/pandas/issues/23558
630
+
631
+ s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h", None], dtype=any_string_dtype)
632
+ result = getattr(s.str, method)("_")
633
+ expected = DataFrame(
634
+ exp,
635
+ dtype=any_string_dtype,
636
+ )
637
+ tm.assert_frame_equal(result, expected)
638
+
639
+
640
+ @pytest.mark.parametrize(
641
+ "method, exp",
642
+ [
643
+ [
644
+ "partition",
645
+ {
646
+ 0: ["a", "c", np.nan, "f", None],
647
+ 1: ["_", "_", np.nan, "_", None],
648
+ 2: ["b_c", "d_e", np.nan, "g_h", None],
649
+ },
650
+ ],
651
+ [
652
+ "rpartition",
653
+ {
654
+ 0: ["a_b", "c_d", np.nan, "f_g", None],
655
+ 1: ["_", "_", np.nan, "_", None],
656
+ 2: ["c", "e", np.nan, "h", None],
657
+ },
658
+ ],
659
+ ],
660
+ )
661
+ def test_partition_to_dataframe_from_series(any_string_dtype, method, exp):
662
+ # https://github.com/pandas-dev/pandas/issues/23558
663
+ s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h", None], dtype=any_string_dtype)
664
+ result = getattr(s.str, method)("_", expand=True)
665
+ expected = DataFrame(
666
+ exp,
667
+ dtype=any_string_dtype,
668
+ )
669
+ tm.assert_frame_equal(result, expected)
670
+
671
+
672
+ def test_partition_with_name(any_string_dtype):
673
+ # GH 12617
674
+
675
+ s = Series(["a,b", "c,d"], name="xxx", dtype=any_string_dtype)
676
+ result = s.str.partition(",")
677
+ expected = DataFrame(
678
+ {0: ["a", "c"], 1: [",", ","], 2: ["b", "d"]}, dtype=any_string_dtype
679
+ )
680
+ tm.assert_frame_equal(result, expected)
681
+
682
+
683
+ def test_partition_with_name_expand(any_string_dtype):
684
+ # GH 12617
685
+ # should preserve name
686
+ s = Series(["a,b", "c,d"], name="xxx", dtype=any_string_dtype)
687
+ result = s.str.partition(",", expand=False)
688
+ expected = Series([("a", ",", "b"), ("c", ",", "d")], name="xxx")
689
+ tm.assert_series_equal(result, expected)
690
+
691
+
692
+ def test_partition_index_with_name():
693
+ idx = Index(["a,b", "c,d"], name="xxx")
694
+ result = idx.str.partition(",")
695
+ expected = MultiIndex.from_tuples([("a", ",", "b"), ("c", ",", "d")])
696
+ assert result.nlevels == 3
697
+ tm.assert_index_equal(result, expected)
698
+
699
+
700
+ def test_partition_index_with_name_expand_false():
701
+ idx = Index(["a,b", "c,d"], name="xxx")
702
+ # should preserve name
703
+ result = idx.str.partition(",", expand=False)
704
+ expected = Index(np.array([("a", ",", "b"), ("c", ",", "d")]), name="xxx")
705
+ assert result.nlevels == 1
706
+ tm.assert_index_equal(result, expected)
707
+
708
+
709
+ @pytest.mark.parametrize("method", ["partition", "rpartition"])
710
+ def test_partition_sep_kwarg(any_string_dtype, method):
711
+ # GH 22676; depr kwarg "pat" in favor of "sep"
712
+ s = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
713
+
714
+ expected = getattr(s.str, method)(sep="_")
715
+ result = getattr(s.str, method)("_")
716
+ tm.assert_frame_equal(result, expected)
717
+
718
+
719
+ def test_get():
720
+ ser = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"])
721
+ result = ser.str.split("_").str.get(1)
722
+ expected = Series(["b", "d", np.nan, "g"], dtype=object)
723
+ tm.assert_series_equal(result, expected)
724
+
725
+
726
+ def test_get_mixed_object():
727
+ ser = Series(["a_b_c", np.nan, "c_d_e", True, datetime.today(), None, 1, 2.0])
728
+ result = ser.str.split("_").str.get(1)
729
+ expected = Series(
730
+ ["b", np.nan, "d", np.nan, np.nan, None, np.nan, np.nan], dtype=object
731
+ )
732
+ tm.assert_series_equal(result, expected)
733
+
734
+
735
+ @pytest.mark.parametrize("idx", [2, -3])
736
+ def test_get_bounds(idx):
737
+ ser = Series(["1_2_3_4_5", "6_7_8_9_10", "11_12"])
738
+ result = ser.str.split("_").str.get(idx)
739
+ expected = Series(["3", "8", np.nan], dtype=object)
740
+ tm.assert_series_equal(result, expected)
741
+
742
+
743
+ @pytest.mark.parametrize(
744
+ "idx, exp", [[2, [3, 3, np.nan, "b"]], [-1, [3, 3, np.nan, np.nan]]]
745
+ )
746
+ def test_get_complex(idx, exp):
747
+ # GH 20671, getting value not in dict raising `KeyError`
748
+ ser = Series([(1, 2, 3), [1, 2, 3], {1, 2, 3}, {1: "a", 2: "b", 3: "c"}])
749
+
750
+ result = ser.str.get(idx)
751
+ expected = Series(exp)
752
+ tm.assert_series_equal(result, expected)
753
+
754
+
755
+ @pytest.mark.parametrize("to_type", [tuple, list, np.array])
756
+ def test_get_complex_nested(to_type):
757
+ ser = Series([to_type([to_type([1, 2])])])
758
+
759
+ result = ser.str.get(0)
760
+ expected = Series([to_type([1, 2])])
761
+ tm.assert_series_equal(result, expected)
762
+
763
+ result = ser.str.get(1)
764
+ expected = Series([np.nan])
765
+ tm.assert_series_equal(result, expected)
766
+
767
+
768
+ def test_get_strings(any_string_dtype):
769
+ ser = Series(["a", "ab", np.nan, "abc"], dtype=any_string_dtype)
770
+ result = ser.str.get(2)
771
+ expected = Series([np.nan, np.nan, np.nan, "c"], dtype=any_string_dtype)
772
+ tm.assert_series_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_string_array.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas._libs import lib
5
+
6
+ from pandas import (
7
+ NA,
8
+ DataFrame,
9
+ Series,
10
+ _testing as tm,
11
+ )
12
+
13
+
14
+ def test_string_array(nullable_string_dtype, any_string_method):
15
+ method_name, args, kwargs = any_string_method
16
+
17
+ data = ["a", "bb", np.nan, "ccc"]
18
+ a = Series(data, dtype=object)
19
+ b = Series(data, dtype=nullable_string_dtype)
20
+
21
+ if method_name == "decode":
22
+ with pytest.raises(TypeError, match="a bytes-like object is required"):
23
+ getattr(b.str, method_name)(*args, **kwargs)
24
+ return
25
+
26
+ expected = getattr(a.str, method_name)(*args, **kwargs)
27
+ result = getattr(b.str, method_name)(*args, **kwargs)
28
+
29
+ if isinstance(expected, Series):
30
+ if expected.dtype == "object" and lib.is_string_array(
31
+ expected.dropna().values,
32
+ ):
33
+ assert result.dtype == nullable_string_dtype
34
+ result = result.astype(object)
35
+
36
+ elif expected.dtype == "object" and lib.is_bool_array(
37
+ expected.values, skipna=True
38
+ ):
39
+ assert result.dtype == "boolean"
40
+ expected = expected.astype("boolean")
41
+
42
+ elif expected.dtype == "bool":
43
+ assert result.dtype == "boolean"
44
+ result = result.astype("bool")
45
+
46
+ elif expected.dtype == "float" and expected.isna().any():
47
+ assert result.dtype == "Int64"
48
+ result = result.astype("float")
49
+
50
+ if expected.dtype == object:
51
+ # GH#18463
52
+ expected[expected.isna()] = NA
53
+
54
+ elif isinstance(expected, DataFrame):
55
+ columns = expected.select_dtypes(include="object").columns
56
+ assert all(result[columns].dtypes == nullable_string_dtype)
57
+ result[columns] = result[columns].astype(object)
58
+ expected[columns] = expected[columns].fillna(NA) # GH#18463
59
+
60
+ tm.assert_equal(result, expected)
61
+
62
+
63
+ @pytest.mark.parametrize(
64
+ "method,expected",
65
+ [
66
+ ("count", [2, None]),
67
+ ("find", [0, None]),
68
+ ("index", [0, None]),
69
+ ("rindex", [2, None]),
70
+ ],
71
+ )
72
+ def test_string_array_numeric_integer_array(nullable_string_dtype, method, expected):
73
+ s = Series(["aba", None], dtype=nullable_string_dtype)
74
+ result = getattr(s.str, method)("a")
75
+ expected = Series(expected, dtype="Int64")
76
+ tm.assert_series_equal(result, expected)
77
+
78
+
79
+ @pytest.mark.parametrize(
80
+ "method,expected",
81
+ [
82
+ ("isdigit", [False, None, True]),
83
+ ("isalpha", [True, None, False]),
84
+ ("isascii", [True, None, True]),
85
+ ("isalnum", [True, None, True]),
86
+ ("isnumeric", [False, None, True]),
87
+ ],
88
+ )
89
+ def test_string_array_boolean_array(nullable_string_dtype, method, expected):
90
+ s = Series(["a", None, "1"], dtype=nullable_string_dtype)
91
+ result = getattr(s.str, method)()
92
+ expected = Series(expected, dtype="boolean")
93
+ tm.assert_series_equal(result, expected)
94
+
95
+
96
+ def test_string_array_extract(nullable_string_dtype):
97
+ # https://github.com/pandas-dev/pandas/issues/30969
98
+ # Only expand=False & multiple groups was failing
99
+
100
+ a = Series(["a1", "b2", "cc"], dtype=nullable_string_dtype)
101
+ b = Series(["a1", "b2", "cc"], dtype="object")
102
+ pat = r"(\w)(\d)"
103
+
104
+ result = a.str.extract(pat, expand=False)
105
+ expected = b.str.extract(pat, expand=False)
106
+ expected = expected.fillna(NA) # GH#18463
107
+ assert all(result.dtypes == nullable_string_dtype)
108
+
109
+ result = result.astype(object)
110
+ tm.assert_equal(result, expected)
111
+
112
+
113
+ @pytest.mark.parametrize(
114
+ "values, width, expected",
115
+ [
116
+ (["a", "ab", "abc", None], 4, ["000a", "00ab", "0abc", None]),
117
+ (["1", "-1", "+1", None], 4, ["0001", "-001", "+001", None]),
118
+ (["1234", "-1234"], 3, ["1234", "-1234"]),
119
+ ],
120
+ )
121
+ def test_string_array_zfill(nullable_string_dtype, values, width, expected):
122
+ # GH #61485
123
+ s = Series(values, dtype=nullable_string_dtype)
124
+ result = s.str.zfill(width)
125
+ expected = Series(expected, dtype=nullable_string_dtype)
126
+ tm.assert_series_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/strings/test_strings.py ADDED
@@ -0,0 +1,952 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ datetime,
3
+ timedelta,
4
+ )
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas.compat import pa_version_under21p0
10
+
11
+ from pandas import (
12
+ NA,
13
+ DataFrame,
14
+ Index,
15
+ MultiIndex,
16
+ Series,
17
+ StringDtype,
18
+ option_context,
19
+ )
20
+ import pandas._testing as tm
21
+ from pandas.core.arrays._arrow_string_mixins import ArrowStringArrayMixin
22
+ from pandas.core.strings.accessor import StringMethods
23
+ from pandas.tests.strings import is_object_or_nan_string_dtype
24
+
25
+
26
+ @pytest.mark.parametrize("pattern", [0, True, Series(["foo", "bar"])])
27
+ def test_startswith_endswith_non_str_patterns(pattern):
28
+ # GH3485
29
+ ser = Series(["foo", "bar"])
30
+ msg = f"expected a string or tuple, not {type(pattern).__name__}"
31
+ with pytest.raises(TypeError, match=msg):
32
+ ser.str.startswith(pattern)
33
+ with pytest.raises(TypeError, match=msg):
34
+ ser.str.endswith(pattern)
35
+
36
+
37
+ def test_iter_raises():
38
+ # GH 54173
39
+ ser = Series(["foo", "bar"])
40
+ with pytest.raises(TypeError, match="'StringMethods' object is not iterable"):
41
+ iter(ser.str)
42
+
43
+
44
+ # test integer/float dtypes (inferred by constructor) and mixed
45
+
46
+
47
+ def test_count(any_string_dtype):
48
+ ser = Series(["foo", "foofoo", np.nan, "foooofooofommmfoo"], dtype=any_string_dtype)
49
+ result = ser.str.count("f[o]+")
50
+ if is_object_or_nan_string_dtype(any_string_dtype):
51
+ expected_dtype = np.float64
52
+ item = np.nan
53
+ else:
54
+ expected_dtype = "Int64"
55
+ item = NA
56
+
57
+ expected = Series([1, 2, item, 4], dtype=expected_dtype)
58
+ tm.assert_series_equal(result, expected)
59
+
60
+
61
+ def test_count_mixed_object():
62
+ ser = Series(
63
+ ["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
64
+ dtype=object,
65
+ )
66
+ result = ser.str.count("a")
67
+ expected = Series([1, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, np.nan])
68
+ tm.assert_series_equal(result, expected)
69
+
70
+
71
+ @pytest.mark.parametrize(
72
+ "pat, expected_data",
73
+ [
74
+ (r"a(?=b)", [0, 1, 0, 0, None]),
75
+ (r"(?<=a)b", [0, 1, 0, 0, None]),
76
+ (r"a(?!b)", [2, 0, 1, 0, None]),
77
+ (r"(?<!b)a", [2, 1, 0, 0, None]),
78
+ ("ab", [0, 1, 0, 0, None]),
79
+ ],
80
+ )
81
+ def test_count_lookarounds(any_string_dtype, pat, expected_data):
82
+ # https://github.com/pandas-dev/pandas/issues/60833
83
+ expected_dtype = (
84
+ "float64" if is_object_or_nan_string_dtype(any_string_dtype) else "Int64"
85
+ )
86
+ ser = Series(["aa", "ab", "ba", "bb", None], dtype=any_string_dtype)
87
+ result = ser.str.count(pat)
88
+ expected = Series(expected_data, dtype=expected_dtype)
89
+ tm.assert_series_equal(result, expected)
90
+
91
+
92
+ def test_count_end_of_string(any_string_dtype):
93
+ # https://github.com/pandas-dev/pandas/pull/63613
94
+ expected_dtype = (
95
+ "int64" if is_object_or_nan_string_dtype(any_string_dtype) else "Int64"
96
+ )
97
+
98
+ ser = Series(["baz", "bar", "bars", "bar\n"], dtype=any_string_dtype)
99
+
100
+ # with dollar sign
101
+ result = ser.str.count("bar$")
102
+ if any_string_dtype == "string" and any_string_dtype.storage == "pyarrow":
103
+ # pyarrow (RE2) only matches $ at the very end of the line
104
+ expected = Series([0, 1, 0, 0], dtype=expected_dtype)
105
+ else:
106
+ # python matches $ before or after an ending newline
107
+ expected = Series([0, 1, 0, 1], dtype=expected_dtype)
108
+ tm.assert_series_equal(result, expected)
109
+
110
+ # with \Z (ensure this is translated to \z for pyarrow)
111
+ result = ser.str.count(r"bar\Z")
112
+ expected = Series([0, 1, 0, 0], dtype=expected_dtype)
113
+ tm.assert_series_equal(result, expected)
114
+
115
+ # ensure finding a literal \Z still works
116
+ ser = Series([r"bar\Z", "bar", "bars", "bar\n"], dtype=any_string_dtype)
117
+ result = ser.str.count(r"bar\\Z")
118
+ expected = Series([1, 0, 0, 0], dtype=expected_dtype)
119
+ tm.assert_series_equal(result, expected)
120
+
121
+
122
+ def test_repeat(any_string_dtype):
123
+ ser = Series(["a", "b", np.nan, "c", np.nan, "d"], dtype=any_string_dtype)
124
+
125
+ result = ser.str.repeat(3)
126
+ expected = Series(
127
+ ["aaa", "bbb", np.nan, "ccc", np.nan, "ddd"], dtype=any_string_dtype
128
+ )
129
+ tm.assert_series_equal(result, expected)
130
+
131
+ result = ser.str.repeat([1, 2, 3, 4, 5, 6])
132
+ expected = Series(
133
+ ["a", "bb", np.nan, "cccc", np.nan, "dddddd"], dtype=any_string_dtype
134
+ )
135
+ tm.assert_series_equal(result, expected)
136
+
137
+
138
+ def test_repeat_mixed_object():
139
+ ser = Series(["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0])
140
+ result = ser.str.repeat(3)
141
+ expected = Series(
142
+ ["aaa", np.nan, "bbb", np.nan, np.nan, "foofoofoo", None, np.nan, np.nan],
143
+ dtype=object,
144
+ )
145
+ tm.assert_series_equal(result, expected)
146
+
147
+
148
+ @pytest.mark.parametrize("arg, repeat", [[None, 4], ["b", None]])
149
+ def test_repeat_with_null(any_string_dtype, arg, repeat):
150
+ # GH: 31632
151
+ ser = Series(["a", arg], dtype=any_string_dtype)
152
+ result = ser.str.repeat([3, repeat])
153
+ expected = Series(["aaa", None], dtype=any_string_dtype)
154
+ tm.assert_series_equal(result, expected)
155
+
156
+
157
+ def test_empty_str_methods(any_string_dtype):
158
+ empty_str = empty = Series(dtype=any_string_dtype)
159
+ empty_inferred_str = Series(dtype="str")
160
+ if is_object_or_nan_string_dtype(any_string_dtype):
161
+ empty_int = Series(dtype="int64")
162
+ empty_bool = Series(dtype=bool)
163
+ else:
164
+ empty_int = Series(dtype="Int64")
165
+ empty_bool = Series(dtype="boolean")
166
+ empty_object = Series(dtype=object)
167
+ empty_bytes = Series(dtype=object)
168
+ empty_df = DataFrame()
169
+
170
+ # GH7241
171
+ # (extract) on empty series
172
+
173
+ tm.assert_series_equal(empty_str, empty.str.cat(empty))
174
+ assert "" == empty.str.cat()
175
+ tm.assert_series_equal(empty_str, empty.str.title())
176
+ tm.assert_series_equal(empty_int, empty.str.count("a"))
177
+ tm.assert_series_equal(empty_bool, empty.str.contains("a"))
178
+ tm.assert_series_equal(empty_bool, empty.str.startswith("a"))
179
+ tm.assert_series_equal(empty_bool, empty.str.endswith("a"))
180
+ tm.assert_series_equal(empty_str, empty.str.lower())
181
+ tm.assert_series_equal(empty_str, empty.str.upper())
182
+ tm.assert_series_equal(empty_str, empty.str.replace("a", "b"))
183
+ tm.assert_series_equal(empty_str, empty.str.repeat(3))
184
+ tm.assert_series_equal(empty_bool, empty.str.match("^a"))
185
+ tm.assert_frame_equal(
186
+ DataFrame(columns=range(1), dtype=any_string_dtype),
187
+ empty.str.extract("()", expand=True),
188
+ )
189
+ tm.assert_frame_equal(
190
+ DataFrame(columns=range(2), dtype=any_string_dtype),
191
+ empty.str.extract("()()", expand=True),
192
+ )
193
+ tm.assert_series_equal(empty_str, empty.str.extract("()", expand=False))
194
+ tm.assert_frame_equal(
195
+ DataFrame(columns=range(2), dtype=any_string_dtype),
196
+ empty.str.extract("()()", expand=False),
197
+ )
198
+ tm.assert_frame_equal(empty_df.set_axis([], axis=1), empty.str.get_dummies())
199
+ tm.assert_series_equal(empty_str, empty_str.str.join(""))
200
+ tm.assert_series_equal(empty_int, empty.str.len())
201
+ tm.assert_series_equal(empty_object, empty_str.str.findall("a"))
202
+ tm.assert_series_equal(empty_int, empty.str.find("a"))
203
+ tm.assert_series_equal(empty_int, empty.str.rfind("a"))
204
+ tm.assert_series_equal(empty_str, empty.str.pad(42))
205
+ tm.assert_series_equal(empty_str, empty.str.center(42))
206
+ tm.assert_series_equal(empty_object, empty.str.split("a"))
207
+ tm.assert_series_equal(empty_object, empty.str.rsplit("a"))
208
+ tm.assert_series_equal(empty_object, empty.str.partition("a", expand=False))
209
+ tm.assert_frame_equal(empty_df, empty.str.partition("a"))
210
+ tm.assert_series_equal(empty_object, empty.str.rpartition("a", expand=False))
211
+ tm.assert_frame_equal(empty_df, empty.str.rpartition("a"))
212
+ tm.assert_series_equal(empty_str, empty.str.slice(stop=1))
213
+ tm.assert_series_equal(empty_str, empty.str.slice(step=1))
214
+ tm.assert_series_equal(empty_str, empty.str.strip())
215
+ tm.assert_series_equal(empty_str, empty.str.lstrip())
216
+ tm.assert_series_equal(empty_str, empty.str.rstrip())
217
+ tm.assert_series_equal(empty_str, empty.str.wrap(42))
218
+ tm.assert_series_equal(empty_str, empty.str.get(0))
219
+ tm.assert_series_equal(empty_inferred_str, empty_bytes.str.decode("ascii"))
220
+ tm.assert_series_equal(empty_bytes, empty.str.encode("ascii"))
221
+ # ismethods should always return boolean (GH 29624)
222
+ tm.assert_series_equal(empty_bool, empty.str.isalnum())
223
+ tm.assert_series_equal(empty_bool, empty.str.isalpha())
224
+ tm.assert_series_equal(empty_bool, empty.str.isascii())
225
+ tm.assert_series_equal(empty_bool, empty.str.isdigit())
226
+ tm.assert_series_equal(empty_bool, empty.str.isspace())
227
+ tm.assert_series_equal(empty_bool, empty.str.islower())
228
+ tm.assert_series_equal(empty_bool, empty.str.isupper())
229
+ tm.assert_series_equal(empty_bool, empty.str.istitle())
230
+ tm.assert_series_equal(empty_bool, empty.str.isnumeric())
231
+ tm.assert_series_equal(empty_bool, empty.str.isdecimal())
232
+ tm.assert_series_equal(empty_str, empty.str.capitalize())
233
+ tm.assert_series_equal(empty_str, empty.str.swapcase())
234
+ tm.assert_series_equal(empty_str, empty.str.normalize("NFC"))
235
+
236
+ table = str.maketrans("a", "b")
237
+ tm.assert_series_equal(empty_str, empty.str.translate(table))
238
+
239
+
240
+ @pytest.mark.parametrize(
241
+ "method, expected",
242
+ [
243
+ ("isascii", [True, True, True, True, True, True, True, True, True, True]),
244
+ ("isalnum", [True, True, True, True, True, False, True, True, False, False]),
245
+ ("isalpha", [True, True, True, False, False, False, True, False, False, False]),
246
+ (
247
+ "isdigit",
248
+ [False, False, False, True, False, False, False, True, False, False],
249
+ ),
250
+ (
251
+ "isnumeric",
252
+ [False, False, False, True, False, False, False, True, False, False],
253
+ ),
254
+ (
255
+ "isspace",
256
+ [False, False, False, False, False, False, False, False, False, True],
257
+ ),
258
+ (
259
+ "islower",
260
+ [False, True, False, False, False, False, False, False, False, False],
261
+ ),
262
+ (
263
+ "isupper",
264
+ [True, False, False, False, True, False, True, False, False, False],
265
+ ),
266
+ (
267
+ "istitle",
268
+ [True, False, True, False, True, False, False, False, False, False],
269
+ ),
270
+ ],
271
+ )
272
+ def test_ismethods(method, expected, any_string_dtype):
273
+ ser = Series(
274
+ ["A", "b", "Xy", "4", "3A", "", "TT", "55", "-", " "], dtype=any_string_dtype
275
+ )
276
+ expected_dtype = (
277
+ "bool" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
278
+ )
279
+ expected = Series(expected, dtype=expected_dtype)
280
+ result = getattr(ser.str, method)()
281
+ tm.assert_series_equal(result, expected)
282
+
283
+ # compare with standard library
284
+ expected_stdlib = [getattr(item, method)() for item in ser]
285
+ assert list(result) == expected_stdlib
286
+
287
+ # with missing value
288
+ ser.iloc[[1, 2, 3, 4]] = np.nan
289
+ result = getattr(ser.str, method)()
290
+ if ser.dtype == "object":
291
+ expected = expected.astype(object)
292
+ expected.iloc[[1, 2, 3, 4]] = np.nan
293
+ elif ser.dtype == "str":
294
+ # NaN propagates as False
295
+ expected.iloc[[1, 2, 3, 4]] = False
296
+ else:
297
+ # nullable dtypes propagate NaN
298
+ expected.iloc[[1, 2, 3, 4]] = np.nan
299
+
300
+
301
+ @pytest.mark.parametrize(
302
+ "method, expected",
303
+ [
304
+ ("isnumeric", [False, True, True, True, False, True, True, False]),
305
+ ("isdecimal", [False, True, False, False, False, False, True, False]),
306
+ ("isdigit", [False, True, True, False, False, False, True, False]),
307
+ ],
308
+ )
309
+ def test_isnumeric_unicode(method, expected, any_string_dtype):
310
+ # 0x00bc: ¼ VULGAR FRACTION ONE QUARTER
311
+ # 0x2605: ★ not number
312
+ # 0x1378: ፸ ETHIOPIC NUMBER SEVENTY
313
+ # 0xFF13: 3 Em 3 # noqa: RUF003
314
+ ser = Series(
315
+ ["A", "3", "³", "¼", "★", "፸", "3", "four"], # noqa: RUF001
316
+ dtype=any_string_dtype,
317
+ )
318
+ expected_dtype = (
319
+ "bool" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
320
+ )
321
+ expected = Series(expected, dtype=expected_dtype)
322
+ if (
323
+ method == "isdigit"
324
+ and isinstance(ser.dtype, StringDtype)
325
+ and ser.dtype.storage == "pyarrow"
326
+ and not pa_version_under21p0
327
+ ):
328
+ # known difference in behavior between python and pyarrow unicode handling
329
+ # pyarrow 21+ considers ¼ and ፸ as a digit, while python does not
330
+ expected.iloc[3] = True
331
+ expected.iloc[5] = True
332
+
333
+ result = getattr(ser.str, method)()
334
+ tm.assert_series_equal(result, expected)
335
+
336
+ # compare with standard library
337
+ # (only for non-pyarrow storage given the above differences)
338
+ if any_string_dtype == "object" or (
339
+ isinstance(any_string_dtype, StringDtype)
340
+ and any_string_dtype.storage == "python"
341
+ ):
342
+ expected = [getattr(item, method)() for item in ser]
343
+ assert list(result) == expected
344
+
345
+
346
+ @pytest.mark.parametrize(
347
+ "method, expected",
348
+ [
349
+ ("isnumeric", [False, np.nan, True, False, np.nan, True, False]),
350
+ ("isdecimal", [False, np.nan, False, False, np.nan, True, False]),
351
+ ],
352
+ )
353
+ def test_isnumeric_unicode_missing(method, expected, any_string_dtype):
354
+ values = ["A", np.nan, "¼", "★", np.nan, "3", "four"] # noqa: RUF001
355
+ ser = Series(values, dtype=any_string_dtype)
356
+ if any_string_dtype == "str":
357
+ # NaN propagates as False
358
+ expected = Series(expected, dtype=object).fillna(False).astype(bool)
359
+ else:
360
+ expected_dtype = (
361
+ "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean"
362
+ )
363
+ expected = Series(expected, dtype=expected_dtype)
364
+ result = getattr(ser.str, method)()
365
+ tm.assert_series_equal(result, expected)
366
+
367
+
368
+ def test_split_join_roundtrip(any_string_dtype):
369
+ ser = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
370
+ result = ser.str.split("_").str.join("_")
371
+ expected = ser.astype(object)
372
+ tm.assert_series_equal(result, expected)
373
+
374
+
375
+ def test_split_join_roundtrip_mixed_object():
376
+ ser = Series(
377
+ ["a_b", np.nan, "asdf_cas_asdf", True, datetime.today(), "foo", None, 1, 2.0]
378
+ )
379
+ result = ser.str.split("_").str.join("_")
380
+ expected = Series(
381
+ ["a_b", np.nan, "asdf_cas_asdf", np.nan, np.nan, "foo", None, np.nan, np.nan],
382
+ dtype=object,
383
+ )
384
+ tm.assert_series_equal(result, expected)
385
+
386
+
387
+ def test_len(any_string_dtype):
388
+ ser = Series(
389
+ ["foo", "fooo", "fooooo", np.nan, "fooooooo", "foo\n", "あ"],
390
+ dtype=any_string_dtype,
391
+ )
392
+ result = ser.str.len()
393
+ if is_object_or_nan_string_dtype(any_string_dtype):
394
+ expected_dtype = "float64"
395
+ item = np.nan
396
+ else:
397
+ expected_dtype = "Int64"
398
+ item = NA
399
+ expected = Series([3, 4, 6, item, 8, 4, 1], dtype=expected_dtype)
400
+ tm.assert_series_equal(result, expected)
401
+
402
+
403
+ def test_len_mixed():
404
+ ser = Series(
405
+ ["a_b", np.nan, "asdf_cas_asdf", True, datetime.today(), "foo", None, 1, 2.0]
406
+ )
407
+ result = ser.str.len()
408
+ expected = Series([3, np.nan, 13, np.nan, np.nan, 3, np.nan, np.nan, np.nan])
409
+ tm.assert_series_equal(result, expected)
410
+
411
+
412
+ @pytest.mark.parametrize(
413
+ "method,sub,start,end,expected",
414
+ [
415
+ ("index", "EF", None, None, [4, 3, 1, 0]),
416
+ ("rindex", "EF", None, None, [4, 5, 7, 4]),
417
+ ("index", "EF", 3, None, [4, 3, 7, 4]),
418
+ ("rindex", "EF", 3, None, [4, 5, 7, 4]),
419
+ ("index", "E", 4, 8, [4, 5, 7, 4]),
420
+ ("rindex", "E", 0, 5, [4, 3, 1, 4]),
421
+ ],
422
+ )
423
+ def test_index(method, sub, start, end, index_or_series, any_string_dtype, expected):
424
+ obj = index_or_series(
425
+ ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"], dtype=any_string_dtype
426
+ )
427
+ expected_dtype = (
428
+ np.int64 if is_object_or_nan_string_dtype(any_string_dtype) else "Int64"
429
+ )
430
+ expected = index_or_series(expected, dtype=expected_dtype)
431
+
432
+ result = getattr(obj.str, method)(sub, start, end)
433
+
434
+ if index_or_series is Series:
435
+ tm.assert_series_equal(result, expected)
436
+ else:
437
+ tm.assert_index_equal(result, expected)
438
+
439
+ # compare with standard library
440
+ expected = [getattr(item, method)(sub, start, end) for item in obj]
441
+ assert list(result) == expected
442
+
443
+
444
+ def test_index_not_found_raises(index_or_series, any_string_dtype):
445
+ obj = index_or_series(
446
+ ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"], dtype=any_string_dtype
447
+ )
448
+ with pytest.raises(ValueError, match="substring not found"):
449
+ obj.str.index("DE")
450
+
451
+
452
+ @pytest.mark.parametrize("method", ["index", "rindex"])
453
+ def test_index_wrong_type_raises(index_or_series, any_string_dtype, method):
454
+ obj = index_or_series([], dtype=any_string_dtype)
455
+ msg = "expected a string object, not int"
456
+
457
+ with pytest.raises(TypeError, match=msg):
458
+ getattr(obj.str, method)(0)
459
+
460
+
461
+ @pytest.mark.parametrize(
462
+ "method, exp",
463
+ [
464
+ ["index", [1, 1, 0]],
465
+ ["rindex", [3, 1, 2]],
466
+ ],
467
+ )
468
+ def test_index_missing(any_string_dtype, method, exp):
469
+ ser = Series(["abcb", "ab", "bcbe", np.nan], dtype=any_string_dtype)
470
+ if is_object_or_nan_string_dtype(any_string_dtype):
471
+ expected_dtype = np.float64
472
+ item = np.nan
473
+ else:
474
+ expected_dtype = "Int64"
475
+ item = NA
476
+
477
+ result = getattr(ser.str, method)("b")
478
+ expected = Series([*exp, item], dtype=expected_dtype)
479
+ tm.assert_series_equal(result, expected)
480
+
481
+
482
+ def test_pipe_failures(any_string_dtype):
483
+ # #2119
484
+ ser = Series(["A|B|C"], dtype=any_string_dtype)
485
+
486
+ result = ser.str.split("|")
487
+ expected = Series([["A", "B", "C"]], dtype=object)
488
+ tm.assert_series_equal(result, expected)
489
+
490
+ result = ser.str.replace("|", " ", regex=False)
491
+ expected = Series(["A B C"], dtype=any_string_dtype)
492
+ tm.assert_series_equal(result, expected)
493
+
494
+
495
+ @pytest.mark.parametrize(
496
+ "start, stop, step, expected",
497
+ [
498
+ (2, 5, None, ["foo", "bar", np.nan, "baz"]),
499
+ (0, 3, -1, ["", "", np.nan, ""]),
500
+ (None, None, -1, ["owtoofaa", "owtrabaa", np.nan, "xuqzabaa"]),
501
+ (None, 2, -1, ["owtoo", "owtra", np.nan, "xuqza"]),
502
+ (3, 10, 2, ["oto", "ato", np.nan, "aqx"]),
503
+ (3, 0, -1, ["ofa", "aba", np.nan, "aba"]),
504
+ ],
505
+ )
506
+ def test_slice(start, stop, step, expected, any_string_dtype):
507
+ ser = Series(["aafootwo", "aabartwo", np.nan, "aabazqux"], dtype=any_string_dtype)
508
+ result = ser.str.slice(start, stop, step)
509
+ expected = Series(expected, dtype=any_string_dtype)
510
+ tm.assert_series_equal(result, expected)
511
+
512
+
513
+ @pytest.mark.parametrize(
514
+ "start, stop, step, expected",
515
+ [
516
+ (2, 5, None, ["foo", np.nan, "bar", np.nan, np.nan, None, np.nan, np.nan]),
517
+ (4, 1, -1, ["oof", np.nan, "rab", np.nan, np.nan, None, np.nan, np.nan]),
518
+ ],
519
+ )
520
+ def test_slice_mixed_object(start, stop, step, expected):
521
+ ser = Series(["aafootwo", np.nan, "aabartwo", True, datetime.today(), None, 1, 2.0])
522
+ result = ser.str.slice(start, stop, step)
523
+ expected = Series(expected, dtype=object)
524
+ tm.assert_series_equal(result, expected)
525
+
526
+
527
+ @pytest.mark.parametrize(
528
+ "start,stop,repl,expected",
529
+ [
530
+ (2, 3, None, ["shrt", "a it longer", "evnlongerthanthat", "", np.nan]),
531
+ (2, 3, "z", ["shzrt", "a zit longer", "evznlongerthanthat", "z", np.nan]),
532
+ (2, 2, "z", ["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]),
533
+ (2, 1, "z", ["shzort", "a zbit longer", "evzenlongerthanthat", "z", np.nan]),
534
+ (-1, None, "z", ["shorz", "a bit longez", "evenlongerthanthaz", "z", np.nan]),
535
+ (None, -2, "z", ["zrt", "zer", "zat", "z", np.nan]),
536
+ (6, 8, "z", ["shortz", "a bit znger", "evenlozerthanthat", "z", np.nan]),
537
+ (-10, 3, "z", ["zrt", "a zit longer", "evenlongzerthanthat", "z", np.nan]),
538
+ ],
539
+ )
540
+ def test_slice_replace(start, stop, repl, expected, any_string_dtype):
541
+ ser = Series(
542
+ ["short", "a bit longer", "evenlongerthanthat", "", np.nan],
543
+ dtype=any_string_dtype,
544
+ )
545
+ expected = Series(expected, dtype=any_string_dtype)
546
+ result = ser.str.slice_replace(start, stop, repl)
547
+ tm.assert_series_equal(result, expected)
548
+
549
+
550
+ @pytest.mark.parametrize(
551
+ "method, exp",
552
+ [
553
+ ["strip", ["aa", "bb", np.nan, "cc"]],
554
+ ["lstrip", ["aa ", "bb \n", np.nan, "cc "]],
555
+ ["rstrip", [" aa", " bb", np.nan, "cc"]],
556
+ ],
557
+ )
558
+ def test_strip_lstrip_rstrip(any_string_dtype, method, exp):
559
+ ser = Series([" aa ", " bb \n", np.nan, "cc "], dtype=any_string_dtype)
560
+
561
+ result = getattr(ser.str, method)()
562
+ expected = Series(exp, dtype=any_string_dtype)
563
+ tm.assert_series_equal(result, expected)
564
+
565
+
566
+ @pytest.mark.parametrize(
567
+ "method, exp",
568
+ [
569
+ ["strip", ["aa", np.nan, "bb"]],
570
+ ["lstrip", ["aa ", np.nan, "bb \t\n"]],
571
+ ["rstrip", [" aa", np.nan, " bb"]],
572
+ ],
573
+ )
574
+ def test_strip_lstrip_rstrip_mixed_object(method, exp):
575
+ ser = Series([" aa ", np.nan, " bb \t\n", True, datetime.today(), None, 1, 2.0])
576
+
577
+ result = getattr(ser.str, method)()
578
+ expected = Series([*exp, np.nan, np.nan, None, np.nan, np.nan], dtype=object)
579
+ tm.assert_series_equal(result, expected)
580
+
581
+
582
+ @pytest.mark.parametrize(
583
+ "method, exp",
584
+ [
585
+ ["strip", ["ABC", " BNSD", "LDFJH "]],
586
+ ["lstrip", ["ABCxx", " BNSD", "LDFJH xx"]],
587
+ ["rstrip", ["xxABC", "xx BNSD", "LDFJH "]],
588
+ ],
589
+ )
590
+ def test_strip_lstrip_rstrip_args(any_string_dtype, method, exp):
591
+ ser = Series(["xxABCxx", "xx BNSD", "LDFJH xx"], dtype=any_string_dtype)
592
+
593
+ result = getattr(ser.str, method)("x")
594
+ expected = Series(exp, dtype=any_string_dtype)
595
+ tm.assert_series_equal(result, expected)
596
+
597
+
598
+ @pytest.mark.parametrize(
599
+ "prefix, expected",
600
+ [
601
+ ("a", ["b", " b c", "bc"]),
602
+ ("ab", ["", "a b c", "bc"]),
603
+ ("", ["ab", "a b c", "bc"]),
604
+ ],
605
+ )
606
+ def test_removeprefix(any_string_dtype, prefix, expected):
607
+ ser = Series(["ab", "a b c", "bc"], dtype=any_string_dtype)
608
+ result = ser.str.removeprefix(prefix)
609
+ ser_expected = Series(expected, dtype=any_string_dtype)
610
+ tm.assert_series_equal(result, ser_expected)
611
+
612
+
613
+ @pytest.mark.parametrize(
614
+ "suffix, expected",
615
+ [
616
+ ("c", ["ab", "a b ", "b"]),
617
+ ("bc", ["ab", "a b c", ""]),
618
+ ("", ["ab", "a b c", "bc"]),
619
+ ],
620
+ )
621
+ def test_removesuffix(any_string_dtype, suffix, expected):
622
+ ser = Series(["ab", "a b c", "bc"], dtype=any_string_dtype)
623
+ result = ser.str.removesuffix(suffix)
624
+ ser_expected = Series(expected, dtype=any_string_dtype)
625
+ tm.assert_series_equal(result, ser_expected)
626
+
627
+
628
+ def test_string_slice_get_syntax(any_string_dtype):
629
+ ser = Series(
630
+ ["YYY", "B", "C", "YYYYYYbYYY", "BYYYcYYY", np.nan, "CYYYBYYY", "dog", "cYYYt"],
631
+ dtype=any_string_dtype,
632
+ )
633
+
634
+ result = ser.str[0]
635
+ expected = ser.str.get(0)
636
+ tm.assert_series_equal(result, expected)
637
+
638
+ result = ser.str[:3]
639
+ expected = ser.str.slice(stop=3)
640
+ tm.assert_series_equal(result, expected)
641
+
642
+ result = ser.str[2::-1]
643
+ expected = ser.str.slice(start=2, step=-1)
644
+ tm.assert_series_equal(result, expected)
645
+
646
+
647
+ def test_string_slice_out_of_bounds_nested():
648
+ ser = Series([(1, 2), (1,), (3, 4, 5)])
649
+ result = ser.str[1]
650
+ expected = Series([2, np.nan, 4])
651
+ tm.assert_series_equal(result, expected)
652
+
653
+
654
+ def test_string_slice_out_of_bounds(any_string_dtype):
655
+ ser = Series(["foo", "b", "ba"], dtype=any_string_dtype)
656
+ result = ser.str[1]
657
+ expected = Series(["o", np.nan, "a"], dtype=any_string_dtype)
658
+ tm.assert_series_equal(result, expected)
659
+
660
+
661
+ def test_encode_decode(any_string_dtype):
662
+ ser = Series(["a", "b", "a\xe4"], dtype=any_string_dtype).str.encode("utf-8")
663
+ result = ser.str.decode("utf-8")
664
+ expected = Series(["a", "b", "a\xe4"], dtype="str")
665
+ tm.assert_series_equal(result, expected)
666
+
667
+
668
+ def test_encode_errors_kwarg(any_string_dtype):
669
+ ser = Series(["a", "b", "a\x9d"], dtype=any_string_dtype)
670
+
671
+ msg = (
672
+ r"'charmap' codec can't encode character '\\x9d' in position 1: "
673
+ "character maps to <undefined>"
674
+ )
675
+ with pytest.raises(UnicodeEncodeError, match=msg):
676
+ ser.str.encode("cp1252")
677
+
678
+ result = ser.str.encode("cp1252", "ignore")
679
+ expected = ser.map(lambda x: x.encode("cp1252", "ignore"))
680
+ tm.assert_series_equal(result, expected)
681
+
682
+
683
+ def test_decode_errors_kwarg():
684
+ ser = Series([b"a", b"b", b"a\x9d"])
685
+
686
+ msg = (
687
+ "'charmap' codec can't decode byte 0x9d in position 1: "
688
+ "character maps to <undefined>"
689
+ )
690
+ with pytest.raises(UnicodeDecodeError, match=msg):
691
+ ser.str.decode("cp1252")
692
+
693
+ result = ser.str.decode("cp1252", "ignore")
694
+ expected = ser.map(lambda x: x.decode("cp1252", "ignore")).astype("str")
695
+ tm.assert_series_equal(result, expected)
696
+
697
+
698
+ def test_decode_string_dtype(string_dtype):
699
+ # https://github.com/pandas-dev/pandas/pull/60940
700
+ ser = Series([b"a", b"b"])
701
+ result = ser.str.decode("utf-8", dtype=string_dtype)
702
+ expected = Series(["a", "b"], dtype=string_dtype)
703
+ tm.assert_series_equal(result, expected)
704
+
705
+
706
+ def test_decode_object_dtype(object_dtype):
707
+ # https://github.com/pandas-dev/pandas/pull/60940
708
+ ser = Series([b"a", rb"\ud800"])
709
+ result = ser.str.decode("utf-8", dtype=object_dtype)
710
+ expected = Series(["a", r"\ud800"], dtype=object_dtype)
711
+ tm.assert_series_equal(result, expected)
712
+
713
+
714
+ def test_decode_bad_dtype():
715
+ # https://github.com/pandas-dev/pandas/pull/60940
716
+ ser = Series([b"a", b"b"])
717
+ msg = "dtype must be string or object, got dtype='int64'"
718
+ with pytest.raises(ValueError, match=msg):
719
+ ser.str.decode("utf-8", dtype="int64")
720
+
721
+
722
+ @pytest.mark.parametrize(
723
+ "form, expected",
724
+ [
725
+ ("NFKC", ["ABC", "ABC", "123", np.nan, "アイエ"]),
726
+ ("NFC", ["ABC", "ABC", "123", np.nan, "アイエ"]), # noqa: RUF001
727
+ ],
728
+ )
729
+ def test_normalize(form, expected, any_string_dtype):
730
+ ser = Series(
731
+ ["ABC", "ABC", "123", np.nan, "アイエ"], # noqa: RUF001
732
+ index=["a", "b", "c", "d", "e"],
733
+ dtype=any_string_dtype,
734
+ )
735
+ expected = Series(expected, index=["a", "b", "c", "d", "e"], dtype=any_string_dtype)
736
+ result = ser.str.normalize(form)
737
+ tm.assert_series_equal(result, expected)
738
+
739
+
740
+ def test_normalize_bad_arg_raises(any_string_dtype):
741
+ ser = Series(
742
+ ["ABC", "ABC", "123", np.nan, "アイエ"], # noqa: RUF001
743
+ index=["a", "b", "c", "d", "e"],
744
+ dtype=any_string_dtype,
745
+ )
746
+ with pytest.raises(ValueError, match="invalid normalization form"):
747
+ ser.str.normalize("xxx")
748
+
749
+
750
+ def test_normalize_index():
751
+ idx = Index(["ABC", "123", "アイエ"]) # noqa: RUF001
752
+ expected = Index(["ABC", "123", "アイエ"])
753
+ result = idx.str.normalize("NFKC")
754
+ tm.assert_index_equal(result, expected)
755
+
756
+
757
+ @pytest.mark.parametrize(
758
+ "values,inferred_type",
759
+ [
760
+ (["a", "b"], "string"),
761
+ (["a", "b", 1], "mixed-integer"),
762
+ (["a", "b", 1.3], "mixed"),
763
+ (["a", "b", 1.3, 1], "mixed-integer"),
764
+ (["aa", datetime(2011, 1, 1)], "mixed"),
765
+ ],
766
+ )
767
+ def test_index_str_accessor_visibility(values, inferred_type, index_or_series):
768
+ obj = index_or_series(values)
769
+ if index_or_series is Index:
770
+ assert obj.inferred_type == inferred_type
771
+
772
+ assert isinstance(obj.str, StringMethods)
773
+
774
+
775
+ @pytest.mark.parametrize(
776
+ "values,inferred_type",
777
+ [
778
+ ([1, np.nan], "floating"),
779
+ ([datetime(2011, 1, 1)], "datetime64"),
780
+ ([timedelta(1)], "timedelta64"),
781
+ ],
782
+ )
783
+ def test_index_str_accessor_non_string_values_raises(
784
+ values, inferred_type, index_or_series
785
+ ):
786
+ obj = index_or_series(values)
787
+ if index_or_series is Index:
788
+ assert obj.inferred_type == inferred_type
789
+
790
+ msg = "Can only use .str accessor with string values"
791
+ with pytest.raises(AttributeError, match=msg):
792
+ obj.str
793
+
794
+
795
+ def test_index_str_accessor_multiindex_raises():
796
+ # MultiIndex has mixed dtype, but not allow to use accessor
797
+ idx = MultiIndex.from_tuples([("a", "b"), ("a", "b")])
798
+ assert idx.inferred_type == "mixed"
799
+
800
+ msg = "Can only use .str accessor with Index, not MultiIndex"
801
+ with pytest.raises(AttributeError, match=msg):
802
+ idx.str
803
+
804
+
805
+ def test_str_accessor_no_new_attributes(any_string_dtype):
806
+ # https://github.com/pandas-dev/pandas/issues/10673
807
+ ser = Series(list("aabbcde"), dtype=any_string_dtype)
808
+ with pytest.raises(AttributeError, match="You cannot add any new attribute"):
809
+ ser.str.xlabel = "a"
810
+
811
+
812
+ def test_cat_on_bytes_raises():
813
+ lhs = Series(np.array(list("abc"), "S1").astype(object))
814
+ rhs = Series(np.array(list("def"), "S1").astype(object))
815
+ msg = "Cannot use .str.cat with values of inferred dtype 'bytes'"
816
+ with pytest.raises(TypeError, match=msg):
817
+ lhs.str.cat(rhs)
818
+
819
+
820
+ def test_str_accessor_in_apply_func():
821
+ # https://github.com/pandas-dev/pandas/issues/38979
822
+ df = DataFrame(zip("abc", "def", strict=True))
823
+ expected = Series(["A/D", "B/E", "C/F"])
824
+ result = df.apply(lambda f: "/".join(f.str.upper()), axis=1)
825
+ tm.assert_series_equal(result, expected)
826
+
827
+
828
+ def test_zfill():
829
+ # https://github.com/pandas-dev/pandas/issues/20868
830
+ value = Series(["-1", "1", "1000", 10, np.nan])
831
+ expected = Series(["-01", "001", "1000", np.nan, np.nan], dtype=object)
832
+ tm.assert_series_equal(value.str.zfill(3), expected)
833
+
834
+ value = Series(["-2", "+5"])
835
+ expected = Series(["-0002", "+0005"])
836
+ tm.assert_series_equal(value.str.zfill(5), expected)
837
+
838
+
839
+ def test_zfill_with_non_integer_argument():
840
+ value = Series(["-2", "+5"])
841
+ wid = "a"
842
+ msg = f"width must be of integer type, not {type(wid).__name__}"
843
+ with pytest.raises(TypeError, match=msg):
844
+ value.str.zfill(wid)
845
+
846
+
847
+ def test_zfill_with_leading_sign():
848
+ value = Series(["-cat", "-1", "+dog"])
849
+ expected = Series(["-0cat", "-0001", "+0dog"])
850
+ tm.assert_series_equal(value.str.zfill(5), expected)
851
+
852
+
853
+ def test_get_with_dict_label():
854
+ # GH47911
855
+ s = Series(
856
+ [
857
+ {"name": "Hello", "value": "World"},
858
+ {"name": "Goodbye", "value": "Planet"},
859
+ {"value": "Sea"},
860
+ ]
861
+ )
862
+ result = s.str.get("name")
863
+ expected = Series(["Hello", "Goodbye", None], dtype=object)
864
+ tm.assert_series_equal(result, expected)
865
+ result = s.str.get("value")
866
+ expected = Series(["World", "Planet", "Sea"], dtype=object)
867
+ tm.assert_series_equal(result, expected)
868
+
869
+
870
+ def test_series_str_decode():
871
+ # GH 22613
872
+ result = Series([b"x", b"y"]).str.decode(encoding="UTF-8", errors="strict")
873
+ expected = Series(["x", "y"], dtype="str")
874
+ tm.assert_series_equal(result, expected)
875
+
876
+
877
+ def test_decode_with_dtype_none():
878
+ with option_context("future.infer_string", True):
879
+ ser = Series([b"a", b"b", b"c"])
880
+ result = ser.str.decode("utf-8", dtype=None)
881
+ expected = Series(["a", "b", "c"], dtype="str")
882
+ tm.assert_series_equal(result, expected)
883
+
884
+
885
+ def test_setitem_with_different_string_storage():
886
+ # GH#52987
887
+ # Test setitem with values from different string storage type
888
+ pytest.importorskip("pyarrow")
889
+
890
+ # Test Series[string[python]].__setitem__(Series[string[pyarrow]])
891
+ ser_python = Series(range(5), dtype="string[python]")
892
+ ser_pyarrow = ser_python.astype("string[pyarrow]")
893
+
894
+ ser_python[:2] = ser_pyarrow[:2]
895
+ expected = Series(["0", "1", "2", "3", "4"], dtype="string[python]")
896
+ tm.assert_series_equal(ser_python, expected)
897
+
898
+ # Test Series[string[pyarrow]].__setitem__(Series[string[python]])
899
+ ser_pyarrow = Series(range(5), dtype="string[pyarrow]")
900
+ ser_python = ser_pyarrow.astype("string[python]")
901
+
902
+ ser_pyarrow[:2] = ser_python[:2]
903
+ expected = Series(["0", "1", "2", "3", "4"], dtype="string[pyarrow]")
904
+ tm.assert_series_equal(ser_pyarrow, expected)
905
+
906
+ # Test with slice and missing values
907
+ ser_python = Series(["a", "b", None, "d", "e"], dtype="string[python]")
908
+ ser_pyarrow = Series(["X", "Y", None], dtype="string[pyarrow]")
909
+
910
+ ser_python[1:4] = ser_pyarrow
911
+ expected = Series(["a", "X", "Y", NA, "e"], dtype="string[python]")
912
+ tm.assert_series_equal(ser_python, expected)
913
+
914
+
915
+ @pytest.mark.parametrize(
916
+ "pat, expected",
917
+ [
918
+ # lookaround assertions
919
+ (r"(?=abc)", True),
920
+ (r"(?<=123)", True),
921
+ (r"(?!xyz)", True),
922
+ (r"(?<!\d)", True),
923
+ (r"(?=a|b)(?<=c)", True),
924
+ (r"abc", False),
925
+ (r"\d+", False),
926
+ (r"(abc)", False),
927
+ (r"a|b", False),
928
+ (r"a*", False),
929
+ (r"", False),
930
+ (r"\\(?=abc)", True),
931
+ (r"(?=.*[A-Z])", True),
932
+ (r"a(?=)", True),
933
+ (r"(?![0-9])", True),
934
+ (r"(?=(?!nested))", True),
935
+ (r"test\(\?\=ing\)", False),
936
+ (r"[(?=)]", False),
937
+ (r"(?#(?=comment)", False),
938
+ (r"(test # (?=comment))", True),
939
+ (r"(?=test)+", False),
940
+ (r"(?=test)*", False),
941
+ (r"(?=test)?", False),
942
+ (r"abc|(?=test)", True),
943
+ (r"^(?=test)$", True),
944
+ # backreferences
945
+ (r"(abc)\1", True),
946
+ (r"\b(\w+)\s+\1\b", True),
947
+ (r"\b(?P<word>\w+)\s+(?P=word)\b", True),
948
+ ],
949
+ )
950
+ def test_has_regex_unsupported_code(pat, expected):
951
+ # https://github.com/pandas-dev/pandas/issues/60833
952
+ assert ArrowStringArrayMixin._has_unsupported_regex(pat) == expected
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_aggregation.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas.core.apply import (
5
+ _make_unique_kwarg_list,
6
+ maybe_mangle_lambdas,
7
+ )
8
+
9
+
10
+ def test_maybe_mangle_lambdas_passthrough():
11
+ assert maybe_mangle_lambdas("mean") == "mean"
12
+ assert maybe_mangle_lambdas(lambda x: x).__name__ == "<lambda>"
13
+ # don't mangle single lambda.
14
+ assert maybe_mangle_lambdas([lambda x: x])[0].__name__ == "<lambda>"
15
+
16
+
17
+ def test_maybe_mangle_lambdas_listlike():
18
+ aggfuncs = [lambda x: 1, lambda x: 2]
19
+ result = maybe_mangle_lambdas(aggfuncs)
20
+ assert result[0].__name__ == "<lambda_0>"
21
+ assert result[1].__name__ == "<lambda_1>"
22
+ assert aggfuncs[0](None) == result[0](None)
23
+ assert aggfuncs[1](None) == result[1](None)
24
+
25
+
26
+ def test_maybe_mangle_lambdas():
27
+ func = {"A": [lambda x: 0, lambda x: 1]}
28
+ result = maybe_mangle_lambdas(func)
29
+ assert result["A"][0].__name__ == "<lambda_0>"
30
+ assert result["A"][1].__name__ == "<lambda_1>"
31
+
32
+
33
+ def test_maybe_mangle_lambdas_args():
34
+ func = {"A": [lambda x, a, b=1: (0, a, b), lambda x: 1]}
35
+ result = maybe_mangle_lambdas(func)
36
+ assert result["A"][0].__name__ == "<lambda_0>"
37
+ assert result["A"][1].__name__ == "<lambda_1>"
38
+
39
+ assert func["A"][0](0, 1) == (0, 1, 1)
40
+ assert func["A"][0](0, 1, 2) == (0, 1, 2)
41
+ assert func["A"][0](0, 2, b=3) == (0, 2, 3)
42
+
43
+
44
+ def test_maybe_mangle_lambdas_named():
45
+ func = {"C": np.mean, "D": {"foo": np.mean, "bar": np.mean}}
46
+ result = maybe_mangle_lambdas(func)
47
+ assert result == func
48
+
49
+
50
+ @pytest.mark.parametrize(
51
+ "order, expected_reorder",
52
+ [
53
+ (
54
+ [
55
+ ("height", "<lambda>"),
56
+ ("height", "max"),
57
+ ("weight", "max"),
58
+ ("height", "<lambda>"),
59
+ ("weight", "<lambda>"),
60
+ ],
61
+ [
62
+ ("height", "<lambda>_0"),
63
+ ("height", "max"),
64
+ ("weight", "max"),
65
+ ("height", "<lambda>_1"),
66
+ ("weight", "<lambda>"),
67
+ ],
68
+ ),
69
+ (
70
+ [
71
+ ("col2", "min"),
72
+ ("col1", "<lambda>"),
73
+ ("col1", "<lambda>"),
74
+ ("col1", "<lambda>"),
75
+ ],
76
+ [
77
+ ("col2", "min"),
78
+ ("col1", "<lambda>_0"),
79
+ ("col1", "<lambda>_1"),
80
+ ("col1", "<lambda>_2"),
81
+ ],
82
+ ),
83
+ (
84
+ [("col", "<lambda>"), ("col", "<lambda>"), ("col", "<lambda>")],
85
+ [("col", "<lambda>_0"), ("col", "<lambda>_1"), ("col", "<lambda>_2")],
86
+ ),
87
+ ],
88
+ )
89
+ def test_make_unique(order, expected_reorder):
90
+ # GH 27519, test if make_unique function reorders correctly
91
+ result = _make_unique_kwarg_list(order)
92
+
93
+ assert result == expected_reorder
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_algos.py ADDED
@@ -0,0 +1,2083 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import struct
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas._libs import (
8
+ algos as libalgos,
9
+ hashtable as ht,
10
+ )
11
+
12
+ from pandas.core.dtypes.common import (
13
+ is_bool_dtype,
14
+ is_complex_dtype,
15
+ is_float_dtype,
16
+ is_integer_dtype,
17
+ is_object_dtype,
18
+ )
19
+ from pandas.core.dtypes.dtypes import (
20
+ CategoricalDtype,
21
+ DatetimeTZDtype,
22
+ )
23
+
24
+ import pandas as pd
25
+ from pandas import (
26
+ Categorical,
27
+ CategoricalIndex,
28
+ DataFrame,
29
+ DatetimeIndex,
30
+ Index,
31
+ IntervalIndex,
32
+ MultiIndex,
33
+ NaT,
34
+ Period,
35
+ PeriodIndex,
36
+ Series,
37
+ Timedelta,
38
+ Timestamp,
39
+ cut,
40
+ date_range,
41
+ timedelta_range,
42
+ to_datetime,
43
+ to_timedelta,
44
+ )
45
+ import pandas._testing as tm
46
+ import pandas.core.algorithms as algos
47
+ from pandas.core.arrays import (
48
+ DatetimeArray,
49
+ TimedeltaArray,
50
+ )
51
+ import pandas.core.common as com
52
+
53
+
54
+ class TestFactorize:
55
+ def test_factorize_complex(self):
56
+ # GH#17927
57
+ array = np.array([1, 2, 2 + 1j], dtype=complex)
58
+ labels, uniques = algos.factorize(array)
59
+
60
+ expected_labels = np.array([0, 1, 2], dtype=np.intp)
61
+ tm.assert_numpy_array_equal(labels, expected_labels)
62
+
63
+ expected_uniques = np.array([(1 + 0j), (2 + 0j), (2 + 1j)], dtype=complex)
64
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
65
+
66
+ def test_factorize(self, index_or_series_obj, sort):
67
+ obj = index_or_series_obj
68
+ result_codes, result_uniques = obj.factorize(sort=sort)
69
+
70
+ constructor = Index
71
+ if isinstance(obj, MultiIndex):
72
+ constructor = MultiIndex.from_tuples
73
+ expected_arr = obj.unique()
74
+ if expected_arr.dtype == np.float16:
75
+ expected_arr = expected_arr.astype(np.float32)
76
+ expected_uniques = constructor(expected_arr)
77
+ if (
78
+ isinstance(obj, Index)
79
+ and expected_uniques.dtype == bool
80
+ and obj.dtype == object
81
+ ):
82
+ expected_uniques = expected_uniques.astype(object)
83
+
84
+ if sort:
85
+ expected_uniques = expected_uniques.sort_values()
86
+
87
+ # construct an integer ndarray so that
88
+ # `expected_uniques.take(expected_codes)` is equal to `obj`
89
+ expected_uniques_list = list(expected_uniques)
90
+ expected_codes = [expected_uniques_list.index(val) for val in obj]
91
+ expected_codes = np.asarray(expected_codes, dtype=np.intp)
92
+
93
+ tm.assert_numpy_array_equal(result_codes, expected_codes)
94
+ tm.assert_index_equal(result_uniques, expected_uniques, exact=True)
95
+
96
+ def test_series_factorize_use_na_sentinel_false(self):
97
+ # GH#35667
98
+ values = np.array([1, 2, 1, np.nan])
99
+ ser = Series(values)
100
+ codes, uniques = ser.factorize(use_na_sentinel=False)
101
+
102
+ expected_codes = np.array([0, 1, 0, 2], dtype=np.intp)
103
+ expected_uniques = Index([1.0, 2.0, np.nan])
104
+
105
+ tm.assert_numpy_array_equal(codes, expected_codes)
106
+ tm.assert_index_equal(uniques, expected_uniques)
107
+
108
+ def test_basic(self):
109
+ items = np.array(["a", "b", "b", "a", "a", "c", "c", "c"], dtype=object)
110
+ codes, uniques = algos.factorize(items)
111
+ tm.assert_numpy_array_equal(uniques, np.array(["a", "b", "c"], dtype=object))
112
+
113
+ codes, uniques = algos.factorize(items, sort=True)
114
+ exp = np.array([0, 1, 1, 0, 0, 2, 2, 2], dtype=np.intp)
115
+ tm.assert_numpy_array_equal(codes, exp)
116
+ exp = np.array(["a", "b", "c"], dtype=object)
117
+ tm.assert_numpy_array_equal(uniques, exp)
118
+
119
+ arr = np.arange(5, dtype=np.intp)[::-1]
120
+
121
+ codes, uniques = algos.factorize(arr)
122
+ exp = np.array([0, 1, 2, 3, 4], dtype=np.intp)
123
+ tm.assert_numpy_array_equal(codes, exp)
124
+ exp = np.array([4, 3, 2, 1, 0], dtype=arr.dtype)
125
+ tm.assert_numpy_array_equal(uniques, exp)
126
+
127
+ codes, uniques = algos.factorize(arr, sort=True)
128
+ exp = np.array([4, 3, 2, 1, 0], dtype=np.intp)
129
+ tm.assert_numpy_array_equal(codes, exp)
130
+ exp = np.array([0, 1, 2, 3, 4], dtype=arr.dtype)
131
+ tm.assert_numpy_array_equal(uniques, exp)
132
+
133
+ arr = np.arange(5.0)[::-1]
134
+
135
+ codes, uniques = algos.factorize(arr)
136
+ exp = np.array([0, 1, 2, 3, 4], dtype=np.intp)
137
+ tm.assert_numpy_array_equal(codes, exp)
138
+ exp = np.array([4.0, 3.0, 2.0, 1.0, 0.0], dtype=arr.dtype)
139
+ tm.assert_numpy_array_equal(uniques, exp)
140
+
141
+ codes, uniques = algos.factorize(arr, sort=True)
142
+ exp = np.array([4, 3, 2, 1, 0], dtype=np.intp)
143
+ tm.assert_numpy_array_equal(codes, exp)
144
+ exp = np.array([0.0, 1.0, 2.0, 3.0, 4.0], dtype=arr.dtype)
145
+ tm.assert_numpy_array_equal(uniques, exp)
146
+
147
+ def test_mixed(self):
148
+ # doc example reshaping.rst
149
+ x = Series(["A", "A", np.nan, "B", 3.14, np.inf])
150
+ codes, uniques = algos.factorize(x)
151
+
152
+ exp = np.array([0, 0, -1, 1, 2, 3], dtype=np.intp)
153
+ tm.assert_numpy_array_equal(codes, exp)
154
+ exp = Index(["A", "B", 3.14, np.inf])
155
+ tm.assert_index_equal(uniques, exp)
156
+
157
+ codes, uniques = algos.factorize(x, sort=True)
158
+ exp = np.array([2, 2, -1, 3, 0, 1], dtype=np.intp)
159
+ tm.assert_numpy_array_equal(codes, exp)
160
+ exp = Index([3.14, np.inf, "A", "B"])
161
+ tm.assert_index_equal(uniques, exp)
162
+
163
+ def test_factorize_datetime64(self):
164
+ # M8
165
+ v1 = Timestamp("20130101 09:00:00.00004")
166
+ v2 = Timestamp("20130101")
167
+ x = Series([v1, v1, v1, v2, v2, v1])
168
+ codes, uniques = algos.factorize(x)
169
+
170
+ exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp)
171
+ tm.assert_numpy_array_equal(codes, exp)
172
+ exp = DatetimeIndex([v1, v2])
173
+ tm.assert_index_equal(uniques, exp)
174
+
175
+ codes, uniques = algos.factorize(x, sort=True)
176
+ exp = np.array([1, 1, 1, 0, 0, 1], dtype=np.intp)
177
+ tm.assert_numpy_array_equal(codes, exp)
178
+ exp = DatetimeIndex([v2, v1])
179
+ tm.assert_index_equal(uniques, exp)
180
+
181
+ def test_factorize_period(self):
182
+ # period
183
+ v1 = Period("201302", freq="M")
184
+ v2 = Period("201303", freq="M")
185
+ x = Series([v1, v1, v1, v2, v2, v1])
186
+
187
+ # periods are not 'sorted' as they are converted back into an index
188
+ codes, uniques = algos.factorize(x)
189
+ exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp)
190
+ tm.assert_numpy_array_equal(codes, exp)
191
+ tm.assert_index_equal(uniques, PeriodIndex([v1, v2]))
192
+
193
+ codes, uniques = algos.factorize(x, sort=True)
194
+ exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp)
195
+ tm.assert_numpy_array_equal(codes, exp)
196
+ tm.assert_index_equal(uniques, PeriodIndex([v1, v2]))
197
+
198
+ def test_factorize_timedelta(self):
199
+ # GH 5986
200
+ v1 = to_timedelta("1 day 1 min")
201
+ v2 = to_timedelta("1 day")
202
+ x = Series([v1, v2, v1, v1, v2, v2, v1])
203
+ codes, uniques = algos.factorize(x)
204
+ exp = np.array([0, 1, 0, 0, 1, 1, 0], dtype=np.intp)
205
+ tm.assert_numpy_array_equal(codes, exp)
206
+ tm.assert_index_equal(uniques, to_timedelta([v1, v2]))
207
+
208
+ codes, uniques = algos.factorize(x, sort=True)
209
+ exp = np.array([1, 0, 1, 1, 0, 0, 1], dtype=np.intp)
210
+ tm.assert_numpy_array_equal(codes, exp)
211
+ tm.assert_index_equal(uniques, to_timedelta([v2, v1]))
212
+
213
+ def test_factorize_nan(self):
214
+ # nan should map to na_sentinel, not reverse_indexer[na_sentinel]
215
+ # rizer.factorize should not raise an exception if na_sentinel indexes
216
+ # outside of reverse_indexer
217
+ key = np.array([1, 2, 1, np.nan], dtype="O")
218
+ rizer = ht.ObjectFactorizer(len(key))
219
+ for na_sentinel in (-1, 20):
220
+ ids = rizer.factorize(key, na_sentinel=na_sentinel)
221
+ expected = np.array([0, 1, 0, na_sentinel], dtype=np.intp)
222
+ assert len(set(key)) == len(set(expected))
223
+ tm.assert_numpy_array_equal(pd.isna(key), expected == na_sentinel)
224
+ tm.assert_numpy_array_equal(ids, expected)
225
+
226
+ def test_factorizer_with_mask(self):
227
+ # GH#49549
228
+ data = np.array([1, 2, 3, 1, 1, 0], dtype="int64")
229
+ mask = np.array([False, False, False, False, False, True])
230
+ rizer = ht.Int64Factorizer(len(data))
231
+ result = rizer.factorize(data, mask=mask)
232
+ expected = np.array([0, 1, 2, 0, 0, -1], dtype=np.intp)
233
+ tm.assert_numpy_array_equal(result, expected)
234
+ expected_uniques = np.array([1, 2, 3], dtype="int64")
235
+ tm.assert_numpy_array_equal(rizer.uniques.to_array(), expected_uniques)
236
+
237
+ def test_factorizer_object_with_nan(self):
238
+ # GH#49549
239
+ data = np.array([1, 2, 3, 1, np.nan])
240
+ rizer = ht.ObjectFactorizer(len(data))
241
+ result = rizer.factorize(data.astype(object))
242
+ expected = np.array([0, 1, 2, 0, -1], dtype=np.intp)
243
+ tm.assert_numpy_array_equal(result, expected)
244
+ expected_uniques = np.array([1, 2, 3], dtype=object)
245
+ tm.assert_numpy_array_equal(rizer.uniques.to_array(), expected_uniques)
246
+
247
+ @pytest.mark.parametrize(
248
+ "data, expected_codes, expected_uniques",
249
+ [
250
+ (
251
+ [(1, 1), (1, 2), (0, 0), (1, 2), "nonsense"],
252
+ [0, 1, 2, 1, 3],
253
+ [(1, 1), (1, 2), (0, 0), "nonsense"],
254
+ ),
255
+ (
256
+ [(1, 1), (1, 2), (0, 0), (1, 2), (1, 2, 3)],
257
+ [0, 1, 2, 1, 3],
258
+ [(1, 1), (1, 2), (0, 0), (1, 2, 3)],
259
+ ),
260
+ ([(1, 1), (1, 2), (0, 0), (1, 2)], [0, 1, 2, 1], [(1, 1), (1, 2), (0, 0)]),
261
+ ],
262
+ )
263
+ def test_factorize_tuple_list(self, data, expected_codes, expected_uniques):
264
+ # GH9454
265
+ data = com.asarray_tuplesafe(data, dtype=object)
266
+ codes, uniques = pd.factorize(data)
267
+
268
+ tm.assert_numpy_array_equal(codes, np.array(expected_codes, dtype=np.intp))
269
+
270
+ expected_uniques_array = com.asarray_tuplesafe(expected_uniques, dtype=object)
271
+ tm.assert_numpy_array_equal(uniques, expected_uniques_array)
272
+
273
+ def test_complex_sorting(self):
274
+ # gh 12666 - check no segfault
275
+ x17 = np.array([complex(i) for i in range(17)], dtype=object)
276
+
277
+ msg = "'[<>]' not supported between instances of .*"
278
+ with pytest.raises(TypeError, match=msg):
279
+ algos.factorize(x17[::-1], sort=True)
280
+
281
+ def test_numeric_dtype_factorize(self, any_real_numpy_dtype):
282
+ # GH41132
283
+ dtype = any_real_numpy_dtype
284
+ data = np.array([1, 2, 2, 1], dtype=dtype)
285
+ expected_codes = np.array([0, 1, 1, 0], dtype=np.intp)
286
+ expected_uniques = np.array([1, 2], dtype=dtype)
287
+
288
+ codes, uniques = algos.factorize(data)
289
+ tm.assert_numpy_array_equal(codes, expected_codes)
290
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
291
+
292
+ def test_float64_factorize(self, writable):
293
+ data = np.array([1.0, 1e8, 1.0, 1e-8, 1e8, 1.0], dtype=np.float64)
294
+ data.setflags(write=writable)
295
+ expected_codes = np.array([0, 1, 0, 2, 1, 0], dtype=np.intp)
296
+ expected_uniques = np.array([1.0, 1e8, 1e-8], dtype=np.float64)
297
+
298
+ codes, uniques = algos.factorize(data)
299
+ tm.assert_numpy_array_equal(codes, expected_codes)
300
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
301
+
302
+ def test_uint64_factorize(self, writable):
303
+ data = np.array([2**64 - 1, 1, 2**64 - 1], dtype=np.uint64)
304
+ data.setflags(write=writable)
305
+ expected_codes = np.array([0, 1, 0], dtype=np.intp)
306
+ expected_uniques = np.array([2**64 - 1, 1], dtype=np.uint64)
307
+
308
+ codes, uniques = algos.factorize(data)
309
+ tm.assert_numpy_array_equal(codes, expected_codes)
310
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
311
+
312
+ def test_int64_factorize(self, writable):
313
+ data = np.array([2**63 - 1, -(2**63), 2**63 - 1], dtype=np.int64)
314
+ data.setflags(write=writable)
315
+ expected_codes = np.array([0, 1, 0], dtype=np.intp)
316
+ expected_uniques = np.array([2**63 - 1, -(2**63)], dtype=np.int64)
317
+
318
+ codes, uniques = algos.factorize(data)
319
+ tm.assert_numpy_array_equal(codes, expected_codes)
320
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
321
+
322
+ def test_string_factorize(self, writable):
323
+ data = np.array(["a", "c", "a", "b", "c"], dtype=object)
324
+ data.setflags(write=writable)
325
+ expected_codes = np.array([0, 1, 0, 2, 1], dtype=np.intp)
326
+ expected_uniques = np.array(["a", "c", "b"], dtype=object)
327
+
328
+ codes, uniques = algos.factorize(data)
329
+ tm.assert_numpy_array_equal(codes, expected_codes)
330
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
331
+
332
+ def test_object_factorize(self, writable):
333
+ data = np.array(["a", "c", None, np.nan, "a", "b", NaT, "c"], dtype=object)
334
+ data.setflags(write=writable)
335
+ expected_codes = np.array([0, 1, -1, -1, 0, 2, -1, 1], dtype=np.intp)
336
+ expected_uniques = np.array(["a", "c", "b"], dtype=object)
337
+
338
+ codes, uniques = algos.factorize(data)
339
+ tm.assert_numpy_array_equal(codes, expected_codes)
340
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
341
+
342
+ def test_datetime64_factorize(self, writable):
343
+ # GH35650 Verify whether read-only datetime64 array can be factorized
344
+ data = np.array([np.datetime64("2020-01-01T00:00:00.000")], dtype="M8[ns]")
345
+ data.setflags(write=writable)
346
+ expected_codes = np.array([0], dtype=np.intp)
347
+ expected_uniques = np.array(
348
+ ["2020-01-01T00:00:00.000000000"], dtype="datetime64[ns]"
349
+ )
350
+
351
+ codes, uniques = pd.factorize(data)
352
+ tm.assert_numpy_array_equal(codes, expected_codes)
353
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
354
+
355
+ def test_factorize_rangeindex(self, sort):
356
+ # increasing -> sort doesn't matter
357
+ ri = pd.RangeIndex.from_range(range(10))
358
+ expected = np.arange(10, dtype=np.intp), ri
359
+
360
+ result = algos.factorize(ri, sort=sort)
361
+ tm.assert_numpy_array_equal(result[0], expected[0])
362
+ tm.assert_index_equal(result[1], expected[1], exact=True)
363
+
364
+ result = ri.factorize(sort=sort)
365
+ tm.assert_numpy_array_equal(result[0], expected[0])
366
+ tm.assert_index_equal(result[1], expected[1], exact=True)
367
+
368
+ def test_factorize_rangeindex_decreasing(self, sort):
369
+ # decreasing -> sort matters
370
+ ri = pd.RangeIndex.from_range(range(10))
371
+ expected = np.arange(10, dtype=np.intp), ri
372
+
373
+ ri2 = ri[::-1]
374
+ expected = expected[0], ri2
375
+ if sort:
376
+ expected = expected[0][::-1], expected[1][::-1]
377
+
378
+ result = algos.factorize(ri2, sort=sort)
379
+ tm.assert_numpy_array_equal(result[0], expected[0])
380
+ tm.assert_index_equal(result[1], expected[1], exact=True)
381
+
382
+ result = ri2.factorize(sort=sort)
383
+ tm.assert_numpy_array_equal(result[0], expected[0])
384
+ tm.assert_index_equal(result[1], expected[1], exact=True)
385
+
386
+ def test_deprecate_order(self):
387
+ # gh 19727 - check warning is raised for deprecated keyword, order.
388
+ # Test not valid once order keyword is removed.
389
+ data = np.array([2**63, 1, 2**63], dtype=np.uint64)
390
+ with pytest.raises(TypeError, match="got an unexpected keyword"):
391
+ algos.factorize(data, order=True)
392
+ with tm.assert_produces_warning(False):
393
+ algos.factorize(data)
394
+
395
+ @pytest.mark.parametrize(
396
+ "data",
397
+ [
398
+ np.array([0, 1, 0], dtype="u8"),
399
+ np.array([-(2**63), 1, -(2**63)], dtype="i8"),
400
+ np.array(["__nan__", "foo", "__nan__"], dtype="object"),
401
+ ],
402
+ )
403
+ def test_parametrized_factorize_na_value_default(self, data):
404
+ # arrays that include the NA default for that type, but isn't used.
405
+ codes, uniques = algos.factorize(data)
406
+ expected_uniques = data[[0, 1]]
407
+ expected_codes = np.array([0, 1, 0], dtype=np.intp)
408
+ tm.assert_numpy_array_equal(codes, expected_codes)
409
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
410
+
411
+ @pytest.mark.parametrize(
412
+ "data, na_value",
413
+ [
414
+ (np.array([0, 1, 0, 2], dtype="u8"), 0),
415
+ (np.array([1, 0, 1, 2], dtype="u8"), 1),
416
+ (np.array([-(2**63), 1, -(2**63), 0], dtype="i8"), -(2**63)),
417
+ (np.array([1, -(2**63), 1, 0], dtype="i8"), 1),
418
+ (np.array(["a", "", "a", "b"], dtype=object), "a"),
419
+ (np.array([(), ("a", 1), (), ("a", 2)], dtype=object), ()),
420
+ (np.array([("a", 1), (), ("a", 1), ("a", 2)], dtype=object), ("a", 1)),
421
+ ],
422
+ )
423
+ def test_parametrized_factorize_na_value(self, data, na_value):
424
+ codes, uniques = algos.factorize_array(data, na_value=na_value)
425
+ expected_uniques = data[[1, 3]]
426
+ expected_codes = np.array([-1, 0, -1, 1], dtype=np.intp)
427
+ tm.assert_numpy_array_equal(codes, expected_codes)
428
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
429
+
430
+ @pytest.mark.parametrize(
431
+ "data, uniques",
432
+ [
433
+ (
434
+ np.array(["b", "a", None, "b"], dtype=object),
435
+ np.array(["b", "a"], dtype=object),
436
+ ),
437
+ (
438
+ pd.array([2, 1, pd.NA, 2], dtype="Int64"),
439
+ pd.array([2, 1], dtype="Int64"),
440
+ ),
441
+ ],
442
+ ids=["numpy_array", "extension_array"],
443
+ )
444
+ def test_factorize_use_na_sentinel(self, sort, data, uniques):
445
+ codes, uniques = algos.factorize(data, sort=sort, use_na_sentinel=True)
446
+ if sort:
447
+ expected_codes = np.array([1, 0, -1, 1], dtype=np.intp)
448
+ expected_uniques = algos.safe_sort(uniques)
449
+ else:
450
+ expected_codes = np.array([0, 1, -1, 0], dtype=np.intp)
451
+ expected_uniques = uniques
452
+ tm.assert_numpy_array_equal(codes, expected_codes)
453
+ if isinstance(data, np.ndarray):
454
+ tm.assert_numpy_array_equal(uniques, expected_uniques)
455
+ else:
456
+ tm.assert_extension_array_equal(uniques, expected_uniques)
457
+
458
+ @pytest.mark.parametrize(
459
+ "data, expected_codes, expected_uniques",
460
+ [
461
+ (
462
+ ["a", None, "b", "a"],
463
+ np.array([0, 1, 2, 0], dtype=np.dtype("intp")),
464
+ np.array(["a", np.nan, "b"], dtype=object),
465
+ ),
466
+ (
467
+ ["a", np.nan, "b", "a"],
468
+ np.array([0, 1, 2, 0], dtype=np.dtype("intp")),
469
+ np.array(["a", np.nan, "b"], dtype=object),
470
+ ),
471
+ ],
472
+ )
473
+ def test_object_factorize_use_na_sentinel_false(
474
+ self, data, expected_codes, expected_uniques
475
+ ):
476
+ codes, uniques = algos.factorize(
477
+ np.array(data, dtype=object), use_na_sentinel=False
478
+ )
479
+
480
+ tm.assert_numpy_array_equal(uniques, expected_uniques, strict_nan=True)
481
+ tm.assert_numpy_array_equal(codes, expected_codes, strict_nan=True)
482
+
483
+ @pytest.mark.parametrize(
484
+ "data, expected_codes, expected_uniques",
485
+ [
486
+ (
487
+ np.array([1, None, 1, 2], dtype=object),
488
+ np.array([0, 1, 0, 2], dtype=np.dtype("intp")),
489
+ np.array([1, np.nan, 2], dtype="O"),
490
+ ),
491
+ (
492
+ np.array([1, np.nan, 1, 2], dtype=np.float64),
493
+ np.array([0, 1, 0, 2], dtype=np.dtype("intp")),
494
+ np.array([1, np.nan, 2], dtype=np.float64),
495
+ ),
496
+ ],
497
+ )
498
+ def test_int_factorize_use_na_sentinel_false(
499
+ self, data, expected_codes, expected_uniques
500
+ ):
501
+ codes, uniques = algos.factorize(data, use_na_sentinel=False)
502
+
503
+ tm.assert_numpy_array_equal(uniques, expected_uniques, strict_nan=True)
504
+ tm.assert_numpy_array_equal(codes, expected_codes, strict_nan=True)
505
+
506
+ @pytest.mark.parametrize(
507
+ "data, expected_codes, expected_uniques",
508
+ [
509
+ (
510
+ Index(Categorical(["a", "a", "b"])),
511
+ np.array([0, 0, 1], dtype=np.intp),
512
+ CategoricalIndex(["a", "b"], categories=["a", "b"], dtype="category"),
513
+ ),
514
+ (
515
+ Series(Categorical(["a", "a", "b"])),
516
+ np.array([0, 0, 1], dtype=np.intp),
517
+ CategoricalIndex(["a", "b"], categories=["a", "b"], dtype="category"),
518
+ ),
519
+ (
520
+ Series(DatetimeIndex(["2017", "2017"], tz="US/Eastern")),
521
+ np.array([0, 0], dtype=np.intp),
522
+ DatetimeIndex(["2017"], tz="US/Eastern"),
523
+ ),
524
+ ],
525
+ )
526
+ def test_factorize_mixed_values(self, data, expected_codes, expected_uniques):
527
+ # GH 19721
528
+ codes, uniques = algos.factorize(data)
529
+ tm.assert_numpy_array_equal(codes, expected_codes)
530
+ tm.assert_index_equal(uniques, expected_uniques)
531
+
532
+ def test_factorize_interval_non_nano(self, unit):
533
+ # GH#56099
534
+ left = DatetimeIndex(["2016-01-01", np.nan, "2015-10-11"]).as_unit(unit)
535
+ right = DatetimeIndex(["2016-01-02", np.nan, "2015-10-15"]).as_unit(unit)
536
+ idx = IntervalIndex.from_arrays(left, right)
537
+ codes, cats = idx.factorize()
538
+ assert cats.dtype == f"interval[datetime64[{unit}], right]"
539
+
540
+ ts = Timestamp(0).as_unit(unit)
541
+ idx2 = IntervalIndex.from_arrays(left - ts, right - ts)
542
+ codes2, cats2 = idx2.factorize()
543
+ assert cats2.dtype == f"interval[timedelta64[{unit}], right]"
544
+
545
+ idx3 = IntervalIndex.from_arrays(
546
+ left.tz_localize("US/Pacific"), right.tz_localize("US/Pacific")
547
+ )
548
+ codes3, cats3 = idx3.factorize()
549
+ assert cats3.dtype == f"interval[datetime64[{unit}, US/Pacific], right]"
550
+
551
+
552
+ class TestUnique:
553
+ def test_ints(self):
554
+ arr = np.random.default_rng(2).integers(0, 100, size=50)
555
+
556
+ result = algos.unique(arr)
557
+ assert isinstance(result, np.ndarray)
558
+
559
+ def test_objects(self):
560
+ arr = np.random.default_rng(2).integers(0, 100, size=50).astype("O")
561
+
562
+ result = algos.unique(arr)
563
+ assert isinstance(result, np.ndarray)
564
+
565
+ def test_object_refcount_bug(self):
566
+ lst = np.array(["A", "B", "C", "D", "E"], dtype=object)
567
+ for i in range(1000):
568
+ len(algos.unique(lst))
569
+
570
+ def test_index_returned(self, index):
571
+ # GH#57043
572
+ index = index.repeat(2)
573
+ result = algos.unique(index)
574
+
575
+ # dict.fromkeys preserves the order
576
+ unique_values = list(dict.fromkeys(index.values))
577
+ if isinstance(index, MultiIndex):
578
+ expected = MultiIndex.from_tuples(unique_values, names=index.names)
579
+ else:
580
+ expected = Index(unique_values, dtype=index.dtype)
581
+ if isinstance(index.dtype, DatetimeTZDtype):
582
+ expected = expected.normalize()
583
+ tm.assert_index_equal(result, expected, exact=True)
584
+
585
+ def test_factorize_multiindex_empty(self):
586
+ # GH#57517
587
+ mi = MultiIndex.from_product(
588
+ [Index([], name="a", dtype=object), Index([], name="i", dtype="f4")]
589
+ )
590
+ codes, uniques = mi.factorize()
591
+ exp_codes = np.array([], dtype=np.intp)
592
+ tm.assert_numpy_array_equal(codes, exp_codes)
593
+ tm.assert_index_equal(uniques, mi[:0])
594
+
595
+ def test_dtype_preservation(self, any_numpy_dtype):
596
+ # GH 15442
597
+ if any_numpy_dtype in (tm.BYTES_DTYPES + tm.STRING_DTYPES):
598
+ data = [1, 2, 2]
599
+ uniques = [1, 2]
600
+ elif is_integer_dtype(any_numpy_dtype):
601
+ data = [1, 2, 2]
602
+ uniques = [1, 2]
603
+ elif is_float_dtype(any_numpy_dtype):
604
+ data = [1, 2, 2]
605
+ uniques = [1.0, 2.0]
606
+ elif is_complex_dtype(any_numpy_dtype):
607
+ data = [complex(1, 0), complex(2, 0), complex(2, 0)]
608
+ uniques = [complex(1, 0), complex(2, 0)]
609
+ elif is_bool_dtype(any_numpy_dtype):
610
+ data = [True, True, False]
611
+ uniques = [True, False]
612
+ elif is_object_dtype(any_numpy_dtype):
613
+ data = ["A", "B", "B"]
614
+ uniques = ["A", "B"]
615
+ else:
616
+ # datetime64[ns]/M8[ns]/timedelta64[ns]/m8[ns] tested elsewhere
617
+ data = [1, 2, 2]
618
+ uniques = [1, 2]
619
+
620
+ result = Series(data, dtype=any_numpy_dtype).unique()
621
+ expected = np.array(uniques, dtype=any_numpy_dtype)
622
+
623
+ if any_numpy_dtype in tm.STRING_DTYPES:
624
+ expected = expected.astype(object)
625
+
626
+ if expected.dtype.kind in ["m", "M"]:
627
+ # We get TimedeltaArray/DatetimeArray
628
+ assert isinstance(result, (DatetimeArray, TimedeltaArray))
629
+ result = np.array(result)
630
+ tm.assert_numpy_array_equal(result, expected)
631
+
632
+ def test_datetime64_dtype_array_returned(self):
633
+ # GH 9431
634
+ dt_arr = np.array(
635
+ [
636
+ "2015-01-03T00:00:00.000000000",
637
+ "2015-01-01T00:00:00.000000000",
638
+ ],
639
+ dtype="M8[ns]",
640
+ )
641
+
642
+ dt_index = to_datetime(
643
+ [
644
+ "2015-01-03T00:00:00.000000000",
645
+ "2015-01-01T00:00:00.000000000",
646
+ "2015-01-01T00:00:00.000000000",
647
+ ]
648
+ )
649
+ result = algos.unique(dt_index)
650
+ expected = to_datetime(dt_arr)
651
+ tm.assert_index_equal(result, expected, exact=True)
652
+
653
+ s = Series(dt_index)
654
+ result = algos.unique(s)
655
+ tm.assert_numpy_array_equal(result, dt_arr)
656
+ assert result.dtype == dt_arr.dtype
657
+
658
+ arr = s.values
659
+ result = algos.unique(arr)
660
+ tm.assert_numpy_array_equal(result, dt_arr)
661
+ assert result.dtype == dt_arr.dtype
662
+
663
+ def test_datetime_non_ns(self):
664
+ a = np.array(["2000", "2000", "2001"], dtype="datetime64[s]")
665
+ result = pd.unique(a)
666
+ expected = np.array(["2000", "2001"], dtype="datetime64[s]")
667
+ tm.assert_numpy_array_equal(result, expected)
668
+
669
+ def test_timedelta_non_ns(self):
670
+ a = np.array(["2000", "2000", "2001"], dtype="timedelta64[s]")
671
+ result = pd.unique(a)
672
+ expected = np.array([2000, 2001], dtype="timedelta64[s]")
673
+ tm.assert_numpy_array_equal(result, expected)
674
+
675
+ def test_timedelta64_dtype_array_returned(self):
676
+ # GH 9431
677
+ td_arr = np.array([31200, 45678, 10000], dtype="m8[ns]")
678
+
679
+ td_index = to_timedelta([31200, 45678, 31200, 10000, 45678])
680
+ result = algos.unique(td_index)
681
+ expected = to_timedelta(td_arr)
682
+ tm.assert_index_equal(result, expected)
683
+ assert result.dtype == expected.dtype
684
+
685
+ s = Series(td_index)
686
+ result = algos.unique(s)
687
+ tm.assert_numpy_array_equal(result, td_arr)
688
+ assert result.dtype == td_arr.dtype
689
+
690
+ arr = s.values
691
+ result = algos.unique(arr)
692
+ tm.assert_numpy_array_equal(result, td_arr)
693
+ assert result.dtype == td_arr.dtype
694
+
695
+ def test_uint64_overflow(self):
696
+ s = Series([1, 2, 2**63, 2**63], dtype=np.uint64)
697
+ exp = np.array([1, 2, 2**63], dtype=np.uint64)
698
+ tm.assert_numpy_array_equal(algos.unique(s), exp)
699
+
700
+ def test_nan_in_object_array(self):
701
+ duplicated_items = ["a", np.nan, "c", "c"]
702
+ result = pd.unique(np.array(duplicated_items, dtype=object))
703
+ expected = np.array(["a", np.nan, "c"], dtype=object)
704
+ tm.assert_numpy_array_equal(result, expected)
705
+
706
+ def test_categorical(self):
707
+ # we are expecting to return in the order
708
+ # of appearance
709
+ expected = Categorical(list("bac"))
710
+
711
+ # we are expecting to return in the order
712
+ # of the categories
713
+ expected_o = Categorical(list("bac"), categories=list("abc"), ordered=True)
714
+
715
+ # GH 15939
716
+ c = Categorical(list("baabc"))
717
+ result = c.unique()
718
+ tm.assert_categorical_equal(result, expected)
719
+
720
+ result = algos.unique(c)
721
+ tm.assert_categorical_equal(result, expected)
722
+
723
+ c = Categorical(list("baabc"), ordered=True)
724
+ result = c.unique()
725
+ tm.assert_categorical_equal(result, expected_o)
726
+
727
+ result = algos.unique(c)
728
+ tm.assert_categorical_equal(result, expected_o)
729
+
730
+ # Series of categorical dtype
731
+ s = Series(Categorical(list("baabc")), name="foo")
732
+ result = s.unique()
733
+ tm.assert_categorical_equal(result, expected)
734
+
735
+ result = pd.unique(s)
736
+ tm.assert_categorical_equal(result, expected)
737
+
738
+ # CI -> return CI
739
+ ci = CategoricalIndex(Categorical(list("baabc"), categories=list("abc")))
740
+ expected = CategoricalIndex(expected)
741
+ result = ci.unique()
742
+ tm.assert_index_equal(result, expected)
743
+
744
+ result = pd.unique(ci)
745
+ tm.assert_index_equal(result, expected)
746
+
747
+ def test_datetime64tz_aware(self, unit):
748
+ # GH 15939
749
+
750
+ dti = Index(
751
+ [
752
+ Timestamp("20160101", tz="US/Eastern"),
753
+ Timestamp("20160101", tz="US/Eastern"),
754
+ ]
755
+ ).as_unit(unit)
756
+ ser = Series(dti)
757
+
758
+ result = ser.unique()
759
+ expected = dti[:1]._data
760
+ tm.assert_extension_array_equal(result, expected)
761
+
762
+ result = dti.unique()
763
+ expected = dti[:1]
764
+ tm.assert_index_equal(result, expected)
765
+
766
+ result = pd.unique(ser)
767
+ expected = dti[:1]._data
768
+ tm.assert_extension_array_equal(result, expected)
769
+
770
+ result = pd.unique(dti)
771
+ expected = dti[:1]
772
+ tm.assert_index_equal(result, expected)
773
+
774
+ def test_order_of_appearance(self):
775
+ # 9346
776
+ # light testing of guarantee of order of appearance
777
+ # these also are the doc-examples
778
+ result = pd.unique(Series([2, 1, 3, 3]))
779
+ tm.assert_numpy_array_equal(result, np.array([2, 1, 3], dtype="int64"))
780
+
781
+ result = pd.unique(Series([2] + [1] * 5))
782
+ tm.assert_numpy_array_equal(result, np.array([2, 1], dtype="int64"))
783
+
784
+ data = np.array(["a", "a", "b", "c"], dtype=object)
785
+ result = pd.unique(data)
786
+ expected = np.array(["a", "b", "c"], dtype=object)
787
+ tm.assert_numpy_array_equal(result, expected)
788
+
789
+ result = pd.unique(Series(Categorical(list("aabc"))))
790
+ expected = Categorical(list("abc"))
791
+ tm.assert_categorical_equal(result, expected)
792
+
793
+ def test_order_of_appearance_dt64(self, unit):
794
+ ser = Series([Timestamp("20160101"), Timestamp("20160101")]).dt.as_unit(unit)
795
+ result = pd.unique(ser)
796
+ expected = np.array(["2016-01-01T00:00:00.000000000"], dtype=f"M8[{unit}]")
797
+ tm.assert_numpy_array_equal(result, expected)
798
+
799
+ def test_order_of_appearance_dt64tz(self, unit):
800
+ dti = DatetimeIndex(
801
+ [
802
+ Timestamp("20160101", tz="US/Eastern"),
803
+ Timestamp("20160101", tz="US/Eastern"),
804
+ ]
805
+ ).as_unit(unit)
806
+ result = pd.unique(dti)
807
+ expected = DatetimeIndex(
808
+ ["2016-01-01 00:00:00"], dtype=f"datetime64[{unit}, US/Eastern]", freq=None
809
+ )
810
+ tm.assert_index_equal(result, expected)
811
+
812
+ @pytest.mark.parametrize(
813
+ "arg ,expected",
814
+ [
815
+ (("1", "1", "2"), np.array(["1", "2"], dtype=object)),
816
+ (("foo",), np.array(["foo"], dtype=object)),
817
+ ],
818
+ )
819
+ def test_tuple_with_strings(self, arg, expected):
820
+ # see GH 17108
821
+ arg = com.asarray_tuplesafe(arg, dtype=object)
822
+ result = pd.unique(arg)
823
+ tm.assert_numpy_array_equal(result, expected)
824
+
825
+ def test_obj_none_preservation(self):
826
+ # GH 20866
827
+ arr = np.array(["foo", None], dtype=object)
828
+ result = pd.unique(arr)
829
+ expected = np.array(["foo", None], dtype=object)
830
+
831
+ tm.assert_numpy_array_equal(result, expected, strict_nan=True)
832
+
833
+ def test_signed_zero(self):
834
+ # GH 21866
835
+ a = np.array([-0.0, 0.0])
836
+ result = pd.unique(a)
837
+ expected = np.array([-0.0]) # 0.0 and -0.0 are equivalent
838
+ tm.assert_numpy_array_equal(result, expected)
839
+
840
+ def test_different_nans(self):
841
+ # GH 21866
842
+ # create different nans from bit-patterns:
843
+ NAN1 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000000))[0]
844
+ NAN2 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000001))[0]
845
+ assert NAN1 != NAN1
846
+ assert NAN2 != NAN2
847
+ a = np.array([NAN1, NAN2]) # NAN1 and NAN2 are equivalent
848
+ result = pd.unique(a)
849
+ expected = np.array([np.nan])
850
+ tm.assert_numpy_array_equal(result, expected)
851
+
852
+ @pytest.mark.parametrize("el_type", [np.float64, object])
853
+ def test_first_nan_kept(self, el_type):
854
+ # GH 22295
855
+ # create different nans from bit-patterns:
856
+ bits_for_nan1 = 0xFFF8000000000001
857
+ bits_for_nan2 = 0x7FF8000000000001
858
+ NAN1 = struct.unpack("d", struct.pack("=Q", bits_for_nan1))[0]
859
+ NAN2 = struct.unpack("d", struct.pack("=Q", bits_for_nan2))[0]
860
+ assert NAN1 != NAN1
861
+ assert NAN2 != NAN2
862
+ a = np.array([NAN1, NAN2], dtype=el_type)
863
+ result = pd.unique(a)
864
+ assert result.size == 1
865
+ # use bit patterns to identify which nan was kept:
866
+ result_nan_bits = struct.unpack("=Q", struct.pack("d", result[0]))[0]
867
+ assert result_nan_bits == bits_for_nan1
868
+
869
+ def test_do_not_mangle_na_values(self, unique_nulls_fixture, unique_nulls_fixture2):
870
+ # GH 22295
871
+ if unique_nulls_fixture is unique_nulls_fixture2:
872
+ return # skip it, values not unique
873
+ a = np.array([unique_nulls_fixture, unique_nulls_fixture2], dtype=object)
874
+ result = pd.unique(a)
875
+ assert result.size == 2
876
+ assert a[0] is unique_nulls_fixture
877
+ assert a[1] is unique_nulls_fixture2
878
+
879
+ def test_unique_masked(self, any_numeric_ea_dtype):
880
+ # GH#48019
881
+ ser = Series([1, pd.NA, 2] * 3, dtype=any_numeric_ea_dtype)
882
+ result = pd.unique(ser)
883
+ expected = pd.array([1, pd.NA, 2], dtype=any_numeric_ea_dtype)
884
+ tm.assert_extension_array_equal(result, expected)
885
+
886
+ def test_unique_NumpyExtensionArray(self):
887
+ arr_complex = pd.array(
888
+ [1 + 1j, 2, 3]
889
+ ) # NumpyEADtype('complex128') => NumpyExtensionArray
890
+ result = pd.unique(arr_complex)
891
+ expected = pd.array([1 + 1j, 2 + 0j, 3 + 0j])
892
+ tm.assert_extension_array_equal(result, expected)
893
+
894
+
895
+ def test_nunique_ints(index_or_series_or_array):
896
+ # GH#36327
897
+ values = index_or_series_or_array(np.random.default_rng(2).integers(0, 20, 30))
898
+ result = algos.nunique_ints(values)
899
+ expected = len(algos.unique(values))
900
+ assert result == expected
901
+
902
+
903
+ class TestIsin:
904
+ def test_invalid(self):
905
+ msg = (
906
+ r"only list-like objects are allowed to be passed to isin\(\), "
907
+ r"you passed a `int`"
908
+ )
909
+ with pytest.raises(TypeError, match=msg):
910
+ algos.isin(1, 1)
911
+ with pytest.raises(TypeError, match=msg):
912
+ algos.isin(1, [1])
913
+ with pytest.raises(TypeError, match=msg):
914
+ algos.isin([1], 1)
915
+
916
+ def test_basic(self):
917
+ result = algos.isin(np.array([1, 2]), [1])
918
+ expected = np.array([True, False])
919
+ tm.assert_numpy_array_equal(result, expected)
920
+
921
+ result = algos.isin(Series([1, 2]), [1])
922
+ expected = np.array([True, False])
923
+ tm.assert_numpy_array_equal(result, expected)
924
+
925
+ result = algos.isin(Series([1, 2]), Series([1]))
926
+ expected = np.array([True, False])
927
+ tm.assert_numpy_array_equal(result, expected)
928
+
929
+ result = algos.isin(Series([1, 2]), {1})
930
+ expected = np.array([True, False])
931
+ tm.assert_numpy_array_equal(result, expected)
932
+
933
+ arg = np.array(["a", "b"], dtype=object)
934
+ result = algos.isin(arg, ["a"])
935
+ expected = np.array([True, False])
936
+ tm.assert_numpy_array_equal(result, expected)
937
+
938
+ result = algos.isin(Series(arg), Series(["a"]))
939
+ expected = np.array([True, False])
940
+ tm.assert_numpy_array_equal(result, expected)
941
+
942
+ result = algos.isin(Series(arg), {"a"})
943
+ expected = np.array([True, False])
944
+ tm.assert_numpy_array_equal(result, expected)
945
+
946
+ result = algos.isin(arg, [1])
947
+ expected = np.array([False, False])
948
+ tm.assert_numpy_array_equal(result, expected)
949
+
950
+ def test_i8(self):
951
+ arr = date_range("20130101", periods=3).values
952
+ result = algos.isin(arr, [arr[0]])
953
+ expected = np.array([True, False, False])
954
+ tm.assert_numpy_array_equal(result, expected)
955
+
956
+ result = algos.isin(arr, arr[0:2])
957
+ expected = np.array([True, True, False])
958
+ tm.assert_numpy_array_equal(result, expected)
959
+
960
+ result = algos.isin(arr, set(arr[0:2]))
961
+ expected = np.array([True, True, False])
962
+ tm.assert_numpy_array_equal(result, expected)
963
+
964
+ arr = timedelta_range("1 day", periods=3).values
965
+ result = algos.isin(arr, [arr[0]])
966
+ expected = np.array([True, False, False])
967
+ tm.assert_numpy_array_equal(result, expected)
968
+
969
+ result = algos.isin(arr, arr[0:2])
970
+ expected = np.array([True, True, False])
971
+ tm.assert_numpy_array_equal(result, expected)
972
+
973
+ result = algos.isin(arr, set(arr[0:2]))
974
+ expected = np.array([True, True, False])
975
+ tm.assert_numpy_array_equal(result, expected)
976
+
977
+ @pytest.mark.parametrize("dtype1", ["m8[ns]", "M8[ns]", "M8[ns, UTC]", "period[D]"])
978
+ @pytest.mark.parametrize("dtype", ["i8", "f8", "u8"])
979
+ def test_isin_datetimelike_values_numeric_comps(self, dtype, dtype1):
980
+ # Anything but object and we get all-False shortcut
981
+
982
+ dta = date_range("2013-01-01", periods=3)._values
983
+ arr = Series(dta.view("i8")).array.view(dtype1)
984
+
985
+ comps = arr.view("i8").astype(dtype)
986
+
987
+ result = algos.isin(comps, arr)
988
+ expected = np.zeros(comps.shape, dtype=bool)
989
+ tm.assert_numpy_array_equal(result, expected)
990
+
991
+ def test_large(self):
992
+ s = date_range("20000101", periods=2000000, freq="s").values
993
+ result = algos.isin(s, s[0:2])
994
+ expected = np.zeros(len(s), dtype=bool)
995
+ expected[0] = True
996
+ expected[1] = True
997
+ tm.assert_numpy_array_equal(result, expected)
998
+
999
+ @pytest.mark.parametrize("dtype", ["m8[ns]", "M8[ns]", "M8[ns, UTC]", "period[D]"])
1000
+ def test_isin_datetimelike_all_nat(self, dtype):
1001
+ # GH#56427
1002
+ dta = date_range("2013-01-01", periods=3)._values
1003
+ arr = Series(dta.view("i8")).array.view(dtype)
1004
+
1005
+ arr[0] = NaT
1006
+ result = algos.isin(arr, [NaT])
1007
+ expected = np.array([True, False, False], dtype=bool)
1008
+ tm.assert_numpy_array_equal(result, expected)
1009
+
1010
+ @pytest.mark.parametrize("dtype", ["m8[ns]", "M8[ns]", "M8[ns, UTC]"])
1011
+ def test_isin_datetimelike_strings_returns_false(self, dtype):
1012
+ # GH#53111
1013
+ dta = date_range("2013-01-01", periods=3)._values
1014
+ arr = Series(dta.view("i8")).array.view(dtype)
1015
+
1016
+ vals = [str(x) for x in arr]
1017
+ res = algos.isin(arr, vals)
1018
+ assert not res.any()
1019
+
1020
+ vals2 = np.array(vals, dtype=str)
1021
+ res2 = algos.isin(arr, vals2)
1022
+ assert not res2.any()
1023
+
1024
+ def test_isin_dt64tz_with_nat(self):
1025
+ # the all-NaT values used to get inferred to tznaive, which was evaluated
1026
+ # as non-matching GH#56427
1027
+ dti = date_range("2016-01-01", periods=3, tz="UTC")
1028
+ ser = Series(dti)
1029
+ ser[0] = NaT
1030
+
1031
+ res = algos.isin(ser._values, [NaT])
1032
+ exp = np.array([True, False, False], dtype=bool)
1033
+ tm.assert_numpy_array_equal(res, exp)
1034
+
1035
+ def test_categorical_from_codes(self):
1036
+ # GH 16639
1037
+ vals = np.array([0, 1, 2, 0])
1038
+ cats = ["a", "b", "c"]
1039
+ Sd = Series(Categorical([1]).from_codes(vals, cats))
1040
+ St = Series(Categorical([1]).from_codes(np.array([0, 1]), cats))
1041
+ expected = np.array([True, True, False, True])
1042
+ result = algos.isin(Sd, St)
1043
+ tm.assert_numpy_array_equal(expected, result)
1044
+
1045
+ def test_categorical_isin(self):
1046
+ vals = np.array([0, 1, 2, 0])
1047
+ cats = ["a", "b", "c"]
1048
+ cat = Categorical([1]).from_codes(vals, cats)
1049
+ other = Categorical([1]).from_codes(np.array([0, 1]), cats)
1050
+
1051
+ expected = np.array([True, True, False, True])
1052
+ result = algos.isin(cat, other)
1053
+ tm.assert_numpy_array_equal(expected, result)
1054
+
1055
+ def test_same_nan_is_in(self):
1056
+ # GH 22160
1057
+ # nan is special, because from " a is b" doesn't follow "a == b"
1058
+ # at least, isin() should follow python's "np.nan in [nan] == True"
1059
+ # casting to -> np.float64 -> another float-object somewhere on
1060
+ # the way could lead jeopardize this behavior
1061
+ comps = np.array([np.nan], dtype=object) # could be casted to float64
1062
+ values = [np.nan]
1063
+ expected = np.array([True])
1064
+ result = algos.isin(comps, values)
1065
+ tm.assert_numpy_array_equal(expected, result)
1066
+
1067
+ def test_same_nan_is_in_large(self):
1068
+ # https://github.com/pandas-dev/pandas/issues/22205
1069
+ s = np.tile(1.0, 1_000_001)
1070
+ s[0] = np.nan
1071
+ result = algos.isin(s, np.array([np.nan, 1]))
1072
+ expected = np.ones(len(s), dtype=bool)
1073
+ tm.assert_numpy_array_equal(result, expected)
1074
+
1075
+ def test_same_nan_is_in_large_series(self):
1076
+ # https://github.com/pandas-dev/pandas/issues/22205
1077
+ s = np.tile(1.0, 1_000_001)
1078
+ series = Series(s)
1079
+ s[0] = np.nan
1080
+ result = series.isin(np.array([np.nan, 1]))
1081
+ expected = Series(np.ones(len(s), dtype=bool))
1082
+ tm.assert_series_equal(result, expected)
1083
+
1084
+ def test_same_object_is_in(self):
1085
+ # GH 22160
1086
+ # there could be special treatment for nans
1087
+ # the user however could define a custom class
1088
+ # with similar behavior, then we at least should
1089
+ # fall back to usual python's behavior: "a in [a] == True"
1090
+ class LikeNan:
1091
+ def __eq__(self, other) -> bool:
1092
+ return False
1093
+
1094
+ def __hash__(self):
1095
+ return 0
1096
+
1097
+ a, b = LikeNan(), LikeNan()
1098
+
1099
+ arg = np.array([a], dtype=object)
1100
+
1101
+ # same object -> True
1102
+ tm.assert_numpy_array_equal(algos.isin(arg, [a]), np.array([True]))
1103
+ # different objects -> False
1104
+ tm.assert_numpy_array_equal(algos.isin(arg, [b]), np.array([False]))
1105
+
1106
+ def test_different_nans(self):
1107
+ # GH 22160
1108
+ # all nans are handled as equivalent
1109
+
1110
+ comps = [float("nan")]
1111
+ values = [float("nan")]
1112
+ assert comps[0] is not values[0] # different nan-objects
1113
+
1114
+ # as list of python-objects:
1115
+ result = algos.isin(np.array(comps), values)
1116
+ tm.assert_numpy_array_equal(np.array([True]), result)
1117
+
1118
+ # as object-array:
1119
+ result = algos.isin(
1120
+ np.asarray(comps, dtype=object), np.asarray(values, dtype=object)
1121
+ )
1122
+ tm.assert_numpy_array_equal(np.array([True]), result)
1123
+
1124
+ # as float64-array:
1125
+ result = algos.isin(
1126
+ np.asarray(comps, dtype=np.float64), np.asarray(values, dtype=np.float64)
1127
+ )
1128
+ tm.assert_numpy_array_equal(np.array([True]), result)
1129
+
1130
+ def test_no_cast(self):
1131
+ # GH 22160
1132
+ # ensure 42 is not casted to a string
1133
+ comps = np.array(["ss", 42], dtype=object)
1134
+ values = ["42"]
1135
+ expected = np.array([False, False])
1136
+
1137
+ result = algos.isin(comps, values)
1138
+ tm.assert_numpy_array_equal(expected, result)
1139
+
1140
+ @pytest.mark.parametrize("empty", [[], Series(dtype=object), np.array([])])
1141
+ def test_empty(self, empty):
1142
+ # see gh-16991
1143
+ vals = Index(["a", "b"])
1144
+ expected = np.array([False, False])
1145
+
1146
+ result = algos.isin(vals, empty)
1147
+ tm.assert_numpy_array_equal(expected, result)
1148
+
1149
+ def test_different_nan_objects(self):
1150
+ # GH 22119
1151
+ comps = np.array(["nan", np.nan * 1j, float("nan")], dtype=object)
1152
+ vals = np.array([float("nan")], dtype=object)
1153
+ expected = np.array([False, False, True])
1154
+ result = algos.isin(comps, vals)
1155
+ tm.assert_numpy_array_equal(expected, result)
1156
+
1157
+ def test_different_nans_as_float64(self):
1158
+ # GH 21866
1159
+ # create different nans from bit-patterns,
1160
+ # these nans will land in different buckets in the hash-table
1161
+ # if no special care is taken
1162
+ NAN1 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000000))[0]
1163
+ NAN2 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000001))[0]
1164
+ assert NAN1 != NAN1
1165
+ assert NAN2 != NAN2
1166
+
1167
+ # check that NAN1 and NAN2 are equivalent:
1168
+ arr = np.array([NAN1, NAN2], dtype=np.float64)
1169
+ lookup1 = np.array([NAN1], dtype=np.float64)
1170
+ result = algos.isin(arr, lookup1)
1171
+ expected = np.array([True, True])
1172
+ tm.assert_numpy_array_equal(result, expected)
1173
+
1174
+ lookup2 = np.array([NAN2], dtype=np.float64)
1175
+ result = algos.isin(arr, lookup2)
1176
+ expected = np.array([True, True])
1177
+ tm.assert_numpy_array_equal(result, expected)
1178
+
1179
+ def test_isin_int_df_string_search(self):
1180
+ """Comparing df with int`s (1,2) with a string at isin() ("1")
1181
+ -> should not match values because int 1 is not equal str 1"""
1182
+ df = DataFrame({"values": [1, 2]})
1183
+ result = df.isin(["1"])
1184
+ expected_false = DataFrame({"values": [False, False]})
1185
+ tm.assert_frame_equal(result, expected_false)
1186
+
1187
+ def test_isin_nan_df_string_search(self):
1188
+ """Comparing df with nan value (np.nan,2) with a string at isin() ("NaN")
1189
+ -> should not match values because np.nan is not equal str NaN"""
1190
+ df = DataFrame({"values": [np.nan, 2]})
1191
+ result = df.isin(np.array(["NaN"], dtype=object))
1192
+ expected_false = DataFrame({"values": [False, False]})
1193
+ tm.assert_frame_equal(result, expected_false)
1194
+
1195
+ def test_isin_float_df_string_search(self):
1196
+ """Comparing df with floats (1.4245,2.32441) with a string at isin() ("1.4245")
1197
+ -> should not match values because float 1.4245 is not equal str 1.4245"""
1198
+ df = DataFrame({"values": [1.4245, 2.32441]})
1199
+ result = df.isin(np.array(["1.4245"], dtype=object))
1200
+ expected_false = DataFrame({"values": [False, False]})
1201
+ tm.assert_frame_equal(result, expected_false)
1202
+
1203
+ def test_isin_unsigned_dtype(self):
1204
+ # GH#46485
1205
+ ser = Series([1378774140726870442], dtype=np.uint64)
1206
+ result = ser.isin([1378774140726870528])
1207
+ expected = Series(False)
1208
+ tm.assert_series_equal(result, expected)
1209
+
1210
+
1211
+ class TestValueCounts:
1212
+ def test_value_counts(self):
1213
+ arr = np.random.default_rng(1234).standard_normal(4)
1214
+ factor = cut(arr, 4)
1215
+
1216
+ # assert isinstance(factor, n)
1217
+ result = algos.value_counts_internal(factor)
1218
+ breaks = [-1.606, -1.018, -0.431, 0.155, 0.741]
1219
+ index = IntervalIndex.from_breaks(breaks).astype(CategoricalDtype(ordered=True))
1220
+ expected = Series([1, 0, 2, 1], index=index, name="count")
1221
+ tm.assert_series_equal(result.sort_index(), expected.sort_index())
1222
+
1223
+ def test_value_counts_bins(self):
1224
+ s = [1, 2, 3, 4]
1225
+ result = algos.value_counts_internal(s, bins=1)
1226
+ expected = Series(
1227
+ [4], index=IntervalIndex.from_tuples([(0.996, 4.0)]), name="count"
1228
+ )
1229
+ tm.assert_series_equal(result, expected)
1230
+
1231
+ result = algos.value_counts_internal(s, bins=2, sort=False)
1232
+ expected = Series(
1233
+ [2, 2],
1234
+ index=IntervalIndex.from_tuples([(0.996, 2.5), (2.5, 4.0)]),
1235
+ name="count",
1236
+ )
1237
+ tm.assert_series_equal(result, expected)
1238
+
1239
+ def test_value_counts_dtypes(self):
1240
+ result = algos.value_counts_internal(np.array([1, 1.0]))
1241
+ assert len(result) == 1
1242
+
1243
+ result = algos.value_counts_internal(np.array([1, 1.0]), bins=1)
1244
+ assert len(result) == 1
1245
+
1246
+ result = algos.value_counts_internal(Series([1, 1.0, "1"])) # object
1247
+ assert len(result) == 2
1248
+
1249
+ msg = "bins argument only works with numeric data"
1250
+ with pytest.raises(TypeError, match=msg):
1251
+ algos.value_counts_internal(np.array(["1", 1], dtype=object), bins=1)
1252
+
1253
+ def test_value_counts_nat(self):
1254
+ td = Series([np.timedelta64(10000, "ns"), NaT], dtype="timedelta64[ns]")
1255
+ dt = to_datetime(["NaT", "2014-01-01"])
1256
+
1257
+ for ser in [td, dt]:
1258
+ vc = algos.value_counts_internal(ser)
1259
+ vc_with_na = algos.value_counts_internal(ser, dropna=False)
1260
+ assert len(vc) == 1
1261
+ assert len(vc_with_na) == 2
1262
+
1263
+ exp_dt = Series({Timestamp("2014-01-01 00:00:00"): 1}, name="count")
1264
+ result_dt = algos.value_counts_internal(dt)
1265
+ tm.assert_series_equal(result_dt, exp_dt)
1266
+
1267
+ exp_td = Series([1], index=[np.timedelta64(10000, "ns")], name="count")
1268
+ result_td = algos.value_counts_internal(td)
1269
+ tm.assert_series_equal(result_td, exp_td)
1270
+
1271
+ @pytest.mark.parametrize("dtype", [object, "M8[us]"])
1272
+ def test_value_counts_datetime_outofbounds(self, dtype):
1273
+ # GH 13663
1274
+ ser = Series(
1275
+ [
1276
+ datetime(3000, 1, 1),
1277
+ datetime(5000, 1, 1),
1278
+ datetime(5000, 1, 1),
1279
+ datetime(6000, 1, 1),
1280
+ datetime(3000, 1, 1),
1281
+ datetime(3000, 1, 1),
1282
+ ],
1283
+ dtype=dtype,
1284
+ )
1285
+
1286
+ res = ser.value_counts()
1287
+
1288
+ exp_index = Index(
1289
+ [datetime(3000, 1, 1), datetime(5000, 1, 1), datetime(6000, 1, 1)],
1290
+ dtype=dtype,
1291
+ )
1292
+ exp = Series([3, 2, 1], index=exp_index, name="count")
1293
+ tm.assert_series_equal(res, exp)
1294
+
1295
+ def test_categorical(self):
1296
+ s = Series(Categorical(list("aaabbc")))
1297
+ result = s.value_counts()
1298
+ expected = Series(
1299
+ [3, 2, 1], index=CategoricalIndex(["a", "b", "c"]), name="count"
1300
+ )
1301
+
1302
+ tm.assert_series_equal(result, expected, check_index_type=True)
1303
+
1304
+ # preserve order?
1305
+ s = s.cat.as_ordered()
1306
+ result = s.value_counts()
1307
+ expected.index = expected.index.as_ordered()
1308
+ tm.assert_series_equal(result, expected, check_index_type=True)
1309
+
1310
+ def test_categorical_nans(self):
1311
+ s = Series(Categorical(list("aaaaabbbcc"))) # 4,3,2,1 (nan)
1312
+ s.iloc[1] = np.nan
1313
+ result = s.value_counts()
1314
+ expected = Series(
1315
+ [4, 3, 2],
1316
+ index=CategoricalIndex(["a", "b", "c"], categories=["a", "b", "c"]),
1317
+ name="count",
1318
+ )
1319
+ tm.assert_series_equal(result, expected, check_index_type=True)
1320
+ result = s.value_counts(dropna=False)
1321
+ expected = Series(
1322
+ [4, 3, 2, 1], index=CategoricalIndex(["a", "b", "c", np.nan]), name="count"
1323
+ )
1324
+ tm.assert_series_equal(result, expected, check_index_type=True)
1325
+
1326
+ # out of order
1327
+ s = Series(
1328
+ Categorical(list("aaaaabbbcc"), ordered=True, categories=["b", "a", "c"])
1329
+ )
1330
+ s.iloc[1] = np.nan
1331
+ result = s.value_counts()
1332
+ expected = Series(
1333
+ [4, 3, 2],
1334
+ index=CategoricalIndex(
1335
+ ["a", "b", "c"],
1336
+ categories=["b", "a", "c"],
1337
+ ordered=True,
1338
+ ),
1339
+ name="count",
1340
+ )
1341
+ tm.assert_series_equal(result, expected, check_index_type=True)
1342
+
1343
+ result = s.value_counts(dropna=False)
1344
+ expected = Series(
1345
+ [4, 3, 2, 1],
1346
+ index=CategoricalIndex(
1347
+ ["a", "b", "c", np.nan], categories=["b", "a", "c"], ordered=True
1348
+ ),
1349
+ name="count",
1350
+ )
1351
+ tm.assert_series_equal(result, expected, check_index_type=True)
1352
+
1353
+ def test_categorical_zeroes(self):
1354
+ # keep the `d` category with 0
1355
+ s = Series(Categorical(list("bbbaac"), categories=list("abcd"), ordered=True))
1356
+ result = s.value_counts()
1357
+ expected = Series(
1358
+ [3, 2, 1, 0],
1359
+ index=Categorical(
1360
+ ["b", "a", "c", "d"], categories=list("abcd"), ordered=True
1361
+ ),
1362
+ name="count",
1363
+ )
1364
+ tm.assert_series_equal(result, expected, check_index_type=True)
1365
+
1366
+ def test_value_counts_dropna(self):
1367
+ # https://github.com/pandas-dev/pandas/issues/9443#issuecomment-73719328
1368
+
1369
+ tm.assert_series_equal(
1370
+ Series([True, True, False]).value_counts(dropna=True),
1371
+ Series([2, 1], index=[True, False], name="count"),
1372
+ )
1373
+ tm.assert_series_equal(
1374
+ Series([True, True, False]).value_counts(dropna=False),
1375
+ Series([2, 1], index=[True, False], name="count"),
1376
+ )
1377
+
1378
+ tm.assert_series_equal(
1379
+ Series([True] * 3 + [False] * 2 + [None] * 5).value_counts(dropna=True),
1380
+ Series([3, 2], index=Index([True, False], dtype=object), name="count"),
1381
+ )
1382
+ tm.assert_series_equal(
1383
+ Series([True] * 5 + [False] * 3 + [None] * 2).value_counts(dropna=False),
1384
+ Series([5, 3, 2], index=[True, False, None], name="count"),
1385
+ )
1386
+ tm.assert_series_equal(
1387
+ Series([10.3, 5.0, 5.0]).value_counts(dropna=True),
1388
+ Series([2, 1], index=[5.0, 10.3], name="count"),
1389
+ )
1390
+ tm.assert_series_equal(
1391
+ Series([10.3, 5.0, 5.0]).value_counts(dropna=False),
1392
+ Series([2, 1], index=[5.0, 10.3], name="count"),
1393
+ )
1394
+
1395
+ tm.assert_series_equal(
1396
+ Series([10.3, 5.0, 5.0, None]).value_counts(dropna=True),
1397
+ Series([2, 1], index=[5.0, 10.3], name="count"),
1398
+ )
1399
+
1400
+ result = Series([10.3, 10.3, 5.0, 5.0, 5.0, None]).value_counts(dropna=False)
1401
+ expected = Series([3, 2, 1], index=[5.0, 10.3, None], name="count")
1402
+ tm.assert_series_equal(result, expected)
1403
+
1404
+ @pytest.mark.parametrize("dtype", (np.float64, object, "M8[ns]"))
1405
+ def test_value_counts_normalized(self, dtype):
1406
+ # GH12558
1407
+ s = Series([1] * 2 + [2] * 3 + [np.nan] * 5)
1408
+ s_typed = s.astype(dtype)
1409
+ result = s_typed.value_counts(normalize=True, dropna=False)
1410
+ expected = Series(
1411
+ [0.5, 0.3, 0.2],
1412
+ index=Series([np.nan, 2.0, 1.0], dtype=dtype),
1413
+ name="proportion",
1414
+ )
1415
+ tm.assert_series_equal(result, expected)
1416
+
1417
+ result = s_typed.value_counts(normalize=True, dropna=True)
1418
+ expected = Series(
1419
+ [0.6, 0.4], index=Series([2.0, 1.0], dtype=dtype), name="proportion"
1420
+ )
1421
+ tm.assert_series_equal(result, expected)
1422
+
1423
+ def test_value_counts_uint64(self):
1424
+ arr = np.array([2**63], dtype=np.uint64)
1425
+ expected = Series([1], index=[2**63], name="count")
1426
+ result = algos.value_counts_internal(arr)
1427
+
1428
+ tm.assert_series_equal(result, expected)
1429
+
1430
+ arr = np.array([-1, 2**63], dtype=object)
1431
+ expected = Series([1, 1], index=[-1, 2**63], name="count")
1432
+ result = algos.value_counts_internal(arr)
1433
+
1434
+ tm.assert_series_equal(result, expected)
1435
+
1436
+ def test_value_counts_series(self):
1437
+ # GH#54857
1438
+ values = np.array([3, 1, 2, 3, 4, np.nan])
1439
+ result = Series(values).value_counts(bins=3)
1440
+ expected = Series(
1441
+ [2, 2, 1],
1442
+ index=IntervalIndex.from_tuples(
1443
+ [(0.996, 2.0), (2.0, 3.0), (3.0, 4.0)], dtype="interval[float64, right]"
1444
+ ),
1445
+ name="count",
1446
+ )
1447
+ tm.assert_series_equal(result, expected)
1448
+
1449
+ def test_value_counts_stability(self):
1450
+ # GH 63155
1451
+ arr = np.random.default_rng(2).integers(0, 32, 64)
1452
+ result = algos.value_counts_internal(arr, sort=True)
1453
+
1454
+ value_counts = Series(arr).value_counts(sort=False)
1455
+ expected = value_counts.sort_values(ascending=False, kind="stable")
1456
+ tm.assert_series_equal(result, expected)
1457
+
1458
+ unstable_sorted = value_counts.sort_values(ascending=False, kind="quicksort")
1459
+ with pytest.raises(AssertionError):
1460
+ tm.assert_series_equal(result, unstable_sorted)
1461
+
1462
+
1463
+ class TestDuplicated:
1464
+ def test_duplicated_with_nas(self):
1465
+ keys = np.array([0, 1, np.nan, 0, 2, np.nan], dtype=object)
1466
+
1467
+ result = algos.duplicated(keys)
1468
+ expected = np.array([False, False, False, True, False, True])
1469
+ tm.assert_numpy_array_equal(result, expected)
1470
+
1471
+ result = algos.duplicated(keys, keep="first")
1472
+ expected = np.array([False, False, False, True, False, True])
1473
+ tm.assert_numpy_array_equal(result, expected)
1474
+
1475
+ result = algos.duplicated(keys, keep="last")
1476
+ expected = np.array([True, False, True, False, False, False])
1477
+ tm.assert_numpy_array_equal(result, expected)
1478
+
1479
+ result = algos.duplicated(keys, keep=False)
1480
+ expected = np.array([True, False, True, True, False, True])
1481
+ tm.assert_numpy_array_equal(result, expected)
1482
+
1483
+ keys = np.empty(8, dtype=object)
1484
+ for i, t in enumerate(
1485
+ zip([0, 0, np.nan, np.nan] * 2, [0, np.nan, 0, np.nan] * 2, strict=True)
1486
+ ):
1487
+ keys[i] = t
1488
+
1489
+ result = algos.duplicated(keys)
1490
+ falses = [False] * 4
1491
+ trues = [True] * 4
1492
+ expected = np.array(falses + trues)
1493
+ tm.assert_numpy_array_equal(result, expected)
1494
+
1495
+ result = algos.duplicated(keys, keep="last")
1496
+ expected = np.array(trues + falses)
1497
+ tm.assert_numpy_array_equal(result, expected)
1498
+
1499
+ result = algos.duplicated(keys, keep=False)
1500
+ expected = np.array(trues + trues)
1501
+ tm.assert_numpy_array_equal(result, expected)
1502
+
1503
+ @pytest.mark.parametrize(
1504
+ "case",
1505
+ [
1506
+ np.array([1, 2, 1, 5, 3, 2, 4, 1, 5, 6]),
1507
+ np.array([1.1, 2.2, 1.1, np.nan, 3.3, 2.2, 4.4, 1.1, np.nan, 6.6]),
1508
+ np.array(
1509
+ [
1510
+ 1 + 1j,
1511
+ 2 + 2j,
1512
+ 1 + 1j,
1513
+ 5 + 5j,
1514
+ 3 + 3j,
1515
+ 2 + 2j,
1516
+ 4 + 4j,
1517
+ 1 + 1j,
1518
+ 5 + 5j,
1519
+ 6 + 6j,
1520
+ ]
1521
+ ),
1522
+ np.array(["a", "b", "a", "e", "c", "b", "d", "a", "e", "f"], dtype=object),
1523
+ np.array([1, 2**63, 1, 3**5, 10, 2**63, 39, 1, 3**5, 7], dtype=np.uint64),
1524
+ ],
1525
+ )
1526
+ def test_numeric_object_likes(self, case):
1527
+ exp_first = np.array(
1528
+ [False, False, True, False, False, True, False, True, True, False]
1529
+ )
1530
+ exp_last = np.array(
1531
+ [True, True, True, True, False, False, False, False, False, False]
1532
+ )
1533
+ exp_false = exp_first | exp_last
1534
+
1535
+ res_first = algos.duplicated(case, keep="first")
1536
+ tm.assert_numpy_array_equal(res_first, exp_first)
1537
+
1538
+ res_last = algos.duplicated(case, keep="last")
1539
+ tm.assert_numpy_array_equal(res_last, exp_last)
1540
+
1541
+ res_false = algos.duplicated(case, keep=False)
1542
+ tm.assert_numpy_array_equal(res_false, exp_false)
1543
+
1544
+ # index
1545
+ for idx in [Index(case), Index(case, dtype="category")]:
1546
+ res_first = idx.duplicated(keep="first")
1547
+ tm.assert_numpy_array_equal(res_first, exp_first)
1548
+
1549
+ res_last = idx.duplicated(keep="last")
1550
+ tm.assert_numpy_array_equal(res_last, exp_last)
1551
+
1552
+ res_false = idx.duplicated(keep=False)
1553
+ tm.assert_numpy_array_equal(res_false, exp_false)
1554
+
1555
+ # series
1556
+ for s in [Series(case), Series(case, dtype="category")]:
1557
+ res_first = s.duplicated(keep="first")
1558
+ tm.assert_series_equal(res_first, Series(exp_first))
1559
+
1560
+ res_last = s.duplicated(keep="last")
1561
+ tm.assert_series_equal(res_last, Series(exp_last))
1562
+
1563
+ res_false = s.duplicated(keep=False)
1564
+ tm.assert_series_equal(res_false, Series(exp_false))
1565
+
1566
+ def test_datetime_likes(self):
1567
+ dt = [
1568
+ "2011-01-01",
1569
+ "2011-01-02",
1570
+ "2011-01-01",
1571
+ "NaT",
1572
+ "2011-01-03",
1573
+ "2011-01-02",
1574
+ "2011-01-04",
1575
+ "2011-01-01",
1576
+ "NaT",
1577
+ "2011-01-06",
1578
+ ]
1579
+ td = [
1580
+ "1 days",
1581
+ "2 days",
1582
+ "1 days",
1583
+ "NaT",
1584
+ "3 days",
1585
+ "2 days",
1586
+ "4 days",
1587
+ "1 days",
1588
+ "NaT",
1589
+ "6 days",
1590
+ ]
1591
+
1592
+ cases = [
1593
+ np.array([Timestamp(d) for d in dt]),
1594
+ np.array([Timestamp(d, tz="US/Eastern") for d in dt]),
1595
+ np.array([Period(d, freq="D") for d in dt]),
1596
+ np.array([np.datetime64(d, "ns") for d in dt]),
1597
+ np.array([Timedelta(d) for d in td]),
1598
+ ]
1599
+
1600
+ exp_first = np.array(
1601
+ [False, False, True, False, False, True, False, True, True, False]
1602
+ )
1603
+ exp_last = np.array(
1604
+ [True, True, True, True, False, False, False, False, False, False]
1605
+ )
1606
+ exp_false = exp_first | exp_last
1607
+
1608
+ for case in cases:
1609
+ res_first = algos.duplicated(case, keep="first")
1610
+ tm.assert_numpy_array_equal(res_first, exp_first)
1611
+
1612
+ res_last = algos.duplicated(case, keep="last")
1613
+ tm.assert_numpy_array_equal(res_last, exp_last)
1614
+
1615
+ res_false = algos.duplicated(case, keep=False)
1616
+ tm.assert_numpy_array_equal(res_false, exp_false)
1617
+
1618
+ # index
1619
+ for idx in [
1620
+ Index(case),
1621
+ Index(case, dtype="category"),
1622
+ Index(case, dtype=object),
1623
+ ]:
1624
+ res_first = idx.duplicated(keep="first")
1625
+ tm.assert_numpy_array_equal(res_first, exp_first)
1626
+
1627
+ res_last = idx.duplicated(keep="last")
1628
+ tm.assert_numpy_array_equal(res_last, exp_last)
1629
+
1630
+ res_false = idx.duplicated(keep=False)
1631
+ tm.assert_numpy_array_equal(res_false, exp_false)
1632
+
1633
+ # series
1634
+ for s in [
1635
+ Series(case),
1636
+ Series(case, dtype="category"),
1637
+ Series(case, dtype=object),
1638
+ ]:
1639
+ res_first = s.duplicated(keep="first")
1640
+ tm.assert_series_equal(res_first, Series(exp_first))
1641
+
1642
+ res_last = s.duplicated(keep="last")
1643
+ tm.assert_series_equal(res_last, Series(exp_last))
1644
+
1645
+ res_false = s.duplicated(keep=False)
1646
+ tm.assert_series_equal(res_false, Series(exp_false))
1647
+
1648
+ @pytest.mark.parametrize("case", [Index([1, 2, 3]), pd.RangeIndex(0, 3)])
1649
+ def test_unique_index(self, case):
1650
+ assert case.is_unique is True
1651
+ tm.assert_numpy_array_equal(case.duplicated(), np.array([False, False, False]))
1652
+
1653
+ @pytest.mark.parametrize(
1654
+ "arr, uniques",
1655
+ [
1656
+ (
1657
+ [(0, 0), (0, 1), (1, 0), (1, 1), (0, 0), (0, 1), (1, 0), (1, 1)],
1658
+ [(0, 0), (0, 1), (1, 0), (1, 1)],
1659
+ ),
1660
+ (
1661
+ [("b", "c"), ("a", "b"), ("a", "b"), ("b", "c")],
1662
+ [("b", "c"), ("a", "b")],
1663
+ ),
1664
+ ([("a", 1), ("b", 2), ("a", 3), ("a", 1)], [("a", 1), ("b", 2), ("a", 3)]),
1665
+ ],
1666
+ )
1667
+ def test_unique_tuples(self, arr, uniques):
1668
+ # https://github.com/pandas-dev/pandas/issues/16519
1669
+ expected = np.empty(len(uniques), dtype=object)
1670
+ expected[:] = uniques
1671
+
1672
+ msg = (
1673
+ r"unique requires a Series, Index, ExtensionArray, np.ndarray "
1674
+ r"or NumpyExtensionArray got list"
1675
+ )
1676
+ with pytest.raises(TypeError, match=msg):
1677
+ # GH#52986
1678
+ pd.unique(arr)
1679
+
1680
+ res = pd.unique(com.asarray_tuplesafe(arr, dtype=object))
1681
+ tm.assert_numpy_array_equal(res, expected)
1682
+
1683
+ @pytest.mark.parametrize(
1684
+ "array,expected",
1685
+ [
1686
+ (
1687
+ [1 + 1j, 0, 1, 1j, 1 + 2j, 1 + 2j],
1688
+ np.array([(1 + 1j), 0j, (1 + 0j), 1j, (1 + 2j)], dtype=complex),
1689
+ )
1690
+ ],
1691
+ )
1692
+ def test_unique_complex_numbers(self, array, expected):
1693
+ # GH 17927
1694
+ msg = (
1695
+ r"unique requires a Series, Index, ExtensionArray, np.ndarray "
1696
+ r"or NumpyExtensionArray got list"
1697
+ )
1698
+
1699
+ with pytest.raises(TypeError, match=msg):
1700
+ # GH#52986
1701
+ pd.unique(array)
1702
+
1703
+ res = pd.unique(np.array(array))
1704
+ tm.assert_numpy_array_equal(res, expected)
1705
+
1706
+
1707
+ class TestHashTable:
1708
+ @pytest.mark.parametrize(
1709
+ "htable, data",
1710
+ [
1711
+ (
1712
+ ht.PyObjectHashTable,
1713
+ np.array([f"foo_{i}" for i in range(1000)], dtype=object),
1714
+ ),
1715
+ (
1716
+ ht.StringHashTable,
1717
+ np.array([f"foo_{i}" for i in range(1000)], dtype=object),
1718
+ ),
1719
+ (ht.Float64HashTable, np.arange(1000, dtype=np.float64)),
1720
+ (ht.Int64HashTable, np.arange(1000, dtype=np.int64)),
1721
+ (ht.UInt64HashTable, np.arange(1000, dtype=np.uint64)),
1722
+ ],
1723
+ )
1724
+ def test_hashtable_unique(self, htable, data, writable):
1725
+ # output of maker has guaranteed unique elements
1726
+ s = Series(data, dtype=data.dtype)
1727
+ if htable == ht.Float64HashTable:
1728
+ # add NaN for float column
1729
+ s.loc[500] = np.nan
1730
+ elif htable == ht.PyObjectHashTable:
1731
+ # use different NaN types for object column
1732
+ s.loc[500:502] = [np.nan, None, NaT]
1733
+
1734
+ # create duplicated selection
1735
+ s_duplicated = s.sample(frac=3, replace=True).reset_index(drop=True)
1736
+ s_duplicated.values.setflags(write=writable)
1737
+
1738
+ # drop_duplicates has own cython code (hash_table_func_helper.pxi)
1739
+ # and is tested separately; keeps first occurrence like ht.unique()
1740
+ expected_unique = s_duplicated.drop_duplicates(keep="first").values
1741
+ result_unique = htable().unique(s_duplicated.values)
1742
+ tm.assert_numpy_array_equal(result_unique, expected_unique)
1743
+
1744
+ # test return_inverse=True
1745
+ # reconstruction can only succeed if the inverse is correct
1746
+ result_unique, result_inverse = htable().unique(
1747
+ s_duplicated.values, return_inverse=True
1748
+ )
1749
+ tm.assert_numpy_array_equal(result_unique, expected_unique)
1750
+ reconstr = result_unique[result_inverse]
1751
+ tm.assert_numpy_array_equal(reconstr, s_duplicated.values)
1752
+
1753
+ @pytest.mark.parametrize(
1754
+ "htable, data",
1755
+ [
1756
+ (
1757
+ ht.PyObjectHashTable,
1758
+ np.array([f"foo_{i}" for i in range(1000)], dtype=object),
1759
+ ),
1760
+ (
1761
+ ht.StringHashTable,
1762
+ np.array([f"foo_{i}" for i in range(1000)], dtype=object),
1763
+ ),
1764
+ (ht.Float64HashTable, np.arange(1000, dtype=np.float64)),
1765
+ (ht.Int64HashTable, np.arange(1000, dtype=np.int64)),
1766
+ (ht.UInt64HashTable, np.arange(1000, dtype=np.uint64)),
1767
+ ],
1768
+ )
1769
+ def test_hashtable_factorize(self, htable, writable, data):
1770
+ # output of maker has guaranteed unique elements
1771
+ s = Series(data, dtype=data.dtype)
1772
+ if htable == ht.Float64HashTable:
1773
+ # add NaN for float column
1774
+ s.loc[500] = np.nan
1775
+ elif htable == ht.PyObjectHashTable:
1776
+ # use different NaN types for object column
1777
+ s.loc[500:502] = [np.nan, None, NaT]
1778
+
1779
+ # create duplicated selection
1780
+ s_duplicated = s.sample(frac=3, replace=True).reset_index(drop=True)
1781
+ s_duplicated.values.setflags(write=writable)
1782
+ na_mask = s_duplicated.isna().values
1783
+
1784
+ result_unique, result_inverse = htable().factorize(s_duplicated.values)
1785
+
1786
+ # drop_duplicates has own cython code (hash_table_func_helper.pxi)
1787
+ # and is tested separately; keeps first occurrence like ht.factorize()
1788
+ # since factorize removes all NaNs, we do the same here
1789
+ expected_unique = s_duplicated.dropna().drop_duplicates().values
1790
+ tm.assert_numpy_array_equal(result_unique, expected_unique)
1791
+
1792
+ # reconstruction can only succeed if the inverse is correct. Since
1793
+ # factorize removes the NaNs, those have to be excluded here as well
1794
+ result_reconstruct = result_unique[result_inverse[~na_mask]]
1795
+ expected_reconstruct = s_duplicated.dropna().values
1796
+ tm.assert_numpy_array_equal(result_reconstruct, expected_reconstruct)
1797
+
1798
+
1799
+ class TestRank:
1800
+ @pytest.mark.parametrize(
1801
+ "arr",
1802
+ [
1803
+ [np.nan, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 3, np.nan],
1804
+ [4.0, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 4.0, np.nan],
1805
+ ],
1806
+ )
1807
+ def test_scipy_compat(self, arr):
1808
+ sp_stats = pytest.importorskip("scipy.stats")
1809
+
1810
+ arr = np.array(arr)
1811
+
1812
+ mask = ~np.isfinite(arr)
1813
+ result = libalgos.rank_1d(arr)
1814
+ arr[mask] = np.inf
1815
+ exp = sp_stats.rankdata(arr)
1816
+ exp[mask] = np.nan
1817
+ tm.assert_almost_equal(result, exp)
1818
+
1819
+ def test_basic(self, writable, any_int_numpy_dtype):
1820
+ exp = np.array([1, 2], dtype=np.float64)
1821
+
1822
+ data = np.array([1, 100], dtype=any_int_numpy_dtype)
1823
+ data.setflags(write=writable)
1824
+ ser = Series(data)
1825
+ result = algos.rank(ser)
1826
+ tm.assert_numpy_array_equal(result, exp)
1827
+
1828
+ @pytest.mark.parametrize("dtype", [np.float64, np.uint64])
1829
+ def test_uint64_overflow(self, dtype):
1830
+ exp = np.array([1, 2], dtype=np.float64)
1831
+
1832
+ s = Series([1, 2**63], dtype=dtype)
1833
+ tm.assert_numpy_array_equal(algos.rank(s), exp)
1834
+
1835
+ @pytest.mark.parametrize("method", ["average", "min", "max"])
1836
+ def test_rank_tiny_values(self, method):
1837
+ # GH62036: regression test for ranking with tiny float values
1838
+ exp = np.array([4.0, 1.0, 3.0, np.nan, 2.0], dtype=np.float64)
1839
+ s = Series(
1840
+ [5.4954145e29, -9.791984e-21, 9.3715776e-26, pd.NA, 1.8790257e-28],
1841
+ dtype="Float64",
1842
+ )
1843
+ s = s.astype(object)
1844
+ result = algos.rank(s, method=method)
1845
+ tm.assert_numpy_array_equal(result, exp)
1846
+
1847
+ def test_too_many_ndims(self):
1848
+ arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
1849
+ msg = "Array with ndim > 2 are not supported"
1850
+
1851
+ with pytest.raises(TypeError, match=msg):
1852
+ algos.rank(arr)
1853
+
1854
+ @pytest.mark.single_cpu
1855
+ def test_pct_max_many_rows(self):
1856
+ # GH 18271
1857
+ values = np.arange(2**24 + 1)
1858
+ result = algos.rank(values, pct=True).max()
1859
+ assert result == 1
1860
+
1861
+ values = np.arange(2**25 + 2).reshape(2**24 + 1, 2)
1862
+ result = algos.rank(values, pct=True).max()
1863
+ assert result == 1
1864
+
1865
+
1866
+ class TestMode:
1867
+ def test_no_mode(self):
1868
+ exp = Series([], dtype=np.float64, index=Index([], dtype=int))
1869
+ result, _ = algos.mode(np.array([]))
1870
+ tm.assert_numpy_array_equal(result, exp.values)
1871
+
1872
+ def test_mode_single(self, any_real_numpy_dtype):
1873
+ # GH 15714
1874
+ exp_single = [1]
1875
+ data_single = [1]
1876
+
1877
+ exp_multi = [1]
1878
+ data_multi = [1, 1]
1879
+
1880
+ ser = Series(data_single, dtype=any_real_numpy_dtype)
1881
+ exp = Series(exp_single, dtype=any_real_numpy_dtype)
1882
+ result, _ = algos.mode(ser.values)
1883
+ tm.assert_numpy_array_equal(result, exp.values)
1884
+ tm.assert_series_equal(ser.mode(), exp)
1885
+
1886
+ ser = Series(data_multi, dtype=any_real_numpy_dtype)
1887
+ exp = Series(exp_multi, dtype=any_real_numpy_dtype)
1888
+ result, _ = algos.mode(ser.values)
1889
+ tm.assert_numpy_array_equal(result, exp.values)
1890
+ tm.assert_series_equal(ser.mode(), exp)
1891
+
1892
+ def test_mode_obj_int(self):
1893
+ exp = Series([1], dtype=int)
1894
+ result, _ = algos.mode(exp.values)
1895
+ tm.assert_numpy_array_equal(result, exp.values)
1896
+
1897
+ exp = Series(["a", "b", "c"], dtype=object)
1898
+ result, _ = algos.mode(exp.values)
1899
+ tm.assert_numpy_array_equal(result, exp.values)
1900
+
1901
+ def test_number_mode(self, any_real_numpy_dtype):
1902
+ exp_single = [1]
1903
+ data_single = [1] * 5 + [2] * 3
1904
+
1905
+ exp_multi = [1, 3]
1906
+ data_multi = [1] * 5 + [2] * 3 + [3] * 5
1907
+
1908
+ ser = Series(data_single, dtype=any_real_numpy_dtype)
1909
+ exp = Series(exp_single, dtype=any_real_numpy_dtype)
1910
+ result, _ = algos.mode(ser.values)
1911
+ tm.assert_numpy_array_equal(result, exp.values)
1912
+ tm.assert_series_equal(ser.mode(), exp)
1913
+
1914
+ ser = Series(data_multi, dtype=any_real_numpy_dtype)
1915
+ exp = Series(exp_multi, dtype=any_real_numpy_dtype)
1916
+ result, _ = algos.mode(ser.values)
1917
+ tm.assert_numpy_array_equal(result, exp.values)
1918
+ tm.assert_series_equal(ser.mode(), exp)
1919
+
1920
+ def test_strobj_mode(self):
1921
+ exp = ["b"]
1922
+ data = ["a"] * 2 + ["b"] * 3
1923
+
1924
+ ser = Series(data, dtype="c")
1925
+ exp = Series(exp, dtype="c")
1926
+ result, _ = algos.mode(ser.values)
1927
+ tm.assert_numpy_array_equal(result, exp.values)
1928
+ tm.assert_series_equal(ser.mode(), exp)
1929
+
1930
+ @pytest.mark.parametrize("dt", [str, object])
1931
+ def test_strobj_multi_char(self, dt, using_infer_string):
1932
+ exp = ["bar"]
1933
+ data = ["foo"] * 2 + ["bar"] * 3
1934
+
1935
+ ser = Series(data, dtype=dt)
1936
+ exp = Series(exp, dtype=dt)
1937
+ result, _ = algos.mode(ser.values)
1938
+ if using_infer_string and dt is str:
1939
+ tm.assert_extension_array_equal(result, exp.values)
1940
+ else:
1941
+ tm.assert_numpy_array_equal(result, exp.values)
1942
+ tm.assert_series_equal(ser.mode(), exp)
1943
+
1944
+ def test_datelike_mode(self):
1945
+ exp = Series(["1900-05-03", "2011-01-03", "2013-01-02"], dtype="M8[ns]")
1946
+ ser = Series(["2011-01-03", "2013-01-02", "1900-05-03"], dtype="M8[ns]")
1947
+ tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
1948
+ tm.assert_series_equal(ser.mode(), exp)
1949
+
1950
+ exp = Series(["2011-01-03", "2013-01-02"], dtype="M8[ns]")
1951
+ ser = Series(
1952
+ ["2011-01-03", "2013-01-02", "1900-05-03", "2011-01-03", "2013-01-02"],
1953
+ dtype="M8[ns]",
1954
+ )
1955
+ tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
1956
+ tm.assert_series_equal(ser.mode(), exp)
1957
+
1958
+ def test_timedelta_mode(self):
1959
+ exp = Series(["-1 days", "0 days", "1 days"], dtype="timedelta64[ns]")
1960
+ ser = Series(["1 days", "-1 days", "0 days"], dtype="timedelta64[ns]")
1961
+ tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
1962
+ tm.assert_series_equal(ser.mode(), exp)
1963
+
1964
+ exp = Series(["2 min", "1 day"], dtype="timedelta64[ns]")
1965
+ ser = Series(
1966
+ ["1 day", "1 day", "-1 day", "-1 day 2 min", "2 min", "2 min"],
1967
+ dtype="timedelta64[ns]",
1968
+ )
1969
+ tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
1970
+ tm.assert_series_equal(ser.mode(), exp)
1971
+
1972
+ def test_mixed_dtype(self):
1973
+ exp = Series(["foo"], dtype=object)
1974
+ ser = Series([1, "foo", "foo"])
1975
+ result, _ = algos.mode(ser.values)
1976
+ tm.assert_numpy_array_equal(result, exp.values)
1977
+ tm.assert_series_equal(ser.mode(), exp)
1978
+
1979
+ def test_uint64_overflow(self):
1980
+ exp = Series([2**63], dtype=np.uint64)
1981
+ ser = Series([1, 2**63, 2**63], dtype=np.uint64)
1982
+ result, _ = algos.mode(ser.values)
1983
+ tm.assert_numpy_array_equal(result, exp.values)
1984
+ tm.assert_series_equal(ser.mode(), exp)
1985
+
1986
+ exp = Series([1, 2**63], dtype=np.uint64)
1987
+ ser = Series([1, 2**63], dtype=np.uint64)
1988
+ result, _ = algos.mode(ser.values)
1989
+ tm.assert_numpy_array_equal(result, exp.values)
1990
+ tm.assert_series_equal(ser.mode(), exp)
1991
+
1992
+ def test_categorical(self):
1993
+ c = Categorical([1, 2])
1994
+ exp = c
1995
+ res = Series(c).mode()._values
1996
+ tm.assert_categorical_equal(res, exp)
1997
+
1998
+ c = Categorical([1, "a", "a"])
1999
+ exp = Categorical(["a"], categories=[1, "a"])
2000
+ res = Series(c).mode()._values
2001
+ tm.assert_categorical_equal(res, exp)
2002
+
2003
+ c = Categorical([1, 1, 2, 3, 3])
2004
+ exp = Categorical([1, 3], categories=[1, 2, 3])
2005
+ res = Series(c).mode()._values
2006
+ tm.assert_categorical_equal(res, exp)
2007
+
2008
+ def test_index(self):
2009
+ idx = Index([1, 2, 3])
2010
+ exp = Series([1, 2, 3], dtype=np.int64)
2011
+ result, _ = algos.mode(idx)
2012
+ tm.assert_numpy_array_equal(result, exp.values)
2013
+
2014
+ idx = Index([1, "a", "a"])
2015
+ exp = Series(["a"], dtype=object)
2016
+ result, _ = algos.mode(idx)
2017
+ tm.assert_numpy_array_equal(result, exp.values)
2018
+
2019
+ idx = Index([1, 1, 2, 3, 3])
2020
+ exp = Series([1, 3], dtype=np.int64)
2021
+ result, _ = algos.mode(idx)
2022
+ tm.assert_numpy_array_equal(result, exp.values)
2023
+
2024
+ idx = Index(
2025
+ ["1 day", "1 day", "-1 day", "-1 day 2 min", "2 min", "2 min"],
2026
+ dtype="timedelta64[ns]",
2027
+ )
2028
+ with pytest.raises(AttributeError, match="TimedeltaIndex"):
2029
+ # algos.mode expects Arraylike, does *not* unwrap TimedeltaIndex
2030
+ algos.mode(idx)
2031
+
2032
+ def test_ser_mode_with_name(self):
2033
+ # GH 46737
2034
+ ser = Series([1, 1, 3], name="foo")
2035
+ result = ser.mode()
2036
+ expected = Series([1], name="foo")
2037
+ tm.assert_series_equal(result, expected)
2038
+
2039
+
2040
+ class TestDiff:
2041
+ @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
2042
+ def test_diff_datetimelike_nat(self, dtype):
2043
+ # NaT - NaT is NaT, not 0
2044
+ arr = np.arange(12).astype(np.int64).view(dtype).reshape(3, 4)
2045
+ arr[:, 2] = arr.dtype.type("NaT", "ns")
2046
+ result = algos.diff(arr, 1, axis=0)
2047
+
2048
+ expected = np.ones(arr.shape, dtype="timedelta64[ns]") * 4
2049
+ expected[:, 2] = np.timedelta64("NaT", "ns")
2050
+ expected[0, :] = np.timedelta64("NaT", "ns")
2051
+
2052
+ tm.assert_numpy_array_equal(result, expected)
2053
+
2054
+ result = algos.diff(arr.T, 1, axis=1)
2055
+ tm.assert_numpy_array_equal(result, expected.T)
2056
+
2057
+ def test_diff_ea_axis(self):
2058
+ dta = date_range("2016-01-01", periods=3, tz="US/Pacific")._data
2059
+
2060
+ msg = "cannot diff DatetimeArray on axis=1"
2061
+ with pytest.raises(ValueError, match=msg):
2062
+ algos.diff(dta, 1, axis=1)
2063
+
2064
+ @pytest.mark.parametrize("dtype", ["int8", "int16"])
2065
+ def test_diff_low_precision_int(self, dtype):
2066
+ arr = np.array([0, 1, 1, 0, 0], dtype=dtype)
2067
+ result = algos.diff(arr, 1)
2068
+ expected = np.array([np.nan, 1, 0, -1, 0], dtype="float32")
2069
+ tm.assert_numpy_array_equal(result, expected)
2070
+
2071
+
2072
+ @pytest.mark.parametrize("op", [np.array, pd.array])
2073
+ def test_union_with_duplicates(op):
2074
+ # GH#36289
2075
+ lvals = op([3, 1, 3, 4])
2076
+ rvals = op([2, 3, 1, 1])
2077
+ expected = op([3, 3, 1, 1, 4, 2])
2078
+ if isinstance(expected, np.ndarray):
2079
+ result = algos.union_with_duplicates(lvals, rvals)
2080
+ tm.assert_numpy_array_equal(result, expected)
2081
+ else:
2082
+ result = algos.union_with_duplicates(lvals, rvals)
2083
+ tm.assert_extension_array_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_col.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ import copy
3
+ from datetime import datetime
4
+ import operator
5
+ import re
6
+
7
+ import numpy as np
8
+ import pytest
9
+
10
+ from pandas._libs.properties import cache_readonly
11
+
12
+ import pandas as pd
13
+ import pandas._testing as tm
14
+ from pandas.api.typing import Expression
15
+ from pandas.tests.test_register_accessor import ensure_removed
16
+
17
+
18
+ @pytest.mark.parametrize(
19
+ ("expr", "expected_values", "expected_str"),
20
+ [
21
+ (pd.col("a"), [1, 2], "col('a')"),
22
+ (pd.col("a") * 2, [2, 4], "col('a') * 2"),
23
+ (pd.col("a").sum(), [3, 3], "col('a').sum()"),
24
+ (pd.col("a") + 1, [2, 3], "col('a') + 1"),
25
+ (1 + pd.col("a"), [2, 3], "1 + col('a')"),
26
+ (pd.col("a") - 1, [0, 1], "col('a') - 1"),
27
+ (1 - pd.col("a"), [0, -1], "1 - col('a')"),
28
+ (pd.col("a") * 1, [1, 2], "col('a') * 1"),
29
+ (1 * pd.col("a"), [1, 2], "1 * col('a')"),
30
+ (2 ** pd.col("a"), [2, 4], "2 ** col('a')"),
31
+ (pd.col("a") ** 2, [1, 4], "col('a') ** 2"),
32
+ (pd.col("a") / 1, [1.0, 2.0], "col('a') / 1"),
33
+ (1 / pd.col("a"), [1.0, 0.5], "1 / col('a')"),
34
+ (pd.col("a") // 1, [1, 2], "col('a') // 1"),
35
+ (1 // pd.col("a"), [1, 0], "1 // col('a')"),
36
+ (pd.col("a") % 1, [0, 0], "col('a') % 1"),
37
+ (1 % pd.col("a"), [0, 1], "1 % col('a')"),
38
+ (pd.col("a") > 1, [False, True], "col('a') > 1"),
39
+ (pd.col("a") >= 1, [True, True], "col('a') >= 1"),
40
+ (pd.col("a") < 1, [False, False], "col('a') < 1"),
41
+ (pd.col("a") <= 1, [True, False], "col('a') <= 1"),
42
+ (pd.col("a") == 1, [True, False], "col('a') == 1"),
43
+ (np.power(pd.col("a"), 2), [1, 4], "power(col('a'), 2)"),
44
+ (np.divide(pd.col("a"), pd.col("a")), [1.0, 1.0], "divide(col('a'), col('a'))"),
45
+ (
46
+ (pd.col("a") + 1) * (pd.col("b") + 2),
47
+ [10, 18],
48
+ "(col('a') + 1) * (col('b') + 2)",
49
+ ),
50
+ (
51
+ (pd.col("a") - 1).astype("bool"),
52
+ [False, True],
53
+ "(col('a') - 1).astype('bool')",
54
+ ),
55
+ # Unary operators
56
+ (-pd.col("a"), [-1, -2], "-col('a')"),
57
+ (+pd.col("a"), [1, 2], "+col('a')"),
58
+ (-(pd.col("a") + 1), [-2, -3], "-(col('a') + 1)"),
59
+ (-pd.col("a") * 2, [-2, -4], "(-col('a')) * 2"),
60
+ (abs(pd.col("a")), [1, 2], "abs(col('a'))"),
61
+ (abs(pd.col("a") - 2), [1, 0], "abs(col('a') - 2)"),
62
+ ],
63
+ )
64
+ def test_col_simple(
65
+ expr: Expression, expected_values: list[object], expected_str: str
66
+ ) -> None:
67
+ # https://github.com/pandas-dev/pandas/pull/64267
68
+ df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
69
+ result = df.assign(c=expr)
70
+ expected = pd.DataFrame({"a": [1, 2], "b": [3, 4], "c": expected_values})
71
+ tm.assert_frame_equal(result, expected)
72
+ assert str(expr) == expected_str
73
+
74
+
75
+ @pytest.mark.parametrize(
76
+ ("op", "expected_values", "expected_str"),
77
+ [
78
+ (operator.iadd, [3, 4], "col('a') + 2"),
79
+ (operator.iand, [0, 2], "col('a') & 2"),
80
+ (operator.ifloordiv, [0, 1], "col('a') // 2"),
81
+ (operator.imod, [1, 0], "col('a') % 2"),
82
+ (operator.imul, [2, 4], "col('a') * 2"),
83
+ (operator.ior, [3, 2], "col('a') | 2"),
84
+ (operator.ipow, [1, 4], "col('a') ** 2"),
85
+ (operator.isub, [-1, 0], "col('a') - 2"),
86
+ (operator.itruediv, [0.5, 1.0], "col('a') / 2"),
87
+ (operator.ixor, [3, 0], "col('a') ^ 2"),
88
+ ],
89
+ )
90
+ def test_inplace_ops(
91
+ op: Callable, expected_values: list[object], expected_str: str
92
+ ) -> None:
93
+ # https://github.com/pandas-dev/pandas/pull/64267
94
+ df = pd.DataFrame({"a": [1, 2]})
95
+ expr = pd.col("a")
96
+ expr = op(expr, 2)
97
+ result = df.assign(c=expr)
98
+ expected = pd.DataFrame({"a": [1, 2], "c": expected_values})
99
+ tm.assert_frame_equal(result, expected)
100
+ assert str(expr) == expected_str
101
+
102
+
103
+ def test_matmul():
104
+ # https://github.com/pandas-dev/pandas/pull/64267
105
+ df = pd.DataFrame({"a": [1, 2]})
106
+
107
+ expr = pd.col("a") @ [3, 4]
108
+ result = df.assign(c=expr)
109
+ expected = pd.DataFrame({"a": [1, 2], "c": [11, 11]})
110
+ tm.assert_frame_equal(result, expected)
111
+ assert str(expr) == "col('a') @ [3, 4]"
112
+
113
+ expr = [3, 4] @ pd.col("a")
114
+ result = df.assign(c=expr)
115
+ expected = pd.DataFrame({"a": [1, 2], "c": [11, 11]})
116
+ tm.assert_frame_equal(result, expected)
117
+ assert str(expr) == "[3, 4] @ col('a')"
118
+
119
+
120
+ def test_frame_getitem() -> None:
121
+ # https://github.com/pandas-dev/pandas/pull/63439
122
+ df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
123
+ expr = pd.col("a") == 2
124
+ result = df[expr]
125
+ expected = df.iloc[[1]]
126
+ tm.assert_frame_equal(result, expected)
127
+
128
+
129
+ def test_frame_setitem() -> None:
130
+ # https://github.com/pandas-dev/pandas/pull/63439
131
+ df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
132
+ expr = pd.col("a") == 2
133
+
134
+ result = df.copy()
135
+ result[expr] = 100
136
+ expected = pd.DataFrame({"a": [1, 100], "b": [3, 100]})
137
+ tm.assert_frame_equal(result, expected)
138
+
139
+
140
+ def test_frame_loc() -> None:
141
+ # https://github.com/pandas-dev/pandas/pull/63439
142
+ df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
143
+ expr = pd.col("a") == 2
144
+ result = df.copy()
145
+ result.loc[expr, "b"] = 100
146
+ expected = pd.DataFrame({"a": [1, 2], "b": [3, 100]})
147
+ tm.assert_frame_equal(result, expected)
148
+
149
+
150
+ def test_frame_iloc() -> None:
151
+ # https://github.com/pandas-dev/pandas/pull/63439
152
+ df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
153
+ expr = pd.col("a") == 2
154
+ result = df.copy()
155
+ result.iloc[expr, 1] = 100
156
+ expected = pd.DataFrame({"a": [1, 2], "b": [3, 100]})
157
+ tm.assert_frame_equal(result, expected)
158
+
159
+
160
+ @pytest.mark.parametrize(
161
+ ("expr", "expected_values", "expected_str"),
162
+ [
163
+ (pd.col("a").dt.year, [2020], "col('a').dt.year"),
164
+ (pd.col("a").dt.strftime("%B"), ["January"], "col('a').dt.strftime('%B')"),
165
+ (pd.col("b").str.upper(), ["FOO"], "col('b').str.upper()"),
166
+ ],
167
+ )
168
+ def test_namespaces(
169
+ expr: Expression, expected_values: list[object], expected_str: str
170
+ ) -> None:
171
+ df = pd.DataFrame({"a": [datetime(2020, 1, 1)], "b": ["foo"]})
172
+ result = df.assign(c=expr)
173
+ expected = pd.DataFrame(
174
+ {"a": [datetime(2020, 1, 1)], "b": ["foo"], "c": expected_values}
175
+ )
176
+ tm.assert_frame_equal(result, expected, check_dtype=False)
177
+ assert str(expr) == expected_str
178
+
179
+
180
+ def test_invalid() -> None:
181
+ df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
182
+ with pytest.raises(ValueError, match=r"did you mean one of \['a', 'b'\] instead"):
183
+ df.assign(c=pd.col("c").mean())
184
+ df = pd.DataFrame({f"col_{i}": [0] for i in range(11)})
185
+ msg = (
186
+ "did you mean one of "
187
+ r"\['col_0', 'col_1', 'col_2', 'col_3', "
188
+ "'col_4', 'col_5', 'col_6', 'col_7', "
189
+ r"'col_8', 'col_9',\.\.\.\] instead"
190
+ )
191
+ ""
192
+ with pytest.raises(ValueError, match=msg):
193
+ df.assign(c=pd.col("c").mean())
194
+
195
+
196
+ def test_custom_accessor() -> None:
197
+ df = pd.DataFrame({"a": [1, 2, 3]})
198
+
199
+ class XYZAccessor:
200
+ def __init__(self, pandas_obj):
201
+ self._obj = pandas_obj
202
+
203
+ def mean(self):
204
+ return self._obj.mean()
205
+
206
+ with ensure_removed(pd.Series, "xyz"):
207
+ pd.api.extensions.register_series_accessor("xyz")(XYZAccessor)
208
+ result = df.assign(b=pd.col("a").xyz.mean())
209
+ expected = pd.DataFrame({"a": [1, 2, 3], "b": [2.0, 2.0, 2.0]})
210
+ tm.assert_frame_equal(result, expected)
211
+
212
+
213
+ @pytest.mark.parametrize(
214
+ ("expr", "expected_values", "expected_str"),
215
+ [
216
+ (
217
+ pd.col("a") & pd.col("b"),
218
+ [False, False, True, False],
219
+ "col('a') & col('b')",
220
+ ),
221
+ (
222
+ pd.col("a") & True,
223
+ [True, False, True, False],
224
+ "col('a') & True",
225
+ ),
226
+ (
227
+ pd.col("a") | pd.col("b"),
228
+ [True, True, True, True],
229
+ "col('a') | col('b')",
230
+ ),
231
+ (
232
+ pd.col("a") | False,
233
+ [True, False, True, False],
234
+ "col('a') | False",
235
+ ),
236
+ (
237
+ pd.col("a") ^ pd.col("b"),
238
+ [True, True, False, True],
239
+ "col('a') ^ col('b')",
240
+ ),
241
+ (
242
+ pd.col("a") ^ True,
243
+ [False, True, False, True],
244
+ "col('a') ^ True",
245
+ ),
246
+ (
247
+ ~pd.col("a"),
248
+ [False, True, False, True],
249
+ "~col('a')",
250
+ ),
251
+ ],
252
+ )
253
+ def test_col_logical_ops(
254
+ expr: Expression, expected_values: list[bool], expected_str: str
255
+ ) -> None:
256
+ # https://github.com/pandas-dev/pandas/issues/63322
257
+ df = pd.DataFrame({"a": [True, False, True, False], "b": [False, True, True, True]})
258
+ result = df.assign(c=expr)
259
+ expected = pd.DataFrame(
260
+ {
261
+ "a": [True, False, True, False],
262
+ "b": [False, True, True, True],
263
+ "c": expected_values,
264
+ }
265
+ )
266
+ tm.assert_frame_equal(result, expected)
267
+ assert str(expr) == expected_str
268
+
269
+ # Test that the expression works with .loc
270
+ result = df.loc[expr]
271
+ expected = df[expected_values]
272
+ tm.assert_frame_equal(result, expected)
273
+
274
+
275
+ def test_expression_getitem() -> None:
276
+ # https://github.com/pandas-dev/pandas/pull/63439
277
+ df = pd.DataFrame({"a": [1, 2, 3]})
278
+ expr = pd.col("a")[1]
279
+ expected_str = "col('a')[1]"
280
+
281
+ assert str(expr) == expected_str
282
+
283
+ result = df.assign(b=expr)
284
+ expected = pd.DataFrame({"a": [1, 2, 3], "b": [2, 2, 2]})
285
+ tm.assert_frame_equal(result, expected)
286
+
287
+
288
+ def test_property() -> None:
289
+ # https://github.com/pandas-dev/pandas/pull/63439
290
+ df = pd.DataFrame({"a": [1, 2, 3]})
291
+ expr = pd.col("a").index
292
+ expected_str = "col('a').index"
293
+
294
+ assert str(expr) == expected_str
295
+
296
+ result = df.assign(b=expr)
297
+ expected = pd.DataFrame({"a": [1, 2, 3], "b": [0, 1, 2]})
298
+ tm.assert_frame_equal(result, expected)
299
+
300
+
301
+ def test_cached_property() -> None:
302
+ # https://github.com/pandas-dev/pandas/pull/63439
303
+ # Ensure test is valid
304
+ assert isinstance(pd.Index.dtype, cache_readonly)
305
+
306
+ df = pd.DataFrame({"a": [1, 2, 3]})
307
+ expr = pd.col("a").index.dtype
308
+ expected_str = "col('a').index.dtype"
309
+ assert str(expr) == expected_str
310
+
311
+ result = df.assign(b=expr)
312
+ expected = pd.DataFrame({"a": [1, 2, 3], "b": np.int64})
313
+ tm.assert_frame_equal(result, expected)
314
+
315
+
316
+ def test_qcut() -> None:
317
+ # https://github.com/pandas-dev/pandas/pull/63439
318
+ df = pd.DataFrame({"a": [1, 2, 3]})
319
+ expr = pd.qcut(pd.col("a"), 3)
320
+ expected_str = "qcut(x=col('a'), q=3, labels=None, retbins=False, precision=3)"
321
+ assert str(expr) == expected_str, str(expr)
322
+
323
+ result = df.assign(b=expr)
324
+ expected = pd.DataFrame({"a": [1, 2, 3], "b": pd.qcut(df["a"], 3)})
325
+ tm.assert_frame_equal(result, expected)
326
+
327
+
328
+ def test_where() -> None:
329
+ # https://github.com/pandas-dev/pandas/pull/63439
330
+ df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
331
+ expr = pd.col("a").where(pd.col("b") == 5, 100)
332
+ expected_str = "col('a').where(col('b') == 5, 100)"
333
+ assert str(expr) == expected_str, str(expr)
334
+
335
+ result = df.assign(c=expr)
336
+ expected = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [100, 2, 100]})
337
+ tm.assert_frame_equal(result, expected)
338
+
339
+ expr = pd.col("a").where(pd.col("b") == 5, pd.col("a") + 1)
340
+ expected_str = "col('a').where(col('b') == 5, col('a') + 1)"
341
+ assert str(expr) == expected_str, str(expr)
342
+
343
+ result = df.assign(c=expr)
344
+ expected = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [2, 2, 4]})
345
+ tm.assert_frame_equal(result, expected)
346
+
347
+
348
+ # Unsupported ops
349
+ def test_bool():
350
+ with pytest.raises(TypeError, match="boolean value of an expression is ambiguous"):
351
+ bool(pd.col("a"))
352
+
353
+
354
+ def test_iter():
355
+ with pytest.raises(TypeError, match="Expression objects are not iterable"):
356
+ iter(pd.col("a"))
357
+
358
+
359
+ def test_contains():
360
+ # Python 3.14 changes the message from "is not iterable" to
361
+ # "is not a container or iterable"
362
+ with pytest.raises(
363
+ TypeError, match="argument of type 'Expression' is not .*iterable"
364
+ ):
365
+ 1 in pd.col("a")
366
+
367
+
368
+ def test_copy():
369
+ with pytest.raises(TypeError, match="Expression objects are not copiable"):
370
+ copy.copy(pd.col("a"))
371
+
372
+
373
+ def test_deepcopy():
374
+ with pytest.raises(TypeError, match="Expression objects are not copiable"):
375
+ copy.deepcopy(pd.col("a"))
376
+
377
+
378
+ def test_divmod():
379
+ msg = re.escape("unsupported operand type(s) for divmod(): 'Expression' and 'int'")
380
+ with pytest.raises(TypeError, match=msg):
381
+ divmod(pd.col("a"), 2)
382
+
383
+
384
+ def test_len():
385
+ with pytest.raises(TypeError, match="object of type 'Expression' has no len()"):
386
+ len(pd.col("a"))
387
+
388
+
389
+ def test_round():
390
+ msg = "type Expression doesn't define __round__ method"
391
+ with pytest.raises(TypeError, match=msg):
392
+ round(pd.col("a"), 2)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_common.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ from functools import partial
3
+ import string
4
+ import subprocess
5
+ import sys
6
+
7
+ import numpy as np
8
+ import pytest
9
+
10
+ from pandas.compat import WASM
11
+
12
+ import pandas as pd
13
+ from pandas import Series
14
+ import pandas._testing as tm
15
+ from pandas.core import ops
16
+ import pandas.core.common as com
17
+ from pandas.util.version import Version
18
+
19
+
20
+ class TestGetCallableName:
21
+ def fn(self, x):
22
+ return x
23
+
24
+ partial1 = partial(fn)
25
+ partial2 = partial(partial1)
26
+ lambda_ = lambda x: x
27
+
28
+ class SomeCall:
29
+ def __call__(self):
30
+ # This shouldn't actually get called below; SomeCall.__init__
31
+ # should.
32
+ raise NotImplementedError
33
+
34
+ @pytest.mark.parametrize(
35
+ "func, expected",
36
+ [
37
+ (fn, "fn"),
38
+ (partial1, "fn"),
39
+ (partial2, "fn"),
40
+ (lambda_, "<lambda>"),
41
+ (SomeCall(), "SomeCall"),
42
+ (1, None),
43
+ ],
44
+ )
45
+ def test_get_callable_name(self, func, expected):
46
+ assert com.get_callable_name(func) == expected
47
+
48
+
49
+ class TestRandomState:
50
+ def test_seed(self):
51
+ seed = 5
52
+ assert com.random_state(seed).uniform() == np.random.RandomState(seed).uniform()
53
+
54
+ def test_object(self):
55
+ seed = 10
56
+ state_obj = np.random.RandomState(seed)
57
+ assert (
58
+ com.random_state(state_obj).uniform()
59
+ == np.random.RandomState(seed).uniform()
60
+ )
61
+
62
+ def test_default(self):
63
+ assert com.random_state() is np.random
64
+
65
+ def test_array_like(self):
66
+ state = np.random.default_rng(None).integers(0, 2**31, size=624, dtype="uint32")
67
+ assert (
68
+ com.random_state(state).uniform() == np.random.RandomState(state).uniform()
69
+ )
70
+
71
+ def test_bit_generators(self):
72
+ seed = 3
73
+ assert (
74
+ com.random_state(np.random.MT19937(seed)).uniform()
75
+ == np.random.RandomState(np.random.MT19937(seed)).uniform()
76
+ )
77
+
78
+ seed = 11
79
+ assert (
80
+ com.random_state(np.random.PCG64(seed)).uniform()
81
+ == np.random.RandomState(np.random.PCG64(seed)).uniform()
82
+ )
83
+
84
+ @pytest.mark.parametrize("state", ["test", 5.5])
85
+ def test_error(self, state):
86
+ msg = (
87
+ "random_state must be an integer, array-like, a BitGenerator, Generator, "
88
+ "a numpy RandomState, or None"
89
+ )
90
+ with pytest.raises(ValueError, match=msg):
91
+ com.random_state(state)
92
+
93
+
94
+ @pytest.mark.parametrize("args, expected", [((1, 2, None), True), ((1, 2, 3), False)])
95
+ def test_any_none(args, expected):
96
+ assert com.any_none(*args) is expected
97
+
98
+
99
+ @pytest.mark.parametrize(
100
+ "args, expected",
101
+ [((1, 2, 3), True), ((1, 2, None), False), ((None, None, None), False)],
102
+ )
103
+ def test_all_not_none(args, expected):
104
+ assert com.all_not_none(*args) is expected
105
+
106
+
107
+ @pytest.mark.parametrize(
108
+ "left, right, expected",
109
+ [
110
+ (Series([1], name="x"), Series([2], name="x"), "x"),
111
+ (Series([1], name="x"), Series([2], name="y"), None),
112
+ (Series([1]), Series([2], name="x"), None),
113
+ (Series([1], name="x"), Series([2]), None),
114
+ (Series([1], name="x"), [2], "x"),
115
+ ([1], Series([2], name="y"), "y"),
116
+ # matching NAs
117
+ (Series([1], name=np.nan), pd.Index([], name=np.nan), np.nan),
118
+ (Series([1], name=np.nan), pd.Index([], name=pd.NaT), None),
119
+ (Series([1], name=pd.NA), pd.Index([], name=pd.NA), pd.NA),
120
+ # tuple name GH#39757
121
+ (
122
+ Series([1], name=np.int64(1)),
123
+ pd.Index([], name=(np.int64(1), np.int64(2))),
124
+ None,
125
+ ),
126
+ (
127
+ Series([1], name=(np.int64(1), np.int64(2))),
128
+ pd.Index([], name=(np.int64(1), np.int64(2))),
129
+ (np.int64(1), np.int64(2)),
130
+ ),
131
+ pytest.param(
132
+ Series([1], name=(np.float64("nan"), np.int64(2))),
133
+ pd.Index([], name=(np.float64("nan"), np.int64(2))),
134
+ (np.float64("nan"), np.int64(2)),
135
+ marks=pytest.mark.xfail(
136
+ reason="Not checking for matching NAs inside tuples."
137
+ ),
138
+ ),
139
+ ],
140
+ )
141
+ def test_maybe_match_name(left, right, expected):
142
+ res = ops.common._maybe_match_name(left, right)
143
+ assert res is expected or res == expected
144
+
145
+
146
+ @pytest.mark.parametrize(
147
+ "into, msg",
148
+ [
149
+ (
150
+ # uninitialized defaultdict
151
+ collections.defaultdict,
152
+ r"to_dict\(\) only accepts initialized defaultdicts",
153
+ ),
154
+ (
155
+ # non-mapping subtypes,, instance
156
+ [],
157
+ "unsupported type: <class 'list'>",
158
+ ),
159
+ (
160
+ # non-mapping subtypes, class
161
+ list,
162
+ "unsupported type: <class 'list'>",
163
+ ),
164
+ ],
165
+ )
166
+ def test_standardize_mapping_type_error(into, msg):
167
+ with pytest.raises(TypeError, match=msg):
168
+ com.standardize_mapping(into)
169
+
170
+
171
+ def test_standardize_mapping():
172
+ fill = {"bad": "data"}
173
+ assert com.standardize_mapping(fill) == dict
174
+
175
+ # Convert instance to type
176
+ assert com.standardize_mapping({}) == dict
177
+
178
+ dd = collections.defaultdict(list)
179
+ assert isinstance(com.standardize_mapping(dd), partial)
180
+
181
+
182
+ def test_git_version():
183
+ # GH 21295
184
+ git_version = pd.__git_version__
185
+ assert len(git_version) == 40
186
+ assert all(c in string.hexdigits for c in git_version)
187
+
188
+
189
+ def test_version_tag():
190
+ version = Version(pd.__version__)
191
+ try:
192
+ version > Version("0.0.1")
193
+ except TypeError as err:
194
+ raise ValueError(
195
+ "No git tags exist, please sync tags between upstream and your repo"
196
+ ) from err
197
+
198
+
199
+ @pytest.mark.parametrize("obj", [obj for obj in pd.__dict__.values() if callable(obj)])
200
+ def test_serializable(obj, temp_file):
201
+ # GH 35611
202
+ unpickled = tm.round_trip_pickle(obj, temp_file)
203
+ assert type(obj) == type(unpickled)
204
+
205
+
206
+ class TestIsBoolIndexer:
207
+ def test_non_bool_array_with_na(self):
208
+ # in particular, this should not raise
209
+ arr = np.array(["A", "B", np.nan], dtype=object)
210
+ assert not com.is_bool_indexer(arr)
211
+
212
+ def test_list_subclass(self):
213
+ # GH#42433
214
+
215
+ class MyList(list):
216
+ pass
217
+
218
+ val = MyList(["a"])
219
+
220
+ assert not com.is_bool_indexer(val)
221
+
222
+ val = MyList([True])
223
+ assert com.is_bool_indexer(val)
224
+
225
+ def test_frozenlist(self):
226
+ # GH#42461
227
+ data = {"col1": [1, 2], "col2": [3, 4]}
228
+ df = pd.DataFrame(data=data)
229
+
230
+ frozen = df.index.names[1:]
231
+ assert not com.is_bool_indexer(frozen)
232
+
233
+ result = df[frozen]
234
+ expected = df[[]]
235
+ tm.assert_frame_equal(result, expected)
236
+
237
+ @pytest.mark.parametrize("scalar", [1, True])
238
+ def test_numpyextensionarray(self, scalar):
239
+ # GH 63391
240
+ arr = pd.arrays.NumpyExtensionArray(np.array([scalar]))
241
+ assert com.is_bool_indexer(arr) is isinstance(scalar, bool)
242
+
243
+
244
+ @pytest.mark.parametrize("with_exception", [True, False])
245
+ def test_temp_setattr(with_exception):
246
+ # GH#45954
247
+ ser = Series(dtype=object)
248
+ ser.name = "first"
249
+ # Raise a ValueError in either case to satisfy pytest.raises
250
+ match = "Inside exception raised" if with_exception else "Outside exception raised"
251
+ with pytest.raises(ValueError, match=match):
252
+ with com.temp_setattr(ser, "name", "second"):
253
+ assert ser.name == "second"
254
+ if with_exception:
255
+ raise ValueError("Inside exception raised")
256
+ raise ValueError("Outside exception raised")
257
+ assert ser.name == "first"
258
+
259
+
260
+ @pytest.mark.skipif(WASM, reason="Can't start subprocesses in WASM")
261
+ @pytest.mark.single_cpu
262
+ def test_str_size():
263
+ # GH#21758
264
+ a = "a"
265
+ expected = sys.getsizeof(a)
266
+ pyexe = sys.executable.replace("\\", "/")
267
+ call = [
268
+ pyexe,
269
+ "-c",
270
+ "a='a';import sys;sys.getsizeof(a);import pandas;print(sys.getsizeof(a));",
271
+ ]
272
+ result = subprocess.check_output(call).decode()[-4:-1].strip("\n")
273
+ assert int(result) == int(expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_downstream.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Testing that we work in the downstream packages
3
+ """
4
+
5
+ import array
6
+ from functools import partial
7
+ import importlib
8
+ import subprocess
9
+ import sys
10
+
11
+ import numpy as np
12
+ import pytest
13
+
14
+ from pandas.errors import IntCastingNaNError
15
+
16
+ import pandas as pd
17
+ from pandas import (
18
+ DataFrame,
19
+ DatetimeIndex,
20
+ Series,
21
+ TimedeltaIndex,
22
+ )
23
+ import pandas._testing as tm
24
+ from pandas.util.version import Version
25
+
26
+
27
+ @pytest.fixture
28
+ def df():
29
+ return DataFrame({"A": [1, 2, 3]})
30
+
31
+
32
+ def test_dask(df):
33
+ # dask sets "compute.use_numexpr" to False, so catch the current value
34
+ # and ensure to reset it afterwards to avoid impacting other tests
35
+ olduse = pd.get_option("compute.use_numexpr")
36
+
37
+ try:
38
+ pytest.importorskip("toolz")
39
+ dd = pytest.importorskip("dask.dataframe")
40
+
41
+ ddf = dd.from_pandas(df, npartitions=3)
42
+ assert ddf.A is not None
43
+ assert ddf.compute() is not None
44
+ finally:
45
+ pd.set_option("compute.use_numexpr", olduse)
46
+
47
+
48
+ # TODO(CoW) see https://github.com/pandas-dev/pandas/pull/51082
49
+ @pytest.mark.skip(reason="not implemented with CoW")
50
+ def test_dask_ufunc():
51
+ # dask sets "compute.use_numexpr" to False, so catch the current value
52
+ # and ensure to reset it afterwards to avoid impacting other tests
53
+ olduse = pd.get_option("compute.use_numexpr")
54
+
55
+ try:
56
+ da = pytest.importorskip("dask.array")
57
+ dd = pytest.importorskip("dask.dataframe")
58
+
59
+ s = Series([1.5, 2.3, 3.7, 4.0])
60
+ ds = dd.from_pandas(s, npartitions=2)
61
+
62
+ result = da.log(ds).compute()
63
+ expected = np.log(s)
64
+ tm.assert_series_equal(result, expected)
65
+ finally:
66
+ pd.set_option("compute.use_numexpr", olduse)
67
+
68
+
69
+ def test_construct_dask_float_array_int_dtype_match_ndarray():
70
+ # GH#40110 make sure we treat a float-dtype dask array with the same
71
+ # rules we would for an ndarray
72
+ dd = pytest.importorskip("dask.dataframe")
73
+
74
+ arr = np.array([1, 2.5, 3])
75
+ darr = dd.from_array(arr)
76
+
77
+ res = Series(darr)
78
+ expected = Series(arr)
79
+ tm.assert_series_equal(res, expected)
80
+
81
+ # GH#49599 in 2.0 we raise instead of silently ignoring the dtype
82
+ msg = "Trying to coerce float values to integers"
83
+ with pytest.raises(ValueError, match=msg):
84
+ Series(darr, dtype="i8")
85
+
86
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
87
+ arr[2] = np.nan
88
+ with pytest.raises(IntCastingNaNError, match=msg):
89
+ Series(darr, dtype="i8")
90
+ # which is the same as we get with a numpy input
91
+ with pytest.raises(IntCastingNaNError, match=msg):
92
+ Series(arr, dtype="i8")
93
+
94
+
95
+ def test_xarray(df):
96
+ pytest.importorskip("xarray")
97
+
98
+ assert df.to_xarray() is not None
99
+
100
+
101
+ def test_xarray_cftimeindex_nearest():
102
+ # https://github.com/pydata/xarray/issues/3751
103
+ cftime = pytest.importorskip("cftime")
104
+ xarray = pytest.importorskip("xarray")
105
+
106
+ times = xarray.date_range("0001", periods=2, use_cftime=True)
107
+ key = cftime.DatetimeGregorian(2000, 1, 1)
108
+ result = times.get_indexer([key], method="nearest")
109
+ expected = 1
110
+ assert result == expected
111
+
112
+
113
+ @pytest.mark.single_cpu
114
+ def test_oo_optimizable():
115
+ # GH 21071
116
+ subprocess.check_call([sys.executable, "-OO", "-c", "import pandas"])
117
+
118
+
119
+ @pytest.mark.single_cpu
120
+ def test_oo_optimized_datetime_index_unpickle():
121
+ # GH 42866
122
+ subprocess.check_call(
123
+ [
124
+ sys.executable,
125
+ "-OO",
126
+ "-c",
127
+ (
128
+ "import pandas as pd, pickle; "
129
+ "pickle.loads(pickle.dumps(pd.date_range('2021-01-01', periods=1)))"
130
+ ),
131
+ ]
132
+ )
133
+
134
+
135
+ def test_statsmodels():
136
+ smf = pytest.importorskip("statsmodels.formula.api")
137
+
138
+ df = DataFrame(
139
+ {"Lottery": range(5), "Literacy": range(5), "Pop1831": range(100, 105)}
140
+ )
141
+ smf.ols("Lottery ~ Literacy + np.log(Pop1831)", data=df).fit()
142
+
143
+
144
+ def test_scikit_learn():
145
+ pytest.importorskip("sklearn")
146
+ from sklearn import (
147
+ datasets,
148
+ svm,
149
+ )
150
+
151
+ digits = datasets.load_digits()
152
+ clf = svm.SVC(gamma=0.001, C=100.0)
153
+ clf.fit(digits.data[:-1], digits.target[:-1])
154
+ clf.predict(digits.data[-1:])
155
+
156
+
157
+ def test_seaborn(mpl_cleanup):
158
+ seaborn = pytest.importorskip("seaborn")
159
+ tips = DataFrame(
160
+ {"day": pd.date_range("2023", freq="D", periods=5), "total_bill": range(5)}
161
+ )
162
+ seaborn.stripplot(x="day", y="total_bill", data=tips)
163
+
164
+
165
+ def test_pandas_datareader():
166
+ pytest.importorskip("pandas_datareader")
167
+
168
+
169
+ @pytest.mark.filterwarnings("ignore:Passing a BlockManager:DeprecationWarning")
170
+ def test_pyarrow(df):
171
+ pyarrow = pytest.importorskip("pyarrow")
172
+ table = pyarrow.Table.from_pandas(df)
173
+ result = table.to_pandas()
174
+ tm.assert_frame_equal(result, df)
175
+
176
+
177
+ def test_yaml_dump(df):
178
+ # GH#42748
179
+ yaml = pytest.importorskip("yaml")
180
+
181
+ dumped = yaml.dump(df)
182
+
183
+ loaded = yaml.load(dumped, Loader=yaml.Loader)
184
+ tm.assert_frame_equal(df, loaded)
185
+
186
+ loaded2 = yaml.load(dumped, Loader=yaml.UnsafeLoader)
187
+ tm.assert_frame_equal(df, loaded2)
188
+
189
+
190
+ @pytest.mark.parametrize("dependency", ["numpy", "dateutil"])
191
+ def test_missing_required_dependency(monkeypatch, dependency):
192
+ # GH#61030
193
+ original_import = __import__
194
+ mock_error = ImportError(f"Mock error for {dependency}")
195
+
196
+ def mock_import(name, *args, **kwargs):
197
+ if name == dependency:
198
+ raise mock_error
199
+ return original_import(name, *args, **kwargs)
200
+
201
+ monkeypatch.setattr("builtins.__import__", mock_import)
202
+
203
+ with pytest.raises(ImportError, match=dependency):
204
+ importlib.reload(importlib.import_module("pandas"))
205
+
206
+
207
+ def test_frame_setitem_dask_array_into_new_col(request):
208
+ # GH#47128
209
+
210
+ # dask sets "compute.use_numexpr" to False, so catch the current value
211
+ # and ensure to reset it afterwards to avoid impacting other tests
212
+ olduse = pd.get_option("compute.use_numexpr")
213
+
214
+ try:
215
+ dask = pytest.importorskip("dask")
216
+ da = pytest.importorskip("dask.array")
217
+ if Version(dask.__version__) <= Version("2025.1.0") and Version(
218
+ np.__version__
219
+ ) >= Version("2.1"):
220
+ request.applymarker(
221
+ pytest.mark.xfail(reason="loc.__setitem__ incorrectly mutated column c")
222
+ )
223
+
224
+ dda = da.array([1, 2])
225
+ df = DataFrame({"a": ["a", "b"]})
226
+ df["b"] = dda
227
+ df["c"] = dda
228
+ df.loc[[False, True], "b"] = 100
229
+ result = df.loc[[1], :]
230
+ expected = DataFrame({"a": ["b"], "b": [100], "c": [2]}, index=[1])
231
+ tm.assert_frame_equal(result, expected)
232
+ finally:
233
+ pd.set_option("compute.use_numexpr", olduse)
234
+
235
+
236
+ def test_pandas_priority():
237
+ # GH#48347
238
+
239
+ class MyClass:
240
+ __pandas_priority__ = 5000
241
+
242
+ def __radd__(self, other):
243
+ return self
244
+
245
+ left = MyClass()
246
+ right = Series(range(3))
247
+
248
+ assert right.__add__(left) is NotImplemented
249
+ assert right + left is left
250
+
251
+
252
+ @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
253
+ @pytest.mark.parametrize(
254
+ "box", [memoryview, partial(array.array, "i"), "dask", "xarray"]
255
+ )
256
+ def test_from_obscure_array(dtype, box):
257
+ # GH#24539 recognize e.g xarray, dask, ...
258
+ # Note: we dont do this for PeriodArray bc _from_sequence won't accept
259
+ # an array of integers
260
+ # TODO: could check with arraylike of Period objects
261
+ # GH#24539 recognize e.g xarray, dask, ...
262
+ arr = np.array([1, 2, 3], dtype=np.int64)
263
+ if box == "dask":
264
+ da = pytest.importorskip("dask.array")
265
+ data = da.array(arr)
266
+ elif box == "xarray":
267
+ xr = pytest.importorskip("xarray")
268
+ data = xr.DataArray(arr)
269
+ else:
270
+ data = box(arr)
271
+
272
+ func = {"M8[ns]": pd.to_datetime, "m8[ns]": pd.to_timedelta}[dtype]
273
+ result = func(arr).array
274
+ expected = func(data).array
275
+ tm.assert_equal(result, expected)
276
+
277
+ # Let's check the Indexes while we're here
278
+ idx_cls = {"M8[ns]": DatetimeIndex, "m8[ns]": TimedeltaIndex}[dtype]
279
+ result = idx_cls(arr)
280
+ expected = idx_cls(data)
281
+ tm.assert_index_equal(result, expected)
282
+
283
+
284
+ def test_xarray_coerce_unit():
285
+ # GH44053
286
+ xr = pytest.importorskip("xarray")
287
+
288
+ arr = xr.DataArray([1, 2, 3])
289
+ result = pd.to_datetime(arr, unit="ns")
290
+ expected = DatetimeIndex(
291
+ [
292
+ "1970-01-01 00:00:00.000000001",
293
+ "1970-01-01 00:00:00.000000002",
294
+ "1970-01-01 00:00:00.000000003",
295
+ ],
296
+ dtype="datetime64[ns]",
297
+ freq=None,
298
+ )
299
+ tm.assert_index_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_errors.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import pytest
4
+
5
+ from pandas.errors import (
6
+ AbstractMethodError,
7
+ Pandas4Warning,
8
+ Pandas5Warning,
9
+ PandasChangeWarning,
10
+ PandasDeprecationWarning,
11
+ PandasPendingDeprecationWarning,
12
+ UndefinedVariableError,
13
+ )
14
+
15
+ import pandas as pd
16
+ import pandas._testing as tm
17
+
18
+
19
+ @pytest.mark.parametrize(
20
+ "exc",
21
+ [
22
+ "AttributeConflictWarning",
23
+ "CSSWarning",
24
+ "CategoricalConversionWarning",
25
+ "ClosedFileError",
26
+ "DataError",
27
+ "DatabaseError",
28
+ "DtypeWarning",
29
+ "EmptyDataError",
30
+ "IncompatibilityWarning",
31
+ "IndexingError",
32
+ "InvalidColumnName",
33
+ "InvalidComparison",
34
+ "InvalidVersion",
35
+ "LossySetitemError",
36
+ "MergeError",
37
+ "NoBufferPresent",
38
+ "NumExprClobberingError",
39
+ "NumbaUtilError",
40
+ "OptionError",
41
+ "OutOfBoundsDatetime",
42
+ "ParserError",
43
+ "ParserWarning",
44
+ "PerformanceWarning",
45
+ "PossibleDataLossError",
46
+ "PossiblePrecisionLoss",
47
+ "PyperclipException",
48
+ "SpecificationError",
49
+ "UnsortedIndexError",
50
+ "UnsupportedFunctionCall",
51
+ "ValueLabelTypeMismatch",
52
+ ],
53
+ )
54
+ def test_exception_importable(exc):
55
+ from pandas import errors
56
+
57
+ err = getattr(errors, exc)
58
+ assert err is not None
59
+
60
+ # check that we can raise on them
61
+
62
+ msg = "^$"
63
+
64
+ with pytest.raises(err, match=msg):
65
+ raise err()
66
+
67
+
68
+ def test_catch_oob():
69
+ from pandas import errors
70
+
71
+ msg = "Cannot cast 1500-01-01 00:00:00 to unit='ns' without overflow"
72
+ with pytest.raises(errors.OutOfBoundsDatetime, match=msg):
73
+ pd.Timestamp("15000101").as_unit("ns")
74
+
75
+
76
+ @pytest.mark.parametrize("is_local", [True, False])
77
+ def test_catch_undefined_variable_error(is_local):
78
+ variable_name = "x"
79
+ if is_local:
80
+ msg = f"local variable '{variable_name}' is not defined"
81
+ else:
82
+ msg = f"name '{variable_name}' is not defined"
83
+
84
+ with pytest.raises(UndefinedVariableError, match=msg):
85
+ raise UndefinedVariableError(variable_name, is_local)
86
+
87
+
88
+ class Foo:
89
+ @classmethod
90
+ def classmethod(cls):
91
+ raise AbstractMethodError(cls, methodtype="classmethod")
92
+
93
+ @property
94
+ def property(self):
95
+ raise AbstractMethodError(self, methodtype="property")
96
+
97
+ def method(self):
98
+ raise AbstractMethodError(self)
99
+
100
+
101
+ def test_AbstractMethodError_classmethod():
102
+ xpr = "This classmethod must be defined in the concrete class Foo"
103
+ with pytest.raises(AbstractMethodError, match=xpr):
104
+ Foo.classmethod()
105
+
106
+ xpr = "This property must be defined in the concrete class Foo"
107
+ with pytest.raises(AbstractMethodError, match=xpr):
108
+ Foo().property
109
+
110
+ xpr = "This method must be defined in the concrete class Foo"
111
+ with pytest.raises(AbstractMethodError, match=xpr):
112
+ Foo().method()
113
+
114
+
115
+ @pytest.mark.parametrize(
116
+ "warn_category, catch_category",
117
+ [
118
+ (Pandas4Warning, PandasChangeWarning),
119
+ (Pandas4Warning, PandasDeprecationWarning),
120
+ (Pandas5Warning, PandasChangeWarning),
121
+ (Pandas5Warning, PandasPendingDeprecationWarning),
122
+ ],
123
+ )
124
+ def test_pandas_warnings(warn_category, catch_category):
125
+ # https://github.com/pandas-dev/pandas/pull/61468
126
+ with tm.assert_produces_warning(catch_category):
127
+ warnings.warn("test", category=warn_category)
128
+
129
+
130
+ @pytest.mark.parametrize(
131
+ "warn_category, filter_category",
132
+ [
133
+ (Pandas4Warning, PandasChangeWarning),
134
+ (Pandas4Warning, PandasDeprecationWarning),
135
+ (Pandas5Warning, PandasChangeWarning),
136
+ (Pandas5Warning, PandasPendingDeprecationWarning),
137
+ ],
138
+ )
139
+ def test_pandas_warnings_filter(warn_category, filter_category):
140
+ # https://github.com/pandas-dev/pandas/pull/61468
141
+ # Ensure users can suppress warnings.
142
+ with tm.assert_produces_warning(None), warnings.catch_warnings():
143
+ warnings.filterwarnings(category=filter_category, action="ignore")
144
+ warnings.warn("test", category=warn_category)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_expressions.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas.compat._optional import import_optional_dependency
8
+
9
+ from pandas import option_context
10
+ import pandas._testing as tm
11
+ from pandas.core.api import DataFrame
12
+ from pandas.core.computation import expressions as expr
13
+ from pandas.util.version import Version
14
+
15
+
16
+ @pytest.fixture
17
+ def _frame():
18
+ return DataFrame(
19
+ np.random.default_rng(2).standard_normal((10001, 4)),
20
+ columns=list("ABCD"),
21
+ dtype="float64",
22
+ )
23
+
24
+
25
+ @pytest.fixture
26
+ def _frame2():
27
+ return DataFrame(
28
+ np.random.default_rng(2).standard_normal((100, 4)),
29
+ columns=list("ABCD"),
30
+ dtype="float64",
31
+ )
32
+
33
+
34
+ @pytest.fixture
35
+ def _mixed(_frame):
36
+ return DataFrame(
37
+ {
38
+ "A": _frame["A"],
39
+ "B": _frame["B"].astype("float32"),
40
+ "C": _frame["C"].astype("int64"),
41
+ "D": _frame["D"].astype("int32"),
42
+ }
43
+ )
44
+
45
+
46
+ @pytest.fixture
47
+ def _mixed2(_frame2):
48
+ return DataFrame(
49
+ {
50
+ "A": _frame2["A"],
51
+ "B": _frame2["B"].astype("float32"),
52
+ "C": _frame2["C"].astype("int64"),
53
+ "D": _frame2["D"].astype("int32"),
54
+ }
55
+ )
56
+
57
+
58
+ @pytest.fixture
59
+ def _integer():
60
+ return DataFrame(
61
+ np.random.default_rng(2).integers(1, 100, size=(10001, 4)),
62
+ columns=list("ABCD"),
63
+ dtype="int64",
64
+ )
65
+
66
+
67
+ @pytest.fixture
68
+ def _integer_integers(_integer):
69
+ # integers to get a case with zeros
70
+ return _integer * np.random.default_rng(2).integers(0, 2, size=np.shape(_integer))
71
+
72
+
73
+ @pytest.fixture
74
+ def _integer2():
75
+ return DataFrame(
76
+ np.random.default_rng(2).integers(1, 100, size=(101, 4)),
77
+ columns=list("ABCD"),
78
+ dtype="int64",
79
+ )
80
+
81
+
82
+ @pytest.fixture
83
+ def _array(_frame):
84
+ return _frame["A"].to_numpy()
85
+
86
+
87
+ @pytest.fixture
88
+ def _array2(_frame2):
89
+ return _frame2["A"].to_numpy()
90
+
91
+
92
+ @pytest.fixture
93
+ def _array_mixed(_mixed):
94
+ return _mixed["D"].to_numpy()
95
+
96
+
97
+ @pytest.fixture
98
+ def _array_mixed2(_mixed2):
99
+ return _mixed2["D"].to_numpy()
100
+
101
+
102
+ @pytest.mark.skipif(not expr.USE_NUMEXPR, reason="not using numexpr")
103
+ class TestExpressions:
104
+ @staticmethod
105
+ def call_op(df, other, flex: bool, opname: str):
106
+ if flex:
107
+ op = lambda x, y: getattr(x, opname)(y)
108
+ op.__name__ = opname
109
+ else:
110
+ op = getattr(operator, opname)
111
+
112
+ with option_context("compute.use_numexpr", False):
113
+ expected = op(df, other)
114
+
115
+ expr.get_test_result()
116
+
117
+ result = op(df, other)
118
+ return result, expected
119
+
120
+ @pytest.mark.parametrize(
121
+ "fixture",
122
+ [
123
+ "_integer",
124
+ "_integer2",
125
+ "_integer_integers",
126
+ "_frame",
127
+ "_frame2",
128
+ "_mixed",
129
+ "_mixed2",
130
+ ],
131
+ )
132
+ @pytest.mark.parametrize("flex", [True, False])
133
+ @pytest.mark.parametrize(
134
+ "arith", ["add", "sub", "mul", "mod", "truediv", "floordiv"]
135
+ )
136
+ def test_run_arithmetic(self, request, fixture, flex, arith, monkeypatch):
137
+ df = request.getfixturevalue(fixture)
138
+ with monkeypatch.context() as m:
139
+ m.setattr(expr, "_MIN_ELEMENTS", 0)
140
+ result, expected = self.call_op(df, df, flex, arith)
141
+
142
+ if arith == "truediv":
143
+ assert all(x.kind == "f" for x in expected.dtypes.values)
144
+ tm.assert_equal(expected, result)
145
+
146
+ for i in range(len(df.columns)):
147
+ result, expected = self.call_op(
148
+ df.iloc[:, i], df.iloc[:, i], flex, arith
149
+ )
150
+ if arith == "truediv":
151
+ assert expected.dtype.kind == "f"
152
+ tm.assert_equal(expected, result)
153
+
154
+ @pytest.mark.parametrize(
155
+ "fixture",
156
+ [
157
+ "_integer",
158
+ "_integer2",
159
+ "_integer_integers",
160
+ "_frame",
161
+ "_frame2",
162
+ "_mixed",
163
+ "_mixed2",
164
+ ],
165
+ )
166
+ @pytest.mark.parametrize("flex", [True, False])
167
+ def test_run_binary(self, request, fixture, flex, comparison_op, monkeypatch):
168
+ """
169
+ tests solely that the result is the same whether or not numexpr is
170
+ enabled. Need to test whether the function does the correct thing
171
+ elsewhere.
172
+ """
173
+ df = request.getfixturevalue(fixture)
174
+ arith = comparison_op.__name__
175
+ with option_context("compute.use_numexpr", False):
176
+ other = df + 1
177
+
178
+ with monkeypatch.context() as m:
179
+ m.setattr(expr, "_MIN_ELEMENTS", 0)
180
+ expr.set_test_mode(True)
181
+
182
+ result, expected = self.call_op(df, other, flex, arith)
183
+
184
+ used_numexpr = expr.get_test_result()
185
+ assert used_numexpr, "Did not use numexpr as expected."
186
+ tm.assert_equal(expected, result)
187
+
188
+ for i in range(len(df.columns)):
189
+ binary_comp = other.iloc[:, i] + 1
190
+ self.call_op(df.iloc[:, i], binary_comp, flex, "add")
191
+
192
+ def test_invalid(self):
193
+ array = np.random.default_rng(2).standard_normal(1_000_001)
194
+ array2 = np.random.default_rng(2).standard_normal(100)
195
+
196
+ # no op
197
+ result = expr._can_use_numexpr(operator.add, None, array, array, "evaluate")
198
+ assert not result
199
+
200
+ # min elements
201
+ result = expr._can_use_numexpr(operator.add, "+", array2, array2, "evaluate")
202
+ assert not result
203
+
204
+ # ok, we only check on first part of expression
205
+ result = expr._can_use_numexpr(operator.add, "+", array, array2, "evaluate")
206
+ assert result
207
+
208
+ @pytest.mark.filterwarnings("ignore:invalid value encountered in:RuntimeWarning")
209
+ @pytest.mark.parametrize(
210
+ "opname,op_str",
211
+ [("add", "+"), ("sub", "-"), ("mul", "*"), ("truediv", "/"), ("pow", "**")],
212
+ )
213
+ @pytest.mark.parametrize(
214
+ "left_fix,right_fix", [("_array", "_array2"), ("_array_mixed", "_array_mixed2")]
215
+ )
216
+ def test_binary_ops(self, request, opname, op_str, left_fix, right_fix):
217
+ left = request.getfixturevalue(left_fix)
218
+ right = request.getfixturevalue(right_fix)
219
+
220
+ def testit(left, right, opname, op_str):
221
+ if opname == "pow":
222
+ left = np.abs(left)
223
+
224
+ op = getattr(operator, opname)
225
+
226
+ # array has 0s
227
+ result = expr.evaluate(op, left, left, use_numexpr=True)
228
+ expected = expr.evaluate(op, left, left, use_numexpr=False)
229
+ tm.assert_numpy_array_equal(result, expected)
230
+
231
+ result = expr._can_use_numexpr(op, op_str, right, right, "evaluate")
232
+ assert not result
233
+
234
+ with option_context("compute.use_numexpr", False):
235
+ testit(left, right, opname, op_str)
236
+
237
+ expr.set_numexpr_threads(1)
238
+ testit(left, right, opname, op_str)
239
+ expr.set_numexpr_threads()
240
+ testit(left, right, opname, op_str)
241
+
242
+ @pytest.mark.parametrize(
243
+ "left_fix,right_fix", [("_array", "_array2"), ("_array_mixed", "_array_mixed2")]
244
+ )
245
+ def test_comparison_ops(self, request, comparison_op, left_fix, right_fix):
246
+ left = request.getfixturevalue(left_fix)
247
+ right = request.getfixturevalue(right_fix)
248
+
249
+ def testit():
250
+ f12 = left + 1
251
+ f22 = right + 1
252
+
253
+ op = comparison_op
254
+
255
+ result = expr.evaluate(op, left, f12, use_numexpr=True)
256
+ expected = expr.evaluate(op, left, f12, use_numexpr=False)
257
+ tm.assert_numpy_array_equal(result, expected)
258
+
259
+ result = expr._can_use_numexpr(op, op, right, f22, "evaluate")
260
+ assert not result
261
+
262
+ with option_context("compute.use_numexpr", False):
263
+ testit()
264
+
265
+ expr.set_numexpr_threads(1)
266
+ testit()
267
+ expr.set_numexpr_threads()
268
+ testit()
269
+
270
+ @pytest.mark.parametrize("cond", [True, False])
271
+ @pytest.mark.parametrize("fixture", ["_frame", "_frame2", "_mixed", "_mixed2"])
272
+ def test_where(self, request, cond, fixture):
273
+ df = request.getfixturevalue(fixture)
274
+
275
+ def testit():
276
+ c = np.empty(df.shape, dtype=np.bool_)
277
+ c.fill(cond)
278
+ result = expr.where(c, df.values, df.values + 1)
279
+ expected = np.where(c, df.values, df.values + 1)
280
+ tm.assert_numpy_array_equal(result, expected)
281
+
282
+ with option_context("compute.use_numexpr", False):
283
+ testit()
284
+
285
+ expr.set_numexpr_threads(1)
286
+ testit()
287
+ expr.set_numexpr_threads()
288
+ testit()
289
+
290
+ @pytest.mark.parametrize(
291
+ "op_str,opname", [("/", "truediv"), ("//", "floordiv"), ("**", "pow")]
292
+ )
293
+ def test_bool_ops_raise_on_arithmetic(self, op_str, opname):
294
+ df = DataFrame(
295
+ {
296
+ "a": np.random.default_rng(2).random(10) > 0.5,
297
+ "b": np.random.default_rng(2).random(10) > 0.5,
298
+ }
299
+ )
300
+
301
+ msg = f"operator '{opname}' not implemented for bool dtypes"
302
+ f = getattr(operator, opname)
303
+ err_msg = re.escape(msg)
304
+
305
+ with pytest.raises(NotImplementedError, match=err_msg):
306
+ f(df, df)
307
+
308
+ with pytest.raises(NotImplementedError, match=err_msg):
309
+ f(df.a, df.b)
310
+
311
+ with pytest.raises(NotImplementedError, match=err_msg):
312
+ f(df.a, True)
313
+
314
+ with pytest.raises(NotImplementedError, match=err_msg):
315
+ f(False, df.a)
316
+
317
+ with pytest.raises(NotImplementedError, match=err_msg):
318
+ f(False, df)
319
+
320
+ with pytest.raises(NotImplementedError, match=err_msg):
321
+ f(df, True)
322
+
323
+ @pytest.mark.parametrize(
324
+ "op_str,opname", [("+", "add"), ("*", "mul"), ("-", "sub")]
325
+ )
326
+ def test_bool_ops_warn_on_arithmetic(self, op_str, opname, monkeypatch):
327
+ n = 10
328
+ df = DataFrame(
329
+ {
330
+ "a": np.random.default_rng(2).random(n) > 0.5,
331
+ "b": np.random.default_rng(2).random(n) > 0.5,
332
+ }
333
+ )
334
+
335
+ subs = {"+": "|", "*": "&", "-": "^"}
336
+ sub_funcs = {"|": "or_", "&": "and_", "^": "xor"}
337
+
338
+ f = getattr(operator, opname)
339
+ fe = getattr(operator, sub_funcs[subs[op_str]])
340
+
341
+ if op_str == "-":
342
+ # raises TypeError
343
+ return
344
+
345
+ msg = "operator is not supported by numexpr"
346
+ ne = import_optional_dependency("numexpr", errors="ignore")
347
+ warning = (
348
+ UserWarning
349
+ if ne
350
+ and op_str in {"+", "*"}
351
+ and Version(ne.__version__) < Version("2.13.1")
352
+ else None
353
+ )
354
+ with monkeypatch.context() as m:
355
+ m.setattr(expr, "_MIN_ELEMENTS", 5)
356
+ with option_context("compute.use_numexpr", True):
357
+ with tm.assert_produces_warning(warning, match=msg):
358
+ r = f(df, df)
359
+ e = fe(df, df)
360
+ tm.assert_frame_equal(r, e)
361
+
362
+ with tm.assert_produces_warning(warning, match=msg):
363
+ r = f(df.a, df.b)
364
+ e = fe(df.a, df.b)
365
+ tm.assert_series_equal(r, e)
366
+
367
+ with tm.assert_produces_warning(warning, match=msg):
368
+ r = f(df.a, True)
369
+ e = fe(df.a, True)
370
+ tm.assert_series_equal(r, e)
371
+
372
+ with tm.assert_produces_warning(warning, match=msg):
373
+ r = f(False, df.a)
374
+ e = fe(False, df.a)
375
+ tm.assert_series_equal(r, e)
376
+
377
+ with tm.assert_produces_warning(warning, match=msg):
378
+ r = f(False, df)
379
+ e = fe(False, df)
380
+ tm.assert_frame_equal(r, e)
381
+
382
+ with tm.assert_produces_warning(warning, match=msg):
383
+ r = f(df, True)
384
+ e = fe(df, True)
385
+ tm.assert_frame_equal(r, e)
386
+
387
+ @pytest.mark.parametrize(
388
+ "test_input,expected",
389
+ [
390
+ (
391
+ DataFrame(
392
+ [[0, 1, 2, "aa"], [0, 1, 2, "aa"]], columns=["a", "b", "c", "dtype"]
393
+ ),
394
+ DataFrame([[False, False], [False, False]], columns=["a", "dtype"]),
395
+ ),
396
+ (
397
+ DataFrame(
398
+ [[0, 3, 2, "aa"], [0, 4, 2, "aa"], [0, 1, 1, "bb"]],
399
+ columns=["a", "b", "c", "dtype"],
400
+ ),
401
+ DataFrame(
402
+ [[False, False], [False, False], [False, False]],
403
+ columns=["a", "dtype"],
404
+ ),
405
+ ),
406
+ ],
407
+ )
408
+ def test_bool_ops_column_name_dtype(self, test_input, expected):
409
+ # GH 22383 - .ne fails if columns containing column name 'dtype'
410
+ result = test_input.loc[:, ["a", "dtype"]].ne(test_input.loc[:, ["a", "dtype"]])
411
+ tm.assert_frame_equal(result, expected)
412
+
413
+ @pytest.mark.parametrize(
414
+ "arith", ("add", "sub", "mul", "mod", "truediv", "floordiv")
415
+ )
416
+ @pytest.mark.parametrize("axis", (0, 1))
417
+ def test_frame_series_axis(self, axis, arith, _frame, monkeypatch):
418
+ # GH#26736 Dataframe.floordiv(Series, axis=1) fails
419
+
420
+ df = _frame
421
+ if axis == 1:
422
+ other = df.iloc[0, :]
423
+ else:
424
+ other = df.iloc[:, 0]
425
+
426
+ with monkeypatch.context() as m:
427
+ m.setattr(expr, "_MIN_ELEMENTS", 0)
428
+
429
+ op_func = getattr(df, arith)
430
+
431
+ with option_context("compute.use_numexpr", False):
432
+ expected = op_func(other, axis=axis)
433
+
434
+ result = op_func(other, axis=axis)
435
+ tm.assert_frame_equal(expected, result)
436
+
437
+ @pytest.mark.parametrize(
438
+ "op",
439
+ [
440
+ "__mod__",
441
+ "__rmod__",
442
+ "__floordiv__",
443
+ "__rfloordiv__",
444
+ ],
445
+ )
446
+ @pytest.mark.parametrize("scalar", [-5, 5])
447
+ def test_python_semantics_with_numexpr_installed(
448
+ self, op, box_with_array, scalar, monkeypatch
449
+ ):
450
+ # https://github.com/pandas-dev/pandas/issues/36047
451
+ with monkeypatch.context() as m:
452
+ m.setattr(expr, "_MIN_ELEMENTS", 0)
453
+ data = np.arange(-50, 50)
454
+ obj = box_with_array(data)
455
+ method = getattr(obj, op)
456
+ result = method(scalar)
457
+
458
+ # compare result with numpy
459
+ with option_context("compute.use_numexpr", False):
460
+ expected = method(scalar)
461
+
462
+ tm.assert_equal(result, expected)
463
+
464
+ # compare result element-wise with Python
465
+ for i, elem in enumerate(data):
466
+ if box_with_array == DataFrame:
467
+ scalar_result = result.iloc[i, 0]
468
+ else:
469
+ scalar_result = result[i]
470
+ try:
471
+ expected = getattr(int(elem), op)(scalar)
472
+ except ZeroDivisionError:
473
+ pass
474
+ else:
475
+ assert scalar_result == expected
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_flags.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import pandas as pd
4
+
5
+
6
+ class TestFlags:
7
+ def test_equality(self):
8
+ a = pd.DataFrame().set_flags(allows_duplicate_labels=True).flags
9
+ b = pd.DataFrame().set_flags(allows_duplicate_labels=False).flags
10
+
11
+ assert a == a
12
+ assert b == b
13
+ assert a != b
14
+ assert a != 2
15
+
16
+ def test_set(self):
17
+ df = pd.DataFrame().set_flags(allows_duplicate_labels=True)
18
+ a = df.flags
19
+ a.allows_duplicate_labels = False
20
+ assert a.allows_duplicate_labels is False
21
+ a["allows_duplicate_labels"] = True
22
+ assert a.allows_duplicate_labels is True
23
+
24
+ def test_repr(self):
25
+ a = repr(pd.DataFrame({"A"}).set_flags(allows_duplicate_labels=True).flags)
26
+ assert a == "<Flags(allows_duplicate_labels=True)>"
27
+ a = repr(pd.DataFrame({"A"}).set_flags(allows_duplicate_labels=False).flags)
28
+ assert a == "<Flags(allows_duplicate_labels=False)>"
29
+
30
+ def test_obj_ref(self):
31
+ df = pd.DataFrame()
32
+ flags = df.flags
33
+ del df
34
+ with pytest.raises(ValueError, match="object has been deleted"):
35
+ flags.allows_duplicate_labels = True
36
+
37
+ def test_getitem(self):
38
+ df = pd.DataFrame()
39
+ flags = df.flags
40
+ assert flags["allows_duplicate_labels"] is True
41
+ flags["allows_duplicate_labels"] = False
42
+ assert flags["allows_duplicate_labels"] is False
43
+
44
+ with pytest.raises(KeyError, match="a"):
45
+ flags["a"]
46
+
47
+ with pytest.raises(ValueError, match="a"):
48
+ flags["a"] = 10
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_multilevel.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas as pd
7
+ from pandas import (
8
+ ArrowDtype,
9
+ DataFrame,
10
+ MultiIndex,
11
+ Series,
12
+ )
13
+ import pandas._testing as tm
14
+
15
+
16
+ class TestMultiLevel:
17
+ def test_reindex_level(self, multiindex_year_month_day_dataframe_random_data):
18
+ # axis=0
19
+ ymd = multiindex_year_month_day_dataframe_random_data
20
+
21
+ month_sums = ymd.groupby("month").sum()
22
+ result = month_sums.reindex(ymd.index, level=1)
23
+ expected = ymd.groupby(level="month").transform("sum")
24
+
25
+ tm.assert_frame_equal(result, expected)
26
+
27
+ # Series
28
+ result = month_sums["A"].reindex(ymd.index, level=1)
29
+ expected = ymd["A"].groupby(level="month").transform("sum")
30
+ tm.assert_series_equal(result, expected, check_names=False)
31
+
32
+ def test_reindex(self, multiindex_dataframe_random_data):
33
+ frame = multiindex_dataframe_random_data
34
+
35
+ expected = frame.iloc[[0, 3]]
36
+ reindexed = frame.loc[[("foo", "one"), ("bar", "one")]]
37
+ tm.assert_frame_equal(reindexed, expected)
38
+
39
+ def test_reindex_preserve_levels(
40
+ self, multiindex_year_month_day_dataframe_random_data
41
+ ):
42
+ ymd = multiindex_year_month_day_dataframe_random_data
43
+
44
+ new_index = ymd.index[::10]
45
+ chunk = ymd.reindex(new_index)
46
+ assert chunk.index.is_(new_index)
47
+
48
+ chunk = ymd.loc[new_index]
49
+ assert chunk.index.equals(new_index)
50
+
51
+ ymdT = ymd.T
52
+ chunk = ymdT.reindex(columns=new_index)
53
+ assert chunk.columns.is_(new_index)
54
+
55
+ chunk = ymdT.loc[:, new_index]
56
+ assert chunk.columns.equals(new_index)
57
+
58
+ def test_groupby_transform(self, multiindex_dataframe_random_data):
59
+ frame = multiindex_dataframe_random_data
60
+
61
+ s = frame["A"]
62
+ grouper = s.index.get_level_values(0)
63
+
64
+ grouped = s.groupby(grouper, group_keys=False)
65
+
66
+ applied = grouped.apply(lambda x: x * 2)
67
+ expected = grouped.transform(lambda x: x * 2)
68
+ result = applied.reindex(expected.index)
69
+ tm.assert_series_equal(result, expected, check_names=False)
70
+
71
+ def test_groupby_corner(self):
72
+ midx = MultiIndex(
73
+ levels=[["foo"], ["bar"], ["baz"]],
74
+ codes=[[0], [0], [0]],
75
+ names=["one", "two", "three"],
76
+ )
77
+ df = DataFrame(
78
+ [np.random.default_rng(2).random(4)],
79
+ columns=["a", "b", "c", "d"],
80
+ index=midx,
81
+ )
82
+ # should work
83
+ df.groupby(level="three")
84
+
85
+ def test_setitem_with_expansion_multiindex_columns(
86
+ self, multiindex_year_month_day_dataframe_random_data
87
+ ):
88
+ ymd = multiindex_year_month_day_dataframe_random_data
89
+
90
+ df = ymd[:5].T
91
+ df[2000, 1, 10] = df[2000, 1, 7]
92
+ assert isinstance(df.columns, MultiIndex)
93
+ assert (df[2000, 1, 10] == df[2000, 1, 7]).all()
94
+
95
+ def test_alignment(self):
96
+ x = Series(
97
+ data=[1, 2, 3], index=MultiIndex.from_tuples([("A", 1), ("A", 2), ("B", 3)])
98
+ )
99
+
100
+ y = Series(
101
+ data=[4, 5, 6], index=MultiIndex.from_tuples([("Z", 1), ("Z", 2), ("B", 3)])
102
+ )
103
+
104
+ res = x - y
105
+ exp_index = x.index.union(y.index)
106
+ exp = x.reindex(exp_index) - y.reindex(exp_index)
107
+ tm.assert_series_equal(res, exp)
108
+
109
+ # hit non-monotonic code path
110
+ res = x[::-1] - y[::-1]
111
+ exp_index = x.index.union(y.index)
112
+ exp = x.reindex(exp_index) - y.reindex(exp_index)
113
+ tm.assert_series_equal(res, exp)
114
+
115
+ def test_groupby_multilevel(self, multiindex_year_month_day_dataframe_random_data):
116
+ ymd = multiindex_year_month_day_dataframe_random_data
117
+
118
+ result = ymd.groupby(level=[0, 1]).mean()
119
+
120
+ k1 = ymd.index.get_level_values(0)
121
+ k2 = ymd.index.get_level_values(1)
122
+
123
+ expected = ymd.groupby([k1, k2]).mean()
124
+
125
+ tm.assert_frame_equal(result, expected)
126
+ assert result.index.names == ymd.index.names[:2]
127
+
128
+ result2 = ymd.groupby(level=ymd.index.names[:2]).mean()
129
+ tm.assert_frame_equal(result, result2)
130
+
131
+ def test_multilevel_consolidate(self):
132
+ index = MultiIndex.from_tuples(
133
+ [("foo", "one"), ("foo", "two"), ("bar", "one"), ("bar", "two")]
134
+ )
135
+ df = DataFrame(
136
+ np.random.default_rng(2).standard_normal((4, 4)), index=index, columns=index
137
+ )
138
+ df["Totals", ""] = df.sum(axis=1)
139
+ df = df._consolidate()
140
+
141
+ def test_level_with_tuples(self):
142
+ index = MultiIndex(
143
+ levels=[[("foo", "bar", 0), ("foo", "baz", 0), ("foo", "qux", 0)], [0, 1]],
144
+ codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
145
+ )
146
+
147
+ series = Series(np.random.default_rng(2).standard_normal(6), index=index)
148
+ frame = DataFrame(np.random.default_rng(2).standard_normal((6, 4)), index=index)
149
+
150
+ result = series[("foo", "bar", 0)]
151
+ result2 = series.loc[("foo", "bar", 0)]
152
+ expected = series[:2]
153
+ expected.index = expected.index.droplevel(0)
154
+ tm.assert_series_equal(result, expected)
155
+ tm.assert_series_equal(result2, expected)
156
+
157
+ with pytest.raises(KeyError, match=r"^\(\('foo', 'bar', 0\), 2\)$"):
158
+ series[("foo", "bar", 0), 2]
159
+
160
+ result = frame.loc[("foo", "bar", 0)]
161
+ result2 = frame.xs(("foo", "bar", 0))
162
+ expected = frame[:2]
163
+ expected.index = expected.index.droplevel(0)
164
+ tm.assert_frame_equal(result, expected)
165
+ tm.assert_frame_equal(result2, expected)
166
+
167
+ index = MultiIndex(
168
+ levels=[[("foo", "bar"), ("foo", "baz"), ("foo", "qux")], [0, 1]],
169
+ codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
170
+ )
171
+
172
+ series = Series(np.random.default_rng(2).standard_normal(6), index=index)
173
+ frame = DataFrame(np.random.default_rng(2).standard_normal((6, 4)), index=index)
174
+
175
+ result = series[("foo", "bar")]
176
+ result2 = series.loc[("foo", "bar")]
177
+ expected = series[:2]
178
+ expected.index = expected.index.droplevel(0)
179
+ tm.assert_series_equal(result, expected)
180
+ tm.assert_series_equal(result2, expected)
181
+
182
+ result = frame.loc[("foo", "bar")]
183
+ result2 = frame.xs(("foo", "bar"))
184
+ expected = frame[:2]
185
+ expected.index = expected.index.droplevel(0)
186
+ tm.assert_frame_equal(result, expected)
187
+ tm.assert_frame_equal(result2, expected)
188
+
189
+ def test_reindex_level_partial_selection(self, multiindex_dataframe_random_data):
190
+ frame = multiindex_dataframe_random_data
191
+
192
+ result = frame.reindex(["foo", "qux"], level=0)
193
+ expected = frame.iloc[[0, 1, 2, 7, 8, 9]]
194
+ tm.assert_frame_equal(result, expected)
195
+
196
+ result = frame.T.reindex(["foo", "qux"], axis=1, level=0)
197
+ tm.assert_frame_equal(result, expected.T)
198
+
199
+ result = frame.loc[["foo", "qux"]]
200
+ tm.assert_frame_equal(result, expected)
201
+
202
+ result = frame["A"].loc[["foo", "qux"]]
203
+ tm.assert_series_equal(result, expected["A"])
204
+
205
+ result = frame.T.loc[:, ["foo", "qux"]]
206
+ tm.assert_frame_equal(result, expected.T)
207
+
208
+ @pytest.mark.parametrize("d", [4, "d"])
209
+ def test_empty_frame_groupby_dtypes_consistency(self, d):
210
+ # GH 20888
211
+ group_keys = ["a", "b", "c"]
212
+ df = DataFrame({"a": [1], "b": [2], "c": [3], "d": [d]})
213
+
214
+ g = df[df.a == 2].groupby(group_keys)
215
+ result = g.first().index
216
+ expected = MultiIndex(
217
+ levels=[[1], [2], [3]], codes=[[], [], []], names=["a", "b", "c"]
218
+ )
219
+
220
+ tm.assert_index_equal(result, expected)
221
+
222
+ def test_duplicate_groupby_issues(self):
223
+ idx_tp = [
224
+ ("600809", "20061231"),
225
+ ("600809", "20070331"),
226
+ ("600809", "20070630"),
227
+ ("600809", "20070331"),
228
+ ]
229
+ dt = ["demo", "demo", "demo", "demo"]
230
+
231
+ idx = MultiIndex.from_tuples(idx_tp, names=["STK_ID", "RPT_Date"])
232
+ s = Series(dt, index=idx)
233
+
234
+ result = s.groupby(s.index).first()
235
+ assert len(result) == 3
236
+
237
+ def test_subsets_multiindex_dtype(self):
238
+ # GH 20757
239
+ data = [["x", 1]]
240
+ columns = [("a", "b", np.nan), ("a", "c", 0.0)]
241
+ df = DataFrame(data, columns=MultiIndex.from_tuples(columns))
242
+ expected = df.dtypes.a.b
243
+ result = df.a.b.dtypes
244
+ tm.assert_series_equal(result, expected)
245
+
246
+ def test_datetime_object_multiindex(self):
247
+ data_dic = {
248
+ (0, datetime.date(2018, 3, 3)): {"A": 1, "B": 10},
249
+ (0, datetime.date(2018, 3, 4)): {"A": 2, "B": 11},
250
+ (1, datetime.date(2018, 3, 3)): {"A": 3, "B": 12},
251
+ (1, datetime.date(2018, 3, 4)): {"A": 4, "B": 13},
252
+ }
253
+ result = DataFrame.from_dict(data_dic, orient="index")
254
+ data = {"A": [1, 2, 3, 4], "B": [10, 11, 12, 13]}
255
+ index = [
256
+ [0, 0, 1, 1],
257
+ [
258
+ datetime.date(2018, 3, 3),
259
+ datetime.date(2018, 3, 4),
260
+ datetime.date(2018, 3, 3),
261
+ datetime.date(2018, 3, 4),
262
+ ],
263
+ ]
264
+ expected = DataFrame(data=data, index=index)
265
+
266
+ tm.assert_frame_equal(result, expected)
267
+
268
+ def test_multiindex_with_na(self):
269
+ df = DataFrame(
270
+ [
271
+ ["A", np.nan, 1.23, 4.56],
272
+ ["A", "G", 1.23, 4.56],
273
+ ["A", "D", 9.87, 10.54],
274
+ ],
275
+ columns=["pivot_0", "pivot_1", "col_1", "col_2"],
276
+ ).set_index(["pivot_0", "pivot_1"])
277
+
278
+ df.at[("A", "F"), "col_2"] = 0.0
279
+
280
+ expected = DataFrame(
281
+ [
282
+ ["A", np.nan, 1.23, 4.56],
283
+ ["A", "G", 1.23, 4.56],
284
+ ["A", "D", 9.87, 10.54],
285
+ ["A", "F", np.nan, 0.0],
286
+ ],
287
+ columns=["pivot_0", "pivot_1", "col_1", "col_2"],
288
+ ).set_index(["pivot_0", "pivot_1"])
289
+
290
+ tm.assert_frame_equal(df, expected)
291
+
292
+ @pytest.mark.parametrize("na", [None, np.nan])
293
+ def test_multiindex_insert_level_with_na(self, na):
294
+ # GH 59003
295
+ df = DataFrame([0], columns=[["A"], ["B"]])
296
+ df[na, "B"] = 1
297
+ tm.assert_frame_equal(df[na], DataFrame([1], columns=["B"]))
298
+
299
+ def test_multiindex_dt_with_nan(self):
300
+ # GH#60388
301
+ df = DataFrame(
302
+ [
303
+ [1, np.nan, 5, np.nan],
304
+ [2, np.nan, 6, np.nan],
305
+ [np.nan, 3, np.nan, 7],
306
+ [np.nan, 4, np.nan, 8],
307
+ ],
308
+ index=Series(["a", "b", "c", "d"], dtype=object, name="sub"),
309
+ columns=MultiIndex.from_product(
310
+ [
311
+ ["value1", "value2"],
312
+ [datetime.datetime(2024, 11, 1), datetime.datetime(2024, 11, 2)],
313
+ ],
314
+ names=[None, "Date"],
315
+ ),
316
+ )
317
+ df = df.reset_index()
318
+ result = df[df.columns[0]]
319
+ expected = Series(["a", "b", "c", "d"], name=("sub", np.nan))
320
+ tm.assert_series_equal(result, expected)
321
+
322
+ @pytest.mark.filterwarnings("ignore:Passing a BlockManager:DeprecationWarning")
323
+ def test_multiindex_with_pyarrow_categorical(self):
324
+ # GH#53051
325
+ pa = pytest.importorskip("pyarrow")
326
+
327
+ df = DataFrame(
328
+ {"string_column": ["A", "B", "C"], "number_column": [1, 2, 3]}
329
+ ).astype(
330
+ {
331
+ "string_column": ArrowDtype(pa.dictionary(pa.int32(), pa.string())),
332
+ "number_column": "float[pyarrow]",
333
+ }
334
+ )
335
+
336
+ df = df.set_index(["string_column", "number_column"])
337
+
338
+ df_expected = DataFrame(
339
+ index=MultiIndex.from_arrays(
340
+ [["A", "B", "C"], [1, 2, 3]], names=["string_column", "number_column"]
341
+ )
342
+ )
343
+ tm.assert_frame_equal(
344
+ df,
345
+ df_expected,
346
+ check_index_type=False,
347
+ check_column_type=False,
348
+ )
349
+
350
+
351
+ class TestSorted:
352
+ """everything you wanted to test about sorting"""
353
+
354
+ def test_sort_non_lexsorted(self):
355
+ # degenerate case where we sort but don't
356
+ # have a satisfying result :<
357
+ # GH 15797
358
+ idx = MultiIndex(
359
+ [["A", "B", "C"], ["c", "b", "a"]], [[0, 1, 2, 0, 1, 2], [0, 2, 1, 1, 0, 2]]
360
+ )
361
+
362
+ df = DataFrame({"col": range(len(idx))}, index=idx, dtype="int64")
363
+ assert df.index.is_monotonic_increasing is False
364
+
365
+ sorted = df.sort_index()
366
+ assert sorted.index.is_monotonic_increasing is True
367
+
368
+ expected = DataFrame(
369
+ {"col": [1, 4, 5, 2]},
370
+ index=MultiIndex.from_tuples(
371
+ [("B", "a"), ("B", "c"), ("C", "a"), ("C", "b")]
372
+ ),
373
+ dtype="int64",
374
+ )
375
+ result = sorted.loc[pd.IndexSlice["B":"C", "a":"c"], :]
376
+ tm.assert_frame_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_nanops.py ADDED
@@ -0,0 +1,1333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas.util._test_decorators as td
7
+
8
+ from pandas.core.dtypes.common import is_integer_dtype
9
+
10
+ import pandas as pd
11
+ from pandas import (
12
+ Series,
13
+ isna,
14
+ )
15
+ import pandas._testing as tm
16
+ from pandas.core import nanops
17
+
18
+ use_bn = nanops._USE_BOTTLENECK
19
+
20
+
21
+ @pytest.fixture
22
+ def disable_bottleneck(monkeypatch):
23
+ with monkeypatch.context() as m:
24
+ m.setattr(nanops, "_USE_BOTTLENECK", False)
25
+ yield
26
+
27
+
28
+ @pytest.fixture
29
+ def arr_shape():
30
+ return 11, 7
31
+
32
+
33
+ @pytest.fixture
34
+ def arr_float(arr_shape):
35
+ return np.random.default_rng(2).standard_normal(arr_shape)
36
+
37
+
38
+ @pytest.fixture
39
+ def arr_complex(arr_float):
40
+ return arr_float + arr_float * 1j
41
+
42
+
43
+ @pytest.fixture
44
+ def arr_int(arr_shape):
45
+ return np.random.default_rng(2).integers(-10, 10, arr_shape)
46
+
47
+
48
+ @pytest.fixture
49
+ def arr_bool(arr_shape):
50
+ return np.random.default_rng(2).integers(0, 2, arr_shape) == 0
51
+
52
+
53
+ @pytest.fixture
54
+ def arr_str(arr_float):
55
+ return np.abs(arr_float).astype("S")
56
+
57
+
58
+ @pytest.fixture
59
+ def arr_utf(arr_float):
60
+ return np.abs(arr_float).astype("U")
61
+
62
+
63
+ @pytest.fixture
64
+ def arr_date(arr_shape):
65
+ return np.random.default_rng(2).integers(0, 20000, arr_shape).astype("M8[ns]")
66
+
67
+
68
+ @pytest.fixture
69
+ def arr_tdelta(arr_shape):
70
+ return np.random.default_rng(2).integers(0, 20000, arr_shape).astype("m8[ns]")
71
+
72
+
73
+ @pytest.fixture
74
+ def arr_nan(arr_shape):
75
+ return np.tile(np.nan, arr_shape)
76
+
77
+
78
+ @pytest.fixture
79
+ def arr_float_nan(arr_float, arr_nan):
80
+ return np.vstack([arr_float, arr_nan])
81
+
82
+
83
+ @pytest.fixture
84
+ def arr_nan_float1(arr_nan, arr_float):
85
+ return np.vstack([arr_nan, arr_float])
86
+
87
+
88
+ @pytest.fixture
89
+ def arr_nan_nan(arr_nan):
90
+ return np.vstack([arr_nan, arr_nan])
91
+
92
+
93
+ @pytest.fixture
94
+ def arr_inf(arr_float):
95
+ return arr_float * np.inf
96
+
97
+
98
+ @pytest.fixture
99
+ def arr_float_inf(arr_float, arr_inf):
100
+ return np.vstack([arr_float, arr_inf])
101
+
102
+
103
+ @pytest.fixture
104
+ def arr_nan_inf(arr_nan, arr_inf):
105
+ return np.vstack([arr_nan, arr_inf])
106
+
107
+
108
+ @pytest.fixture
109
+ def arr_float_nan_inf(arr_float, arr_nan, arr_inf):
110
+ return np.vstack([arr_float, arr_nan, arr_inf])
111
+
112
+
113
+ @pytest.fixture
114
+ def arr_nan_nan_inf(arr_nan, arr_inf):
115
+ return np.vstack([arr_nan, arr_nan, arr_inf])
116
+
117
+
118
+ @pytest.fixture
119
+ def arr_obj(
120
+ arr_float, arr_int, arr_bool, arr_complex, arr_str, arr_utf, arr_date, arr_tdelta
121
+ ):
122
+ return np.vstack(
123
+ [
124
+ arr_float.astype("O"),
125
+ arr_int.astype("O"),
126
+ arr_bool.astype("O"),
127
+ arr_complex.astype("O"),
128
+ arr_str.astype("O"),
129
+ arr_utf.astype("O"),
130
+ arr_date.astype("O"),
131
+ arr_tdelta.astype("O"),
132
+ ]
133
+ )
134
+
135
+
136
+ @pytest.fixture
137
+ def arr_nan_nanj(arr_nan):
138
+ with np.errstate(invalid="ignore"):
139
+ return arr_nan + arr_nan * 1j
140
+
141
+
142
+ @pytest.fixture
143
+ def arr_complex_nan(arr_complex, arr_nan_nanj):
144
+ with np.errstate(invalid="ignore"):
145
+ return np.vstack([arr_complex, arr_nan_nanj])
146
+
147
+
148
+ @pytest.fixture
149
+ def arr_nan_infj(arr_inf):
150
+ with np.errstate(invalid="ignore"):
151
+ return arr_inf * 1j
152
+
153
+
154
+ @pytest.fixture
155
+ def arr_complex_nan_infj(arr_complex, arr_nan_infj):
156
+ with np.errstate(invalid="ignore"):
157
+ return np.vstack([arr_complex, arr_nan_infj])
158
+
159
+
160
+ @pytest.fixture
161
+ def arr_float_1d(arr_float):
162
+ return arr_float[:, 0]
163
+
164
+
165
+ @pytest.fixture
166
+ def arr_nan_1d(arr_nan):
167
+ return arr_nan[:, 0]
168
+
169
+
170
+ @pytest.fixture
171
+ def arr_float_nan_1d(arr_float_nan):
172
+ return arr_float_nan[:, 0]
173
+
174
+
175
+ @pytest.fixture
176
+ def arr_float1_nan_1d(arr_float1_nan):
177
+ return arr_float1_nan[:, 0]
178
+
179
+
180
+ @pytest.fixture
181
+ def arr_nan_float1_1d(arr_nan_float1):
182
+ return arr_nan_float1[:, 0]
183
+
184
+
185
+ class TestnanopsDataFrame:
186
+ def setup_method(self):
187
+ nanops._USE_BOTTLENECK = False
188
+
189
+ arr_shape = (11, 7)
190
+
191
+ self.arr_float = np.random.default_rng(2).standard_normal(arr_shape)
192
+ self.arr_float1 = np.random.default_rng(2).standard_normal(arr_shape)
193
+ self.arr_complex = self.arr_float + self.arr_float1 * 1j
194
+ self.arr_int = np.random.default_rng(2).integers(-10, 10, arr_shape)
195
+ self.arr_bool = np.random.default_rng(2).integers(0, 2, arr_shape) == 0
196
+ self.arr_str = np.abs(self.arr_float).astype("S")
197
+ self.arr_utf = np.abs(self.arr_float).astype("U")
198
+ self.arr_date = (
199
+ np.random.default_rng(2).integers(0, 20000, arr_shape).astype("M8[ns]")
200
+ )
201
+ self.arr_tdelta = (
202
+ np.random.default_rng(2).integers(0, 20000, arr_shape).astype("m8[ns]")
203
+ )
204
+
205
+ self.arr_nan = np.tile(np.nan, arr_shape)
206
+ self.arr_float_nan = np.vstack([self.arr_float, self.arr_nan])
207
+ self.arr_float1_nan = np.vstack([self.arr_float1, self.arr_nan])
208
+ self.arr_nan_float1 = np.vstack([self.arr_nan, self.arr_float1])
209
+ self.arr_nan_nan = np.vstack([self.arr_nan, self.arr_nan])
210
+
211
+ self.arr_inf = self.arr_float * np.inf
212
+ self.arr_float_inf = np.vstack([self.arr_float, self.arr_inf])
213
+
214
+ self.arr_nan_inf = np.vstack([self.arr_nan, self.arr_inf])
215
+ self.arr_float_nan_inf = np.vstack([self.arr_float, self.arr_nan, self.arr_inf])
216
+ self.arr_nan_nan_inf = np.vstack([self.arr_nan, self.arr_nan, self.arr_inf])
217
+ self.arr_obj = np.vstack(
218
+ [
219
+ self.arr_float.astype("O"),
220
+ self.arr_int.astype("O"),
221
+ self.arr_bool.astype("O"),
222
+ self.arr_complex.astype("O"),
223
+ self.arr_str.astype("O"),
224
+ self.arr_utf.astype("O"),
225
+ self.arr_date.astype("O"),
226
+ self.arr_tdelta.astype("O"),
227
+ ]
228
+ )
229
+
230
+ with np.errstate(invalid="ignore"):
231
+ self.arr_nan_nanj = self.arr_nan + self.arr_nan * 1j
232
+ self.arr_complex_nan = np.vstack([self.arr_complex, self.arr_nan_nanj])
233
+
234
+ self.arr_nan_infj = self.arr_inf * 1j
235
+ self.arr_complex_nan_infj = np.vstack([self.arr_complex, self.arr_nan_infj])
236
+
237
+ self.arr_float_2d = self.arr_float
238
+ self.arr_float1_2d = self.arr_float1
239
+
240
+ self.arr_nan_2d = self.arr_nan
241
+ self.arr_float_nan_2d = self.arr_float_nan
242
+ self.arr_float1_nan_2d = self.arr_float1_nan
243
+ self.arr_nan_float1_2d = self.arr_nan_float1
244
+
245
+ self.arr_float_1d = self.arr_float[:, 0]
246
+ self.arr_float1_1d = self.arr_float1[:, 0]
247
+
248
+ self.arr_nan_1d = self.arr_nan[:, 0]
249
+ self.arr_float_nan_1d = self.arr_float_nan[:, 0]
250
+ self.arr_float1_nan_1d = self.arr_float1_nan[:, 0]
251
+ self.arr_nan_float1_1d = self.arr_nan_float1[:, 0]
252
+
253
+ def teardown_method(self):
254
+ nanops._USE_BOTTLENECK = use_bn
255
+
256
+ def check_results(self, targ, res, axis, check_dtype=True):
257
+ res = getattr(res, "asm8", res)
258
+
259
+ if (
260
+ axis != 0
261
+ and hasattr(targ, "shape")
262
+ and targ.ndim
263
+ and targ.shape != res.shape
264
+ ):
265
+ res = np.split(res, [targ.shape[0]], axis=0)[0]
266
+
267
+ try:
268
+ tm.assert_almost_equal(targ, res, check_dtype=check_dtype)
269
+ except AssertionError:
270
+ # handle timedelta dtypes
271
+ if hasattr(targ, "dtype") and targ.dtype == "m8[ns]":
272
+ raise
273
+
274
+ # There are sometimes rounding errors with
275
+ # complex and object dtypes.
276
+ # If it isn't one of those, re-raise the error.
277
+ if not hasattr(res, "dtype") or res.dtype.kind not in ["c", "O"]:
278
+ raise
279
+ # convert object dtypes to something that can be split into
280
+ # real and imaginary parts
281
+ if res.dtype.kind == "O":
282
+ if targ.dtype.kind != "O":
283
+ res = res.astype(targ.dtype)
284
+ else:
285
+ cast_dtype = "c16" if hasattr(np, "complex128") else "f8"
286
+ res = res.astype(cast_dtype)
287
+ targ = targ.astype(cast_dtype)
288
+ # there should never be a case where numpy returns an object
289
+ # but nanops doesn't, so make that an exception
290
+ elif targ.dtype.kind == "O":
291
+ raise
292
+ tm.assert_almost_equal(np.real(targ), np.real(res), check_dtype=check_dtype)
293
+ tm.assert_almost_equal(np.imag(targ), np.imag(res), check_dtype=check_dtype)
294
+
295
+ def check_fun_data(
296
+ self,
297
+ testfunc,
298
+ targfunc,
299
+ testar,
300
+ testarval,
301
+ targarval,
302
+ skipna,
303
+ check_dtype=True,
304
+ empty_targfunc=None,
305
+ **kwargs,
306
+ ):
307
+ for axis in [*list(range(targarval.ndim)), None]:
308
+ targartempval = targarval if skipna else testarval
309
+ if skipna and empty_targfunc and isna(targartempval).all():
310
+ targ = empty_targfunc(targartempval, axis=axis, **kwargs)
311
+ else:
312
+ targ = targfunc(targartempval, axis=axis, **kwargs)
313
+
314
+ if targartempval.dtype == object and (
315
+ targfunc is np.any or targfunc is np.all
316
+ ):
317
+ # GH#12863 the numpy functions will retain e.g. floatiness
318
+ if isinstance(targ, np.ndarray):
319
+ targ = targ.astype(bool)
320
+ else:
321
+ targ = bool(targ)
322
+
323
+ if testfunc.__name__ in ["nanargmax", "nanargmin"] and (
324
+ testar.startswith("arr_nan")
325
+ or (testar.endswith("nan") and (not skipna or axis == 1))
326
+ ):
327
+ with pytest.raises(ValueError, match="Encountered .* NA value"):
328
+ testfunc(testarval, axis=axis, skipna=skipna, **kwargs)
329
+ return
330
+ res = testfunc(testarval, axis=axis, skipna=skipna, **kwargs)
331
+
332
+ if (
333
+ isinstance(targ, np.complex128)
334
+ and isinstance(res, float)
335
+ and np.isnan(targ)
336
+ and np.isnan(res)
337
+ ):
338
+ # GH#18463
339
+ targ = res
340
+
341
+ self.check_results(targ, res, axis, check_dtype=check_dtype)
342
+ if skipna:
343
+ res = testfunc(testarval, axis=axis, **kwargs)
344
+ self.check_results(targ, res, axis, check_dtype=check_dtype)
345
+ if axis is None:
346
+ res = testfunc(testarval, skipna=skipna, **kwargs)
347
+ self.check_results(targ, res, axis, check_dtype=check_dtype)
348
+ if skipna and axis is None:
349
+ res = testfunc(testarval, **kwargs)
350
+ self.check_results(targ, res, axis, check_dtype=check_dtype)
351
+
352
+ if testarval.ndim <= 1:
353
+ return
354
+
355
+ # Recurse on lower-dimension
356
+ testarval2 = np.take(testarval, 0, axis=-1)
357
+ targarval2 = np.take(targarval, 0, axis=-1)
358
+ self.check_fun_data(
359
+ testfunc,
360
+ targfunc,
361
+ testar,
362
+ testarval2,
363
+ targarval2,
364
+ skipna=skipna,
365
+ check_dtype=check_dtype,
366
+ empty_targfunc=empty_targfunc,
367
+ **kwargs,
368
+ )
369
+
370
+ def check_fun(
371
+ self, testfunc, targfunc, testar, skipna, empty_targfunc=None, **kwargs
372
+ ):
373
+ targar = testar
374
+ if testar.endswith("_nan") and hasattr(self, testar[:-4]):
375
+ targar = testar[:-4]
376
+
377
+ testarval = getattr(self, testar)
378
+ targarval = getattr(self, targar)
379
+ self.check_fun_data(
380
+ testfunc,
381
+ targfunc,
382
+ testar,
383
+ testarval,
384
+ targarval,
385
+ skipna=skipna,
386
+ empty_targfunc=empty_targfunc,
387
+ **kwargs,
388
+ )
389
+
390
+ def check_funs(
391
+ self,
392
+ testfunc,
393
+ targfunc,
394
+ skipna,
395
+ allow_complex=True,
396
+ allow_all_nan=True,
397
+ allow_date=True,
398
+ allow_tdelta=True,
399
+ allow_obj=True,
400
+ **kwargs,
401
+ ):
402
+ self.check_fun(testfunc, targfunc, "arr_float", skipna, **kwargs)
403
+ self.check_fun(testfunc, targfunc, "arr_float_nan", skipna, **kwargs)
404
+ self.check_fun(testfunc, targfunc, "arr_int", skipna, **kwargs)
405
+ self.check_fun(testfunc, targfunc, "arr_bool", skipna, **kwargs)
406
+ objs = [
407
+ self.arr_float.astype("O"),
408
+ self.arr_int.astype("O"),
409
+ self.arr_bool.astype("O"),
410
+ ]
411
+
412
+ if allow_all_nan:
413
+ self.check_fun(testfunc, targfunc, "arr_nan", skipna, **kwargs)
414
+
415
+ if allow_complex:
416
+ self.check_fun(testfunc, targfunc, "arr_complex", skipna, **kwargs)
417
+ self.check_fun(testfunc, targfunc, "arr_complex_nan", skipna, **kwargs)
418
+ if allow_all_nan:
419
+ self.check_fun(testfunc, targfunc, "arr_nan_nanj", skipna, **kwargs)
420
+ objs += [self.arr_complex.astype("O")]
421
+
422
+ if allow_date:
423
+ targfunc(self.arr_date)
424
+ self.check_fun(testfunc, targfunc, "arr_date", skipna, **kwargs)
425
+ objs += [self.arr_date.astype("O")]
426
+
427
+ if allow_tdelta:
428
+ try:
429
+ targfunc(self.arr_tdelta)
430
+ except TypeError:
431
+ pass
432
+ else:
433
+ self.check_fun(testfunc, targfunc, "arr_tdelta", skipna, **kwargs)
434
+ objs += [self.arr_tdelta.astype("O")]
435
+
436
+ if allow_obj:
437
+ self.arr_obj = np.vstack(objs)
438
+ # some nanops handle object dtypes better than their numpy
439
+ # counterparts, so the numpy functions need to be given something
440
+ # else
441
+ if allow_obj == "convert":
442
+ targfunc = partial(
443
+ self._badobj_wrap, func=targfunc, allow_complex=allow_complex
444
+ )
445
+ self.check_fun(testfunc, targfunc, "arr_obj", skipna, **kwargs)
446
+
447
+ def _badobj_wrap(self, value, func, allow_complex=True, **kwargs):
448
+ if value.dtype.kind == "O":
449
+ if allow_complex:
450
+ value = value.astype("c16")
451
+ else:
452
+ value = value.astype("f8")
453
+ return func(value, **kwargs)
454
+
455
+ @pytest.mark.parametrize(
456
+ "nan_op,np_op", [(nanops.nanany, np.any), (nanops.nanall, np.all)]
457
+ )
458
+ def test_nan_funcs(self, nan_op, np_op, skipna):
459
+ self.check_funs(nan_op, np_op, skipna, allow_all_nan=False, allow_date=False)
460
+
461
+ def test_nansum(self, skipna):
462
+ self.check_funs(
463
+ nanops.nansum,
464
+ np.sum,
465
+ skipna,
466
+ allow_date=False,
467
+ check_dtype=False,
468
+ empty_targfunc=np.nansum,
469
+ )
470
+
471
+ def test_nanmean(self, skipna):
472
+ self.check_funs(
473
+ nanops.nanmean, np.mean, skipna, allow_obj=False, allow_date=False
474
+ )
475
+
476
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
477
+ def test_nanmedian(self, skipna):
478
+ self.check_funs(
479
+ nanops.nanmedian,
480
+ np.median,
481
+ skipna,
482
+ allow_complex=False,
483
+ allow_date=False,
484
+ allow_obj="convert",
485
+ )
486
+
487
+ @pytest.mark.parametrize("ddof", range(3))
488
+ def test_nanvar(self, ddof, skipna):
489
+ self.check_funs(
490
+ nanops.nanvar,
491
+ np.var,
492
+ skipna,
493
+ allow_complex=False,
494
+ allow_date=False,
495
+ allow_obj="convert",
496
+ ddof=ddof,
497
+ )
498
+
499
+ @pytest.mark.parametrize("ddof", range(3))
500
+ def test_nanstd(self, ddof, skipna):
501
+ self.check_funs(
502
+ nanops.nanstd,
503
+ np.std,
504
+ skipna,
505
+ allow_complex=False,
506
+ allow_date=False,
507
+ allow_obj="convert",
508
+ ddof=ddof,
509
+ )
510
+
511
+ @pytest.mark.parametrize("ddof", range(3))
512
+ def test_nansem(self, ddof, skipna):
513
+ sp_stats = pytest.importorskip("scipy.stats")
514
+
515
+ with np.errstate(invalid="ignore"):
516
+ self.check_funs(
517
+ nanops.nansem,
518
+ sp_stats.sem,
519
+ skipna,
520
+ allow_complex=False,
521
+ allow_date=False,
522
+ allow_tdelta=False,
523
+ allow_obj="convert",
524
+ ddof=ddof,
525
+ )
526
+
527
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
528
+ @pytest.mark.parametrize(
529
+ "nan_op,np_op", [(nanops.nanmin, np.min), (nanops.nanmax, np.max)]
530
+ )
531
+ def test_nanops_with_warnings(self, nan_op, np_op, skipna):
532
+ self.check_funs(nan_op, np_op, skipna, allow_obj=False)
533
+
534
+ def _argminmax_wrap(self, value, axis=None, func=None):
535
+ res = func(value, axis)
536
+ nans = np.min(value, axis)
537
+ nullnan = isna(nans)
538
+ if res.ndim:
539
+ res[nullnan] = -1
540
+ elif (hasattr(nullnan, "all") and nullnan.all()) or (
541
+ not hasattr(nullnan, "all") and nullnan
542
+ ):
543
+ res = -1
544
+ return res
545
+
546
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
547
+ def test_nanargmax(self, skipna):
548
+ func = partial(self._argminmax_wrap, func=np.argmax)
549
+ self.check_funs(nanops.nanargmax, func, skipna, allow_obj=False)
550
+
551
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
552
+ def test_nanargmin(self, skipna):
553
+ func = partial(self._argminmax_wrap, func=np.argmin)
554
+ self.check_funs(nanops.nanargmin, func, skipna, allow_obj=False)
555
+
556
+ def _skew_kurt_wrap(self, values, axis=None, func=None):
557
+ if not isinstance(values.dtype.type, np.floating):
558
+ values = values.astype("f8")
559
+ result = func(values, axis=axis, bias=False)
560
+ # fix for handling cases where all elements in an axis are the same
561
+ if isinstance(result, np.ndarray):
562
+ result[np.max(values, axis=axis) == np.min(values, axis=axis)] = 0
563
+ return result
564
+ elif np.max(values) == np.min(values):
565
+ return 0.0
566
+ return result
567
+
568
+ def test_nanskew(self, skipna):
569
+ sp_stats = pytest.importorskip("scipy.stats")
570
+
571
+ func = partial(self._skew_kurt_wrap, func=sp_stats.skew)
572
+ with np.errstate(invalid="ignore"):
573
+ self.check_funs(
574
+ nanops.nanskew,
575
+ func,
576
+ skipna,
577
+ allow_complex=False,
578
+ allow_date=False,
579
+ allow_tdelta=False,
580
+ )
581
+
582
+ def test_nankurt(self, skipna):
583
+ sp_stats = pytest.importorskip("scipy.stats")
584
+
585
+ func1 = partial(sp_stats.kurtosis, fisher=True)
586
+ func = partial(self._skew_kurt_wrap, func=func1)
587
+ with np.errstate(invalid="ignore"):
588
+ self.check_funs(
589
+ nanops.nankurt,
590
+ func,
591
+ skipna,
592
+ allow_complex=False,
593
+ allow_date=False,
594
+ allow_tdelta=False,
595
+ )
596
+
597
+ def test_nanprod(self, skipna):
598
+ self.check_funs(
599
+ nanops.nanprod,
600
+ np.prod,
601
+ skipna,
602
+ allow_date=False,
603
+ allow_tdelta=False,
604
+ empty_targfunc=np.nanprod,
605
+ )
606
+
607
+ def check_nancorr_nancov_2d(self, checkfun, targ0, targ1, **kwargs):
608
+ res00 = checkfun(self.arr_float_2d, self.arr_float1_2d, **kwargs)
609
+ res01 = checkfun(
610
+ self.arr_float_2d,
611
+ self.arr_float1_2d,
612
+ min_periods=len(self.arr_float_2d) - 1,
613
+ **kwargs,
614
+ )
615
+ tm.assert_almost_equal(targ0, res00)
616
+ tm.assert_almost_equal(targ0, res01)
617
+
618
+ res10 = checkfun(self.arr_float_nan_2d, self.arr_float1_nan_2d, **kwargs)
619
+ res11 = checkfun(
620
+ self.arr_float_nan_2d,
621
+ self.arr_float1_nan_2d,
622
+ min_periods=len(self.arr_float_2d) - 1,
623
+ **kwargs,
624
+ )
625
+ tm.assert_almost_equal(targ1, res10)
626
+ tm.assert_almost_equal(targ1, res11)
627
+
628
+ targ2 = np.nan
629
+ res20 = checkfun(self.arr_nan_2d, self.arr_float1_2d, **kwargs)
630
+ res21 = checkfun(self.arr_float_2d, self.arr_nan_2d, **kwargs)
631
+ res22 = checkfun(self.arr_nan_2d, self.arr_nan_2d, **kwargs)
632
+ res23 = checkfun(self.arr_float_nan_2d, self.arr_nan_float1_2d, **kwargs)
633
+ res24 = checkfun(
634
+ self.arr_float_nan_2d,
635
+ self.arr_nan_float1_2d,
636
+ min_periods=len(self.arr_float_2d) - 1,
637
+ **kwargs,
638
+ )
639
+ res25 = checkfun(
640
+ self.arr_float_2d,
641
+ self.arr_float1_2d,
642
+ min_periods=len(self.arr_float_2d) + 1,
643
+ **kwargs,
644
+ )
645
+ tm.assert_almost_equal(targ2, res20)
646
+ tm.assert_almost_equal(targ2, res21)
647
+ tm.assert_almost_equal(targ2, res22)
648
+ tm.assert_almost_equal(targ2, res23)
649
+ tm.assert_almost_equal(targ2, res24)
650
+ tm.assert_almost_equal(targ2, res25)
651
+
652
+ def check_nancorr_nancov_1d(self, checkfun, targ0, targ1, **kwargs):
653
+ res00 = checkfun(self.arr_float_1d, self.arr_float1_1d, **kwargs)
654
+ res01 = checkfun(
655
+ self.arr_float_1d,
656
+ self.arr_float1_1d,
657
+ min_periods=len(self.arr_float_1d) - 1,
658
+ **kwargs,
659
+ )
660
+ tm.assert_almost_equal(targ0, res00)
661
+ tm.assert_almost_equal(targ0, res01)
662
+
663
+ res10 = checkfun(self.arr_float_nan_1d, self.arr_float1_nan_1d, **kwargs)
664
+ res11 = checkfun(
665
+ self.arr_float_nan_1d,
666
+ self.arr_float1_nan_1d,
667
+ min_periods=len(self.arr_float_1d) - 1,
668
+ **kwargs,
669
+ )
670
+ tm.assert_almost_equal(targ1, res10)
671
+ tm.assert_almost_equal(targ1, res11)
672
+
673
+ targ2 = np.nan
674
+ res20 = checkfun(self.arr_nan_1d, self.arr_float1_1d, **kwargs)
675
+ res21 = checkfun(self.arr_float_1d, self.arr_nan_1d, **kwargs)
676
+ res22 = checkfun(self.arr_nan_1d, self.arr_nan_1d, **kwargs)
677
+ res23 = checkfun(self.arr_float_nan_1d, self.arr_nan_float1_1d, **kwargs)
678
+ res24 = checkfun(
679
+ self.arr_float_nan_1d,
680
+ self.arr_nan_float1_1d,
681
+ min_periods=len(self.arr_float_1d) - 1,
682
+ **kwargs,
683
+ )
684
+ res25 = checkfun(
685
+ self.arr_float_1d,
686
+ self.arr_float1_1d,
687
+ min_periods=len(self.arr_float_1d) + 1,
688
+ **kwargs,
689
+ )
690
+ tm.assert_almost_equal(targ2, res20)
691
+ tm.assert_almost_equal(targ2, res21)
692
+ tm.assert_almost_equal(targ2, res22)
693
+ tm.assert_almost_equal(targ2, res23)
694
+ tm.assert_almost_equal(targ2, res24)
695
+ tm.assert_almost_equal(targ2, res25)
696
+
697
+ def test_nancorr(self):
698
+ targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1]
699
+ targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1]
700
+ self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1)
701
+ targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1]
702
+ targ1 = np.corrcoef(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1]
703
+ self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="pearson")
704
+
705
+ def test_nancorr_pearson(self):
706
+ targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1]
707
+ targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1]
708
+ self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="pearson")
709
+ targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1]
710
+ targ1 = np.corrcoef(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1]
711
+ self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="pearson")
712
+
713
+ def test_nancorr_kendall(self):
714
+ sp_stats = pytest.importorskip("scipy.stats")
715
+
716
+ targ0 = sp_stats.kendalltau(self.arr_float_2d, self.arr_float1_2d)[0]
717
+ targ1 = sp_stats.kendalltau(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0]
718
+ self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="kendall")
719
+ targ0 = sp_stats.kendalltau(self.arr_float_1d, self.arr_float1_1d)[0]
720
+ targ1 = sp_stats.kendalltau(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0]
721
+ self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="kendall")
722
+
723
+ def test_nancorr_spearman(self):
724
+ sp_stats = pytest.importorskip("scipy.stats")
725
+
726
+ targ0 = sp_stats.spearmanr(self.arr_float_2d, self.arr_float1_2d)[0]
727
+ targ1 = sp_stats.spearmanr(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0]
728
+ self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1, method="spearman")
729
+ targ0 = sp_stats.spearmanr(self.arr_float_1d, self.arr_float1_1d)[0]
730
+ targ1 = sp_stats.spearmanr(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0]
731
+ self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="spearman")
732
+
733
+ def test_invalid_method(self):
734
+ pytest.importorskip("scipy")
735
+ targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1]
736
+ targ1 = np.corrcoef(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1]
737
+ msg = "Unknown method 'foo', expected one of 'kendall', 'spearman'"
738
+ with pytest.raises(ValueError, match=msg):
739
+ self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1, method="foo")
740
+
741
+ def test_nancov(self):
742
+ targ0 = np.cov(self.arr_float_2d, self.arr_float1_2d)[0, 1]
743
+ targ1 = np.cov(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1]
744
+ self.check_nancorr_nancov_2d(nanops.nancov, targ0, targ1)
745
+ targ0 = np.cov(self.arr_float_1d, self.arr_float1_1d)[0, 1]
746
+ targ1 = np.cov(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1]
747
+ self.check_nancorr_nancov_1d(nanops.nancov, targ0, targ1)
748
+
749
+
750
+ @pytest.mark.parametrize(
751
+ "arr, correct",
752
+ [
753
+ ("arr_complex", False),
754
+ ("arr_int", False),
755
+ ("arr_bool", False),
756
+ ("arr_str", False),
757
+ ("arr_utf", False),
758
+ ("arr_complex_nan", False),
759
+ ("arr_nan_nanj", False),
760
+ ("arr_nan_infj", True),
761
+ ("arr_complex_nan_infj", True),
762
+ ],
763
+ )
764
+ def test_has_infs_non_float(request, arr, correct, disable_bottleneck):
765
+ val = request.getfixturevalue(arr)
766
+ while getattr(val, "ndim", True):
767
+ res0 = nanops._has_infs(val)
768
+ if correct:
769
+ assert res0
770
+ else:
771
+ assert not res0
772
+
773
+ if not hasattr(val, "ndim"):
774
+ break
775
+
776
+ # Reduce dimension for next step in the loop
777
+ val = np.take(val, 0, axis=-1)
778
+
779
+
780
+ @pytest.mark.parametrize(
781
+ "arr, correct",
782
+ [
783
+ ("arr_float", False),
784
+ ("arr_nan", False),
785
+ ("arr_float_nan", False),
786
+ ("arr_nan_nan", False),
787
+ ("arr_float_inf", True),
788
+ ("arr_inf", True),
789
+ ("arr_nan_inf", True),
790
+ ("arr_float_nan_inf", True),
791
+ ("arr_nan_nan_inf", True),
792
+ ],
793
+ )
794
+ @pytest.mark.parametrize("astype", [None, "f4", "f2"])
795
+ def test_has_infs_floats(request, arr, correct, astype, disable_bottleneck):
796
+ val = request.getfixturevalue(arr)
797
+ if astype is not None:
798
+ val = val.astype(astype)
799
+ while getattr(val, "ndim", True):
800
+ res0 = nanops._has_infs(val)
801
+ if correct:
802
+ assert res0
803
+ else:
804
+ assert not res0
805
+
806
+ if not hasattr(val, "ndim"):
807
+ break
808
+
809
+ # Reduce dimension for next step in the loop
810
+ val = np.take(val, 0, axis=-1)
811
+
812
+
813
+ @pytest.mark.parametrize(
814
+ "fixture", ["arr_float", "arr_complex", "arr_int", "arr_bool", "arr_str", "arr_utf"]
815
+ )
816
+ def test_bn_ok_dtype(fixture, request, disable_bottleneck):
817
+ obj = request.getfixturevalue(fixture)
818
+ assert nanops._bn_ok_dtype(obj.dtype, "test")
819
+
820
+
821
+ @pytest.mark.parametrize(
822
+ "fixture",
823
+ [
824
+ "arr_date",
825
+ "arr_tdelta",
826
+ "arr_obj",
827
+ ],
828
+ )
829
+ def test_bn_not_ok_dtype(fixture, request, disable_bottleneck):
830
+ obj = request.getfixturevalue(fixture)
831
+ assert not nanops._bn_ok_dtype(obj.dtype, "test")
832
+
833
+
834
+ class TestEnsureNumeric:
835
+ def test_numeric_values(self):
836
+ # Test integer
837
+ assert nanops._ensure_numeric(1) == 1
838
+
839
+ # Test float
840
+ assert nanops._ensure_numeric(1.1) == 1.1
841
+
842
+ # Test complex
843
+ assert nanops._ensure_numeric(1 + 2j) == 1 + 2j
844
+
845
+ def test_ndarray(self):
846
+ # Test numeric ndarray
847
+ values = np.array([1, 2, 3])
848
+ assert np.allclose(nanops._ensure_numeric(values), values)
849
+
850
+ # Test object ndarray
851
+ o_values = values.astype(object)
852
+ assert np.allclose(nanops._ensure_numeric(o_values), values)
853
+
854
+ # Test convertible string ndarray
855
+ s_values = np.array(["1", "2", "3"], dtype=object)
856
+ msg = r"Could not convert \['1' '2' '3'\] to numeric"
857
+ with pytest.raises(TypeError, match=msg):
858
+ nanops._ensure_numeric(s_values)
859
+
860
+ # Test non-convertible string ndarray
861
+ s_values = np.array(["foo", "bar", "baz"], dtype=object)
862
+ msg = r"Could not convert .* to numeric"
863
+ with pytest.raises(TypeError, match=msg):
864
+ nanops._ensure_numeric(s_values)
865
+
866
+ def test_convertable_values(self):
867
+ with pytest.raises(TypeError, match="Could not convert string '1' to numeric"):
868
+ nanops._ensure_numeric("1")
869
+ with pytest.raises(
870
+ TypeError, match="Could not convert string '1.1' to numeric"
871
+ ):
872
+ nanops._ensure_numeric("1.1")
873
+ with pytest.raises(
874
+ TypeError, match=r"Could not convert string '1\+1j' to numeric"
875
+ ):
876
+ nanops._ensure_numeric("1+1j")
877
+
878
+ def test_non_convertable_values(self):
879
+ msg = "Could not convert string 'foo' to numeric"
880
+ with pytest.raises(TypeError, match=msg):
881
+ nanops._ensure_numeric("foo")
882
+
883
+ # with the wrong type, python raises TypeError for us
884
+ msg = "argument must be a string or a number"
885
+ with pytest.raises(TypeError, match=msg):
886
+ nanops._ensure_numeric({})
887
+ with pytest.raises(TypeError, match=msg):
888
+ nanops._ensure_numeric([])
889
+
890
+
891
+ class TestNanvarFixedValues:
892
+ # xref GH10242
893
+ # Samples from a normal distribution.
894
+ @pytest.fixture
895
+ def variance(self):
896
+ return 3.0
897
+
898
+ @pytest.fixture
899
+ def samples(self, variance):
900
+ return self.prng.normal(scale=variance**0.5, size=100000)
901
+
902
+ def test_nanvar_all_finite(self, samples, variance):
903
+ actual_variance = nanops.nanvar(samples)
904
+ tm.assert_almost_equal(actual_variance, variance, rtol=1e-2)
905
+
906
+ def test_nanvar_nans(self, samples, variance):
907
+ samples_test = np.nan * np.ones(2 * samples.shape[0])
908
+ samples_test[::2] = samples
909
+
910
+ actual_variance = nanops.nanvar(samples_test, skipna=True)
911
+ tm.assert_almost_equal(actual_variance, variance, rtol=1e-2)
912
+
913
+ actual_variance = nanops.nanvar(samples_test, skipna=False)
914
+ tm.assert_almost_equal(actual_variance, np.nan, rtol=1e-2)
915
+
916
+ def test_nanstd_nans(self, samples, variance):
917
+ samples_test = np.nan * np.ones(2 * samples.shape[0])
918
+ samples_test[::2] = samples
919
+
920
+ actual_std = nanops.nanstd(samples_test, skipna=True)
921
+ tm.assert_almost_equal(actual_std, variance**0.5, rtol=1e-2)
922
+
923
+ actual_std = nanops.nanvar(samples_test, skipna=False)
924
+ tm.assert_almost_equal(actual_std, np.nan, rtol=1e-2)
925
+
926
+ def test_nanvar_axis(self, samples, variance):
927
+ # Generate some sample data.
928
+ samples_unif = self.prng.uniform(size=samples.shape[0])
929
+ samples = np.vstack([samples, samples_unif])
930
+
931
+ actual_variance = nanops.nanvar(samples, axis=1)
932
+ tm.assert_almost_equal(
933
+ actual_variance, np.array([variance, 1.0 / 12]), rtol=1e-2
934
+ )
935
+
936
+ def test_nanvar_ddof(self):
937
+ n = 5
938
+ samples = self.prng.uniform(size=(10000, n + 1))
939
+ samples[:, -1] = np.nan # Force use of our own algorithm.
940
+
941
+ variance_0 = nanops.nanvar(samples, axis=1, skipna=True, ddof=0).mean()
942
+ variance_1 = nanops.nanvar(samples, axis=1, skipna=True, ddof=1).mean()
943
+ variance_2 = nanops.nanvar(samples, axis=1, skipna=True, ddof=2).mean()
944
+
945
+ # The unbiased estimate.
946
+ var = 1.0 / 12
947
+ tm.assert_almost_equal(variance_1, var, rtol=1e-2)
948
+
949
+ # The underestimated variance.
950
+ tm.assert_almost_equal(variance_0, (n - 1.0) / n * var, rtol=1e-2)
951
+
952
+ # The overestimated variance.
953
+ tm.assert_almost_equal(variance_2, (n - 1.0) / (n - 2.0) * var, rtol=1e-2)
954
+
955
+ @pytest.mark.parametrize("axis", range(2))
956
+ @pytest.mark.parametrize("ddof", range(3))
957
+ def test_ground_truth(self, axis, ddof):
958
+ # Test against values that were precomputed with Numpy.
959
+ samples = np.empty((4, 4))
960
+ samples[:3, :3] = np.array(
961
+ [
962
+ [0.97303362, 0.21869576, 0.55560287],
963
+ [0.72980153, 0.03109364, 0.99155171],
964
+ [0.09317602, 0.60078248, 0.15871292],
965
+ ]
966
+ )
967
+ samples[3] = samples[:, 3] = np.nan
968
+
969
+ # Actual variances along axis=0, 1 for ddof=0, 1, 2
970
+ variance = np.array(
971
+ [
972
+ [
973
+ [0.13762259, 0.05619224, 0.11568816],
974
+ [0.20643388, 0.08428837, 0.17353224],
975
+ [0.41286776, 0.16857673, 0.34706449],
976
+ ],
977
+ [
978
+ [0.09519783, 0.16435395, 0.05082054],
979
+ [0.14279674, 0.24653093, 0.07623082],
980
+ [0.28559348, 0.49306186, 0.15246163],
981
+ ],
982
+ ]
983
+ )
984
+
985
+ # Test nanvar.
986
+ var = nanops.nanvar(samples, skipna=True, axis=axis, ddof=ddof)
987
+ tm.assert_almost_equal(var[:3], variance[axis, ddof])
988
+ assert np.isnan(var[3])
989
+
990
+ # Test nanstd.
991
+ std = nanops.nanstd(samples, skipna=True, axis=axis, ddof=ddof)
992
+ tm.assert_almost_equal(std[:3], variance[axis, ddof] ** 0.5)
993
+ assert np.isnan(std[3])
994
+
995
+ @pytest.mark.parametrize("ddof", range(3))
996
+ @pytest.mark.parametrize("axis", [0, 1, None])
997
+ @pytest.mark.parametrize("method", ["var", "std", "sem"])
998
+ def test_complex_nanvar(self, ddof, axis, method):
999
+ arr = self.prng.standard_normal((5, 4)) + self.prng.standard_normal((5, 4)) * 1j
1000
+ nanops_method = getattr(nanops, f"nan{method}")
1001
+ if method in {"var", "std"}:
1002
+ comparator_method = getattr(np, method)
1003
+ elif method == "sem":
1004
+ comparator_method = pytest.importorskip("scipy.stats").sem
1005
+ result = nanops_method(arr, axis=axis, ddof=ddof)
1006
+ expected = comparator_method(arr, axis=axis, ddof=ddof)
1007
+ tm.assert_almost_equal(result, expected)
1008
+
1009
+ @pytest.mark.parametrize("ddof", range(3))
1010
+ def test_nanstd_roundoff(self, ddof):
1011
+ # Regression test for GH 10242 (test data taken from GH 10489). Ensure
1012
+ # that variance is stable.
1013
+ data = Series(766897346 * np.ones(10))
1014
+ result = data.std(ddof=ddof)
1015
+ assert result == 0.0
1016
+
1017
+ @property
1018
+ def prng(self):
1019
+ return np.random.default_rng(2)
1020
+
1021
+
1022
+ class TestNanskewFixedValues:
1023
+ # xref GH 11974
1024
+ # Test data + skewness value (computed with scipy.stats.skew)
1025
+ @pytest.fixture
1026
+ def samples(self):
1027
+ return np.sin(np.linspace(0, 1, 200))
1028
+
1029
+ @pytest.fixture
1030
+ def actual_skew(self):
1031
+ return -0.1875895205961754
1032
+
1033
+ @pytest.mark.parametrize("val", [3075.2, 3075.3, 3075.5])
1034
+ def test_constant_series(self, val):
1035
+ # xref GH 11974
1036
+ data = val * np.ones(300)
1037
+ skew = nanops.nanskew(data)
1038
+ assert skew == 0.0
1039
+
1040
+ def test_all_finite(self):
1041
+ alpha, beta = 0.3, 0.1
1042
+ left_tailed = self.prng.beta(alpha, beta, size=100)
1043
+ assert nanops.nanskew(left_tailed) < 0
1044
+
1045
+ alpha, beta = 0.1, 0.3
1046
+ right_tailed = self.prng.beta(alpha, beta, size=100)
1047
+ assert nanops.nanskew(right_tailed) > 0
1048
+
1049
+ def test_ground_truth(self, samples, actual_skew):
1050
+ skew = nanops.nanskew(samples)
1051
+ tm.assert_almost_equal(skew, actual_skew)
1052
+
1053
+ def test_axis(self, samples, actual_skew):
1054
+ samples = np.vstack([samples, np.nan * np.ones(len(samples))])
1055
+ skew = nanops.nanskew(samples, axis=1)
1056
+ tm.assert_almost_equal(skew, np.array([actual_skew, np.nan]))
1057
+
1058
+ def test_nans(self, samples):
1059
+ samples = np.hstack([samples, np.nan])
1060
+ skew = nanops.nanskew(samples, skipna=False)
1061
+ assert np.isnan(skew)
1062
+
1063
+ def test_nans_skipna(self, samples, actual_skew):
1064
+ samples = np.hstack([samples, np.nan])
1065
+ skew = nanops.nanskew(samples, skipna=True)
1066
+ tm.assert_almost_equal(skew, actual_skew)
1067
+
1068
+ @pytest.mark.parametrize(
1069
+ "initial_data, nobs",
1070
+ [
1071
+ ([-2.05191341e-05, -4.10391103e-05], 27),
1072
+ ([-2.05191341e-10, -4.10391103e-10], 27),
1073
+ ([-2.05191341e-05, -4.10391103e-05], 10_000),
1074
+ ([-2.05191341e-10, -4.10391103e-10], 10_000),
1075
+ ],
1076
+ )
1077
+ def test_low_variance(self, initial_data, nobs):
1078
+ st = pytest.importorskip("scipy.stats")
1079
+ data = np.zeros((nobs,), dtype=np.float64)
1080
+ data[: len(initial_data)] = initial_data
1081
+ skew = nanops.nanskew(data)
1082
+ expected = st.skew(data, bias=False)
1083
+ tm.assert_almost_equal(skew, expected)
1084
+
1085
+ @property
1086
+ def prng(self):
1087
+ return np.random.default_rng(2)
1088
+
1089
+
1090
+ class TestNankurtFixedValues:
1091
+ # xref GH 11974
1092
+ # Test data + kurtosis value (computed with scipy.stats.kurtosis)
1093
+ @pytest.fixture
1094
+ def samples(self):
1095
+ return np.sin(np.linspace(0, 1, 200))
1096
+
1097
+ @pytest.fixture
1098
+ def actual_kurt(self):
1099
+ return -1.2058303433799713
1100
+
1101
+ @pytest.mark.parametrize("val", [3075.2, 3075.3, 3075.5])
1102
+ def test_constant_series(self, val):
1103
+ # xref GH 11974
1104
+ data = val * np.ones(300)
1105
+ kurt = nanops.nankurt(data)
1106
+ tm.assert_equal(kurt, 0.0)
1107
+
1108
+ def test_all_finite(self):
1109
+ alpha, beta = 0.3, 0.1
1110
+ left_tailed = self.prng.beta(alpha, beta, size=100)
1111
+ assert nanops.nankurt(left_tailed) < 2
1112
+
1113
+ alpha, beta = 0.1, 0.3
1114
+ right_tailed = self.prng.beta(alpha, beta, size=100)
1115
+ assert nanops.nankurt(right_tailed) < 0
1116
+
1117
+ def test_ground_truth(self, samples, actual_kurt):
1118
+ kurt = nanops.nankurt(samples)
1119
+ tm.assert_almost_equal(kurt, actual_kurt)
1120
+
1121
+ def test_axis(self, samples, actual_kurt):
1122
+ samples = np.vstack([samples, np.nan * np.ones(len(samples))])
1123
+ kurt = nanops.nankurt(samples, axis=1)
1124
+ tm.assert_almost_equal(kurt, np.array([actual_kurt, np.nan]))
1125
+
1126
+ def test_nans(self, samples):
1127
+ samples = np.hstack([samples, np.nan])
1128
+ kurt = nanops.nankurt(samples, skipna=False)
1129
+ assert np.isnan(kurt)
1130
+
1131
+ def test_nans_skipna(self, samples, actual_kurt):
1132
+ samples = np.hstack([samples, np.nan])
1133
+ kurt = nanops.nankurt(samples, skipna=True)
1134
+ tm.assert_almost_equal(kurt, actual_kurt)
1135
+
1136
+ @pytest.mark.parametrize(
1137
+ "initial_data, nobs",
1138
+ [
1139
+ ([-2.05191341e-05, -4.10391103e-05], 27),
1140
+ ([-2.05191341e-10, -4.10391103e-10], 27),
1141
+ ([-2.05191341e-05, -4.10391103e-05], 10_000),
1142
+ ([-2.05191341e-10, -4.10391103e-10], 10_000),
1143
+ ],
1144
+ )
1145
+ def test_low_variance(self, initial_data, nobs):
1146
+ # GH#57972
1147
+ st = pytest.importorskip("scipy.stats")
1148
+ data = np.zeros((nobs,), dtype=np.float64)
1149
+ data[: len(initial_data)] = initial_data
1150
+ kurt = nanops.nankurt(data)
1151
+ expected = st.kurtosis(data, bias=False)
1152
+ tm.assert_almost_equal(kurt, expected)
1153
+
1154
+ @property
1155
+ def prng(self):
1156
+ return np.random.default_rng(2)
1157
+
1158
+
1159
+ class TestDatetime64NaNOps:
1160
+ # Enabling mean changes the behavior of DataFrame.mean
1161
+ # See https://github.com/pandas-dev/pandas/issues/24752
1162
+ def test_nanmean(self, unit):
1163
+ dti = pd.date_range("2016-01-01", periods=3).as_unit(unit)
1164
+ expected = dti[1]
1165
+
1166
+ for obj in [dti, dti._data]:
1167
+ result = nanops.nanmean(obj)
1168
+ assert result == expected
1169
+
1170
+ dti2 = dti.insert(1, pd.NaT)
1171
+
1172
+ for obj in [dti2, dti2._data]:
1173
+ result = nanops.nanmean(obj)
1174
+ assert result == expected
1175
+
1176
+ @pytest.mark.parametrize("constructor", ["M8", "m8"])
1177
+ def test_nanmean_skipna_false(self, constructor, unit):
1178
+ dtype = f"{constructor}[{unit}]"
1179
+ arr = np.arange(12).astype(np.int64).view(dtype).reshape(4, 3)
1180
+
1181
+ arr[-1, -1] = "NaT"
1182
+
1183
+ result = nanops.nanmean(arr, skipna=False)
1184
+ assert np.isnat(result)
1185
+ assert result.dtype == dtype
1186
+
1187
+ result = nanops.nanmean(arr, axis=0, skipna=False)
1188
+ expected = np.array([4, 5, "NaT"], dtype=arr.dtype)
1189
+ tm.assert_numpy_array_equal(result, expected)
1190
+
1191
+ result = nanops.nanmean(arr, axis=1, skipna=False)
1192
+ expected = np.array([arr[0, 1], arr[1, 1], arr[2, 1], arr[-1, -1]])
1193
+ tm.assert_numpy_array_equal(result, expected)
1194
+
1195
+
1196
+ def test_use_bottleneck():
1197
+ if nanops._BOTTLENECK_INSTALLED:
1198
+ with pd.option_context("use_bottleneck", True):
1199
+ assert pd.get_option("use_bottleneck")
1200
+
1201
+ with pd.option_context("use_bottleneck", False):
1202
+ assert not pd.get_option("use_bottleneck")
1203
+
1204
+
1205
+ @pytest.mark.parametrize(
1206
+ "numpy_op, expected",
1207
+ [
1208
+ (np.sum, 10),
1209
+ (np.nansum, 10),
1210
+ (np.mean, 2.5),
1211
+ (np.nanmean, 2.5),
1212
+ (np.median, 2.5),
1213
+ (np.nanmedian, 2.5),
1214
+ (np.min, 1),
1215
+ (np.max, 4),
1216
+ (np.nanmin, 1),
1217
+ (np.nanmax, 4),
1218
+ ],
1219
+ )
1220
+ def test_numpy_ops(numpy_op, expected):
1221
+ # GH8383
1222
+ result = numpy_op(Series([1, 2, 3, 4]))
1223
+ assert result == expected
1224
+
1225
+
1226
+ @pytest.mark.parametrize(
1227
+ "operation",
1228
+ [
1229
+ nanops.nanany,
1230
+ nanops.nanall,
1231
+ nanops.nansum,
1232
+ nanops.nanmean,
1233
+ nanops.nanmedian,
1234
+ nanops.nanstd,
1235
+ nanops.nanvar,
1236
+ nanops.nansem,
1237
+ nanops.nanargmax,
1238
+ nanops.nanargmin,
1239
+ nanops.nanmax,
1240
+ nanops.nanmin,
1241
+ nanops.nanskew,
1242
+ nanops.nankurt,
1243
+ nanops.nanprod,
1244
+ ],
1245
+ )
1246
+ def test_nanops_independent_of_mask_param(operation):
1247
+ # GH22764
1248
+ ser = Series([1, 2, np.nan, 3, np.nan, 4])
1249
+ mask = ser.isna()
1250
+ median_expected = operation(ser._values)
1251
+ median_result = operation(ser._values, mask=mask)
1252
+ assert median_expected == median_result
1253
+
1254
+
1255
+ @pytest.mark.parametrize("min_count", [-1, 0])
1256
+ def test_check_below_min_count_negative_or_zero_min_count(min_count):
1257
+ # GH35227
1258
+ result = nanops.check_below_min_count((21, 37), None, min_count)
1259
+ expected_result = False
1260
+ assert result == expected_result
1261
+
1262
+
1263
+ @pytest.mark.parametrize(
1264
+ "mask", [None, np.array([False, False, True]), np.array([True] + 9 * [False])]
1265
+ )
1266
+ @pytest.mark.parametrize("min_count, expected_result", [(1, False), (101, True)])
1267
+ def test_check_below_min_count_positive_min_count(mask, min_count, expected_result):
1268
+ # GH35227
1269
+ shape = (10, 10)
1270
+ result = nanops.check_below_min_count(shape, mask, min_count)
1271
+ assert result == expected_result
1272
+
1273
+
1274
+ @td.skip_if_windows
1275
+ @td.skip_if_32bit
1276
+ @pytest.mark.parametrize("min_count, expected_result", [(1, False), (2812191852, True)])
1277
+ def test_check_below_min_count_large_shape(min_count, expected_result):
1278
+ # GH35227 large shape used to show that the issue is fixed
1279
+ shape = (2244367, 1253)
1280
+ result = nanops.check_below_min_count(shape, mask=None, min_count=min_count)
1281
+ assert result == expected_result
1282
+
1283
+
1284
+ @pytest.mark.parametrize("func", ["nanmean", "nansum"])
1285
+ def test_check_bottleneck_disallow(any_real_numpy_dtype, func):
1286
+ # GH 42878 bottleneck sometimes produces unreliable results for mean and sum
1287
+ assert not nanops._bn_ok_dtype(np.dtype(any_real_numpy_dtype).type, func)
1288
+
1289
+
1290
+ @pytest.mark.parametrize("val", [2**55, -(2**55), 20150515061816532])
1291
+ def test_nanmean_overflow(disable_bottleneck, val, using_python_scalars):
1292
+ # GH 10155
1293
+ # In the previous implementation mean can overflow for int dtypes, it
1294
+ # is now consistent with numpy
1295
+
1296
+ ser = Series(val, index=range(500), dtype=np.int64)
1297
+ result = ser.mean()
1298
+ assert result == val
1299
+ if using_python_scalars:
1300
+ assert type(result) == float
1301
+ else:
1302
+ np_result = ser.values.mean()
1303
+ assert result == np_result
1304
+ assert result.dtype == np.float64
1305
+
1306
+
1307
+ @pytest.mark.parametrize(
1308
+ "dtype",
1309
+ [
1310
+ np.int16,
1311
+ np.int32,
1312
+ np.int64,
1313
+ np.float32,
1314
+ np.float64,
1315
+ getattr(np, "float128", None),
1316
+ ],
1317
+ )
1318
+ @pytest.mark.parametrize("method", ["mean", "std", "var", "skew", "kurt", "min", "max"])
1319
+ def test_returned_dtype(disable_bottleneck, dtype, method, using_python_scalars):
1320
+ if dtype is None:
1321
+ pytest.skip("np.float128 not available")
1322
+
1323
+ ser = Series(range(10), dtype=dtype)
1324
+ result = getattr(ser, method)()
1325
+ if using_python_scalars:
1326
+ if is_integer_dtype(dtype) and method in ["min", "max"]:
1327
+ assert isinstance(result, int)
1328
+ else:
1329
+ assert type(result) == float
1330
+ elif is_integer_dtype(dtype) and method not in ["min", "max"]:
1331
+ assert result.dtype == np.float64
1332
+ else:
1333
+ assert result.dtype == dtype
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_optional_dependency.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import types
3
+
4
+ import pytest
5
+
6
+ from pandas.compat._optional import (
7
+ VERSIONS,
8
+ import_optional_dependency,
9
+ )
10
+
11
+ import pandas._testing as tm
12
+
13
+
14
+ def test_import_optional():
15
+ match = "Import .*notapackage.* pip .* conda .* notapackage"
16
+ with pytest.raises(ImportError, match=match) as exc_info:
17
+ import_optional_dependency("notapackage")
18
+ # The original exception should be there as context:
19
+ assert isinstance(exc_info.value.__context__, ImportError)
20
+
21
+ result = import_optional_dependency("notapackage", errors="ignore")
22
+ assert result is None
23
+
24
+
25
+ def test_xlrd_version_fallback():
26
+ pytest.importorskip("xlrd")
27
+ import_optional_dependency("xlrd")
28
+
29
+
30
+ def test_bad_version(monkeypatch):
31
+ name = "fakemodule"
32
+ module = types.ModuleType(name)
33
+ module.__version__ = "0.9.0"
34
+ sys.modules[name] = module
35
+ monkeypatch.setitem(VERSIONS, name, "1.0.0")
36
+
37
+ match = "Pandas requires .*1.0.0.* of .fakemodule.*'0.9.0'"
38
+ with pytest.raises(ImportError, match=match):
39
+ import_optional_dependency("fakemodule")
40
+
41
+ # Test min_version parameter
42
+ result = import_optional_dependency("fakemodule", min_version="0.8")
43
+ assert result is module
44
+
45
+ with tm.assert_produces_warning(UserWarning, match=match):
46
+ result = import_optional_dependency("fakemodule", errors="warn")
47
+ assert result is None
48
+
49
+ module.__version__ = "1.0.0" # exact match is OK
50
+ result = import_optional_dependency("fakemodule")
51
+ assert result is module
52
+
53
+ with pytest.raises(ImportError, match="Pandas requires version '1.1.0'"):
54
+ import_optional_dependency("fakemodule", min_version="1.1.0")
55
+
56
+ with tm.assert_produces_warning(UserWarning, match="Pandas requires version"):
57
+ result = import_optional_dependency(
58
+ "fakemodule", errors="warn", min_version="1.1.0"
59
+ )
60
+ assert result is None
61
+
62
+ result = import_optional_dependency(
63
+ "fakemodule", errors="ignore", min_version="1.1.0"
64
+ )
65
+ assert result is None
66
+
67
+
68
+ def test_submodule(monkeypatch):
69
+ # Create a fake module with a submodule
70
+ name = "fakemodule"
71
+ module = types.ModuleType(name)
72
+ module.__version__ = "0.9.0"
73
+ sys.modules[name] = module
74
+ sub_name = "submodule"
75
+ submodule = types.ModuleType(sub_name)
76
+ setattr(module, sub_name, submodule)
77
+ sys.modules[f"{name}.{sub_name}"] = submodule
78
+ monkeypatch.setitem(VERSIONS, name, "1.0.0")
79
+
80
+ match = "Pandas requires .*1.0.0.* of .fakemodule.*'0.9.0'"
81
+ with pytest.raises(ImportError, match=match):
82
+ import_optional_dependency("fakemodule.submodule")
83
+
84
+ with tm.assert_produces_warning(UserWarning, match=match):
85
+ result = import_optional_dependency("fakemodule.submodule", errors="warn")
86
+ assert result is None
87
+
88
+ module.__version__ = "1.0.0" # exact match is OK
89
+ result = import_optional_dependency("fakemodule.submodule")
90
+ assert result is submodule
91
+
92
+
93
+ def test_no_version_raises(monkeypatch):
94
+ name = "fakemodule"
95
+ module = types.ModuleType(name)
96
+ sys.modules[name] = module
97
+ monkeypatch.setitem(VERSIONS, name, "1.0.0")
98
+
99
+ with pytest.raises(ImportError, match="Can't determine .* fakemodule"):
100
+ import_optional_dependency(name)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_register_accessor.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Generator
2
+ import contextlib
3
+ import weakref
4
+
5
+ import pytest
6
+
7
+ import pandas as pd
8
+ import pandas._testing as tm
9
+ from pandas.core import accessor
10
+
11
+
12
+ def test_dirname_mixin() -> None:
13
+ # GH37173
14
+
15
+ class X(accessor.DirNamesMixin):
16
+ x = 1
17
+ y: int
18
+
19
+ def __init__(self) -> None:
20
+ self.z = 3
21
+
22
+ result = [attr_name for attr_name in dir(X()) if not attr_name.startswith("_")]
23
+
24
+ assert result == ["x", "z"]
25
+
26
+
27
+ @contextlib.contextmanager
28
+ def ensure_removed(obj, attr) -> Generator[None, None, None]:
29
+ """Ensure that an attribute added to 'obj' during the test is
30
+ removed when we're done
31
+ """
32
+ try:
33
+ yield
34
+ finally:
35
+ try:
36
+ delattr(obj, attr)
37
+ except AttributeError:
38
+ pass
39
+ obj._accessors.discard(attr)
40
+
41
+
42
+ class MyAccessor:
43
+ def __init__(self, obj) -> None:
44
+ self.obj = obj
45
+ self.item = "item"
46
+
47
+ @property
48
+ def prop(self):
49
+ return self.item
50
+
51
+ def method(self):
52
+ return self.item
53
+
54
+
55
+ @pytest.mark.parametrize(
56
+ "obj, registrar",
57
+ [
58
+ (pd.Series, pd.api.extensions.register_series_accessor),
59
+ (pd.DataFrame, pd.api.extensions.register_dataframe_accessor),
60
+ (pd.Index, pd.api.extensions.register_index_accessor),
61
+ ],
62
+ )
63
+ def test_register(obj, registrar):
64
+ with ensure_removed(obj, "mine"):
65
+ before = set(dir(obj))
66
+ registrar("mine")(MyAccessor)
67
+ o = obj([]) if obj is not pd.Series else obj([], dtype=object)
68
+ assert o.mine.prop == "item"
69
+ after = set(dir(obj))
70
+ assert (before ^ after) == {"mine"}
71
+ assert "mine" in obj._accessors
72
+
73
+
74
+ def test_accessor_works():
75
+ with ensure_removed(pd.Series, "mine"):
76
+ pd.api.extensions.register_series_accessor("mine")(MyAccessor)
77
+
78
+ s = pd.Series([1, 2])
79
+ assert s.mine.obj is s
80
+
81
+ assert s.mine.prop == "item"
82
+ assert s.mine.method() == "item"
83
+
84
+
85
+ def test_overwrite_warns():
86
+ match = r".*MyAccessor.*fake.*Series.*"
87
+ with tm.assert_produces_warning(UserWarning, match=match):
88
+ with ensure_removed(pd.Series, "fake"):
89
+ setattr(pd.Series, "fake", 123)
90
+ pd.api.extensions.register_series_accessor("fake")(MyAccessor)
91
+ s = pd.Series([1, 2])
92
+ assert s.fake.prop == "item"
93
+
94
+
95
+ def test_raises_attribute_error():
96
+ with ensure_removed(pd.Series, "bad"):
97
+
98
+ @pd.api.extensions.register_series_accessor("bad")
99
+ class Bad:
100
+ def __init__(self, data) -> None:
101
+ raise AttributeError("whoops")
102
+
103
+ with pytest.raises(AttributeError, match="whoops"):
104
+ pd.Series([], dtype=object).bad
105
+
106
+
107
+ @pytest.mark.parametrize(
108
+ "klass, registrar",
109
+ [
110
+ (pd.Series, pd.api.extensions.register_series_accessor),
111
+ (pd.DataFrame, pd.api.extensions.register_dataframe_accessor),
112
+ (pd.Index, pd.api.extensions.register_index_accessor),
113
+ ],
114
+ )
115
+ def test_no_circular_reference(klass, registrar):
116
+ # GH 41357
117
+ with ensure_removed(klass, "access"):
118
+ registrar("access")(MyAccessor)
119
+ obj = klass([0])
120
+ ref = weakref.ref(obj)
121
+ assert obj.access.obj is obj
122
+ del obj
123
+ assert ref() is None
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_sorting.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ from datetime import datetime
3
+ from itertools import product
4
+
5
+ import numpy as np
6
+ import pytest
7
+
8
+ from pandas import (
9
+ NA,
10
+ DataFrame,
11
+ MultiIndex,
12
+ Series,
13
+ array,
14
+ concat,
15
+ merge,
16
+ )
17
+ import pandas._testing as tm
18
+ from pandas.core.algorithms import safe_sort
19
+ import pandas.core.common as com
20
+ from pandas.core.sorting import (
21
+ _decons_group_index,
22
+ get_group_index,
23
+ is_int64_overflow_possible,
24
+ lexsort_indexer,
25
+ nargsort,
26
+ )
27
+
28
+
29
+ @pytest.fixture
30
+ def left_right():
31
+ low, high, n = -1 << 10, 1 << 10, 1 << 20
32
+ left = DataFrame(
33
+ np.random.default_rng(2).integers(low, high, (n, 7)), columns=list("ABCDEFG")
34
+ )
35
+ left["left"] = left.sum(axis=1)
36
+ right = left.sample(
37
+ frac=1, random_state=np.random.default_rng(2), ignore_index=True
38
+ )
39
+ right.columns = [*right.columns[:-1].tolist(), "right"]
40
+ right["right"] *= -1
41
+ return left, right
42
+
43
+
44
+ class TestSorting:
45
+ @pytest.mark.slow
46
+ def test_int64_overflow(self):
47
+ B = np.concatenate((np.arange(1000), np.arange(1000), np.arange(500)))
48
+ A = np.arange(2500)
49
+ df = DataFrame(
50
+ {
51
+ "A": A,
52
+ "B": B,
53
+ "C": A,
54
+ "D": B,
55
+ "E": A,
56
+ "F": B,
57
+ "G": A,
58
+ "H": B,
59
+ "values": np.random.default_rng(2).standard_normal(2500),
60
+ }
61
+ )
62
+
63
+ lg = df.groupby(["A", "B", "C", "D", "E", "F", "G", "H"])
64
+ rg = df.groupby(["H", "G", "F", "E", "D", "C", "B", "A"])
65
+
66
+ left = lg.sum()["values"]
67
+ right = rg.sum()["values"]
68
+
69
+ exp_index, _ = left.index.sortlevel()
70
+ tm.assert_index_equal(left.index, exp_index)
71
+
72
+ exp_index, _ = right.index.sortlevel(0)
73
+ tm.assert_index_equal(right.index, exp_index)
74
+
75
+ tups = list(map(tuple, df[["A", "B", "C", "D", "E", "F", "G", "H"]].values))
76
+ tups = com.asarray_tuplesafe(tups)
77
+
78
+ expected = df.groupby(tups).sum()["values"]
79
+
80
+ for k, v in expected.items():
81
+ assert left[k] == right[k[::-1]]
82
+ assert left[k] == v
83
+ assert len(left) == len(right)
84
+
85
+ def test_int64_overflow_groupby_large_range(self):
86
+ # GH9096
87
+ values = range(55109)
88
+ data = DataFrame.from_dict({"a": values, "b": values, "c": values, "d": values})
89
+ grouped = data.groupby(["a", "b", "c", "d"])
90
+ assert len(grouped) == len(values)
91
+
92
+ @pytest.mark.slow
93
+ @pytest.mark.parametrize("agg", ["mean", "median"])
94
+ def test_int64_overflow_groupby_large_df_shuffled(self, agg):
95
+ rs = np.random.default_rng(2)
96
+ arr = rs.integers(-1 << 12, 1 << 12, (1 << 15, 5))
97
+ i = rs.choice(len(arr), len(arr) * 4)
98
+ arr = np.vstack((arr, arr[i])) # add some duplicate rows
99
+
100
+ i = rs.permutation(len(arr))
101
+ arr = arr[i] # shuffle rows
102
+
103
+ df = DataFrame(arr, columns=list("abcde"))
104
+ df["jim"], df["joe"] = np.zeros((2, len(df)))
105
+ gr = df.groupby(list("abcde"))
106
+
107
+ # verify this is testing what it is supposed to test!
108
+ assert is_int64_overflow_possible(
109
+ tuple(ping.ngroups for ping in gr._grouper.groupings)
110
+ )
111
+
112
+ mi = MultiIndex.from_arrays(
113
+ [ar.ravel() for ar in np.array_split(np.unique(arr, axis=0), 5, axis=1)],
114
+ names=list("abcde"),
115
+ )
116
+
117
+ res = DataFrame(
118
+ np.zeros((len(mi), 2)), columns=["jim", "joe"], index=mi
119
+ ).sort_index()
120
+
121
+ tm.assert_frame_equal(getattr(gr, agg)(), res)
122
+
123
+ @pytest.mark.parametrize(
124
+ "order, na_position, exp",
125
+ [
126
+ [
127
+ True,
128
+ "last",
129
+ list(range(5, 105)) + list(range(5)) + list(range(105, 110)),
130
+ ],
131
+ [
132
+ True,
133
+ "first",
134
+ list(range(5)) + list(range(105, 110)) + list(range(5, 105)),
135
+ ],
136
+ [
137
+ False,
138
+ "last",
139
+ list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110)),
140
+ ],
141
+ [
142
+ False,
143
+ "first",
144
+ list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1)),
145
+ ],
146
+ ],
147
+ )
148
+ def test_lexsort_indexer(self, order, na_position, exp):
149
+ keys = [[np.nan] * 5 + list(range(100)) + [np.nan] * 5]
150
+ result = lexsort_indexer(keys, orders=order, na_position=na_position)
151
+ tm.assert_numpy_array_equal(result, np.array(exp, dtype=np.intp))
152
+
153
+ @pytest.mark.parametrize(
154
+ "ascending, na_position, exp",
155
+ [
156
+ [
157
+ True,
158
+ "last",
159
+ list(range(5, 105)) + list(range(5)) + list(range(105, 110)),
160
+ ],
161
+ [
162
+ True,
163
+ "first",
164
+ list(range(5)) + list(range(105, 110)) + list(range(5, 105)),
165
+ ],
166
+ [
167
+ False,
168
+ "last",
169
+ list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110)),
170
+ ],
171
+ [
172
+ False,
173
+ "first",
174
+ list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1)),
175
+ ],
176
+ ],
177
+ )
178
+ def test_nargsort(self, ascending, na_position, exp):
179
+ # list places NaNs last, np.array(..., dtype="O") may not place NaNs first
180
+ items = np.array([np.nan] * 5 + list(range(100)) + [np.nan] * 5, dtype="O")
181
+
182
+ # mergesort is the most difficult to get right because we want it to be
183
+ # stable.
184
+
185
+ # According to numpy/core/tests/test_multiarray, """The number of
186
+ # sorted items must be greater than ~50 to check the actual algorithm
187
+ # because quick and merge sort fall over to insertion sort for small
188
+ # arrays."""
189
+
190
+ result = nargsort(
191
+ items, kind="mergesort", ascending=ascending, na_position=na_position
192
+ )
193
+ tm.assert_numpy_array_equal(result, np.array(exp), check_dtype=False)
194
+
195
+
196
+ class TestMerge:
197
+ def test_int64_overflow_outer_merge(self):
198
+ # #2690, combinatorial explosion
199
+ df1 = DataFrame(
200
+ np.random.default_rng(2).standard_normal((1000, 7)),
201
+ columns=[*list("ABCDEF"), "G1"],
202
+ )
203
+ df2 = DataFrame(
204
+ np.random.default_rng(3).standard_normal((1000, 7)),
205
+ columns=[*list("ABCDEF"), "G2"],
206
+ )
207
+ result = merge(df1, df2, how="outer")
208
+ assert len(result) == 2000
209
+
210
+ @pytest.mark.slow
211
+ def test_int64_overflow_check_sum_col(self, left_right):
212
+ left, right = left_right
213
+
214
+ out = merge(left, right, how="outer")
215
+ assert len(out) == len(left)
216
+ tm.assert_series_equal(out["left"], -out["right"], check_names=False)
217
+ result = out.iloc[:, :-2].sum(axis=1)
218
+ tm.assert_series_equal(out["left"], result, check_names=False)
219
+ assert result.name is None
220
+
221
+ @pytest.mark.slow
222
+ def test_int64_overflow_how_merge(self, left_right, join_type):
223
+ left, right = left_right
224
+
225
+ out = merge(left, right, how="outer")
226
+ out.sort_values(out.columns.tolist(), inplace=True)
227
+ tm.assert_frame_equal(out, merge(left, right, how=join_type, sort=True))
228
+
229
+ @pytest.mark.slow
230
+ def test_int64_overflow_sort_false_order(self, left_right):
231
+ left, right = left_right
232
+
233
+ # check that left merge w/ sort=False maintains left frame order
234
+ out = merge(left, right, how="left", sort=False)
235
+ tm.assert_frame_equal(left, out[left.columns.tolist()])
236
+
237
+ out = merge(right, left, how="left", sort=False)
238
+ tm.assert_frame_equal(right, out[right.columns.tolist()])
239
+
240
+ @pytest.mark.slow
241
+ def test_int64_overflow_one_to_many_none_match(self, join_type, sort):
242
+ # one-2-many/none match
243
+ how = join_type
244
+ low, high, n = -1 << 10, 1 << 10, 1 << 11
245
+ left = DataFrame(
246
+ np.random.default_rng(2).integers(low, high, (n, 7)).astype("int64"),
247
+ columns=list("ABCDEFG"),
248
+ )
249
+
250
+ # confirm that this is checking what it is supposed to check
251
+ shape = left.apply(Series.nunique).values
252
+ assert is_int64_overflow_possible(shape)
253
+
254
+ # add duplicates to left frame
255
+ left = concat([left, left], ignore_index=True)
256
+
257
+ right = DataFrame(
258
+ np.random.default_rng(3).integers(low, high, (n // 2, 7)).astype("int64"),
259
+ columns=list("ABCDEFG"),
260
+ )
261
+
262
+ # add duplicates & overlap with left to the right frame
263
+ i = np.random.default_rng(4).choice(len(left), n)
264
+ right = concat([right, right, left.iloc[i]], ignore_index=True)
265
+
266
+ left["left"] = np.random.default_rng(2).standard_normal(len(left))
267
+ right["right"] = np.random.default_rng(2).standard_normal(len(right))
268
+
269
+ # shuffle left & right frames
270
+ left = left.sample(
271
+ frac=1, ignore_index=True, random_state=np.random.default_rng(5)
272
+ )
273
+ right = right.sample(
274
+ frac=1, ignore_index=True, random_state=np.random.default_rng(6)
275
+ )
276
+
277
+ # manually compute outer merge
278
+ ldict, rdict = defaultdict(list), defaultdict(list)
279
+
280
+ for idx, row in left.set_index(list("ABCDEFG")).iterrows():
281
+ ldict[idx].append(row["left"])
282
+
283
+ for idx, row in right.set_index(list("ABCDEFG")).iterrows():
284
+ rdict[idx].append(row["right"])
285
+
286
+ vals = []
287
+ for k, lval in ldict.items():
288
+ rval = rdict.get(k, [np.nan])
289
+ for lv, rv in product(lval, rval):
290
+ vals.append((*k, lv, rv))
291
+
292
+ for k, rval in rdict.items():
293
+ if k not in ldict:
294
+ vals.extend((*k, np.nan, rv) for rv in rval)
295
+
296
+ out = DataFrame(vals, columns=[*list("ABCDEFG"), "left", "right"])
297
+ out = out.sort_values(out.columns.to_list(), ignore_index=True)
298
+
299
+ jmask = {
300
+ "left": out["left"].notna(),
301
+ "right": out["right"].notna(),
302
+ "inner": out["left"].notna() & out["right"].notna(),
303
+ "outer": np.ones(len(out), dtype="bool"),
304
+ }
305
+
306
+ mask = jmask[how]
307
+ frame = out[mask].sort_values(out.columns.to_list(), ignore_index=True)
308
+ assert mask.all() ^ mask.any() or how == "outer"
309
+
310
+ res = merge(left, right, how=how, sort=sort)
311
+ if sort:
312
+ kcols = list("ABCDEFG")
313
+ tm.assert_frame_equal(
314
+ res[kcols], res[kcols].sort_values(kcols, kind="mergesort")
315
+ )
316
+
317
+ # as in GH9092 dtypes break with outer/right join
318
+ # 2021-12-18: dtype does not break anymore
319
+ tm.assert_frame_equal(
320
+ frame, res.sort_values(res.columns.to_list(), ignore_index=True)
321
+ )
322
+
323
+
324
+ @pytest.mark.parametrize(
325
+ "codes_list, shape",
326
+ [
327
+ [
328
+ [
329
+ np.tile([0, 1, 2, 3, 0, 1, 2, 3], 100).astype(np.int64),
330
+ np.tile([0, 2, 4, 3, 0, 1, 2, 3], 100).astype(np.int64),
331
+ np.tile([5, 1, 0, 2, 3, 0, 5, 4], 100).astype(np.int64),
332
+ ],
333
+ (4, 5, 6),
334
+ ],
335
+ [
336
+ [
337
+ np.tile(np.arange(10000, dtype=np.int64), 5),
338
+ np.tile(np.arange(10000, dtype=np.int64), 5),
339
+ ],
340
+ (10000, 10000),
341
+ ],
342
+ ],
343
+ )
344
+ def test_decons(codes_list, shape):
345
+ group_index = get_group_index(codes_list, shape, sort=True, xnull=True)
346
+ codes_list2 = _decons_group_index(group_index, shape)
347
+
348
+ for a, b in zip(codes_list, codes_list2, strict=True):
349
+ tm.assert_numpy_array_equal(a, b)
350
+
351
+
352
+ class TestSafeSort:
353
+ @pytest.mark.parametrize(
354
+ "arg, exp",
355
+ [
356
+ [[3, 1, 2, 0, 4], [0, 1, 2, 3, 4]],
357
+ [
358
+ np.array(list("baaacb"), dtype=object),
359
+ np.array(list("aaabbc"), dtype=object),
360
+ ],
361
+ [[], []],
362
+ ],
363
+ )
364
+ def test_basic_sort(self, arg, exp):
365
+ result = safe_sort(np.array(arg))
366
+ expected = np.array(exp)
367
+ tm.assert_numpy_array_equal(result, expected)
368
+
369
+ @pytest.mark.parametrize("verify", [True, False])
370
+ @pytest.mark.parametrize(
371
+ "codes, exp_codes",
372
+ [
373
+ [[0, 1, 1, 2, 3, 0, -1, 4], [3, 1, 1, 2, 0, 3, -1, 4]],
374
+ [[], []],
375
+ ],
376
+ )
377
+ def test_codes(self, verify, codes, exp_codes):
378
+ values = np.array([3, 1, 2, 0, 4])
379
+ expected = np.array([0, 1, 2, 3, 4])
380
+
381
+ result, result_codes = safe_sort(
382
+ values, codes, use_na_sentinel=True, verify=verify
383
+ )
384
+ expected_codes = np.array(exp_codes, dtype=np.intp)
385
+ tm.assert_numpy_array_equal(result, expected)
386
+ tm.assert_numpy_array_equal(result_codes, expected_codes)
387
+
388
+ def test_codes_out_of_bound(self):
389
+ values = np.array([3, 1, 2, 0, 4])
390
+ expected = np.array([0, 1, 2, 3, 4])
391
+
392
+ # out of bound indices
393
+ codes = [0, 101, 102, 2, 3, 0, 99, 4]
394
+ result, result_codes = safe_sort(values, codes, use_na_sentinel=True)
395
+ expected_codes = np.array([3, -1, -1, 2, 0, 3, -1, 4], dtype=np.intp)
396
+ tm.assert_numpy_array_equal(result, expected)
397
+ tm.assert_numpy_array_equal(result_codes, expected_codes)
398
+
399
+ @pytest.mark.parametrize("codes", [[-1, -1], [2, -1], [2, 2]])
400
+ def test_codes_empty_array_out_of_bound(self, codes):
401
+ empty_values = np.array([])
402
+ expected_codes = -np.ones_like(codes, dtype=np.intp)
403
+ _, result_codes = safe_sort(empty_values, codes)
404
+ tm.assert_numpy_array_equal(result_codes, expected_codes)
405
+
406
+ def test_mixed_integer(self):
407
+ values = np.array(["b", 1, 0, "a", 0, "b"], dtype=object)
408
+ result = safe_sort(values)
409
+ expected = np.array([0, 0, 1, "a", "b", "b"], dtype=object)
410
+ tm.assert_numpy_array_equal(result, expected)
411
+
412
+ def test_mixed_integer_with_codes(self):
413
+ values = np.array(["b", 1, 0, "a"], dtype=object)
414
+ codes = [0, 1, 2, 3, 0, -1, 1]
415
+ result, result_codes = safe_sort(values, codes)
416
+ expected = np.array([0, 1, "a", "b"], dtype=object)
417
+ expected_codes = np.array([3, 1, 0, 2, 3, -1, 1], dtype=np.intp)
418
+ tm.assert_numpy_array_equal(result, expected)
419
+ tm.assert_numpy_array_equal(result_codes, expected_codes)
420
+
421
+ def test_unsortable(self):
422
+ # GH 13714
423
+ arr = np.array([1, 2, datetime.now(), 0, 3], dtype=object)
424
+ msg = "'[<>]' not supported between instances of .*"
425
+ with pytest.raises(TypeError, match=msg):
426
+ safe_sort(arr)
427
+
428
+ @pytest.mark.parametrize(
429
+ "arg, codes, err, msg",
430
+ [
431
+ [1, None, TypeError, "Only np.ndarray, ExtensionArray, and Index"],
432
+ [np.array([0, 1, 2]), 1, TypeError, "Only list-like objects or None"],
433
+ [np.array([0, 1, 2, 1]), [0, 1], ValueError, "values should be unique"],
434
+ ],
435
+ )
436
+ def test_exceptions(self, arg, codes, err, msg):
437
+ with pytest.raises(err, match=msg):
438
+ safe_sort(values=arg, codes=codes)
439
+
440
+ @pytest.mark.parametrize(
441
+ "arg, exp", [[[1, 3, 2], [1, 2, 3]], [[1, 3, NA, 2], [1, 2, 3, NA]]]
442
+ )
443
+ def test_extension_array(self, arg, exp):
444
+ a = array(arg, dtype="Int64")
445
+ result = safe_sort(a)
446
+ expected = array(exp, dtype="Int64")
447
+ tm.assert_extension_array_equal(result, expected)
448
+
449
+ @pytest.mark.parametrize("verify", [True, False])
450
+ def test_extension_array_codes(self, verify):
451
+ a = array([1, 3, 2], dtype="Int64")
452
+ result, codes = safe_sort(a, [0, 1, -1, 2], use_na_sentinel=True, verify=verify)
453
+ expected_values = array([1, 2, 3], dtype="Int64")
454
+ expected_codes = np.array([0, 2, -1, 1], dtype=np.intp)
455
+ tm.assert_extension_array_equal(result, expected_values)
456
+ tm.assert_numpy_array_equal(codes, expected_codes)
457
+
458
+
459
+ def test_mixed_str_null(nulls_fixture):
460
+ values = np.array(["b", nulls_fixture, "a", "b"], dtype=object)
461
+ result = safe_sort(values)
462
+ expected = np.array(["a", "b", "b", nulls_fixture], dtype=object)
463
+ tm.assert_numpy_array_equal(result, expected)
464
+
465
+
466
+ def test_safe_sort_multiindex():
467
+ # GH#48412
468
+ arr1 = Series([2, 1, NA, NA], dtype="Int64")
469
+ arr2 = [2, 1, 3, 3]
470
+ midx = MultiIndex.from_arrays([arr1, arr2])
471
+ result = safe_sort(midx)
472
+ expected = MultiIndex.from_arrays(
473
+ [Series([1, 2, NA, NA], dtype="Int64"), [1, 2, 3, 3]]
474
+ )
475
+ tm.assert_index_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/test_take.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas._libs import iNaT
7
+
8
+ from pandas import array
9
+ import pandas._testing as tm
10
+ import pandas.core.algorithms as algos
11
+
12
+
13
+ @pytest.fixture(
14
+ params=[
15
+ (np.int8, np.int16(127), np.int8),
16
+ (np.int8, np.int16(128), np.int16),
17
+ (np.int32, 1, np.int32),
18
+ (np.int32, 2.0, np.float64),
19
+ (np.int32, 3.0 + 4.0j, np.complex128),
20
+ (np.int32, True, np.object_),
21
+ (np.int32, "", np.object_),
22
+ (np.float64, 1, np.float64),
23
+ (np.float64, 2.0, np.float64),
24
+ (np.float64, 3.0 + 4.0j, np.complex128),
25
+ (np.float64, True, np.object_),
26
+ (np.float64, "", np.object_),
27
+ (np.complex128, 1, np.complex128),
28
+ (np.complex128, 2.0, np.complex128),
29
+ (np.complex128, 3.0 + 4.0j, np.complex128),
30
+ (np.complex128, True, np.object_),
31
+ (np.complex128, "", np.object_),
32
+ (np.bool_, 1, np.object_),
33
+ (np.bool_, 2.0, np.object_),
34
+ (np.bool_, 3.0 + 4.0j, np.object_),
35
+ (np.bool_, True, np.bool_),
36
+ (np.bool_, "", np.object_),
37
+ ]
38
+ )
39
+ def dtype_fill_out_dtype(request):
40
+ return request.param
41
+
42
+
43
+ class TestTake:
44
+ def test_1d_fill_nonna(self, dtype_fill_out_dtype):
45
+ dtype, fill_value, out_dtype = dtype_fill_out_dtype
46
+ data = np.random.default_rng(2).integers(0, 2, 4).astype(dtype)
47
+ indexer = [2, 1, 0, -1]
48
+
49
+ result = algos.take_nd(data, indexer, fill_value=fill_value)
50
+ assert (result[[0, 1, 2]] == data[[2, 1, 0]]).all()
51
+ assert result[3] == fill_value
52
+ assert result.dtype == out_dtype
53
+
54
+ indexer = [2, 1, 0, 1]
55
+
56
+ result = algos.take_nd(data, indexer, fill_value=fill_value)
57
+ assert (result[[0, 1, 2, 3]] == data[indexer]).all()
58
+ assert result.dtype == dtype
59
+
60
+ def test_2d_fill_nonna(self, dtype_fill_out_dtype):
61
+ dtype, fill_value, out_dtype = dtype_fill_out_dtype
62
+ data = np.random.default_rng(2).integers(0, 2, (5, 3)).astype(dtype)
63
+ indexer = [2, 1, 0, -1]
64
+
65
+ result = algos.take_nd(data, indexer, axis=0, fill_value=fill_value)
66
+ assert (result[[0, 1, 2], :] == data[[2, 1, 0], :]).all()
67
+ assert (result[3, :] == fill_value).all()
68
+ assert result.dtype == out_dtype
69
+
70
+ result = algos.take_nd(data, indexer, axis=1, fill_value=fill_value)
71
+ assert (result[:, [0, 1, 2]] == data[:, [2, 1, 0]]).all()
72
+ assert (result[:, 3] == fill_value).all()
73
+ assert result.dtype == out_dtype
74
+
75
+ indexer = [2, 1, 0, 1]
76
+ result = algos.take_nd(data, indexer, axis=0, fill_value=fill_value)
77
+ assert (result[[0, 1, 2, 3], :] == data[indexer, :]).all()
78
+ assert result.dtype == dtype
79
+
80
+ result = algos.take_nd(data, indexer, axis=1, fill_value=fill_value)
81
+ assert (result[:, [0, 1, 2, 3]] == data[:, indexer]).all()
82
+ assert result.dtype == dtype
83
+
84
+ def test_3d_fill_nonna(self, dtype_fill_out_dtype):
85
+ dtype, fill_value, out_dtype = dtype_fill_out_dtype
86
+
87
+ data = np.random.default_rng(2).integers(0, 2, (5, 4, 3)).astype(dtype)
88
+ indexer = [2, 1, 0, -1]
89
+
90
+ result = algos.take_nd(data, indexer, axis=0, fill_value=fill_value)
91
+ assert (result[[0, 1, 2], :, :] == data[[2, 1, 0], :, :]).all()
92
+ assert (result[3, :, :] == fill_value).all()
93
+ assert result.dtype == out_dtype
94
+
95
+ result = algos.take_nd(data, indexer, axis=1, fill_value=fill_value)
96
+ assert (result[:, [0, 1, 2], :] == data[:, [2, 1, 0], :]).all()
97
+ assert (result[:, 3, :] == fill_value).all()
98
+ assert result.dtype == out_dtype
99
+
100
+ result = algos.take_nd(data, indexer, axis=2, fill_value=fill_value)
101
+ assert (result[:, :, [0, 1, 2]] == data[:, :, [2, 1, 0]]).all()
102
+ assert (result[:, :, 3] == fill_value).all()
103
+ assert result.dtype == out_dtype
104
+
105
+ indexer = [2, 1, 0, 1]
106
+ result = algos.take_nd(data, indexer, axis=0, fill_value=fill_value)
107
+ assert (result[[0, 1, 2, 3], :, :] == data[indexer, :, :]).all()
108
+ assert result.dtype == dtype
109
+
110
+ result = algos.take_nd(data, indexer, axis=1, fill_value=fill_value)
111
+ assert (result[:, [0, 1, 2, 3], :] == data[:, indexer, :]).all()
112
+ assert result.dtype == dtype
113
+
114
+ result = algos.take_nd(data, indexer, axis=2, fill_value=fill_value)
115
+ assert (result[:, :, [0, 1, 2, 3]] == data[:, :, indexer]).all()
116
+ assert result.dtype == dtype
117
+
118
+ def test_1d_other_dtypes(self):
119
+ arr = np.random.default_rng(2).standard_normal(10).astype(np.float32)
120
+
121
+ indexer = [1, 2, 3, -1]
122
+ result = algos.take_nd(arr, indexer)
123
+ expected = arr.take(indexer)
124
+ expected[-1] = np.nan
125
+ tm.assert_almost_equal(result, expected)
126
+
127
+ def test_2d_other_dtypes(self):
128
+ arr = np.random.default_rng(2).standard_normal((10, 5)).astype(np.float32)
129
+
130
+ indexer = [1, 2, 3, -1]
131
+
132
+ # axis=0
133
+ result = algos.take_nd(arr, indexer, axis=0)
134
+ expected = arr.take(indexer, axis=0)
135
+ expected[-1] = np.nan
136
+ tm.assert_almost_equal(result, expected)
137
+
138
+ # axis=1
139
+ result = algos.take_nd(arr, indexer, axis=1)
140
+ expected = arr.take(indexer, axis=1)
141
+ expected[:, -1] = np.nan
142
+ tm.assert_almost_equal(result, expected)
143
+
144
+ def test_1d_bool(self):
145
+ arr = np.array([0, 1, 0], dtype=bool)
146
+
147
+ result = algos.take_nd(arr, [0, 2, 2, 1])
148
+ expected = arr.take([0, 2, 2, 1])
149
+ tm.assert_numpy_array_equal(result, expected)
150
+
151
+ result = algos.take_nd(arr, [0, 2, -1])
152
+ assert result.dtype == np.object_
153
+
154
+ def test_2d_bool(self):
155
+ arr = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 1]], dtype=bool)
156
+
157
+ result = algos.take_nd(arr, [0, 2, 2, 1])
158
+ expected = arr.take([0, 2, 2, 1], axis=0)
159
+ tm.assert_numpy_array_equal(result, expected)
160
+
161
+ result = algos.take_nd(arr, [0, 2, 2, 1], axis=1)
162
+ expected = arr.take([0, 2, 2, 1], axis=1)
163
+ tm.assert_numpy_array_equal(result, expected)
164
+
165
+ result = algos.take_nd(arr, [0, 2, -1])
166
+ assert result.dtype == np.object_
167
+
168
+ def test_2d_float32(self):
169
+ arr = np.random.default_rng(2).standard_normal((4, 3)).astype(np.float32)
170
+ indexer = [0, 2, -1, 1, -1]
171
+
172
+ # axis=0
173
+ result = algos.take_nd(arr, indexer, axis=0)
174
+
175
+ expected = arr.take(indexer, axis=0)
176
+ expected[[2, 4], :] = np.nan
177
+ tm.assert_almost_equal(result, expected)
178
+
179
+ # axis=1
180
+ result = algos.take_nd(arr, indexer, axis=1)
181
+ expected = arr.take(indexer, axis=1)
182
+ expected[:, [2, 4]] = np.nan
183
+ tm.assert_almost_equal(result, expected)
184
+
185
+ def test_2d_datetime64(self):
186
+ # 2005/01/01 - 2006/01/01
187
+ arr = (
188
+ np.random.default_rng(2).integers(11_045_376, 11_360_736, (5, 3))
189
+ * 100_000_000_000
190
+ )
191
+ arr = arr.view(dtype="datetime64[ns]")
192
+ indexer = [0, 2, -1, 1, -1]
193
+
194
+ # axis=0
195
+ result = algos.take_nd(arr, indexer, axis=0)
196
+ expected = arr.take(indexer, axis=0)
197
+ expected.view(np.int64)[[2, 4], :] = iNaT
198
+ tm.assert_almost_equal(result, expected)
199
+
200
+ result = algos.take_nd(arr, indexer, axis=0, fill_value=datetime(2007, 1, 1))
201
+ expected = arr.take(indexer, axis=0)
202
+ expected[[2, 4], :] = datetime(2007, 1, 1)
203
+ tm.assert_almost_equal(result, expected)
204
+
205
+ # axis=1
206
+ result = algos.take_nd(arr, indexer, axis=1)
207
+ expected = arr.take(indexer, axis=1)
208
+ expected.view(np.int64)[:, [2, 4]] = iNaT
209
+ tm.assert_almost_equal(result, expected)
210
+
211
+ result = algos.take_nd(arr, indexer, axis=1, fill_value=datetime(2007, 1, 1))
212
+ expected = arr.take(indexer, axis=1)
213
+ expected[:, [2, 4]] = datetime(2007, 1, 1)
214
+ tm.assert_almost_equal(result, expected)
215
+
216
+ def test_take_axis_0(self):
217
+ arr = np.arange(12).reshape(4, 3)
218
+ result = algos.take(arr, [0, -1])
219
+ expected = np.array([[0, 1, 2], [9, 10, 11]])
220
+ tm.assert_numpy_array_equal(result, expected)
221
+
222
+ # allow_fill=True
223
+ result = algos.take(arr, [0, -1], allow_fill=True, fill_value=0)
224
+ expected = np.array([[0, 1, 2], [0, 0, 0]])
225
+ tm.assert_numpy_array_equal(result, expected)
226
+
227
+ def test_take_axis_1(self):
228
+ arr = np.arange(12).reshape(4, 3)
229
+ result = algos.take(arr, [0, -1], axis=1)
230
+ expected = np.array([[0, 2], [3, 5], [6, 8], [9, 11]])
231
+ tm.assert_numpy_array_equal(result, expected)
232
+
233
+ # allow_fill=True
234
+ result = algos.take(arr, [0, -1], axis=1, allow_fill=True, fill_value=0)
235
+ expected = np.array([[0, 0], [3, 0], [6, 0], [9, 0]])
236
+ tm.assert_numpy_array_equal(result, expected)
237
+
238
+ # GH#26976 make sure we validate along the correct axis
239
+ with pytest.raises(IndexError, match="indices are out-of-bounds"):
240
+ algos.take(arr, [0, 3], axis=1, allow_fill=True, fill_value=0)
241
+
242
+ def test_take_non_hashable_fill_value(self):
243
+ arr = np.array([1, 2, 3])
244
+ indexer = np.array([1, -1])
245
+ with pytest.raises(ValueError, match="fill_value must be a scalar"):
246
+ algos.take(arr, indexer, allow_fill=True, fill_value=[1])
247
+
248
+ # with object dtype it is allowed
249
+ arr = np.array([1, 2, 3], dtype=object)
250
+ result = algos.take(arr, indexer, allow_fill=True, fill_value=[1])
251
+ expected = np.array([2, [1]], dtype=object)
252
+ tm.assert_numpy_array_equal(result, expected)
253
+
254
+
255
+ class TestExtensionTake:
256
+ # The take method found in pd.api.extensions
257
+
258
+ def test_bounds_check_large(self):
259
+ arr = np.array([1, 2])
260
+
261
+ msg = "indices are out-of-bounds"
262
+ with pytest.raises(IndexError, match=msg):
263
+ algos.take(arr, [2, 3], allow_fill=True)
264
+
265
+ msg = "index 2 is out of bounds for( axis 0 with)? size 2"
266
+ with pytest.raises(IndexError, match=msg):
267
+ algos.take(arr, [2, 3], allow_fill=False)
268
+
269
+ def test_bounds_check_small(self):
270
+ arr = np.array([1, 2, 3], dtype=np.int64)
271
+ indexer = [0, -1, -2]
272
+
273
+ msg = r"'indices' contains values less than allowed \(-2 < -1\)"
274
+ with pytest.raises(ValueError, match=msg):
275
+ algos.take(arr, indexer, allow_fill=True)
276
+
277
+ result = algos.take(arr, indexer)
278
+ expected = np.array([1, 3, 2], dtype=np.int64)
279
+ tm.assert_numpy_array_equal(result, expected)
280
+
281
+ @pytest.mark.parametrize("allow_fill", [True, False])
282
+ def test_take_empty(self, allow_fill):
283
+ arr = np.array([], dtype=np.int64)
284
+ # empty take is ok
285
+ result = algos.take(arr, [], allow_fill=allow_fill)
286
+ tm.assert_numpy_array_equal(arr, result)
287
+
288
+ msg = "|".join(
289
+ [
290
+ "cannot do a non-empty take from an empty axes.",
291
+ "indices are out-of-bounds",
292
+ ]
293
+ )
294
+ with pytest.raises(IndexError, match=msg):
295
+ algos.take(arr, [0], allow_fill=allow_fill)
296
+
297
+ def test_take_na_empty(self):
298
+ result = algos.take(np.array([]), [-1, -1], allow_fill=True, fill_value=0.0)
299
+ expected = np.array([0.0, 0.0])
300
+ tm.assert_numpy_array_equal(result, expected)
301
+
302
+ def test_take_coerces_list(self):
303
+ # GH#52981 coercing is deprecated, disabled in 3.0
304
+ arr = [1, 2, 3]
305
+ msg = (
306
+ "pd.api.extensions.take requires a numpy.ndarray, ExtensionArray, "
307
+ "Index, Series, or NumpyExtensionArray got list"
308
+ )
309
+ with pytest.raises(TypeError, match=msg):
310
+ algos.take(arr, [0, 0])
311
+
312
+ def test_take_NumpyExtensionArray(self):
313
+ # GH#59177
314
+ arr = array([1 + 1j, 2, 3]) # NumpyEADtype('complex128') (NumpyExtensionArray)
315
+ assert algos.take(arr, [2]) == 2
316
+ arr = array([1, 2, 3]) # Int64Dtype() (ExtensionArray)
317
+ assert algos.take(arr, [2]) == 2
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/__init__.py ADDED
File without changes
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_datetime.py ADDED
The diff for this file is too large to render. See raw diff
 
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_numeric.py ADDED
@@ -0,0 +1,904 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import decimal
2
+
3
+ import numpy as np
4
+ from numpy import iinfo
5
+ import pytest
6
+
7
+ import pandas.util._test_decorators as td
8
+
9
+ import pandas as pd
10
+ from pandas import (
11
+ ArrowDtype,
12
+ DataFrame,
13
+ Index,
14
+ Series,
15
+ option_context,
16
+ to_numeric,
17
+ )
18
+ import pandas._testing as tm
19
+
20
+
21
+ @pytest.fixture(params=[None, "raise", "coerce"])
22
+ def errors(request):
23
+ return request.param
24
+
25
+
26
+ @pytest.fixture(params=[True, False])
27
+ def signed(request):
28
+ return request.param
29
+
30
+
31
+ @pytest.fixture(params=[lambda x: x, str], ids=["identity", "str"])
32
+ def transform(request):
33
+ return request.param
34
+
35
+
36
+ @pytest.fixture(params=[47393996303418497800, 100000000000000000000])
37
+ def large_val(request):
38
+ return request.param
39
+
40
+
41
+ @pytest.fixture(params=[True, False])
42
+ def multiple_elts(request):
43
+ return request.param
44
+
45
+
46
+ @pytest.fixture(
47
+ params=[
48
+ (lambda x: Index(x, name="idx"), tm.assert_index_equal),
49
+ (lambda x: Series(x, name="ser"), tm.assert_series_equal),
50
+ (lambda x: np.array(Index(x).values), tm.assert_numpy_array_equal),
51
+ ]
52
+ )
53
+ def transform_assert_equal(request):
54
+ return request.param
55
+
56
+
57
+ @pytest.mark.parametrize(
58
+ "input_kwargs,result_kwargs",
59
+ [
60
+ ({}, {"dtype": np.int64}),
61
+ ({"errors": "coerce", "downcast": "integer"}, {"dtype": np.int8}),
62
+ ],
63
+ )
64
+ def test_empty(input_kwargs, result_kwargs):
65
+ # see gh-16302
66
+ ser = Series([], dtype=object)
67
+ result = to_numeric(ser, **input_kwargs)
68
+
69
+ expected = Series([], **result_kwargs)
70
+ tm.assert_series_equal(result, expected)
71
+
72
+
73
+ @pytest.mark.parametrize(
74
+ "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
75
+ )
76
+ @pytest.mark.parametrize("last_val", ["7", 7])
77
+ def test_series(last_val, infer_string):
78
+ with option_context("future.infer_string", infer_string):
79
+ ser = Series(["1", "-3.14", last_val])
80
+ result = to_numeric(ser)
81
+
82
+ expected = Series([1, -3.14, 7])
83
+ tm.assert_series_equal(result, expected)
84
+
85
+
86
+ @pytest.mark.parametrize(
87
+ "data",
88
+ [
89
+ [1, 3, 4, 5],
90
+ [1.0, 3.0, 4.0, 5.0],
91
+ # Bool is regarded as numeric.
92
+ [True, False, True, True],
93
+ ],
94
+ )
95
+ def test_series_numeric(data):
96
+ ser = Series(data, index=list("ABCD"), name="EFG")
97
+
98
+ result = to_numeric(ser)
99
+ tm.assert_series_equal(result, ser)
100
+
101
+
102
+ @pytest.mark.parametrize(
103
+ "data,msg",
104
+ [
105
+ ([1, -3.14, "apple"], 'Unable to parse string "apple" at position 2'),
106
+ (
107
+ ["orange", 1, -3.14, "apple"],
108
+ 'Unable to parse string "orange" at position 0',
109
+ ),
110
+ ],
111
+ )
112
+ def test_error(data, msg):
113
+ ser = Series(data)
114
+
115
+ with pytest.raises(ValueError, match=msg):
116
+ to_numeric(ser, errors="raise")
117
+
118
+
119
+ def test_ignore_error():
120
+ ser = Series([1, -3.14, "apple"])
121
+ result = to_numeric(ser, errors="coerce")
122
+
123
+ expected = Series([1, -3.14, np.nan])
124
+ tm.assert_series_equal(result, expected)
125
+
126
+
127
+ @pytest.mark.parametrize(
128
+ "errors,exp",
129
+ [
130
+ ("raise", 'Unable to parse string "apple" at position 2'),
131
+ # Coerces to float.
132
+ ("coerce", [1.0, 0.0, np.nan]),
133
+ ],
134
+ )
135
+ def test_bool_handling(errors, exp):
136
+ ser = Series([True, False, "apple"])
137
+
138
+ if isinstance(exp, str):
139
+ with pytest.raises(ValueError, match=exp):
140
+ to_numeric(ser, errors=errors)
141
+ else:
142
+ result = to_numeric(ser, errors=errors)
143
+ expected = Series(exp)
144
+
145
+ tm.assert_series_equal(result, expected)
146
+
147
+
148
+ def test_list():
149
+ ser = ["1", "-3.14", "7"]
150
+ res = to_numeric(ser)
151
+
152
+ expected = np.array([1, -3.14, 7])
153
+ tm.assert_numpy_array_equal(res, expected)
154
+
155
+
156
+ @pytest.mark.parametrize(
157
+ "data,arr_kwargs",
158
+ [
159
+ ([1, 3, 4, 5], {"dtype": np.int64}),
160
+ ([1.0, 3.0, 4.0, 5.0], {}),
161
+ # Boolean is regarded as numeric.
162
+ ([True, False, True, True], {}),
163
+ ],
164
+ )
165
+ def test_list_numeric(data, arr_kwargs):
166
+ result = to_numeric(data)
167
+ expected = np.array(data, **arr_kwargs)
168
+ tm.assert_numpy_array_equal(result, expected)
169
+
170
+
171
+ @pytest.mark.parametrize("kwargs", [{"dtype": "O"}, {}])
172
+ def test_numeric(kwargs):
173
+ data = [1, -3.14, 7]
174
+
175
+ ser = Series(data, **kwargs)
176
+ result = to_numeric(ser)
177
+
178
+ expected = Series(data)
179
+ tm.assert_series_equal(result, expected)
180
+
181
+
182
+ @pytest.mark.parametrize(
183
+ "columns",
184
+ [
185
+ # One column.
186
+ "a",
187
+ # Multiple columns.
188
+ ["a", "b"],
189
+ ],
190
+ )
191
+ def test_numeric_df_columns(columns):
192
+ # see gh-14827
193
+ df = DataFrame(
194
+ {
195
+ "a": [1.2, decimal.Decimal("3.14"), decimal.Decimal("infinity"), "0.1"],
196
+ "b": [1.0, 2.0, 3.0, 4.0],
197
+ }
198
+ )
199
+
200
+ expected = DataFrame({"a": [1.2, 3.14, np.inf, 0.1], "b": [1.0, 2.0, 3.0, 4.0]})
201
+ df[columns] = df[columns].apply(to_numeric)
202
+
203
+ tm.assert_frame_equal(df, expected)
204
+
205
+
206
+ @pytest.mark.parametrize(
207
+ "data,exp_data",
208
+ [
209
+ (
210
+ [[decimal.Decimal("3.14"), 1.0], decimal.Decimal("1.6"), 0.1],
211
+ [[3.14, 1.0], 1.6, 0.1],
212
+ ),
213
+ ([np.array([decimal.Decimal("3.14"), 1.0]), 0.1], [[3.14, 1.0], 0.1]),
214
+ ],
215
+ )
216
+ def test_numeric_embedded_arr_likes(data, exp_data):
217
+ # Test to_numeric with embedded lists and arrays
218
+ df = DataFrame({"a": data})
219
+ df["a"] = df["a"].apply(to_numeric)
220
+
221
+ expected = DataFrame({"a": exp_data})
222
+ tm.assert_frame_equal(df, expected)
223
+
224
+
225
+ def test_all_nan():
226
+ ser = Series(["a", "b", "c"])
227
+ result = to_numeric(ser, errors="coerce")
228
+
229
+ expected = Series([np.nan, np.nan, np.nan])
230
+ tm.assert_series_equal(result, expected)
231
+
232
+
233
+ def test_type_check(errors):
234
+ # see gh-11776
235
+ df = DataFrame({"a": [1, -3.14, 7], "b": ["4", "5", "6"]})
236
+ kwargs = {"errors": errors} if errors is not None else {}
237
+ with pytest.raises(TypeError, match="1-d array"):
238
+ to_numeric(df, **kwargs)
239
+
240
+
241
+ @pytest.mark.parametrize("val", [1, 1.1, 20001])
242
+ def test_scalar(val, signed, transform):
243
+ val = -val if signed else val
244
+ assert to_numeric(transform(val)) == float(val)
245
+
246
+
247
+ def test_really_large_scalar(large_val, signed, transform, errors):
248
+ # see gh-24910
249
+ kwargs = {"errors": errors} if errors is not None else {}
250
+ val = -large_val if signed else large_val
251
+
252
+ val = transform(val)
253
+
254
+ expected = float(val) if errors == "coerce" else int(val)
255
+ tm.assert_almost_equal(to_numeric(val, **kwargs), expected)
256
+
257
+
258
+ def test_really_large_in_arr(large_val, signed, transform, multiple_elts, errors):
259
+ # see gh-24910
260
+ kwargs = {"errors": errors} if errors is not None else {}
261
+ val = -large_val if signed else large_val
262
+ val = transform(val)
263
+
264
+ extra_elt = "string"
265
+ arr = [val] + multiple_elts * [extra_elt]
266
+
267
+ coercing = errors == "coerce"
268
+
269
+ if errors in (None, "raise") and multiple_elts:
270
+ msg = 'Unable to parse string "string" at position 1'
271
+
272
+ with pytest.raises(ValueError, match=msg):
273
+ to_numeric(arr, **kwargs)
274
+ else:
275
+ result = to_numeric(arr, **kwargs)
276
+
277
+ exp_val = float(val) if (coercing) else int(val)
278
+ expected = [exp_val]
279
+
280
+ if multiple_elts:
281
+ if coercing:
282
+ expected.append(np.nan)
283
+ exp_dtype = float
284
+ else:
285
+ expected.append(extra_elt)
286
+ exp_dtype = object
287
+ else:
288
+ exp_dtype = float if isinstance(exp_val, float) else object
289
+
290
+ tm.assert_almost_equal(result, np.array(expected, dtype=exp_dtype))
291
+
292
+
293
+ def test_really_large_in_arr_consistent(large_val, signed, multiple_elts, errors):
294
+ # see gh-24910
295
+ #
296
+ # Even if we discover that we have to hold float, does not mean
297
+ # we should be lenient on subsequent elements that fail to be integer.
298
+ kwargs = {"errors": errors} if errors is not None else {}
299
+ arr = [str(-large_val if signed else large_val)]
300
+
301
+ if multiple_elts:
302
+ arr.insert(0, large_val)
303
+
304
+ result = to_numeric(arr, **kwargs)
305
+ expected = [float(i) if errors == "coerce" else int(i) for i in arr]
306
+ exp_dtype = float if errors == "coerce" else object
307
+
308
+ tm.assert_almost_equal(result, np.array(expected, dtype=exp_dtype))
309
+
310
+
311
+ @pytest.mark.parametrize(
312
+ "errors,checker",
313
+ [
314
+ ("raise", 'Unable to parse string "fail" at position 0'),
315
+ ("coerce", lambda x: np.isnan(x)),
316
+ ],
317
+ )
318
+ def test_scalar_fail(errors, checker):
319
+ scalar = "fail"
320
+
321
+ if isinstance(checker, str):
322
+ with pytest.raises(ValueError, match=checker):
323
+ to_numeric(scalar, errors=errors)
324
+ else:
325
+ assert checker(to_numeric(scalar, errors=errors))
326
+
327
+
328
+ @pytest.mark.parametrize("data", [[1, 2, 3], [1.0, np.nan, 3, np.nan]])
329
+ def test_numeric_dtypes(data, transform_assert_equal):
330
+ transform, assert_equal = transform_assert_equal
331
+ data = transform(data)
332
+
333
+ result = to_numeric(data)
334
+ assert_equal(result, data)
335
+
336
+
337
+ @pytest.mark.parametrize(
338
+ "data,exp",
339
+ [
340
+ (["1", "2", "3"], np.array([1, 2, 3], dtype="int64")),
341
+ (["1.5", "2.7", "3.4"], np.array([1.5, 2.7, 3.4])),
342
+ ],
343
+ )
344
+ def test_str(data, exp, transform_assert_equal):
345
+ transform, assert_equal = transform_assert_equal
346
+ result = to_numeric(transform(data))
347
+
348
+ expected = transform(exp)
349
+ assert_equal(result, expected)
350
+
351
+
352
+ def test_datetime_like(tz_naive_fixture, transform_assert_equal):
353
+ transform, assert_equal = transform_assert_equal
354
+ idx = pd.date_range("20130101", periods=3, tz=tz_naive_fixture)
355
+
356
+ result = to_numeric(transform(idx))
357
+ expected = transform(idx.asi8)
358
+ assert_equal(result, expected)
359
+
360
+
361
+ def test_timedelta(transform_assert_equal):
362
+ transform, assert_equal = transform_assert_equal
363
+ idx = pd.timedelta_range("1 days", periods=3, freq="D")
364
+
365
+ result = to_numeric(transform(idx))
366
+ expected = transform(idx.asi8)
367
+ assert_equal(result, expected)
368
+
369
+
370
+ @pytest.mark.parametrize(
371
+ "scalar",
372
+ [
373
+ pd.Timedelta(1, "D"),
374
+ pd.Timestamp("2017-01-01T12"),
375
+ pd.Timestamp("2017-01-01T12", tz="US/Pacific"),
376
+ ],
377
+ )
378
+ def test_timedelta_timestamp_scalar(scalar):
379
+ # GH#59944
380
+ result = to_numeric(scalar)
381
+ expected = to_numeric(Series(scalar))[0]
382
+ assert result == expected
383
+
384
+
385
+ def test_period(request, transform_assert_equal):
386
+ transform, assert_equal = transform_assert_equal
387
+
388
+ idx = pd.period_range("2011-01", periods=3, freq="M", name="")
389
+ inp = transform(idx)
390
+
391
+ if not isinstance(inp, Index):
392
+ request.applymarker(
393
+ pytest.mark.xfail(reason="Missing PeriodDtype support in to_numeric")
394
+ )
395
+ result = to_numeric(inp)
396
+ expected = transform(idx.asi8)
397
+ assert_equal(result, expected)
398
+
399
+
400
+ @pytest.mark.parametrize(
401
+ "errors,expected",
402
+ [
403
+ ("raise", "Invalid object type at position 0"),
404
+ ("coerce", Series([np.nan, 1.0, np.nan])),
405
+ ],
406
+ )
407
+ def test_non_hashable(errors, expected):
408
+ # see gh-13324
409
+ ser = Series([[10.0, 2], 1.0, "apple"])
410
+
411
+ if isinstance(expected, str):
412
+ with pytest.raises(TypeError, match=expected):
413
+ to_numeric(ser, errors=errors)
414
+ else:
415
+ result = to_numeric(ser, errors=errors)
416
+ tm.assert_series_equal(result, expected)
417
+
418
+
419
+ def test_downcast_invalid_cast():
420
+ # see gh-13352
421
+ data = ["1", 2, 3]
422
+ invalid_downcast = "unsigned-integer"
423
+ msg = "invalid downcasting method provided"
424
+
425
+ with pytest.raises(ValueError, match=msg):
426
+ to_numeric(data, downcast=invalid_downcast)
427
+
428
+
429
+ def test_errors_invalid_value():
430
+ # see gh-26466
431
+ data = ["1", 2, 3]
432
+ invalid_error_value = "invalid"
433
+ msg = "invalid error value specified"
434
+
435
+ with pytest.raises(ValueError, match=msg):
436
+ to_numeric(data, errors=invalid_error_value)
437
+
438
+
439
+ @pytest.mark.parametrize(
440
+ "data",
441
+ [
442
+ ["1", 2, 3],
443
+ [1, 2, 3],
444
+ np.array(["1970-01-02", "1970-01-03", "1970-01-04"], dtype="datetime64[D]"),
445
+ ],
446
+ )
447
+ @pytest.mark.parametrize(
448
+ "kwargs,exp_dtype",
449
+ [
450
+ # Basic function tests.
451
+ ({}, np.int64),
452
+ ({"downcast": None}, np.int64),
453
+ # Support below np.float32 is rare and far between.
454
+ ({"downcast": "float"}, np.dtype(np.float32).char),
455
+ # Basic dtype support.
456
+ ({"downcast": "unsigned"}, np.dtype(np.typecodes["UnsignedInteger"][0])),
457
+ ],
458
+ )
459
+ def test_downcast_basic(data, kwargs, exp_dtype):
460
+ # see gh-13352
461
+ result = to_numeric(data, **kwargs)
462
+ expected = np.array([1, 2, 3], dtype=exp_dtype)
463
+ tm.assert_numpy_array_equal(result, expected)
464
+
465
+
466
+ @pytest.mark.parametrize("signed_downcast", ["integer", "signed"])
467
+ @pytest.mark.parametrize(
468
+ "data",
469
+ [
470
+ ["1", 2, 3],
471
+ [1, 2, 3],
472
+ np.array(["1970-01-02", "1970-01-03", "1970-01-04"], dtype="datetime64[D]"),
473
+ ],
474
+ )
475
+ def test_signed_downcast(data, signed_downcast):
476
+ # see gh-13352
477
+ smallest_int_dtype = np.dtype(np.typecodes["Integer"][0])
478
+ expected = np.array([1, 2, 3], dtype=smallest_int_dtype)
479
+
480
+ res = to_numeric(data, downcast=signed_downcast)
481
+ tm.assert_numpy_array_equal(res, expected)
482
+
483
+
484
+ def test_ignore_downcast_neg_to_unsigned():
485
+ # Cannot cast to an unsigned integer
486
+ # because we have a negative number.
487
+ data = ["-1", 2, 3]
488
+ expected = np.array([-1, 2, 3], dtype=np.int64)
489
+
490
+ res = to_numeric(data, downcast="unsigned")
491
+ tm.assert_numpy_array_equal(res, expected)
492
+
493
+
494
+ # Warning in 32 bit platforms
495
+ @pytest.mark.parametrize("downcast", ["integer", "signed", "unsigned"])
496
+ @pytest.mark.parametrize(
497
+ "data,expected",
498
+ [
499
+ (["1.1", 2, 3], np.array([1.1, 2, 3], dtype=np.float64)),
500
+ (
501
+ [10000.0, 20000, 3000, 40000.36, 50000, 50000.00],
502
+ np.array(
503
+ [10000.0, 20000, 3000, 40000.36, 50000, 50000.00], dtype=np.float64
504
+ ),
505
+ ),
506
+ ],
507
+ )
508
+ def test_ignore_downcast_cannot_convert_float(data, expected, downcast):
509
+ # Cannot cast to an integer (signed or unsigned)
510
+ # because we have a float number.
511
+ res = to_numeric(data, downcast=downcast)
512
+ tm.assert_numpy_array_equal(res, expected)
513
+
514
+
515
+ @pytest.mark.parametrize(
516
+ "downcast,expected_dtype",
517
+ [("integer", np.int16), ("signed", np.int16), ("unsigned", np.uint16)],
518
+ )
519
+ def test_downcast_not8bit(downcast, expected_dtype):
520
+ # the smallest integer dtype need not be np.(u)int8
521
+ data = ["256", 257, 258]
522
+
523
+ expected = np.array([256, 257, 258], dtype=expected_dtype)
524
+ res = to_numeric(data, downcast=downcast)
525
+ tm.assert_numpy_array_equal(res, expected)
526
+
527
+
528
+ @pytest.mark.parametrize(
529
+ "dtype,downcast,min_max",
530
+ [
531
+ ("int8", "integer", [iinfo(np.int8).min, iinfo(np.int8).max]),
532
+ ("int16", "integer", [iinfo(np.int16).min, iinfo(np.int16).max]),
533
+ ("int32", "integer", [iinfo(np.int32).min, iinfo(np.int32).max]),
534
+ ("int64", "integer", [iinfo(np.int64).min, iinfo(np.int64).max]),
535
+ ("uint8", "unsigned", [iinfo(np.uint8).min, iinfo(np.uint8).max]),
536
+ ("uint16", "unsigned", [iinfo(np.uint16).min, iinfo(np.uint16).max]),
537
+ ("uint32", "unsigned", [iinfo(np.uint32).min, iinfo(np.uint32).max]),
538
+ ("uint64", "unsigned", [iinfo(np.uint64).min, iinfo(np.uint64).max]),
539
+ ("int16", "integer", [iinfo(np.int8).min, iinfo(np.int8).max + 1]),
540
+ ("int32", "integer", [iinfo(np.int16).min, iinfo(np.int16).max + 1]),
541
+ ("int64", "integer", [iinfo(np.int32).min, iinfo(np.int32).max + 1]),
542
+ ("int16", "integer", [iinfo(np.int8).min - 1, iinfo(np.int16).max]),
543
+ ("int32", "integer", [iinfo(np.int16).min - 1, iinfo(np.int32).max]),
544
+ ("int64", "integer", [iinfo(np.int32).min - 1, iinfo(np.int64).max]),
545
+ ("uint16", "unsigned", [iinfo(np.uint8).min, iinfo(np.uint8).max + 1]),
546
+ ("uint32", "unsigned", [iinfo(np.uint16).min, iinfo(np.uint16).max + 1]),
547
+ ("uint64", "unsigned", [iinfo(np.uint32).min, iinfo(np.uint32).max + 1]),
548
+ ],
549
+ )
550
+ def test_downcast_limits(dtype, downcast, min_max):
551
+ # see gh-14404: test the limits of each downcast.
552
+ series = to_numeric(Series(min_max), downcast=downcast)
553
+ assert series.dtype == dtype
554
+
555
+
556
+ def test_downcast_float64_to_float32():
557
+ # GH-43693: Check float64 preservation when >= 16,777,217
558
+ series = Series([16777217.0, np.finfo(np.float64).max, np.nan], dtype=np.float64)
559
+ result = to_numeric(series, downcast="float")
560
+
561
+ assert series.dtype == result.dtype
562
+
563
+
564
+ def test_downcast_uint64():
565
+ # see gh-14422:
566
+ # BUG: to_numeric doesn't work uint64 numbers
567
+ ser = Series([0, 9223372036854775808])
568
+ result = to_numeric(ser, downcast="unsigned")
569
+ expected = Series([0, 9223372036854775808], dtype=np.uint64)
570
+ tm.assert_series_equal(result, expected)
571
+
572
+
573
+ @pytest.mark.parametrize(
574
+ "data,exp_data",
575
+ [
576
+ (
577
+ [200, 300, "", "NaN", 30000000000000000000],
578
+ [200, 300, np.nan, np.nan, 30000000000000000000],
579
+ ),
580
+ (
581
+ ["12345678901234567890", "1234567890", "ITEM"],
582
+ [12345678901234567890, 1234567890, np.nan],
583
+ ),
584
+ ],
585
+ )
586
+ def test_coerce_uint64_conflict(data, exp_data):
587
+ # see gh-17007 and gh-17125
588
+ #
589
+ # Still returns float despite the uint64-nan conflict,
590
+ # which would normally force the casting to object.
591
+ result = to_numeric(Series(data), errors="coerce")
592
+ expected = Series(exp_data, dtype=float)
593
+ tm.assert_series_equal(result, expected)
594
+
595
+
596
+ def test_non_coerce_uint64_conflict():
597
+ # see gh-17007 and gh-17125
598
+ #
599
+ # For completeness.
600
+ ser = Series(["12345678901234567890", "1234567890", "ITEM"])
601
+
602
+ with pytest.raises(ValueError, match="Unable to parse string"):
603
+ to_numeric(ser, errors="raise")
604
+
605
+
606
+ @pytest.mark.parametrize("dc1", ["integer", "float", "unsigned"])
607
+ @pytest.mark.parametrize("dc2", ["integer", "float", "unsigned"])
608
+ def test_downcast_empty(dc1, dc2):
609
+ # GH32493
610
+
611
+ tm.assert_numpy_array_equal(
612
+ to_numeric([], downcast=dc1),
613
+ to_numeric([], downcast=dc2),
614
+ check_dtype=False,
615
+ )
616
+
617
+
618
+ def test_failure_to_convert_uint64_string_to_NaN():
619
+ # GH 32394
620
+ result = to_numeric("uint64", errors="coerce")
621
+ assert np.isnan(result)
622
+
623
+ ser = Series([32, 64, np.nan])
624
+ result = to_numeric(Series(["32", "64", "uint64"]), errors="coerce")
625
+ tm.assert_series_equal(result, ser)
626
+
627
+
628
+ @pytest.mark.parametrize(
629
+ "strrep",
630
+ [
631
+ "243.164",
632
+ "245.968",
633
+ "249.585",
634
+ "259.745",
635
+ "265.742",
636
+ "272.567",
637
+ "279.196",
638
+ "280.366",
639
+ "275.034",
640
+ "271.351",
641
+ "272.889",
642
+ "270.627",
643
+ "280.828",
644
+ "290.383",
645
+ "308.153",
646
+ "319.945",
647
+ "336.0",
648
+ "344.09",
649
+ "351.385",
650
+ "356.178",
651
+ "359.82",
652
+ "361.03",
653
+ "367.701",
654
+ "380.812",
655
+ "387.98",
656
+ "391.749",
657
+ "391.171",
658
+ "385.97",
659
+ "385.345",
660
+ "386.121",
661
+ "390.996",
662
+ "399.734",
663
+ "413.073",
664
+ "421.532",
665
+ "430.221",
666
+ "437.092",
667
+ "439.746",
668
+ "446.01",
669
+ "451.191",
670
+ "460.463",
671
+ "469.779",
672
+ "472.025",
673
+ "479.49",
674
+ "474.864",
675
+ "467.54",
676
+ "471.978",
677
+ ],
678
+ )
679
+ def test_precision_float_conversion(strrep):
680
+ # GH 31364
681
+ result = to_numeric(strrep)
682
+
683
+ assert result == float(strrep)
684
+
685
+
686
+ @pytest.mark.parametrize(
687
+ "values, expected",
688
+ [
689
+ (["1", "2", None], Series([1, 2, pd.NA], dtype="Int64")),
690
+ (["1", "2", "3"], Series([1, 2, 3], dtype="Int64")),
691
+ (["1", "2", 3], Series([1, 2, 3], dtype="Int64")),
692
+ (["1", "2", 3.5], Series([1, 2, 3.5], dtype="Float64")),
693
+ (["1", None, 3.5], Series([1, pd.NA, 3.5], dtype="Float64")),
694
+ (["1", "2", "3.5"], Series([1, 2, 3.5], dtype="Float64")),
695
+ ],
696
+ )
697
+ def test_to_numeric_from_nullable_string(values, nullable_string_dtype, expected):
698
+ # https://github.com/pandas-dev/pandas/issues/37262
699
+ s = Series(values, dtype=nullable_string_dtype)
700
+ result = to_numeric(s)
701
+ tm.assert_series_equal(result, expected)
702
+
703
+
704
+ def test_to_numeric_from_nullable_string_coerce(nullable_string_dtype):
705
+ # GH#52146
706
+ values = ["a", "1"]
707
+ ser = Series(values, dtype=nullable_string_dtype)
708
+ result = to_numeric(ser, errors="coerce")
709
+ expected = Series([pd.NA, 1], dtype="Int64")
710
+ tm.assert_series_equal(result, expected)
711
+
712
+
713
+ @pytest.mark.parametrize(
714
+ "data, input_dtype, downcast, expected_dtype",
715
+ (
716
+ ([1, 1], "Int64", "integer", "Int8"),
717
+ ([1.0, pd.NA], "Float64", "integer", "Int8"),
718
+ ([1.0, 1.1], "Float64", "integer", "Float64"),
719
+ ([1, pd.NA], "Int64", "integer", "Int8"),
720
+ ([450, 300], "Int64", "integer", "Int16"),
721
+ ([1, 1], "Float64", "integer", "Int8"),
722
+ ([np.iinfo(np.int64).max - 1, 1], "Int64", "integer", "Int64"),
723
+ ([1, 1], "Int64", "signed", "Int8"),
724
+ ([1.0, 1.0], "Float32", "signed", "Int8"),
725
+ ([1.0, 1.1], "Float64", "signed", "Float64"),
726
+ ([1, pd.NA], "Int64", "signed", "Int8"),
727
+ ([450, -300], "Int64", "signed", "Int16"),
728
+ ([np.iinfo(np.uint64).max - 1, 1], "UInt64", "signed", "UInt64"),
729
+ ([1, 1], "Int64", "unsigned", "UInt8"),
730
+ ([1.0, 1.0], "Float32", "unsigned", "UInt8"),
731
+ ([1.0, 1.1], "Float64", "unsigned", "Float64"),
732
+ ([1, pd.NA], "Int64", "unsigned", "UInt8"),
733
+ ([450, -300], "Int64", "unsigned", "Int64"),
734
+ ([-1, -1], "Int32", "unsigned", "Int32"),
735
+ ([1, 1], "Float64", "float", "Float32"),
736
+ ([1, 1.1], "Float64", "float", "Float32"),
737
+ ([1, 1], "Float32", "float", "Float32"),
738
+ ([1, 1.1], "Float32", "float", "Float32"),
739
+ ),
740
+ )
741
+ def test_downcast_nullable_numeric(data, input_dtype, downcast, expected_dtype):
742
+ arr = pd.array(data, dtype=input_dtype)
743
+ result = to_numeric(arr, downcast=downcast)
744
+ expected = pd.array(data, dtype=expected_dtype)
745
+ tm.assert_extension_array_equal(result, expected)
746
+
747
+
748
+ def test_downcast_nullable_mask_is_copied():
749
+ # GH38974
750
+
751
+ arr = pd.array([1, 2, pd.NA], dtype="Int64")
752
+
753
+ result = to_numeric(arr, downcast="integer")
754
+ expected = pd.array([1, 2, pd.NA], dtype="Int8")
755
+ tm.assert_extension_array_equal(result, expected)
756
+
757
+ arr[1] = pd.NA # should not modify result
758
+ tm.assert_extension_array_equal(result, expected)
759
+
760
+
761
+ def test_to_numeric_scientific_notation():
762
+ # GH 15898
763
+ result = to_numeric("1.7e+308")
764
+ expected = np.float64(1.7e308)
765
+ assert result == expected
766
+
767
+
768
+ @pytest.mark.parametrize("val", [9876543210.0, 2.0**128])
769
+ def test_to_numeric_large_float_not_downcast_to_float_32(val):
770
+ # GH 19729
771
+ expected = Series([val])
772
+ result = to_numeric(expected, downcast="float")
773
+ tm.assert_series_equal(result, expected)
774
+
775
+
776
+ @pytest.mark.parametrize(
777
+ "val, dtype", [(1, "Int64"), (1.5, "Float64"), (True, "boolean")]
778
+ )
779
+ def test_to_numeric_dtype_backend(val, dtype):
780
+ # GH#50505
781
+ ser = Series([val], dtype=object)
782
+ result = to_numeric(ser, dtype_backend="numpy_nullable")
783
+ expected = Series([val], dtype=dtype)
784
+ tm.assert_series_equal(result, expected)
785
+
786
+
787
+ @pytest.mark.parametrize(
788
+ "val, dtype",
789
+ [
790
+ (1, "Int64"),
791
+ (1.5, "Float64"),
792
+ (True, "boolean"),
793
+ (1, "int64[pyarrow]"),
794
+ (1.5, "float64[pyarrow]"),
795
+ (True, "bool[pyarrow]"),
796
+ ],
797
+ )
798
+ def test_to_numeric_dtype_backend_na(val, dtype):
799
+ # GH#50505
800
+ if "pyarrow" in dtype:
801
+ pytest.importorskip("pyarrow")
802
+ dtype_backend = "pyarrow"
803
+ else:
804
+ dtype_backend = "numpy_nullable"
805
+ ser = Series([val, None], dtype=object)
806
+ result = to_numeric(ser, dtype_backend=dtype_backend)
807
+ expected = Series([val, pd.NA], dtype=dtype)
808
+ tm.assert_series_equal(result, expected)
809
+
810
+
811
+ @pytest.mark.parametrize(
812
+ "val, dtype, downcast",
813
+ [
814
+ (1, "Int8", "integer"),
815
+ (1.5, "Float32", "float"),
816
+ (1, "Int8", "signed"),
817
+ (1, "int8[pyarrow]", "integer"),
818
+ (1.5, "float[pyarrow]", "float"),
819
+ (1, "int8[pyarrow]", "signed"),
820
+ ],
821
+ )
822
+ def test_to_numeric_dtype_backend_downcasting(val, dtype, downcast):
823
+ # GH#50505
824
+ if "pyarrow" in dtype:
825
+ pytest.importorskip("pyarrow")
826
+ dtype_backend = "pyarrow"
827
+ else:
828
+ dtype_backend = "numpy_nullable"
829
+ ser = Series([val, None], dtype=object)
830
+ result = to_numeric(ser, dtype_backend=dtype_backend, downcast=downcast)
831
+ expected = Series([val, pd.NA], dtype=dtype)
832
+ tm.assert_series_equal(result, expected)
833
+
834
+
835
+ @pytest.mark.parametrize(
836
+ "smaller, dtype_backend",
837
+ [["UInt8", "numpy_nullable"], ["uint8[pyarrow]", "pyarrow"]],
838
+ )
839
+ def test_to_numeric_dtype_backend_downcasting_uint(smaller, dtype_backend):
840
+ # GH#50505
841
+ if dtype_backend == "pyarrow":
842
+ pytest.importorskip("pyarrow")
843
+ ser = Series([1, pd.NA], dtype="UInt64")
844
+ result = to_numeric(ser, dtype_backend=dtype_backend, downcast="unsigned")
845
+ expected = Series([1, pd.NA], dtype=smaller)
846
+ tm.assert_series_equal(result, expected)
847
+
848
+
849
+ @pytest.mark.parametrize(
850
+ "dtype",
851
+ [
852
+ "Int64",
853
+ "UInt64",
854
+ "Float64",
855
+ "boolean",
856
+ "int64[pyarrow]",
857
+ "uint64[pyarrow]",
858
+ "float64[pyarrow]",
859
+ "bool[pyarrow]",
860
+ ],
861
+ )
862
+ def test_to_numeric_dtype_backend_already_nullable(dtype):
863
+ # GH#50505
864
+ if "pyarrow" in dtype:
865
+ pytest.importorskip("pyarrow")
866
+ ser = Series([1, pd.NA], dtype=dtype)
867
+ result = to_numeric(ser, dtype_backend="numpy_nullable")
868
+ expected = Series([1, pd.NA], dtype=dtype)
869
+ tm.assert_series_equal(result, expected)
870
+
871
+
872
+ def test_to_numeric_dtype_backend_error(dtype_backend):
873
+ # GH#50505
874
+ ser = Series(["a", "b", ""])
875
+ expected = ser.copy()
876
+ with pytest.raises(ValueError, match="Unable to parse string"):
877
+ to_numeric(ser, dtype_backend=dtype_backend)
878
+
879
+ result = to_numeric(ser, dtype_backend=dtype_backend, errors="coerce")
880
+ if dtype_backend == "pyarrow":
881
+ dtype = "double[pyarrow]"
882
+ else:
883
+ dtype = "Float64"
884
+ expected = Series([pd.NA, pd.NA, pd.NA], dtype=dtype)
885
+ tm.assert_series_equal(result, expected)
886
+
887
+
888
+ def test_invalid_dtype_backend():
889
+ ser = Series([1, 2, 3])
890
+ msg = (
891
+ "dtype_backend numpy is invalid, only 'numpy_nullable' and "
892
+ "'pyarrow' are allowed."
893
+ )
894
+ with pytest.raises(ValueError, match=msg):
895
+ to_numeric(ser, dtype_backend="numpy")
896
+
897
+
898
+ def test_coerce_pyarrow_backend():
899
+ # GH 52588
900
+ pa = pytest.importorskip("pyarrow")
901
+ ser = Series(list("12x"), dtype=ArrowDtype(pa.string()))
902
+ result = to_numeric(ser, errors="coerce", dtype_backend="pyarrow")
903
+ expected = Series([1, 2, None], dtype=ArrowDtype(pa.int64()))
904
+ tm.assert_series_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_time.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import time
2
+ import locale
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas import Series
8
+ import pandas._testing as tm
9
+ from pandas.core.tools.times import to_time
10
+
11
+ # The tests marked with this are locale-dependent.
12
+ # They pass, except when the machine locale is zh_CN or it_IT.
13
+ fails_on_non_english = pytest.mark.xfail(
14
+ locale.getlocale()[0] in ("zh_CN", "it_IT"),
15
+ reason="fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8",
16
+ strict=False,
17
+ )
18
+
19
+
20
+ class TestToTime:
21
+ @pytest.mark.parametrize(
22
+ "time_string",
23
+ [
24
+ "14:15",
25
+ "1415",
26
+ pytest.param("2:15pm", marks=fails_on_non_english),
27
+ pytest.param("0215pm", marks=fails_on_non_english),
28
+ "14:15:00",
29
+ "141500",
30
+ pytest.param("2:15:00pm", marks=fails_on_non_english),
31
+ pytest.param("021500pm", marks=fails_on_non_english),
32
+ time(14, 15),
33
+ ],
34
+ )
35
+ def test_parsers_time(self, time_string):
36
+ # GH#11818
37
+ assert to_time(time_string) == time(14, 15)
38
+
39
+ def test_odd_format(self):
40
+ new_string = "14.15"
41
+ assert to_time(new_string, format="%H.%M") == time(14, 15)
42
+
43
+ def test_arraylike(self):
44
+ arg = ["14:15", "20:20"]
45
+ expected_arr = [time(14, 15), time(20, 20)]
46
+ assert to_time(arg) == expected_arr
47
+ assert to_time(arg, format="%H:%M") == expected_arr
48
+ assert to_time(arg, infer_time_format=True) == expected_arr
49
+ assert to_time(arg, format="%I:%M%p", errors="coerce") == [None, None]
50
+
51
+ with pytest.raises(ValueError, match="errors must be"):
52
+ to_time(arg, format="%I:%M%p", errors="ignore")
53
+
54
+ msg = "Cannot convert.+to a time with given format"
55
+ with pytest.raises(ValueError, match=msg):
56
+ to_time(arg, format="%I:%M%p", errors="raise")
57
+
58
+ tm.assert_series_equal(
59
+ to_time(Series(arg, name="test")), Series(expected_arr, name="test")
60
+ )
61
+
62
+ res = to_time(np.array(arg))
63
+ assert isinstance(res, list)
64
+ assert res == expected_arr
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tools/test_to_timedelta.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ time,
3
+ timedelta,
4
+ )
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas.compat import (
10
+ IS64,
11
+ WASM,
12
+ )
13
+ from pandas.errors import (
14
+ OutOfBoundsTimedelta,
15
+ Pandas4Warning,
16
+ )
17
+
18
+ import pandas as pd
19
+ from pandas import (
20
+ Series,
21
+ TimedeltaIndex,
22
+ isna,
23
+ to_timedelta,
24
+ )
25
+ import pandas._testing as tm
26
+ from pandas.core.arrays import TimedeltaArray
27
+
28
+
29
+ class TestTimedeltas:
30
+ def test_to_timedelta_mixed_unit_strings(self):
31
+ # https://github.com/pandas-dev/pandas/pull/63196#issuecomment-3595743721
32
+ result = to_timedelta(["1 days 06:05:01.00003", "15.5us"])
33
+
34
+ expected = TimedeltaIndex([108_301_000_030_000, 15_500], dtype="m8[ns]")
35
+ tm.assert_index_equal(result, expected)
36
+
37
+ def test_to_timedelta_all_nat_unit(self):
38
+ # With all-NaT entries, we get "s" unit
39
+ result = to_timedelta([None])
40
+ assert result.unit == "s"
41
+
42
+ result = TimedeltaIndex([None])
43
+ assert result.unit == "s"
44
+
45
+ def test_to_timedelta_month_raises(self):
46
+ obj = np.timedelta64(1, "M")
47
+
48
+ msg = "Unit M is not supported."
49
+ with pytest.raises(ValueError, match=msg):
50
+ to_timedelta(obj)
51
+ with pytest.raises(ValueError, match=msg):
52
+ pd.Timedelta(obj)
53
+ with pytest.raises(ValueError, match=msg):
54
+ to_timedelta([obj])
55
+ with pytest.raises(ValueError, match=msg):
56
+ TimedeltaIndex([obj])
57
+
58
+ def test_to_timedelta_none(self):
59
+ # GH#23055
60
+ assert to_timedelta(None) is pd.NaT
61
+
62
+ def test_to_timedelta_dt64_raises(self):
63
+ # Passing datetime64-dtype data to TimedeltaIndex is no longer
64
+ # supported GH#29794
65
+ msg = r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]"
66
+
67
+ ser = Series([pd.NaT], dtype="M8[ns]")
68
+ with pytest.raises(TypeError, match=msg):
69
+ to_timedelta(ser)
70
+ with pytest.raises(TypeError, match=msg):
71
+ ser.to_frame().apply(to_timedelta)
72
+
73
+ def test_to_timedelta_readonly(self, writable):
74
+ # GH#34857
75
+ arr = np.array([], dtype=object)
76
+ arr.setflags(write=writable)
77
+ result = to_timedelta(arr)
78
+ expected = to_timedelta([])
79
+ tm.assert_index_equal(result, expected)
80
+
81
+ def test_to_timedelta_null(self):
82
+ result = to_timedelta(["", ""])
83
+ assert isna(result).all()
84
+
85
+ def test_to_timedelta_same_np_timedelta64(self):
86
+ # pass thru
87
+ result = to_timedelta(np.array([np.timedelta64(1, "s")]))
88
+ expected = pd.Index(np.array([np.timedelta64(1, "s")]))
89
+ tm.assert_index_equal(result, expected)
90
+
91
+ def test_to_timedelta_series(self):
92
+ # Series
93
+ expected = Series(
94
+ [timedelta(days=1), timedelta(days=1, seconds=1)], dtype="m8[us]"
95
+ )
96
+
97
+ msg = "'d' is deprecated and will be removed in a future version."
98
+ with tm.assert_produces_warning(Pandas4Warning, match=msg):
99
+ result = to_timedelta(Series(["1d", "1days 00:00:01"]))
100
+ tm.assert_series_equal(result, expected)
101
+
102
+ def test_to_timedelta_units(self):
103
+ # with units
104
+ result = TimedeltaIndex(
105
+ [np.timedelta64(0, "ns"), np.timedelta64(10, "s").astype("m8[ns]")]
106
+ )
107
+ expected = to_timedelta([0, 10], unit="s").as_unit("ns")
108
+ tm.assert_index_equal(result, expected)
109
+
110
+ def test_to_timedelta_mixed_dtype(self):
111
+ # https://github.com/pandas-dev/pandas/issues/64044
112
+ result = to_timedelta(np.array([0.5, 2]), unit="m")
113
+ expected = TimedeltaIndex(
114
+ ["0 days 00:00:30", "0 days 00:02:00"], dtype="timedelta64[ns]", freq=None
115
+ )
116
+ tm.assert_index_equal(result, expected)
117
+
118
+ @pytest.mark.parametrize(
119
+ "dtype, unit",
120
+ [
121
+ ["int64", "s"],
122
+ ["int64", "m"],
123
+ ["int64", "h"],
124
+ ["timedelta64[s]", "s"],
125
+ ["timedelta64[D]", "D"],
126
+ ],
127
+ )
128
+ def test_to_timedelta_units_dtypes(self, dtype, unit):
129
+ # arrays of various dtypes
130
+ arr = np.array([1] * 5, dtype=dtype)
131
+ result = to_timedelta(arr, unit=unit)
132
+ exp_dtype = "m8[s]"
133
+ expected = TimedeltaIndex([np.timedelta64(1, unit)] * 5, dtype=exp_dtype)
134
+ tm.assert_index_equal(result, expected)
135
+
136
+ def test_to_timedelta_oob_non_nano(self):
137
+ arr = np.array([pd.NaT._value + 1], dtype="timedelta64[m]")
138
+
139
+ msg = (
140
+ "Cannot convert -9223372036854775807 minutes to "
141
+ r"timedelta64\[s\] without overflow"
142
+ )
143
+ with pytest.raises(OutOfBoundsTimedelta, match=msg):
144
+ to_timedelta(arr)
145
+
146
+ with pytest.raises(OutOfBoundsTimedelta, match=msg):
147
+ TimedeltaIndex(arr)
148
+
149
+ with pytest.raises(OutOfBoundsTimedelta, match=msg):
150
+ TimedeltaArray._from_sequence(arr, dtype="m8[s]")
151
+
152
+ @pytest.mark.parametrize("box", [lambda x: x, pd.DataFrame])
153
+ @pytest.mark.parametrize("errors", ["raise", "coerce"])
154
+ def test_to_timedelta_dataframe(self, box, errors):
155
+ # GH 11776
156
+ arg = box(np.arange(10).reshape(2, 5))
157
+ with pytest.raises(TypeError, match="1-d array"):
158
+ to_timedelta(arg, errors=errors)
159
+
160
+ def test_to_timedelta_invalid_errors(self):
161
+ # bad value for errors parameter
162
+ msg = "errors must be one of"
163
+ with pytest.raises(ValueError, match=msg):
164
+ to_timedelta(["foo"], errors="never")
165
+
166
+ @pytest.mark.parametrize("arg", [[1, 2], 1])
167
+ def test_to_timedelta_invalid_unit(self, arg):
168
+ # these will error
169
+ msg = "invalid unit abbreviation: foo"
170
+ with pytest.raises(ValueError, match=msg):
171
+ to_timedelta(arg, unit="foo")
172
+
173
+ def test_to_timedelta_time(self):
174
+ # time not supported ATM
175
+ msg = (
176
+ "Value must be Timedelta, string, integer, float, timedelta or convertible"
177
+ )
178
+ with pytest.raises(ValueError, match=msg):
179
+ to_timedelta(time(second=1))
180
+ assert to_timedelta(time(second=1), errors="coerce") is pd.NaT
181
+
182
+ def test_to_timedelta_bad_value(self):
183
+ msg = "Could not convert 'foo' to NumPy timedelta"
184
+ with pytest.raises(ValueError, match=msg):
185
+ to_timedelta(["foo", "bar"])
186
+
187
+ def test_to_timedelta_bad_value_coerce(self):
188
+ tm.assert_index_equal(
189
+ TimedeltaIndex([pd.NaT, pd.NaT]),
190
+ to_timedelta(["foo", "bar"], errors="coerce"),
191
+ )
192
+
193
+ tm.assert_index_equal(
194
+ TimedeltaIndex(["1 day", pd.NaT, "1 min"]),
195
+ to_timedelta(["1 day", "bar", "1 min"], errors="coerce"),
196
+ )
197
+
198
+ @pytest.mark.parametrize(
199
+ "val, errors",
200
+ [
201
+ ("1M", True),
202
+ ("1 M", True),
203
+ ("1Y", True),
204
+ ("1 Y", True),
205
+ ("1y", True),
206
+ ("1 y", True),
207
+ ("1m", False),
208
+ ("1 m", False),
209
+ ("1 day", False),
210
+ ("2day", False),
211
+ ],
212
+ )
213
+ def test_unambiguous_timedelta_values(self, val, errors):
214
+ # GH36666 Deprecate use of strings denoting units with 'M', 'Y', 'm' or 'y'
215
+ # in pd.to_timedelta
216
+ msg = "Units 'M', 'Y' and 'y' do not represent unambiguous timedelta"
217
+ if errors:
218
+ with pytest.raises(ValueError, match=msg):
219
+ to_timedelta(val)
220
+ else:
221
+ # check it doesn't raise
222
+ to_timedelta(val)
223
+
224
+ def test_to_timedelta_via_apply(self):
225
+ # GH 5458
226
+ expected = Series([np.timedelta64(1, "s")], dtype="m8[us]")
227
+ result = Series(["00:00:01"]).apply(to_timedelta)
228
+ tm.assert_series_equal(result, expected)
229
+
230
+ result = Series([to_timedelta("00:00:01")])
231
+ tm.assert_series_equal(result, expected)
232
+
233
+ def test_to_timedelta_inference_without_warning(self):
234
+ # GH#41731 inference produces a warning in the Series constructor,
235
+ # but _not_ in to_timedelta
236
+ vals = ["00:00:01", pd.NaT]
237
+ with tm.assert_produces_warning(None):
238
+ result = to_timedelta(vals)
239
+
240
+ expected = TimedeltaIndex([pd.Timedelta(seconds=1), pd.NaT], dtype="m8[us]")
241
+ tm.assert_index_equal(result, expected)
242
+
243
+ def test_to_timedelta_on_missing_values(self):
244
+ # GH5438
245
+ timedelta_NaT = np.timedelta64("NaT", "ns")
246
+
247
+ actual = to_timedelta(Series(["00:00:01", np.nan]))
248
+ expected = Series(
249
+ [np.timedelta64(1000000000, "ns"), timedelta_NaT],
250
+ dtype=f"{tm.ENDIAN}m8[us]",
251
+ )
252
+ tm.assert_series_equal(actual, expected)
253
+
254
+ ser = Series(["00:00:01", pd.NaT], dtype="m8[us]")
255
+ actual = to_timedelta(ser)
256
+ tm.assert_series_equal(actual, expected)
257
+
258
+ @pytest.mark.parametrize("val", [np.nan, pd.NaT, pd.NA])
259
+ def test_to_timedelta_on_missing_values_scalar(self, val):
260
+ actual = to_timedelta(val)
261
+ assert actual._value == np.timedelta64("NaT", "ns").astype("int64")
262
+
263
+ @pytest.mark.parametrize("val", [np.nan, pd.NaT, pd.NA])
264
+ def test_to_timedelta_on_missing_values_list(self, val):
265
+ actual = to_timedelta([val])
266
+ assert actual[0]._value == np.timedelta64("NaT", "ns").astype("int64")
267
+
268
+ @pytest.mark.skipif(WASM, reason="No fp exception support in WASM")
269
+ @pytest.mark.xfail(not IS64, reason="Floating point error")
270
+ def test_to_timedelta_float(self):
271
+ # https://github.com/pandas-dev/pandas/issues/25077
272
+ arr = np.arange(0, 1, 1e-6)[-10:]
273
+ result = to_timedelta(arr, unit="s")
274
+ expected_asi8 = np.arange(999990000, 10**9, 1000, dtype="int64")
275
+ tm.assert_numpy_array_equal(result.asi8, expected_asi8)
276
+
277
+ def test_to_timedelta_coerce_strings_unit(self):
278
+ arr = np.array([1, 2, "error"], dtype=object)
279
+ result = to_timedelta(arr, unit="ns", errors="coerce")
280
+ expected = to_timedelta([1, 2, pd.NaT], unit="ns")
281
+ tm.assert_index_equal(result, expected)
282
+
283
+ @pytest.mark.parametrize(
284
+ "expected_val, result_val", [[timedelta(days=2), 2], [None, None]]
285
+ )
286
+ def test_to_timedelta_nullable_int64_dtype(self, expected_val, result_val):
287
+ # GH 35574
288
+ expected = Series([timedelta(days=1), expected_val], dtype="m8[s]")
289
+ result = to_timedelta(Series([1, result_val], dtype="Int64"), unit="days")
290
+
291
+ tm.assert_series_equal(result, expected)
292
+
293
+ @pytest.mark.parametrize(
294
+ ("input", "expected"),
295
+ [
296
+ ("8:53:08.71800000001", "8:53:08.718"),
297
+ ("8:53:08.718001", "8:53:08.718001"),
298
+ ("8:53:08.7180000001", "8:53:08.7180000001"),
299
+ ("-8:53:08.71800000001", "-8:53:08.718"),
300
+ ("8:53:08.7180000089", "8:53:08.718000008"),
301
+ ],
302
+ )
303
+ @pytest.mark.parametrize("func", [pd.Timedelta, to_timedelta])
304
+ def test_to_timedelta_precision_over_nanos(self, input, expected, func):
305
+ # GH: 36738
306
+ expected = pd.Timedelta(expected)
307
+ result = func(input)
308
+ assert result == expected
309
+
310
+ def test_to_timedelta_zerodim(self, fixed_now_ts):
311
+ # ndarray.item() incorrectly returns int for dt64[ns] and td64[ns]
312
+ dt64 = fixed_now_ts.to_datetime64()
313
+ arg = np.array(dt64)
314
+
315
+ msg = (
316
+ "Value must be Timedelta, string, integer, float, timedelta "
317
+ "or convertible, not datetime64"
318
+ )
319
+ with pytest.raises(ValueError, match=msg):
320
+ to_timedelta(arg)
321
+
322
+ arg2 = arg.view("m8[ns]")
323
+ result = to_timedelta(arg2)
324
+ assert isinstance(result, pd.Timedelta)
325
+ assert result._value == dt64.view("i8")
326
+
327
+ def test_to_timedelta_numeric_ea(self, any_numeric_ea_dtype):
328
+ # GH#48796
329
+ ser = Series([1, pd.NA], dtype=any_numeric_ea_dtype)
330
+ result = to_timedelta(ser)
331
+ expected = Series([pd.Timedelta(1, unit="ns"), pd.NaT])
332
+ tm.assert_series_equal(result, expected)
333
+
334
+ def test_to_timedelta_fraction(self):
335
+ result = to_timedelta(1.0 / 3, unit="h")
336
+ expected = pd.Timedelta("0 days 00:19:59.999999998")
337
+ assert result == expected
338
+
339
+ def test_to_timedelta_unit_round_floats(self):
340
+ # When the float is round, we give the requested unit
341
+ # (or nearest-supported) like we do with integers
342
+ arr = np.array([45.0], dtype=object)
343
+ result = to_timedelta(arr, unit="s")
344
+ expected = to_timedelta([45], unit="s")
345
+ tm.assert_index_equal(result, expected)
346
+
347
+ arr2 = arr.astype(np.float64)
348
+ result2 = to_timedelta(arr2, unit="s")
349
+ tm.assert_index_equal(result2, expected)
350
+
351
+ def test_to_timedelta_unit_non_round_floats(self):
352
+ # With non-round floats, we have to give nanosecond
353
+ arr = np.array([45.5], dtype=object)
354
+ result = to_timedelta(arr, unit="s")
355
+ assert result.unit == "ns"
356
+
357
+ arr2 = arr.astype(np.float64)
358
+ result2 = to_timedelta(arr2, unit="s")
359
+ assert result2.unit == "ns"
360
+
361
+ def test_to_timedelta_unit_mixed_round_and_non_round_floats(self):
362
+ # GH#65150 - round floats mixed with non-round floats should
363
+ # respect the unit for all values
364
+ expected = to_timedelta(["0 days 00:00:01", "0 days 00:00:01.01"]).as_unit("ns")
365
+
366
+ result = to_timedelta([1.0, 1.01], unit="s")
367
+ tm.assert_index_equal(result, expected)
368
+
369
+ # Also test integers mixed with non-round floats
370
+ result2 = to_timedelta([1, 1.01], unit="s")
371
+ tm.assert_index_equal(result2, expected)
372
+
373
+
374
+ def test_from_numeric_arrow_dtype(any_numeric_ea_dtype):
375
+ # GH 52425
376
+ pytest.importorskip("pyarrow")
377
+ ser = Series([1, 2], dtype=f"{any_numeric_ea_dtype.lower()}[pyarrow]")
378
+ result = to_timedelta(ser)
379
+ expected = Series([1, 2], dtype="timedelta64[ns]")
380
+ tm.assert_series_equal(result, expected)
381
+
382
+
383
+ @pytest.mark.parametrize("unit", ["ns", "ms"])
384
+ def test_from_timedelta_arrow_dtype(unit):
385
+ # GH 54298
386
+ pytest.importorskip("pyarrow")
387
+ expected = Series([timedelta(1)], dtype=f"duration[{unit}][pyarrow]")
388
+ result = to_timedelta(expected)
389
+ tm.assert_series_equal(result, expected)
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tseries/__init__.py ADDED
File without changes
couto/12yd/.venv/lib/python3.12/site-packages/pandas/tests/tseries/frequencies/__init__.py ADDED
File without changes