Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/INSTALLER +1 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/LICENSE +1250 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/METADATA +1574 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/RECORD +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/REQUESTED +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/WHEEL +6 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/entry_points.txt +3 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/constructors/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/constructors/test_from_dict.py +223 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/constructors/test_from_records.py +503 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_coercion.py +209 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_delitem.py +60 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_get.py +27 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_get_value.py +22 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_getitem.py +472 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_indexing.py +2033 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_insert.py +120 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_mask.py +152 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_set_value.py +77 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_setitem.py +1526 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_take.py +92 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_where.py +1104 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_xs.py +444 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/__init__.py +7 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_add_prefix_suffix.py +49 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_align.py +484 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_asfreq.py +263 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_asof.py +198 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_assign.py +84 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_astype.py +924 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_at_time.py +132 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_between_time.py +227 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_clip.py +199 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_combine.py +47 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_combine_first.py +556 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_compare.py +305 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_convert_dtypes.py +198 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_copy.py +64 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_count.py +39 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_cov_corr.py +470 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_describe.py +417 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_diff.py +308 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_dot.py +155 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_drop.py +546 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_drop_duplicates.py +473 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_droplevel.py +36 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_dropna.py +285 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_dtypes.py +150 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_duplicated.py +117 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,1250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-2023, 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.Apache License
|
| 1061 |
+
Version 2.0, January 2004
|
| 1062 |
+
http://www.apache.org/licenses/
|
| 1063 |
+
|
| 1064 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 1065 |
+
|
| 1066 |
+
1. Definitions.
|
| 1067 |
+
|
| 1068 |
+
"License" shall mean the terms and conditions for use, reproduction, and
|
| 1069 |
+
distribution as defined by Sections 1 through 9 of this document.
|
| 1070 |
+
|
| 1071 |
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
| 1072 |
+
owner that is granting the License.
|
| 1073 |
+
|
| 1074 |
+
"Legal Entity" shall mean the union of the acting entity and all other entities
|
| 1075 |
+
that control, are controlled by, or are under common control with that entity.
|
| 1076 |
+
For the purposes of this definition, "control" means (i) the power, direct or
|
| 1077 |
+
indirect, to cause the direction or management of such entity, whether by
|
| 1078 |
+
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 1079 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 1080 |
+
|
| 1081 |
+
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
| 1082 |
+
permissions granted by this License.
|
| 1083 |
+
|
| 1084 |
+
"Source" form shall mean the preferred form for making modifications, including
|
| 1085 |
+
but not limited to software source code, documentation source, and configuration
|
| 1086 |
+
files.
|
| 1087 |
+
|
| 1088 |
+
"Object" form shall mean any form resulting from mechanical transformation or
|
| 1089 |
+
translation of a Source form, including but not limited to compiled object code,
|
| 1090 |
+
generated documentation, and conversions to other media types.
|
| 1091 |
+
|
| 1092 |
+
"Work" shall mean the work of authorship, whether in Source or Object form, made
|
| 1093 |
+
available under the License, as indicated by a copyright notice that is included
|
| 1094 |
+
in or attached to the work (an example is provided in the Appendix below).
|
| 1095 |
+
|
| 1096 |
+
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
| 1097 |
+
is based on (or derived from) the Work and for which the editorial revisions,
|
| 1098 |
+
annotations, elaborations, or other modifications represent, as a whole, an
|
| 1099 |
+
original work of authorship. For the purposes of this License, Derivative Works
|
| 1100 |
+
shall not include works that remain separable from, or merely link (or bind by
|
| 1101 |
+
name) to the interfaces of, the Work and Derivative Works thereof.
|
| 1102 |
+
|
| 1103 |
+
"Contribution" shall mean any work of authorship, including the original version
|
| 1104 |
+
of the Work and any modifications or additions to that Work or Derivative Works
|
| 1105 |
+
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
| 1106 |
+
by the copyright owner or by an individual or Legal Entity authorized to submit
|
| 1107 |
+
on behalf of the copyright owner. For the purposes of this definition,
|
| 1108 |
+
"submitted" means any form of electronic, verbal, or written communication sent
|
| 1109 |
+
to the Licensor or its representatives, including but not limited to
|
| 1110 |
+
communication on electronic mailing lists, source code control systems, and
|
| 1111 |
+
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
| 1112 |
+
the purpose of discussing and improving the Work, but excluding communication
|
| 1113 |
+
that is conspicuously marked or otherwise designated in writing by the copyright
|
| 1114 |
+
owner as "Not a Contribution."
|
| 1115 |
+
|
| 1116 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
| 1117 |
+
of whom a Contribution has been received by Licensor and subsequently
|
| 1118 |
+
incorporated within the Work.
|
| 1119 |
+
|
| 1120 |
+
2. Grant of Copyright License.
|
| 1121 |
+
|
| 1122 |
+
Subject to the terms and conditions of this License, each Contributor hereby
|
| 1123 |
+
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
| 1124 |
+
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
| 1125 |
+
publicly display, publicly perform, sublicense, and distribute the Work and such
|
| 1126 |
+
Derivative Works in Source or Object form.
|
| 1127 |
+
|
| 1128 |
+
3. Grant of Patent License.
|
| 1129 |
+
|
| 1130 |
+
Subject to the terms and conditions of this License, each Contributor hereby
|
| 1131 |
+
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
| 1132 |
+
irrevocable (except as stated in this section) patent license to make, have
|
| 1133 |
+
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
| 1134 |
+
such license applies only to those patent claims licensable by such Contributor
|
| 1135 |
+
that are necessarily infringed by their Contribution(s) alone or by combination
|
| 1136 |
+
of their Contribution(s) with the Work to which such Contribution(s) was
|
| 1137 |
+
submitted. If You institute patent litigation against any entity (including a
|
| 1138 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
| 1139 |
+
Contribution incorporated within the Work constitutes direct or contributory
|
| 1140 |
+
patent infringement, then any patent licenses granted to You under this License
|
| 1141 |
+
for that Work shall terminate as of the date such litigation is filed.
|
| 1142 |
+
|
| 1143 |
+
4. Redistribution.
|
| 1144 |
+
|
| 1145 |
+
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
| 1146 |
+
in any medium, with or without modifications, and in Source or Object form,
|
| 1147 |
+
provided that You meet the following conditions:
|
| 1148 |
+
|
| 1149 |
+
You must give any other recipients of the Work or Derivative Works a copy of
|
| 1150 |
+
this License; and
|
| 1151 |
+
You must cause any modified files to carry prominent notices stating that You
|
| 1152 |
+
changed the files; and
|
| 1153 |
+
You must retain, in the Source form of any Derivative Works that You distribute,
|
| 1154 |
+
all copyright, patent, trademark, and attribution notices from the Source form
|
| 1155 |
+
of the Work, excluding those notices that do not pertain to any part of the
|
| 1156 |
+
Derivative Works; and
|
| 1157 |
+
If the Work includes a "NOTICE" text file as part of its distribution, then any
|
| 1158 |
+
Derivative Works that You distribute must include a readable copy of the
|
| 1159 |
+
attribution notices contained within such NOTICE file, excluding those notices
|
| 1160 |
+
that do not pertain to any part of the Derivative Works, in at least one of the
|
| 1161 |
+
following places: within a NOTICE text file distributed as part of the
|
| 1162 |
+
Derivative Works; within the Source form or documentation, if provided along
|
| 1163 |
+
with the Derivative Works; or, within a display generated by the Derivative
|
| 1164 |
+
Works, if and wherever such third-party notices normally appear. The contents of
|
| 1165 |
+
the NOTICE file are for informational purposes only and do not modify the
|
| 1166 |
+
License. You may add Your own attribution notices within Derivative Works that
|
| 1167 |
+
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
| 1168 |
+
provided that such additional attribution notices cannot be construed as
|
| 1169 |
+
modifying the License.
|
| 1170 |
+
You may add Your own copyright statement to Your modifications and may provide
|
| 1171 |
+
additional or different license terms and conditions for use, reproduction, or
|
| 1172 |
+
distribution of Your modifications, or for any such Derivative Works as a whole,
|
| 1173 |
+
provided Your use, reproduction, and distribution of the Work otherwise complies
|
| 1174 |
+
with the conditions stated in this License.
|
| 1175 |
+
|
| 1176 |
+
5. Submission of Contributions.
|
| 1177 |
+
|
| 1178 |
+
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
| 1179 |
+
for inclusion in the Work by You to the Licensor shall be under the terms and
|
| 1180 |
+
conditions of this License, without any additional terms or conditions.
|
| 1181 |
+
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
| 1182 |
+
any separate license agreement you may have executed with Licensor regarding
|
| 1183 |
+
such Contributions.
|
| 1184 |
+
|
| 1185 |
+
6. Trademarks.
|
| 1186 |
+
|
| 1187 |
+
This License does not grant permission to use the trade names, trademarks,
|
| 1188 |
+
service marks, or product names of the Licensor, except as required for
|
| 1189 |
+
reasonable and customary use in describing the origin of the Work and
|
| 1190 |
+
reproducing the content of the NOTICE file.
|
| 1191 |
+
|
| 1192 |
+
7. Disclaimer of Warranty.
|
| 1193 |
+
|
| 1194 |
+
Unless required by applicable law or agreed to in writing, Licensor provides the
|
| 1195 |
+
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 1196 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
| 1197 |
+
including, without limitation, any warranties or conditions of TITLE,
|
| 1198 |
+
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
| 1199 |
+
solely responsible for determining the appropriateness of using or
|
| 1200 |
+
redistributing the Work and assume any risks associated with Your exercise of
|
| 1201 |
+
permissions under this License.
|
| 1202 |
+
|
| 1203 |
+
8. Limitation of Liability.
|
| 1204 |
+
|
| 1205 |
+
In no event and under no legal theory, whether in tort (including negligence),
|
| 1206 |
+
contract, or otherwise, unless required by applicable law (such as deliberate
|
| 1207 |
+
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
| 1208 |
+
liable to You for damages, including any direct, indirect, special, incidental,
|
| 1209 |
+
or consequential damages of any character arising as a result of this License or
|
| 1210 |
+
out of the use or inability to use the Work (including but not limited to
|
| 1211 |
+
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
| 1212 |
+
any and all other commercial damages or losses), even if such Contributor has
|
| 1213 |
+
been advised of the possibility of such damages.
|
| 1214 |
+
|
| 1215 |
+
9. Accepting Warranty or Additional Liability.
|
| 1216 |
+
|
| 1217 |
+
While redistributing the Work or Derivative Works thereof, You may choose to
|
| 1218 |
+
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
| 1219 |
+
other liability obligations and/or rights consistent with this License. However,
|
| 1220 |
+
in accepting such obligations, You may act only on Your own behalf and on Your
|
| 1221 |
+
sole responsibility, not on behalf of any other Contributor, and only if You
|
| 1222 |
+
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
| 1223 |
+
incurred by, or claims asserted against, such Contributor by reason of your
|
| 1224 |
+
accepting any such warranty or additional liability.
|
| 1225 |
+
|
| 1226 |
+
END OF TERMS AND CONDITIONS
|
| 1227 |
+
|
| 1228 |
+
APPENDIX: How to apply the Apache License to your work
|
| 1229 |
+
|
| 1230 |
+
To apply the Apache License to your work, attach the following boilerplate
|
| 1231 |
+
notice, with the fields enclosed by brackets "[]" replaced with your own
|
| 1232 |
+
identifying information. (Don't include the brackets!) The text should be
|
| 1233 |
+
enclosed in the appropriate comment syntax for the file format. We also
|
| 1234 |
+
recommend that a file or class name and description of purpose be included on
|
| 1235 |
+
the same "printed page" as the copyright notice for easier identification within
|
| 1236 |
+
third-party archives.
|
| 1237 |
+
|
| 1238 |
+
Copyright [yyyy] [name of copyright owner]
|
| 1239 |
+
|
| 1240 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 1241 |
+
you may not use this file except in compliance with the License.
|
| 1242 |
+
You may obtain a copy of the License at
|
| 1243 |
+
|
| 1244 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 1245 |
+
|
| 1246 |
+
Unless required by applicable law or agreed to in writing, software
|
| 1247 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 1248 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 1249 |
+
See the License for the specific language governing permissions and
|
| 1250 |
+
limitations under the License.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/METADATA
ADDED
|
@@ -0,0 +1,1574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: pandas
|
| 3 |
+
Version: 2.3.3
|
| 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-2023, 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.Apache License
|
| 1066 |
+
Version 2.0, January 2004
|
| 1067 |
+
http://www.apache.org/licenses/
|
| 1068 |
+
|
| 1069 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 1070 |
+
|
| 1071 |
+
1. Definitions.
|
| 1072 |
+
|
| 1073 |
+
"License" shall mean the terms and conditions for use, reproduction, and
|
| 1074 |
+
distribution as defined by Sections 1 through 9 of this document.
|
| 1075 |
+
|
| 1076 |
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
| 1077 |
+
owner that is granting the License.
|
| 1078 |
+
|
| 1079 |
+
"Legal Entity" shall mean the union of the acting entity and all other entities
|
| 1080 |
+
that control, are controlled by, or are under common control with that entity.
|
| 1081 |
+
For the purposes of this definition, "control" means (i) the power, direct or
|
| 1082 |
+
indirect, to cause the direction or management of such entity, whether by
|
| 1083 |
+
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 1084 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 1085 |
+
|
| 1086 |
+
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
| 1087 |
+
permissions granted by this License.
|
| 1088 |
+
|
| 1089 |
+
"Source" form shall mean the preferred form for making modifications, including
|
| 1090 |
+
but not limited to software source code, documentation source, and configuration
|
| 1091 |
+
files.
|
| 1092 |
+
|
| 1093 |
+
"Object" form shall mean any form resulting from mechanical transformation or
|
| 1094 |
+
translation of a Source form, including but not limited to compiled object code,
|
| 1095 |
+
generated documentation, and conversions to other media types.
|
| 1096 |
+
|
| 1097 |
+
"Work" shall mean the work of authorship, whether in Source or Object form, made
|
| 1098 |
+
available under the License, as indicated by a copyright notice that is included
|
| 1099 |
+
in or attached to the work (an example is provided in the Appendix below).
|
| 1100 |
+
|
| 1101 |
+
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
| 1102 |
+
is based on (or derived from) the Work and for which the editorial revisions,
|
| 1103 |
+
annotations, elaborations, or other modifications represent, as a whole, an
|
| 1104 |
+
original work of authorship. For the purposes of this License, Derivative Works
|
| 1105 |
+
shall not include works that remain separable from, or merely link (or bind by
|
| 1106 |
+
name) to the interfaces of, the Work and Derivative Works thereof.
|
| 1107 |
+
|
| 1108 |
+
"Contribution" shall mean any work of authorship, including the original version
|
| 1109 |
+
of the Work and any modifications or additions to that Work or Derivative Works
|
| 1110 |
+
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
| 1111 |
+
by the copyright owner or by an individual or Legal Entity authorized to submit
|
| 1112 |
+
on behalf of the copyright owner. For the purposes of this definition,
|
| 1113 |
+
"submitted" means any form of electronic, verbal, or written communication sent
|
| 1114 |
+
to the Licensor or its representatives, including but not limited to
|
| 1115 |
+
communication on electronic mailing lists, source code control systems, and
|
| 1116 |
+
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
| 1117 |
+
the purpose of discussing and improving the Work, but excluding communication
|
| 1118 |
+
that is conspicuously marked or otherwise designated in writing by the copyright
|
| 1119 |
+
owner as "Not a Contribution."
|
| 1120 |
+
|
| 1121 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
| 1122 |
+
of whom a Contribution has been received by Licensor and subsequently
|
| 1123 |
+
incorporated within the Work.
|
| 1124 |
+
|
| 1125 |
+
2. Grant of Copyright License.
|
| 1126 |
+
|
| 1127 |
+
Subject to the terms and conditions of this License, each Contributor hereby
|
| 1128 |
+
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
| 1129 |
+
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
| 1130 |
+
publicly display, publicly perform, sublicense, and distribute the Work and such
|
| 1131 |
+
Derivative Works in Source or Object form.
|
| 1132 |
+
|
| 1133 |
+
3. Grant of Patent License.
|
| 1134 |
+
|
| 1135 |
+
Subject to the terms and conditions of this License, each Contributor hereby
|
| 1136 |
+
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
| 1137 |
+
irrevocable (except as stated in this section) patent license to make, have
|
| 1138 |
+
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
| 1139 |
+
such license applies only to those patent claims licensable by such Contributor
|
| 1140 |
+
that are necessarily infringed by their Contribution(s) alone or by combination
|
| 1141 |
+
of their Contribution(s) with the Work to which such Contribution(s) was
|
| 1142 |
+
submitted. If You institute patent litigation against any entity (including a
|
| 1143 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
| 1144 |
+
Contribution incorporated within the Work constitutes direct or contributory
|
| 1145 |
+
patent infringement, then any patent licenses granted to You under this License
|
| 1146 |
+
for that Work shall terminate as of the date such litigation is filed.
|
| 1147 |
+
|
| 1148 |
+
4. Redistribution.
|
| 1149 |
+
|
| 1150 |
+
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
| 1151 |
+
in any medium, with or without modifications, and in Source or Object form,
|
| 1152 |
+
provided that You meet the following conditions:
|
| 1153 |
+
|
| 1154 |
+
You must give any other recipients of the Work or Derivative Works a copy of
|
| 1155 |
+
this License; and
|
| 1156 |
+
You must cause any modified files to carry prominent notices stating that You
|
| 1157 |
+
changed the files; and
|
| 1158 |
+
You must retain, in the Source form of any Derivative Works that You distribute,
|
| 1159 |
+
all copyright, patent, trademark, and attribution notices from the Source form
|
| 1160 |
+
of the Work, excluding those notices that do not pertain to any part of the
|
| 1161 |
+
Derivative Works; and
|
| 1162 |
+
If the Work includes a "NOTICE" text file as part of its distribution, then any
|
| 1163 |
+
Derivative Works that You distribute must include a readable copy of the
|
| 1164 |
+
attribution notices contained within such NOTICE file, excluding those notices
|
| 1165 |
+
that do not pertain to any part of the Derivative Works, in at least one of the
|
| 1166 |
+
following places: within a NOTICE text file distributed as part of the
|
| 1167 |
+
Derivative Works; within the Source form or documentation, if provided along
|
| 1168 |
+
with the Derivative Works; or, within a display generated by the Derivative
|
| 1169 |
+
Works, if and wherever such third-party notices normally appear. The contents of
|
| 1170 |
+
the NOTICE file are for informational purposes only and do not modify the
|
| 1171 |
+
License. You may add Your own attribution notices within Derivative Works that
|
| 1172 |
+
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
| 1173 |
+
provided that such additional attribution notices cannot be construed as
|
| 1174 |
+
modifying the License.
|
| 1175 |
+
You may add Your own copyright statement to Your modifications and may provide
|
| 1176 |
+
additional or different license terms and conditions for use, reproduction, or
|
| 1177 |
+
distribution of Your modifications, or for any such Derivative Works as a whole,
|
| 1178 |
+
provided Your use, reproduction, and distribution of the Work otherwise complies
|
| 1179 |
+
with the conditions stated in this License.
|
| 1180 |
+
|
| 1181 |
+
5. Submission of Contributions.
|
| 1182 |
+
|
| 1183 |
+
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
| 1184 |
+
for inclusion in the Work by You to the Licensor shall be under the terms and
|
| 1185 |
+
conditions of this License, without any additional terms or conditions.
|
| 1186 |
+
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
| 1187 |
+
any separate license agreement you may have executed with Licensor regarding
|
| 1188 |
+
such Contributions.
|
| 1189 |
+
|
| 1190 |
+
6. Trademarks.
|
| 1191 |
+
|
| 1192 |
+
This License does not grant permission to use the trade names, trademarks,
|
| 1193 |
+
service marks, or product names of the Licensor, except as required for
|
| 1194 |
+
reasonable and customary use in describing the origin of the Work and
|
| 1195 |
+
reproducing the content of the NOTICE file.
|
| 1196 |
+
|
| 1197 |
+
7. Disclaimer of Warranty.
|
| 1198 |
+
|
| 1199 |
+
Unless required by applicable law or agreed to in writing, Licensor provides the
|
| 1200 |
+
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 1201 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
| 1202 |
+
including, without limitation, any warranties or conditions of TITLE,
|
| 1203 |
+
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
| 1204 |
+
solely responsible for determining the appropriateness of using or
|
| 1205 |
+
redistributing the Work and assume any risks associated with Your exercise of
|
| 1206 |
+
permissions under this License.
|
| 1207 |
+
|
| 1208 |
+
8. Limitation of Liability.
|
| 1209 |
+
|
| 1210 |
+
In no event and under no legal theory, whether in tort (including negligence),
|
| 1211 |
+
contract, or otherwise, unless required by applicable law (such as deliberate
|
| 1212 |
+
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
| 1213 |
+
liable to You for damages, including any direct, indirect, special, incidental,
|
| 1214 |
+
or consequential damages of any character arising as a result of this License or
|
| 1215 |
+
out of the use or inability to use the Work (including but not limited to
|
| 1216 |
+
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
| 1217 |
+
any and all other commercial damages or losses), even if such Contributor has
|
| 1218 |
+
been advised of the possibility of such damages.
|
| 1219 |
+
|
| 1220 |
+
9. Accepting Warranty or Additional Liability.
|
| 1221 |
+
|
| 1222 |
+
While redistributing the Work or Derivative Works thereof, You may choose to
|
| 1223 |
+
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
| 1224 |
+
other liability obligations and/or rights consistent with this License. However,
|
| 1225 |
+
in accepting such obligations, You may act only on Your own behalf and on Your
|
| 1226 |
+
sole responsibility, not on behalf of any other Contributor, and only if You
|
| 1227 |
+
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
| 1228 |
+
incurred by, or claims asserted against, such Contributor by reason of your
|
| 1229 |
+
accepting any such warranty or additional liability.
|
| 1230 |
+
|
| 1231 |
+
END OF TERMS AND CONDITIONS
|
| 1232 |
+
|
| 1233 |
+
APPENDIX: How to apply the Apache License to your work
|
| 1234 |
+
|
| 1235 |
+
To apply the Apache License to your work, attach the following boilerplate
|
| 1236 |
+
notice, with the fields enclosed by brackets "[]" replaced with your own
|
| 1237 |
+
identifying information. (Don't include the brackets!) The text should be
|
| 1238 |
+
enclosed in the appropriate comment syntax for the file format. We also
|
| 1239 |
+
recommend that a file or class name and description of purpose be included on
|
| 1240 |
+
the same "printed page" as the copyright notice for easier identification within
|
| 1241 |
+
third-party archives.
|
| 1242 |
+
|
| 1243 |
+
Copyright [yyyy] [name of copyright owner]
|
| 1244 |
+
|
| 1245 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 1246 |
+
you may not use this file except in compliance with the License.
|
| 1247 |
+
You may obtain a copy of the License at
|
| 1248 |
+
|
| 1249 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 1250 |
+
|
| 1251 |
+
Unless required by applicable law or agreed to in writing, software
|
| 1252 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 1253 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 1254 |
+
See the License for the specific language governing permissions and
|
| 1255 |
+
limitations under the License.
|
| 1256 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 1257 |
+
Classifier: Environment :: Console
|
| 1258 |
+
Classifier: Intended Audience :: Science/Research
|
| 1259 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 1260 |
+
Classifier: Operating System :: OS Independent
|
| 1261 |
+
Classifier: Programming Language :: Cython
|
| 1262 |
+
Classifier: Programming Language :: Python
|
| 1263 |
+
Classifier: Programming Language :: Python :: 3
|
| 1264 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 1265 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 1266 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 1267 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 1268 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 1269 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 1270 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 1271 |
+
Classifier: Topic :: Scientific/Engineering
|
| 1272 |
+
Project-URL: homepage, https://pandas.pydata.org
|
| 1273 |
+
Project-URL: documentation, https://pandas.pydata.org/docs/
|
| 1274 |
+
Project-URL: repository, https://github.com/pandas-dev/pandas
|
| 1275 |
+
Requires-Python: >=3.9
|
| 1276 |
+
Requires-Dist: numpy>=1.22.4; python_version < "3.11"
|
| 1277 |
+
Requires-Dist: numpy>=1.23.2; python_version == "3.11"
|
| 1278 |
+
Requires-Dist: numpy>=1.26.0; python_version >= "3.12"
|
| 1279 |
+
Requires-Dist: python-dateutil>=2.8.2
|
| 1280 |
+
Requires-Dist: pytz>=2020.1
|
| 1281 |
+
Requires-Dist: tzdata>=2022.7
|
| 1282 |
+
Provides-Extra: test
|
| 1283 |
+
Requires-Dist: hypothesis>=6.46.1; extra == "test"
|
| 1284 |
+
Requires-Dist: pytest>=7.3.2; extra == "test"
|
| 1285 |
+
Requires-Dist: pytest-xdist>=2.2.0; extra == "test"
|
| 1286 |
+
Provides-Extra: pyarrow
|
| 1287 |
+
Requires-Dist: pyarrow>=10.0.1; extra == "pyarrow"
|
| 1288 |
+
Provides-Extra: performance
|
| 1289 |
+
Requires-Dist: bottleneck>=1.3.6; extra == "performance"
|
| 1290 |
+
Requires-Dist: numba>=0.56.4; extra == "performance"
|
| 1291 |
+
Requires-Dist: numexpr>=2.8.4; extra == "performance"
|
| 1292 |
+
Provides-Extra: computation
|
| 1293 |
+
Requires-Dist: scipy>=1.10.0; extra == "computation"
|
| 1294 |
+
Requires-Dist: xarray>=2022.12.0; extra == "computation"
|
| 1295 |
+
Provides-Extra: fss
|
| 1296 |
+
Requires-Dist: fsspec>=2022.11.0; extra == "fss"
|
| 1297 |
+
Provides-Extra: aws
|
| 1298 |
+
Requires-Dist: s3fs>=2022.11.0; extra == "aws"
|
| 1299 |
+
Provides-Extra: gcp
|
| 1300 |
+
Requires-Dist: gcsfs>=2022.11.0; extra == "gcp"
|
| 1301 |
+
Requires-Dist: pandas-gbq>=0.19.0; extra == "gcp"
|
| 1302 |
+
Provides-Extra: excel
|
| 1303 |
+
Requires-Dist: odfpy>=1.4.1; extra == "excel"
|
| 1304 |
+
Requires-Dist: openpyxl>=3.1.0; extra == "excel"
|
| 1305 |
+
Requires-Dist: python-calamine>=0.1.7; extra == "excel"
|
| 1306 |
+
Requires-Dist: pyxlsb>=1.0.10; extra == "excel"
|
| 1307 |
+
Requires-Dist: xlrd>=2.0.1; extra == "excel"
|
| 1308 |
+
Requires-Dist: xlsxwriter>=3.0.5; extra == "excel"
|
| 1309 |
+
Provides-Extra: parquet
|
| 1310 |
+
Requires-Dist: pyarrow>=10.0.1; extra == "parquet"
|
| 1311 |
+
Provides-Extra: feather
|
| 1312 |
+
Requires-Dist: pyarrow>=10.0.1; extra == "feather"
|
| 1313 |
+
Provides-Extra: hdf5
|
| 1314 |
+
Requires-Dist: tables>=3.8.0; extra == "hdf5"
|
| 1315 |
+
Provides-Extra: spss
|
| 1316 |
+
Requires-Dist: pyreadstat>=1.2.0; extra == "spss"
|
| 1317 |
+
Provides-Extra: postgresql
|
| 1318 |
+
Requires-Dist: SQLAlchemy>=2.0.0; extra == "postgresql"
|
| 1319 |
+
Requires-Dist: psycopg2>=2.9.6; extra == "postgresql"
|
| 1320 |
+
Requires-Dist: adbc-driver-postgresql>=0.8.0; extra == "postgresql"
|
| 1321 |
+
Provides-Extra: mysql
|
| 1322 |
+
Requires-Dist: SQLAlchemy>=2.0.0; extra == "mysql"
|
| 1323 |
+
Requires-Dist: pymysql>=1.0.2; extra == "mysql"
|
| 1324 |
+
Provides-Extra: sql-other
|
| 1325 |
+
Requires-Dist: SQLAlchemy>=2.0.0; extra == "sql-other"
|
| 1326 |
+
Requires-Dist: adbc-driver-postgresql>=0.8.0; extra == "sql-other"
|
| 1327 |
+
Requires-Dist: adbc-driver-sqlite>=0.8.0; extra == "sql-other"
|
| 1328 |
+
Provides-Extra: html
|
| 1329 |
+
Requires-Dist: beautifulsoup4>=4.11.2; extra == "html"
|
| 1330 |
+
Requires-Dist: html5lib>=1.1; extra == "html"
|
| 1331 |
+
Requires-Dist: lxml>=4.9.2; extra == "html"
|
| 1332 |
+
Provides-Extra: xml
|
| 1333 |
+
Requires-Dist: lxml>=4.9.2; extra == "xml"
|
| 1334 |
+
Provides-Extra: plot
|
| 1335 |
+
Requires-Dist: matplotlib>=3.6.3; extra == "plot"
|
| 1336 |
+
Provides-Extra: output-formatting
|
| 1337 |
+
Requires-Dist: jinja2>=3.1.2; extra == "output-formatting"
|
| 1338 |
+
Requires-Dist: tabulate>=0.9.0; extra == "output-formatting"
|
| 1339 |
+
Provides-Extra: clipboard
|
| 1340 |
+
Requires-Dist: PyQt5>=5.15.9; extra == "clipboard"
|
| 1341 |
+
Requires-Dist: qtpy>=2.3.0; extra == "clipboard"
|
| 1342 |
+
Provides-Extra: compression
|
| 1343 |
+
Requires-Dist: zstandard>=0.19.0; extra == "compression"
|
| 1344 |
+
Provides-Extra: consortium-standard
|
| 1345 |
+
Requires-Dist: dataframe-api-compat>=0.1.7; extra == "consortium-standard"
|
| 1346 |
+
Provides-Extra: all
|
| 1347 |
+
Requires-Dist: adbc-driver-postgresql>=0.8.0; extra == "all"
|
| 1348 |
+
Requires-Dist: adbc-driver-sqlite>=0.8.0; extra == "all"
|
| 1349 |
+
Requires-Dist: beautifulsoup4>=4.11.2; extra == "all"
|
| 1350 |
+
Requires-Dist: bottleneck>=1.3.6; extra == "all"
|
| 1351 |
+
Requires-Dist: dataframe-api-compat>=0.1.7; extra == "all"
|
| 1352 |
+
Requires-Dist: fastparquet>=2022.12.0; extra == "all"
|
| 1353 |
+
Requires-Dist: fsspec>=2022.11.0; extra == "all"
|
| 1354 |
+
Requires-Dist: gcsfs>=2022.11.0; extra == "all"
|
| 1355 |
+
Requires-Dist: html5lib>=1.1; extra == "all"
|
| 1356 |
+
Requires-Dist: hypothesis>=6.46.1; extra == "all"
|
| 1357 |
+
Requires-Dist: jinja2>=3.1.2; extra == "all"
|
| 1358 |
+
Requires-Dist: lxml>=4.9.2; extra == "all"
|
| 1359 |
+
Requires-Dist: matplotlib>=3.6.3; extra == "all"
|
| 1360 |
+
Requires-Dist: numba>=0.56.4; extra == "all"
|
| 1361 |
+
Requires-Dist: numexpr>=2.8.4; extra == "all"
|
| 1362 |
+
Requires-Dist: odfpy>=1.4.1; extra == "all"
|
| 1363 |
+
Requires-Dist: openpyxl>=3.1.0; extra == "all"
|
| 1364 |
+
Requires-Dist: pandas-gbq>=0.19.0; extra == "all"
|
| 1365 |
+
Requires-Dist: psycopg2>=2.9.6; extra == "all"
|
| 1366 |
+
Requires-Dist: pyarrow>=10.0.1; extra == "all"
|
| 1367 |
+
Requires-Dist: pymysql>=1.0.2; extra == "all"
|
| 1368 |
+
Requires-Dist: PyQt5>=5.15.9; extra == "all"
|
| 1369 |
+
Requires-Dist: pyreadstat>=1.2.0; extra == "all"
|
| 1370 |
+
Requires-Dist: pytest>=7.3.2; extra == "all"
|
| 1371 |
+
Requires-Dist: pytest-xdist>=2.2.0; extra == "all"
|
| 1372 |
+
Requires-Dist: python-calamine>=0.1.7; extra == "all"
|
| 1373 |
+
Requires-Dist: pyxlsb>=1.0.10; extra == "all"
|
| 1374 |
+
Requires-Dist: qtpy>=2.3.0; extra == "all"
|
| 1375 |
+
Requires-Dist: scipy>=1.10.0; extra == "all"
|
| 1376 |
+
Requires-Dist: s3fs>=2022.11.0; extra == "all"
|
| 1377 |
+
Requires-Dist: SQLAlchemy>=2.0.0; extra == "all"
|
| 1378 |
+
Requires-Dist: tables>=3.8.0; extra == "all"
|
| 1379 |
+
Requires-Dist: tabulate>=0.9.0; extra == "all"
|
| 1380 |
+
Requires-Dist: xarray>=2022.12.0; extra == "all"
|
| 1381 |
+
Requires-Dist: xlrd>=2.0.1; extra == "all"
|
| 1382 |
+
Requires-Dist: xlsxwriter>=3.0.5; extra == "all"
|
| 1383 |
+
Requires-Dist: zstandard>=0.19.0; extra == "all"
|
| 1384 |
+
Description-Content-Type: text/markdown
|
| 1385 |
+
|
| 1386 |
+
<div align="center">
|
| 1387 |
+
<img src="https://pandas.pydata.org/static/img/pandas.svg"><br>
|
| 1388 |
+
</div>
|
| 1389 |
+
|
| 1390 |
+
-----------------
|
| 1391 |
+
|
| 1392 |
+
# pandas: powerful Python data analysis toolkit
|
| 1393 |
+
|
| 1394 |
+
| | |
|
| 1395 |
+
| --- | --- |
|
| 1396 |
+
| Testing | [](https://github.com/pandas-dev/pandas/actions/workflows/unit-tests.yml) [](https://codecov.io/gh/pandas-dev/pandas) |
|
| 1397 |
+
| Package | [](https://pypi.org/project/pandas/) [](https://pypi.org/project/pandas/) [](https://anaconda.org/conda-forge/pandas) [](https://anaconda.org/conda-forge/pandas) |
|
| 1398 |
+
| Meta | [](https://numfocus.org) [](https://doi.org/10.5281/zenodo.3509134) [](https://github.com/pandas-dev/pandas/blob/main/LICENSE) [](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) |
|
| 1399 |
+
|
| 1400 |
+
|
| 1401 |
+
## What is it?
|
| 1402 |
+
|
| 1403 |
+
**pandas** is a Python package that provides fast, flexible, and expressive data
|
| 1404 |
+
structures designed to make working with "relational" or "labeled" data both
|
| 1405 |
+
easy and intuitive. It aims to be the fundamental high-level building block for
|
| 1406 |
+
doing practical, **real world** data analysis in Python. Additionally, it has
|
| 1407 |
+
the broader goal of becoming **the most powerful and flexible open source data
|
| 1408 |
+
analysis / manipulation tool available in any language**. It is already well on
|
| 1409 |
+
its way towards this goal.
|
| 1410 |
+
|
| 1411 |
+
## Table of Contents
|
| 1412 |
+
|
| 1413 |
+
- [Main Features](#main-features)
|
| 1414 |
+
- [Where to get it](#where-to-get-it)
|
| 1415 |
+
- [Dependencies](#dependencies)
|
| 1416 |
+
- [Installation from sources](#installation-from-sources)
|
| 1417 |
+
- [License](#license)
|
| 1418 |
+
- [Documentation](#documentation)
|
| 1419 |
+
- [Background](#background)
|
| 1420 |
+
- [Getting Help](#getting-help)
|
| 1421 |
+
- [Discussion and Development](#discussion-and-development)
|
| 1422 |
+
- [Contributing to pandas](#contributing-to-pandas)
|
| 1423 |
+
|
| 1424 |
+
## Main Features
|
| 1425 |
+
Here are just a few of the things that pandas does well:
|
| 1426 |
+
|
| 1427 |
+
- Easy handling of [**missing data**][missing-data] (represented as
|
| 1428 |
+
`NaN`, `NA`, or `NaT`) in floating point as well as non-floating point data
|
| 1429 |
+
- Size mutability: columns can be [**inserted and
|
| 1430 |
+
deleted**][insertion-deletion] from DataFrame and higher dimensional
|
| 1431 |
+
objects
|
| 1432 |
+
- Automatic and explicit [**data alignment**][alignment]: objects can
|
| 1433 |
+
be explicitly aligned to a set of labels, or the user can simply
|
| 1434 |
+
ignore the labels and let `Series`, `DataFrame`, etc. automatically
|
| 1435 |
+
align the data for you in computations
|
| 1436 |
+
- Powerful, flexible [**group by**][groupby] functionality to perform
|
| 1437 |
+
split-apply-combine operations on data sets, for both aggregating
|
| 1438 |
+
and transforming data
|
| 1439 |
+
- Make it [**easy to convert**][conversion] ragged,
|
| 1440 |
+
differently-indexed data in other Python and NumPy data structures
|
| 1441 |
+
into DataFrame objects
|
| 1442 |
+
- Intelligent label-based [**slicing**][slicing], [**fancy
|
| 1443 |
+
indexing**][fancy-indexing], and [**subsetting**][subsetting] of
|
| 1444 |
+
large data sets
|
| 1445 |
+
- Intuitive [**merging**][merging] and [**joining**][joining] data
|
| 1446 |
+
sets
|
| 1447 |
+
- Flexible [**reshaping**][reshape] and [**pivoting**][pivot-table] of
|
| 1448 |
+
data sets
|
| 1449 |
+
- [**Hierarchical**][mi] labeling of axes (possible to have multiple
|
| 1450 |
+
labels per tick)
|
| 1451 |
+
- Robust IO tools for loading data from [**flat files**][flat-files]
|
| 1452 |
+
(CSV and delimited), [**Excel files**][excel], [**databases**][db],
|
| 1453 |
+
and saving/loading data from the ultrafast [**HDF5 format**][hdfstore]
|
| 1454 |
+
- [**Time series**][timeseries]-specific functionality: date range
|
| 1455 |
+
generation and frequency conversion, moving window statistics,
|
| 1456 |
+
date shifting and lagging
|
| 1457 |
+
|
| 1458 |
+
|
| 1459 |
+
[missing-data]: https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html
|
| 1460 |
+
[insertion-deletion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#column-selection-addition-deletion
|
| 1461 |
+
[alignment]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html?highlight=alignment#intro-to-data-structures
|
| 1462 |
+
[groupby]: https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#group-by-split-apply-combine
|
| 1463 |
+
[conversion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#dataframe
|
| 1464 |
+
[slicing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#slicing-ranges
|
| 1465 |
+
[fancy-indexing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced
|
| 1466 |
+
[subsetting]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing
|
| 1467 |
+
[merging]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#database-style-dataframe-or-named-series-joining-merging
|
| 1468 |
+
[joining]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#joining-on-index
|
| 1469 |
+
[reshape]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html
|
| 1470 |
+
[pivot-table]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html
|
| 1471 |
+
[mi]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#hierarchical-indexing-multiindex
|
| 1472 |
+
[flat-files]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#csv-text-files
|
| 1473 |
+
[excel]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#excel-files
|
| 1474 |
+
[db]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#sql-queries
|
| 1475 |
+
[hdfstore]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#hdf5-pytables
|
| 1476 |
+
[timeseries]: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#time-series-date-functionality
|
| 1477 |
+
|
| 1478 |
+
## Where to get it
|
| 1479 |
+
The source code is currently hosted on GitHub at:
|
| 1480 |
+
https://github.com/pandas-dev/pandas
|
| 1481 |
+
|
| 1482 |
+
Binary installers for the latest released version are available at the [Python
|
| 1483 |
+
Package Index (PyPI)](https://pypi.org/project/pandas) and on [Conda](https://docs.conda.io/en/latest/).
|
| 1484 |
+
|
| 1485 |
+
```sh
|
| 1486 |
+
# conda
|
| 1487 |
+
conda install -c conda-forge pandas
|
| 1488 |
+
```
|
| 1489 |
+
|
| 1490 |
+
```sh
|
| 1491 |
+
# or PyPI
|
| 1492 |
+
pip install pandas
|
| 1493 |
+
```
|
| 1494 |
+
|
| 1495 |
+
The list of changes to pandas between each release can be found
|
| 1496 |
+
[here](https://pandas.pydata.org/pandas-docs/stable/whatsnew/index.html). For full
|
| 1497 |
+
details, see the commit logs at https://github.com/pandas-dev/pandas.
|
| 1498 |
+
|
| 1499 |
+
## Dependencies
|
| 1500 |
+
- [NumPy - Adds support for large, multi-dimensional arrays, matrices and high-level mathematical functions to operate on these arrays](https://www.numpy.org)
|
| 1501 |
+
- [python-dateutil - Provides powerful extensions to the standard datetime module](https://dateutil.readthedocs.io/en/stable/index.html)
|
| 1502 |
+
- [pytz - Brings the Olson tz database into Python which allows accurate and cross platform timezone calculations](https://github.com/stub42/pytz)
|
| 1503 |
+
|
| 1504 |
+
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.
|
| 1505 |
+
|
| 1506 |
+
## Installation from sources
|
| 1507 |
+
To install pandas from source you need [Cython](https://cython.org/) in addition to the normal
|
| 1508 |
+
dependencies above. Cython can be installed from PyPI:
|
| 1509 |
+
|
| 1510 |
+
```sh
|
| 1511 |
+
pip install cython
|
| 1512 |
+
```
|
| 1513 |
+
|
| 1514 |
+
In the `pandas` directory (same one where you found this file after
|
| 1515 |
+
cloning the git repo), execute:
|
| 1516 |
+
|
| 1517 |
+
```sh
|
| 1518 |
+
pip install .
|
| 1519 |
+
```
|
| 1520 |
+
|
| 1521 |
+
or for installing in [development mode](https://pip.pypa.io/en/latest/cli/pip_install/#install-editable):
|
| 1522 |
+
|
| 1523 |
+
|
| 1524 |
+
```sh
|
| 1525 |
+
python -m pip install -ve . --no-build-isolation --config-settings=editable-verbose=true
|
| 1526 |
+
```
|
| 1527 |
+
|
| 1528 |
+
See the full instructions for [installing from source](https://pandas.pydata.org/docs/dev/development/contributing_environment.html).
|
| 1529 |
+
|
| 1530 |
+
## License
|
| 1531 |
+
[BSD 3](LICENSE)
|
| 1532 |
+
|
| 1533 |
+
## Documentation
|
| 1534 |
+
The official documentation is hosted on [PyData.org](https://pandas.pydata.org/pandas-docs/stable/).
|
| 1535 |
+
|
| 1536 |
+
## Background
|
| 1537 |
+
Work on ``pandas`` started at [AQR](https://www.aqr.com/) (a quantitative hedge fund) in 2008 and
|
| 1538 |
+
has been under active development since then.
|
| 1539 |
+
|
| 1540 |
+
## Getting Help
|
| 1541 |
+
|
| 1542 |
+
For usage questions, the best place to go to is [StackOverflow](https://stackoverflow.com/questions/tagged/pandas).
|
| 1543 |
+
Further, general questions and discussions can also take place on the [pydata mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata).
|
| 1544 |
+
|
| 1545 |
+
## Discussion and Development
|
| 1546 |
+
Most development discussions take place on GitHub in this repo, via the [GitHub issue tracker](https://github.com/pandas-dev/pandas/issues).
|
| 1547 |
+
|
| 1548 |
+
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.
|
| 1549 |
+
|
| 1550 |
+
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.
|
| 1551 |
+
|
| 1552 |
+
Additional information on the communication channels can be found on the [contributor community](https://pandas.pydata.org/docs/development/community.html) page.
|
| 1553 |
+
|
| 1554 |
+
## Contributing to pandas
|
| 1555 |
+
|
| 1556 |
+
[](https://www.codetriage.com/pandas-dev/pandas)
|
| 1557 |
+
|
| 1558 |
+
All contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome.
|
| 1559 |
+
|
| 1560 |
+
A detailed overview on how to contribute can be found in the **[contributing guide](https://pandas.pydata.org/docs/dev/development/contributing.html)**.
|
| 1561 |
+
|
| 1562 |
+
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?labels=Docs&sort=updated&state=open) and [good first issue](https://github.com/pandas-dev/pandas/issues?labels=good+first+issue&sort=updated&state=open) where you could start out.
|
| 1563 |
+
|
| 1564 |
+
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).
|
| 1565 |
+
|
| 1566 |
+
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!
|
| 1567 |
+
|
| 1568 |
+
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).
|
| 1569 |
+
|
| 1570 |
+
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)
|
| 1571 |
+
|
| 1572 |
+
<hr>
|
| 1573 |
+
|
| 1574 |
+
[Go to Top](#table-of-contents)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/RECORD
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/REQUESTED
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: meson
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp310-cp310-manylinux_2_24_x86_64
|
| 5 |
+
Tag: cp310-cp310-manylinux_2_28_x86_64
|
| 6 |
+
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas-2.3.3.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pandas_plotting_backends]
|
| 2 |
+
matplotlib = pandas:plotting._matplotlib
|
| 3 |
+
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/constructors/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/constructors/test_from_dict.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas import (
|
| 7 |
+
DataFrame,
|
| 8 |
+
Index,
|
| 9 |
+
MultiIndex,
|
| 10 |
+
RangeIndex,
|
| 11 |
+
Series,
|
| 12 |
+
)
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestFromDict:
|
| 17 |
+
# Note: these tests are specific to the from_dict method, not for
|
| 18 |
+
# passing dictionaries to DataFrame.__init__
|
| 19 |
+
|
| 20 |
+
def test_constructor_list_of_odicts(self):
|
| 21 |
+
data = [
|
| 22 |
+
OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]]),
|
| 23 |
+
OrderedDict([["a", 1.5], ["b", 3], ["d", 6]]),
|
| 24 |
+
OrderedDict([["a", 1.5], ["d", 6]]),
|
| 25 |
+
OrderedDict(),
|
| 26 |
+
OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]),
|
| 27 |
+
OrderedDict([["b", 3], ["c", 4], ["d", 6]]),
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
result = DataFrame(data)
|
| 31 |
+
expected = DataFrame.from_dict(
|
| 32 |
+
dict(zip(range(len(data)), data)), orient="index"
|
| 33 |
+
)
|
| 34 |
+
tm.assert_frame_equal(result, expected.reindex(result.index))
|
| 35 |
+
|
| 36 |
+
def test_constructor_single_row(self):
|
| 37 |
+
data = [OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]])]
|
| 38 |
+
|
| 39 |
+
result = DataFrame(data)
|
| 40 |
+
expected = DataFrame.from_dict(dict(zip([0], data)), orient="index").reindex(
|
| 41 |
+
result.index
|
| 42 |
+
)
|
| 43 |
+
tm.assert_frame_equal(result, expected)
|
| 44 |
+
|
| 45 |
+
def test_constructor_list_of_series(self):
|
| 46 |
+
data = [
|
| 47 |
+
OrderedDict([["a", 1.5], ["b", 3.0], ["c", 4.0]]),
|
| 48 |
+
OrderedDict([["a", 1.5], ["b", 3.0], ["c", 6.0]]),
|
| 49 |
+
]
|
| 50 |
+
sdict = OrderedDict(zip(["x", "y"], data))
|
| 51 |
+
idx = Index(["a", "b", "c"])
|
| 52 |
+
|
| 53 |
+
# all named
|
| 54 |
+
data2 = [
|
| 55 |
+
Series([1.5, 3, 4], idx, dtype="O", name="x"),
|
| 56 |
+
Series([1.5, 3, 6], idx, name="y"),
|
| 57 |
+
]
|
| 58 |
+
result = DataFrame(data2)
|
| 59 |
+
expected = DataFrame.from_dict(sdict, orient="index")
|
| 60 |
+
tm.assert_frame_equal(result, expected)
|
| 61 |
+
|
| 62 |
+
# some unnamed
|
| 63 |
+
data2 = [
|
| 64 |
+
Series([1.5, 3, 4], idx, dtype="O", name="x"),
|
| 65 |
+
Series([1.5, 3, 6], idx),
|
| 66 |
+
]
|
| 67 |
+
result = DataFrame(data2)
|
| 68 |
+
|
| 69 |
+
sdict = OrderedDict(zip(["x", "Unnamed 0"], data))
|
| 70 |
+
expected = DataFrame.from_dict(sdict, orient="index")
|
| 71 |
+
tm.assert_frame_equal(result, expected)
|
| 72 |
+
|
| 73 |
+
# none named
|
| 74 |
+
data = [
|
| 75 |
+
OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]]),
|
| 76 |
+
OrderedDict([["a", 1.5], ["b", 3], ["d", 6]]),
|
| 77 |
+
OrderedDict([["a", 1.5], ["d", 6]]),
|
| 78 |
+
OrderedDict(),
|
| 79 |
+
OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]),
|
| 80 |
+
OrderedDict([["b", 3], ["c", 4], ["d", 6]]),
|
| 81 |
+
]
|
| 82 |
+
data = [Series(d) for d in data]
|
| 83 |
+
|
| 84 |
+
result = DataFrame(data)
|
| 85 |
+
sdict = OrderedDict(zip(range(len(data)), data))
|
| 86 |
+
expected = DataFrame.from_dict(sdict, orient="index")
|
| 87 |
+
tm.assert_frame_equal(result, expected.reindex(result.index))
|
| 88 |
+
|
| 89 |
+
result2 = DataFrame(data, index=np.arange(6, dtype=np.int64))
|
| 90 |
+
tm.assert_frame_equal(result, result2)
|
| 91 |
+
|
| 92 |
+
result = DataFrame([Series(dtype=object)])
|
| 93 |
+
expected = DataFrame(index=[0])
|
| 94 |
+
tm.assert_frame_equal(result, expected)
|
| 95 |
+
|
| 96 |
+
data = [
|
| 97 |
+
OrderedDict([["a", 1.5], ["b", 3.0], ["c", 4.0]]),
|
| 98 |
+
OrderedDict([["a", 1.5], ["b", 3.0], ["c", 6.0]]),
|
| 99 |
+
]
|
| 100 |
+
sdict = OrderedDict(zip(range(len(data)), data))
|
| 101 |
+
|
| 102 |
+
idx = Index(["a", "b", "c"])
|
| 103 |
+
data2 = [Series([1.5, 3, 4], idx, dtype="O"), Series([1.5, 3, 6], idx)]
|
| 104 |
+
result = DataFrame(data2)
|
| 105 |
+
expected = DataFrame.from_dict(sdict, orient="index")
|
| 106 |
+
tm.assert_frame_equal(result, expected)
|
| 107 |
+
|
| 108 |
+
def test_constructor_orient(self, float_string_frame):
|
| 109 |
+
data_dict = float_string_frame.T._series
|
| 110 |
+
recons = DataFrame.from_dict(data_dict, orient="index")
|
| 111 |
+
expected = float_string_frame.reindex(index=recons.index)
|
| 112 |
+
tm.assert_frame_equal(recons, expected)
|
| 113 |
+
|
| 114 |
+
# dict of sequence
|
| 115 |
+
a = {"hi": [32, 3, 3], "there": [3, 5, 3]}
|
| 116 |
+
rs = DataFrame.from_dict(a, orient="index")
|
| 117 |
+
xp = DataFrame.from_dict(a).T.reindex(list(a.keys()))
|
| 118 |
+
tm.assert_frame_equal(rs, xp)
|
| 119 |
+
|
| 120 |
+
def test_constructor_from_ordered_dict(self):
|
| 121 |
+
# GH#8425
|
| 122 |
+
a = OrderedDict(
|
| 123 |
+
[
|
| 124 |
+
("one", OrderedDict([("col_a", "foo1"), ("col_b", "bar1")])),
|
| 125 |
+
("two", OrderedDict([("col_a", "foo2"), ("col_b", "bar2")])),
|
| 126 |
+
("three", OrderedDict([("col_a", "foo3"), ("col_b", "bar3")])),
|
| 127 |
+
]
|
| 128 |
+
)
|
| 129 |
+
expected = DataFrame.from_dict(a, orient="columns").T
|
| 130 |
+
result = DataFrame.from_dict(a, orient="index")
|
| 131 |
+
tm.assert_frame_equal(result, expected)
|
| 132 |
+
|
| 133 |
+
def test_from_dict_columns_parameter(self):
|
| 134 |
+
# GH#18529
|
| 135 |
+
# Test new columns parameter for from_dict that was added to make
|
| 136 |
+
# from_items(..., orient='index', columns=[...]) easier to replicate
|
| 137 |
+
result = DataFrame.from_dict(
|
| 138 |
+
OrderedDict([("A", [1, 2]), ("B", [4, 5])]),
|
| 139 |
+
orient="index",
|
| 140 |
+
columns=["one", "two"],
|
| 141 |
+
)
|
| 142 |
+
expected = DataFrame([[1, 2], [4, 5]], index=["A", "B"], columns=["one", "two"])
|
| 143 |
+
tm.assert_frame_equal(result, expected)
|
| 144 |
+
|
| 145 |
+
msg = "cannot use columns parameter with orient='columns'"
|
| 146 |
+
with pytest.raises(ValueError, match=msg):
|
| 147 |
+
DataFrame.from_dict(
|
| 148 |
+
{"A": [1, 2], "B": [4, 5]},
|
| 149 |
+
orient="columns",
|
| 150 |
+
columns=["one", "two"],
|
| 151 |
+
)
|
| 152 |
+
with pytest.raises(ValueError, match=msg):
|
| 153 |
+
DataFrame.from_dict({"A": [1, 2], "B": [4, 5]}, columns=["one", "two"])
|
| 154 |
+
|
| 155 |
+
@pytest.mark.parametrize(
|
| 156 |
+
"data_dict, orient, expected",
|
| 157 |
+
[
|
| 158 |
+
({}, "index", RangeIndex(0)),
|
| 159 |
+
(
|
| 160 |
+
[{("a",): 1}, {("a",): 2}],
|
| 161 |
+
"columns",
|
| 162 |
+
Index([("a",)], tupleize_cols=False),
|
| 163 |
+
),
|
| 164 |
+
(
|
| 165 |
+
[OrderedDict([(("a",), 1), (("b",), 2)])],
|
| 166 |
+
"columns",
|
| 167 |
+
Index([("a",), ("b",)], tupleize_cols=False),
|
| 168 |
+
),
|
| 169 |
+
([{("a", "b"): 1}], "columns", Index([("a", "b")], tupleize_cols=False)),
|
| 170 |
+
],
|
| 171 |
+
)
|
| 172 |
+
def test_constructor_from_dict_tuples(self, data_dict, orient, expected):
|
| 173 |
+
# GH#16769
|
| 174 |
+
df = DataFrame.from_dict(data_dict, orient)
|
| 175 |
+
result = df.columns
|
| 176 |
+
tm.assert_index_equal(result, expected)
|
| 177 |
+
|
| 178 |
+
def test_frame_dict_constructor_empty_series(self):
|
| 179 |
+
s1 = Series(
|
| 180 |
+
[1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (2, 2), (2, 4)])
|
| 181 |
+
)
|
| 182 |
+
s2 = Series(
|
| 183 |
+
[1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (3, 2), (3, 4)])
|
| 184 |
+
)
|
| 185 |
+
s3 = Series(dtype=object)
|
| 186 |
+
|
| 187 |
+
# it works!
|
| 188 |
+
DataFrame({"foo": s1, "bar": s2, "baz": s3})
|
| 189 |
+
DataFrame.from_dict({"foo": s1, "baz": s3, "bar": s2})
|
| 190 |
+
|
| 191 |
+
def test_from_dict_scalars_requires_index(self):
|
| 192 |
+
msg = "If using all scalar values, you must pass an index"
|
| 193 |
+
with pytest.raises(ValueError, match=msg):
|
| 194 |
+
DataFrame.from_dict(OrderedDict([("b", 8), ("a", 5), ("a", 6)]))
|
| 195 |
+
|
| 196 |
+
def test_from_dict_orient_invalid(self):
|
| 197 |
+
msg = (
|
| 198 |
+
"Expected 'index', 'columns' or 'tight' for orient parameter. "
|
| 199 |
+
"Got 'abc' instead"
|
| 200 |
+
)
|
| 201 |
+
with pytest.raises(ValueError, match=msg):
|
| 202 |
+
DataFrame.from_dict({"foo": 1, "baz": 3, "bar": 2}, orient="abc")
|
| 203 |
+
|
| 204 |
+
def test_from_dict_order_with_single_column(self):
|
| 205 |
+
data = {
|
| 206 |
+
"alpha": {
|
| 207 |
+
"value2": 123,
|
| 208 |
+
"value1": 532,
|
| 209 |
+
"animal": 222,
|
| 210 |
+
"plant": False,
|
| 211 |
+
"name": "test",
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
result = DataFrame.from_dict(
|
| 215 |
+
data,
|
| 216 |
+
orient="columns",
|
| 217 |
+
)
|
| 218 |
+
expected = DataFrame(
|
| 219 |
+
[[123], [532], [222], [False], ["test"]],
|
| 220 |
+
index=["value2", "value1", "animal", "plant", "name"],
|
| 221 |
+
columns=["alpha"],
|
| 222 |
+
)
|
| 223 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/constructors/test_from_records.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Iterator
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from decimal import Decimal
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
import pytz
|
| 8 |
+
|
| 9 |
+
from pandas._config import using_string_dtype
|
| 10 |
+
|
| 11 |
+
from pandas.compat import is_platform_little_endian
|
| 12 |
+
|
| 13 |
+
from pandas import (
|
| 14 |
+
CategoricalIndex,
|
| 15 |
+
DataFrame,
|
| 16 |
+
Index,
|
| 17 |
+
Interval,
|
| 18 |
+
RangeIndex,
|
| 19 |
+
Series,
|
| 20 |
+
date_range,
|
| 21 |
+
)
|
| 22 |
+
import pandas._testing as tm
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TestFromRecords:
|
| 26 |
+
def test_from_records_dt64tz_frame(self):
|
| 27 |
+
# GH#51162 don't lose tz when calling from_records with DataFrame input
|
| 28 |
+
dti = date_range("2016-01-01", periods=10, tz="US/Pacific")
|
| 29 |
+
df = DataFrame({i: dti for i in range(4)})
|
| 30 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 31 |
+
res = DataFrame.from_records(df)
|
| 32 |
+
tm.assert_frame_equal(res, df)
|
| 33 |
+
|
| 34 |
+
def test_from_records_with_datetimes(self):
|
| 35 |
+
# this may fail on certain platforms because of a numpy issue
|
| 36 |
+
# related GH#6140
|
| 37 |
+
if not is_platform_little_endian():
|
| 38 |
+
pytest.skip("known failure of test on non-little endian")
|
| 39 |
+
|
| 40 |
+
# construction with a null in a recarray
|
| 41 |
+
# GH#6140
|
| 42 |
+
expected = DataFrame({"EXPIRY": [datetime(2005, 3, 1, 0, 0), None]})
|
| 43 |
+
|
| 44 |
+
arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])]
|
| 45 |
+
dtypes = [("EXPIRY", "<M8[ns]")]
|
| 46 |
+
|
| 47 |
+
recarray = np.rec.fromarrays(arrdata, dtype=dtypes)
|
| 48 |
+
|
| 49 |
+
result = DataFrame.from_records(recarray)
|
| 50 |
+
tm.assert_frame_equal(result, expected)
|
| 51 |
+
|
| 52 |
+
# coercion should work too
|
| 53 |
+
arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])]
|
| 54 |
+
dtypes = [("EXPIRY", "<M8[m]")]
|
| 55 |
+
recarray = np.rec.fromarrays(arrdata, dtype=dtypes)
|
| 56 |
+
result = DataFrame.from_records(recarray)
|
| 57 |
+
# we get the closest supported unit, "s"
|
| 58 |
+
expected["EXPIRY"] = expected["EXPIRY"].astype("M8[s]")
|
| 59 |
+
tm.assert_frame_equal(result, expected)
|
| 60 |
+
|
| 61 |
+
@pytest.mark.xfail(using_string_dtype(), reason="dtype checking logic doesn't work")
|
| 62 |
+
def test_from_records_sequencelike(self):
|
| 63 |
+
df = DataFrame(
|
| 64 |
+
{
|
| 65 |
+
"A": np.array(
|
| 66 |
+
np.random.default_rng(2).standard_normal(6), dtype=np.float64
|
| 67 |
+
),
|
| 68 |
+
"A1": np.array(
|
| 69 |
+
np.random.default_rng(2).standard_normal(6), dtype=np.float64
|
| 70 |
+
),
|
| 71 |
+
"B": np.array(np.arange(6), dtype=np.int64),
|
| 72 |
+
"C": ["foo"] * 6,
|
| 73 |
+
"D": np.array([True, False] * 3, dtype=bool),
|
| 74 |
+
"E": np.array(
|
| 75 |
+
np.random.default_rng(2).standard_normal(6), dtype=np.float32
|
| 76 |
+
),
|
| 77 |
+
"E1": np.array(
|
| 78 |
+
np.random.default_rng(2).standard_normal(6), dtype=np.float32
|
| 79 |
+
),
|
| 80 |
+
"F": np.array(np.arange(6), dtype=np.int32),
|
| 81 |
+
}
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
# this is actually tricky to create the recordlike arrays and
|
| 85 |
+
# have the dtypes be intact
|
| 86 |
+
blocks = df._to_dict_of_blocks()
|
| 87 |
+
tuples = []
|
| 88 |
+
columns = []
|
| 89 |
+
dtypes = []
|
| 90 |
+
for dtype, b in blocks.items():
|
| 91 |
+
columns.extend(b.columns)
|
| 92 |
+
dtypes.extend([(c, np.dtype(dtype).descr[0][1]) for c in b.columns])
|
| 93 |
+
for i in range(len(df.index)):
|
| 94 |
+
tup = []
|
| 95 |
+
for _, b in blocks.items():
|
| 96 |
+
tup.extend(b.iloc[i].values)
|
| 97 |
+
tuples.append(tuple(tup))
|
| 98 |
+
|
| 99 |
+
recarray = np.array(tuples, dtype=dtypes).view(np.rec.recarray)
|
| 100 |
+
recarray2 = df.to_records()
|
| 101 |
+
lists = [list(x) for x in tuples]
|
| 102 |
+
|
| 103 |
+
# tuples (lose the dtype info)
|
| 104 |
+
result = DataFrame.from_records(tuples, columns=columns).reindex(
|
| 105 |
+
columns=df.columns
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# created recarray and with to_records recarray (have dtype info)
|
| 109 |
+
result2 = DataFrame.from_records(recarray, columns=columns).reindex(
|
| 110 |
+
columns=df.columns
|
| 111 |
+
)
|
| 112 |
+
result3 = DataFrame.from_records(recarray2, columns=columns).reindex(
|
| 113 |
+
columns=df.columns
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# list of tuples (no dtype info)
|
| 117 |
+
result4 = DataFrame.from_records(lists, columns=columns).reindex(
|
| 118 |
+
columns=df.columns
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
tm.assert_frame_equal(result, df, check_dtype=False)
|
| 122 |
+
tm.assert_frame_equal(result2, df)
|
| 123 |
+
tm.assert_frame_equal(result3, df)
|
| 124 |
+
tm.assert_frame_equal(result4, df, check_dtype=False)
|
| 125 |
+
|
| 126 |
+
# tuples is in the order of the columns
|
| 127 |
+
result = DataFrame.from_records(tuples)
|
| 128 |
+
tm.assert_index_equal(result.columns, RangeIndex(8))
|
| 129 |
+
|
| 130 |
+
# test exclude parameter & we are casting the results here (as we don't
|
| 131 |
+
# have dtype info to recover)
|
| 132 |
+
columns_to_test = [columns.index("C"), columns.index("E1")]
|
| 133 |
+
|
| 134 |
+
exclude = list(set(range(8)) - set(columns_to_test))
|
| 135 |
+
result = DataFrame.from_records(tuples, exclude=exclude)
|
| 136 |
+
result.columns = [columns[i] for i in sorted(columns_to_test)]
|
| 137 |
+
tm.assert_series_equal(result["C"], df["C"])
|
| 138 |
+
tm.assert_series_equal(result["E1"], df["E1"])
|
| 139 |
+
|
| 140 |
+
def test_from_records_sequencelike_empty(self):
|
| 141 |
+
# empty case
|
| 142 |
+
result = DataFrame.from_records([], columns=["foo", "bar", "baz"])
|
| 143 |
+
assert len(result) == 0
|
| 144 |
+
tm.assert_index_equal(result.columns, Index(["foo", "bar", "baz"]))
|
| 145 |
+
|
| 146 |
+
result = DataFrame.from_records([])
|
| 147 |
+
assert len(result) == 0
|
| 148 |
+
assert len(result.columns) == 0
|
| 149 |
+
|
| 150 |
+
def test_from_records_dictlike(self):
|
| 151 |
+
# test the dict methods
|
| 152 |
+
df = DataFrame(
|
| 153 |
+
{
|
| 154 |
+
"A": np.array(
|
| 155 |
+
np.random.default_rng(2).standard_normal(6), dtype=np.float64
|
| 156 |
+
),
|
| 157 |
+
"A1": np.array(
|
| 158 |
+
np.random.default_rng(2).standard_normal(6), dtype=np.float64
|
| 159 |
+
),
|
| 160 |
+
"B": np.array(np.arange(6), dtype=np.int64),
|
| 161 |
+
"C": ["foo"] * 6,
|
| 162 |
+
"D": np.array([True, False] * 3, dtype=bool),
|
| 163 |
+
"E": np.array(
|
| 164 |
+
np.random.default_rng(2).standard_normal(6), dtype=np.float32
|
| 165 |
+
),
|
| 166 |
+
"E1": np.array(
|
| 167 |
+
np.random.default_rng(2).standard_normal(6), dtype=np.float32
|
| 168 |
+
),
|
| 169 |
+
"F": np.array(np.arange(6), dtype=np.int32),
|
| 170 |
+
}
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# columns is in a different order here than the actual items iterated
|
| 174 |
+
# from the dict
|
| 175 |
+
blocks = df._to_dict_of_blocks()
|
| 176 |
+
columns = []
|
| 177 |
+
for b in blocks.values():
|
| 178 |
+
columns.extend(b.columns)
|
| 179 |
+
|
| 180 |
+
asdict = dict(df.items())
|
| 181 |
+
asdict2 = {x: y.values for x, y in df.items()}
|
| 182 |
+
|
| 183 |
+
# dict of series & dict of ndarrays (have dtype info)
|
| 184 |
+
results = []
|
| 185 |
+
results.append(DataFrame.from_records(asdict).reindex(columns=df.columns))
|
| 186 |
+
results.append(
|
| 187 |
+
DataFrame.from_records(asdict, columns=columns).reindex(columns=df.columns)
|
| 188 |
+
)
|
| 189 |
+
results.append(
|
| 190 |
+
DataFrame.from_records(asdict2, columns=columns).reindex(columns=df.columns)
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
for r in results:
|
| 194 |
+
tm.assert_frame_equal(r, df)
|
| 195 |
+
|
| 196 |
+
def test_from_records_with_index_data(self):
|
| 197 |
+
df = DataFrame(
|
| 198 |
+
np.random.default_rng(2).standard_normal((10, 3)), columns=["A", "B", "C"]
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
data = np.random.default_rng(2).standard_normal(10)
|
| 202 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 203 |
+
df1 = DataFrame.from_records(df, index=data)
|
| 204 |
+
tm.assert_index_equal(df1.index, Index(data))
|
| 205 |
+
|
| 206 |
+
def test_from_records_bad_index_column(self):
|
| 207 |
+
df = DataFrame(
|
| 208 |
+
np.random.default_rng(2).standard_normal((10, 3)), columns=["A", "B", "C"]
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
# should pass
|
| 212 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 213 |
+
df1 = DataFrame.from_records(df, index=["C"])
|
| 214 |
+
tm.assert_index_equal(df1.index, Index(df.C))
|
| 215 |
+
|
| 216 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 217 |
+
df1 = DataFrame.from_records(df, index="C")
|
| 218 |
+
tm.assert_index_equal(df1.index, Index(df.C))
|
| 219 |
+
|
| 220 |
+
# should fail
|
| 221 |
+
msg = "|".join(
|
| 222 |
+
[
|
| 223 |
+
r"'None of \[2\] are in the columns'",
|
| 224 |
+
]
|
| 225 |
+
)
|
| 226 |
+
with pytest.raises(KeyError, match=msg):
|
| 227 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 228 |
+
DataFrame.from_records(df, index=[2])
|
| 229 |
+
with pytest.raises(KeyError, match=msg):
|
| 230 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 231 |
+
DataFrame.from_records(df, index=2)
|
| 232 |
+
|
| 233 |
+
def test_from_records_non_tuple(self):
|
| 234 |
+
class Record:
|
| 235 |
+
def __init__(self, *args) -> None:
|
| 236 |
+
self.args = args
|
| 237 |
+
|
| 238 |
+
def __getitem__(self, i):
|
| 239 |
+
return self.args[i]
|
| 240 |
+
|
| 241 |
+
def __iter__(self) -> Iterator:
|
| 242 |
+
return iter(self.args)
|
| 243 |
+
|
| 244 |
+
recs = [Record(1, 2, 3), Record(4, 5, 6), Record(7, 8, 9)]
|
| 245 |
+
tups = [tuple(rec) for rec in recs]
|
| 246 |
+
|
| 247 |
+
result = DataFrame.from_records(recs)
|
| 248 |
+
expected = DataFrame.from_records(tups)
|
| 249 |
+
tm.assert_frame_equal(result, expected)
|
| 250 |
+
|
| 251 |
+
def test_from_records_len0_with_columns(self):
|
| 252 |
+
# GH#2633
|
| 253 |
+
result = DataFrame.from_records([], index="foo", columns=["foo", "bar"])
|
| 254 |
+
expected = Index(["bar"])
|
| 255 |
+
|
| 256 |
+
assert len(result) == 0
|
| 257 |
+
assert result.index.name == "foo"
|
| 258 |
+
tm.assert_index_equal(result.columns, expected)
|
| 259 |
+
|
| 260 |
+
def test_from_records_series_list_dict(self):
|
| 261 |
+
# GH#27358
|
| 262 |
+
expected = DataFrame([[{"a": 1, "b": 2}, {"a": 3, "b": 4}]]).T
|
| 263 |
+
data = Series([[{"a": 1, "b": 2}], [{"a": 3, "b": 4}]])
|
| 264 |
+
result = DataFrame.from_records(data)
|
| 265 |
+
tm.assert_frame_equal(result, expected)
|
| 266 |
+
|
| 267 |
+
def test_from_records_series_categorical_index(self):
|
| 268 |
+
# GH#32805
|
| 269 |
+
index = CategoricalIndex(
|
| 270 |
+
[Interval(-20, -10), Interval(-10, 0), Interval(0, 10)]
|
| 271 |
+
)
|
| 272 |
+
series_of_dicts = Series([{"a": 1}, {"a": 2}, {"b": 3}], index=index)
|
| 273 |
+
frame = DataFrame.from_records(series_of_dicts, index=index)
|
| 274 |
+
expected = DataFrame(
|
| 275 |
+
{"a": [1, 2, np.nan], "b": [np.nan, np.nan, 3]}, index=index
|
| 276 |
+
)
|
| 277 |
+
tm.assert_frame_equal(frame, expected)
|
| 278 |
+
|
| 279 |
+
def test_frame_from_records_utc(self):
|
| 280 |
+
rec = {"datum": 1.5, "begin_time": datetime(2006, 4, 27, tzinfo=pytz.utc)}
|
| 281 |
+
|
| 282 |
+
# it works
|
| 283 |
+
DataFrame.from_records([rec], index="begin_time")
|
| 284 |
+
|
| 285 |
+
def test_from_records_to_records(self):
|
| 286 |
+
# from numpy documentation
|
| 287 |
+
arr = np.zeros((2,), dtype=("i4,f4,S10"))
|
| 288 |
+
arr[:] = [(1, 2.0, "Hello"), (2, 3.0, "World")]
|
| 289 |
+
|
| 290 |
+
DataFrame.from_records(arr)
|
| 291 |
+
|
| 292 |
+
index = Index(np.arange(len(arr))[::-1])
|
| 293 |
+
indexed_frame = DataFrame.from_records(arr, index=index)
|
| 294 |
+
tm.assert_index_equal(indexed_frame.index, index)
|
| 295 |
+
|
| 296 |
+
# without names, it should go to last ditch
|
| 297 |
+
arr2 = np.zeros((2, 3))
|
| 298 |
+
tm.assert_frame_equal(DataFrame.from_records(arr2), DataFrame(arr2))
|
| 299 |
+
|
| 300 |
+
# wrong length
|
| 301 |
+
msg = "|".join(
|
| 302 |
+
[
|
| 303 |
+
r"Length of values \(2\) does not match length of index \(1\)",
|
| 304 |
+
]
|
| 305 |
+
)
|
| 306 |
+
with pytest.raises(ValueError, match=msg):
|
| 307 |
+
DataFrame.from_records(arr, index=index[:-1])
|
| 308 |
+
|
| 309 |
+
indexed_frame = DataFrame.from_records(arr, index="f1")
|
| 310 |
+
|
| 311 |
+
# what to do?
|
| 312 |
+
records = indexed_frame.to_records()
|
| 313 |
+
assert len(records.dtype.names) == 3
|
| 314 |
+
|
| 315 |
+
records = indexed_frame.to_records(index=False)
|
| 316 |
+
assert len(records.dtype.names) == 2
|
| 317 |
+
assert "index" not in records.dtype.names
|
| 318 |
+
|
| 319 |
+
def test_from_records_nones(self):
|
| 320 |
+
tuples = [(1, 2, None, 3), (1, 2, None, 3), (None, 2, 5, 3)]
|
| 321 |
+
|
| 322 |
+
df = DataFrame.from_records(tuples, columns=["a", "b", "c", "d"])
|
| 323 |
+
assert np.isnan(df["c"][0])
|
| 324 |
+
|
| 325 |
+
def test_from_records_iterator(self):
|
| 326 |
+
arr = np.array(
|
| 327 |
+
[(1.0, 1.0, 2, 2), (3.0, 3.0, 4, 4), (5.0, 5.0, 6, 6), (7.0, 7.0, 8, 8)],
|
| 328 |
+
dtype=[
|
| 329 |
+
("x", np.float64),
|
| 330 |
+
("u", np.float32),
|
| 331 |
+
("y", np.int64),
|
| 332 |
+
("z", np.int32),
|
| 333 |
+
],
|
| 334 |
+
)
|
| 335 |
+
df = DataFrame.from_records(iter(arr), nrows=2)
|
| 336 |
+
xp = DataFrame(
|
| 337 |
+
{
|
| 338 |
+
"x": np.array([1.0, 3.0], dtype=np.float64),
|
| 339 |
+
"u": np.array([1.0, 3.0], dtype=np.float32),
|
| 340 |
+
"y": np.array([2, 4], dtype=np.int64),
|
| 341 |
+
"z": np.array([2, 4], dtype=np.int32),
|
| 342 |
+
}
|
| 343 |
+
)
|
| 344 |
+
tm.assert_frame_equal(df.reindex_like(xp), xp)
|
| 345 |
+
|
| 346 |
+
# no dtypes specified here, so just compare with the default
|
| 347 |
+
arr = [(1.0, 2), (3.0, 4), (5.0, 6), (7.0, 8)]
|
| 348 |
+
df = DataFrame.from_records(iter(arr), columns=["x", "y"], nrows=2)
|
| 349 |
+
tm.assert_frame_equal(df, xp.reindex(columns=["x", "y"]), check_dtype=False)
|
| 350 |
+
|
| 351 |
+
def test_from_records_tuples_generator(self):
|
| 352 |
+
def tuple_generator(length):
|
| 353 |
+
for i in range(length):
|
| 354 |
+
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
| 355 |
+
yield (i, letters[i % len(letters)], i / length)
|
| 356 |
+
|
| 357 |
+
columns_names = ["Integer", "String", "Float"]
|
| 358 |
+
columns = [
|
| 359 |
+
[i[j] for i in tuple_generator(10)] for j in range(len(columns_names))
|
| 360 |
+
]
|
| 361 |
+
data = {"Integer": columns[0], "String": columns[1], "Float": columns[2]}
|
| 362 |
+
expected = DataFrame(data, columns=columns_names)
|
| 363 |
+
|
| 364 |
+
generator = tuple_generator(10)
|
| 365 |
+
result = DataFrame.from_records(generator, columns=columns_names)
|
| 366 |
+
tm.assert_frame_equal(result, expected)
|
| 367 |
+
|
| 368 |
+
def test_from_records_lists_generator(self):
|
| 369 |
+
def list_generator(length):
|
| 370 |
+
for i in range(length):
|
| 371 |
+
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
| 372 |
+
yield [i, letters[i % len(letters)], i / length]
|
| 373 |
+
|
| 374 |
+
columns_names = ["Integer", "String", "Float"]
|
| 375 |
+
columns = [
|
| 376 |
+
[i[j] for i in list_generator(10)] for j in range(len(columns_names))
|
| 377 |
+
]
|
| 378 |
+
data = {"Integer": columns[0], "String": columns[1], "Float": columns[2]}
|
| 379 |
+
expected = DataFrame(data, columns=columns_names)
|
| 380 |
+
|
| 381 |
+
generator = list_generator(10)
|
| 382 |
+
result = DataFrame.from_records(generator, columns=columns_names)
|
| 383 |
+
tm.assert_frame_equal(result, expected)
|
| 384 |
+
|
| 385 |
+
def test_from_records_columns_not_modified(self):
|
| 386 |
+
tuples = [(1, 2, 3), (1, 2, 3), (2, 5, 3)]
|
| 387 |
+
|
| 388 |
+
columns = ["a", "b", "c"]
|
| 389 |
+
original_columns = list(columns)
|
| 390 |
+
|
| 391 |
+
DataFrame.from_records(tuples, columns=columns, index="a")
|
| 392 |
+
|
| 393 |
+
assert columns == original_columns
|
| 394 |
+
|
| 395 |
+
def test_from_records_decimal(self):
|
| 396 |
+
tuples = [(Decimal("1.5"),), (Decimal("2.5"),), (None,)]
|
| 397 |
+
|
| 398 |
+
df = DataFrame.from_records(tuples, columns=["a"])
|
| 399 |
+
assert df["a"].dtype == object
|
| 400 |
+
|
| 401 |
+
df = DataFrame.from_records(tuples, columns=["a"], coerce_float=True)
|
| 402 |
+
assert df["a"].dtype == np.float64
|
| 403 |
+
assert np.isnan(df["a"].values[-1])
|
| 404 |
+
|
| 405 |
+
def test_from_records_duplicates(self):
|
| 406 |
+
result = DataFrame.from_records([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "a"])
|
| 407 |
+
|
| 408 |
+
expected = DataFrame([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "a"])
|
| 409 |
+
|
| 410 |
+
tm.assert_frame_equal(result, expected)
|
| 411 |
+
|
| 412 |
+
def test_from_records_set_index_name(self):
|
| 413 |
+
def create_dict(order_id):
|
| 414 |
+
return {
|
| 415 |
+
"order_id": order_id,
|
| 416 |
+
"quantity": np.random.default_rng(2).integers(1, 10),
|
| 417 |
+
"price": np.random.default_rng(2).integers(1, 10),
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
documents = [create_dict(i) for i in range(10)]
|
| 421 |
+
# demo missing data
|
| 422 |
+
documents.append({"order_id": 10, "quantity": 5})
|
| 423 |
+
|
| 424 |
+
result = DataFrame.from_records(documents, index="order_id")
|
| 425 |
+
assert result.index.name == "order_id"
|
| 426 |
+
|
| 427 |
+
# MultiIndex
|
| 428 |
+
result = DataFrame.from_records(documents, index=["order_id", "quantity"])
|
| 429 |
+
assert result.index.names == ("order_id", "quantity")
|
| 430 |
+
|
| 431 |
+
def test_from_records_misc_brokenness(self):
|
| 432 |
+
# GH#2179
|
| 433 |
+
|
| 434 |
+
data = {1: ["foo"], 2: ["bar"]}
|
| 435 |
+
|
| 436 |
+
result = DataFrame.from_records(data, columns=["a", "b"])
|
| 437 |
+
exp = DataFrame(data, columns=["a", "b"])
|
| 438 |
+
tm.assert_frame_equal(result, exp)
|
| 439 |
+
|
| 440 |
+
# overlap in index/index_names
|
| 441 |
+
|
| 442 |
+
data = {"a": [1, 2, 3], "b": [4, 5, 6]}
|
| 443 |
+
|
| 444 |
+
result = DataFrame.from_records(data, index=["a", "b", "c"])
|
| 445 |
+
exp = DataFrame(data, index=["a", "b", "c"])
|
| 446 |
+
tm.assert_frame_equal(result, exp)
|
| 447 |
+
|
| 448 |
+
def test_from_records_misc_brokenness2(self):
|
| 449 |
+
# GH#2623
|
| 450 |
+
rows = []
|
| 451 |
+
rows.append([datetime(2010, 1, 1), 1])
|
| 452 |
+
rows.append([datetime(2010, 1, 2), "hi"]) # test col upconverts to obj
|
| 453 |
+
result = DataFrame.from_records(rows, columns=["date", "test"])
|
| 454 |
+
expected = DataFrame(
|
| 455 |
+
{"date": [row[0] for row in rows], "test": [row[1] for row in rows]}
|
| 456 |
+
)
|
| 457 |
+
tm.assert_frame_equal(result, expected)
|
| 458 |
+
assert result.dtypes["test"] == np.dtype(object)
|
| 459 |
+
|
| 460 |
+
def test_from_records_misc_brokenness3(self):
|
| 461 |
+
rows = []
|
| 462 |
+
rows.append([datetime(2010, 1, 1), 1])
|
| 463 |
+
rows.append([datetime(2010, 1, 2), 1])
|
| 464 |
+
result = DataFrame.from_records(rows, columns=["date", "test"])
|
| 465 |
+
expected = DataFrame(
|
| 466 |
+
{"date": [row[0] for row in rows], "test": [row[1] for row in rows]}
|
| 467 |
+
)
|
| 468 |
+
tm.assert_frame_equal(result, expected)
|
| 469 |
+
|
| 470 |
+
def test_from_records_empty(self):
|
| 471 |
+
# GH#3562
|
| 472 |
+
result = DataFrame.from_records([], columns=["a", "b", "c"])
|
| 473 |
+
expected = DataFrame(columns=["a", "b", "c"])
|
| 474 |
+
tm.assert_frame_equal(result, expected)
|
| 475 |
+
|
| 476 |
+
result = DataFrame.from_records([], columns=["a", "b", "b"])
|
| 477 |
+
expected = DataFrame(columns=["a", "b", "b"])
|
| 478 |
+
tm.assert_frame_equal(result, expected)
|
| 479 |
+
|
| 480 |
+
def test_from_records_empty_with_nonempty_fields_gh3682(self):
|
| 481 |
+
a = np.array([(1, 2)], dtype=[("id", np.int64), ("value", np.int64)])
|
| 482 |
+
df = DataFrame.from_records(a, index="id")
|
| 483 |
+
|
| 484 |
+
ex_index = Index([1], name="id")
|
| 485 |
+
expected = DataFrame({"value": [2]}, index=ex_index, columns=["value"])
|
| 486 |
+
tm.assert_frame_equal(df, expected)
|
| 487 |
+
|
| 488 |
+
b = a[:0]
|
| 489 |
+
df2 = DataFrame.from_records(b, index="id")
|
| 490 |
+
tm.assert_frame_equal(df2, df.iloc[:0])
|
| 491 |
+
|
| 492 |
+
def test_from_records_empty2(self):
|
| 493 |
+
# GH#42456
|
| 494 |
+
dtype = [("prop", int)]
|
| 495 |
+
shape = (0, len(dtype))
|
| 496 |
+
arr = np.empty(shape, dtype=dtype)
|
| 497 |
+
|
| 498 |
+
result = DataFrame.from_records(arr)
|
| 499 |
+
expected = DataFrame({"prop": np.array([], dtype=int)})
|
| 500 |
+
tm.assert_frame_equal(result, expected)
|
| 501 |
+
|
| 502 |
+
alt = DataFrame(arr)
|
| 503 |
+
tm.assert_frame_equal(alt, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/__init__.py
ADDED
|
File without changes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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests for values coercion in setitem-like operations on DataFrame.
|
| 3 |
+
|
| 4 |
+
For the most part, these should be multi-column DataFrames, otherwise
|
| 5 |
+
we would share the tests with Series.
|
| 6 |
+
"""
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from pandas import (
|
| 12 |
+
DataFrame,
|
| 13 |
+
MultiIndex,
|
| 14 |
+
NaT,
|
| 15 |
+
Series,
|
| 16 |
+
Timestamp,
|
| 17 |
+
date_range,
|
| 18 |
+
)
|
| 19 |
+
import pandas._testing as tm
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TestDataFrameSetitemCoercion:
|
| 23 |
+
@pytest.mark.parametrize("consolidate", [True, False])
|
| 24 |
+
def test_loc_setitem_multiindex_columns(self, consolidate):
|
| 25 |
+
# GH#18415 Setting values in a single column preserves dtype,
|
| 26 |
+
# while setting them in multiple columns did unwanted cast.
|
| 27 |
+
|
| 28 |
+
# Note that A here has 2 blocks, below we do the same thing
|
| 29 |
+
# with a consolidated frame.
|
| 30 |
+
A = DataFrame(np.zeros((6, 5), dtype=np.float32))
|
| 31 |
+
A = pd.concat([A, A], axis=1, keys=[1, 2])
|
| 32 |
+
if consolidate:
|
| 33 |
+
A = A._consolidate()
|
| 34 |
+
|
| 35 |
+
A.loc[2:3, (1, slice(2, 3))] = np.ones((2, 2), dtype=np.float32)
|
| 36 |
+
assert (A.dtypes == np.float32).all()
|
| 37 |
+
|
| 38 |
+
A.loc[0:5, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)
|
| 39 |
+
|
| 40 |
+
assert (A.dtypes == np.float32).all()
|
| 41 |
+
|
| 42 |
+
A.loc[:, (1, slice(2, 3))] = np.ones((6, 2), dtype=np.float32)
|
| 43 |
+
assert (A.dtypes == np.float32).all()
|
| 44 |
+
|
| 45 |
+
# TODO: i think this isn't about MultiIndex and could be done with iloc?
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_37477():
|
| 49 |
+
# fixed by GH#45121
|
| 50 |
+
orig = DataFrame({"A": [1, 2, 3], "B": [3, 4, 5]})
|
| 51 |
+
expected = DataFrame({"A": [1, 2, 3], "B": [3, 1.2, 5]})
|
| 52 |
+
|
| 53 |
+
df = orig.copy()
|
| 54 |
+
with tm.assert_produces_warning(
|
| 55 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 56 |
+
):
|
| 57 |
+
df.at[1, "B"] = 1.2
|
| 58 |
+
tm.assert_frame_equal(df, expected)
|
| 59 |
+
|
| 60 |
+
df = orig.copy()
|
| 61 |
+
with tm.assert_produces_warning(
|
| 62 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 63 |
+
):
|
| 64 |
+
df.loc[1, "B"] = 1.2
|
| 65 |
+
tm.assert_frame_equal(df, expected)
|
| 66 |
+
|
| 67 |
+
df = orig.copy()
|
| 68 |
+
with tm.assert_produces_warning(
|
| 69 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 70 |
+
):
|
| 71 |
+
df.iat[1, 1] = 1.2
|
| 72 |
+
tm.assert_frame_equal(df, expected)
|
| 73 |
+
|
| 74 |
+
df = orig.copy()
|
| 75 |
+
with tm.assert_produces_warning(
|
| 76 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 77 |
+
):
|
| 78 |
+
df.iloc[1, 1] = 1.2
|
| 79 |
+
tm.assert_frame_equal(df, expected)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_6942(indexer_al):
|
| 83 |
+
# check that the .at __setitem__ after setting "Live" actually sets the data
|
| 84 |
+
start = Timestamp("2014-04-01")
|
| 85 |
+
t1 = Timestamp("2014-04-23 12:42:38.883082")
|
| 86 |
+
t2 = Timestamp("2014-04-24 01:33:30.040039")
|
| 87 |
+
|
| 88 |
+
dti = date_range(start, periods=1)
|
| 89 |
+
orig = DataFrame(index=dti, columns=["timenow", "Live"])
|
| 90 |
+
|
| 91 |
+
df = orig.copy()
|
| 92 |
+
indexer_al(df)[start, "timenow"] = t1
|
| 93 |
+
|
| 94 |
+
df["Live"] = True
|
| 95 |
+
|
| 96 |
+
df.at[start, "timenow"] = t2
|
| 97 |
+
assert df.iloc[0, 0] == t2
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_26395(indexer_al):
|
| 101 |
+
# .at case fixed by GH#45121 (best guess)
|
| 102 |
+
df = DataFrame(index=["A", "B", "C"])
|
| 103 |
+
df["D"] = 0
|
| 104 |
+
|
| 105 |
+
indexer_al(df)["C", "D"] = 2
|
| 106 |
+
expected = DataFrame({"D": [0, 0, 2]}, index=["A", "B", "C"], dtype=np.int64)
|
| 107 |
+
tm.assert_frame_equal(df, expected)
|
| 108 |
+
|
| 109 |
+
with tm.assert_produces_warning(
|
| 110 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 111 |
+
):
|
| 112 |
+
indexer_al(df)["C", "D"] = 44.5
|
| 113 |
+
expected = DataFrame(
|
| 114 |
+
{"D": [0, 0, 44.5]},
|
| 115 |
+
index=["A", "B", "C"],
|
| 116 |
+
columns=["D"],
|
| 117 |
+
dtype=np.float64,
|
| 118 |
+
)
|
| 119 |
+
tm.assert_frame_equal(df, expected)
|
| 120 |
+
|
| 121 |
+
with tm.assert_produces_warning(
|
| 122 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 123 |
+
):
|
| 124 |
+
indexer_al(df)["C", "D"] = "hello"
|
| 125 |
+
expected = DataFrame(
|
| 126 |
+
{"D": [0, 0, "hello"]},
|
| 127 |
+
index=["A", "B", "C"],
|
| 128 |
+
columns=["D"],
|
| 129 |
+
dtype=object,
|
| 130 |
+
)
|
| 131 |
+
tm.assert_frame_equal(df, expected)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@pytest.mark.xfail(reason="unwanted upcast")
|
| 135 |
+
def test_15231():
|
| 136 |
+
df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
|
| 137 |
+
df.loc[2] = Series({"a": 5, "b": 6})
|
| 138 |
+
assert (df.dtypes == np.int64).all()
|
| 139 |
+
|
| 140 |
+
df.loc[3] = Series({"a": 7})
|
| 141 |
+
|
| 142 |
+
# df["a"] doesn't have any NaNs, should not have been cast
|
| 143 |
+
exp_dtypes = Series([np.int64, np.float64], dtype=object, index=["a", "b"])
|
| 144 |
+
tm.assert_series_equal(df.dtypes, exp_dtypes)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_iloc_setitem_unnecesssary_float_upcasting():
|
| 148 |
+
# GH#12255
|
| 149 |
+
df = DataFrame(
|
| 150 |
+
{
|
| 151 |
+
0: np.array([1, 3], dtype=np.float32),
|
| 152 |
+
1: np.array([2, 4], dtype=np.float32),
|
| 153 |
+
2: ["a", "b"],
|
| 154 |
+
}
|
| 155 |
+
)
|
| 156 |
+
orig = df.copy()
|
| 157 |
+
|
| 158 |
+
values = df[0].values.reshape(2, 1)
|
| 159 |
+
df.iloc[:, 0:1] = values
|
| 160 |
+
|
| 161 |
+
tm.assert_frame_equal(df, orig)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@pytest.mark.xfail(reason="unwanted casting to dt64")
|
| 165 |
+
def test_12499():
|
| 166 |
+
# TODO: OP in GH#12499 used np.datetim64("NaT") instead of pd.NaT,
|
| 167 |
+
# which has consequences for the expected df["two"] (though i think at
|
| 168 |
+
# the time it might not have because of a separate bug). See if it makes
|
| 169 |
+
# a difference which one we use here.
|
| 170 |
+
ts = Timestamp("2016-03-01 03:13:22.98986", tz="UTC")
|
| 171 |
+
|
| 172 |
+
data = [{"one": 0, "two": ts}]
|
| 173 |
+
orig = DataFrame(data)
|
| 174 |
+
df = orig.copy()
|
| 175 |
+
df.loc[1] = [np.nan, NaT]
|
| 176 |
+
|
| 177 |
+
expected = DataFrame(
|
| 178 |
+
{"one": [0, np.nan], "two": Series([ts, NaT], dtype="datetime64[ns, UTC]")}
|
| 179 |
+
)
|
| 180 |
+
tm.assert_frame_equal(df, expected)
|
| 181 |
+
|
| 182 |
+
data = [{"one": 0, "two": ts}]
|
| 183 |
+
df = orig.copy()
|
| 184 |
+
df.loc[1, :] = [np.nan, NaT]
|
| 185 |
+
tm.assert_frame_equal(df, expected)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def test_20476():
|
| 189 |
+
mi = MultiIndex.from_product([["A", "B"], ["a", "b", "c"]])
|
| 190 |
+
df = DataFrame(-1, index=range(3), columns=mi)
|
| 191 |
+
filler = DataFrame([[1, 2, 3.0]] * 3, index=range(3), columns=["a", "b", "c"])
|
| 192 |
+
df["A"] = filler
|
| 193 |
+
|
| 194 |
+
expected = DataFrame(
|
| 195 |
+
{
|
| 196 |
+
0: [1, 1, 1],
|
| 197 |
+
1: [2, 2, 2],
|
| 198 |
+
2: [3.0, 3.0, 3.0],
|
| 199 |
+
3: [-1, -1, -1],
|
| 200 |
+
4: [-1, -1, -1],
|
| 201 |
+
5: [-1, -1, -1],
|
| 202 |
+
}
|
| 203 |
+
)
|
| 204 |
+
expected.columns = mi
|
| 205 |
+
exp_dtypes = Series(
|
| 206 |
+
[np.dtype(np.int64)] * 2 + [np.dtype(np.float64)] + [np.dtype(np.int64)] * 3,
|
| 207 |
+
index=mi,
|
| 208 |
+
)
|
| 209 |
+
tm.assert_series_equal(df.dtypes, exp_dtypes)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_delitem.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas import (
|
| 7 |
+
DataFrame,
|
| 8 |
+
MultiIndex,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestDataFrameDelItem:
|
| 13 |
+
def test_delitem(self, float_frame):
|
| 14 |
+
del float_frame["A"]
|
| 15 |
+
assert "A" not in float_frame
|
| 16 |
+
|
| 17 |
+
def test_delitem_multiindex(self):
|
| 18 |
+
midx = MultiIndex.from_product([["A", "B"], [1, 2]])
|
| 19 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((4, 4)), columns=midx)
|
| 20 |
+
assert len(df.columns) == 4
|
| 21 |
+
assert ("A",) in df.columns
|
| 22 |
+
assert "A" in df.columns
|
| 23 |
+
|
| 24 |
+
result = df["A"]
|
| 25 |
+
assert isinstance(result, DataFrame)
|
| 26 |
+
del df["A"]
|
| 27 |
+
|
| 28 |
+
assert len(df.columns) == 2
|
| 29 |
+
|
| 30 |
+
# A still in the levels, BUT get a KeyError if trying
|
| 31 |
+
# to delete
|
| 32 |
+
assert ("A",) not in df.columns
|
| 33 |
+
with pytest.raises(KeyError, match=re.escape("('A',)")):
|
| 34 |
+
del df[("A",)]
|
| 35 |
+
|
| 36 |
+
# behavior of dropped/deleted MultiIndex levels changed from
|
| 37 |
+
# GH 2770 to GH 19027: MultiIndex no longer '.__contains__'
|
| 38 |
+
# levels which are dropped/deleted
|
| 39 |
+
assert "A" not in df.columns
|
| 40 |
+
with pytest.raises(KeyError, match=re.escape("('A',)")):
|
| 41 |
+
del df["A"]
|
| 42 |
+
|
| 43 |
+
def test_delitem_corner(self, float_frame):
|
| 44 |
+
f = float_frame.copy()
|
| 45 |
+
del f["D"]
|
| 46 |
+
assert len(f.columns) == 3
|
| 47 |
+
with pytest.raises(KeyError, match=r"^'D'$"):
|
| 48 |
+
del f["D"]
|
| 49 |
+
del f["B"]
|
| 50 |
+
assert len(f.columns) == 2
|
| 51 |
+
|
| 52 |
+
def test_delitem_col_still_multiindex(self):
|
| 53 |
+
arrays = [["a", "b", "c", "top"], ["", "", "", "OD"], ["", "", "", "wx"]]
|
| 54 |
+
|
| 55 |
+
tuples = sorted(zip(*arrays))
|
| 56 |
+
index = MultiIndex.from_tuples(tuples)
|
| 57 |
+
|
| 58 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((3, 4)), columns=index)
|
| 59 |
+
del df[("a", "", "")]
|
| 60 |
+
assert isinstance(df.columns, MultiIndex)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_get.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from pandas import DataFrame
|
| 4 |
+
import pandas._testing as tm
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestGet:
|
| 8 |
+
def test_get(self, float_frame):
|
| 9 |
+
b = float_frame.get("B")
|
| 10 |
+
tm.assert_series_equal(b, float_frame["B"])
|
| 11 |
+
|
| 12 |
+
assert float_frame.get("foo") is None
|
| 13 |
+
tm.assert_series_equal(
|
| 14 |
+
float_frame.get("foo", float_frame["B"]), float_frame["B"]
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
@pytest.mark.parametrize(
|
| 18 |
+
"df",
|
| 19 |
+
[
|
| 20 |
+
DataFrame(),
|
| 21 |
+
DataFrame(columns=list("AB")),
|
| 22 |
+
DataFrame(columns=list("AB"), index=range(3)),
|
| 23 |
+
],
|
| 24 |
+
)
|
| 25 |
+
def test_get_none(self, df):
|
| 26 |
+
# see gh-5652
|
| 27 |
+
assert df.get(None) is None
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_get_value.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from pandas import (
|
| 4 |
+
DataFrame,
|
| 5 |
+
MultiIndex,
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestGetValue:
|
| 10 |
+
def test_get_set_value_no_partial_indexing(self):
|
| 11 |
+
# partial w/ MultiIndex raise exception
|
| 12 |
+
index = MultiIndex.from_tuples([(0, 1), (0, 2), (1, 1), (1, 2)])
|
| 13 |
+
df = DataFrame(index=index, columns=range(4))
|
| 14 |
+
with pytest.raises(KeyError, match=r"^0$"):
|
| 15 |
+
df._get_value(0, 1)
|
| 16 |
+
|
| 17 |
+
def test_get_value(self, float_frame):
|
| 18 |
+
for idx in float_frame.index:
|
| 19 |
+
for col in float_frame.columns:
|
| 20 |
+
result = float_frame._get_value(idx, col)
|
| 21 |
+
expected = float_frame[col][idx]
|
| 22 |
+
assert result == expected
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_getitem.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
Categorical,
|
| 8 |
+
CategoricalDtype,
|
| 9 |
+
CategoricalIndex,
|
| 10 |
+
DataFrame,
|
| 11 |
+
DateOffset,
|
| 12 |
+
DatetimeIndex,
|
| 13 |
+
Index,
|
| 14 |
+
MultiIndex,
|
| 15 |
+
Series,
|
| 16 |
+
Timestamp,
|
| 17 |
+
concat,
|
| 18 |
+
date_range,
|
| 19 |
+
get_dummies,
|
| 20 |
+
period_range,
|
| 21 |
+
)
|
| 22 |
+
import pandas._testing as tm
|
| 23 |
+
from pandas.core.arrays import SparseArray
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class TestGetitem:
|
| 27 |
+
def test_getitem_unused_level_raises(self):
|
| 28 |
+
# GH#20410
|
| 29 |
+
mi = MultiIndex(
|
| 30 |
+
levels=[["a_lot", "onlyone", "notevenone"], [1970, ""]],
|
| 31 |
+
codes=[[1, 0], [1, 0]],
|
| 32 |
+
)
|
| 33 |
+
df = DataFrame(-1, index=range(3), columns=mi)
|
| 34 |
+
|
| 35 |
+
with pytest.raises(KeyError, match="notevenone"):
|
| 36 |
+
df["notevenone"]
|
| 37 |
+
|
| 38 |
+
def test_getitem_periodindex(self):
|
| 39 |
+
rng = period_range("1/1/2000", periods=5)
|
| 40 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)), columns=rng)
|
| 41 |
+
|
| 42 |
+
ts = df[rng[0]]
|
| 43 |
+
tm.assert_series_equal(ts, df.iloc[:, 0])
|
| 44 |
+
|
| 45 |
+
ts = df["1/1/2000"]
|
| 46 |
+
tm.assert_series_equal(ts, df.iloc[:, 0])
|
| 47 |
+
|
| 48 |
+
def test_getitem_list_of_labels_categoricalindex_cols(self):
|
| 49 |
+
# GH#16115
|
| 50 |
+
cats = Categorical([Timestamp("12-31-1999"), Timestamp("12-31-2000")])
|
| 51 |
+
|
| 52 |
+
expected = DataFrame([[1, 0], [0, 1]], dtype="bool", index=[0, 1], columns=cats)
|
| 53 |
+
dummies = get_dummies(cats)
|
| 54 |
+
result = dummies[list(dummies.columns)]
|
| 55 |
+
tm.assert_frame_equal(result, expected)
|
| 56 |
+
|
| 57 |
+
def test_getitem_sparse_column_return_type_and_dtype(self):
|
| 58 |
+
# https://github.com/pandas-dev/pandas/issues/23559
|
| 59 |
+
data = SparseArray([0, 1])
|
| 60 |
+
df = DataFrame({"A": data})
|
| 61 |
+
expected = Series(data, name="A")
|
| 62 |
+
result = df["A"]
|
| 63 |
+
tm.assert_series_equal(result, expected)
|
| 64 |
+
|
| 65 |
+
# Also check iloc and loc while we're here
|
| 66 |
+
result = df.iloc[:, 0]
|
| 67 |
+
tm.assert_series_equal(result, expected)
|
| 68 |
+
|
| 69 |
+
result = df.loc[:, "A"]
|
| 70 |
+
tm.assert_series_equal(result, expected)
|
| 71 |
+
|
| 72 |
+
def test_getitem_string_columns(self):
|
| 73 |
+
# GH#46185
|
| 74 |
+
df = DataFrame([[1, 2]], columns=Index(["A", "B"], dtype="string"))
|
| 75 |
+
result = df.A
|
| 76 |
+
expected = df["A"]
|
| 77 |
+
tm.assert_series_equal(result, expected)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class TestGetitemListLike:
|
| 81 |
+
def test_getitem_list_missing_key(self):
|
| 82 |
+
# GH#13822, incorrect error string with non-unique columns when missing
|
| 83 |
+
# column is accessed
|
| 84 |
+
df = DataFrame({"x": [1.0], "y": [2.0], "z": [3.0]})
|
| 85 |
+
df.columns = ["x", "x", "z"]
|
| 86 |
+
|
| 87 |
+
# Check that we get the correct value in the KeyError
|
| 88 |
+
with pytest.raises(KeyError, match=r"\['y'\] not in index"):
|
| 89 |
+
df[["x", "y", "z"]]
|
| 90 |
+
|
| 91 |
+
def test_getitem_list_duplicates(self):
|
| 92 |
+
# GH#1943
|
| 93 |
+
df = DataFrame(
|
| 94 |
+
np.random.default_rng(2).standard_normal((4, 4)), columns=list("AABC")
|
| 95 |
+
)
|
| 96 |
+
df.columns.name = "foo"
|
| 97 |
+
|
| 98 |
+
result = df[["B", "C"]]
|
| 99 |
+
assert result.columns.name == "foo"
|
| 100 |
+
|
| 101 |
+
expected = df.iloc[:, 2:]
|
| 102 |
+
tm.assert_frame_equal(result, expected)
|
| 103 |
+
|
| 104 |
+
def test_getitem_dupe_cols(self):
|
| 105 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"])
|
| 106 |
+
msg = "\"None of [Index(['baf'], dtype="
|
| 107 |
+
with pytest.raises(KeyError, match=re.escape(msg)):
|
| 108 |
+
df[["baf"]]
|
| 109 |
+
|
| 110 |
+
@pytest.mark.parametrize(
|
| 111 |
+
"idx_type",
|
| 112 |
+
[
|
| 113 |
+
list,
|
| 114 |
+
iter,
|
| 115 |
+
Index,
|
| 116 |
+
set,
|
| 117 |
+
lambda keys: dict(zip(keys, range(len(keys)))),
|
| 118 |
+
lambda keys: dict(zip(keys, range(len(keys)))).keys(),
|
| 119 |
+
],
|
| 120 |
+
ids=["list", "iter", "Index", "set", "dict", "dict_keys"],
|
| 121 |
+
)
|
| 122 |
+
@pytest.mark.parametrize("levels", [1, 2])
|
| 123 |
+
def test_getitem_listlike(self, idx_type, levels, float_frame):
|
| 124 |
+
# GH#21294
|
| 125 |
+
|
| 126 |
+
if levels == 1:
|
| 127 |
+
frame, missing = float_frame, "food"
|
| 128 |
+
else:
|
| 129 |
+
# MultiIndex columns
|
| 130 |
+
frame = DataFrame(
|
| 131 |
+
np.random.default_rng(2).standard_normal((8, 3)),
|
| 132 |
+
columns=Index(
|
| 133 |
+
[("foo", "bar"), ("baz", "qux"), ("peek", "aboo")],
|
| 134 |
+
name=("sth", "sth2"),
|
| 135 |
+
),
|
| 136 |
+
)
|
| 137 |
+
missing = ("good", "food")
|
| 138 |
+
|
| 139 |
+
keys = [frame.columns[1], frame.columns[0]]
|
| 140 |
+
idx = idx_type(keys)
|
| 141 |
+
idx_check = list(idx_type(keys))
|
| 142 |
+
|
| 143 |
+
if isinstance(idx, (set, dict)):
|
| 144 |
+
with pytest.raises(TypeError, match="as an indexer is not supported"):
|
| 145 |
+
frame[idx]
|
| 146 |
+
|
| 147 |
+
return
|
| 148 |
+
else:
|
| 149 |
+
result = frame[idx]
|
| 150 |
+
|
| 151 |
+
expected = frame.loc[:, idx_check]
|
| 152 |
+
expected.columns.names = frame.columns.names
|
| 153 |
+
|
| 154 |
+
tm.assert_frame_equal(result, expected)
|
| 155 |
+
|
| 156 |
+
idx = idx_type(keys + [missing])
|
| 157 |
+
with pytest.raises(KeyError, match="not in index"):
|
| 158 |
+
frame[idx]
|
| 159 |
+
|
| 160 |
+
def test_getitem_iloc_generator(self):
|
| 161 |
+
# GH#39614
|
| 162 |
+
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
|
| 163 |
+
indexer = (x for x in [1, 2])
|
| 164 |
+
result = df.iloc[indexer]
|
| 165 |
+
expected = DataFrame({"a": [2, 3], "b": [5, 6]}, index=[1, 2])
|
| 166 |
+
tm.assert_frame_equal(result, expected)
|
| 167 |
+
|
| 168 |
+
def test_getitem_iloc_two_dimensional_generator(self):
|
| 169 |
+
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
|
| 170 |
+
indexer = (x for x in [1, 2])
|
| 171 |
+
result = df.iloc[indexer, 1]
|
| 172 |
+
expected = Series([5, 6], name="b", index=[1, 2])
|
| 173 |
+
tm.assert_series_equal(result, expected)
|
| 174 |
+
|
| 175 |
+
def test_getitem_iloc_dateoffset_days(self):
|
| 176 |
+
# GH 46671
|
| 177 |
+
df = DataFrame(
|
| 178 |
+
list(range(10)),
|
| 179 |
+
index=date_range("01-01-2022", periods=10, freq=DateOffset(days=1)),
|
| 180 |
+
)
|
| 181 |
+
result = df.loc["2022-01-01":"2022-01-03"]
|
| 182 |
+
expected = DataFrame(
|
| 183 |
+
[0, 1, 2],
|
| 184 |
+
index=DatetimeIndex(
|
| 185 |
+
["2022-01-01", "2022-01-02", "2022-01-03"],
|
| 186 |
+
dtype="datetime64[ns]",
|
| 187 |
+
freq=DateOffset(days=1),
|
| 188 |
+
),
|
| 189 |
+
)
|
| 190 |
+
tm.assert_frame_equal(result, expected)
|
| 191 |
+
|
| 192 |
+
df = DataFrame(
|
| 193 |
+
list(range(10)),
|
| 194 |
+
index=date_range(
|
| 195 |
+
"01-01-2022", periods=10, freq=DateOffset(days=1, hours=2)
|
| 196 |
+
),
|
| 197 |
+
)
|
| 198 |
+
result = df.loc["2022-01-01":"2022-01-03"]
|
| 199 |
+
expected = DataFrame(
|
| 200 |
+
[0, 1, 2],
|
| 201 |
+
index=DatetimeIndex(
|
| 202 |
+
["2022-01-01 00:00:00", "2022-01-02 02:00:00", "2022-01-03 04:00:00"],
|
| 203 |
+
dtype="datetime64[ns]",
|
| 204 |
+
freq=DateOffset(days=1, hours=2),
|
| 205 |
+
),
|
| 206 |
+
)
|
| 207 |
+
tm.assert_frame_equal(result, expected)
|
| 208 |
+
|
| 209 |
+
df = DataFrame(
|
| 210 |
+
list(range(10)),
|
| 211 |
+
index=date_range("01-01-2022", periods=10, freq=DateOffset(minutes=3)),
|
| 212 |
+
)
|
| 213 |
+
result = df.loc["2022-01-01":"2022-01-03"]
|
| 214 |
+
tm.assert_frame_equal(result, df)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class TestGetitemCallable:
|
| 218 |
+
def test_getitem_callable(self, float_frame):
|
| 219 |
+
# GH#12533
|
| 220 |
+
result = float_frame[lambda x: "A"]
|
| 221 |
+
expected = float_frame.loc[:, "A"]
|
| 222 |
+
tm.assert_series_equal(result, expected)
|
| 223 |
+
|
| 224 |
+
result = float_frame[lambda x: ["A", "B"]]
|
| 225 |
+
expected = float_frame.loc[:, ["A", "B"]]
|
| 226 |
+
tm.assert_frame_equal(result, float_frame.loc[:, ["A", "B"]])
|
| 227 |
+
|
| 228 |
+
df = float_frame[:3]
|
| 229 |
+
result = df[lambda x: [True, False, True]]
|
| 230 |
+
expected = float_frame.iloc[[0, 2], :]
|
| 231 |
+
tm.assert_frame_equal(result, expected)
|
| 232 |
+
|
| 233 |
+
def test_loc_multiindex_columns_one_level(self):
|
| 234 |
+
# GH#29749
|
| 235 |
+
df = DataFrame([[1, 2]], columns=[["a", "b"]])
|
| 236 |
+
expected = DataFrame([1], columns=[["a"]])
|
| 237 |
+
|
| 238 |
+
result = df["a"]
|
| 239 |
+
tm.assert_frame_equal(result, expected)
|
| 240 |
+
|
| 241 |
+
result = df.loc[:, "a"]
|
| 242 |
+
tm.assert_frame_equal(result, expected)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class TestGetitemBooleanMask:
|
| 246 |
+
def test_getitem_bool_mask_categorical_index(self):
|
| 247 |
+
df3 = DataFrame(
|
| 248 |
+
{
|
| 249 |
+
"A": np.arange(6, dtype="int64"),
|
| 250 |
+
},
|
| 251 |
+
index=CategoricalIndex(
|
| 252 |
+
[1, 1, 2, 1, 3, 2],
|
| 253 |
+
dtype=CategoricalDtype([3, 2, 1], ordered=True),
|
| 254 |
+
name="B",
|
| 255 |
+
),
|
| 256 |
+
)
|
| 257 |
+
df4 = DataFrame(
|
| 258 |
+
{
|
| 259 |
+
"A": np.arange(6, dtype="int64"),
|
| 260 |
+
},
|
| 261 |
+
index=CategoricalIndex(
|
| 262 |
+
[1, 1, 2, 1, 3, 2],
|
| 263 |
+
dtype=CategoricalDtype([3, 2, 1], ordered=False),
|
| 264 |
+
name="B",
|
| 265 |
+
),
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
result = df3[df3.index == "a"]
|
| 269 |
+
expected = df3.iloc[[]]
|
| 270 |
+
tm.assert_frame_equal(result, expected)
|
| 271 |
+
|
| 272 |
+
result = df4[df4.index == "a"]
|
| 273 |
+
expected = df4.iloc[[]]
|
| 274 |
+
tm.assert_frame_equal(result, expected)
|
| 275 |
+
|
| 276 |
+
result = df3[df3.index == 1]
|
| 277 |
+
expected = df3.iloc[[0, 1, 3]]
|
| 278 |
+
tm.assert_frame_equal(result, expected)
|
| 279 |
+
|
| 280 |
+
result = df4[df4.index == 1]
|
| 281 |
+
expected = df4.iloc[[0, 1, 3]]
|
| 282 |
+
tm.assert_frame_equal(result, expected)
|
| 283 |
+
|
| 284 |
+
# since we have an ordered categorical
|
| 285 |
+
|
| 286 |
+
# CategoricalIndex([1, 1, 2, 1, 3, 2],
|
| 287 |
+
# categories=[3, 2, 1],
|
| 288 |
+
# ordered=True,
|
| 289 |
+
# name='B')
|
| 290 |
+
result = df3[df3.index < 2]
|
| 291 |
+
expected = df3.iloc[[4]]
|
| 292 |
+
tm.assert_frame_equal(result, expected)
|
| 293 |
+
|
| 294 |
+
result = df3[df3.index > 1]
|
| 295 |
+
expected = df3.iloc[[]]
|
| 296 |
+
tm.assert_frame_equal(result, expected)
|
| 297 |
+
|
| 298 |
+
# unordered
|
| 299 |
+
# cannot be compared
|
| 300 |
+
|
| 301 |
+
# CategoricalIndex([1, 1, 2, 1, 3, 2],
|
| 302 |
+
# categories=[3, 2, 1],
|
| 303 |
+
# ordered=False,
|
| 304 |
+
# name='B')
|
| 305 |
+
msg = "Unordered Categoricals can only compare equality or not"
|
| 306 |
+
with pytest.raises(TypeError, match=msg):
|
| 307 |
+
df4[df4.index < 2]
|
| 308 |
+
with pytest.raises(TypeError, match=msg):
|
| 309 |
+
df4[df4.index > 1]
|
| 310 |
+
|
| 311 |
+
@pytest.mark.parametrize(
|
| 312 |
+
"data1,data2,expected_data",
|
| 313 |
+
(
|
| 314 |
+
(
|
| 315 |
+
[[1, 2], [3, 4]],
|
| 316 |
+
[[0.5, 6], [7, 8]],
|
| 317 |
+
[[np.nan, 3.0], [np.nan, 4.0], [np.nan, 7.0], [6.0, 8.0]],
|
| 318 |
+
),
|
| 319 |
+
(
|
| 320 |
+
[[1, 2], [3, 4]],
|
| 321 |
+
[[5, 6], [7, 8]],
|
| 322 |
+
[[np.nan, 3.0], [np.nan, 4.0], [5, 7], [6, 8]],
|
| 323 |
+
),
|
| 324 |
+
),
|
| 325 |
+
)
|
| 326 |
+
def test_getitem_bool_mask_duplicate_columns_mixed_dtypes(
|
| 327 |
+
self,
|
| 328 |
+
data1,
|
| 329 |
+
data2,
|
| 330 |
+
expected_data,
|
| 331 |
+
):
|
| 332 |
+
# GH#31954
|
| 333 |
+
|
| 334 |
+
df1 = DataFrame(np.array(data1))
|
| 335 |
+
df2 = DataFrame(np.array(data2))
|
| 336 |
+
df = concat([df1, df2], axis=1)
|
| 337 |
+
|
| 338 |
+
result = df[df > 2]
|
| 339 |
+
|
| 340 |
+
exdict = {i: np.array(col) for i, col in enumerate(expected_data)}
|
| 341 |
+
expected = DataFrame(exdict).rename(columns={2: 0, 3: 1})
|
| 342 |
+
tm.assert_frame_equal(result, expected)
|
| 343 |
+
|
| 344 |
+
@pytest.fixture
|
| 345 |
+
def df_dup_cols(self):
|
| 346 |
+
dups = ["A", "A", "C", "D"]
|
| 347 |
+
df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64")
|
| 348 |
+
return df
|
| 349 |
+
|
| 350 |
+
def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self, df_dup_cols):
|
| 351 |
+
# `df.A > 6` is a DataFrame with a different shape from df
|
| 352 |
+
|
| 353 |
+
# boolean with the duplicate raises
|
| 354 |
+
df = df_dup_cols
|
| 355 |
+
msg = "cannot reindex on an axis with duplicate labels"
|
| 356 |
+
with pytest.raises(ValueError, match=msg):
|
| 357 |
+
df[df.A > 6]
|
| 358 |
+
|
| 359 |
+
def test_getitem_boolean_series_with_duplicate_columns(self, df_dup_cols):
|
| 360 |
+
# boolean indexing
|
| 361 |
+
# GH#4879
|
| 362 |
+
df = DataFrame(
|
| 363 |
+
np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64"
|
| 364 |
+
)
|
| 365 |
+
expected = df[df.C > 6]
|
| 366 |
+
expected.columns = df_dup_cols.columns
|
| 367 |
+
|
| 368 |
+
df = df_dup_cols
|
| 369 |
+
result = df[df.C > 6]
|
| 370 |
+
|
| 371 |
+
tm.assert_frame_equal(result, expected)
|
| 372 |
+
|
| 373 |
+
def test_getitem_boolean_frame_with_duplicate_columns(self, df_dup_cols):
|
| 374 |
+
# where
|
| 375 |
+
df = DataFrame(
|
| 376 |
+
np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64"
|
| 377 |
+
)
|
| 378 |
+
# `df > 6` is a DataFrame with the same shape+alignment as df
|
| 379 |
+
expected = df[df > 6]
|
| 380 |
+
expected.columns = df_dup_cols.columns
|
| 381 |
+
|
| 382 |
+
df = df_dup_cols
|
| 383 |
+
result = df[df > 6]
|
| 384 |
+
|
| 385 |
+
tm.assert_frame_equal(result, expected)
|
| 386 |
+
|
| 387 |
+
def test_getitem_empty_frame_with_boolean(self):
|
| 388 |
+
# Test for issue GH#11859
|
| 389 |
+
|
| 390 |
+
df = DataFrame()
|
| 391 |
+
df2 = df[df > 0]
|
| 392 |
+
tm.assert_frame_equal(df, df2)
|
| 393 |
+
|
| 394 |
+
def test_getitem_returns_view_when_column_is_unique_in_df(
|
| 395 |
+
self, using_copy_on_write, warn_copy_on_write
|
| 396 |
+
):
|
| 397 |
+
# GH#45316
|
| 398 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"])
|
| 399 |
+
df_orig = df.copy()
|
| 400 |
+
view = df["b"]
|
| 401 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 402 |
+
view.loc[:] = 100
|
| 403 |
+
if using_copy_on_write:
|
| 404 |
+
expected = df_orig
|
| 405 |
+
else:
|
| 406 |
+
expected = DataFrame([[1, 2, 100], [4, 5, 100]], columns=["a", "a", "b"])
|
| 407 |
+
tm.assert_frame_equal(df, expected)
|
| 408 |
+
|
| 409 |
+
def test_getitem_frozenset_unique_in_column(self):
|
| 410 |
+
# GH#41062
|
| 411 |
+
df = DataFrame([[1, 2, 3, 4]], columns=[frozenset(["KEY"]), "B", "C", "C"])
|
| 412 |
+
result = df[frozenset(["KEY"])]
|
| 413 |
+
expected = Series([1], name=frozenset(["KEY"]))
|
| 414 |
+
tm.assert_series_equal(result, expected)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class TestGetitemSlice:
|
| 418 |
+
def test_getitem_slice_float64(self, frame_or_series):
|
| 419 |
+
values = np.arange(10.0, 50.0, 2)
|
| 420 |
+
index = Index(values)
|
| 421 |
+
|
| 422 |
+
start, end = values[[5, 15]]
|
| 423 |
+
|
| 424 |
+
data = np.random.default_rng(2).standard_normal((20, 3))
|
| 425 |
+
if frame_or_series is not DataFrame:
|
| 426 |
+
data = data[:, 0]
|
| 427 |
+
|
| 428 |
+
obj = frame_or_series(data, index=index)
|
| 429 |
+
|
| 430 |
+
result = obj[start:end]
|
| 431 |
+
expected = obj.iloc[5:16]
|
| 432 |
+
tm.assert_equal(result, expected)
|
| 433 |
+
|
| 434 |
+
result = obj.loc[start:end]
|
| 435 |
+
tm.assert_equal(result, expected)
|
| 436 |
+
|
| 437 |
+
def test_getitem_datetime_slice(self):
|
| 438 |
+
# GH#43223
|
| 439 |
+
df = DataFrame(
|
| 440 |
+
{"a": 0},
|
| 441 |
+
index=DatetimeIndex(
|
| 442 |
+
[
|
| 443 |
+
"11.01.2011 22:00",
|
| 444 |
+
"11.01.2011 23:00",
|
| 445 |
+
"12.01.2011 00:00",
|
| 446 |
+
"2011-01-13 00:00",
|
| 447 |
+
]
|
| 448 |
+
),
|
| 449 |
+
)
|
| 450 |
+
with pytest.raises(
|
| 451 |
+
KeyError, match="Value based partial slicing on non-monotonic"
|
| 452 |
+
):
|
| 453 |
+
df["2011-01-01":"2011-11-01"]
|
| 454 |
+
|
| 455 |
+
def test_getitem_slice_same_dim_only_one_axis(self):
|
| 456 |
+
# GH#54622
|
| 457 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 8)))
|
| 458 |
+
result = df.iloc[(slice(None, None, 2),)]
|
| 459 |
+
assert result.shape == (5, 8)
|
| 460 |
+
expected = df.iloc[slice(None, None, 2), slice(None)]
|
| 461 |
+
tm.assert_frame_equal(result, expected)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
class TestGetitemDeprecatedIndexers:
|
| 465 |
+
@pytest.mark.parametrize("key", [{"a", "b"}, {"a": "a"}])
|
| 466 |
+
def test_getitem_dict_and_set_deprecated(self, key):
|
| 467 |
+
# GH#42825 enforced in 2.0
|
| 468 |
+
df = DataFrame(
|
| 469 |
+
[[1, 2], [3, 4]], columns=MultiIndex.from_tuples([("a", 1), ("b", 2)])
|
| 470 |
+
)
|
| 471 |
+
with pytest.raises(TypeError, match="as an indexer is not supported"):
|
| 472 |
+
df[key]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_indexing.py
ADDED
|
@@ -0,0 +1,2033 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import namedtuple
|
| 2 |
+
from datetime import (
|
| 3 |
+
datetime,
|
| 4 |
+
timedelta,
|
| 5 |
+
)
|
| 6 |
+
from decimal import Decimal
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from pandas._config import using_string_dtype
|
| 13 |
+
|
| 14 |
+
from pandas._libs import iNaT
|
| 15 |
+
from pandas.errors import (
|
| 16 |
+
InvalidIndexError,
|
| 17 |
+
PerformanceWarning,
|
| 18 |
+
SettingWithCopyError,
|
| 19 |
+
)
|
| 20 |
+
import pandas.util._test_decorators as td
|
| 21 |
+
|
| 22 |
+
from pandas.core.dtypes.common import is_integer
|
| 23 |
+
|
| 24 |
+
import pandas as pd
|
| 25 |
+
from pandas import (
|
| 26 |
+
Categorical,
|
| 27 |
+
DataFrame,
|
| 28 |
+
DatetimeIndex,
|
| 29 |
+
Index,
|
| 30 |
+
MultiIndex,
|
| 31 |
+
Series,
|
| 32 |
+
Timestamp,
|
| 33 |
+
date_range,
|
| 34 |
+
isna,
|
| 35 |
+
notna,
|
| 36 |
+
to_datetime,
|
| 37 |
+
)
|
| 38 |
+
import pandas._testing as tm
|
| 39 |
+
|
| 40 |
+
# We pass through a TypeError raised by numpy
|
| 41 |
+
_slice_msg = "slice indices must be integers or None or have an __index__ method"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class TestDataFrameIndexing:
|
| 45 |
+
def test_getitem(self, float_frame):
|
| 46 |
+
# Slicing
|
| 47 |
+
sl = float_frame[:20]
|
| 48 |
+
assert len(sl.index) == 20
|
| 49 |
+
|
| 50 |
+
# Column access
|
| 51 |
+
for _, series in sl.items():
|
| 52 |
+
assert len(series.index) == 20
|
| 53 |
+
tm.assert_index_equal(series.index, sl.index)
|
| 54 |
+
|
| 55 |
+
for key, _ in float_frame._series.items():
|
| 56 |
+
assert float_frame[key] is not None
|
| 57 |
+
|
| 58 |
+
assert "random" not in float_frame
|
| 59 |
+
with pytest.raises(KeyError, match="random"):
|
| 60 |
+
float_frame["random"]
|
| 61 |
+
|
| 62 |
+
def test_getitem_numeric_should_not_fallback_to_positional(self, any_numeric_dtype):
|
| 63 |
+
# GH51053
|
| 64 |
+
dtype = any_numeric_dtype
|
| 65 |
+
idx = Index([1, 0, 1], dtype=dtype)
|
| 66 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=idx)
|
| 67 |
+
result = df[1]
|
| 68 |
+
expected = DataFrame([[1, 3], [4, 6]], columns=Index([1, 1], dtype=dtype))
|
| 69 |
+
tm.assert_frame_equal(result, expected, check_exact=True)
|
| 70 |
+
|
| 71 |
+
def test_getitem2(self, float_frame):
|
| 72 |
+
df = float_frame.copy()
|
| 73 |
+
df["$10"] = np.random.default_rng(2).standard_normal(len(df))
|
| 74 |
+
|
| 75 |
+
ad = np.random.default_rng(2).standard_normal(len(df))
|
| 76 |
+
df["@awesome_domain"] = ad
|
| 77 |
+
|
| 78 |
+
with pytest.raises(KeyError, match=re.escape("'df[\"$10\"]'")):
|
| 79 |
+
df.__getitem__('df["$10"]')
|
| 80 |
+
|
| 81 |
+
res = df["@awesome_domain"]
|
| 82 |
+
tm.assert_numpy_array_equal(ad, res.values)
|
| 83 |
+
|
| 84 |
+
def test_setitem_numeric_should_not_fallback_to_positional(self, any_numeric_dtype):
|
| 85 |
+
# GH51053
|
| 86 |
+
dtype = any_numeric_dtype
|
| 87 |
+
idx = Index([1, 0, 1], dtype=dtype)
|
| 88 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=idx)
|
| 89 |
+
df[1] = 10
|
| 90 |
+
expected = DataFrame([[10, 2, 10], [10, 5, 10]], columns=idx)
|
| 91 |
+
tm.assert_frame_equal(df, expected, check_exact=True)
|
| 92 |
+
|
| 93 |
+
def test_setitem_list(self, float_frame):
|
| 94 |
+
float_frame["E"] = "foo"
|
| 95 |
+
data = float_frame[["A", "B"]]
|
| 96 |
+
float_frame[["B", "A"]] = data
|
| 97 |
+
|
| 98 |
+
tm.assert_series_equal(float_frame["B"], data["A"], check_names=False)
|
| 99 |
+
tm.assert_series_equal(float_frame["A"], data["B"], check_names=False)
|
| 100 |
+
|
| 101 |
+
msg = "Columns must be same length as key"
|
| 102 |
+
with pytest.raises(ValueError, match=msg):
|
| 103 |
+
data[["A"]] = float_frame[["A", "B"]]
|
| 104 |
+
newcolumndata = range(len(data.index) - 1)
|
| 105 |
+
msg = (
|
| 106 |
+
rf"Length of values \({len(newcolumndata)}\) "
|
| 107 |
+
rf"does not match length of index \({len(data)}\)"
|
| 108 |
+
)
|
| 109 |
+
with pytest.raises(ValueError, match=msg):
|
| 110 |
+
data["A"] = newcolumndata
|
| 111 |
+
|
| 112 |
+
def test_setitem_list2(self):
|
| 113 |
+
df = DataFrame(0, index=range(3), columns=["tt1", "tt2"], dtype=int)
|
| 114 |
+
df.loc[1, ["tt1", "tt2"]] = [1, 2]
|
| 115 |
+
|
| 116 |
+
result = df.loc[df.index[1], ["tt1", "tt2"]]
|
| 117 |
+
expected = Series([1, 2], df.columns, dtype=int, name=1)
|
| 118 |
+
tm.assert_series_equal(result, expected)
|
| 119 |
+
|
| 120 |
+
df["tt1"] = df["tt2"] = "0"
|
| 121 |
+
df.loc[df.index[1], ["tt1", "tt2"]] = ["1", "2"]
|
| 122 |
+
result = df.loc[df.index[1], ["tt1", "tt2"]]
|
| 123 |
+
expected = Series(["1", "2"], df.columns, name=1)
|
| 124 |
+
tm.assert_series_equal(result, expected)
|
| 125 |
+
|
| 126 |
+
def test_getitem_boolean(self, mixed_float_frame, mixed_int_frame, datetime_frame):
|
| 127 |
+
# boolean indexing
|
| 128 |
+
d = datetime_frame.index[10]
|
| 129 |
+
indexer = datetime_frame.index > d
|
| 130 |
+
indexer_obj = indexer.astype(object)
|
| 131 |
+
|
| 132 |
+
subindex = datetime_frame.index[indexer]
|
| 133 |
+
subframe = datetime_frame[indexer]
|
| 134 |
+
|
| 135 |
+
tm.assert_index_equal(subindex, subframe.index)
|
| 136 |
+
with pytest.raises(ValueError, match="Item wrong length"):
|
| 137 |
+
datetime_frame[indexer[:-1]]
|
| 138 |
+
|
| 139 |
+
subframe_obj = datetime_frame[indexer_obj]
|
| 140 |
+
tm.assert_frame_equal(subframe_obj, subframe)
|
| 141 |
+
|
| 142 |
+
with pytest.raises(ValueError, match="Boolean array expected"):
|
| 143 |
+
datetime_frame[datetime_frame]
|
| 144 |
+
|
| 145 |
+
# test that Series work
|
| 146 |
+
indexer_obj = Series(indexer_obj, datetime_frame.index)
|
| 147 |
+
|
| 148 |
+
subframe_obj = datetime_frame[indexer_obj]
|
| 149 |
+
tm.assert_frame_equal(subframe_obj, subframe)
|
| 150 |
+
|
| 151 |
+
# test that Series indexers reindex
|
| 152 |
+
# we are producing a warning that since the passed boolean
|
| 153 |
+
# key is not the same as the given index, we will reindex
|
| 154 |
+
# not sure this is really necessary
|
| 155 |
+
with tm.assert_produces_warning(UserWarning):
|
| 156 |
+
indexer_obj = indexer_obj.reindex(datetime_frame.index[::-1])
|
| 157 |
+
subframe_obj = datetime_frame[indexer_obj]
|
| 158 |
+
tm.assert_frame_equal(subframe_obj, subframe)
|
| 159 |
+
|
| 160 |
+
# test df[df > 0]
|
| 161 |
+
for df in [
|
| 162 |
+
datetime_frame,
|
| 163 |
+
mixed_float_frame,
|
| 164 |
+
mixed_int_frame,
|
| 165 |
+
]:
|
| 166 |
+
data = df._get_numeric_data()
|
| 167 |
+
bif = df[df > 0]
|
| 168 |
+
bifw = DataFrame(
|
| 169 |
+
{c: np.where(data[c] > 0, data[c], np.nan) for c in data.columns},
|
| 170 |
+
index=data.index,
|
| 171 |
+
columns=data.columns,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
# add back other columns to compare
|
| 175 |
+
for c in df.columns:
|
| 176 |
+
if c not in bifw:
|
| 177 |
+
bifw[c] = df[c]
|
| 178 |
+
bifw = bifw.reindex(columns=df.columns)
|
| 179 |
+
|
| 180 |
+
tm.assert_frame_equal(bif, bifw, check_dtype=False)
|
| 181 |
+
for c in df.columns:
|
| 182 |
+
if bif[c].dtype != bifw[c].dtype:
|
| 183 |
+
assert bif[c].dtype == df[c].dtype
|
| 184 |
+
|
| 185 |
+
def test_getitem_boolean_casting(self, datetime_frame):
|
| 186 |
+
# don't upcast if we don't need to
|
| 187 |
+
df = datetime_frame.copy()
|
| 188 |
+
df["E"] = 1
|
| 189 |
+
df["E"] = df["E"].astype("int32")
|
| 190 |
+
df["E1"] = df["E"].copy()
|
| 191 |
+
df["F"] = 1
|
| 192 |
+
df["F"] = df["F"].astype("int64")
|
| 193 |
+
df["F1"] = df["F"].copy()
|
| 194 |
+
|
| 195 |
+
casted = df[df > 0]
|
| 196 |
+
result = casted.dtypes
|
| 197 |
+
expected = Series(
|
| 198 |
+
[np.dtype("float64")] * 4
|
| 199 |
+
+ [np.dtype("int32")] * 2
|
| 200 |
+
+ [np.dtype("int64")] * 2,
|
| 201 |
+
index=["A", "B", "C", "D", "E", "E1", "F", "F1"],
|
| 202 |
+
)
|
| 203 |
+
tm.assert_series_equal(result, expected)
|
| 204 |
+
|
| 205 |
+
# int block splitting
|
| 206 |
+
df.loc[df.index[1:3], ["E1", "F1"]] = 0
|
| 207 |
+
casted = df[df > 0]
|
| 208 |
+
result = casted.dtypes
|
| 209 |
+
expected = Series(
|
| 210 |
+
[np.dtype("float64")] * 4
|
| 211 |
+
+ [np.dtype("int32")]
|
| 212 |
+
+ [np.dtype("float64")]
|
| 213 |
+
+ [np.dtype("int64")]
|
| 214 |
+
+ [np.dtype("float64")],
|
| 215 |
+
index=["A", "B", "C", "D", "E", "E1", "F", "F1"],
|
| 216 |
+
)
|
| 217 |
+
tm.assert_series_equal(result, expected)
|
| 218 |
+
|
| 219 |
+
@pytest.mark.parametrize(
|
| 220 |
+
"lst", [[True, False, True], [True, True, True], [False, False, False]]
|
| 221 |
+
)
|
| 222 |
+
def test_getitem_boolean_list(self, lst):
|
| 223 |
+
df = DataFrame(np.arange(12).reshape(3, 4))
|
| 224 |
+
result = df[lst]
|
| 225 |
+
expected = df.loc[df.index[lst]]
|
| 226 |
+
tm.assert_frame_equal(result, expected)
|
| 227 |
+
|
| 228 |
+
def test_getitem_boolean_iadd(self):
|
| 229 |
+
arr = np.random.default_rng(2).standard_normal((5, 5))
|
| 230 |
+
|
| 231 |
+
df = DataFrame(arr.copy(), columns=["A", "B", "C", "D", "E"])
|
| 232 |
+
|
| 233 |
+
df[df < 0] += 1
|
| 234 |
+
arr[arr < 0] += 1
|
| 235 |
+
|
| 236 |
+
tm.assert_almost_equal(df.values, arr)
|
| 237 |
+
|
| 238 |
+
def test_boolean_index_empty_corner(self):
|
| 239 |
+
# #2096
|
| 240 |
+
blah = DataFrame(np.empty([0, 1]), columns=["A"], index=DatetimeIndex([]))
|
| 241 |
+
|
| 242 |
+
# both of these should succeed trivially
|
| 243 |
+
k = np.array([], bool)
|
| 244 |
+
|
| 245 |
+
blah[k]
|
| 246 |
+
blah[k] = 0
|
| 247 |
+
|
| 248 |
+
def test_getitem_ix_mixed_integer(self):
|
| 249 |
+
df = DataFrame(
|
| 250 |
+
np.random.default_rng(2).standard_normal((4, 3)),
|
| 251 |
+
index=[1, 10, "C", "E"],
|
| 252 |
+
columns=[1, 2, 3],
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
result = df.iloc[:-1]
|
| 256 |
+
expected = df.loc[df.index[:-1]]
|
| 257 |
+
tm.assert_frame_equal(result, expected)
|
| 258 |
+
|
| 259 |
+
result = df.loc[[1, 10]]
|
| 260 |
+
expected = df.loc[Index([1, 10])]
|
| 261 |
+
tm.assert_frame_equal(result, expected)
|
| 262 |
+
|
| 263 |
+
def test_getitem_ix_mixed_integer2(self):
|
| 264 |
+
# 11320
|
| 265 |
+
df = DataFrame(
|
| 266 |
+
{
|
| 267 |
+
"rna": (1.5, 2.2, 3.2, 4.5),
|
| 268 |
+
-1000: [11, 21, 36, 40],
|
| 269 |
+
0: [10, 22, 43, 34],
|
| 270 |
+
1000: [0, 10, 20, 30],
|
| 271 |
+
},
|
| 272 |
+
columns=["rna", -1000, 0, 1000],
|
| 273 |
+
)
|
| 274 |
+
result = df[[1000]]
|
| 275 |
+
expected = df.iloc[:, [3]]
|
| 276 |
+
tm.assert_frame_equal(result, expected)
|
| 277 |
+
result = df[[-1000]]
|
| 278 |
+
expected = df.iloc[:, [1]]
|
| 279 |
+
tm.assert_frame_equal(result, expected)
|
| 280 |
+
|
| 281 |
+
def test_getattr(self, float_frame):
|
| 282 |
+
tm.assert_series_equal(float_frame.A, float_frame["A"])
|
| 283 |
+
msg = "'DataFrame' object has no attribute 'NONEXISTENT_NAME'"
|
| 284 |
+
with pytest.raises(AttributeError, match=msg):
|
| 285 |
+
float_frame.NONEXISTENT_NAME
|
| 286 |
+
|
| 287 |
+
def test_setattr_column(self):
|
| 288 |
+
df = DataFrame({"foobar": 1}, index=range(10))
|
| 289 |
+
|
| 290 |
+
df.foobar = 5
|
| 291 |
+
assert (df.foobar == 5).all()
|
| 292 |
+
|
| 293 |
+
def test_setitem(
|
| 294 |
+
self, float_frame, using_copy_on_write, warn_copy_on_write, using_infer_string
|
| 295 |
+
):
|
| 296 |
+
# not sure what else to do here
|
| 297 |
+
series = float_frame["A"][::2]
|
| 298 |
+
float_frame["col5"] = series
|
| 299 |
+
assert "col5" in float_frame
|
| 300 |
+
|
| 301 |
+
assert len(series) == 15
|
| 302 |
+
assert len(float_frame) == 30
|
| 303 |
+
|
| 304 |
+
exp = np.ravel(np.column_stack((series.values, [np.nan] * 15)))
|
| 305 |
+
exp = Series(exp, index=float_frame.index, name="col5")
|
| 306 |
+
tm.assert_series_equal(float_frame["col5"], exp)
|
| 307 |
+
|
| 308 |
+
series = float_frame["A"]
|
| 309 |
+
float_frame["col6"] = series
|
| 310 |
+
tm.assert_series_equal(series, float_frame["col6"], check_names=False)
|
| 311 |
+
|
| 312 |
+
# set ndarray
|
| 313 |
+
arr = np.random.default_rng(2).standard_normal(len(float_frame))
|
| 314 |
+
float_frame["col9"] = arr
|
| 315 |
+
assert (float_frame["col9"] == arr).all()
|
| 316 |
+
|
| 317 |
+
float_frame["col7"] = 5
|
| 318 |
+
assert (float_frame["col7"] == 5).all()
|
| 319 |
+
|
| 320 |
+
float_frame["col0"] = 3.14
|
| 321 |
+
assert (float_frame["col0"] == 3.14).all()
|
| 322 |
+
|
| 323 |
+
float_frame["col8"] = "foo"
|
| 324 |
+
assert (float_frame["col8"] == "foo").all()
|
| 325 |
+
|
| 326 |
+
# this is partially a view (e.g. some blocks are view)
|
| 327 |
+
# so raise/warn
|
| 328 |
+
smaller = float_frame[:2]
|
| 329 |
+
|
| 330 |
+
msg = r"\nA value is trying to be set on a copy of a slice from a DataFrame"
|
| 331 |
+
if using_copy_on_write or warn_copy_on_write:
|
| 332 |
+
# With CoW, adding a new column doesn't raise a warning
|
| 333 |
+
smaller["col10"] = ["1", "2"]
|
| 334 |
+
else:
|
| 335 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 336 |
+
smaller["col10"] = ["1", "2"]
|
| 337 |
+
|
| 338 |
+
if using_infer_string:
|
| 339 |
+
assert smaller["col10"].dtype == "str"
|
| 340 |
+
else:
|
| 341 |
+
assert smaller["col10"].dtype == np.object_
|
| 342 |
+
assert (smaller["col10"] == ["1", "2"]).all()
|
| 343 |
+
|
| 344 |
+
def test_setitem2(self):
|
| 345 |
+
# dtype changing GH4204
|
| 346 |
+
df = DataFrame([[0, 0]])
|
| 347 |
+
df.iloc[0] = np.nan
|
| 348 |
+
expected = DataFrame([[np.nan, np.nan]])
|
| 349 |
+
tm.assert_frame_equal(df, expected)
|
| 350 |
+
|
| 351 |
+
df = DataFrame([[0, 0]])
|
| 352 |
+
df.loc[0] = np.nan
|
| 353 |
+
tm.assert_frame_equal(df, expected)
|
| 354 |
+
|
| 355 |
+
def test_setitem_boolean(self, float_frame):
|
| 356 |
+
df = float_frame.copy()
|
| 357 |
+
values = float_frame.values.copy()
|
| 358 |
+
|
| 359 |
+
df[df["A"] > 0] = 4
|
| 360 |
+
values[values[:, 0] > 0] = 4
|
| 361 |
+
tm.assert_almost_equal(df.values, values)
|
| 362 |
+
|
| 363 |
+
# test that column reindexing works
|
| 364 |
+
series = df["A"] == 4
|
| 365 |
+
series = series.reindex(df.index[::-1])
|
| 366 |
+
df[series] = 1
|
| 367 |
+
values[values[:, 0] == 4] = 1
|
| 368 |
+
tm.assert_almost_equal(df.values, values)
|
| 369 |
+
|
| 370 |
+
df[df > 0] = 5
|
| 371 |
+
values[values > 0] = 5
|
| 372 |
+
tm.assert_almost_equal(df.values, values)
|
| 373 |
+
|
| 374 |
+
df[df == 5] = 0
|
| 375 |
+
values[values == 5] = 0
|
| 376 |
+
tm.assert_almost_equal(df.values, values)
|
| 377 |
+
|
| 378 |
+
# a df that needs alignment first
|
| 379 |
+
df[df[:-1] < 0] = 2
|
| 380 |
+
np.putmask(values[:-1], values[:-1] < 0, 2)
|
| 381 |
+
tm.assert_almost_equal(df.values, values)
|
| 382 |
+
|
| 383 |
+
# indexed with same shape but rows-reversed df
|
| 384 |
+
df[df[::-1] == 2] = 3
|
| 385 |
+
values[values == 2] = 3
|
| 386 |
+
tm.assert_almost_equal(df.values, values)
|
| 387 |
+
|
| 388 |
+
msg = "Must pass DataFrame or 2-d ndarray with boolean values only"
|
| 389 |
+
with pytest.raises(TypeError, match=msg):
|
| 390 |
+
df[df * 0] = 2
|
| 391 |
+
|
| 392 |
+
# index with DataFrame
|
| 393 |
+
df_orig = df.copy()
|
| 394 |
+
mask = df > np.abs(df)
|
| 395 |
+
df[df > np.abs(df)] = np.nan
|
| 396 |
+
values = df_orig.values.copy()
|
| 397 |
+
values[mask.values] = np.nan
|
| 398 |
+
expected = DataFrame(values, index=df_orig.index, columns=df_orig.columns)
|
| 399 |
+
tm.assert_frame_equal(df, expected)
|
| 400 |
+
|
| 401 |
+
# set from DataFrame
|
| 402 |
+
df[df > np.abs(df)] = df * 2
|
| 403 |
+
np.putmask(values, mask.values, df.values * 2)
|
| 404 |
+
expected = DataFrame(values, index=df_orig.index, columns=df_orig.columns)
|
| 405 |
+
tm.assert_frame_equal(df, expected)
|
| 406 |
+
|
| 407 |
+
def test_setitem_cast(self, float_frame):
|
| 408 |
+
float_frame["D"] = float_frame["D"].astype("i8")
|
| 409 |
+
assert float_frame["D"].dtype == np.int64
|
| 410 |
+
|
| 411 |
+
# #669, should not cast?
|
| 412 |
+
# this is now set to int64, which means a replacement of the column to
|
| 413 |
+
# the value dtype (and nothing to do with the existing dtype)
|
| 414 |
+
float_frame["B"] = 0
|
| 415 |
+
assert float_frame["B"].dtype == np.int64
|
| 416 |
+
|
| 417 |
+
# cast if pass array of course
|
| 418 |
+
float_frame["B"] = np.arange(len(float_frame))
|
| 419 |
+
assert issubclass(float_frame["B"].dtype.type, np.integer)
|
| 420 |
+
|
| 421 |
+
float_frame["foo"] = "bar"
|
| 422 |
+
float_frame["foo"] = 0
|
| 423 |
+
assert float_frame["foo"].dtype == np.int64
|
| 424 |
+
|
| 425 |
+
float_frame["foo"] = "bar"
|
| 426 |
+
float_frame["foo"] = 2.5
|
| 427 |
+
assert float_frame["foo"].dtype == np.float64
|
| 428 |
+
|
| 429 |
+
float_frame["something"] = 0
|
| 430 |
+
assert float_frame["something"].dtype == np.int64
|
| 431 |
+
float_frame["something"] = 2
|
| 432 |
+
assert float_frame["something"].dtype == np.int64
|
| 433 |
+
float_frame["something"] = 2.5
|
| 434 |
+
assert float_frame["something"].dtype == np.float64
|
| 435 |
+
|
| 436 |
+
def test_setitem_corner(self, float_frame, using_infer_string):
|
| 437 |
+
# corner case
|
| 438 |
+
df = DataFrame({"B": [1.0, 2.0, 3.0], "C": ["a", "b", "c"]}, index=np.arange(3))
|
| 439 |
+
del df["B"]
|
| 440 |
+
df["B"] = [1.0, 2.0, 3.0]
|
| 441 |
+
assert "B" in df
|
| 442 |
+
assert len(df.columns) == 2
|
| 443 |
+
|
| 444 |
+
df["A"] = "beginning"
|
| 445 |
+
df["E"] = "foo"
|
| 446 |
+
df["D"] = "bar"
|
| 447 |
+
df[datetime.now()] = "date"
|
| 448 |
+
df[datetime.now()] = 5.0
|
| 449 |
+
|
| 450 |
+
# what to do when empty frame with index
|
| 451 |
+
dm = DataFrame(index=float_frame.index)
|
| 452 |
+
dm["A"] = "foo"
|
| 453 |
+
dm["B"] = "bar"
|
| 454 |
+
assert len(dm.columns) == 2
|
| 455 |
+
assert dm.values.dtype == np.object_
|
| 456 |
+
|
| 457 |
+
# upcast
|
| 458 |
+
dm["C"] = 1
|
| 459 |
+
assert dm["C"].dtype == np.int64
|
| 460 |
+
|
| 461 |
+
dm["E"] = 1.0
|
| 462 |
+
assert dm["E"].dtype == np.float64
|
| 463 |
+
|
| 464 |
+
# set existing column
|
| 465 |
+
dm["A"] = "bar"
|
| 466 |
+
assert "bar" == dm["A"].iloc[0]
|
| 467 |
+
|
| 468 |
+
dm = DataFrame(index=np.arange(3))
|
| 469 |
+
dm["A"] = 1
|
| 470 |
+
dm["foo"] = "bar"
|
| 471 |
+
del dm["foo"]
|
| 472 |
+
dm["foo"] = "bar"
|
| 473 |
+
if using_infer_string:
|
| 474 |
+
assert dm["foo"].dtype == "str"
|
| 475 |
+
else:
|
| 476 |
+
assert dm["foo"].dtype == np.object_
|
| 477 |
+
|
| 478 |
+
dm["coercible"] = ["1", "2", "3"]
|
| 479 |
+
if using_infer_string:
|
| 480 |
+
assert dm["coercible"].dtype == "str"
|
| 481 |
+
else:
|
| 482 |
+
assert dm["coercible"].dtype == np.object_
|
| 483 |
+
|
| 484 |
+
def test_setitem_corner2(self):
|
| 485 |
+
data = {
|
| 486 |
+
"title": ["foobar", "bar", "foobar"] + ["foobar"] * 17,
|
| 487 |
+
"cruft": np.random.default_rng(2).random(20),
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
df = DataFrame(data)
|
| 491 |
+
ix = df[df["title"] == "bar"].index
|
| 492 |
+
|
| 493 |
+
df.loc[ix, ["title"]] = "foobar"
|
| 494 |
+
df.loc[ix, ["cruft"]] = 0
|
| 495 |
+
|
| 496 |
+
assert df.loc[1, "title"] == "foobar"
|
| 497 |
+
assert df.loc[1, "cruft"] == 0
|
| 498 |
+
|
| 499 |
+
def test_setitem_ambig(self, using_infer_string):
|
| 500 |
+
# Difficulties with mixed-type data
|
| 501 |
+
# Created as float type
|
| 502 |
+
dm = DataFrame(index=range(3), columns=range(3))
|
| 503 |
+
|
| 504 |
+
coercable_series = Series([Decimal(1) for _ in range(3)], index=range(3))
|
| 505 |
+
uncoercable_series = Series(["foo", "bzr", "baz"], index=range(3))
|
| 506 |
+
|
| 507 |
+
dm[0] = np.ones(3)
|
| 508 |
+
assert len(dm.columns) == 3
|
| 509 |
+
|
| 510 |
+
dm[1] = coercable_series
|
| 511 |
+
assert len(dm.columns) == 3
|
| 512 |
+
|
| 513 |
+
dm[2] = uncoercable_series
|
| 514 |
+
assert len(dm.columns) == 3
|
| 515 |
+
if using_infer_string:
|
| 516 |
+
assert dm[2].dtype == "str"
|
| 517 |
+
else:
|
| 518 |
+
assert dm[2].dtype == np.object_
|
| 519 |
+
|
| 520 |
+
def test_setitem_None(self, float_frame):
|
| 521 |
+
# GH #766
|
| 522 |
+
float_frame[None] = float_frame["A"]
|
| 523 |
+
tm.assert_series_equal(
|
| 524 |
+
float_frame.iloc[:, -1], float_frame["A"], check_names=False
|
| 525 |
+
)
|
| 526 |
+
tm.assert_series_equal(
|
| 527 |
+
float_frame.loc[:, None], float_frame["A"], check_names=False
|
| 528 |
+
)
|
| 529 |
+
tm.assert_series_equal(float_frame[None], float_frame["A"], check_names=False)
|
| 530 |
+
|
| 531 |
+
def test_loc_setitem_boolean_mask_allfalse(self):
|
| 532 |
+
# GH 9596
|
| 533 |
+
df = DataFrame(
|
| 534 |
+
{"a": ["1", "2", "3"], "b": ["11", "22", "33"], "c": ["111", "222", "333"]}
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
result = df.copy()
|
| 538 |
+
result.loc[result.b.isna(), "a"] = result.a.copy()
|
| 539 |
+
tm.assert_frame_equal(result, df)
|
| 540 |
+
|
| 541 |
+
def test_getitem_fancy_slice_integers_step(self):
|
| 542 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
|
| 543 |
+
|
| 544 |
+
# this is OK
|
| 545 |
+
df.iloc[:8:2]
|
| 546 |
+
df.iloc[:8:2] = np.nan
|
| 547 |
+
assert isna(df.iloc[:8:2]).values.all()
|
| 548 |
+
|
| 549 |
+
def test_getitem_setitem_integer_slice_keyerrors(self):
|
| 550 |
+
df = DataFrame(
|
| 551 |
+
np.random.default_rng(2).standard_normal((10, 5)), index=range(0, 20, 2)
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
# this is OK
|
| 555 |
+
cp = df.copy()
|
| 556 |
+
cp.iloc[4:10] = 0
|
| 557 |
+
assert (cp.iloc[4:10] == 0).values.all()
|
| 558 |
+
|
| 559 |
+
# so is this
|
| 560 |
+
cp = df.copy()
|
| 561 |
+
cp.iloc[3:11] = 0
|
| 562 |
+
assert (cp.iloc[3:11] == 0).values.all()
|
| 563 |
+
|
| 564 |
+
result = df.iloc[2:6]
|
| 565 |
+
result2 = df.loc[3:11]
|
| 566 |
+
expected = df.reindex([4, 6, 8, 10])
|
| 567 |
+
|
| 568 |
+
tm.assert_frame_equal(result, expected)
|
| 569 |
+
tm.assert_frame_equal(result2, expected)
|
| 570 |
+
|
| 571 |
+
# non-monotonic, raise KeyError
|
| 572 |
+
df2 = df.iloc[list(range(5)) + list(range(5, 10))[::-1]]
|
| 573 |
+
with pytest.raises(KeyError, match=r"^3$"):
|
| 574 |
+
df2.loc[3:11]
|
| 575 |
+
with pytest.raises(KeyError, match=r"^3$"):
|
| 576 |
+
df2.loc[3:11] = 0
|
| 577 |
+
|
| 578 |
+
@td.skip_array_manager_invalid_test # already covered in test_iloc_col_slice_view
|
| 579 |
+
def test_fancy_getitem_slice_mixed(
|
| 580 |
+
self, float_frame, float_string_frame, using_copy_on_write, warn_copy_on_write
|
| 581 |
+
):
|
| 582 |
+
sliced = float_string_frame.iloc[:, -3:]
|
| 583 |
+
assert sliced["D"].dtype == np.float64
|
| 584 |
+
|
| 585 |
+
# get view with single block
|
| 586 |
+
# setting it triggers setting with copy
|
| 587 |
+
original = float_frame.copy()
|
| 588 |
+
sliced = float_frame.iloc[:, -3:]
|
| 589 |
+
|
| 590 |
+
assert np.shares_memory(sliced["C"]._values, float_frame["C"]._values)
|
| 591 |
+
|
| 592 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 593 |
+
sliced.loc[:, "C"] = 4.0
|
| 594 |
+
if not using_copy_on_write:
|
| 595 |
+
assert (float_frame["C"] == 4).all()
|
| 596 |
+
|
| 597 |
+
# with the enforcement of GH#45333 in 2.0, this remains a view
|
| 598 |
+
np.shares_memory(sliced["C"]._values, float_frame["C"]._values)
|
| 599 |
+
else:
|
| 600 |
+
tm.assert_frame_equal(float_frame, original)
|
| 601 |
+
|
| 602 |
+
def test_getitem_setitem_non_ix_labels(self):
|
| 603 |
+
df = DataFrame(range(20), index=date_range("2020-01-01", periods=20))
|
| 604 |
+
|
| 605 |
+
start, end = df.index[[5, 10]]
|
| 606 |
+
|
| 607 |
+
result = df.loc[start:end]
|
| 608 |
+
result2 = df[start:end]
|
| 609 |
+
expected = df[5:11]
|
| 610 |
+
tm.assert_frame_equal(result, expected)
|
| 611 |
+
tm.assert_frame_equal(result2, expected)
|
| 612 |
+
|
| 613 |
+
result = df.copy()
|
| 614 |
+
result.loc[start:end] = 0
|
| 615 |
+
result2 = df.copy()
|
| 616 |
+
result2[start:end] = 0
|
| 617 |
+
expected = df.copy()
|
| 618 |
+
expected[5:11] = 0
|
| 619 |
+
tm.assert_frame_equal(result, expected)
|
| 620 |
+
tm.assert_frame_equal(result2, expected)
|
| 621 |
+
|
| 622 |
+
def test_ix_multi_take(self):
|
| 623 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((3, 2)))
|
| 624 |
+
rs = df.loc[df.index == 0, :]
|
| 625 |
+
xp = df.reindex([0])
|
| 626 |
+
tm.assert_frame_equal(rs, xp)
|
| 627 |
+
|
| 628 |
+
# GH#1321
|
| 629 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((3, 2)))
|
| 630 |
+
rs = df.loc[df.index == 0, df.columns == 1]
|
| 631 |
+
xp = df.reindex(index=[0], columns=[1])
|
| 632 |
+
tm.assert_frame_equal(rs, xp)
|
| 633 |
+
|
| 634 |
+
def test_getitem_fancy_scalar(self, float_frame):
|
| 635 |
+
f = float_frame
|
| 636 |
+
ix = f.loc
|
| 637 |
+
|
| 638 |
+
# individual value
|
| 639 |
+
for col in f.columns:
|
| 640 |
+
ts = f[col]
|
| 641 |
+
for idx in f.index[::5]:
|
| 642 |
+
assert ix[idx, col] == ts[idx]
|
| 643 |
+
|
| 644 |
+
@td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values
|
| 645 |
+
def test_setitem_fancy_scalar(self, float_frame):
|
| 646 |
+
f = float_frame
|
| 647 |
+
expected = float_frame.copy()
|
| 648 |
+
ix = f.loc
|
| 649 |
+
|
| 650 |
+
# individual value
|
| 651 |
+
for j, col in enumerate(f.columns):
|
| 652 |
+
f[col]
|
| 653 |
+
for idx in f.index[::5]:
|
| 654 |
+
i = f.index.get_loc(idx)
|
| 655 |
+
val = np.random.default_rng(2).standard_normal()
|
| 656 |
+
expected.iloc[i, j] = val
|
| 657 |
+
|
| 658 |
+
ix[idx, col] = val
|
| 659 |
+
tm.assert_frame_equal(f, expected)
|
| 660 |
+
|
| 661 |
+
def test_getitem_fancy_boolean(self, float_frame):
|
| 662 |
+
f = float_frame
|
| 663 |
+
ix = f.loc
|
| 664 |
+
|
| 665 |
+
expected = f.reindex(columns=["B", "D"])
|
| 666 |
+
result = ix[:, [False, True, False, True]]
|
| 667 |
+
tm.assert_frame_equal(result, expected)
|
| 668 |
+
|
| 669 |
+
expected = f.reindex(index=f.index[5:10], columns=["B", "D"])
|
| 670 |
+
result = ix[f.index[5:10], [False, True, False, True]]
|
| 671 |
+
tm.assert_frame_equal(result, expected)
|
| 672 |
+
|
| 673 |
+
boolvec = f.index > f.index[7]
|
| 674 |
+
expected = f.reindex(index=f.index[boolvec])
|
| 675 |
+
result = ix[boolvec]
|
| 676 |
+
tm.assert_frame_equal(result, expected)
|
| 677 |
+
result = ix[boolvec, :]
|
| 678 |
+
tm.assert_frame_equal(result, expected)
|
| 679 |
+
|
| 680 |
+
result = ix[boolvec, f.columns[2:]]
|
| 681 |
+
expected = f.reindex(index=f.index[boolvec], columns=["C", "D"])
|
| 682 |
+
tm.assert_frame_equal(result, expected)
|
| 683 |
+
|
| 684 |
+
@td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values
|
| 685 |
+
def test_setitem_fancy_boolean(self, float_frame):
|
| 686 |
+
# from 2d, set with booleans
|
| 687 |
+
frame = float_frame.copy()
|
| 688 |
+
expected = float_frame.copy()
|
| 689 |
+
values = expected.values.copy()
|
| 690 |
+
|
| 691 |
+
mask = frame["A"] > 0
|
| 692 |
+
frame.loc[mask] = 0.0
|
| 693 |
+
values[mask.values] = 0.0
|
| 694 |
+
expected = DataFrame(values, index=expected.index, columns=expected.columns)
|
| 695 |
+
tm.assert_frame_equal(frame, expected)
|
| 696 |
+
|
| 697 |
+
frame = float_frame.copy()
|
| 698 |
+
expected = float_frame.copy()
|
| 699 |
+
values = expected.values.copy()
|
| 700 |
+
frame.loc[mask, ["A", "B"]] = 0.0
|
| 701 |
+
values[mask.values, :2] = 0.0
|
| 702 |
+
expected = DataFrame(values, index=expected.index, columns=expected.columns)
|
| 703 |
+
tm.assert_frame_equal(frame, expected)
|
| 704 |
+
|
| 705 |
+
def test_getitem_fancy_ints(self, float_frame):
|
| 706 |
+
result = float_frame.iloc[[1, 4, 7]]
|
| 707 |
+
expected = float_frame.loc[float_frame.index[[1, 4, 7]]]
|
| 708 |
+
tm.assert_frame_equal(result, expected)
|
| 709 |
+
|
| 710 |
+
result = float_frame.iloc[:, [2, 0, 1]]
|
| 711 |
+
expected = float_frame.loc[:, float_frame.columns[[2, 0, 1]]]
|
| 712 |
+
tm.assert_frame_equal(result, expected)
|
| 713 |
+
|
| 714 |
+
def test_getitem_setitem_boolean_misaligned(self, float_frame):
|
| 715 |
+
# boolean index misaligned labels
|
| 716 |
+
mask = float_frame["A"][::-1] > 1
|
| 717 |
+
|
| 718 |
+
result = float_frame.loc[mask]
|
| 719 |
+
expected = float_frame.loc[mask[::-1]]
|
| 720 |
+
tm.assert_frame_equal(result, expected)
|
| 721 |
+
|
| 722 |
+
cp = float_frame.copy()
|
| 723 |
+
expected = float_frame.copy()
|
| 724 |
+
cp.loc[mask] = 0
|
| 725 |
+
expected.loc[mask] = 0
|
| 726 |
+
tm.assert_frame_equal(cp, expected)
|
| 727 |
+
|
| 728 |
+
def test_getitem_setitem_boolean_multi(self):
|
| 729 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((3, 2)))
|
| 730 |
+
|
| 731 |
+
# get
|
| 732 |
+
k1 = np.array([True, False, True])
|
| 733 |
+
k2 = np.array([False, True])
|
| 734 |
+
result = df.loc[k1, k2]
|
| 735 |
+
expected = df.loc[[0, 2], [1]]
|
| 736 |
+
tm.assert_frame_equal(result, expected)
|
| 737 |
+
|
| 738 |
+
expected = df.copy()
|
| 739 |
+
df.loc[np.array([True, False, True]), np.array([False, True])] = 5
|
| 740 |
+
expected.loc[[0, 2], [1]] = 5
|
| 741 |
+
tm.assert_frame_equal(df, expected)
|
| 742 |
+
|
| 743 |
+
def test_getitem_setitem_float_labels(self, using_array_manager):
|
| 744 |
+
index = Index([1.5, 2, 3, 4, 5])
|
| 745 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)), index=index)
|
| 746 |
+
|
| 747 |
+
result = df.loc[1.5:4]
|
| 748 |
+
expected = df.reindex([1.5, 2, 3, 4])
|
| 749 |
+
tm.assert_frame_equal(result, expected)
|
| 750 |
+
assert len(result) == 4
|
| 751 |
+
|
| 752 |
+
result = df.loc[4:5]
|
| 753 |
+
expected = df.reindex([4, 5]) # reindex with int
|
| 754 |
+
tm.assert_frame_equal(result, expected, check_index_type=False)
|
| 755 |
+
assert len(result) == 2
|
| 756 |
+
|
| 757 |
+
result = df.loc[4:5]
|
| 758 |
+
expected = df.reindex([4.0, 5.0]) # reindex with float
|
| 759 |
+
tm.assert_frame_equal(result, expected)
|
| 760 |
+
assert len(result) == 2
|
| 761 |
+
|
| 762 |
+
# loc_float changes this to work properly
|
| 763 |
+
result = df.loc[1:2]
|
| 764 |
+
expected = df.iloc[0:2]
|
| 765 |
+
tm.assert_frame_equal(result, expected)
|
| 766 |
+
|
| 767 |
+
expected = df.iloc[0:2]
|
| 768 |
+
msg = r"The behavior of obj\[i:j\] with a float-dtype index"
|
| 769 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 770 |
+
result = df[1:2]
|
| 771 |
+
tm.assert_frame_equal(result, expected)
|
| 772 |
+
|
| 773 |
+
# #2727
|
| 774 |
+
index = Index([1.0, 2.5, 3.5, 4.5, 5.0])
|
| 775 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((5, 5)), index=index)
|
| 776 |
+
|
| 777 |
+
# positional slicing only via iloc!
|
| 778 |
+
msg = (
|
| 779 |
+
"cannot do positional indexing on Index with "
|
| 780 |
+
r"these indexers \[1.0\] of type float"
|
| 781 |
+
)
|
| 782 |
+
with pytest.raises(TypeError, match=msg):
|
| 783 |
+
df.iloc[1.0:5]
|
| 784 |
+
|
| 785 |
+
result = df.iloc[4:5]
|
| 786 |
+
expected = df.reindex([5.0])
|
| 787 |
+
tm.assert_frame_equal(result, expected)
|
| 788 |
+
assert len(result) == 1
|
| 789 |
+
|
| 790 |
+
cp = df.copy()
|
| 791 |
+
|
| 792 |
+
with pytest.raises(TypeError, match=_slice_msg):
|
| 793 |
+
cp.iloc[1.0:5] = 0
|
| 794 |
+
|
| 795 |
+
with pytest.raises(TypeError, match=msg):
|
| 796 |
+
result = cp.iloc[1.0:5] == 0
|
| 797 |
+
|
| 798 |
+
assert result.values.all()
|
| 799 |
+
assert (cp.iloc[0:1] == df.iloc[0:1]).values.all()
|
| 800 |
+
|
| 801 |
+
cp = df.copy()
|
| 802 |
+
cp.iloc[4:5] = 0
|
| 803 |
+
assert (cp.iloc[4:5] == 0).values.all()
|
| 804 |
+
assert (cp.iloc[0:4] == df.iloc[0:4]).values.all()
|
| 805 |
+
|
| 806 |
+
# float slicing
|
| 807 |
+
result = df.loc[1.0:5]
|
| 808 |
+
expected = df
|
| 809 |
+
tm.assert_frame_equal(result, expected)
|
| 810 |
+
assert len(result) == 5
|
| 811 |
+
|
| 812 |
+
result = df.loc[1.1:5]
|
| 813 |
+
expected = df.reindex([2.5, 3.5, 4.5, 5.0])
|
| 814 |
+
tm.assert_frame_equal(result, expected)
|
| 815 |
+
assert len(result) == 4
|
| 816 |
+
|
| 817 |
+
result = df.loc[4.51:5]
|
| 818 |
+
expected = df.reindex([5.0])
|
| 819 |
+
tm.assert_frame_equal(result, expected)
|
| 820 |
+
assert len(result) == 1
|
| 821 |
+
|
| 822 |
+
result = df.loc[1.0:5.0]
|
| 823 |
+
expected = df.reindex([1.0, 2.5, 3.5, 4.5, 5.0])
|
| 824 |
+
tm.assert_frame_equal(result, expected)
|
| 825 |
+
assert len(result) == 5
|
| 826 |
+
|
| 827 |
+
cp = df.copy()
|
| 828 |
+
cp.loc[1.0:5.0] = 0
|
| 829 |
+
result = cp.loc[1.0:5.0]
|
| 830 |
+
assert (result == 0).values.all()
|
| 831 |
+
|
| 832 |
+
def test_setitem_single_column_mixed_datetime(self):
|
| 833 |
+
df = DataFrame(
|
| 834 |
+
np.random.default_rng(2).standard_normal((5, 3)),
|
| 835 |
+
index=["a", "b", "c", "d", "e"],
|
| 836 |
+
columns=["foo", "bar", "baz"],
|
| 837 |
+
)
|
| 838 |
+
|
| 839 |
+
df["timestamp"] = Timestamp("20010102")
|
| 840 |
+
|
| 841 |
+
# check our dtypes
|
| 842 |
+
result = df.dtypes
|
| 843 |
+
expected = Series(
|
| 844 |
+
[np.dtype("float64")] * 3 + [np.dtype("datetime64[s]")],
|
| 845 |
+
index=["foo", "bar", "baz", "timestamp"],
|
| 846 |
+
)
|
| 847 |
+
tm.assert_series_equal(result, expected)
|
| 848 |
+
|
| 849 |
+
# GH#16674 iNaT is treated as an integer when given by the user
|
| 850 |
+
with tm.assert_produces_warning(
|
| 851 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 852 |
+
):
|
| 853 |
+
df.loc["b", "timestamp"] = iNaT
|
| 854 |
+
assert not isna(df.loc["b", "timestamp"])
|
| 855 |
+
assert df["timestamp"].dtype == np.object_
|
| 856 |
+
assert df.loc["b", "timestamp"] == iNaT
|
| 857 |
+
|
| 858 |
+
# allow this syntax (as of GH#3216)
|
| 859 |
+
df.loc["c", "timestamp"] = np.nan
|
| 860 |
+
assert isna(df.loc["c", "timestamp"])
|
| 861 |
+
|
| 862 |
+
# allow this syntax
|
| 863 |
+
df.loc["d", :] = np.nan
|
| 864 |
+
assert not isna(df.loc["c", :]).all()
|
| 865 |
+
|
| 866 |
+
def test_setitem_mixed_datetime(self):
|
| 867 |
+
# GH 9336
|
| 868 |
+
expected = DataFrame(
|
| 869 |
+
{
|
| 870 |
+
"a": [0, 0, 0, 0, 13, 14],
|
| 871 |
+
"b": [
|
| 872 |
+
datetime(2012, 1, 1),
|
| 873 |
+
1,
|
| 874 |
+
"x",
|
| 875 |
+
"y",
|
| 876 |
+
datetime(2013, 1, 1),
|
| 877 |
+
datetime(2014, 1, 1),
|
| 878 |
+
],
|
| 879 |
+
}
|
| 880 |
+
)
|
| 881 |
+
df = DataFrame(0, columns=list("ab"), index=range(6))
|
| 882 |
+
df["b"] = pd.NaT
|
| 883 |
+
df.loc[0, "b"] = datetime(2012, 1, 1)
|
| 884 |
+
with tm.assert_produces_warning(
|
| 885 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 886 |
+
):
|
| 887 |
+
df.loc[1, "b"] = 1
|
| 888 |
+
df.loc[[2, 3], "b"] = "x", "y"
|
| 889 |
+
A = np.array(
|
| 890 |
+
[
|
| 891 |
+
[13, np.datetime64("2013-01-01T00:00:00")],
|
| 892 |
+
[14, np.datetime64("2014-01-01T00:00:00")],
|
| 893 |
+
]
|
| 894 |
+
)
|
| 895 |
+
df.loc[[4, 5], ["a", "b"]] = A
|
| 896 |
+
tm.assert_frame_equal(df, expected)
|
| 897 |
+
|
| 898 |
+
def test_setitem_frame_float(self, float_frame):
|
| 899 |
+
piece = float_frame.loc[float_frame.index[:2], ["A", "B"]]
|
| 900 |
+
float_frame.loc[float_frame.index[-2] :, ["A", "B"]] = piece.values
|
| 901 |
+
result = float_frame.loc[float_frame.index[-2:], ["A", "B"]].values
|
| 902 |
+
expected = piece.values
|
| 903 |
+
tm.assert_almost_equal(result, expected)
|
| 904 |
+
|
| 905 |
+
# dtype inference
|
| 906 |
+
@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)")
|
| 907 |
+
def test_setitem_frame_mixed(self, float_string_frame):
|
| 908 |
+
# GH 3216
|
| 909 |
+
|
| 910 |
+
# already aligned
|
| 911 |
+
f = float_string_frame.copy()
|
| 912 |
+
piece = DataFrame(
|
| 913 |
+
[[1.0, 2.0], [3.0, 4.0]], index=f.index[0:2], columns=["A", "B"]
|
| 914 |
+
)
|
| 915 |
+
key = (f.index[slice(None, 2)], ["A", "B"])
|
| 916 |
+
f.loc[key] = piece
|
| 917 |
+
tm.assert_almost_equal(f.loc[f.index[0:2], ["A", "B"]].values, piece.values)
|
| 918 |
+
|
| 919 |
+
# dtype inference
|
| 920 |
+
@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)")
|
| 921 |
+
def test_setitem_frame_mixed_rows_unaligned(self, float_string_frame):
|
| 922 |
+
# GH#3216 rows unaligned
|
| 923 |
+
f = float_string_frame.copy()
|
| 924 |
+
piece = DataFrame(
|
| 925 |
+
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]],
|
| 926 |
+
index=list(f.index[0:2]) + ["foo", "bar"],
|
| 927 |
+
columns=["A", "B"],
|
| 928 |
+
)
|
| 929 |
+
key = (f.index[slice(None, 2)], ["A", "B"])
|
| 930 |
+
f.loc[key] = piece
|
| 931 |
+
tm.assert_almost_equal(
|
| 932 |
+
f.loc[f.index[0:2:], ["A", "B"]].values, piece.values[0:2]
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
# dtype inference
|
| 936 |
+
@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)")
|
| 937 |
+
def test_setitem_frame_mixed_key_unaligned(self, float_string_frame):
|
| 938 |
+
# GH#3216 key is unaligned with values
|
| 939 |
+
f = float_string_frame.copy()
|
| 940 |
+
piece = f.loc[f.index[:2], ["A"]]
|
| 941 |
+
piece.index = f.index[-2:]
|
| 942 |
+
key = (f.index[slice(-2, None)], ["A", "B"])
|
| 943 |
+
f.loc[key] = piece
|
| 944 |
+
piece["B"] = np.nan
|
| 945 |
+
tm.assert_almost_equal(f.loc[f.index[-2:], ["A", "B"]].values, piece.values)
|
| 946 |
+
|
| 947 |
+
def test_setitem_frame_mixed_ndarray(self, float_string_frame):
|
| 948 |
+
# GH#3216 ndarray
|
| 949 |
+
f = float_string_frame.copy()
|
| 950 |
+
piece = float_string_frame.loc[f.index[:2], ["A", "B"]]
|
| 951 |
+
key = (f.index[slice(-2, None)], ["A", "B"])
|
| 952 |
+
f.loc[key] = piece.values
|
| 953 |
+
tm.assert_almost_equal(f.loc[f.index[-2:], ["A", "B"]].values, piece.values)
|
| 954 |
+
|
| 955 |
+
def test_setitem_frame_upcast(self):
|
| 956 |
+
# needs upcasting
|
| 957 |
+
df = DataFrame([[1, 2, "foo"], [3, 4, "bar"]], columns=["A", "B", "C"])
|
| 958 |
+
df2 = df.copy()
|
| 959 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
| 960 |
+
df2.loc[:, ["A", "B"]] = df.loc[:, ["A", "B"]] + 0.5
|
| 961 |
+
expected = df.reindex(columns=["A", "B"])
|
| 962 |
+
expected += 0.5
|
| 963 |
+
expected["C"] = df["C"]
|
| 964 |
+
tm.assert_frame_equal(df2, expected)
|
| 965 |
+
|
| 966 |
+
def test_setitem_frame_align(self, float_frame):
|
| 967 |
+
piece = float_frame.loc[float_frame.index[:2], ["A", "B"]]
|
| 968 |
+
piece.index = float_frame.index[-2:]
|
| 969 |
+
piece.columns = ["A", "B"]
|
| 970 |
+
float_frame.loc[float_frame.index[-2:], ["A", "B"]] = piece
|
| 971 |
+
result = float_frame.loc[float_frame.index[-2:], ["A", "B"]].values
|
| 972 |
+
expected = piece.values
|
| 973 |
+
tm.assert_almost_equal(result, expected)
|
| 974 |
+
|
| 975 |
+
def test_getitem_setitem_ix_duplicates(self):
|
| 976 |
+
# #1201
|
| 977 |
+
df = DataFrame(
|
| 978 |
+
np.random.default_rng(2).standard_normal((5, 3)),
|
| 979 |
+
index=["foo", "foo", "bar", "baz", "bar"],
|
| 980 |
+
)
|
| 981 |
+
|
| 982 |
+
result = df.loc["foo"]
|
| 983 |
+
expected = df[:2]
|
| 984 |
+
tm.assert_frame_equal(result, expected)
|
| 985 |
+
|
| 986 |
+
result = df.loc["bar"]
|
| 987 |
+
expected = df.iloc[[2, 4]]
|
| 988 |
+
tm.assert_frame_equal(result, expected)
|
| 989 |
+
|
| 990 |
+
result = df.loc["baz"]
|
| 991 |
+
expected = df.iloc[3]
|
| 992 |
+
tm.assert_series_equal(result, expected)
|
| 993 |
+
|
| 994 |
+
def test_getitem_ix_boolean_duplicates_multiple(self):
|
| 995 |
+
# #1201
|
| 996 |
+
df = DataFrame(
|
| 997 |
+
np.random.default_rng(2).standard_normal((5, 3)),
|
| 998 |
+
index=["foo", "foo", "bar", "baz", "bar"],
|
| 999 |
+
)
|
| 1000 |
+
|
| 1001 |
+
result = df.loc[["bar"]]
|
| 1002 |
+
exp = df.iloc[[2, 4]]
|
| 1003 |
+
tm.assert_frame_equal(result, exp)
|
| 1004 |
+
|
| 1005 |
+
result = df.loc[df[1] > 0]
|
| 1006 |
+
exp = df[df[1] > 0]
|
| 1007 |
+
tm.assert_frame_equal(result, exp)
|
| 1008 |
+
|
| 1009 |
+
result = df.loc[df[0] > 0]
|
| 1010 |
+
exp = df[df[0] > 0]
|
| 1011 |
+
tm.assert_frame_equal(result, exp)
|
| 1012 |
+
|
| 1013 |
+
@pytest.mark.parametrize("bool_value", [True, False])
|
| 1014 |
+
def test_getitem_setitem_ix_bool_keyerror(self, bool_value):
|
| 1015 |
+
# #2199
|
| 1016 |
+
df = DataFrame({"a": [1, 2, 3]})
|
| 1017 |
+
message = f"{bool_value}: boolean label can not be used without a boolean index"
|
| 1018 |
+
with pytest.raises(KeyError, match=message):
|
| 1019 |
+
df.loc[bool_value]
|
| 1020 |
+
|
| 1021 |
+
msg = "cannot use a single bool to index into setitem"
|
| 1022 |
+
with pytest.raises(KeyError, match=msg):
|
| 1023 |
+
df.loc[bool_value] = 0
|
| 1024 |
+
|
| 1025 |
+
# TODO: rename? remove?
|
| 1026 |
+
def test_single_element_ix_dont_upcast(self, float_frame):
|
| 1027 |
+
float_frame["E"] = 1
|
| 1028 |
+
assert issubclass(float_frame["E"].dtype.type, (int, np.integer))
|
| 1029 |
+
|
| 1030 |
+
result = float_frame.loc[float_frame.index[5], "E"]
|
| 1031 |
+
assert is_integer(result)
|
| 1032 |
+
|
| 1033 |
+
# GH 11617
|
| 1034 |
+
df = DataFrame({"a": [1.23]})
|
| 1035 |
+
df["b"] = 666
|
| 1036 |
+
|
| 1037 |
+
result = df.loc[0, "b"]
|
| 1038 |
+
assert is_integer(result)
|
| 1039 |
+
|
| 1040 |
+
expected = Series([666], [0], name="b")
|
| 1041 |
+
result = df.loc[[0], "b"]
|
| 1042 |
+
tm.assert_series_equal(result, expected)
|
| 1043 |
+
|
| 1044 |
+
def test_iloc_callable_tuple_return_value(self):
|
| 1045 |
+
# GH53769
|
| 1046 |
+
df = DataFrame(np.arange(40).reshape(10, 4), index=range(0, 20, 2))
|
| 1047 |
+
msg = "callable with iloc"
|
| 1048 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 1049 |
+
df.iloc[lambda _: (0,)]
|
| 1050 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 1051 |
+
df.iloc[lambda _: (0,)] = 1
|
| 1052 |
+
|
| 1053 |
+
def test_iloc_row(self):
|
| 1054 |
+
df = DataFrame(
|
| 1055 |
+
np.random.default_rng(2).standard_normal((10, 4)), index=range(0, 20, 2)
|
| 1056 |
+
)
|
| 1057 |
+
|
| 1058 |
+
result = df.iloc[1]
|
| 1059 |
+
exp = df.loc[2]
|
| 1060 |
+
tm.assert_series_equal(result, exp)
|
| 1061 |
+
|
| 1062 |
+
result = df.iloc[2]
|
| 1063 |
+
exp = df.loc[4]
|
| 1064 |
+
tm.assert_series_equal(result, exp)
|
| 1065 |
+
|
| 1066 |
+
# slice
|
| 1067 |
+
result = df.iloc[slice(4, 8)]
|
| 1068 |
+
expected = df.loc[8:14]
|
| 1069 |
+
tm.assert_frame_equal(result, expected)
|
| 1070 |
+
|
| 1071 |
+
# list of integers
|
| 1072 |
+
result = df.iloc[[1, 2, 4, 6]]
|
| 1073 |
+
expected = df.reindex(df.index[[1, 2, 4, 6]])
|
| 1074 |
+
tm.assert_frame_equal(result, expected)
|
| 1075 |
+
|
| 1076 |
+
def test_iloc_row_slice_view(self, using_copy_on_write, warn_copy_on_write):
|
| 1077 |
+
df = DataFrame(
|
| 1078 |
+
np.random.default_rng(2).standard_normal((10, 4)), index=range(0, 20, 2)
|
| 1079 |
+
)
|
| 1080 |
+
original = df.copy()
|
| 1081 |
+
|
| 1082 |
+
# verify slice is view
|
| 1083 |
+
# setting it makes it raise/warn
|
| 1084 |
+
subset = df.iloc[slice(4, 8)]
|
| 1085 |
+
|
| 1086 |
+
assert np.shares_memory(df[2], subset[2])
|
| 1087 |
+
|
| 1088 |
+
exp_col = original[2].copy()
|
| 1089 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 1090 |
+
subset.loc[:, 2] = 0.0
|
| 1091 |
+
if not using_copy_on_write:
|
| 1092 |
+
exp_col._values[4:8] = 0.0
|
| 1093 |
+
|
| 1094 |
+
# With the enforcement of GH#45333 in 2.0, this remains a view
|
| 1095 |
+
assert np.shares_memory(df[2], subset[2])
|
| 1096 |
+
tm.assert_series_equal(df[2], exp_col)
|
| 1097 |
+
|
| 1098 |
+
def test_iloc_col(self):
|
| 1099 |
+
df = DataFrame(
|
| 1100 |
+
np.random.default_rng(2).standard_normal((4, 10)), columns=range(0, 20, 2)
|
| 1101 |
+
)
|
| 1102 |
+
|
| 1103 |
+
result = df.iloc[:, 1]
|
| 1104 |
+
exp = df.loc[:, 2]
|
| 1105 |
+
tm.assert_series_equal(result, exp)
|
| 1106 |
+
|
| 1107 |
+
result = df.iloc[:, 2]
|
| 1108 |
+
exp = df.loc[:, 4]
|
| 1109 |
+
tm.assert_series_equal(result, exp)
|
| 1110 |
+
|
| 1111 |
+
# slice
|
| 1112 |
+
result = df.iloc[:, slice(4, 8)]
|
| 1113 |
+
expected = df.loc[:, 8:14]
|
| 1114 |
+
tm.assert_frame_equal(result, expected)
|
| 1115 |
+
|
| 1116 |
+
# list of integers
|
| 1117 |
+
result = df.iloc[:, [1, 2, 4, 6]]
|
| 1118 |
+
expected = df.reindex(columns=df.columns[[1, 2, 4, 6]])
|
| 1119 |
+
tm.assert_frame_equal(result, expected)
|
| 1120 |
+
|
| 1121 |
+
def test_iloc_col_slice_view(
|
| 1122 |
+
self, using_array_manager, using_copy_on_write, warn_copy_on_write
|
| 1123 |
+
):
|
| 1124 |
+
df = DataFrame(
|
| 1125 |
+
np.random.default_rng(2).standard_normal((4, 10)), columns=range(0, 20, 2)
|
| 1126 |
+
)
|
| 1127 |
+
original = df.copy()
|
| 1128 |
+
subset = df.iloc[:, slice(4, 8)]
|
| 1129 |
+
|
| 1130 |
+
if not using_array_manager and not using_copy_on_write:
|
| 1131 |
+
# verify slice is view
|
| 1132 |
+
assert np.shares_memory(df[8]._values, subset[8]._values)
|
| 1133 |
+
|
| 1134 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 1135 |
+
subset.loc[:, 8] = 0.0
|
| 1136 |
+
|
| 1137 |
+
assert (df[8] == 0).all()
|
| 1138 |
+
|
| 1139 |
+
# with the enforcement of GH#45333 in 2.0, this remains a view
|
| 1140 |
+
assert np.shares_memory(df[8]._values, subset[8]._values)
|
| 1141 |
+
else:
|
| 1142 |
+
if using_copy_on_write:
|
| 1143 |
+
# verify slice is view
|
| 1144 |
+
assert np.shares_memory(df[8]._values, subset[8]._values)
|
| 1145 |
+
subset[8] = 0.0
|
| 1146 |
+
# subset changed
|
| 1147 |
+
assert (subset[8] == 0).all()
|
| 1148 |
+
# but df itself did not change (setitem replaces full column)
|
| 1149 |
+
tm.assert_frame_equal(df, original)
|
| 1150 |
+
|
| 1151 |
+
def test_loc_duplicates(self):
|
| 1152 |
+
# gh-17105
|
| 1153 |
+
|
| 1154 |
+
# insert a duplicate element to the index
|
| 1155 |
+
trange = date_range(
|
| 1156 |
+
start=Timestamp(year=2017, month=1, day=1),
|
| 1157 |
+
end=Timestamp(year=2017, month=1, day=5),
|
| 1158 |
+
)
|
| 1159 |
+
|
| 1160 |
+
trange = trange.insert(loc=5, item=Timestamp(year=2017, month=1, day=5))
|
| 1161 |
+
|
| 1162 |
+
df = DataFrame(0, index=trange, columns=["A", "B"])
|
| 1163 |
+
bool_idx = np.array([False, False, False, False, False, True])
|
| 1164 |
+
|
| 1165 |
+
# assignment
|
| 1166 |
+
df.loc[trange[bool_idx], "A"] = 6
|
| 1167 |
+
|
| 1168 |
+
expected = DataFrame(
|
| 1169 |
+
{"A": [0, 0, 0, 0, 6, 6], "B": [0, 0, 0, 0, 0, 0]}, index=trange
|
| 1170 |
+
)
|
| 1171 |
+
tm.assert_frame_equal(df, expected)
|
| 1172 |
+
|
| 1173 |
+
# in-place
|
| 1174 |
+
df = DataFrame(0, index=trange, columns=["A", "B"])
|
| 1175 |
+
df.loc[trange[bool_idx], "A"] += 6
|
| 1176 |
+
tm.assert_frame_equal(df, expected)
|
| 1177 |
+
|
| 1178 |
+
def test_setitem_with_unaligned_tz_aware_datetime_column(self):
|
| 1179 |
+
# GH 12981
|
| 1180 |
+
# Assignment of unaligned offset-aware datetime series.
|
| 1181 |
+
# Make sure timezone isn't lost
|
| 1182 |
+
column = Series(date_range("2015-01-01", periods=3, tz="utc"), name="dates")
|
| 1183 |
+
df = DataFrame({"dates": column})
|
| 1184 |
+
df["dates"] = column[[1, 0, 2]]
|
| 1185 |
+
tm.assert_series_equal(df["dates"], column)
|
| 1186 |
+
|
| 1187 |
+
df = DataFrame({"dates": column})
|
| 1188 |
+
df.loc[[0, 1, 2], "dates"] = column[[1, 0, 2]]
|
| 1189 |
+
tm.assert_series_equal(df["dates"], column)
|
| 1190 |
+
|
| 1191 |
+
def test_loc_setitem_datetimelike_with_inference(self):
|
| 1192 |
+
# GH 7592
|
| 1193 |
+
# assignment of timedeltas with NaT
|
| 1194 |
+
|
| 1195 |
+
one_hour = timedelta(hours=1)
|
| 1196 |
+
df = DataFrame(index=date_range("20130101", periods=4))
|
| 1197 |
+
df["A"] = np.array([1 * one_hour] * 4, dtype="m8[ns]")
|
| 1198 |
+
df.loc[:, "B"] = np.array([2 * one_hour] * 4, dtype="m8[ns]")
|
| 1199 |
+
df.loc[df.index[:3], "C"] = np.array([3 * one_hour] * 3, dtype="m8[ns]")
|
| 1200 |
+
df.loc[:, "D"] = np.array([4 * one_hour] * 4, dtype="m8[ns]")
|
| 1201 |
+
df.loc[df.index[:3], "E"] = np.array([5 * one_hour] * 3, dtype="m8[ns]")
|
| 1202 |
+
df["F"] = np.timedelta64("NaT")
|
| 1203 |
+
df.loc[df.index[:-1], "F"] = np.array([6 * one_hour] * 3, dtype="m8[ns]")
|
| 1204 |
+
df.loc[df.index[-3] :, "G"] = date_range("20130101", periods=3)
|
| 1205 |
+
df["H"] = np.datetime64("NaT")
|
| 1206 |
+
result = df.dtypes
|
| 1207 |
+
expected = Series(
|
| 1208 |
+
[np.dtype("timedelta64[ns]")] * 6 + [np.dtype("datetime64[ns]")] * 2,
|
| 1209 |
+
index=list("ABCDEFGH"),
|
| 1210 |
+
)
|
| 1211 |
+
tm.assert_series_equal(result, expected)
|
| 1212 |
+
|
| 1213 |
+
def test_getitem_boolean_indexing_mixed(self):
|
| 1214 |
+
df = DataFrame(
|
| 1215 |
+
{
|
| 1216 |
+
0: {35: np.nan, 40: np.nan, 43: np.nan, 49: np.nan, 50: np.nan},
|
| 1217 |
+
1: {
|
| 1218 |
+
35: np.nan,
|
| 1219 |
+
40: 0.32632316859446198,
|
| 1220 |
+
43: np.nan,
|
| 1221 |
+
49: 0.32632316859446198,
|
| 1222 |
+
50: 0.39114724480578139,
|
| 1223 |
+
},
|
| 1224 |
+
2: {
|
| 1225 |
+
35: np.nan,
|
| 1226 |
+
40: np.nan,
|
| 1227 |
+
43: 0.29012581014105987,
|
| 1228 |
+
49: np.nan,
|
| 1229 |
+
50: np.nan,
|
| 1230 |
+
},
|
| 1231 |
+
3: {35: np.nan, 40: np.nan, 43: np.nan, 49: np.nan, 50: np.nan},
|
| 1232 |
+
4: {
|
| 1233 |
+
35: 0.34215328467153283,
|
| 1234 |
+
40: np.nan,
|
| 1235 |
+
43: np.nan,
|
| 1236 |
+
49: np.nan,
|
| 1237 |
+
50: np.nan,
|
| 1238 |
+
},
|
| 1239 |
+
"y": {35: 0, 40: 0, 43: 0, 49: 0, 50: 1},
|
| 1240 |
+
}
|
| 1241 |
+
)
|
| 1242 |
+
|
| 1243 |
+
# mixed int/float ok
|
| 1244 |
+
df2 = df.copy()
|
| 1245 |
+
df2[df2 > 0.3] = 1
|
| 1246 |
+
expected = df.copy()
|
| 1247 |
+
expected.loc[40, 1] = 1
|
| 1248 |
+
expected.loc[49, 1] = 1
|
| 1249 |
+
expected.loc[50, 1] = 1
|
| 1250 |
+
expected.loc[35, 4] = 1
|
| 1251 |
+
tm.assert_frame_equal(df2, expected)
|
| 1252 |
+
|
| 1253 |
+
df["foo"] = "test"
|
| 1254 |
+
msg = "not supported between instances|unorderable types|Invalid comparison"
|
| 1255 |
+
|
| 1256 |
+
with pytest.raises(TypeError, match=msg):
|
| 1257 |
+
df[df > 0.3] = 1
|
| 1258 |
+
|
| 1259 |
+
def test_type_error_multiindex(self):
|
| 1260 |
+
# See gh-12218
|
| 1261 |
+
mi = MultiIndex.from_product([["x", "y"], [0, 1]], names=[None, "c"])
|
| 1262 |
+
dg = DataFrame(
|
| 1263 |
+
[[1, 1, 2, 2], [3, 3, 4, 4]], columns=mi, index=Index([0, 1], name="i")
|
| 1264 |
+
)
|
| 1265 |
+
with pytest.raises(InvalidIndexError, match="slice"):
|
| 1266 |
+
dg[:, 0]
|
| 1267 |
+
|
| 1268 |
+
index = Index(range(2), name="i")
|
| 1269 |
+
columns = MultiIndex(
|
| 1270 |
+
levels=[["x", "y"], [0, 1]], codes=[[0, 1], [0, 0]], names=[None, "c"]
|
| 1271 |
+
)
|
| 1272 |
+
expected = DataFrame([[1, 2], [3, 4]], columns=columns, index=index)
|
| 1273 |
+
|
| 1274 |
+
result = dg.loc[:, (slice(None), 0)]
|
| 1275 |
+
tm.assert_frame_equal(result, expected)
|
| 1276 |
+
|
| 1277 |
+
name = ("x", 0)
|
| 1278 |
+
index = Index(range(2), name="i")
|
| 1279 |
+
expected = Series([1, 3], index=index, name=name)
|
| 1280 |
+
|
| 1281 |
+
result = dg["x", 0]
|
| 1282 |
+
tm.assert_series_equal(result, expected)
|
| 1283 |
+
|
| 1284 |
+
def test_getitem_interval_index_partial_indexing(self):
|
| 1285 |
+
# GH#36490
|
| 1286 |
+
df = DataFrame(
|
| 1287 |
+
np.ones((3, 4)), columns=pd.IntervalIndex.from_breaks(np.arange(5))
|
| 1288 |
+
)
|
| 1289 |
+
|
| 1290 |
+
expected = df.iloc[:, 0]
|
| 1291 |
+
|
| 1292 |
+
res = df[0.5]
|
| 1293 |
+
tm.assert_series_equal(res, expected)
|
| 1294 |
+
|
| 1295 |
+
res = df.loc[:, 0.5]
|
| 1296 |
+
tm.assert_series_equal(res, expected)
|
| 1297 |
+
|
| 1298 |
+
def test_setitem_array_as_cell_value(self):
|
| 1299 |
+
# GH#43422
|
| 1300 |
+
df = DataFrame(columns=["a", "b"], dtype=object)
|
| 1301 |
+
df.loc[0] = {"a": np.zeros((2,)), "b": np.zeros((2, 2))}
|
| 1302 |
+
expected = DataFrame({"a": [np.zeros((2,))], "b": [np.zeros((2, 2))]})
|
| 1303 |
+
tm.assert_frame_equal(df, expected)
|
| 1304 |
+
|
| 1305 |
+
def test_iloc_setitem_nullable_2d_values(self):
|
| 1306 |
+
df = DataFrame({"A": [1, 2, 3]}, dtype="Int64")
|
| 1307 |
+
orig = df.copy()
|
| 1308 |
+
|
| 1309 |
+
df.loc[:] = df.values[:, ::-1]
|
| 1310 |
+
tm.assert_frame_equal(df, orig)
|
| 1311 |
+
|
| 1312 |
+
df.loc[:] = pd.core.arrays.NumpyExtensionArray(df.values[:, ::-1])
|
| 1313 |
+
tm.assert_frame_equal(df, orig)
|
| 1314 |
+
|
| 1315 |
+
df.iloc[:] = df.iloc[:, :].copy()
|
| 1316 |
+
tm.assert_frame_equal(df, orig)
|
| 1317 |
+
|
| 1318 |
+
def test_getitem_segfault_with_empty_like_object(self):
|
| 1319 |
+
# GH#46848
|
| 1320 |
+
df = DataFrame(np.empty((1, 1), dtype=object))
|
| 1321 |
+
df[0] = np.empty_like(df[0])
|
| 1322 |
+
# this produces the segfault
|
| 1323 |
+
df[[0]]
|
| 1324 |
+
|
| 1325 |
+
@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")
|
| 1326 |
+
@pytest.mark.parametrize(
|
| 1327 |
+
"null", [pd.NaT, pd.NaT.to_numpy("M8[ns]"), pd.NaT.to_numpy("m8[ns]")]
|
| 1328 |
+
)
|
| 1329 |
+
def test_setting_mismatched_na_into_nullable_fails(
|
| 1330 |
+
self, null, any_numeric_ea_dtype
|
| 1331 |
+
):
|
| 1332 |
+
# GH#44514 don't cast mismatched nulls to pd.NA
|
| 1333 |
+
df = DataFrame({"A": [1, 2, 3]}, dtype=any_numeric_ea_dtype)
|
| 1334 |
+
ser = df["A"].copy()
|
| 1335 |
+
arr = ser._values
|
| 1336 |
+
|
| 1337 |
+
msg = "|".join(
|
| 1338 |
+
[
|
| 1339 |
+
r"timedelta64\[ns\] cannot be converted to (Floating|Integer)Dtype",
|
| 1340 |
+
r"datetime64\[ns\] cannot be converted to (Floating|Integer)Dtype",
|
| 1341 |
+
"'values' contains non-numeric NA",
|
| 1342 |
+
r"Invalid value '.*' for dtype '(U?Int|Float)\d{1,2}'",
|
| 1343 |
+
]
|
| 1344 |
+
)
|
| 1345 |
+
with pytest.raises(TypeError, match=msg):
|
| 1346 |
+
arr[0] = null
|
| 1347 |
+
|
| 1348 |
+
with pytest.raises(TypeError, match=msg):
|
| 1349 |
+
arr[:2] = [null, null]
|
| 1350 |
+
|
| 1351 |
+
with pytest.raises(TypeError, match=msg):
|
| 1352 |
+
ser[0] = null
|
| 1353 |
+
|
| 1354 |
+
with pytest.raises(TypeError, match=msg):
|
| 1355 |
+
ser[:2] = [null, null]
|
| 1356 |
+
|
| 1357 |
+
with pytest.raises(TypeError, match=msg):
|
| 1358 |
+
ser.iloc[0] = null
|
| 1359 |
+
|
| 1360 |
+
with pytest.raises(TypeError, match=msg):
|
| 1361 |
+
ser.iloc[:2] = [null, null]
|
| 1362 |
+
|
| 1363 |
+
with pytest.raises(TypeError, match=msg):
|
| 1364 |
+
df.iloc[0, 0] = null
|
| 1365 |
+
|
| 1366 |
+
with pytest.raises(TypeError, match=msg):
|
| 1367 |
+
df.iloc[:2, 0] = [null, null]
|
| 1368 |
+
|
| 1369 |
+
# Multi-Block
|
| 1370 |
+
df2 = df.copy()
|
| 1371 |
+
df2["B"] = ser.copy()
|
| 1372 |
+
with pytest.raises(TypeError, match=msg):
|
| 1373 |
+
df2.iloc[0, 0] = null
|
| 1374 |
+
|
| 1375 |
+
with pytest.raises(TypeError, match=msg):
|
| 1376 |
+
df2.iloc[:2, 0] = [null, null]
|
| 1377 |
+
|
| 1378 |
+
def test_loc_expand_empty_frame_keep_index_name(self):
|
| 1379 |
+
# GH#45621
|
| 1380 |
+
df = DataFrame(columns=["b"], index=Index([], name="a"))
|
| 1381 |
+
df.loc[0] = 1
|
| 1382 |
+
expected = DataFrame({"b": [1]}, index=Index([0], name="a"))
|
| 1383 |
+
tm.assert_frame_equal(df, expected)
|
| 1384 |
+
|
| 1385 |
+
def test_loc_expand_empty_frame_keep_midx_names(self):
|
| 1386 |
+
# GH#46317
|
| 1387 |
+
df = DataFrame(
|
| 1388 |
+
columns=["d"], index=MultiIndex.from_tuples([], names=["a", "b", "c"])
|
| 1389 |
+
)
|
| 1390 |
+
df.loc[(1, 2, 3)] = "foo"
|
| 1391 |
+
expected = DataFrame(
|
| 1392 |
+
{"d": ["foo"]},
|
| 1393 |
+
index=MultiIndex.from_tuples([(1, 2, 3)], names=["a", "b", "c"]),
|
| 1394 |
+
)
|
| 1395 |
+
tm.assert_frame_equal(df, expected)
|
| 1396 |
+
|
| 1397 |
+
@pytest.mark.parametrize(
|
| 1398 |
+
"val, idxr",
|
| 1399 |
+
[
|
| 1400 |
+
("x", "a"),
|
| 1401 |
+
("x", ["a"]),
|
| 1402 |
+
(1, "a"),
|
| 1403 |
+
(1, ["a"]),
|
| 1404 |
+
],
|
| 1405 |
+
)
|
| 1406 |
+
def test_loc_setitem_rhs_frame(self, idxr, val):
|
| 1407 |
+
# GH#47578
|
| 1408 |
+
df = DataFrame({"a": [1, 2]})
|
| 1409 |
+
|
| 1410 |
+
with tm.assert_produces_warning(
|
| 1411 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 1412 |
+
):
|
| 1413 |
+
df.loc[:, idxr] = DataFrame({"a": [val, 11]}, index=[1, 2])
|
| 1414 |
+
expected = DataFrame({"a": [np.nan, val]})
|
| 1415 |
+
tm.assert_frame_equal(df, expected)
|
| 1416 |
+
|
| 1417 |
+
@td.skip_array_manager_invalid_test
|
| 1418 |
+
def test_iloc_setitem_enlarge_no_warning(self, warn_copy_on_write):
|
| 1419 |
+
# GH#47381
|
| 1420 |
+
df = DataFrame(columns=["a", "b"])
|
| 1421 |
+
expected = df.copy()
|
| 1422 |
+
view = df[:]
|
| 1423 |
+
df.iloc[:, 0] = np.array([1, 2], dtype=np.float64)
|
| 1424 |
+
tm.assert_frame_equal(view, expected)
|
| 1425 |
+
|
| 1426 |
+
def test_loc_internals_not_updated_correctly(self):
|
| 1427 |
+
# GH#47867 all steps are necessary to reproduce the initial bug
|
| 1428 |
+
df = DataFrame(
|
| 1429 |
+
{"bool_col": True, "a": 1, "b": 2.5},
|
| 1430 |
+
index=MultiIndex.from_arrays([[1, 2], [1, 2]], names=["idx1", "idx2"]),
|
| 1431 |
+
)
|
| 1432 |
+
idx = [(1, 1)]
|
| 1433 |
+
|
| 1434 |
+
df["c"] = 3
|
| 1435 |
+
df.loc[idx, "c"] = 0
|
| 1436 |
+
|
| 1437 |
+
df.loc[idx, "c"]
|
| 1438 |
+
df.loc[idx, ["a", "b"]]
|
| 1439 |
+
|
| 1440 |
+
df.loc[idx, "c"] = 15
|
| 1441 |
+
result = df.loc[idx, "c"]
|
| 1442 |
+
expected = df = Series(
|
| 1443 |
+
15,
|
| 1444 |
+
index=MultiIndex.from_arrays([[1], [1]], names=["idx1", "idx2"]),
|
| 1445 |
+
name="c",
|
| 1446 |
+
)
|
| 1447 |
+
tm.assert_series_equal(result, expected)
|
| 1448 |
+
|
| 1449 |
+
@pytest.mark.parametrize("val", [None, [None], pd.NA, [pd.NA]])
|
| 1450 |
+
def test_iloc_setitem_string_list_na(self, val):
|
| 1451 |
+
# GH#45469
|
| 1452 |
+
df = DataFrame({"a": ["a", "b", "c"]}, dtype="string")
|
| 1453 |
+
df.iloc[[0], :] = val
|
| 1454 |
+
expected = DataFrame({"a": [pd.NA, "b", "c"]}, dtype="string")
|
| 1455 |
+
tm.assert_frame_equal(df, expected)
|
| 1456 |
+
|
| 1457 |
+
@pytest.mark.parametrize("val", [None, pd.NA])
|
| 1458 |
+
def test_iloc_setitem_string_na(self, val):
|
| 1459 |
+
# GH#45469
|
| 1460 |
+
df = DataFrame({"a": ["a", "b", "c"]}, dtype="string")
|
| 1461 |
+
df.iloc[0, :] = val
|
| 1462 |
+
expected = DataFrame({"a": [pd.NA, "b", "c"]}, dtype="string")
|
| 1463 |
+
tm.assert_frame_equal(df, expected)
|
| 1464 |
+
|
| 1465 |
+
@pytest.mark.parametrize("func", [list, Series, np.array])
|
| 1466 |
+
def test_iloc_setitem_ea_null_slice_length_one_list(self, func):
|
| 1467 |
+
# GH#48016
|
| 1468 |
+
df = DataFrame({"a": [1, 2, 3]}, dtype="Int64")
|
| 1469 |
+
df.iloc[:, func([0])] = 5
|
| 1470 |
+
expected = DataFrame({"a": [5, 5, 5]}, dtype="Int64")
|
| 1471 |
+
tm.assert_frame_equal(df, expected)
|
| 1472 |
+
|
| 1473 |
+
def test_loc_named_tuple_for_midx(self):
|
| 1474 |
+
# GH#48124
|
| 1475 |
+
df = DataFrame(
|
| 1476 |
+
index=MultiIndex.from_product(
|
| 1477 |
+
[["A", "B"], ["a", "b", "c"]], names=["first", "second"]
|
| 1478 |
+
)
|
| 1479 |
+
)
|
| 1480 |
+
indexer_tuple = namedtuple("Indexer", df.index.names)
|
| 1481 |
+
idxr = indexer_tuple(first="A", second=["a", "b"])
|
| 1482 |
+
result = df.loc[idxr, :]
|
| 1483 |
+
expected = DataFrame(
|
| 1484 |
+
index=MultiIndex.from_tuples(
|
| 1485 |
+
[("A", "a"), ("A", "b")], names=["first", "second"]
|
| 1486 |
+
)
|
| 1487 |
+
)
|
| 1488 |
+
tm.assert_frame_equal(result, expected)
|
| 1489 |
+
|
| 1490 |
+
@pytest.mark.parametrize("indexer", [["a"], "a"])
|
| 1491 |
+
@pytest.mark.parametrize("col", [{}, {"b": 1}])
|
| 1492 |
+
def test_set_2d_casting_date_to_int(self, col, indexer):
|
| 1493 |
+
# GH#49159
|
| 1494 |
+
df = DataFrame(
|
| 1495 |
+
{"a": [Timestamp("2022-12-29"), Timestamp("2022-12-30")], **col},
|
| 1496 |
+
)
|
| 1497 |
+
df.loc[[1], indexer] = df["a"] + pd.Timedelta(days=1)
|
| 1498 |
+
expected = DataFrame(
|
| 1499 |
+
{"a": [Timestamp("2022-12-29"), Timestamp("2022-12-31")], **col},
|
| 1500 |
+
)
|
| 1501 |
+
tm.assert_frame_equal(df, expected)
|
| 1502 |
+
|
| 1503 |
+
@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")
|
| 1504 |
+
@pytest.mark.parametrize("has_ref", [True, False])
|
| 1505 |
+
@pytest.mark.parametrize("col", [{}, {"name": "a"}])
|
| 1506 |
+
def test_loc_setitem_reordering_with_all_true_indexer(self, col, has_ref):
|
| 1507 |
+
# GH#48701
|
| 1508 |
+
n = 17
|
| 1509 |
+
df = DataFrame({**col, "x": range(n), "y": range(n)})
|
| 1510 |
+
value = df[["x", "y"]].copy()
|
| 1511 |
+
expected = df.copy()
|
| 1512 |
+
if has_ref:
|
| 1513 |
+
view = df[:] # noqa: F841
|
| 1514 |
+
df.loc[n * [True], ["x", "y"]] = value
|
| 1515 |
+
tm.assert_frame_equal(df, expected)
|
| 1516 |
+
|
| 1517 |
+
def test_loc_rhs_empty_warning(self):
|
| 1518 |
+
# GH48480
|
| 1519 |
+
df = DataFrame(columns=["a", "b"])
|
| 1520 |
+
expected = df.copy()
|
| 1521 |
+
rhs = DataFrame(columns=["a"])
|
| 1522 |
+
with tm.assert_produces_warning(None):
|
| 1523 |
+
df.loc[:, "a"] = rhs
|
| 1524 |
+
tm.assert_frame_equal(df, expected)
|
| 1525 |
+
|
| 1526 |
+
def test_iloc_ea_series_indexer(self):
|
| 1527 |
+
# GH#49521
|
| 1528 |
+
df = DataFrame([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
|
| 1529 |
+
indexer = Series([0, 1], dtype="Int64")
|
| 1530 |
+
row_indexer = Series([1], dtype="Int64")
|
| 1531 |
+
result = df.iloc[row_indexer, indexer]
|
| 1532 |
+
expected = DataFrame([[5, 6]], index=[1])
|
| 1533 |
+
tm.assert_frame_equal(result, expected)
|
| 1534 |
+
|
| 1535 |
+
result = df.iloc[row_indexer.values, indexer.values]
|
| 1536 |
+
tm.assert_frame_equal(result, expected)
|
| 1537 |
+
|
| 1538 |
+
def test_iloc_ea_series_indexer_with_na(self):
|
| 1539 |
+
# GH#49521
|
| 1540 |
+
df = DataFrame([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
|
| 1541 |
+
indexer = Series([0, pd.NA], dtype="Int64")
|
| 1542 |
+
msg = "cannot convert"
|
| 1543 |
+
with pytest.raises(ValueError, match=msg):
|
| 1544 |
+
df.iloc[:, indexer]
|
| 1545 |
+
with pytest.raises(ValueError, match=msg):
|
| 1546 |
+
df.iloc[:, indexer.values]
|
| 1547 |
+
|
| 1548 |
+
@pytest.mark.parametrize("indexer", [True, (True,)])
|
| 1549 |
+
@pytest.mark.parametrize("dtype", [bool, "boolean"])
|
| 1550 |
+
def test_loc_bool_multiindex(self, dtype, indexer):
|
| 1551 |
+
# GH#47687
|
| 1552 |
+
midx = MultiIndex.from_arrays(
|
| 1553 |
+
[
|
| 1554 |
+
Series([True, True, False, False], dtype=dtype),
|
| 1555 |
+
Series([True, False, True, False], dtype=dtype),
|
| 1556 |
+
],
|
| 1557 |
+
names=["a", "b"],
|
| 1558 |
+
)
|
| 1559 |
+
df = DataFrame({"c": [1, 2, 3, 4]}, index=midx)
|
| 1560 |
+
with tm.maybe_produces_warning(PerformanceWarning, isinstance(indexer, tuple)):
|
| 1561 |
+
result = df.loc[indexer]
|
| 1562 |
+
expected = DataFrame(
|
| 1563 |
+
{"c": [1, 2]}, index=Index([True, False], name="b", dtype=dtype)
|
| 1564 |
+
)
|
| 1565 |
+
tm.assert_frame_equal(result, expected)
|
| 1566 |
+
|
| 1567 |
+
@pytest.mark.parametrize("utc", [False, True])
|
| 1568 |
+
@pytest.mark.parametrize("indexer", ["date", ["date"]])
|
| 1569 |
+
def test_loc_datetime_assignment_dtype_does_not_change(self, utc, indexer):
|
| 1570 |
+
# GH#49837
|
| 1571 |
+
df = DataFrame(
|
| 1572 |
+
{
|
| 1573 |
+
"date": to_datetime(
|
| 1574 |
+
[datetime(2022, 1, 20), datetime(2022, 1, 22)], utc=utc
|
| 1575 |
+
),
|
| 1576 |
+
"update": [True, False],
|
| 1577 |
+
}
|
| 1578 |
+
)
|
| 1579 |
+
expected = df.copy(deep=True)
|
| 1580 |
+
|
| 1581 |
+
update_df = df[df["update"]]
|
| 1582 |
+
|
| 1583 |
+
df.loc[df["update"], indexer] = update_df["date"]
|
| 1584 |
+
|
| 1585 |
+
tm.assert_frame_equal(df, expected)
|
| 1586 |
+
|
| 1587 |
+
@pytest.mark.parametrize("indexer, idx", [(tm.loc, 1), (tm.iloc, 2)])
|
| 1588 |
+
def test_setitem_value_coercing_dtypes(self, indexer, idx):
|
| 1589 |
+
# GH#50467
|
| 1590 |
+
df = DataFrame([["1", np.nan], ["2", np.nan], ["3", np.nan]], dtype=object)
|
| 1591 |
+
rhs = DataFrame([[1, np.nan], [2, np.nan]])
|
| 1592 |
+
indexer(df)[:idx, :] = rhs
|
| 1593 |
+
expected = DataFrame([[1, np.nan], [2, np.nan], ["3", np.nan]], dtype=object)
|
| 1594 |
+
tm.assert_frame_equal(df, expected)
|
| 1595 |
+
|
| 1596 |
+
|
| 1597 |
+
class TestDataFrameIndexingUInt64:
|
| 1598 |
+
def test_setitem(self):
|
| 1599 |
+
df = DataFrame(
|
| 1600 |
+
{"A": np.arange(3), "B": [2**63, 2**63 + 5, 2**63 + 10]},
|
| 1601 |
+
dtype=np.uint64,
|
| 1602 |
+
)
|
| 1603 |
+
idx = df["A"].rename("foo")
|
| 1604 |
+
|
| 1605 |
+
# setitem
|
| 1606 |
+
assert "C" not in df.columns
|
| 1607 |
+
df["C"] = idx
|
| 1608 |
+
tm.assert_series_equal(df["C"], Series(idx, name="C"))
|
| 1609 |
+
|
| 1610 |
+
assert "D" not in df.columns
|
| 1611 |
+
df["D"] = "foo"
|
| 1612 |
+
df["D"] = idx
|
| 1613 |
+
tm.assert_series_equal(df["D"], Series(idx, name="D"))
|
| 1614 |
+
del df["D"]
|
| 1615 |
+
|
| 1616 |
+
# With NaN: because uint64 has no NaN element,
|
| 1617 |
+
# the column should be cast to object.
|
| 1618 |
+
df2 = df.copy()
|
| 1619 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
| 1620 |
+
df2.iloc[1, 1] = pd.NaT
|
| 1621 |
+
df2.iloc[1, 2] = pd.NaT
|
| 1622 |
+
result = df2["B"]
|
| 1623 |
+
tm.assert_series_equal(notna(result), Series([True, False, True], name="B"))
|
| 1624 |
+
tm.assert_series_equal(
|
| 1625 |
+
df2.dtypes,
|
| 1626 |
+
Series(
|
| 1627 |
+
[np.dtype("uint64"), np.dtype("O"), np.dtype("O")],
|
| 1628 |
+
index=["A", "B", "C"],
|
| 1629 |
+
),
|
| 1630 |
+
)
|
| 1631 |
+
|
| 1632 |
+
|
| 1633 |
+
def test_object_casting_indexing_wraps_datetimelike(using_array_manager):
|
| 1634 |
+
# GH#31649, check the indexing methods all the way down the stack
|
| 1635 |
+
df = DataFrame(
|
| 1636 |
+
{
|
| 1637 |
+
"A": [1, 2],
|
| 1638 |
+
"B": date_range("2000", periods=2),
|
| 1639 |
+
"C": pd.timedelta_range("1 Day", periods=2),
|
| 1640 |
+
}
|
| 1641 |
+
)
|
| 1642 |
+
|
| 1643 |
+
ser = df.loc[0]
|
| 1644 |
+
assert isinstance(ser.values[1], Timestamp)
|
| 1645 |
+
assert isinstance(ser.values[2], pd.Timedelta)
|
| 1646 |
+
|
| 1647 |
+
ser = df.iloc[0]
|
| 1648 |
+
assert isinstance(ser.values[1], Timestamp)
|
| 1649 |
+
assert isinstance(ser.values[2], pd.Timedelta)
|
| 1650 |
+
|
| 1651 |
+
ser = df.xs(0, axis=0)
|
| 1652 |
+
assert isinstance(ser.values[1], Timestamp)
|
| 1653 |
+
assert isinstance(ser.values[2], pd.Timedelta)
|
| 1654 |
+
|
| 1655 |
+
if using_array_manager:
|
| 1656 |
+
# remainder of the test checking BlockManager internals
|
| 1657 |
+
return
|
| 1658 |
+
|
| 1659 |
+
mgr = df._mgr
|
| 1660 |
+
mgr._rebuild_blknos_and_blklocs()
|
| 1661 |
+
arr = mgr.fast_xs(0).array
|
| 1662 |
+
assert isinstance(arr[1], Timestamp)
|
| 1663 |
+
assert isinstance(arr[2], pd.Timedelta)
|
| 1664 |
+
|
| 1665 |
+
blk = mgr.blocks[mgr.blknos[1]]
|
| 1666 |
+
assert blk.dtype == "M8[ns]" # we got the right block
|
| 1667 |
+
val = blk.iget((0, 0))
|
| 1668 |
+
assert isinstance(val, Timestamp)
|
| 1669 |
+
|
| 1670 |
+
blk = mgr.blocks[mgr.blknos[2]]
|
| 1671 |
+
assert blk.dtype == "m8[ns]" # we got the right block
|
| 1672 |
+
val = blk.iget((0, 0))
|
| 1673 |
+
assert isinstance(val, pd.Timedelta)
|
| 1674 |
+
|
| 1675 |
+
|
| 1676 |
+
msg1 = r"Cannot setitem on a Categorical with a new category( \(.*\))?, set the"
|
| 1677 |
+
msg2 = "Cannot set a Categorical with another, without identical categories"
|
| 1678 |
+
|
| 1679 |
+
|
| 1680 |
+
class TestLocILocDataFrameCategorical:
|
| 1681 |
+
@pytest.fixture
|
| 1682 |
+
def orig(self):
|
| 1683 |
+
cats = Categorical(["a", "a", "a", "a", "a", "a", "a"], categories=["a", "b"])
|
| 1684 |
+
idx = Index(["h", "i", "j", "k", "l", "m", "n"])
|
| 1685 |
+
values = [1, 1, 1, 1, 1, 1, 1]
|
| 1686 |
+
orig = DataFrame({"cats": cats, "values": values}, index=idx)
|
| 1687 |
+
return orig
|
| 1688 |
+
|
| 1689 |
+
@pytest.fixture
|
| 1690 |
+
def exp_single_row(self):
|
| 1691 |
+
# The expected values if we change a single row
|
| 1692 |
+
cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"])
|
| 1693 |
+
idx1 = Index(["h", "i", "j", "k", "l", "m", "n"])
|
| 1694 |
+
values1 = [1, 1, 2, 1, 1, 1, 1]
|
| 1695 |
+
exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1)
|
| 1696 |
+
return exp_single_row
|
| 1697 |
+
|
| 1698 |
+
@pytest.fixture
|
| 1699 |
+
def exp_multi_row(self):
|
| 1700 |
+
# assign multiple rows (mixed values) (-> array) -> exp_multi_row
|
| 1701 |
+
# changed multiple rows
|
| 1702 |
+
cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])
|
| 1703 |
+
idx2 = Index(["h", "i", "j", "k", "l", "m", "n"])
|
| 1704 |
+
values2 = [1, 1, 2, 2, 1, 1, 1]
|
| 1705 |
+
exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2)
|
| 1706 |
+
return exp_multi_row
|
| 1707 |
+
|
| 1708 |
+
@pytest.fixture
|
| 1709 |
+
def exp_parts_cats_col(self):
|
| 1710 |
+
# changed part of the cats column
|
| 1711 |
+
cats3 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])
|
| 1712 |
+
idx3 = Index(["h", "i", "j", "k", "l", "m", "n"])
|
| 1713 |
+
values3 = [1, 1, 1, 1, 1, 1, 1]
|
| 1714 |
+
exp_parts_cats_col = DataFrame({"cats": cats3, "values": values3}, index=idx3)
|
| 1715 |
+
return exp_parts_cats_col
|
| 1716 |
+
|
| 1717 |
+
@pytest.fixture
|
| 1718 |
+
def exp_single_cats_value(self):
|
| 1719 |
+
# changed single value in cats col
|
| 1720 |
+
cats4 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"])
|
| 1721 |
+
idx4 = Index(["h", "i", "j", "k", "l", "m", "n"])
|
| 1722 |
+
values4 = [1, 1, 1, 1, 1, 1, 1]
|
| 1723 |
+
exp_single_cats_value = DataFrame(
|
| 1724 |
+
{"cats": cats4, "values": values4}, index=idx4
|
| 1725 |
+
)
|
| 1726 |
+
return exp_single_cats_value
|
| 1727 |
+
|
| 1728 |
+
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
|
| 1729 |
+
def test_loc_iloc_setitem_list_of_lists(self, orig, exp_multi_row, indexer):
|
| 1730 |
+
# - assign multiple rows (mixed values) -> exp_multi_row
|
| 1731 |
+
df = orig.copy()
|
| 1732 |
+
|
| 1733 |
+
key = slice(2, 4)
|
| 1734 |
+
if indexer is tm.loc:
|
| 1735 |
+
key = slice("j", "k")
|
| 1736 |
+
|
| 1737 |
+
indexer(df)[key, :] = [["b", 2], ["b", 2]]
|
| 1738 |
+
tm.assert_frame_equal(df, exp_multi_row)
|
| 1739 |
+
|
| 1740 |
+
df = orig.copy()
|
| 1741 |
+
with pytest.raises(TypeError, match=msg1):
|
| 1742 |
+
indexer(df)[key, :] = [["c", 2], ["c", 2]]
|
| 1743 |
+
|
| 1744 |
+
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc, tm.at, tm.iat])
|
| 1745 |
+
def test_loc_iloc_at_iat_setitem_single_value_in_categories(
|
| 1746 |
+
self, orig, exp_single_cats_value, indexer
|
| 1747 |
+
):
|
| 1748 |
+
# - assign a single value -> exp_single_cats_value
|
| 1749 |
+
df = orig.copy()
|
| 1750 |
+
|
| 1751 |
+
key = (2, 0)
|
| 1752 |
+
if indexer in [tm.loc, tm.at]:
|
| 1753 |
+
key = (df.index[2], df.columns[0])
|
| 1754 |
+
|
| 1755 |
+
# "b" is among the categories for df["cat"}]
|
| 1756 |
+
indexer(df)[key] = "b"
|
| 1757 |
+
tm.assert_frame_equal(df, exp_single_cats_value)
|
| 1758 |
+
|
| 1759 |
+
# "c" is not among the categories for df["cat"]
|
| 1760 |
+
with pytest.raises(TypeError, match=msg1):
|
| 1761 |
+
indexer(df)[key] = "c"
|
| 1762 |
+
|
| 1763 |
+
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
|
| 1764 |
+
def test_loc_iloc_setitem_mask_single_value_in_categories(
|
| 1765 |
+
self, orig, exp_single_cats_value, indexer
|
| 1766 |
+
):
|
| 1767 |
+
# mask with single True
|
| 1768 |
+
df = orig.copy()
|
| 1769 |
+
|
| 1770 |
+
mask = df.index == "j"
|
| 1771 |
+
key = 0
|
| 1772 |
+
if indexer is tm.loc:
|
| 1773 |
+
key = df.columns[key]
|
| 1774 |
+
|
| 1775 |
+
indexer(df)[mask, key] = "b"
|
| 1776 |
+
tm.assert_frame_equal(df, exp_single_cats_value)
|
| 1777 |
+
|
| 1778 |
+
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
|
| 1779 |
+
def test_loc_iloc_setitem_full_row_non_categorical_rhs(
|
| 1780 |
+
self, orig, exp_single_row, indexer
|
| 1781 |
+
):
|
| 1782 |
+
# - assign a complete row (mixed values) -> exp_single_row
|
| 1783 |
+
df = orig.copy()
|
| 1784 |
+
|
| 1785 |
+
key = 2
|
| 1786 |
+
if indexer is tm.loc:
|
| 1787 |
+
key = df.index[2]
|
| 1788 |
+
|
| 1789 |
+
# not categorical dtype, but "b" _is_ among the categories for df["cat"]
|
| 1790 |
+
indexer(df)[key, :] = ["b", 2]
|
| 1791 |
+
tm.assert_frame_equal(df, exp_single_row)
|
| 1792 |
+
|
| 1793 |
+
# "c" is not among the categories for df["cat"]
|
| 1794 |
+
with pytest.raises(TypeError, match=msg1):
|
| 1795 |
+
indexer(df)[key, :] = ["c", 2]
|
| 1796 |
+
|
| 1797 |
+
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
|
| 1798 |
+
def test_loc_iloc_setitem_partial_col_categorical_rhs(
|
| 1799 |
+
self, orig, exp_parts_cats_col, indexer
|
| 1800 |
+
):
|
| 1801 |
+
# assign a part of a column with dtype == categorical ->
|
| 1802 |
+
# exp_parts_cats_col
|
| 1803 |
+
df = orig.copy()
|
| 1804 |
+
|
| 1805 |
+
key = (slice(2, 4), 0)
|
| 1806 |
+
if indexer is tm.loc:
|
| 1807 |
+
key = (slice("j", "k"), df.columns[0])
|
| 1808 |
+
|
| 1809 |
+
# same categories as we currently have in df["cats"]
|
| 1810 |
+
compat = Categorical(["b", "b"], categories=["a", "b"])
|
| 1811 |
+
indexer(df)[key] = compat
|
| 1812 |
+
tm.assert_frame_equal(df, exp_parts_cats_col)
|
| 1813 |
+
|
| 1814 |
+
# categories do not match df["cat"]'s, but "b" is among them
|
| 1815 |
+
semi_compat = Categorical(list("bb"), categories=list("abc"))
|
| 1816 |
+
with pytest.raises(TypeError, match=msg2):
|
| 1817 |
+
# different categories but holdable values
|
| 1818 |
+
# -> not sure if this should fail or pass
|
| 1819 |
+
indexer(df)[key] = semi_compat
|
| 1820 |
+
|
| 1821 |
+
# categories do not match df["cat"]'s, and "c" is not among them
|
| 1822 |
+
incompat = Categorical(list("cc"), categories=list("abc"))
|
| 1823 |
+
with pytest.raises(TypeError, match=msg2):
|
| 1824 |
+
# different values
|
| 1825 |
+
indexer(df)[key] = incompat
|
| 1826 |
+
|
| 1827 |
+
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
|
| 1828 |
+
def test_loc_iloc_setitem_non_categorical_rhs(
|
| 1829 |
+
self, orig, exp_parts_cats_col, indexer
|
| 1830 |
+
):
|
| 1831 |
+
# assign a part of a column with dtype != categorical -> exp_parts_cats_col
|
| 1832 |
+
df = orig.copy()
|
| 1833 |
+
|
| 1834 |
+
key = (slice(2, 4), 0)
|
| 1835 |
+
if indexer is tm.loc:
|
| 1836 |
+
key = (slice("j", "k"), df.columns[0])
|
| 1837 |
+
|
| 1838 |
+
# "b" is among the categories for df["cat"]
|
| 1839 |
+
indexer(df)[key] = ["b", "b"]
|
| 1840 |
+
tm.assert_frame_equal(df, exp_parts_cats_col)
|
| 1841 |
+
|
| 1842 |
+
# "c" not part of the categories
|
| 1843 |
+
with pytest.raises(TypeError, match=msg1):
|
| 1844 |
+
indexer(df)[key] = ["c", "c"]
|
| 1845 |
+
|
| 1846 |
+
@pytest.mark.parametrize("indexer", [tm.getitem, tm.loc, tm.iloc])
|
| 1847 |
+
def test_getitem_preserve_object_index_with_dates(self, indexer):
|
| 1848 |
+
# https://github.com/pandas-dev/pandas/pull/42950 - when selecting a column
|
| 1849 |
+
# from dataframe, don't try to infer object dtype index on Series construction
|
| 1850 |
+
idx = date_range("2012", periods=3).astype(object)
|
| 1851 |
+
df = DataFrame({0: [1, 2, 3]}, index=idx)
|
| 1852 |
+
assert df.index.dtype == object
|
| 1853 |
+
|
| 1854 |
+
if indexer is tm.getitem:
|
| 1855 |
+
ser = indexer(df)[0]
|
| 1856 |
+
else:
|
| 1857 |
+
ser = indexer(df)[:, 0]
|
| 1858 |
+
|
| 1859 |
+
assert ser.index.dtype == object
|
| 1860 |
+
|
| 1861 |
+
def test_loc_on_multiindex_one_level(self):
|
| 1862 |
+
# GH#45779
|
| 1863 |
+
df = DataFrame(
|
| 1864 |
+
data=[[0], [1]],
|
| 1865 |
+
index=MultiIndex.from_tuples([("a",), ("b",)], names=["first"]),
|
| 1866 |
+
)
|
| 1867 |
+
expected = DataFrame(
|
| 1868 |
+
data=[[0]], index=MultiIndex.from_tuples([("a",)], names=["first"])
|
| 1869 |
+
)
|
| 1870 |
+
result = df.loc["a"]
|
| 1871 |
+
tm.assert_frame_equal(result, expected)
|
| 1872 |
+
|
| 1873 |
+
|
| 1874 |
+
class TestDeprecatedIndexers:
|
| 1875 |
+
@pytest.mark.parametrize(
|
| 1876 |
+
"key", [{1}, {1: 1}, ({1}, "a"), ({1: 1}, "a"), (1, {"a"}), (1, {"a": "a"})]
|
| 1877 |
+
)
|
| 1878 |
+
def test_getitem_dict_and_set_deprecated(self, key):
|
| 1879 |
+
# GH#42825 enforced in 2.0
|
| 1880 |
+
df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
|
| 1881 |
+
with pytest.raises(TypeError, match="as an indexer is not supported"):
|
| 1882 |
+
df.loc[key]
|
| 1883 |
+
|
| 1884 |
+
@pytest.mark.parametrize(
|
| 1885 |
+
"key",
|
| 1886 |
+
[
|
| 1887 |
+
{1},
|
| 1888 |
+
{1: 1},
|
| 1889 |
+
(({1}, 2), "a"),
|
| 1890 |
+
(({1: 1}, 2), "a"),
|
| 1891 |
+
((1, 2), {"a"}),
|
| 1892 |
+
((1, 2), {"a": "a"}),
|
| 1893 |
+
],
|
| 1894 |
+
)
|
| 1895 |
+
def test_getitem_dict_and_set_deprecated_multiindex(self, key):
|
| 1896 |
+
# GH#42825 enforced in 2.0
|
| 1897 |
+
df = DataFrame(
|
| 1898 |
+
[[1, 2], [3, 4]],
|
| 1899 |
+
columns=["a", "b"],
|
| 1900 |
+
index=MultiIndex.from_tuples([(1, 2), (3, 4)]),
|
| 1901 |
+
)
|
| 1902 |
+
with pytest.raises(TypeError, match="as an indexer is not supported"):
|
| 1903 |
+
df.loc[key]
|
| 1904 |
+
|
| 1905 |
+
@pytest.mark.parametrize(
|
| 1906 |
+
"key", [{1}, {1: 1}, ({1}, "a"), ({1: 1}, "a"), (1, {"a"}), (1, {"a": "a"})]
|
| 1907 |
+
)
|
| 1908 |
+
def test_setitem_dict_and_set_disallowed(self, key):
|
| 1909 |
+
# GH#42825 enforced in 2.0
|
| 1910 |
+
df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
|
| 1911 |
+
with pytest.raises(TypeError, match="as an indexer is not supported"):
|
| 1912 |
+
df.loc[key] = 1
|
| 1913 |
+
|
| 1914 |
+
@pytest.mark.parametrize(
|
| 1915 |
+
"key",
|
| 1916 |
+
[
|
| 1917 |
+
{1},
|
| 1918 |
+
{1: 1},
|
| 1919 |
+
(({1}, 2), "a"),
|
| 1920 |
+
(({1: 1}, 2), "a"),
|
| 1921 |
+
((1, 2), {"a"}),
|
| 1922 |
+
((1, 2), {"a": "a"}),
|
| 1923 |
+
],
|
| 1924 |
+
)
|
| 1925 |
+
def test_setitem_dict_and_set_disallowed_multiindex(self, key):
|
| 1926 |
+
# GH#42825 enforced in 2.0
|
| 1927 |
+
df = DataFrame(
|
| 1928 |
+
[[1, 2], [3, 4]],
|
| 1929 |
+
columns=["a", "b"],
|
| 1930 |
+
index=MultiIndex.from_tuples([(1, 2), (3, 4)]),
|
| 1931 |
+
)
|
| 1932 |
+
with pytest.raises(TypeError, match="as an indexer is not supported"):
|
| 1933 |
+
df.loc[key] = 1
|
| 1934 |
+
|
| 1935 |
+
|
| 1936 |
+
def test_adding_new_conditional_column() -> None:
|
| 1937 |
+
# https://github.com/pandas-dev/pandas/issues/55025
|
| 1938 |
+
df = DataFrame({"x": [1]})
|
| 1939 |
+
df.loc[df["x"] == 1, "y"] = "1"
|
| 1940 |
+
expected = DataFrame({"x": [1], "y": ["1"]})
|
| 1941 |
+
tm.assert_frame_equal(df, expected)
|
| 1942 |
+
|
| 1943 |
+
df = DataFrame({"x": [1]})
|
| 1944 |
+
# try inserting something which numpy would store as 'object'
|
| 1945 |
+
value = lambda x: x
|
| 1946 |
+
df.loc[df["x"] == 1, "y"] = value
|
| 1947 |
+
expected = DataFrame({"x": [1], "y": [value]})
|
| 1948 |
+
tm.assert_frame_equal(df, expected)
|
| 1949 |
+
|
| 1950 |
+
|
| 1951 |
+
@pytest.mark.parametrize(
|
| 1952 |
+
("dtype", "infer_string"),
|
| 1953 |
+
[
|
| 1954 |
+
(object, False),
|
| 1955 |
+
(pd.StringDtype(na_value=np.nan), True),
|
| 1956 |
+
],
|
| 1957 |
+
)
|
| 1958 |
+
def test_adding_new_conditional_column_with_string(dtype, infer_string) -> None:
|
| 1959 |
+
# https://github.com/pandas-dev/pandas/issues/56204
|
| 1960 |
+
df = DataFrame({"a": [1, 2], "b": [3, 4]})
|
| 1961 |
+
with pd.option_context("future.infer_string", infer_string):
|
| 1962 |
+
df.loc[df["a"] == 1, "c"] = "1"
|
| 1963 |
+
expected = DataFrame({"a": [1, 2], "b": [3, 4], "c": ["1", float("nan")]}).astype(
|
| 1964 |
+
{"a": "int64", "b": "int64", "c": dtype}
|
| 1965 |
+
)
|
| 1966 |
+
tm.assert_frame_equal(df, expected)
|
| 1967 |
+
|
| 1968 |
+
|
| 1969 |
+
def test_add_new_column_infer_string():
|
| 1970 |
+
# GH#55366
|
| 1971 |
+
df = DataFrame({"x": [1]})
|
| 1972 |
+
with pd.option_context("future.infer_string", True):
|
| 1973 |
+
df.loc[df["x"] == 1, "y"] = "1"
|
| 1974 |
+
expected = DataFrame(
|
| 1975 |
+
{"x": [1], "y": Series(["1"], dtype=pd.StringDtype(na_value=np.nan))},
|
| 1976 |
+
columns=Index(["x", "y"], dtype="str"),
|
| 1977 |
+
)
|
| 1978 |
+
tm.assert_frame_equal(df, expected)
|
| 1979 |
+
|
| 1980 |
+
|
| 1981 |
+
class TestSetitemValidation:
|
| 1982 |
+
# This is adapted from pandas/tests/arrays/masked/test_indexing.py
|
| 1983 |
+
# but checks for warnings instead of errors.
|
| 1984 |
+
def _check_setitem_invalid(self, df, invalid, indexer, warn):
|
| 1985 |
+
msg = "Setting an item of incompatible dtype is deprecated"
|
| 1986 |
+
msg = re.escape(msg)
|
| 1987 |
+
|
| 1988 |
+
orig_df = df.copy()
|
| 1989 |
+
|
| 1990 |
+
# iloc
|
| 1991 |
+
with tm.assert_produces_warning(warn, match=msg):
|
| 1992 |
+
df.iloc[indexer, 0] = invalid
|
| 1993 |
+
df = orig_df.copy()
|
| 1994 |
+
|
| 1995 |
+
# loc
|
| 1996 |
+
with tm.assert_produces_warning(warn, match=msg):
|
| 1997 |
+
df.loc[indexer, "a"] = invalid
|
| 1998 |
+
df = orig_df.copy()
|
| 1999 |
+
|
| 2000 |
+
_invalid_scalars = [
|
| 2001 |
+
1 + 2j,
|
| 2002 |
+
"True",
|
| 2003 |
+
"1",
|
| 2004 |
+
"1.0",
|
| 2005 |
+
pd.NaT,
|
| 2006 |
+
np.datetime64("NaT"),
|
| 2007 |
+
np.timedelta64("NaT"),
|
| 2008 |
+
]
|
| 2009 |
+
_indexers = [0, [0], slice(0, 1), [True, False, False], slice(None, None, None)]
|
| 2010 |
+
|
| 2011 |
+
@pytest.mark.parametrize(
|
| 2012 |
+
"invalid", _invalid_scalars + [1, 1.0, np.int64(1), np.float64(1)]
|
| 2013 |
+
)
|
| 2014 |
+
@pytest.mark.parametrize("indexer", _indexers)
|
| 2015 |
+
def test_setitem_validation_scalar_bool(self, invalid, indexer):
|
| 2016 |
+
df = DataFrame({"a": [True, False, False]}, dtype="bool")
|
| 2017 |
+
self._check_setitem_invalid(df, invalid, indexer, FutureWarning)
|
| 2018 |
+
|
| 2019 |
+
@pytest.mark.parametrize("invalid", _invalid_scalars + [True, 1.5, np.float64(1.5)])
|
| 2020 |
+
@pytest.mark.parametrize("indexer", _indexers)
|
| 2021 |
+
def test_setitem_validation_scalar_int(self, invalid, any_int_numpy_dtype, indexer):
|
| 2022 |
+
df = DataFrame({"a": [1, 2, 3]}, dtype=any_int_numpy_dtype)
|
| 2023 |
+
if isna(invalid) and invalid is not pd.NaT and not np.isnat(invalid):
|
| 2024 |
+
warn = None
|
| 2025 |
+
else:
|
| 2026 |
+
warn = FutureWarning
|
| 2027 |
+
self._check_setitem_invalid(df, invalid, indexer, warn)
|
| 2028 |
+
|
| 2029 |
+
@pytest.mark.parametrize("invalid", _invalid_scalars + [True])
|
| 2030 |
+
@pytest.mark.parametrize("indexer", _indexers)
|
| 2031 |
+
def test_setitem_validation_scalar_float(self, invalid, float_numpy_dtype, indexer):
|
| 2032 |
+
df = DataFrame({"a": [1, 2, None]}, dtype=float_numpy_dtype)
|
| 2033 |
+
self._check_setitem_invalid(df, invalid, indexer, FutureWarning)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_insert.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_insert is specifically for the DataFrame.insert method; not to be
|
| 3 |
+
confused with tests with "insert" in their names that are really testing
|
| 4 |
+
__setitem__.
|
| 5 |
+
"""
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from pandas.errors import PerformanceWarning
|
| 10 |
+
|
| 11 |
+
from pandas import (
|
| 12 |
+
DataFrame,
|
| 13 |
+
Index,
|
| 14 |
+
)
|
| 15 |
+
import pandas._testing as tm
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TestDataFrameInsert:
|
| 19 |
+
def test_insert(self):
|
| 20 |
+
df = DataFrame(
|
| 21 |
+
np.random.default_rng(2).standard_normal((5, 3)),
|
| 22 |
+
index=np.arange(5),
|
| 23 |
+
columns=["c", "b", "a"],
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
df.insert(0, "foo", df["a"])
|
| 27 |
+
tm.assert_index_equal(df.columns, Index(["foo", "c", "b", "a"]))
|
| 28 |
+
tm.assert_series_equal(df["a"], df["foo"], check_names=False)
|
| 29 |
+
|
| 30 |
+
df.insert(2, "bar", df["c"])
|
| 31 |
+
tm.assert_index_equal(df.columns, Index(["foo", "c", "bar", "b", "a"]))
|
| 32 |
+
tm.assert_almost_equal(df["c"], df["bar"], check_names=False)
|
| 33 |
+
|
| 34 |
+
with pytest.raises(ValueError, match="already exists"):
|
| 35 |
+
df.insert(1, "a", df["b"])
|
| 36 |
+
|
| 37 |
+
msg = "cannot insert c, already exists"
|
| 38 |
+
with pytest.raises(ValueError, match=msg):
|
| 39 |
+
df.insert(1, "c", df["b"])
|
| 40 |
+
|
| 41 |
+
df.columns.name = "some_name"
|
| 42 |
+
# preserve columns name field
|
| 43 |
+
df.insert(0, "baz", df["c"])
|
| 44 |
+
assert df.columns.name == "some_name"
|
| 45 |
+
|
| 46 |
+
def test_insert_column_bug_4032(self):
|
| 47 |
+
# GH#4032, inserting a column and renaming causing errors
|
| 48 |
+
df = DataFrame({"b": [1.1, 2.2]})
|
| 49 |
+
|
| 50 |
+
df = df.rename(columns={})
|
| 51 |
+
df.insert(0, "a", [1, 2])
|
| 52 |
+
result = df.rename(columns={})
|
| 53 |
+
|
| 54 |
+
expected = DataFrame([[1, 1.1], [2, 2.2]], columns=["a", "b"])
|
| 55 |
+
tm.assert_frame_equal(result, expected)
|
| 56 |
+
|
| 57 |
+
df.insert(0, "c", [1.3, 2.3])
|
| 58 |
+
result = df.rename(columns={})
|
| 59 |
+
|
| 60 |
+
expected = DataFrame([[1.3, 1, 1.1], [2.3, 2, 2.2]], columns=["c", "a", "b"])
|
| 61 |
+
tm.assert_frame_equal(result, expected)
|
| 62 |
+
|
| 63 |
+
def test_insert_with_columns_dups(self):
|
| 64 |
+
# GH#14291
|
| 65 |
+
df = DataFrame()
|
| 66 |
+
df.insert(0, "A", ["g", "h", "i"], allow_duplicates=True)
|
| 67 |
+
df.insert(0, "A", ["d", "e", "f"], allow_duplicates=True)
|
| 68 |
+
df.insert(0, "A", ["a", "b", "c"], allow_duplicates=True)
|
| 69 |
+
exp = DataFrame(
|
| 70 |
+
[["a", "d", "g"], ["b", "e", "h"], ["c", "f", "i"]], columns=["A", "A", "A"]
|
| 71 |
+
)
|
| 72 |
+
tm.assert_frame_equal(df, exp)
|
| 73 |
+
|
| 74 |
+
def test_insert_item_cache(self, using_array_manager, using_copy_on_write):
|
| 75 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((4, 3)))
|
| 76 |
+
ser = df[0]
|
| 77 |
+
|
| 78 |
+
if using_array_manager:
|
| 79 |
+
expected_warning = None
|
| 80 |
+
else:
|
| 81 |
+
# with BlockManager warn about high fragmentation of single dtype
|
| 82 |
+
expected_warning = PerformanceWarning
|
| 83 |
+
|
| 84 |
+
with tm.assert_produces_warning(expected_warning):
|
| 85 |
+
for n in range(100):
|
| 86 |
+
df[n + 3] = df[1] * n
|
| 87 |
+
|
| 88 |
+
if using_copy_on_write:
|
| 89 |
+
ser.iloc[0] = 99
|
| 90 |
+
assert df.iloc[0, 0] == df[0][0]
|
| 91 |
+
assert df.iloc[0, 0] != 99
|
| 92 |
+
else:
|
| 93 |
+
ser.values[0] = 99
|
| 94 |
+
assert df.iloc[0, 0] == df[0][0]
|
| 95 |
+
assert df.iloc[0, 0] == 99
|
| 96 |
+
|
| 97 |
+
def test_insert_EA_no_warning(self):
|
| 98 |
+
# PerformanceWarning about fragmented frame should not be raised when
|
| 99 |
+
# using EAs (https://github.com/pandas-dev/pandas/issues/44098)
|
| 100 |
+
df = DataFrame(
|
| 101 |
+
np.random.default_rng(2).integers(0, 100, size=(3, 100)), dtype="Int64"
|
| 102 |
+
)
|
| 103 |
+
with tm.assert_produces_warning(None):
|
| 104 |
+
df["a"] = np.array([1, 2, 3])
|
| 105 |
+
|
| 106 |
+
def test_insert_frame(self):
|
| 107 |
+
# GH#42403
|
| 108 |
+
df = DataFrame({"col1": [1, 2], "col2": [3, 4]})
|
| 109 |
+
|
| 110 |
+
msg = (
|
| 111 |
+
"Expected a one-dimensional object, got a DataFrame with 2 columns instead."
|
| 112 |
+
)
|
| 113 |
+
with pytest.raises(ValueError, match=msg):
|
| 114 |
+
df.insert(1, "newcol", df)
|
| 115 |
+
|
| 116 |
+
def test_insert_int64_loc(self):
|
| 117 |
+
# GH#53193
|
| 118 |
+
df = DataFrame({"a": [1, 2]})
|
| 119 |
+
df.insert(np.int64(0), "b", 0)
|
| 120 |
+
tm.assert_frame_equal(df, DataFrame({"b": [0, 0], "a": [1, 2]}))
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_mask.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests for DataFrame.mask; tests DataFrame.where as a side-effect.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from pandas import (
|
| 8 |
+
NA,
|
| 9 |
+
DataFrame,
|
| 10 |
+
Float64Dtype,
|
| 11 |
+
Series,
|
| 12 |
+
StringDtype,
|
| 13 |
+
Timedelta,
|
| 14 |
+
isna,
|
| 15 |
+
)
|
| 16 |
+
import pandas._testing as tm
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestDataFrameMask:
|
| 20 |
+
def test_mask(self):
|
| 21 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
|
| 22 |
+
cond = df > 0
|
| 23 |
+
|
| 24 |
+
rs = df.where(cond, np.nan)
|
| 25 |
+
tm.assert_frame_equal(rs, df.mask(df <= 0))
|
| 26 |
+
tm.assert_frame_equal(rs, df.mask(~cond))
|
| 27 |
+
|
| 28 |
+
other = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
|
| 29 |
+
rs = df.where(cond, other)
|
| 30 |
+
tm.assert_frame_equal(rs, df.mask(df <= 0, other))
|
| 31 |
+
tm.assert_frame_equal(rs, df.mask(~cond, other))
|
| 32 |
+
|
| 33 |
+
def test_mask2(self):
|
| 34 |
+
# see GH#21891
|
| 35 |
+
df = DataFrame([1, 2])
|
| 36 |
+
res = df.mask([[True], [False]])
|
| 37 |
+
|
| 38 |
+
exp = DataFrame([np.nan, 2])
|
| 39 |
+
tm.assert_frame_equal(res, exp)
|
| 40 |
+
|
| 41 |
+
def test_mask_inplace(self):
|
| 42 |
+
# GH#8801
|
| 43 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
|
| 44 |
+
cond = df > 0
|
| 45 |
+
|
| 46 |
+
rdf = df.copy()
|
| 47 |
+
|
| 48 |
+
return_value = rdf.where(cond, inplace=True)
|
| 49 |
+
assert return_value is None
|
| 50 |
+
tm.assert_frame_equal(rdf, df.where(cond))
|
| 51 |
+
tm.assert_frame_equal(rdf, df.mask(~cond))
|
| 52 |
+
|
| 53 |
+
rdf = df.copy()
|
| 54 |
+
return_value = rdf.where(cond, -df, inplace=True)
|
| 55 |
+
assert return_value is None
|
| 56 |
+
tm.assert_frame_equal(rdf, df.where(cond, -df))
|
| 57 |
+
tm.assert_frame_equal(rdf, df.mask(~cond, -df))
|
| 58 |
+
|
| 59 |
+
def test_mask_edge_case_1xN_frame(self):
|
| 60 |
+
# GH#4071
|
| 61 |
+
df = DataFrame([[1, 2]])
|
| 62 |
+
res = df.mask(DataFrame([[True, False]]))
|
| 63 |
+
expec = DataFrame([[np.nan, 2]])
|
| 64 |
+
tm.assert_frame_equal(res, expec)
|
| 65 |
+
|
| 66 |
+
def test_mask_callable(self):
|
| 67 |
+
# GH#12533
|
| 68 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 69 |
+
result = df.mask(lambda x: x > 4, lambda x: x + 1)
|
| 70 |
+
exp = DataFrame([[1, 2, 3], [4, 6, 7], [8, 9, 10]])
|
| 71 |
+
tm.assert_frame_equal(result, exp)
|
| 72 |
+
tm.assert_frame_equal(result, df.mask(df > 4, df + 1))
|
| 73 |
+
|
| 74 |
+
# return ndarray and scalar
|
| 75 |
+
result = df.mask(lambda x: (x % 2 == 0).values, lambda x: 99)
|
| 76 |
+
exp = DataFrame([[1, 99, 3], [99, 5, 99], [7, 99, 9]])
|
| 77 |
+
tm.assert_frame_equal(result, exp)
|
| 78 |
+
tm.assert_frame_equal(result, df.mask(df % 2 == 0, 99))
|
| 79 |
+
|
| 80 |
+
# chain
|
| 81 |
+
result = (df + 2).mask(lambda x: x > 8, lambda x: x + 10)
|
| 82 |
+
exp = DataFrame([[3, 4, 5], [6, 7, 8], [19, 20, 21]])
|
| 83 |
+
tm.assert_frame_equal(result, exp)
|
| 84 |
+
tm.assert_frame_equal(result, (df + 2).mask((df + 2) > 8, (df + 2) + 10))
|
| 85 |
+
|
| 86 |
+
def test_mask_dtype_bool_conversion(self):
|
| 87 |
+
# GH#3733
|
| 88 |
+
df = DataFrame(data=np.random.default_rng(2).standard_normal((100, 50)))
|
| 89 |
+
df = df.where(df > 0) # create nans
|
| 90 |
+
bools = df > 0
|
| 91 |
+
mask = isna(df)
|
| 92 |
+
expected = bools.astype(object).mask(mask)
|
| 93 |
+
result = bools.mask(mask)
|
| 94 |
+
tm.assert_frame_equal(result, expected)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_mask_stringdtype(frame_or_series):
|
| 98 |
+
# GH 40824
|
| 99 |
+
obj = DataFrame(
|
| 100 |
+
{"A": ["foo", "bar", "baz", NA]},
|
| 101 |
+
index=["id1", "id2", "id3", "id4"],
|
| 102 |
+
dtype=StringDtype(),
|
| 103 |
+
)
|
| 104 |
+
filtered_obj = DataFrame(
|
| 105 |
+
{"A": ["this", "that"]}, index=["id2", "id3"], dtype=StringDtype()
|
| 106 |
+
)
|
| 107 |
+
expected = DataFrame(
|
| 108 |
+
{"A": [NA, "this", "that", NA]},
|
| 109 |
+
index=["id1", "id2", "id3", "id4"],
|
| 110 |
+
dtype=StringDtype(),
|
| 111 |
+
)
|
| 112 |
+
if frame_or_series is Series:
|
| 113 |
+
obj = obj["A"]
|
| 114 |
+
filtered_obj = filtered_obj["A"]
|
| 115 |
+
expected = expected["A"]
|
| 116 |
+
|
| 117 |
+
filter_ser = Series([False, True, True, False])
|
| 118 |
+
result = obj.mask(filter_ser, filtered_obj)
|
| 119 |
+
|
| 120 |
+
tm.assert_equal(result, expected)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_mask_where_dtype_timedelta():
|
| 124 |
+
# https://github.com/pandas-dev/pandas/issues/39548
|
| 125 |
+
df = DataFrame([Timedelta(i, unit="d") for i in range(5)])
|
| 126 |
+
|
| 127 |
+
expected = DataFrame(np.full(5, np.nan, dtype="timedelta64[ns]"))
|
| 128 |
+
tm.assert_frame_equal(df.mask(df.notna()), expected)
|
| 129 |
+
|
| 130 |
+
expected = DataFrame(
|
| 131 |
+
[np.nan, np.nan, np.nan, Timedelta("3 day"), Timedelta("4 day")]
|
| 132 |
+
)
|
| 133 |
+
tm.assert_frame_equal(df.where(df > Timedelta(2, unit="d")), expected)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def test_mask_return_dtype():
|
| 137 |
+
# GH#50488
|
| 138 |
+
ser = Series([0.0, 1.0, 2.0, 3.0], dtype=Float64Dtype())
|
| 139 |
+
cond = ~ser.isna()
|
| 140 |
+
other = Series([True, False, True, False])
|
| 141 |
+
excepted = Series([1.0, 0.0, 1.0, 0.0], dtype=ser.dtype)
|
| 142 |
+
result = ser.mask(cond, other)
|
| 143 |
+
tm.assert_series_equal(result, excepted)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def test_mask_inplace_no_other():
|
| 147 |
+
# GH#51685
|
| 148 |
+
df = DataFrame({"a": [1.0, 2.0], "b": ["x", "y"]})
|
| 149 |
+
cond = DataFrame({"a": [True, False], "b": [False, True]})
|
| 150 |
+
df.mask(cond, inplace=True)
|
| 151 |
+
expected = DataFrame({"a": [np.nan, 2], "b": ["x", np.nan]})
|
| 152 |
+
tm.assert_frame_equal(df, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_set_value.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from pandas.core.dtypes.common import is_float_dtype
|
| 4 |
+
|
| 5 |
+
from pandas import (
|
| 6 |
+
DataFrame,
|
| 7 |
+
isna,
|
| 8 |
+
)
|
| 9 |
+
import pandas._testing as tm
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestSetValue:
|
| 13 |
+
def test_set_value(self, float_frame):
|
| 14 |
+
for idx in float_frame.index:
|
| 15 |
+
for col in float_frame.columns:
|
| 16 |
+
float_frame._set_value(idx, col, 1)
|
| 17 |
+
assert float_frame[col][idx] == 1
|
| 18 |
+
|
| 19 |
+
def test_set_value_resize(self, float_frame, using_infer_string):
|
| 20 |
+
res = float_frame._set_value("foobar", "B", 0)
|
| 21 |
+
assert res is None
|
| 22 |
+
assert float_frame.index[-1] == "foobar"
|
| 23 |
+
assert float_frame._get_value("foobar", "B") == 0
|
| 24 |
+
|
| 25 |
+
float_frame.loc["foobar", "qux"] = 0
|
| 26 |
+
assert float_frame._get_value("foobar", "qux") == 0
|
| 27 |
+
|
| 28 |
+
res = float_frame.copy()
|
| 29 |
+
res._set_value("foobar", "baz", "sam")
|
| 30 |
+
if using_infer_string:
|
| 31 |
+
assert res["baz"].dtype == "str"
|
| 32 |
+
else:
|
| 33 |
+
assert res["baz"].dtype == np.object_
|
| 34 |
+
res = float_frame.copy()
|
| 35 |
+
res._set_value("foobar", "baz", True)
|
| 36 |
+
assert res["baz"].dtype == np.object_
|
| 37 |
+
|
| 38 |
+
res = float_frame.copy()
|
| 39 |
+
res._set_value("foobar", "baz", 5)
|
| 40 |
+
assert is_float_dtype(res["baz"])
|
| 41 |
+
assert isna(res["baz"].drop(["foobar"])).all()
|
| 42 |
+
|
| 43 |
+
with tm.assert_produces_warning(
|
| 44 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 45 |
+
):
|
| 46 |
+
res._set_value("foobar", "baz", "sam")
|
| 47 |
+
assert res.loc["foobar", "baz"] == "sam"
|
| 48 |
+
|
| 49 |
+
def test_set_value_with_index_dtype_change(self):
|
| 50 |
+
df_orig = DataFrame(
|
| 51 |
+
np.random.default_rng(2).standard_normal((3, 3)),
|
| 52 |
+
index=range(3),
|
| 53 |
+
columns=list("ABC"),
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# this is actually ambiguous as the 2 is interpreted as a positional
|
| 57 |
+
# so column is not created
|
| 58 |
+
df = df_orig.copy()
|
| 59 |
+
df._set_value("C", 2, 1.0)
|
| 60 |
+
assert list(df.index) == list(df_orig.index) + ["C"]
|
| 61 |
+
# assert list(df.columns) == list(df_orig.columns) + [2]
|
| 62 |
+
|
| 63 |
+
df = df_orig.copy()
|
| 64 |
+
df.loc["C", 2] = 1.0
|
| 65 |
+
assert list(df.index) == list(df_orig.index) + ["C"]
|
| 66 |
+
# assert list(df.columns) == list(df_orig.columns) + [2]
|
| 67 |
+
|
| 68 |
+
# create both new
|
| 69 |
+
df = df_orig.copy()
|
| 70 |
+
df._set_value("C", "D", 1.0)
|
| 71 |
+
assert list(df.index) == list(df_orig.index) + ["C"]
|
| 72 |
+
assert list(df.columns) == list(df_orig.columns) + ["D"]
|
| 73 |
+
|
| 74 |
+
df = df_orig.copy()
|
| 75 |
+
df.loc["C", "D"] = 1.0
|
| 76 |
+
assert list(df.index) == list(df_orig.index) + ["C"]
|
| 77 |
+
assert list(df.columns) == list(df_orig.columns) + ["D"]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_setitem.py
ADDED
|
@@ -0,0 +1,1526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas.errors import SettingWithCopyWarning
|
| 7 |
+
import pandas.util._test_decorators as td
|
| 8 |
+
|
| 9 |
+
from pandas.core.dtypes.base import _registry as ea_registry
|
| 10 |
+
from pandas.core.dtypes.common import is_object_dtype
|
| 11 |
+
from pandas.core.dtypes.dtypes import (
|
| 12 |
+
CategoricalDtype,
|
| 13 |
+
DatetimeTZDtype,
|
| 14 |
+
IntervalDtype,
|
| 15 |
+
PeriodDtype,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
import pandas as pd
|
| 19 |
+
from pandas import (
|
| 20 |
+
Categorical,
|
| 21 |
+
DataFrame,
|
| 22 |
+
DatetimeIndex,
|
| 23 |
+
Index,
|
| 24 |
+
Interval,
|
| 25 |
+
IntervalIndex,
|
| 26 |
+
MultiIndex,
|
| 27 |
+
NaT,
|
| 28 |
+
Period,
|
| 29 |
+
PeriodIndex,
|
| 30 |
+
Series,
|
| 31 |
+
Timestamp,
|
| 32 |
+
cut,
|
| 33 |
+
date_range,
|
| 34 |
+
notna,
|
| 35 |
+
period_range,
|
| 36 |
+
)
|
| 37 |
+
import pandas._testing as tm
|
| 38 |
+
from pandas.core.arrays import SparseArray
|
| 39 |
+
|
| 40 |
+
from pandas.tseries.offsets import BDay
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class TestDataFrameSetItem:
|
| 44 |
+
def test_setitem_str_subclass(self):
|
| 45 |
+
# GH#37366
|
| 46 |
+
class mystring(str):
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
data = ["2020-10-22 01:21:00+00:00"]
|
| 50 |
+
index = DatetimeIndex(data)
|
| 51 |
+
df = DataFrame({"a": [1]}, index=index)
|
| 52 |
+
df["b"] = 2
|
| 53 |
+
df[mystring("c")] = 3
|
| 54 |
+
expected = DataFrame({"a": [1], "b": [2], mystring("c"): [3]}, index=index)
|
| 55 |
+
tm.assert_equal(df, expected)
|
| 56 |
+
|
| 57 |
+
@pytest.mark.parametrize(
|
| 58 |
+
"dtype", ["int32", "int64", "uint32", "uint64", "float32", "float64"]
|
| 59 |
+
)
|
| 60 |
+
def test_setitem_dtype(self, dtype, float_frame):
|
| 61 |
+
# Use integers since casting negative floats to uints is undefined
|
| 62 |
+
arr = np.random.default_rng(2).integers(1, 10, len(float_frame))
|
| 63 |
+
|
| 64 |
+
float_frame[dtype] = np.array(arr, dtype=dtype)
|
| 65 |
+
assert float_frame[dtype].dtype.name == dtype
|
| 66 |
+
|
| 67 |
+
def test_setitem_list_not_dataframe(self, float_frame):
|
| 68 |
+
data = np.random.default_rng(2).standard_normal((len(float_frame), 2))
|
| 69 |
+
float_frame[["A", "B"]] = data
|
| 70 |
+
tm.assert_almost_equal(float_frame[["A", "B"]].values, data)
|
| 71 |
+
|
| 72 |
+
def test_setitem_error_msmgs(self):
|
| 73 |
+
# GH 7432
|
| 74 |
+
df = DataFrame(
|
| 75 |
+
{"bar": [1, 2, 3], "baz": ["d", "e", "f"]},
|
| 76 |
+
index=Index(["a", "b", "c"], name="foo"),
|
| 77 |
+
)
|
| 78 |
+
ser = Series(
|
| 79 |
+
["g", "h", "i", "j"],
|
| 80 |
+
index=Index(["a", "b", "c", "a"], name="foo"),
|
| 81 |
+
name="fiz",
|
| 82 |
+
)
|
| 83 |
+
msg = "cannot reindex on an axis with duplicate labels"
|
| 84 |
+
with pytest.raises(ValueError, match=msg):
|
| 85 |
+
df["newcol"] = ser
|
| 86 |
+
|
| 87 |
+
# GH 4107, more descriptive error message
|
| 88 |
+
df = DataFrame(
|
| 89 |
+
np.random.default_rng(2).integers(0, 2, (4, 4)),
|
| 90 |
+
columns=["a", "b", "c", "d"],
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
msg = "Cannot set a DataFrame with multiple columns to the single column gr"
|
| 94 |
+
with pytest.raises(ValueError, match=msg):
|
| 95 |
+
df["gr"] = df.groupby(["b", "c"]).count()
|
| 96 |
+
|
| 97 |
+
# GH 55956, specific message for zero columns
|
| 98 |
+
msg = "Cannot set a DataFrame without columns to the column gr"
|
| 99 |
+
with pytest.raises(ValueError, match=msg):
|
| 100 |
+
df["gr"] = DataFrame()
|
| 101 |
+
|
| 102 |
+
def test_setitem_benchmark(self):
|
| 103 |
+
# from the vb_suite/frame_methods/frame_insert_columns
|
| 104 |
+
N = 10
|
| 105 |
+
K = 5
|
| 106 |
+
df = DataFrame(index=range(N))
|
| 107 |
+
new_col = np.random.default_rng(2).standard_normal(N)
|
| 108 |
+
for i in range(K):
|
| 109 |
+
df[i] = new_col
|
| 110 |
+
expected = DataFrame(np.repeat(new_col, K).reshape(N, K), index=range(N))
|
| 111 |
+
tm.assert_frame_equal(df, expected)
|
| 112 |
+
|
| 113 |
+
def test_setitem_different_dtype(self):
|
| 114 |
+
df = DataFrame(
|
| 115 |
+
np.random.default_rng(2).standard_normal((5, 3)),
|
| 116 |
+
index=np.arange(5),
|
| 117 |
+
columns=["c", "b", "a"],
|
| 118 |
+
)
|
| 119 |
+
df.insert(0, "foo", df["a"])
|
| 120 |
+
df.insert(2, "bar", df["c"])
|
| 121 |
+
|
| 122 |
+
# diff dtype
|
| 123 |
+
|
| 124 |
+
# new item
|
| 125 |
+
df["x"] = df["a"].astype("float32")
|
| 126 |
+
result = df.dtypes
|
| 127 |
+
expected = Series(
|
| 128 |
+
[np.dtype("float64")] * 5 + [np.dtype("float32")],
|
| 129 |
+
index=["foo", "c", "bar", "b", "a", "x"],
|
| 130 |
+
)
|
| 131 |
+
tm.assert_series_equal(result, expected)
|
| 132 |
+
|
| 133 |
+
# replacing current (in different block)
|
| 134 |
+
df["a"] = df["a"].astype("float32")
|
| 135 |
+
result = df.dtypes
|
| 136 |
+
expected = Series(
|
| 137 |
+
[np.dtype("float64")] * 4 + [np.dtype("float32")] * 2,
|
| 138 |
+
index=["foo", "c", "bar", "b", "a", "x"],
|
| 139 |
+
)
|
| 140 |
+
tm.assert_series_equal(result, expected)
|
| 141 |
+
|
| 142 |
+
df["y"] = df["a"].astype("int32")
|
| 143 |
+
result = df.dtypes
|
| 144 |
+
expected = Series(
|
| 145 |
+
[np.dtype("float64")] * 4 + [np.dtype("float32")] * 2 + [np.dtype("int32")],
|
| 146 |
+
index=["foo", "c", "bar", "b", "a", "x", "y"],
|
| 147 |
+
)
|
| 148 |
+
tm.assert_series_equal(result, expected)
|
| 149 |
+
|
| 150 |
+
def test_setitem_overwrite_index(self):
|
| 151 |
+
# GH 13522 - assign the index as a column and then overwrite the values
|
| 152 |
+
# -> should not affect the index
|
| 153 |
+
df = DataFrame(index=["A", "B", "C"])
|
| 154 |
+
df["X"] = df.index
|
| 155 |
+
df["X"] = ["x", "y", "z"]
|
| 156 |
+
exp = DataFrame(
|
| 157 |
+
data={"X": ["x", "y", "z"]}, index=["A", "B", "C"], columns=["X"]
|
| 158 |
+
)
|
| 159 |
+
tm.assert_frame_equal(df, exp)
|
| 160 |
+
|
| 161 |
+
def test_setitem_empty_columns(self):
|
| 162 |
+
# Starting from an empty DataFrame and setting a column should result
|
| 163 |
+
# in a default string dtype for the columns' Index
|
| 164 |
+
# https://github.com/pandas-dev/pandas/issues/60338
|
| 165 |
+
|
| 166 |
+
df = DataFrame()
|
| 167 |
+
df["foo"] = [1, 2, 3]
|
| 168 |
+
expected = DataFrame({"foo": [1, 2, 3]})
|
| 169 |
+
tm.assert_frame_equal(df, expected)
|
| 170 |
+
|
| 171 |
+
df = DataFrame(columns=Index([]))
|
| 172 |
+
df["foo"] = [1, 2, 3]
|
| 173 |
+
expected = DataFrame({"foo": [1, 2, 3]})
|
| 174 |
+
tm.assert_frame_equal(df, expected)
|
| 175 |
+
|
| 176 |
+
def test_setitem_dt64_index_empty_columns(self):
|
| 177 |
+
rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s")
|
| 178 |
+
df = DataFrame(index=np.arange(len(rng)))
|
| 179 |
+
|
| 180 |
+
df["A"] = rng
|
| 181 |
+
assert df["A"].dtype == np.dtype("M8[ns]")
|
| 182 |
+
|
| 183 |
+
def test_setitem_timestamp_empty_columns(self):
|
| 184 |
+
# GH#19843
|
| 185 |
+
df = DataFrame(index=range(3))
|
| 186 |
+
df["now"] = Timestamp("20130101", tz="UTC").as_unit("ns")
|
| 187 |
+
|
| 188 |
+
expected = DataFrame(
|
| 189 |
+
[[Timestamp("20130101", tz="UTC")]] * 3, index=range(3), columns=["now"]
|
| 190 |
+
)
|
| 191 |
+
tm.assert_frame_equal(df, expected)
|
| 192 |
+
|
| 193 |
+
def test_setitem_wrong_length_categorical_dtype_raises(self):
|
| 194 |
+
# GH#29523
|
| 195 |
+
cat = Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"])
|
| 196 |
+
df = DataFrame(range(10), columns=["bar"])
|
| 197 |
+
|
| 198 |
+
msg = (
|
| 199 |
+
rf"Length of values \({len(cat)}\) "
|
| 200 |
+
rf"does not match length of index \({len(df)}\)"
|
| 201 |
+
)
|
| 202 |
+
with pytest.raises(ValueError, match=msg):
|
| 203 |
+
df["foo"] = cat
|
| 204 |
+
|
| 205 |
+
def test_setitem_with_sparse_value(self):
|
| 206 |
+
# GH#8131
|
| 207 |
+
df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]})
|
| 208 |
+
sp_array = SparseArray([0, 0, 1])
|
| 209 |
+
df["new_column"] = sp_array
|
| 210 |
+
|
| 211 |
+
expected = Series(sp_array, name="new_column")
|
| 212 |
+
tm.assert_series_equal(df["new_column"], expected)
|
| 213 |
+
|
| 214 |
+
def test_setitem_with_unaligned_sparse_value(self):
|
| 215 |
+
df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]})
|
| 216 |
+
sp_series = Series(SparseArray([0, 0, 1]), index=[2, 1, 0])
|
| 217 |
+
|
| 218 |
+
df["new_column"] = sp_series
|
| 219 |
+
expected = Series(SparseArray([1, 0, 0]), name="new_column")
|
| 220 |
+
tm.assert_series_equal(df["new_column"], expected)
|
| 221 |
+
|
| 222 |
+
def test_setitem_period_preserves_dtype(self):
|
| 223 |
+
# GH: 26861
|
| 224 |
+
data = [Period("2003-12", "D")]
|
| 225 |
+
result = DataFrame([])
|
| 226 |
+
result["a"] = data
|
| 227 |
+
|
| 228 |
+
expected = DataFrame({"a": data}, columns=["a"])
|
| 229 |
+
|
| 230 |
+
tm.assert_frame_equal(result, expected)
|
| 231 |
+
|
| 232 |
+
def test_setitem_dict_preserves_dtypes(self):
|
| 233 |
+
# https://github.com/pandas-dev/pandas/issues/34573
|
| 234 |
+
expected = DataFrame(
|
| 235 |
+
{
|
| 236 |
+
"a": Series([0, 1, 2], dtype="int64"),
|
| 237 |
+
"b": Series([1, 2, 3], dtype=float),
|
| 238 |
+
"c": Series([1, 2, 3], dtype=float),
|
| 239 |
+
"d": Series([1, 2, 3], dtype="uint32"),
|
| 240 |
+
}
|
| 241 |
+
)
|
| 242 |
+
df = DataFrame(
|
| 243 |
+
{
|
| 244 |
+
"a": Series([], dtype="int64"),
|
| 245 |
+
"b": Series([], dtype=float),
|
| 246 |
+
"c": Series([], dtype=float),
|
| 247 |
+
"d": Series([], dtype="uint32"),
|
| 248 |
+
}
|
| 249 |
+
)
|
| 250 |
+
for idx, b in enumerate([1, 2, 3]):
|
| 251 |
+
df.loc[df.shape[0]] = {
|
| 252 |
+
"a": int(idx),
|
| 253 |
+
"b": float(b),
|
| 254 |
+
"c": float(b),
|
| 255 |
+
"d": np.uint32(b),
|
| 256 |
+
}
|
| 257 |
+
tm.assert_frame_equal(df, expected)
|
| 258 |
+
|
| 259 |
+
@pytest.mark.parametrize(
|
| 260 |
+
"obj,dtype",
|
| 261 |
+
[
|
| 262 |
+
(Period("2020-01"), PeriodDtype("M")),
|
| 263 |
+
(Interval(left=0, right=5), IntervalDtype("int64", "right")),
|
| 264 |
+
(
|
| 265 |
+
Timestamp("2011-01-01", tz="US/Eastern"),
|
| 266 |
+
DatetimeTZDtype(unit="s", tz="US/Eastern"),
|
| 267 |
+
),
|
| 268 |
+
],
|
| 269 |
+
)
|
| 270 |
+
def test_setitem_extension_types(self, obj, dtype):
|
| 271 |
+
# GH: 34832
|
| 272 |
+
expected = DataFrame({"idx": [1, 2, 3], "obj": Series([obj] * 3, dtype=dtype)})
|
| 273 |
+
|
| 274 |
+
df = DataFrame({"idx": [1, 2, 3]})
|
| 275 |
+
df["obj"] = obj
|
| 276 |
+
|
| 277 |
+
tm.assert_frame_equal(df, expected)
|
| 278 |
+
|
| 279 |
+
@pytest.mark.parametrize(
|
| 280 |
+
"ea_name",
|
| 281 |
+
[
|
| 282 |
+
dtype.name
|
| 283 |
+
for dtype in ea_registry.dtypes
|
| 284 |
+
# property would require instantiation
|
| 285 |
+
if not isinstance(dtype.name, property)
|
| 286 |
+
]
|
| 287 |
+
+ ["datetime64[ns, UTC]", "period[D]"],
|
| 288 |
+
)
|
| 289 |
+
def test_setitem_with_ea_name(self, ea_name):
|
| 290 |
+
# GH 38386
|
| 291 |
+
result = DataFrame([0])
|
| 292 |
+
result[ea_name] = [1]
|
| 293 |
+
expected = DataFrame({0: [0], ea_name: [1]})
|
| 294 |
+
tm.assert_frame_equal(result, expected)
|
| 295 |
+
|
| 296 |
+
def test_setitem_dt64_ndarray_with_NaT_and_diff_time_units(self):
|
| 297 |
+
# GH#7492
|
| 298 |
+
data_ns = np.array([1, "nat"], dtype="datetime64[ns]")
|
| 299 |
+
result = Series(data_ns).to_frame()
|
| 300 |
+
result["new"] = data_ns
|
| 301 |
+
expected = DataFrame({0: [1, None], "new": [1, None]}, dtype="datetime64[ns]")
|
| 302 |
+
tm.assert_frame_equal(result, expected)
|
| 303 |
+
|
| 304 |
+
# OutOfBoundsDatetime error shouldn't occur; as of 2.0 we preserve "M8[s]"
|
| 305 |
+
data_s = np.array([1, "nat"], dtype="datetime64[s]")
|
| 306 |
+
result["new"] = data_s
|
| 307 |
+
tm.assert_series_equal(result[0], expected[0])
|
| 308 |
+
tm.assert_numpy_array_equal(result["new"].to_numpy(), data_s)
|
| 309 |
+
|
| 310 |
+
@pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"])
|
| 311 |
+
def test_frame_setitem_datetime64_col_other_units(self, unit):
|
| 312 |
+
# Check that non-nano dt64 values get cast to dt64 on setitem
|
| 313 |
+
# into a not-yet-existing column
|
| 314 |
+
n = 100
|
| 315 |
+
|
| 316 |
+
dtype = np.dtype(f"M8[{unit}]")
|
| 317 |
+
vals = np.arange(n, dtype=np.int64).view(dtype)
|
| 318 |
+
if unit in ["s", "ms"]:
|
| 319 |
+
# supported unit
|
| 320 |
+
ex_vals = vals
|
| 321 |
+
else:
|
| 322 |
+
# we get the nearest supported units, i.e. "s"
|
| 323 |
+
ex_vals = vals.astype("datetime64[s]")
|
| 324 |
+
|
| 325 |
+
df = DataFrame({"ints": np.arange(n)}, index=np.arange(n))
|
| 326 |
+
df[unit] = vals
|
| 327 |
+
|
| 328 |
+
assert df[unit].dtype == ex_vals.dtype
|
| 329 |
+
assert (df[unit].values == ex_vals).all()
|
| 330 |
+
|
| 331 |
+
@pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"])
|
| 332 |
+
def test_frame_setitem_existing_datetime64_col_other_units(self, unit):
|
| 333 |
+
# Check that non-nano dt64 values get cast to dt64 on setitem
|
| 334 |
+
# into an already-existing dt64 column
|
| 335 |
+
n = 100
|
| 336 |
+
|
| 337 |
+
dtype = np.dtype(f"M8[{unit}]")
|
| 338 |
+
vals = np.arange(n, dtype=np.int64).view(dtype)
|
| 339 |
+
ex_vals = vals.astype("datetime64[ns]")
|
| 340 |
+
|
| 341 |
+
df = DataFrame({"ints": np.arange(n)}, index=np.arange(n))
|
| 342 |
+
df["dates"] = np.arange(n, dtype=np.int64).view("M8[ns]")
|
| 343 |
+
|
| 344 |
+
# We overwrite existing dt64 column with new, non-nano dt64 vals
|
| 345 |
+
df["dates"] = vals
|
| 346 |
+
assert (df["dates"].values == ex_vals).all()
|
| 347 |
+
|
| 348 |
+
def test_setitem_dt64tz(self, timezone_frame, using_copy_on_write):
|
| 349 |
+
df = timezone_frame
|
| 350 |
+
idx = df["B"].rename("foo")
|
| 351 |
+
|
| 352 |
+
# setitem
|
| 353 |
+
df["C"] = idx
|
| 354 |
+
tm.assert_series_equal(df["C"], Series(idx, name="C"))
|
| 355 |
+
|
| 356 |
+
df["D"] = "foo"
|
| 357 |
+
df["D"] = idx
|
| 358 |
+
tm.assert_series_equal(df["D"], Series(idx, name="D"))
|
| 359 |
+
del df["D"]
|
| 360 |
+
|
| 361 |
+
# assert that A & C are not sharing the same base (e.g. they
|
| 362 |
+
# are copies)
|
| 363 |
+
# Note: This does not hold with Copy on Write (because of lazy copying)
|
| 364 |
+
v1 = df._mgr.arrays[1]
|
| 365 |
+
v2 = df._mgr.arrays[2]
|
| 366 |
+
tm.assert_extension_array_equal(v1, v2)
|
| 367 |
+
v1base = v1._ndarray.base
|
| 368 |
+
v2base = v2._ndarray.base
|
| 369 |
+
if not using_copy_on_write:
|
| 370 |
+
assert v1base is None or (id(v1base) != id(v2base))
|
| 371 |
+
else:
|
| 372 |
+
assert id(v1base) == id(v2base)
|
| 373 |
+
|
| 374 |
+
# with nan
|
| 375 |
+
df2 = df.copy()
|
| 376 |
+
df2.iloc[1, 1] = NaT
|
| 377 |
+
df2.iloc[1, 2] = NaT
|
| 378 |
+
result = df2["B"]
|
| 379 |
+
tm.assert_series_equal(notna(result), Series([True, False, True], name="B"))
|
| 380 |
+
tm.assert_series_equal(df2.dtypes, df.dtypes)
|
| 381 |
+
|
| 382 |
+
def test_setitem_periodindex(self):
|
| 383 |
+
rng = period_range("1/1/2000", periods=5, name="index")
|
| 384 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)), index=rng)
|
| 385 |
+
|
| 386 |
+
df["Index"] = rng
|
| 387 |
+
rs = Index(df["Index"])
|
| 388 |
+
tm.assert_index_equal(rs, rng, check_names=False)
|
| 389 |
+
assert rs.name == "Index"
|
| 390 |
+
assert rng.name == "index"
|
| 391 |
+
|
| 392 |
+
rs = df.reset_index().set_index("index")
|
| 393 |
+
assert isinstance(rs.index, PeriodIndex)
|
| 394 |
+
tm.assert_index_equal(rs.index, rng)
|
| 395 |
+
|
| 396 |
+
def test_setitem_complete_column_with_array(self):
|
| 397 |
+
# GH#37954
|
| 398 |
+
df = DataFrame({"a": ["one", "two", "three"], "b": [1, 2, 3]})
|
| 399 |
+
arr = np.array([[1, 1], [3, 1], [5, 1]])
|
| 400 |
+
df[["c", "d"]] = arr
|
| 401 |
+
expected = DataFrame(
|
| 402 |
+
{
|
| 403 |
+
"a": ["one", "two", "three"],
|
| 404 |
+
"b": [1, 2, 3],
|
| 405 |
+
"c": [1, 3, 5],
|
| 406 |
+
"d": [1, 1, 1],
|
| 407 |
+
}
|
| 408 |
+
)
|
| 409 |
+
expected["c"] = expected["c"].astype(arr.dtype)
|
| 410 |
+
expected["d"] = expected["d"].astype(arr.dtype)
|
| 411 |
+
assert expected["c"].dtype == arr.dtype
|
| 412 |
+
assert expected["d"].dtype == arr.dtype
|
| 413 |
+
tm.assert_frame_equal(df, expected)
|
| 414 |
+
|
| 415 |
+
def test_setitem_period_d_dtype(self):
|
| 416 |
+
# GH 39763
|
| 417 |
+
rng = period_range("2016-01-01", periods=9, freq="D", name="A")
|
| 418 |
+
result = DataFrame(rng)
|
| 419 |
+
expected = DataFrame(
|
| 420 |
+
{"A": ["NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT"]},
|
| 421 |
+
dtype="period[D]",
|
| 422 |
+
)
|
| 423 |
+
result.iloc[:] = rng._na_value
|
| 424 |
+
tm.assert_frame_equal(result, expected)
|
| 425 |
+
|
| 426 |
+
@pytest.mark.parametrize("dtype", ["f8", "i8", "u8"])
|
| 427 |
+
def test_setitem_bool_with_numeric_index(self, dtype):
|
| 428 |
+
# GH#36319
|
| 429 |
+
cols = Index([1, 2, 3], dtype=dtype)
|
| 430 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((3, 3)), columns=cols)
|
| 431 |
+
|
| 432 |
+
df[False] = ["a", "b", "c"]
|
| 433 |
+
|
| 434 |
+
expected_cols = Index([1, 2, 3, False], dtype=object)
|
| 435 |
+
if dtype == "f8":
|
| 436 |
+
expected_cols = Index([1.0, 2.0, 3.0, False], dtype=object)
|
| 437 |
+
|
| 438 |
+
tm.assert_index_equal(df.columns, expected_cols)
|
| 439 |
+
|
| 440 |
+
@pytest.mark.parametrize("indexer", ["B", ["B"]])
|
| 441 |
+
def test_setitem_frame_length_0_str_key(self, indexer):
|
| 442 |
+
# GH#38831
|
| 443 |
+
df = DataFrame(columns=["A", "B"])
|
| 444 |
+
other = DataFrame({"B": [1, 2]})
|
| 445 |
+
df[indexer] = other
|
| 446 |
+
expected = DataFrame({"A": [np.nan] * 2, "B": [1, 2]})
|
| 447 |
+
expected["A"] = expected["A"].astype("object")
|
| 448 |
+
tm.assert_frame_equal(df, expected)
|
| 449 |
+
|
| 450 |
+
def test_setitem_frame_duplicate_columns(self):
|
| 451 |
+
# GH#15695
|
| 452 |
+
cols = ["A", "B", "C"] * 2
|
| 453 |
+
df = DataFrame(index=range(3), columns=cols)
|
| 454 |
+
df.loc[0, "A"] = (0, 3)
|
| 455 |
+
df.loc[:, "B"] = (1, 4)
|
| 456 |
+
df["C"] = (2, 5)
|
| 457 |
+
expected = DataFrame(
|
| 458 |
+
[
|
| 459 |
+
[0, 1, 2, 3, 4, 5],
|
| 460 |
+
[np.nan, 1, 2, np.nan, 4, 5],
|
| 461 |
+
[np.nan, 1, 2, np.nan, 4, 5],
|
| 462 |
+
],
|
| 463 |
+
dtype="object",
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
# set these with unique columns to be extra-unambiguous
|
| 467 |
+
expected[2] = expected[2].astype(np.int64)
|
| 468 |
+
expected[5] = expected[5].astype(np.int64)
|
| 469 |
+
expected.columns = cols
|
| 470 |
+
|
| 471 |
+
tm.assert_frame_equal(df, expected)
|
| 472 |
+
|
| 473 |
+
def test_setitem_frame_duplicate_columns_size_mismatch(self):
|
| 474 |
+
# GH#39510
|
| 475 |
+
cols = ["A", "B", "C"] * 2
|
| 476 |
+
df = DataFrame(index=range(3), columns=cols)
|
| 477 |
+
with pytest.raises(ValueError, match="Columns must be same length as key"):
|
| 478 |
+
df[["A"]] = (0, 3, 5)
|
| 479 |
+
|
| 480 |
+
df2 = df.iloc[:, :3] # unique columns
|
| 481 |
+
with pytest.raises(ValueError, match="Columns must be same length as key"):
|
| 482 |
+
df2[["A"]] = (0, 3, 5)
|
| 483 |
+
|
| 484 |
+
@pytest.mark.parametrize("cols", [["a", "b", "c"], ["a", "a", "a"]])
|
| 485 |
+
def test_setitem_df_wrong_column_number(self, cols):
|
| 486 |
+
# GH#38604
|
| 487 |
+
df = DataFrame([[1, 2, 3]], columns=cols)
|
| 488 |
+
rhs = DataFrame([[10, 11]], columns=["d", "e"])
|
| 489 |
+
msg = "Columns must be same length as key"
|
| 490 |
+
with pytest.raises(ValueError, match=msg):
|
| 491 |
+
df["a"] = rhs
|
| 492 |
+
|
| 493 |
+
def test_setitem_listlike_indexer_duplicate_columns(self):
|
| 494 |
+
# GH#38604
|
| 495 |
+
df = DataFrame([[1, 2, 3]], columns=["a", "b", "b"])
|
| 496 |
+
rhs = DataFrame([[10, 11, 12]], columns=["a", "b", "b"])
|
| 497 |
+
df[["a", "b"]] = rhs
|
| 498 |
+
expected = DataFrame([[10, 11, 12]], columns=["a", "b", "b"])
|
| 499 |
+
tm.assert_frame_equal(df, expected)
|
| 500 |
+
|
| 501 |
+
df[["c", "b"]] = rhs
|
| 502 |
+
expected = DataFrame([[10, 11, 12, 10]], columns=["a", "b", "b", "c"])
|
| 503 |
+
tm.assert_frame_equal(df, expected)
|
| 504 |
+
|
| 505 |
+
def test_setitem_listlike_indexer_duplicate_columns_not_equal_length(self):
|
| 506 |
+
# GH#39403
|
| 507 |
+
df = DataFrame([[1, 2, 3]], columns=["a", "b", "b"])
|
| 508 |
+
rhs = DataFrame([[10, 11]], columns=["a", "b"])
|
| 509 |
+
msg = "Columns must be same length as key"
|
| 510 |
+
with pytest.raises(ValueError, match=msg):
|
| 511 |
+
df[["a", "b"]] = rhs
|
| 512 |
+
|
| 513 |
+
def test_setitem_intervals(self):
|
| 514 |
+
df = DataFrame({"A": range(10)})
|
| 515 |
+
ser = cut(df["A"], 5)
|
| 516 |
+
assert isinstance(ser.cat.categories, IntervalIndex)
|
| 517 |
+
|
| 518 |
+
# B & D end up as Categoricals
|
| 519 |
+
# the remainder are converted to in-line objects
|
| 520 |
+
# containing an IntervalIndex.values
|
| 521 |
+
df["B"] = ser
|
| 522 |
+
df["C"] = np.array(ser)
|
| 523 |
+
df["D"] = ser.values
|
| 524 |
+
df["E"] = np.array(ser.values)
|
| 525 |
+
df["F"] = ser.astype(object)
|
| 526 |
+
|
| 527 |
+
assert isinstance(df["B"].dtype, CategoricalDtype)
|
| 528 |
+
assert isinstance(df["B"].cat.categories.dtype, IntervalDtype)
|
| 529 |
+
assert isinstance(df["D"].dtype, CategoricalDtype)
|
| 530 |
+
assert isinstance(df["D"].cat.categories.dtype, IntervalDtype)
|
| 531 |
+
|
| 532 |
+
# These go through the Series constructor and so get inferred back
|
| 533 |
+
# to IntervalDtype
|
| 534 |
+
assert isinstance(df["C"].dtype, IntervalDtype)
|
| 535 |
+
assert isinstance(df["E"].dtype, IntervalDtype)
|
| 536 |
+
|
| 537 |
+
# But the Series constructor doesn't do inference on Series objects,
|
| 538 |
+
# so setting df["F"] doesn't get cast back to IntervalDtype
|
| 539 |
+
assert is_object_dtype(df["F"])
|
| 540 |
+
|
| 541 |
+
# they compare equal as Index
|
| 542 |
+
# when converted to numpy objects
|
| 543 |
+
c = lambda x: Index(np.array(x))
|
| 544 |
+
tm.assert_index_equal(c(df.B), c(df.B))
|
| 545 |
+
tm.assert_index_equal(c(df.B), c(df.C), check_names=False)
|
| 546 |
+
tm.assert_index_equal(c(df.B), c(df.D), check_names=False)
|
| 547 |
+
tm.assert_index_equal(c(df.C), c(df.D), check_names=False)
|
| 548 |
+
|
| 549 |
+
# B & D are the same Series
|
| 550 |
+
tm.assert_series_equal(df["B"], df["B"])
|
| 551 |
+
tm.assert_series_equal(df["B"], df["D"], check_names=False)
|
| 552 |
+
|
| 553 |
+
# C & E are the same Series
|
| 554 |
+
tm.assert_series_equal(df["C"], df["C"])
|
| 555 |
+
tm.assert_series_equal(df["C"], df["E"], check_names=False)
|
| 556 |
+
|
| 557 |
+
def test_setitem_categorical(self):
|
| 558 |
+
# GH#35369
|
| 559 |
+
df = DataFrame({"h": Series(list("mn")).astype("category")})
|
| 560 |
+
df.h = df.h.cat.reorder_categories(["n", "m"])
|
| 561 |
+
expected = DataFrame(
|
| 562 |
+
{"h": Categorical(["m", "n"]).reorder_categories(["n", "m"])}
|
| 563 |
+
)
|
| 564 |
+
tm.assert_frame_equal(df, expected)
|
| 565 |
+
|
| 566 |
+
def test_setitem_with_empty_listlike(self):
|
| 567 |
+
# GH#17101
|
| 568 |
+
index = Index([], name="idx")
|
| 569 |
+
result = DataFrame(columns=["A"], index=index)
|
| 570 |
+
result["A"] = []
|
| 571 |
+
expected = DataFrame(columns=["A"], index=index)
|
| 572 |
+
tm.assert_index_equal(result.index, expected.index)
|
| 573 |
+
|
| 574 |
+
@pytest.mark.parametrize(
|
| 575 |
+
"cols, values, expected",
|
| 576 |
+
[
|
| 577 |
+
(["C", "D", "D", "a"], [1, 2, 3, 4], 4), # with duplicates
|
| 578 |
+
(["D", "C", "D", "a"], [1, 2, 3, 4], 4), # mixed order
|
| 579 |
+
(["C", "B", "B", "a"], [1, 2, 3, 4], 4), # other duplicate cols
|
| 580 |
+
(["C", "B", "a"], [1, 2, 3], 3), # no duplicates
|
| 581 |
+
(["B", "C", "a"], [3, 2, 1], 1), # alphabetical order
|
| 582 |
+
(["C", "a", "B"], [3, 2, 1], 2), # in the middle
|
| 583 |
+
],
|
| 584 |
+
)
|
| 585 |
+
def test_setitem_same_column(self, cols, values, expected):
|
| 586 |
+
# GH#23239
|
| 587 |
+
df = DataFrame([values], columns=cols)
|
| 588 |
+
df["a"] = df["a"]
|
| 589 |
+
result = df["a"].values[0]
|
| 590 |
+
assert result == expected
|
| 591 |
+
|
| 592 |
+
def test_setitem_multi_index(self):
|
| 593 |
+
# GH#7655, test that assigning to a sub-frame of a frame
|
| 594 |
+
# with multi-index columns aligns both rows and columns
|
| 595 |
+
it = ["jim", "joe", "jolie"], ["first", "last"], ["left", "center", "right"]
|
| 596 |
+
|
| 597 |
+
cols = MultiIndex.from_product(it)
|
| 598 |
+
index = date_range("20141006", periods=20)
|
| 599 |
+
vals = np.random.default_rng(2).integers(1, 1000, (len(index), len(cols)))
|
| 600 |
+
df = DataFrame(vals, columns=cols, index=index)
|
| 601 |
+
|
| 602 |
+
i, j = df.index.values.copy(), it[-1][:]
|
| 603 |
+
|
| 604 |
+
np.random.default_rng(2).shuffle(i)
|
| 605 |
+
df["jim"] = df["jolie"].loc[i, ::-1]
|
| 606 |
+
tm.assert_frame_equal(df["jim"], df["jolie"])
|
| 607 |
+
|
| 608 |
+
np.random.default_rng(2).shuffle(j)
|
| 609 |
+
df[("joe", "first")] = df[("jolie", "last")].loc[i, j]
|
| 610 |
+
tm.assert_frame_equal(df[("joe", "first")], df[("jolie", "last")])
|
| 611 |
+
|
| 612 |
+
np.random.default_rng(2).shuffle(j)
|
| 613 |
+
df[("joe", "last")] = df[("jolie", "first")].loc[i, j]
|
| 614 |
+
tm.assert_frame_equal(df[("joe", "last")], df[("jolie", "first")])
|
| 615 |
+
|
| 616 |
+
@pytest.mark.parametrize(
|
| 617 |
+
"columns,box,expected",
|
| 618 |
+
[
|
| 619 |
+
(
|
| 620 |
+
["A", "B", "C", "D"],
|
| 621 |
+
7,
|
| 622 |
+
DataFrame(
|
| 623 |
+
[[7, 7, 7, 7], [7, 7, 7, 7], [7, 7, 7, 7]],
|
| 624 |
+
columns=["A", "B", "C", "D"],
|
| 625 |
+
),
|
| 626 |
+
),
|
| 627 |
+
(
|
| 628 |
+
["C", "D"],
|
| 629 |
+
[7, 8],
|
| 630 |
+
DataFrame(
|
| 631 |
+
[[1, 2, 7, 8], [3, 4, 7, 8], [5, 6, 7, 8]],
|
| 632 |
+
columns=["A", "B", "C", "D"],
|
| 633 |
+
),
|
| 634 |
+
),
|
| 635 |
+
(
|
| 636 |
+
["A", "B", "C"],
|
| 637 |
+
np.array([7, 8, 9], dtype=np.int64),
|
| 638 |
+
DataFrame([[7, 8, 9], [7, 8, 9], [7, 8, 9]], columns=["A", "B", "C"]),
|
| 639 |
+
),
|
| 640 |
+
(
|
| 641 |
+
["B", "C", "D"],
|
| 642 |
+
[[7, 8, 9], [10, 11, 12], [13, 14, 15]],
|
| 643 |
+
DataFrame(
|
| 644 |
+
[[1, 7, 8, 9], [3, 10, 11, 12], [5, 13, 14, 15]],
|
| 645 |
+
columns=["A", "B", "C", "D"],
|
| 646 |
+
),
|
| 647 |
+
),
|
| 648 |
+
(
|
| 649 |
+
["C", "A", "D"],
|
| 650 |
+
np.array([[7, 8, 9], [10, 11, 12], [13, 14, 15]], dtype=np.int64),
|
| 651 |
+
DataFrame(
|
| 652 |
+
[[8, 2, 7, 9], [11, 4, 10, 12], [14, 6, 13, 15]],
|
| 653 |
+
columns=["A", "B", "C", "D"],
|
| 654 |
+
),
|
| 655 |
+
),
|
| 656 |
+
(
|
| 657 |
+
["A", "C"],
|
| 658 |
+
DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]),
|
| 659 |
+
DataFrame(
|
| 660 |
+
[[7, 2, 8], [9, 4, 10], [11, 6, 12]], columns=["A", "B", "C"]
|
| 661 |
+
),
|
| 662 |
+
),
|
| 663 |
+
],
|
| 664 |
+
)
|
| 665 |
+
def test_setitem_list_missing_columns(self, columns, box, expected):
|
| 666 |
+
# GH#29334
|
| 667 |
+
df = DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "B"])
|
| 668 |
+
df[columns] = box
|
| 669 |
+
tm.assert_frame_equal(df, expected)
|
| 670 |
+
|
| 671 |
+
def test_setitem_list_of_tuples(self, float_frame):
|
| 672 |
+
tuples = list(zip(float_frame["A"], float_frame["B"]))
|
| 673 |
+
float_frame["tuples"] = tuples
|
| 674 |
+
|
| 675 |
+
result = float_frame["tuples"]
|
| 676 |
+
expected = Series(tuples, index=float_frame.index, name="tuples")
|
| 677 |
+
tm.assert_series_equal(result, expected)
|
| 678 |
+
|
| 679 |
+
def test_setitem_iloc_generator(self):
|
| 680 |
+
# GH#39614
|
| 681 |
+
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
|
| 682 |
+
indexer = (x for x in [1, 2])
|
| 683 |
+
df.iloc[indexer] = 1
|
| 684 |
+
expected = DataFrame({"a": [1, 1, 1], "b": [4, 1, 1]})
|
| 685 |
+
tm.assert_frame_equal(df, expected)
|
| 686 |
+
|
| 687 |
+
def test_setitem_iloc_two_dimensional_generator(self):
|
| 688 |
+
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
|
| 689 |
+
indexer = (x for x in [1, 2])
|
| 690 |
+
df.iloc[indexer, 1] = 1
|
| 691 |
+
expected = DataFrame({"a": [1, 2, 3], "b": [4, 1, 1]})
|
| 692 |
+
tm.assert_frame_equal(df, expected)
|
| 693 |
+
|
| 694 |
+
def test_setitem_dtypes_bytes_type_to_object(self):
|
| 695 |
+
# GH 20734
|
| 696 |
+
index = Series(name="id", dtype="S24")
|
| 697 |
+
df = DataFrame(index=index, columns=Index([], dtype="str"))
|
| 698 |
+
df["a"] = Series(name="a", index=index, dtype=np.uint32)
|
| 699 |
+
df["b"] = Series(name="b", index=index, dtype="S64")
|
| 700 |
+
df["c"] = Series(name="c", index=index, dtype="S64")
|
| 701 |
+
df["d"] = Series(name="d", index=index, dtype=np.uint8)
|
| 702 |
+
result = df.dtypes
|
| 703 |
+
expected = Series([np.uint32, object, object, np.uint8], index=list("abcd"))
|
| 704 |
+
tm.assert_series_equal(result, expected)
|
| 705 |
+
|
| 706 |
+
def test_boolean_mask_nullable_int64(self):
|
| 707 |
+
# GH 28928
|
| 708 |
+
result = DataFrame({"a": [3, 4], "b": [5, 6]}).astype(
|
| 709 |
+
{"a": "int64", "b": "Int64"}
|
| 710 |
+
)
|
| 711 |
+
mask = Series(False, index=result.index)
|
| 712 |
+
result.loc[mask, "a"] = result["a"]
|
| 713 |
+
result.loc[mask, "b"] = result["b"]
|
| 714 |
+
expected = DataFrame({"a": [3, 4], "b": [5, 6]}).astype(
|
| 715 |
+
{"a": "int64", "b": "Int64"}
|
| 716 |
+
)
|
| 717 |
+
tm.assert_frame_equal(result, expected)
|
| 718 |
+
|
| 719 |
+
def test_setitem_ea_dtype_rhs_series(self):
|
| 720 |
+
# GH#47425
|
| 721 |
+
df = DataFrame({"a": [1, 2]})
|
| 722 |
+
df["a"] = Series([1, 2], dtype="Int64")
|
| 723 |
+
expected = DataFrame({"a": [1, 2]}, dtype="Int64")
|
| 724 |
+
tm.assert_frame_equal(df, expected)
|
| 725 |
+
|
| 726 |
+
# TODO(ArrayManager) set column with 2d column array, see #44788
|
| 727 |
+
@td.skip_array_manager_not_yet_implemented
|
| 728 |
+
def test_setitem_npmatrix_2d(self):
|
| 729 |
+
# GH#42376
|
| 730 |
+
# for use-case df["x"] = sparse.random((10, 10)).mean(axis=1)
|
| 731 |
+
expected = DataFrame(
|
| 732 |
+
{"np-array": np.ones(10), "np-matrix": np.ones(10)}, index=np.arange(10)
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
a = np.ones((10, 1))
|
| 736 |
+
df = DataFrame(index=np.arange(10), columns=Index([], dtype="str"))
|
| 737 |
+
df["np-array"] = a
|
| 738 |
+
|
| 739 |
+
# Instantiation of `np.matrix` gives PendingDeprecationWarning
|
| 740 |
+
with tm.assert_produces_warning(PendingDeprecationWarning):
|
| 741 |
+
df["np-matrix"] = np.matrix(a)
|
| 742 |
+
|
| 743 |
+
tm.assert_frame_equal(df, expected)
|
| 744 |
+
|
| 745 |
+
@pytest.mark.parametrize("vals", [{}, {"d": "a"}])
|
| 746 |
+
def test_setitem_aligning_dict_with_index(self, vals):
|
| 747 |
+
# GH#47216
|
| 748 |
+
df = DataFrame({"a": [1, 2], "b": [3, 4], **vals})
|
| 749 |
+
df.loc[:, "a"] = {1: 100, 0: 200}
|
| 750 |
+
df.loc[:, "c"] = {0: 5, 1: 6}
|
| 751 |
+
df.loc[:, "e"] = {1: 5}
|
| 752 |
+
expected = DataFrame(
|
| 753 |
+
{"a": [200, 100], "b": [3, 4], **vals, "c": [5, 6], "e": [np.nan, 5]}
|
| 754 |
+
)
|
| 755 |
+
tm.assert_frame_equal(df, expected)
|
| 756 |
+
|
| 757 |
+
def test_setitem_rhs_dataframe(self):
|
| 758 |
+
# GH#47578
|
| 759 |
+
df = DataFrame({"a": [1, 2]})
|
| 760 |
+
df["a"] = DataFrame({"a": [10, 11]}, index=[1, 2])
|
| 761 |
+
expected = DataFrame({"a": [np.nan, 10]})
|
| 762 |
+
tm.assert_frame_equal(df, expected)
|
| 763 |
+
|
| 764 |
+
df = DataFrame({"a": [1, 2]})
|
| 765 |
+
df.isetitem(0, DataFrame({"a": [10, 11]}, index=[1, 2]))
|
| 766 |
+
tm.assert_frame_equal(df, expected)
|
| 767 |
+
|
| 768 |
+
def test_setitem_frame_overwrite_with_ea_dtype(self, any_numeric_ea_dtype):
|
| 769 |
+
# GH#46896
|
| 770 |
+
df = DataFrame(columns=["a", "b"], data=[[1, 2], [3, 4]])
|
| 771 |
+
df["a"] = DataFrame({"a": [10, 11]}, dtype=any_numeric_ea_dtype)
|
| 772 |
+
expected = DataFrame(
|
| 773 |
+
{
|
| 774 |
+
"a": Series([10, 11], dtype=any_numeric_ea_dtype),
|
| 775 |
+
"b": [2, 4],
|
| 776 |
+
}
|
| 777 |
+
)
|
| 778 |
+
tm.assert_frame_equal(df, expected)
|
| 779 |
+
|
| 780 |
+
def test_setitem_string_option_object_index(self):
|
| 781 |
+
# GH#55638
|
| 782 |
+
pytest.importorskip("pyarrow")
|
| 783 |
+
df = DataFrame({"a": [1, 2]})
|
| 784 |
+
with pd.option_context("future.infer_string", True):
|
| 785 |
+
df["b"] = Index(["a", "b"], dtype=object)
|
| 786 |
+
expected = DataFrame({"a": [1, 2], "b": Series(["a", "b"], dtype=object)})
|
| 787 |
+
tm.assert_frame_equal(df, expected)
|
| 788 |
+
|
| 789 |
+
def test_setitem_frame_midx_columns(self):
|
| 790 |
+
# GH#49121
|
| 791 |
+
df = DataFrame({("a", "b"): [10]})
|
| 792 |
+
expected = df.copy()
|
| 793 |
+
col_name = ("a", "b")
|
| 794 |
+
df[col_name] = df[[col_name]]
|
| 795 |
+
tm.assert_frame_equal(df, expected)
|
| 796 |
+
|
| 797 |
+
def test_loc_setitem_ea_dtype(self):
|
| 798 |
+
# GH#55604
|
| 799 |
+
df = DataFrame({"a": np.array([10], dtype="i8")})
|
| 800 |
+
df.loc[:, "a"] = Series([11], dtype="Int64")
|
| 801 |
+
expected = DataFrame({"a": np.array([11], dtype="i8")})
|
| 802 |
+
tm.assert_frame_equal(df, expected)
|
| 803 |
+
|
| 804 |
+
df = DataFrame({"a": np.array([10], dtype="i8")})
|
| 805 |
+
df.iloc[:, 0] = Series([11], dtype="Int64")
|
| 806 |
+
tm.assert_frame_equal(df, expected)
|
| 807 |
+
|
| 808 |
+
def test_setitem_object_inferring(self):
|
| 809 |
+
# GH#56102
|
| 810 |
+
idx = Index([Timestamp("2019-12-31")], dtype=object)
|
| 811 |
+
df = DataFrame({"a": [1]})
|
| 812 |
+
with tm.assert_produces_warning(FutureWarning, match="infer"):
|
| 813 |
+
df.loc[:, "b"] = idx
|
| 814 |
+
with tm.assert_produces_warning(FutureWarning, match="infer"):
|
| 815 |
+
df["c"] = idx
|
| 816 |
+
|
| 817 |
+
expected = DataFrame(
|
| 818 |
+
{
|
| 819 |
+
"a": [1],
|
| 820 |
+
"b": Series([Timestamp("2019-12-31")], dtype="datetime64[ns]"),
|
| 821 |
+
"c": Series([Timestamp("2019-12-31")], dtype="datetime64[ns]"),
|
| 822 |
+
}
|
| 823 |
+
)
|
| 824 |
+
tm.assert_frame_equal(df, expected)
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
class TestSetitemTZAwareValues:
|
| 828 |
+
@pytest.fixture
|
| 829 |
+
def idx(self):
|
| 830 |
+
naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B")
|
| 831 |
+
idx = naive.tz_localize("US/Pacific")
|
| 832 |
+
return idx
|
| 833 |
+
|
| 834 |
+
@pytest.fixture
|
| 835 |
+
def expected(self, idx):
|
| 836 |
+
expected = Series(np.array(idx.tolist(), dtype="object"), name="B")
|
| 837 |
+
assert expected.dtype == idx.dtype
|
| 838 |
+
return expected
|
| 839 |
+
|
| 840 |
+
def test_setitem_dt64series(self, idx, expected):
|
| 841 |
+
# convert to utc
|
| 842 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"])
|
| 843 |
+
df["B"] = idx
|
| 844 |
+
df["B"] = idx.to_series(index=[0, 1]).dt.tz_convert(None)
|
| 845 |
+
|
| 846 |
+
result = df["B"]
|
| 847 |
+
comp = Series(idx.tz_convert("UTC").tz_localize(None), name="B")
|
| 848 |
+
tm.assert_series_equal(result, comp)
|
| 849 |
+
|
| 850 |
+
def test_setitem_datetimeindex(self, idx, expected):
|
| 851 |
+
# setting a DataFrame column with a tzaware DTI retains the dtype
|
| 852 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"])
|
| 853 |
+
|
| 854 |
+
# assign to frame
|
| 855 |
+
df["B"] = idx
|
| 856 |
+
result = df["B"]
|
| 857 |
+
tm.assert_series_equal(result, expected)
|
| 858 |
+
|
| 859 |
+
def test_setitem_object_array_of_tzaware_datetimes(self, idx, expected):
|
| 860 |
+
# setting a DataFrame column with a tzaware DTI retains the dtype
|
| 861 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"])
|
| 862 |
+
|
| 863 |
+
# object array of datetimes with a tz
|
| 864 |
+
df["B"] = idx.to_pydatetime()
|
| 865 |
+
result = df["B"]
|
| 866 |
+
tm.assert_series_equal(result, expected)
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
class TestDataFrameSetItemWithExpansion:
|
| 870 |
+
def test_setitem_listlike_views(self, using_copy_on_write, warn_copy_on_write):
|
| 871 |
+
# GH#38148
|
| 872 |
+
df = DataFrame({"a": [1, 2, 3], "b": [4, 4, 6]})
|
| 873 |
+
|
| 874 |
+
# get one column as a view of df
|
| 875 |
+
ser = df["a"]
|
| 876 |
+
|
| 877 |
+
# add columns with list-like indexer
|
| 878 |
+
df[["c", "d"]] = np.array([[0.1, 0.2], [0.3, 0.4], [0.4, 0.5]])
|
| 879 |
+
|
| 880 |
+
# edit in place the first column to check view semantics
|
| 881 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 882 |
+
df.iloc[0, 0] = 100
|
| 883 |
+
|
| 884 |
+
if using_copy_on_write:
|
| 885 |
+
expected = Series([1, 2, 3], name="a")
|
| 886 |
+
else:
|
| 887 |
+
expected = Series([100, 2, 3], name="a")
|
| 888 |
+
tm.assert_series_equal(ser, expected)
|
| 889 |
+
|
| 890 |
+
def test_setitem_string_column_numpy_dtype_raising(self):
|
| 891 |
+
# GH#39010
|
| 892 |
+
df = DataFrame([[1, 2], [3, 4]])
|
| 893 |
+
df["0 - Name"] = [5, 6]
|
| 894 |
+
expected = DataFrame([[1, 2, 5], [3, 4, 6]], columns=[0, 1, "0 - Name"])
|
| 895 |
+
tm.assert_frame_equal(df, expected)
|
| 896 |
+
|
| 897 |
+
def test_setitem_empty_df_duplicate_columns(self, using_copy_on_write):
|
| 898 |
+
# GH#38521
|
| 899 |
+
df = DataFrame(columns=["a", "b", "b"], dtype="float64")
|
| 900 |
+
df.loc[:, "a"] = list(range(2))
|
| 901 |
+
expected = DataFrame(
|
| 902 |
+
[[0, np.nan, np.nan], [1, np.nan, np.nan]], columns=["a", "b", "b"]
|
| 903 |
+
)
|
| 904 |
+
tm.assert_frame_equal(df, expected)
|
| 905 |
+
|
| 906 |
+
def test_setitem_with_expansion_categorical_dtype(self):
|
| 907 |
+
# assignment
|
| 908 |
+
df = DataFrame(
|
| 909 |
+
{
|
| 910 |
+
"value": np.array(
|
| 911 |
+
np.random.default_rng(2).integers(0, 10000, 100), dtype="int32"
|
| 912 |
+
)
|
| 913 |
+
}
|
| 914 |
+
)
|
| 915 |
+
labels = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)])
|
| 916 |
+
|
| 917 |
+
df = df.sort_values(by=["value"], ascending=True)
|
| 918 |
+
ser = cut(df.value, range(0, 10500, 500), right=False, labels=labels)
|
| 919 |
+
cat = ser.values
|
| 920 |
+
|
| 921 |
+
# setting with a Categorical
|
| 922 |
+
df["D"] = cat
|
| 923 |
+
result = df.dtypes
|
| 924 |
+
expected = Series(
|
| 925 |
+
[np.dtype("int32"), CategoricalDtype(categories=labels, ordered=False)],
|
| 926 |
+
index=["value", "D"],
|
| 927 |
+
)
|
| 928 |
+
tm.assert_series_equal(result, expected)
|
| 929 |
+
|
| 930 |
+
# setting with a Series
|
| 931 |
+
df["E"] = ser
|
| 932 |
+
result = df.dtypes
|
| 933 |
+
expected = Series(
|
| 934 |
+
[
|
| 935 |
+
np.dtype("int32"),
|
| 936 |
+
CategoricalDtype(categories=labels, ordered=False),
|
| 937 |
+
CategoricalDtype(categories=labels, ordered=False),
|
| 938 |
+
],
|
| 939 |
+
index=["value", "D", "E"],
|
| 940 |
+
)
|
| 941 |
+
tm.assert_series_equal(result, expected)
|
| 942 |
+
|
| 943 |
+
result1 = df["D"]
|
| 944 |
+
result2 = df["E"]
|
| 945 |
+
tm.assert_categorical_equal(result1._mgr.array, cat)
|
| 946 |
+
|
| 947 |
+
# sorting
|
| 948 |
+
ser.name = "E"
|
| 949 |
+
tm.assert_series_equal(result2.sort_index(), ser.sort_index())
|
| 950 |
+
|
| 951 |
+
def test_setitem_scalars_no_index(self):
|
| 952 |
+
# GH#16823 / GH#17894
|
| 953 |
+
df = DataFrame()
|
| 954 |
+
df["foo"] = 1
|
| 955 |
+
expected = DataFrame(columns=["foo"]).astype(np.int64)
|
| 956 |
+
tm.assert_frame_equal(df, expected)
|
| 957 |
+
|
| 958 |
+
def test_setitem_newcol_tuple_key(self, float_frame):
|
| 959 |
+
assert (
|
| 960 |
+
"A",
|
| 961 |
+
"B",
|
| 962 |
+
) not in float_frame.columns
|
| 963 |
+
float_frame["A", "B"] = float_frame["A"]
|
| 964 |
+
assert ("A", "B") in float_frame.columns
|
| 965 |
+
|
| 966 |
+
result = float_frame["A", "B"]
|
| 967 |
+
expected = float_frame["A"]
|
| 968 |
+
tm.assert_series_equal(result, expected, check_names=False)
|
| 969 |
+
|
| 970 |
+
def test_frame_setitem_newcol_timestamp(self):
|
| 971 |
+
# GH#2155
|
| 972 |
+
columns = date_range(start="1/1/2012", end="2/1/2012", freq=BDay())
|
| 973 |
+
data = DataFrame(columns=columns, index=range(10))
|
| 974 |
+
t = datetime(2012, 11, 1)
|
| 975 |
+
ts = Timestamp(t)
|
| 976 |
+
data[ts] = np.nan # works, mostly a smoke-test
|
| 977 |
+
assert np.isnan(data[ts]).all()
|
| 978 |
+
|
| 979 |
+
def test_frame_setitem_rangeindex_into_new_col(self):
|
| 980 |
+
# GH#47128
|
| 981 |
+
df = DataFrame({"a": ["a", "b"]})
|
| 982 |
+
df["b"] = df.index
|
| 983 |
+
df.loc[[False, True], "b"] = 100
|
| 984 |
+
result = df.loc[[1], :]
|
| 985 |
+
expected = DataFrame({"a": ["b"], "b": [100]}, index=[1])
|
| 986 |
+
tm.assert_frame_equal(result, expected)
|
| 987 |
+
|
| 988 |
+
def test_setitem_frame_keep_ea_dtype(self, any_numeric_ea_dtype):
|
| 989 |
+
# GH#46896
|
| 990 |
+
df = DataFrame(columns=["a", "b"], data=[[1, 2], [3, 4]])
|
| 991 |
+
df["c"] = DataFrame({"a": [10, 11]}, dtype=any_numeric_ea_dtype)
|
| 992 |
+
expected = DataFrame(
|
| 993 |
+
{
|
| 994 |
+
"a": [1, 3],
|
| 995 |
+
"b": [2, 4],
|
| 996 |
+
"c": Series([10, 11], dtype=any_numeric_ea_dtype),
|
| 997 |
+
}
|
| 998 |
+
)
|
| 999 |
+
tm.assert_frame_equal(df, expected)
|
| 1000 |
+
|
| 1001 |
+
def test_loc_expansion_with_timedelta_type(self):
|
| 1002 |
+
result = DataFrame(columns=list("abc"))
|
| 1003 |
+
result.loc[0] = {
|
| 1004 |
+
"a": pd.to_timedelta(5, unit="s"),
|
| 1005 |
+
"b": pd.to_timedelta(72, unit="s"),
|
| 1006 |
+
"c": "23",
|
| 1007 |
+
}
|
| 1008 |
+
expected = DataFrame(
|
| 1009 |
+
[[pd.Timedelta("0 days 00:00:05"), pd.Timedelta("0 days 00:01:12"), "23"]],
|
| 1010 |
+
index=Index([0]),
|
| 1011 |
+
columns=(["a", "b", "c"]),
|
| 1012 |
+
)
|
| 1013 |
+
tm.assert_frame_equal(result, expected)
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
class TestDataFrameSetItemSlicing:
|
| 1017 |
+
def test_setitem_slice_position(self):
|
| 1018 |
+
# GH#31469
|
| 1019 |
+
df = DataFrame(np.zeros((100, 1)))
|
| 1020 |
+
df[-4:] = 1
|
| 1021 |
+
arr = np.zeros((100, 1))
|
| 1022 |
+
arr[-4:] = 1
|
| 1023 |
+
expected = DataFrame(arr)
|
| 1024 |
+
tm.assert_frame_equal(df, expected)
|
| 1025 |
+
|
| 1026 |
+
@pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc])
|
| 1027 |
+
@pytest.mark.parametrize("box", [Series, np.array, list, pd.array])
|
| 1028 |
+
@pytest.mark.parametrize("n", [1, 2, 3])
|
| 1029 |
+
def test_setitem_slice_indexer_broadcasting_rhs(self, n, box, indexer):
|
| 1030 |
+
# GH#40440
|
| 1031 |
+
df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"])
|
| 1032 |
+
indexer(df)[1:] = box([10, 11, 12])
|
| 1033 |
+
expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"])
|
| 1034 |
+
tm.assert_frame_equal(df, expected)
|
| 1035 |
+
|
| 1036 |
+
@pytest.mark.parametrize("box", [Series, np.array, list, pd.array])
|
| 1037 |
+
@pytest.mark.parametrize("n", [1, 2, 3])
|
| 1038 |
+
def test_setitem_list_indexer_broadcasting_rhs(self, n, box):
|
| 1039 |
+
# GH#40440
|
| 1040 |
+
df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"])
|
| 1041 |
+
df.iloc[list(range(1, n + 1))] = box([10, 11, 12])
|
| 1042 |
+
expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"])
|
| 1043 |
+
tm.assert_frame_equal(df, expected)
|
| 1044 |
+
|
| 1045 |
+
@pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc])
|
| 1046 |
+
@pytest.mark.parametrize("box", [Series, np.array, list, pd.array])
|
| 1047 |
+
@pytest.mark.parametrize("n", [1, 2, 3])
|
| 1048 |
+
def test_setitem_slice_broadcasting_rhs_mixed_dtypes(self, n, box, indexer):
|
| 1049 |
+
# GH#40440
|
| 1050 |
+
df = DataFrame(
|
| 1051 |
+
[[1, 3, 5], ["x", "y", "z"]] + [[2, 4, 6]] * n, columns=["a", "b", "c"]
|
| 1052 |
+
)
|
| 1053 |
+
indexer(df)[1:] = box([10, 11, 12])
|
| 1054 |
+
expected = DataFrame(
|
| 1055 |
+
[[1, 3, 5]] + [[10, 11, 12]] * (n + 1),
|
| 1056 |
+
columns=["a", "b", "c"],
|
| 1057 |
+
dtype="object",
|
| 1058 |
+
)
|
| 1059 |
+
tm.assert_frame_equal(df, expected)
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
class TestDataFrameSetItemCallable:
|
| 1063 |
+
def test_setitem_callable(self):
|
| 1064 |
+
# GH#12533
|
| 1065 |
+
df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]})
|
| 1066 |
+
df[lambda x: "A"] = [11, 12, 13, 14]
|
| 1067 |
+
|
| 1068 |
+
exp = DataFrame({"A": [11, 12, 13, 14], "B": [5, 6, 7, 8]})
|
| 1069 |
+
tm.assert_frame_equal(df, exp)
|
| 1070 |
+
|
| 1071 |
+
def test_setitem_other_callable(self):
|
| 1072 |
+
# GH#13299
|
| 1073 |
+
def inc(x):
|
| 1074 |
+
return x + 1
|
| 1075 |
+
|
| 1076 |
+
# Set dtype object straight away to avoid upcast when setting inc below
|
| 1077 |
+
df = DataFrame([[-1, 1], [1, -1]], dtype=object)
|
| 1078 |
+
df[df > 0] = inc
|
| 1079 |
+
|
| 1080 |
+
expected = DataFrame([[-1, inc], [inc, -1]])
|
| 1081 |
+
tm.assert_frame_equal(df, expected)
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
class TestDataFrameSetItemBooleanMask:
|
| 1085 |
+
@td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values
|
| 1086 |
+
@pytest.mark.parametrize(
|
| 1087 |
+
"mask_type",
|
| 1088 |
+
[lambda df: df > np.abs(df) / 2, lambda df: (df > np.abs(df) / 2).values],
|
| 1089 |
+
ids=["dataframe", "array"],
|
| 1090 |
+
)
|
| 1091 |
+
def test_setitem_boolean_mask(self, mask_type, float_frame):
|
| 1092 |
+
# Test for issue #18582
|
| 1093 |
+
df = float_frame.copy()
|
| 1094 |
+
mask = mask_type(df)
|
| 1095 |
+
|
| 1096 |
+
# index with boolean mask
|
| 1097 |
+
result = df.copy()
|
| 1098 |
+
result[mask] = np.nan
|
| 1099 |
+
|
| 1100 |
+
expected = df.values.copy()
|
| 1101 |
+
expected[np.array(mask)] = np.nan
|
| 1102 |
+
expected = DataFrame(expected, index=df.index, columns=df.columns)
|
| 1103 |
+
tm.assert_frame_equal(result, expected)
|
| 1104 |
+
|
| 1105 |
+
@pytest.mark.xfail(reason="Currently empty indexers are treated as all False")
|
| 1106 |
+
@pytest.mark.parametrize("box", [list, np.array, Series])
|
| 1107 |
+
def test_setitem_loc_empty_indexer_raises_with_non_empty_value(self, box):
|
| 1108 |
+
# GH#37672
|
| 1109 |
+
df = DataFrame({"a": ["a"], "b": [1], "c": [1]})
|
| 1110 |
+
if box == Series:
|
| 1111 |
+
indexer = box([], dtype="object")
|
| 1112 |
+
else:
|
| 1113 |
+
indexer = box([])
|
| 1114 |
+
msg = "Must have equal len keys and value when setting with an iterable"
|
| 1115 |
+
with pytest.raises(ValueError, match=msg):
|
| 1116 |
+
df.loc[indexer, ["b"]] = [1]
|
| 1117 |
+
|
| 1118 |
+
@pytest.mark.parametrize("box", [list, np.array, Series])
|
| 1119 |
+
def test_setitem_loc_only_false_indexer_dtype_changed(self, box):
|
| 1120 |
+
# GH#37550
|
| 1121 |
+
# Dtype is only changed when value to set is a Series and indexer is
|
| 1122 |
+
# empty/bool all False
|
| 1123 |
+
df = DataFrame({"a": ["a"], "b": [1], "c": [1]})
|
| 1124 |
+
indexer = box([False])
|
| 1125 |
+
df.loc[indexer, ["b"]] = 10 - df["c"]
|
| 1126 |
+
expected = DataFrame({"a": ["a"], "b": [1], "c": [1]})
|
| 1127 |
+
tm.assert_frame_equal(df, expected)
|
| 1128 |
+
|
| 1129 |
+
df.loc[indexer, ["b"]] = 9
|
| 1130 |
+
tm.assert_frame_equal(df, expected)
|
| 1131 |
+
|
| 1132 |
+
@pytest.mark.parametrize("indexer", [tm.setitem, tm.loc])
|
| 1133 |
+
def test_setitem_boolean_mask_aligning(self, indexer):
|
| 1134 |
+
# GH#39931
|
| 1135 |
+
df = DataFrame({"a": [1, 4, 2, 3], "b": [5, 6, 7, 8]})
|
| 1136 |
+
expected = df.copy()
|
| 1137 |
+
mask = df["a"] >= 3
|
| 1138 |
+
indexer(df)[mask] = indexer(df)[mask].sort_values("a")
|
| 1139 |
+
tm.assert_frame_equal(df, expected)
|
| 1140 |
+
|
| 1141 |
+
def test_setitem_mask_categorical(self):
|
| 1142 |
+
# assign multiple rows (mixed values) (-> array) -> exp_multi_row
|
| 1143 |
+
# changed multiple rows
|
| 1144 |
+
cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])
|
| 1145 |
+
idx2 = Index(["h", "i", "j", "k", "l", "m", "n"])
|
| 1146 |
+
values2 = [1, 1, 2, 2, 1, 1, 1]
|
| 1147 |
+
exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2)
|
| 1148 |
+
|
| 1149 |
+
catsf = Categorical(
|
| 1150 |
+
["a", "a", "c", "c", "a", "a", "a"], categories=["a", "b", "c"]
|
| 1151 |
+
)
|
| 1152 |
+
idxf = Index(["h", "i", "j", "k", "l", "m", "n"])
|
| 1153 |
+
valuesf = [1, 1, 3, 3, 1, 1, 1]
|
| 1154 |
+
df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf)
|
| 1155 |
+
|
| 1156 |
+
exp_fancy = exp_multi_row.copy()
|
| 1157 |
+
exp_fancy["cats"] = exp_fancy["cats"].cat.set_categories(["a", "b", "c"])
|
| 1158 |
+
|
| 1159 |
+
mask = df["cats"] == "c"
|
| 1160 |
+
df[mask] = ["b", 2]
|
| 1161 |
+
# category c is kept in .categories
|
| 1162 |
+
tm.assert_frame_equal(df, exp_fancy)
|
| 1163 |
+
|
| 1164 |
+
@pytest.mark.parametrize("dtype", ["float", "int64"])
|
| 1165 |
+
@pytest.mark.parametrize("kwargs", [{}, {"index": [1]}, {"columns": ["A"]}])
|
| 1166 |
+
def test_setitem_empty_frame_with_boolean(self, dtype, kwargs):
|
| 1167 |
+
# see GH#10126
|
| 1168 |
+
kwargs["dtype"] = dtype
|
| 1169 |
+
df = DataFrame(**kwargs)
|
| 1170 |
+
|
| 1171 |
+
df2 = df.copy()
|
| 1172 |
+
df[df > df2] = 47
|
| 1173 |
+
tm.assert_frame_equal(df, df2)
|
| 1174 |
+
|
| 1175 |
+
def test_setitem_boolean_indexing(self):
|
| 1176 |
+
idx = list(range(3))
|
| 1177 |
+
cols = ["A", "B", "C"]
|
| 1178 |
+
df1 = DataFrame(
|
| 1179 |
+
index=idx,
|
| 1180 |
+
columns=cols,
|
| 1181 |
+
data=np.array(
|
| 1182 |
+
[[0.0, 0.5, 1.0], [1.5, 2.0, 2.5], [3.0, 3.5, 4.0]], dtype=float
|
| 1183 |
+
),
|
| 1184 |
+
)
|
| 1185 |
+
df2 = DataFrame(index=idx, columns=cols, data=np.ones((len(idx), len(cols))))
|
| 1186 |
+
|
| 1187 |
+
expected = DataFrame(
|
| 1188 |
+
index=idx,
|
| 1189 |
+
columns=cols,
|
| 1190 |
+
data=np.array([[0.0, 0.5, 1.0], [1.5, 2.0, -1], [-1, -1, -1]], dtype=float),
|
| 1191 |
+
)
|
| 1192 |
+
|
| 1193 |
+
df1[df1 > 2.0 * df2] = -1
|
| 1194 |
+
tm.assert_frame_equal(df1, expected)
|
| 1195 |
+
with pytest.raises(ValueError, match="Item wrong length"):
|
| 1196 |
+
df1[df1.index[:-1] > 2] = -1
|
| 1197 |
+
|
| 1198 |
+
def test_loc_setitem_all_false_boolean_two_blocks(self):
|
| 1199 |
+
# GH#40885
|
| 1200 |
+
df = DataFrame({"a": [1, 2], "b": [3, 4], "c": "a"})
|
| 1201 |
+
expected = df.copy()
|
| 1202 |
+
indexer = Series([False, False], name="c")
|
| 1203 |
+
df.loc[indexer, ["b"]] = DataFrame({"b": [5, 6]}, index=[0, 1])
|
| 1204 |
+
tm.assert_frame_equal(df, expected)
|
| 1205 |
+
|
| 1206 |
+
def test_setitem_ea_boolean_mask(self):
|
| 1207 |
+
# GH#47125
|
| 1208 |
+
df = DataFrame([[-1, 2], [3, -4]])
|
| 1209 |
+
expected = DataFrame([[0, 2], [3, 0]])
|
| 1210 |
+
boolean_indexer = DataFrame(
|
| 1211 |
+
{
|
| 1212 |
+
0: Series([True, False], dtype="boolean"),
|
| 1213 |
+
1: Series([pd.NA, True], dtype="boolean"),
|
| 1214 |
+
}
|
| 1215 |
+
)
|
| 1216 |
+
df[boolean_indexer] = 0
|
| 1217 |
+
tm.assert_frame_equal(df, expected)
|
| 1218 |
+
|
| 1219 |
+
|
| 1220 |
+
class TestDataFrameSetitemCopyViewSemantics:
|
| 1221 |
+
def test_setitem_always_copy(self, float_frame):
|
| 1222 |
+
assert "E" not in float_frame.columns
|
| 1223 |
+
s = float_frame["A"].copy()
|
| 1224 |
+
float_frame["E"] = s
|
| 1225 |
+
|
| 1226 |
+
float_frame.iloc[5:10, float_frame.columns.get_loc("E")] = np.nan
|
| 1227 |
+
assert notna(s[5:10]).all()
|
| 1228 |
+
|
| 1229 |
+
@pytest.mark.parametrize("consolidate", [True, False])
|
| 1230 |
+
def test_setitem_partial_column_inplace(
|
| 1231 |
+
self, consolidate, using_array_manager, using_copy_on_write
|
| 1232 |
+
):
|
| 1233 |
+
# This setting should be in-place, regardless of whether frame is
|
| 1234 |
+
# single-block or multi-block
|
| 1235 |
+
# GH#304 this used to be incorrectly not-inplace, in which case
|
| 1236 |
+
# we needed to ensure _item_cache was cleared.
|
| 1237 |
+
|
| 1238 |
+
df = DataFrame(
|
| 1239 |
+
{"x": [1.1, 2.1, 3.1, 4.1], "y": [5.1, 6.1, 7.1, 8.1]}, index=[0, 1, 2, 3]
|
| 1240 |
+
)
|
| 1241 |
+
df.insert(2, "z", np.nan)
|
| 1242 |
+
if not using_array_manager:
|
| 1243 |
+
if consolidate:
|
| 1244 |
+
df._consolidate_inplace()
|
| 1245 |
+
assert len(df._mgr.blocks) == 1
|
| 1246 |
+
else:
|
| 1247 |
+
assert len(df._mgr.blocks) == 2
|
| 1248 |
+
|
| 1249 |
+
zvals = df["z"]._values
|
| 1250 |
+
|
| 1251 |
+
df.loc[2:, "z"] = 42
|
| 1252 |
+
|
| 1253 |
+
expected = Series([np.nan, np.nan, 42, 42], index=df.index, name="z")
|
| 1254 |
+
tm.assert_series_equal(df["z"], expected)
|
| 1255 |
+
|
| 1256 |
+
# check setting occurred in-place
|
| 1257 |
+
if not using_copy_on_write:
|
| 1258 |
+
tm.assert_numpy_array_equal(zvals, expected.values)
|
| 1259 |
+
assert np.shares_memory(zvals, df["z"]._values)
|
| 1260 |
+
|
| 1261 |
+
def test_setitem_duplicate_columns_not_inplace(self):
|
| 1262 |
+
# GH#39510
|
| 1263 |
+
cols = ["A", "B"] * 2
|
| 1264 |
+
df = DataFrame(0.0, index=[0], columns=cols)
|
| 1265 |
+
df_copy = df.copy()
|
| 1266 |
+
df_view = df[:]
|
| 1267 |
+
df["B"] = (2, 5)
|
| 1268 |
+
|
| 1269 |
+
expected = DataFrame([[0.0, 2, 0.0, 5]], columns=cols)
|
| 1270 |
+
tm.assert_frame_equal(df_view, df_copy)
|
| 1271 |
+
tm.assert_frame_equal(df, expected)
|
| 1272 |
+
|
| 1273 |
+
@pytest.mark.parametrize(
|
| 1274 |
+
"value", [1, np.array([[1], [1]], dtype="int64"), [[1], [1]]]
|
| 1275 |
+
)
|
| 1276 |
+
def test_setitem_same_dtype_not_inplace(self, value, using_array_manager):
|
| 1277 |
+
# GH#39510
|
| 1278 |
+
cols = ["A", "B"]
|
| 1279 |
+
df = DataFrame(0, index=[0, 1], columns=cols)
|
| 1280 |
+
df_copy = df.copy()
|
| 1281 |
+
df_view = df[:]
|
| 1282 |
+
df[["B"]] = value
|
| 1283 |
+
|
| 1284 |
+
expected = DataFrame([[0, 1], [0, 1]], columns=cols)
|
| 1285 |
+
tm.assert_frame_equal(df, expected)
|
| 1286 |
+
tm.assert_frame_equal(df_view, df_copy)
|
| 1287 |
+
|
| 1288 |
+
@pytest.mark.parametrize("value", [1.0, np.array([[1.0], [1.0]]), [[1.0], [1.0]]])
|
| 1289 |
+
def test_setitem_listlike_key_scalar_value_not_inplace(self, value):
|
| 1290 |
+
# GH#39510
|
| 1291 |
+
cols = ["A", "B"]
|
| 1292 |
+
df = DataFrame(0, index=[0, 1], columns=cols)
|
| 1293 |
+
df_copy = df.copy()
|
| 1294 |
+
df_view = df[:]
|
| 1295 |
+
df[["B"]] = value
|
| 1296 |
+
|
| 1297 |
+
expected = DataFrame([[0, 1.0], [0, 1.0]], columns=cols)
|
| 1298 |
+
tm.assert_frame_equal(df_view, df_copy)
|
| 1299 |
+
tm.assert_frame_equal(df, expected)
|
| 1300 |
+
|
| 1301 |
+
@pytest.mark.parametrize(
|
| 1302 |
+
"indexer",
|
| 1303 |
+
[
|
| 1304 |
+
"a",
|
| 1305 |
+
["a"],
|
| 1306 |
+
pytest.param(
|
| 1307 |
+
[True, False],
|
| 1308 |
+
marks=pytest.mark.xfail(
|
| 1309 |
+
reason="Boolean indexer incorrectly setting inplace",
|
| 1310 |
+
strict=False, # passing on some builds, no obvious pattern
|
| 1311 |
+
),
|
| 1312 |
+
),
|
| 1313 |
+
],
|
| 1314 |
+
)
|
| 1315 |
+
@pytest.mark.parametrize(
|
| 1316 |
+
"value, set_value",
|
| 1317 |
+
[
|
| 1318 |
+
(1, 5),
|
| 1319 |
+
(1.0, 5.0),
|
| 1320 |
+
(Timestamp("2020-12-31"), Timestamp("2021-12-31")),
|
| 1321 |
+
("a", "b"),
|
| 1322 |
+
],
|
| 1323 |
+
)
|
| 1324 |
+
def test_setitem_not_operating_inplace(self, value, set_value, indexer):
|
| 1325 |
+
# GH#43406
|
| 1326 |
+
df = DataFrame({"a": value}, index=[0, 1])
|
| 1327 |
+
expected = df.copy()
|
| 1328 |
+
view = df[:]
|
| 1329 |
+
df[indexer] = set_value
|
| 1330 |
+
tm.assert_frame_equal(view, expected)
|
| 1331 |
+
|
| 1332 |
+
@td.skip_array_manager_invalid_test
|
| 1333 |
+
def test_setitem_column_update_inplace(
|
| 1334 |
+
self, using_copy_on_write, warn_copy_on_write
|
| 1335 |
+
):
|
| 1336 |
+
# https://github.com/pandas-dev/pandas/issues/47172
|
| 1337 |
+
|
| 1338 |
+
labels = [f"c{i}" for i in range(10)]
|
| 1339 |
+
df = DataFrame({col: np.zeros(len(labels)) for col in labels}, index=labels)
|
| 1340 |
+
values = df._mgr.blocks[0].values
|
| 1341 |
+
|
| 1342 |
+
with tm.raises_chained_assignment_error():
|
| 1343 |
+
for label in df.columns:
|
| 1344 |
+
df[label][label] = 1
|
| 1345 |
+
if not using_copy_on_write:
|
| 1346 |
+
# diagonal values all updated
|
| 1347 |
+
assert np.all(values[np.arange(10), np.arange(10)] == 1)
|
| 1348 |
+
else:
|
| 1349 |
+
# original dataframe not updated
|
| 1350 |
+
assert np.all(values[np.arange(10), np.arange(10)] == 0)
|
| 1351 |
+
|
| 1352 |
+
def test_setitem_column_frame_as_category(self):
|
| 1353 |
+
# GH31581
|
| 1354 |
+
df = DataFrame([1, 2, 3])
|
| 1355 |
+
df["col1"] = DataFrame([1, 2, 3], dtype="category")
|
| 1356 |
+
df["col2"] = Series([1, 2, 3], dtype="category")
|
| 1357 |
+
|
| 1358 |
+
expected_types = Series(
|
| 1359 |
+
["int64", "category", "category"], index=[0, "col1", "col2"], dtype=object
|
| 1360 |
+
)
|
| 1361 |
+
tm.assert_series_equal(df.dtypes, expected_types)
|
| 1362 |
+
|
| 1363 |
+
@pytest.mark.parametrize("dtype", ["int64", "Int64"])
|
| 1364 |
+
def test_setitem_iloc_with_numpy_array(self, dtype):
|
| 1365 |
+
# GH-33828
|
| 1366 |
+
df = DataFrame({"a": np.ones(3)}, dtype=dtype)
|
| 1367 |
+
df.iloc[np.array([0]), np.array([0])] = np.array([[2]])
|
| 1368 |
+
|
| 1369 |
+
expected = DataFrame({"a": [2, 1, 1]}, dtype=dtype)
|
| 1370 |
+
tm.assert_frame_equal(df, expected)
|
| 1371 |
+
|
| 1372 |
+
def test_setitem_frame_dup_cols_dtype(self):
|
| 1373 |
+
# GH#53143
|
| 1374 |
+
df = DataFrame([[1, 2, 3, 4], [4, 5, 6, 7]], columns=["a", "b", "a", "c"])
|
| 1375 |
+
rhs = DataFrame([[0, 1.5], [2, 2.5]], columns=["a", "a"])
|
| 1376 |
+
df["a"] = rhs
|
| 1377 |
+
expected = DataFrame(
|
| 1378 |
+
[[0, 2, 1.5, 4], [2, 5, 2.5, 7]], columns=["a", "b", "a", "c"]
|
| 1379 |
+
)
|
| 1380 |
+
tm.assert_frame_equal(df, expected)
|
| 1381 |
+
|
| 1382 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"])
|
| 1383 |
+
rhs = DataFrame([[0, 1.5], [2, 2.5]], columns=["a", "a"])
|
| 1384 |
+
df["a"] = rhs
|
| 1385 |
+
expected = DataFrame([[0, 1.5, 3], [2, 2.5, 6]], columns=["a", "a", "b"])
|
| 1386 |
+
tm.assert_frame_equal(df, expected)
|
| 1387 |
+
|
| 1388 |
+
def test_frame_setitem_empty_dataframe(self):
|
| 1389 |
+
# GH#28871
|
| 1390 |
+
dti = DatetimeIndex(["2000-01-01"], dtype="M8[ns]", name="date")
|
| 1391 |
+
df = DataFrame({"date": dti}).set_index("date")
|
| 1392 |
+
df = df[0:0].copy()
|
| 1393 |
+
|
| 1394 |
+
df["3010"] = None
|
| 1395 |
+
df["2010"] = None
|
| 1396 |
+
|
| 1397 |
+
expected = DataFrame(
|
| 1398 |
+
[],
|
| 1399 |
+
columns=["3010", "2010"],
|
| 1400 |
+
index=dti[:0],
|
| 1401 |
+
)
|
| 1402 |
+
tm.assert_frame_equal(df, expected)
|
| 1403 |
+
|
| 1404 |
+
def test_iloc_setitem_view_2dblock(self, using_copy_on_write, warn_copy_on_write):
|
| 1405 |
+
# https://github.com/pandas-dev/pandas/issues/60309
|
| 1406 |
+
df_parent = DataFrame(
|
| 1407 |
+
{
|
| 1408 |
+
"A": [1, 4, 1, 5],
|
| 1409 |
+
"B": [2, 5, 2, 6],
|
| 1410 |
+
"C": [3, 6, 1, 7],
|
| 1411 |
+
"D": [8, 9, 10, 11],
|
| 1412 |
+
}
|
| 1413 |
+
)
|
| 1414 |
+
df_orig = df_parent.copy()
|
| 1415 |
+
df = df_parent[["B", "C"]]
|
| 1416 |
+
|
| 1417 |
+
# Perform the iloc operation
|
| 1418 |
+
if using_copy_on_write:
|
| 1419 |
+
df.iloc[[1, 3], :] = [[2, 2], [2, 2]]
|
| 1420 |
+
|
| 1421 |
+
# Check that original DataFrame is unchanged
|
| 1422 |
+
tm.assert_frame_equal(df_parent, df_orig)
|
| 1423 |
+
elif warn_copy_on_write:
|
| 1424 |
+
# TODO(COW): should this warn?
|
| 1425 |
+
# with tm.assert_cow_warning(warn_copy_on_write):
|
| 1426 |
+
df.iloc[[1, 3], :] = [[2, 2], [2, 2]]
|
| 1427 |
+
else:
|
| 1428 |
+
with pd.option_context("chained_assignment", "warn"):
|
| 1429 |
+
with tm.assert_produces_warning(SettingWithCopyWarning):
|
| 1430 |
+
df.iloc[[1, 3], :] = [[2, 2], [2, 2]]
|
| 1431 |
+
|
| 1432 |
+
# Check that df is modified correctly
|
| 1433 |
+
expected = DataFrame({"B": [2, 2, 2, 2], "C": [3, 2, 1, 2]}, index=df.index)
|
| 1434 |
+
tm.assert_frame_equal(df, expected)
|
| 1435 |
+
|
| 1436 |
+
# with setting to subset of columns
|
| 1437 |
+
df = df_parent[["B", "C", "D"]]
|
| 1438 |
+
if using_copy_on_write or warn_copy_on_write:
|
| 1439 |
+
df.iloc[[1, 3], 0:3:2] = [[2, 2], [2, 2]]
|
| 1440 |
+
tm.assert_frame_equal(df_parent, df_orig)
|
| 1441 |
+
else:
|
| 1442 |
+
with pd.option_context("chained_assignment", "warn"):
|
| 1443 |
+
with tm.assert_produces_warning(SettingWithCopyWarning):
|
| 1444 |
+
df.iloc[[1, 3], 0:3:2] = [[2, 2], [2, 2]]
|
| 1445 |
+
|
| 1446 |
+
expected = DataFrame(
|
| 1447 |
+
{"B": [2, 2, 2, 2], "C": [3, 6, 1, 7], "D": [8, 2, 10, 2]}, index=df.index
|
| 1448 |
+
)
|
| 1449 |
+
tm.assert_frame_equal(df, expected)
|
| 1450 |
+
|
| 1451 |
+
@pytest.mark.parametrize(
|
| 1452 |
+
"indexer, value",
|
| 1453 |
+
[
|
| 1454 |
+
(([0, 2], slice(None)), [[2, 2, 2, 2], [2, 2, 2, 2]]),
|
| 1455 |
+
((slice(None), slice(None)), 2),
|
| 1456 |
+
((0, [1, 3]), [2, 2]),
|
| 1457 |
+
(([0], 1), [2]),
|
| 1458 |
+
(([0], np.int64(1)), [2]),
|
| 1459 |
+
((slice(None), np.int64(1)), [2, 2, 2]),
|
| 1460 |
+
((slice(None, 2), np.int64(1)), [2, 2]),
|
| 1461 |
+
(
|
| 1462 |
+
(np.array([False, True, False]), np.array([False, True, False, True])),
|
| 1463 |
+
[2, 2],
|
| 1464 |
+
),
|
| 1465 |
+
],
|
| 1466 |
+
)
|
| 1467 |
+
def test_setitem_2dblock_with_ref(
|
| 1468 |
+
self, indexer, value, using_copy_on_write, warn_copy_on_write
|
| 1469 |
+
):
|
| 1470 |
+
# https://github.com/pandas-dev/pandas/issues/60309
|
| 1471 |
+
arr = np.arange(12).reshape(3, 4)
|
| 1472 |
+
|
| 1473 |
+
df_parent = DataFrame(arr.copy(), columns=list("ABCD"))
|
| 1474 |
+
# the test is specifically for the case where the df is backed by a single
|
| 1475 |
+
# block (taking the non-split path)
|
| 1476 |
+
assert df_parent._mgr.is_single_block
|
| 1477 |
+
df_orig = df_parent.copy()
|
| 1478 |
+
df = df_parent[:]
|
| 1479 |
+
|
| 1480 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 1481 |
+
df.iloc[indexer] = value
|
| 1482 |
+
|
| 1483 |
+
# Check that original DataFrame is unchanged
|
| 1484 |
+
if using_copy_on_write:
|
| 1485 |
+
tm.assert_frame_equal(df_parent, df_orig)
|
| 1486 |
+
|
| 1487 |
+
# Check that df is modified correctly
|
| 1488 |
+
arr[indexer] = value
|
| 1489 |
+
expected = DataFrame(arr, columns=list("ABCD"))
|
| 1490 |
+
tm.assert_frame_equal(df, expected)
|
| 1491 |
+
|
| 1492 |
+
|
| 1493 |
+
def test_full_setter_loc_incompatible_dtype():
|
| 1494 |
+
# https://github.com/pandas-dev/pandas/issues/55791
|
| 1495 |
+
df = DataFrame({"a": [1, 2]})
|
| 1496 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
| 1497 |
+
df.loc[:, "a"] = True
|
| 1498 |
+
expected = DataFrame({"a": [True, True]})
|
| 1499 |
+
tm.assert_frame_equal(df, expected)
|
| 1500 |
+
|
| 1501 |
+
df = DataFrame({"a": [1, 2]})
|
| 1502 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
| 1503 |
+
df.loc[:, "a"] = {0: 3.5, 1: 4.5}
|
| 1504 |
+
expected = DataFrame({"a": [3.5, 4.5]})
|
| 1505 |
+
tm.assert_frame_equal(df, expected)
|
| 1506 |
+
|
| 1507 |
+
df = DataFrame({"a": [1, 2]})
|
| 1508 |
+
df.loc[:, "a"] = {0: 3, 1: 4}
|
| 1509 |
+
expected = DataFrame({"a": [3, 4]})
|
| 1510 |
+
tm.assert_frame_equal(df, expected)
|
| 1511 |
+
|
| 1512 |
+
|
| 1513 |
+
def test_setitem_partial_row_multiple_columns():
|
| 1514 |
+
# https://github.com/pandas-dev/pandas/issues/56503
|
| 1515 |
+
df = DataFrame({"A": [1, 2, 3], "B": [4.0, 5, 6]})
|
| 1516 |
+
# should not warn
|
| 1517 |
+
df.loc[df.index <= 1, ["F", "G"]] = (1, "abc")
|
| 1518 |
+
expected = DataFrame(
|
| 1519 |
+
{
|
| 1520 |
+
"A": [1, 2, 3],
|
| 1521 |
+
"B": [4.0, 5, 6],
|
| 1522 |
+
"F": [1.0, 1, float("nan")],
|
| 1523 |
+
"G": ["abc", "abc", float("nan")],
|
| 1524 |
+
}
|
| 1525 |
+
)
|
| 1526 |
+
tm.assert_frame_equal(df, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_take.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas._testing as tm
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestDataFrameTake:
|
| 7 |
+
def test_take_slices_deprecated(self, float_frame):
|
| 8 |
+
# GH#51539
|
| 9 |
+
df = float_frame
|
| 10 |
+
|
| 11 |
+
slc = slice(0, 4, 1)
|
| 12 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 13 |
+
df.take(slc, axis=0)
|
| 14 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 15 |
+
df.take(slc, axis=1)
|
| 16 |
+
|
| 17 |
+
def test_take(self, float_frame):
|
| 18 |
+
# homogeneous
|
| 19 |
+
order = [3, 1, 2, 0]
|
| 20 |
+
for df in [float_frame]:
|
| 21 |
+
result = df.take(order, axis=0)
|
| 22 |
+
expected = df.reindex(df.index.take(order))
|
| 23 |
+
tm.assert_frame_equal(result, expected)
|
| 24 |
+
|
| 25 |
+
# axis = 1
|
| 26 |
+
result = df.take(order, axis=1)
|
| 27 |
+
expected = df.loc[:, ["D", "B", "C", "A"]]
|
| 28 |
+
tm.assert_frame_equal(result, expected, check_names=False)
|
| 29 |
+
|
| 30 |
+
# negative indices
|
| 31 |
+
order = [2, 1, -1]
|
| 32 |
+
for df in [float_frame]:
|
| 33 |
+
result = df.take(order, axis=0)
|
| 34 |
+
expected = df.reindex(df.index.take(order))
|
| 35 |
+
tm.assert_frame_equal(result, expected)
|
| 36 |
+
|
| 37 |
+
result = df.take(order, axis=0)
|
| 38 |
+
tm.assert_frame_equal(result, expected)
|
| 39 |
+
|
| 40 |
+
# axis = 1
|
| 41 |
+
result = df.take(order, axis=1)
|
| 42 |
+
expected = df.loc[:, ["C", "B", "D"]]
|
| 43 |
+
tm.assert_frame_equal(result, expected, check_names=False)
|
| 44 |
+
|
| 45 |
+
# illegal indices
|
| 46 |
+
msg = "indices are out-of-bounds"
|
| 47 |
+
with pytest.raises(IndexError, match=msg):
|
| 48 |
+
df.take([3, 1, 2, 30], axis=0)
|
| 49 |
+
with pytest.raises(IndexError, match=msg):
|
| 50 |
+
df.take([3, 1, 2, -31], axis=0)
|
| 51 |
+
with pytest.raises(IndexError, match=msg):
|
| 52 |
+
df.take([3, 1, 2, 5], axis=1)
|
| 53 |
+
with pytest.raises(IndexError, match=msg):
|
| 54 |
+
df.take([3, 1, 2, -5], axis=1)
|
| 55 |
+
|
| 56 |
+
def test_take_mixed_type(self, float_string_frame):
|
| 57 |
+
# mixed-dtype
|
| 58 |
+
order = [4, 1, 2, 0, 3]
|
| 59 |
+
for df in [float_string_frame]:
|
| 60 |
+
result = df.take(order, axis=0)
|
| 61 |
+
expected = df.reindex(df.index.take(order))
|
| 62 |
+
tm.assert_frame_equal(result, expected)
|
| 63 |
+
|
| 64 |
+
# axis = 1
|
| 65 |
+
result = df.take(order, axis=1)
|
| 66 |
+
expected = df.loc[:, ["foo", "B", "C", "A", "D"]]
|
| 67 |
+
tm.assert_frame_equal(result, expected)
|
| 68 |
+
|
| 69 |
+
# negative indices
|
| 70 |
+
order = [4, 1, -2]
|
| 71 |
+
for df in [float_string_frame]:
|
| 72 |
+
result = df.take(order, axis=0)
|
| 73 |
+
expected = df.reindex(df.index.take(order))
|
| 74 |
+
tm.assert_frame_equal(result, expected)
|
| 75 |
+
|
| 76 |
+
# axis = 1
|
| 77 |
+
result = df.take(order, axis=1)
|
| 78 |
+
expected = df.loc[:, ["foo", "B", "D"]]
|
| 79 |
+
tm.assert_frame_equal(result, expected)
|
| 80 |
+
|
| 81 |
+
def test_take_mixed_numeric(self, mixed_float_frame, mixed_int_frame):
|
| 82 |
+
# by dtype
|
| 83 |
+
order = [1, 2, 0, 3]
|
| 84 |
+
for df in [mixed_float_frame, mixed_int_frame]:
|
| 85 |
+
result = df.take(order, axis=0)
|
| 86 |
+
expected = df.reindex(df.index.take(order))
|
| 87 |
+
tm.assert_frame_equal(result, expected)
|
| 88 |
+
|
| 89 |
+
# axis = 1
|
| 90 |
+
result = df.take(order, axis=1)
|
| 91 |
+
expected = df.loc[:, ["B", "C", "A", "D"]]
|
| 92 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_where.py
ADDED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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
|
| 3 |
+
from hypothesis import given
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from pandas.core.dtypes.common import is_scalar
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from pandas import (
|
| 11 |
+
DataFrame,
|
| 12 |
+
DatetimeIndex,
|
| 13 |
+
Index,
|
| 14 |
+
Series,
|
| 15 |
+
StringDtype,
|
| 16 |
+
Timestamp,
|
| 17 |
+
date_range,
|
| 18 |
+
isna,
|
| 19 |
+
)
|
| 20 |
+
import pandas._testing as tm
|
| 21 |
+
from pandas._testing._hypothesis import OPTIONAL_ONE_OF_ALL
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.fixture(params=["default", "float_string", "mixed_float", "mixed_int"])
|
| 25 |
+
def where_frame(request, float_string_frame, mixed_float_frame, mixed_int_frame):
|
| 26 |
+
if request.param == "default":
|
| 27 |
+
return DataFrame(
|
| 28 |
+
np.random.default_rng(2).standard_normal((5, 3)), columns=["A", "B", "C"]
|
| 29 |
+
)
|
| 30 |
+
if request.param == "float_string":
|
| 31 |
+
return float_string_frame
|
| 32 |
+
if request.param == "mixed_float":
|
| 33 |
+
return mixed_float_frame
|
| 34 |
+
if request.param == "mixed_int":
|
| 35 |
+
return mixed_int_frame
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _safe_add(df):
|
| 39 |
+
# only add to the numeric items
|
| 40 |
+
def is_ok(s):
|
| 41 |
+
return (
|
| 42 |
+
issubclass(s.dtype.type, (np.integer, np.floating)) and s.dtype != "uint8"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
return DataFrame(dict((c, s + 1) if is_ok(s) else (c, s) for c, s in df.items()))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class TestDataFrameIndexingWhere:
|
| 49 |
+
def test_where_get(self, where_frame, float_string_frame):
|
| 50 |
+
def _check_get(df, cond, check_dtypes=True):
|
| 51 |
+
other1 = _safe_add(df)
|
| 52 |
+
rs = df.where(cond, other1)
|
| 53 |
+
rs2 = df.where(cond.values, other1)
|
| 54 |
+
for k, v in rs.items():
|
| 55 |
+
exp = Series(np.where(cond[k], df[k], other1[k]), index=v.index)
|
| 56 |
+
tm.assert_series_equal(v, exp, check_names=False)
|
| 57 |
+
tm.assert_frame_equal(rs, rs2)
|
| 58 |
+
|
| 59 |
+
# dtypes
|
| 60 |
+
if check_dtypes:
|
| 61 |
+
assert (rs.dtypes == df.dtypes).all()
|
| 62 |
+
|
| 63 |
+
# check getting
|
| 64 |
+
df = where_frame
|
| 65 |
+
if df is float_string_frame:
|
| 66 |
+
msg = (
|
| 67 |
+
"'>' not supported between instances of 'str' and 'int'"
|
| 68 |
+
"|Invalid comparison"
|
| 69 |
+
)
|
| 70 |
+
with pytest.raises(TypeError, match=msg):
|
| 71 |
+
df > 0
|
| 72 |
+
return
|
| 73 |
+
cond = df > 0
|
| 74 |
+
_check_get(df, cond)
|
| 75 |
+
|
| 76 |
+
def test_where_upcasting(self):
|
| 77 |
+
# upcasting case (GH # 2794)
|
| 78 |
+
df = DataFrame(
|
| 79 |
+
{
|
| 80 |
+
c: Series([1] * 3, dtype=c)
|
| 81 |
+
for c in ["float32", "float64", "int32", "int64"]
|
| 82 |
+
}
|
| 83 |
+
)
|
| 84 |
+
df.iloc[1, :] = 0
|
| 85 |
+
result = df.dtypes
|
| 86 |
+
expected = Series(
|
| 87 |
+
[
|
| 88 |
+
np.dtype("float32"),
|
| 89 |
+
np.dtype("float64"),
|
| 90 |
+
np.dtype("int32"),
|
| 91 |
+
np.dtype("int64"),
|
| 92 |
+
],
|
| 93 |
+
index=["float32", "float64", "int32", "int64"],
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# when we don't preserve boolean casts
|
| 97 |
+
#
|
| 98 |
+
# expected = Series({ 'float32' : 1, 'float64' : 3 })
|
| 99 |
+
|
| 100 |
+
tm.assert_series_equal(result, expected)
|
| 101 |
+
|
| 102 |
+
@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning")
|
| 103 |
+
def test_where_alignment(self, where_frame, float_string_frame):
|
| 104 |
+
# aligning
|
| 105 |
+
def _check_align(df, cond, other, check_dtypes=True):
|
| 106 |
+
rs = df.where(cond, other)
|
| 107 |
+
for i, k in enumerate(rs.columns):
|
| 108 |
+
result = rs[k]
|
| 109 |
+
d = df[k].values
|
| 110 |
+
c = cond[k].reindex(df[k].index).fillna(False).values
|
| 111 |
+
|
| 112 |
+
if is_scalar(other):
|
| 113 |
+
o = other
|
| 114 |
+
elif isinstance(other, np.ndarray):
|
| 115 |
+
o = Series(other[:, i], index=result.index).values
|
| 116 |
+
else:
|
| 117 |
+
o = other[k].values
|
| 118 |
+
|
| 119 |
+
new_values = d if c.all() else np.where(c, d, o)
|
| 120 |
+
expected = Series(new_values, index=result.index, name=k)
|
| 121 |
+
|
| 122 |
+
# since we can't always have the correct numpy dtype
|
| 123 |
+
# as numpy doesn't know how to downcast, don't check
|
| 124 |
+
tm.assert_series_equal(result, expected, check_dtype=False)
|
| 125 |
+
|
| 126 |
+
# dtypes
|
| 127 |
+
# can't check dtype when other is an ndarray
|
| 128 |
+
|
| 129 |
+
if check_dtypes and not isinstance(other, np.ndarray):
|
| 130 |
+
assert (rs.dtypes == df.dtypes).all()
|
| 131 |
+
|
| 132 |
+
df = where_frame
|
| 133 |
+
if df is float_string_frame:
|
| 134 |
+
msg = (
|
| 135 |
+
"'>' not supported between instances of 'str' and 'int'"
|
| 136 |
+
"|Invalid comparison"
|
| 137 |
+
)
|
| 138 |
+
with pytest.raises(TypeError, match=msg):
|
| 139 |
+
df > 0
|
| 140 |
+
return
|
| 141 |
+
|
| 142 |
+
# other is a frame
|
| 143 |
+
cond = (df > 0)[1:]
|
| 144 |
+
_check_align(df, cond, _safe_add(df))
|
| 145 |
+
|
| 146 |
+
# check other is ndarray
|
| 147 |
+
cond = df > 0
|
| 148 |
+
_check_align(df, cond, (_safe_add(df).values))
|
| 149 |
+
|
| 150 |
+
# integers are upcast, so don't check the dtypes
|
| 151 |
+
cond = df > 0
|
| 152 |
+
check_dtypes = all(not issubclass(s.type, np.integer) for s in df.dtypes)
|
| 153 |
+
_check_align(df, cond, np.nan, check_dtypes=check_dtypes)
|
| 154 |
+
|
| 155 |
+
# Ignore deprecation warning in Python 3.12 for inverting a bool
|
| 156 |
+
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
|
| 157 |
+
def test_where_invalid(self):
|
| 158 |
+
# invalid conditions
|
| 159 |
+
df = DataFrame(
|
| 160 |
+
np.random.default_rng(2).standard_normal((5, 3)), columns=["A", "B", "C"]
|
| 161 |
+
)
|
| 162 |
+
cond = df > 0
|
| 163 |
+
|
| 164 |
+
err1 = (df + 1).values[0:2, :]
|
| 165 |
+
msg = "other must be the same shape as self when an ndarray"
|
| 166 |
+
with pytest.raises(ValueError, match=msg):
|
| 167 |
+
df.where(cond, err1)
|
| 168 |
+
|
| 169 |
+
err2 = cond.iloc[:2, :].values
|
| 170 |
+
other1 = _safe_add(df)
|
| 171 |
+
msg = "Array conditional must be same shape as self"
|
| 172 |
+
with pytest.raises(ValueError, match=msg):
|
| 173 |
+
df.where(err2, other1)
|
| 174 |
+
|
| 175 |
+
with pytest.raises(ValueError, match=msg):
|
| 176 |
+
df.mask(True)
|
| 177 |
+
with pytest.raises(ValueError, match=msg):
|
| 178 |
+
df.mask(0)
|
| 179 |
+
|
| 180 |
+
@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning")
|
| 181 |
+
def test_where_set(self, where_frame, float_string_frame, mixed_int_frame):
|
| 182 |
+
# where inplace
|
| 183 |
+
|
| 184 |
+
def _check_set(df, cond, check_dtypes=True):
|
| 185 |
+
dfi = df.copy()
|
| 186 |
+
econd = cond.reindex_like(df).fillna(True).infer_objects(copy=False)
|
| 187 |
+
expected = dfi.mask(~econd)
|
| 188 |
+
|
| 189 |
+
return_value = dfi.where(cond, np.nan, inplace=True)
|
| 190 |
+
assert return_value is None
|
| 191 |
+
tm.assert_frame_equal(dfi, expected)
|
| 192 |
+
|
| 193 |
+
# dtypes (and confirm upcasts)x
|
| 194 |
+
if check_dtypes:
|
| 195 |
+
for k, v in df.dtypes.items():
|
| 196 |
+
if issubclass(v.type, np.integer) and not cond[k].all():
|
| 197 |
+
v = np.dtype("float64")
|
| 198 |
+
assert dfi[k].dtype == v
|
| 199 |
+
|
| 200 |
+
df = where_frame
|
| 201 |
+
if df is float_string_frame:
|
| 202 |
+
msg = (
|
| 203 |
+
"'>' not supported between instances of 'str' and 'int'"
|
| 204 |
+
"|Invalid comparison"
|
| 205 |
+
)
|
| 206 |
+
with pytest.raises(TypeError, match=msg):
|
| 207 |
+
df > 0
|
| 208 |
+
return
|
| 209 |
+
if df is mixed_int_frame:
|
| 210 |
+
df = df.astype("float64")
|
| 211 |
+
|
| 212 |
+
cond = df > 0
|
| 213 |
+
_check_set(df, cond)
|
| 214 |
+
|
| 215 |
+
cond = df >= 0
|
| 216 |
+
_check_set(df, cond)
|
| 217 |
+
|
| 218 |
+
# aligning
|
| 219 |
+
cond = (df >= 0)[1:]
|
| 220 |
+
_check_set(df, cond)
|
| 221 |
+
|
| 222 |
+
def test_where_series_slicing(self):
|
| 223 |
+
# GH 10218
|
| 224 |
+
# test DataFrame.where with Series slicing
|
| 225 |
+
df = DataFrame({"a": range(3), "b": range(4, 7)})
|
| 226 |
+
result = df.where(df["a"] == 1)
|
| 227 |
+
expected = df[df["a"] == 1].reindex(df.index)
|
| 228 |
+
tm.assert_frame_equal(result, expected)
|
| 229 |
+
|
| 230 |
+
@pytest.mark.parametrize("klass", [list, tuple, np.array])
|
| 231 |
+
def test_where_array_like(self, klass):
|
| 232 |
+
# see gh-15414
|
| 233 |
+
df = DataFrame({"a": [1, 2, 3]})
|
| 234 |
+
cond = [[False], [True], [True]]
|
| 235 |
+
expected = DataFrame({"a": [np.nan, 2, 3]})
|
| 236 |
+
|
| 237 |
+
result = df.where(klass(cond))
|
| 238 |
+
tm.assert_frame_equal(result, expected)
|
| 239 |
+
|
| 240 |
+
df["b"] = 2
|
| 241 |
+
expected["b"] = [2, np.nan, 2]
|
| 242 |
+
cond = [[False, True], [True, False], [True, True]]
|
| 243 |
+
|
| 244 |
+
result = df.where(klass(cond))
|
| 245 |
+
tm.assert_frame_equal(result, expected)
|
| 246 |
+
|
| 247 |
+
@pytest.mark.parametrize(
|
| 248 |
+
"cond",
|
| 249 |
+
[
|
| 250 |
+
[[1], [0], [1]],
|
| 251 |
+
Series([[2], [5], [7]]),
|
| 252 |
+
DataFrame({"a": [2, 5, 7]}),
|
| 253 |
+
[["True"], ["False"], ["True"]],
|
| 254 |
+
[[Timestamp("2017-01-01")], [pd.NaT], [Timestamp("2017-01-02")]],
|
| 255 |
+
],
|
| 256 |
+
)
|
| 257 |
+
def test_where_invalid_input_single(self, cond):
|
| 258 |
+
# see gh-15414: only boolean arrays accepted
|
| 259 |
+
df = DataFrame({"a": [1, 2, 3]})
|
| 260 |
+
msg = "Boolean array expected for the condition"
|
| 261 |
+
|
| 262 |
+
with pytest.raises(ValueError, match=msg):
|
| 263 |
+
df.where(cond)
|
| 264 |
+
|
| 265 |
+
@pytest.mark.parametrize(
|
| 266 |
+
"cond",
|
| 267 |
+
[
|
| 268 |
+
[[0, 1], [1, 0], [1, 1]],
|
| 269 |
+
Series([[0, 2], [5, 0], [4, 7]]),
|
| 270 |
+
[["False", "True"], ["True", "False"], ["True", "True"]],
|
| 271 |
+
DataFrame({"a": [2, 5, 7], "b": [4, 8, 9]}),
|
| 272 |
+
[
|
| 273 |
+
[pd.NaT, Timestamp("2017-01-01")],
|
| 274 |
+
[Timestamp("2017-01-02"), pd.NaT],
|
| 275 |
+
[Timestamp("2017-01-03"), Timestamp("2017-01-03")],
|
| 276 |
+
],
|
| 277 |
+
],
|
| 278 |
+
)
|
| 279 |
+
def test_where_invalid_input_multiple(self, cond):
|
| 280 |
+
# see gh-15414: only boolean arrays accepted
|
| 281 |
+
df = DataFrame({"a": [1, 2, 3], "b": [2, 2, 2]})
|
| 282 |
+
msg = "Boolean array expected for the condition"
|
| 283 |
+
|
| 284 |
+
with pytest.raises(ValueError, match=msg):
|
| 285 |
+
df.where(cond)
|
| 286 |
+
|
| 287 |
+
def test_where_dataframe_col_match(self):
|
| 288 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6]])
|
| 289 |
+
cond = DataFrame([[True, False, True], [False, False, True]])
|
| 290 |
+
|
| 291 |
+
result = df.where(cond)
|
| 292 |
+
expected = DataFrame([[1.0, np.nan, 3], [np.nan, np.nan, 6]])
|
| 293 |
+
tm.assert_frame_equal(result, expected)
|
| 294 |
+
|
| 295 |
+
# this *does* align, though has no matching columns
|
| 296 |
+
cond.columns = ["a", "b", "c"]
|
| 297 |
+
result = df.where(cond)
|
| 298 |
+
expected = DataFrame(np.nan, index=df.index, columns=df.columns)
|
| 299 |
+
tm.assert_frame_equal(result, expected)
|
| 300 |
+
|
| 301 |
+
def test_where_ndframe_align(self):
|
| 302 |
+
msg = "Array conditional must be same shape as self"
|
| 303 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6]])
|
| 304 |
+
|
| 305 |
+
cond = [True]
|
| 306 |
+
with pytest.raises(ValueError, match=msg):
|
| 307 |
+
df.where(cond)
|
| 308 |
+
|
| 309 |
+
expected = DataFrame([[1, 2, 3], [np.nan, np.nan, np.nan]])
|
| 310 |
+
|
| 311 |
+
out = df.where(Series(cond))
|
| 312 |
+
tm.assert_frame_equal(out, expected)
|
| 313 |
+
|
| 314 |
+
cond = np.array([False, True, False, True])
|
| 315 |
+
with pytest.raises(ValueError, match=msg):
|
| 316 |
+
df.where(cond)
|
| 317 |
+
|
| 318 |
+
expected = DataFrame([[np.nan, np.nan, np.nan], [4, 5, 6]])
|
| 319 |
+
|
| 320 |
+
out = df.where(Series(cond))
|
| 321 |
+
tm.assert_frame_equal(out, expected)
|
| 322 |
+
|
| 323 |
+
def test_where_bug(self):
|
| 324 |
+
# see gh-2793
|
| 325 |
+
df = DataFrame(
|
| 326 |
+
{"a": [1.0, 2.0, 3.0, 4.0], "b": [4.0, 3.0, 2.0, 1.0]}, dtype="float64"
|
| 327 |
+
)
|
| 328 |
+
expected = DataFrame(
|
| 329 |
+
{"a": [np.nan, np.nan, 3.0, 4.0], "b": [4.0, 3.0, np.nan, np.nan]},
|
| 330 |
+
dtype="float64",
|
| 331 |
+
)
|
| 332 |
+
result = df.where(df > 2, np.nan)
|
| 333 |
+
tm.assert_frame_equal(result, expected)
|
| 334 |
+
|
| 335 |
+
result = df.copy()
|
| 336 |
+
return_value = result.where(result > 2, np.nan, inplace=True)
|
| 337 |
+
assert return_value is None
|
| 338 |
+
tm.assert_frame_equal(result, expected)
|
| 339 |
+
|
| 340 |
+
def test_where_bug_mixed(self, any_signed_int_numpy_dtype):
|
| 341 |
+
# see gh-2793
|
| 342 |
+
df = DataFrame(
|
| 343 |
+
{
|
| 344 |
+
"a": np.array([1, 2, 3, 4], dtype=any_signed_int_numpy_dtype),
|
| 345 |
+
"b": np.array([4.0, 3.0, 2.0, 1.0], dtype="float64"),
|
| 346 |
+
}
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
expected = DataFrame(
|
| 350 |
+
{"a": [-1, -1, 3, 4], "b": [4.0, 3.0, -1, -1]},
|
| 351 |
+
).astype({"a": any_signed_int_numpy_dtype, "b": "float64"})
|
| 352 |
+
|
| 353 |
+
result = df.where(df > 2, -1)
|
| 354 |
+
tm.assert_frame_equal(result, expected)
|
| 355 |
+
|
| 356 |
+
result = df.copy()
|
| 357 |
+
return_value = result.where(result > 2, -1, inplace=True)
|
| 358 |
+
assert return_value is None
|
| 359 |
+
tm.assert_frame_equal(result, expected)
|
| 360 |
+
|
| 361 |
+
def test_where_bug_transposition(self):
|
| 362 |
+
# see gh-7506
|
| 363 |
+
a = DataFrame({0: [1, 2], 1: [3, 4], 2: [5, 6]})
|
| 364 |
+
b = DataFrame({0: [np.nan, 8], 1: [9, np.nan], 2: [np.nan, np.nan]})
|
| 365 |
+
do_not_replace = b.isna() | (a > b)
|
| 366 |
+
|
| 367 |
+
expected = a.copy()
|
| 368 |
+
expected[~do_not_replace] = b
|
| 369 |
+
|
| 370 |
+
msg = "Downcasting behavior in Series and DataFrame methods 'where'"
|
| 371 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 372 |
+
result = a.where(do_not_replace, b)
|
| 373 |
+
tm.assert_frame_equal(result, expected)
|
| 374 |
+
|
| 375 |
+
a = DataFrame({0: [4, 6], 1: [1, 0]})
|
| 376 |
+
b = DataFrame({0: [np.nan, 3], 1: [3, np.nan]})
|
| 377 |
+
do_not_replace = b.isna() | (a > b)
|
| 378 |
+
|
| 379 |
+
expected = a.copy()
|
| 380 |
+
expected[~do_not_replace] = b
|
| 381 |
+
|
| 382 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 383 |
+
result = a.where(do_not_replace, b)
|
| 384 |
+
tm.assert_frame_equal(result, expected)
|
| 385 |
+
|
| 386 |
+
def test_where_datetime(self):
|
| 387 |
+
# GH 3311
|
| 388 |
+
df = DataFrame(
|
| 389 |
+
{
|
| 390 |
+
"A": date_range("20130102", periods=5),
|
| 391 |
+
"B": date_range("20130104", periods=5),
|
| 392 |
+
"C": np.random.default_rng(2).standard_normal(5),
|
| 393 |
+
}
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
stamp = datetime(2013, 1, 3)
|
| 397 |
+
msg = "'>' not supported between instances of 'float' and 'datetime.datetime'"
|
| 398 |
+
with pytest.raises(TypeError, match=msg):
|
| 399 |
+
df > stamp
|
| 400 |
+
|
| 401 |
+
result = df[df.iloc[:, :-1] > stamp]
|
| 402 |
+
|
| 403 |
+
expected = df.copy()
|
| 404 |
+
expected.loc[[0, 1], "A"] = np.nan
|
| 405 |
+
|
| 406 |
+
expected.loc[:, "C"] = np.nan
|
| 407 |
+
tm.assert_frame_equal(result, expected)
|
| 408 |
+
|
| 409 |
+
def test_where_none(self):
|
| 410 |
+
# GH 4667
|
| 411 |
+
# setting with None changes dtype
|
| 412 |
+
df = DataFrame({"series": Series(range(10))}).astype(float)
|
| 413 |
+
df[df > 7] = None
|
| 414 |
+
expected = DataFrame(
|
| 415 |
+
{"series": Series([0, 1, 2, 3, 4, 5, 6, 7, np.nan, np.nan])}
|
| 416 |
+
)
|
| 417 |
+
tm.assert_frame_equal(df, expected)
|
| 418 |
+
|
| 419 |
+
# GH 7656
|
| 420 |
+
df = DataFrame(
|
| 421 |
+
[
|
| 422 |
+
{"A": 1, "B": np.nan, "C": "Test"},
|
| 423 |
+
{"A": np.nan, "B": "Test", "C": np.nan},
|
| 424 |
+
]
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
orig = df.copy()
|
| 428 |
+
|
| 429 |
+
mask = ~isna(df)
|
| 430 |
+
df.where(mask, None, inplace=True)
|
| 431 |
+
expected = DataFrame(
|
| 432 |
+
{
|
| 433 |
+
"A": [1.0, np.nan],
|
| 434 |
+
"B": [None, "Test"],
|
| 435 |
+
"C": ["Test", None],
|
| 436 |
+
}
|
| 437 |
+
)
|
| 438 |
+
tm.assert_frame_equal(df, expected)
|
| 439 |
+
|
| 440 |
+
df = orig.copy()
|
| 441 |
+
df[~mask] = None
|
| 442 |
+
tm.assert_frame_equal(df, expected)
|
| 443 |
+
|
| 444 |
+
def test_where_empty_df_and_empty_cond_having_non_bool_dtypes(self):
|
| 445 |
+
# see gh-21947
|
| 446 |
+
df = DataFrame(columns=["a"])
|
| 447 |
+
cond = df
|
| 448 |
+
assert (cond.dtypes == object).all()
|
| 449 |
+
|
| 450 |
+
result = df.where(cond)
|
| 451 |
+
tm.assert_frame_equal(result, df)
|
| 452 |
+
|
| 453 |
+
def test_where_align(self):
|
| 454 |
+
def create():
|
| 455 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 3)))
|
| 456 |
+
df.iloc[3:5, 0] = np.nan
|
| 457 |
+
df.iloc[4:6, 1] = np.nan
|
| 458 |
+
df.iloc[5:8, 2] = np.nan
|
| 459 |
+
return df
|
| 460 |
+
|
| 461 |
+
# series
|
| 462 |
+
df = create()
|
| 463 |
+
expected = df.fillna(df.mean())
|
| 464 |
+
result = df.where(pd.notna(df), df.mean(), axis="columns")
|
| 465 |
+
tm.assert_frame_equal(result, expected)
|
| 466 |
+
|
| 467 |
+
return_value = df.where(pd.notna(df), df.mean(), inplace=True, axis="columns")
|
| 468 |
+
assert return_value is None
|
| 469 |
+
tm.assert_frame_equal(df, expected)
|
| 470 |
+
|
| 471 |
+
df = create().fillna(0)
|
| 472 |
+
expected = df.apply(lambda x, y: x.where(x > 0, y), y=df[0])
|
| 473 |
+
result = df.where(df > 0, df[0], axis="index")
|
| 474 |
+
tm.assert_frame_equal(result, expected)
|
| 475 |
+
result = df.where(df > 0, df[0], axis="rows")
|
| 476 |
+
tm.assert_frame_equal(result, expected)
|
| 477 |
+
|
| 478 |
+
# frame
|
| 479 |
+
df = create()
|
| 480 |
+
expected = df.fillna(1)
|
| 481 |
+
result = df.where(
|
| 482 |
+
pd.notna(df), DataFrame(1, index=df.index, columns=df.columns)
|
| 483 |
+
)
|
| 484 |
+
tm.assert_frame_equal(result, expected)
|
| 485 |
+
|
| 486 |
+
def test_where_complex(self):
|
| 487 |
+
# GH 6345
|
| 488 |
+
expected = DataFrame([[1 + 1j, 2], [np.nan, 4 + 1j]], columns=["a", "b"])
|
| 489 |
+
df = DataFrame([[1 + 1j, 2], [5 + 1j, 4 + 1j]], columns=["a", "b"])
|
| 490 |
+
df[df.abs() >= 5] = np.nan
|
| 491 |
+
tm.assert_frame_equal(df, expected)
|
| 492 |
+
|
| 493 |
+
def test_where_axis(self):
|
| 494 |
+
# GH 9736
|
| 495 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((2, 2)))
|
| 496 |
+
mask = DataFrame([[False, False], [False, False]])
|
| 497 |
+
ser = Series([0, 1])
|
| 498 |
+
|
| 499 |
+
expected = DataFrame([[0, 0], [1, 1]], dtype="float64")
|
| 500 |
+
result = df.where(mask, ser, axis="index")
|
| 501 |
+
tm.assert_frame_equal(result, expected)
|
| 502 |
+
|
| 503 |
+
result = df.copy()
|
| 504 |
+
return_value = result.where(mask, ser, axis="index", inplace=True)
|
| 505 |
+
assert return_value is None
|
| 506 |
+
tm.assert_frame_equal(result, expected)
|
| 507 |
+
|
| 508 |
+
expected = DataFrame([[0, 1], [0, 1]], dtype="float64")
|
| 509 |
+
result = df.where(mask, ser, axis="columns")
|
| 510 |
+
tm.assert_frame_equal(result, expected)
|
| 511 |
+
|
| 512 |
+
result = df.copy()
|
| 513 |
+
return_value = result.where(mask, ser, axis="columns", inplace=True)
|
| 514 |
+
assert return_value is None
|
| 515 |
+
tm.assert_frame_equal(result, expected)
|
| 516 |
+
|
| 517 |
+
def test_where_axis_with_upcast(self):
|
| 518 |
+
# Upcast needed
|
| 519 |
+
df = DataFrame([[1, 2], [3, 4]], dtype="int64")
|
| 520 |
+
mask = DataFrame([[False, False], [False, False]])
|
| 521 |
+
ser = Series([0, np.nan])
|
| 522 |
+
|
| 523 |
+
expected = DataFrame([[0, 0], [np.nan, np.nan]], dtype="float64")
|
| 524 |
+
result = df.where(mask, ser, axis="index")
|
| 525 |
+
tm.assert_frame_equal(result, expected)
|
| 526 |
+
|
| 527 |
+
result = df.copy()
|
| 528 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
| 529 |
+
return_value = result.where(mask, ser, axis="index", inplace=True)
|
| 530 |
+
assert return_value is None
|
| 531 |
+
tm.assert_frame_equal(result, expected)
|
| 532 |
+
|
| 533 |
+
expected = DataFrame([[0, np.nan], [0, np.nan]])
|
| 534 |
+
result = df.where(mask, ser, axis="columns")
|
| 535 |
+
tm.assert_frame_equal(result, expected)
|
| 536 |
+
|
| 537 |
+
expected = DataFrame(
|
| 538 |
+
{
|
| 539 |
+
0: np.array([0, 0], dtype="int64"),
|
| 540 |
+
1: np.array([np.nan, np.nan], dtype="float64"),
|
| 541 |
+
}
|
| 542 |
+
)
|
| 543 |
+
result = df.copy()
|
| 544 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
| 545 |
+
return_value = result.where(mask, ser, axis="columns", inplace=True)
|
| 546 |
+
assert return_value is None
|
| 547 |
+
tm.assert_frame_equal(result, expected)
|
| 548 |
+
|
| 549 |
+
def test_where_axis_multiple_dtypes(self):
|
| 550 |
+
# Multiple dtypes (=> multiple Blocks)
|
| 551 |
+
df = pd.concat(
|
| 552 |
+
[
|
| 553 |
+
DataFrame(np.random.default_rng(2).standard_normal((10, 2))),
|
| 554 |
+
DataFrame(
|
| 555 |
+
np.random.default_rng(2).integers(0, 10, size=(10, 2)),
|
| 556 |
+
dtype="int64",
|
| 557 |
+
),
|
| 558 |
+
],
|
| 559 |
+
ignore_index=True,
|
| 560 |
+
axis=1,
|
| 561 |
+
)
|
| 562 |
+
mask = DataFrame(False, columns=df.columns, index=df.index)
|
| 563 |
+
s1 = Series(1, index=df.columns)
|
| 564 |
+
s2 = Series(2, index=df.index)
|
| 565 |
+
|
| 566 |
+
result = df.where(mask, s1, axis="columns")
|
| 567 |
+
expected = DataFrame(1.0, columns=df.columns, index=df.index)
|
| 568 |
+
expected[2] = expected[2].astype("int64")
|
| 569 |
+
expected[3] = expected[3].astype("int64")
|
| 570 |
+
tm.assert_frame_equal(result, expected)
|
| 571 |
+
|
| 572 |
+
result = df.copy()
|
| 573 |
+
return_value = result.where(mask, s1, axis="columns", inplace=True)
|
| 574 |
+
assert return_value is None
|
| 575 |
+
tm.assert_frame_equal(result, expected)
|
| 576 |
+
|
| 577 |
+
result = df.where(mask, s2, axis="index")
|
| 578 |
+
expected = DataFrame(2.0, columns=df.columns, index=df.index)
|
| 579 |
+
expected[2] = expected[2].astype("int64")
|
| 580 |
+
expected[3] = expected[3].astype("int64")
|
| 581 |
+
tm.assert_frame_equal(result, expected)
|
| 582 |
+
|
| 583 |
+
result = df.copy()
|
| 584 |
+
return_value = result.where(mask, s2, axis="index", inplace=True)
|
| 585 |
+
assert return_value is None
|
| 586 |
+
tm.assert_frame_equal(result, expected)
|
| 587 |
+
|
| 588 |
+
# DataFrame vs DataFrame
|
| 589 |
+
d1 = df.copy().drop(1, axis=0)
|
| 590 |
+
# Explicit cast to avoid implicit cast when setting value to np.nan
|
| 591 |
+
expected = df.copy().astype("float")
|
| 592 |
+
expected.loc[1, :] = np.nan
|
| 593 |
+
|
| 594 |
+
result = df.where(mask, d1)
|
| 595 |
+
tm.assert_frame_equal(result, expected)
|
| 596 |
+
result = df.where(mask, d1, axis="index")
|
| 597 |
+
tm.assert_frame_equal(result, expected)
|
| 598 |
+
result = df.copy()
|
| 599 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
| 600 |
+
return_value = result.where(mask, d1, inplace=True)
|
| 601 |
+
assert return_value is None
|
| 602 |
+
tm.assert_frame_equal(result, expected)
|
| 603 |
+
result = df.copy()
|
| 604 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
| 605 |
+
return_value = result.where(mask, d1, inplace=True, axis="index")
|
| 606 |
+
assert return_value is None
|
| 607 |
+
tm.assert_frame_equal(result, expected)
|
| 608 |
+
|
| 609 |
+
d2 = df.copy().drop(1, axis=1)
|
| 610 |
+
expected = df.copy()
|
| 611 |
+
expected.loc[:, 1] = np.nan
|
| 612 |
+
|
| 613 |
+
result = df.where(mask, d2)
|
| 614 |
+
tm.assert_frame_equal(result, expected)
|
| 615 |
+
result = df.where(mask, d2, axis="columns")
|
| 616 |
+
tm.assert_frame_equal(result, expected)
|
| 617 |
+
result = df.copy()
|
| 618 |
+
return_value = result.where(mask, d2, inplace=True)
|
| 619 |
+
assert return_value is None
|
| 620 |
+
tm.assert_frame_equal(result, expected)
|
| 621 |
+
result = df.copy()
|
| 622 |
+
return_value = result.where(mask, d2, inplace=True, axis="columns")
|
| 623 |
+
assert return_value is None
|
| 624 |
+
tm.assert_frame_equal(result, expected)
|
| 625 |
+
|
| 626 |
+
def test_where_callable(self):
|
| 627 |
+
# GH 12533
|
| 628 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 629 |
+
result = df.where(lambda x: x > 4, lambda x: x + 1)
|
| 630 |
+
exp = DataFrame([[2, 3, 4], [5, 5, 6], [7, 8, 9]])
|
| 631 |
+
tm.assert_frame_equal(result, exp)
|
| 632 |
+
tm.assert_frame_equal(result, df.where(df > 4, df + 1))
|
| 633 |
+
|
| 634 |
+
# return ndarray and scalar
|
| 635 |
+
result = df.where(lambda x: (x % 2 == 0).values, lambda x: 99)
|
| 636 |
+
exp = DataFrame([[99, 2, 99], [4, 99, 6], [99, 8, 99]])
|
| 637 |
+
tm.assert_frame_equal(result, exp)
|
| 638 |
+
tm.assert_frame_equal(result, df.where(df % 2 == 0, 99))
|
| 639 |
+
|
| 640 |
+
# chain
|
| 641 |
+
result = (df + 2).where(lambda x: x > 8, lambda x: x + 10)
|
| 642 |
+
exp = DataFrame([[13, 14, 15], [16, 17, 18], [9, 10, 11]])
|
| 643 |
+
tm.assert_frame_equal(result, exp)
|
| 644 |
+
tm.assert_frame_equal(result, (df + 2).where((df + 2) > 8, (df + 2) + 10))
|
| 645 |
+
|
| 646 |
+
def test_where_tz_values(self, tz_naive_fixture, frame_or_series):
|
| 647 |
+
obj1 = DataFrame(
|
| 648 |
+
DatetimeIndex(["20150101", "20150102", "20150103"], tz=tz_naive_fixture),
|
| 649 |
+
columns=["date"],
|
| 650 |
+
)
|
| 651 |
+
obj2 = DataFrame(
|
| 652 |
+
DatetimeIndex(["20150103", "20150104", "20150105"], tz=tz_naive_fixture),
|
| 653 |
+
columns=["date"],
|
| 654 |
+
)
|
| 655 |
+
mask = DataFrame([True, True, False], columns=["date"])
|
| 656 |
+
exp = DataFrame(
|
| 657 |
+
DatetimeIndex(["20150101", "20150102", "20150105"], tz=tz_naive_fixture),
|
| 658 |
+
columns=["date"],
|
| 659 |
+
)
|
| 660 |
+
if frame_or_series is Series:
|
| 661 |
+
obj1 = obj1["date"]
|
| 662 |
+
obj2 = obj2["date"]
|
| 663 |
+
mask = mask["date"]
|
| 664 |
+
exp = exp["date"]
|
| 665 |
+
|
| 666 |
+
result = obj1.where(mask, obj2)
|
| 667 |
+
tm.assert_equal(exp, result)
|
| 668 |
+
|
| 669 |
+
def test_df_where_change_dtype(self):
|
| 670 |
+
# GH#16979
|
| 671 |
+
df = DataFrame(np.arange(2 * 3).reshape(2, 3), columns=list("ABC"))
|
| 672 |
+
mask = np.array([[True, False, False], [False, False, True]])
|
| 673 |
+
|
| 674 |
+
result = df.where(mask)
|
| 675 |
+
expected = DataFrame(
|
| 676 |
+
[[0, np.nan, np.nan], [np.nan, np.nan, 5]], columns=list("ABC")
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
tm.assert_frame_equal(result, expected)
|
| 680 |
+
|
| 681 |
+
@pytest.mark.parametrize("kwargs", [{}, {"other": None}])
|
| 682 |
+
def test_df_where_with_category(self, kwargs):
|
| 683 |
+
# GH#16979
|
| 684 |
+
data = np.arange(2 * 3, dtype=np.int64).reshape(2, 3)
|
| 685 |
+
df = DataFrame(data, columns=list("ABC"))
|
| 686 |
+
mask = np.array([[True, False, False], [False, False, True]])
|
| 687 |
+
|
| 688 |
+
# change type to category
|
| 689 |
+
df.A = df.A.astype("category")
|
| 690 |
+
df.B = df.B.astype("category")
|
| 691 |
+
df.C = df.C.astype("category")
|
| 692 |
+
|
| 693 |
+
result = df.where(mask, **kwargs)
|
| 694 |
+
A = pd.Categorical([0, np.nan], categories=[0, 3])
|
| 695 |
+
B = pd.Categorical([np.nan, np.nan], categories=[1, 4])
|
| 696 |
+
C = pd.Categorical([np.nan, 5], categories=[2, 5])
|
| 697 |
+
expected = DataFrame({"A": A, "B": B, "C": C})
|
| 698 |
+
|
| 699 |
+
tm.assert_frame_equal(result, expected)
|
| 700 |
+
|
| 701 |
+
# Check Series.where while we're here
|
| 702 |
+
result = df.A.where(mask[:, 0], **kwargs)
|
| 703 |
+
expected = Series(A, name="A")
|
| 704 |
+
|
| 705 |
+
tm.assert_series_equal(result, expected)
|
| 706 |
+
|
| 707 |
+
def test_where_categorical_filtering(self):
|
| 708 |
+
# GH#22609 Verify filtering operations on DataFrames with categorical Series
|
| 709 |
+
df = DataFrame(data=[[0, 0], [1, 1]], columns=["a", "b"])
|
| 710 |
+
df["b"] = df["b"].astype("category")
|
| 711 |
+
|
| 712 |
+
result = df.where(df["a"] > 0)
|
| 713 |
+
# Explicitly cast to 'float' to avoid implicit cast when setting np.nan
|
| 714 |
+
expected = df.copy().astype({"a": "float"})
|
| 715 |
+
expected.loc[0, :] = np.nan
|
| 716 |
+
|
| 717 |
+
tm.assert_equal(result, expected)
|
| 718 |
+
|
| 719 |
+
def test_where_ea_other(self):
|
| 720 |
+
# GH#38729/GH#38742
|
| 721 |
+
df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
|
| 722 |
+
arr = pd.array([7, pd.NA, 9])
|
| 723 |
+
ser = Series(arr)
|
| 724 |
+
mask = np.ones(df.shape, dtype=bool)
|
| 725 |
+
mask[1, :] = False
|
| 726 |
+
|
| 727 |
+
# TODO: ideally we would get Int64 instead of object
|
| 728 |
+
result = df.where(mask, ser, axis=0)
|
| 729 |
+
expected = DataFrame({"A": [1, np.nan, 3], "B": [4, np.nan, 6]})
|
| 730 |
+
tm.assert_frame_equal(result, expected)
|
| 731 |
+
|
| 732 |
+
ser2 = Series(arr[:2], index=["A", "B"])
|
| 733 |
+
expected = DataFrame({"A": [1, 7, 3], "B": [4, np.nan, 6]})
|
| 734 |
+
result = df.where(mask, ser2, axis=1)
|
| 735 |
+
tm.assert_frame_equal(result, expected)
|
| 736 |
+
|
| 737 |
+
def test_where_interval_noop(self):
|
| 738 |
+
# GH#44181
|
| 739 |
+
df = DataFrame([pd.Interval(0, 0)])
|
| 740 |
+
res = df.where(df.notna())
|
| 741 |
+
tm.assert_frame_equal(res, df)
|
| 742 |
+
|
| 743 |
+
ser = df[0]
|
| 744 |
+
res = ser.where(ser.notna())
|
| 745 |
+
tm.assert_series_equal(res, ser)
|
| 746 |
+
|
| 747 |
+
def test_where_interval_fullop_downcast(self, frame_or_series):
|
| 748 |
+
# GH#45768
|
| 749 |
+
obj = frame_or_series([pd.Interval(0, 0)] * 2)
|
| 750 |
+
other = frame_or_series([1.0, 2.0])
|
| 751 |
+
|
| 752 |
+
msg = "Downcasting behavior in Series and DataFrame methods 'where'"
|
| 753 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 754 |
+
res = obj.where(~obj.notna(), other)
|
| 755 |
+
|
| 756 |
+
# since all entries are being changed, we will downcast result
|
| 757 |
+
# from object to ints (not floats)
|
| 758 |
+
tm.assert_equal(res, other.astype(np.int64))
|
| 759 |
+
|
| 760 |
+
# unlike where, Block.putmask does not downcast
|
| 761 |
+
with tm.assert_produces_warning(
|
| 762 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 763 |
+
):
|
| 764 |
+
obj.mask(obj.notna(), other, inplace=True)
|
| 765 |
+
tm.assert_equal(obj, other.astype(object))
|
| 766 |
+
|
| 767 |
+
@pytest.mark.parametrize(
|
| 768 |
+
"dtype",
|
| 769 |
+
[
|
| 770 |
+
"timedelta64[ns]",
|
| 771 |
+
"datetime64[ns]",
|
| 772 |
+
"datetime64[ns, Asia/Tokyo]",
|
| 773 |
+
"Period[D]",
|
| 774 |
+
],
|
| 775 |
+
)
|
| 776 |
+
def test_where_datetimelike_noop(self, dtype):
|
| 777 |
+
# GH#45135, analogue to GH#44181 for Period don't raise on no-op
|
| 778 |
+
# For td64/dt64/dt64tz we already don't raise, but also are
|
| 779 |
+
# checking that we don't unnecessarily upcast to object.
|
| 780 |
+
with tm.assert_produces_warning(FutureWarning, match="is deprecated"):
|
| 781 |
+
ser = Series(np.arange(3) * 10**9, dtype=np.int64).view(dtype)
|
| 782 |
+
df = ser.to_frame()
|
| 783 |
+
mask = np.array([False, False, False])
|
| 784 |
+
|
| 785 |
+
res = ser.where(~mask, "foo")
|
| 786 |
+
tm.assert_series_equal(res, ser)
|
| 787 |
+
|
| 788 |
+
mask2 = mask.reshape(-1, 1)
|
| 789 |
+
res2 = df.where(~mask2, "foo")
|
| 790 |
+
tm.assert_frame_equal(res2, df)
|
| 791 |
+
|
| 792 |
+
res3 = ser.mask(mask, "foo")
|
| 793 |
+
tm.assert_series_equal(res3, ser)
|
| 794 |
+
|
| 795 |
+
res4 = df.mask(mask2, "foo")
|
| 796 |
+
tm.assert_frame_equal(res4, df)
|
| 797 |
+
|
| 798 |
+
# opposite case where we are replacing *all* values -> we downcast
|
| 799 |
+
# from object dtype # GH#45768
|
| 800 |
+
msg = "Downcasting behavior in Series and DataFrame methods 'where'"
|
| 801 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 802 |
+
res5 = df.where(mask2, 4)
|
| 803 |
+
expected = DataFrame(4, index=df.index, columns=df.columns)
|
| 804 |
+
tm.assert_frame_equal(res5, expected)
|
| 805 |
+
|
| 806 |
+
# unlike where, Block.putmask does not downcast
|
| 807 |
+
with tm.assert_produces_warning(
|
| 808 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 809 |
+
):
|
| 810 |
+
df.mask(~mask2, 4, inplace=True)
|
| 811 |
+
tm.assert_frame_equal(df, expected.astype(object))
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def test_where_int_downcasting_deprecated():
|
| 815 |
+
# GH#44597
|
| 816 |
+
arr = np.arange(6).astype(np.int16).reshape(3, 2)
|
| 817 |
+
df = DataFrame(arr)
|
| 818 |
+
|
| 819 |
+
mask = np.zeros(arr.shape, dtype=bool)
|
| 820 |
+
mask[:, 0] = True
|
| 821 |
+
|
| 822 |
+
res = df.where(mask, 2**17)
|
| 823 |
+
|
| 824 |
+
expected = DataFrame({0: arr[:, 0], 1: np.array([2**17] * 3, dtype=np.int32)})
|
| 825 |
+
tm.assert_frame_equal(res, expected)
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
def test_where_copies_with_noop(frame_or_series):
|
| 829 |
+
# GH-39595
|
| 830 |
+
result = frame_or_series([1, 2, 3, 4])
|
| 831 |
+
expected = result.copy()
|
| 832 |
+
col = result[0] if frame_or_series is DataFrame else result
|
| 833 |
+
|
| 834 |
+
where_res = result.where(col < 5)
|
| 835 |
+
where_res *= 2
|
| 836 |
+
|
| 837 |
+
tm.assert_equal(result, expected)
|
| 838 |
+
|
| 839 |
+
where_res = result.where(col > 5, [1, 2, 3, 4])
|
| 840 |
+
where_res *= 2
|
| 841 |
+
|
| 842 |
+
tm.assert_equal(result, expected)
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
def test_where_string_dtype(frame_or_series):
|
| 846 |
+
# GH40824
|
| 847 |
+
obj = frame_or_series(
|
| 848 |
+
["a", "b", "c", "d"], index=["id1", "id2", "id3", "id4"], dtype=StringDtype()
|
| 849 |
+
)
|
| 850 |
+
filtered_obj = frame_or_series(
|
| 851 |
+
["b", "c"], index=["id2", "id3"], dtype=StringDtype()
|
| 852 |
+
)
|
| 853 |
+
filter_ser = Series([False, True, True, False])
|
| 854 |
+
|
| 855 |
+
result = obj.where(filter_ser, filtered_obj)
|
| 856 |
+
expected = frame_or_series(
|
| 857 |
+
[pd.NA, "b", "c", pd.NA],
|
| 858 |
+
index=["id1", "id2", "id3", "id4"],
|
| 859 |
+
dtype=StringDtype(),
|
| 860 |
+
)
|
| 861 |
+
tm.assert_equal(result, expected)
|
| 862 |
+
|
| 863 |
+
result = obj.mask(~filter_ser, filtered_obj)
|
| 864 |
+
tm.assert_equal(result, expected)
|
| 865 |
+
|
| 866 |
+
obj.mask(~filter_ser, filtered_obj, inplace=True)
|
| 867 |
+
tm.assert_equal(result, expected)
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def test_where_bool_comparison():
|
| 871 |
+
# GH 10336
|
| 872 |
+
df_mask = DataFrame(
|
| 873 |
+
{"AAA": [True] * 4, "BBB": [False] * 4, "CCC": [True, False, True, False]}
|
| 874 |
+
)
|
| 875 |
+
result = df_mask.where(df_mask == False) # noqa: E712
|
| 876 |
+
expected = DataFrame(
|
| 877 |
+
{
|
| 878 |
+
"AAA": np.array([np.nan] * 4, dtype=object),
|
| 879 |
+
"BBB": [False] * 4,
|
| 880 |
+
"CCC": [np.nan, False, np.nan, False],
|
| 881 |
+
}
|
| 882 |
+
)
|
| 883 |
+
tm.assert_frame_equal(result, expected)
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
def test_where_none_nan_coerce():
|
| 887 |
+
# GH 15613
|
| 888 |
+
expected = DataFrame(
|
| 889 |
+
{
|
| 890 |
+
"A": [Timestamp("20130101"), pd.NaT, Timestamp("20130103")],
|
| 891 |
+
"B": [1, 2, np.nan],
|
| 892 |
+
}
|
| 893 |
+
)
|
| 894 |
+
result = expected.where(expected.notnull(), None)
|
| 895 |
+
tm.assert_frame_equal(result, expected)
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def test_where_duplicate_axes_mixed_dtypes():
|
| 899 |
+
# GH 25399, verify manually masking is not affected anymore by dtype of column for
|
| 900 |
+
# duplicate axes.
|
| 901 |
+
result = DataFrame(data=[[0, np.nan]], columns=Index(["A", "A"]))
|
| 902 |
+
index, columns = result.axes
|
| 903 |
+
mask = DataFrame(data=[[True, True]], columns=columns, index=index)
|
| 904 |
+
a = result.astype(object).where(mask)
|
| 905 |
+
b = result.astype("f8").where(mask)
|
| 906 |
+
c = result.T.where(mask.T).T
|
| 907 |
+
d = result.where(mask) # used to fail with "cannot reindex from a duplicate axis"
|
| 908 |
+
tm.assert_frame_equal(a.astype("f8"), b.astype("f8"))
|
| 909 |
+
tm.assert_frame_equal(b.astype("f8"), c.astype("f8"))
|
| 910 |
+
tm.assert_frame_equal(c.astype("f8"), d.astype("f8"))
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
def test_where_columns_casting():
|
| 914 |
+
# GH 42295
|
| 915 |
+
|
| 916 |
+
df = DataFrame({"a": [1.0, 2.0], "b": [3, np.nan]})
|
| 917 |
+
expected = df.copy()
|
| 918 |
+
result = df.where(pd.notnull(df), None)
|
| 919 |
+
# make sure dtypes don't change
|
| 920 |
+
tm.assert_frame_equal(expected, result)
|
| 921 |
+
|
| 922 |
+
|
| 923 |
+
@pytest.mark.parametrize("as_cat", [True, False])
|
| 924 |
+
def test_where_period_invalid_na(frame_or_series, as_cat, request):
|
| 925 |
+
# GH#44697
|
| 926 |
+
idx = pd.period_range("2016-01-01", periods=3, freq="D")
|
| 927 |
+
if as_cat:
|
| 928 |
+
idx = idx.astype("category")
|
| 929 |
+
obj = frame_or_series(idx)
|
| 930 |
+
|
| 931 |
+
# NA value that we should *not* cast to Period dtype
|
| 932 |
+
tdnat = pd.NaT.to_numpy("m8[ns]")
|
| 933 |
+
|
| 934 |
+
mask = np.array([True, True, False], ndmin=obj.ndim).T
|
| 935 |
+
|
| 936 |
+
if as_cat:
|
| 937 |
+
msg = (
|
| 938 |
+
r"Cannot setitem on a Categorical with a new category \(NaT\), "
|
| 939 |
+
"set the categories first"
|
| 940 |
+
)
|
| 941 |
+
else:
|
| 942 |
+
msg = "value should be a 'Period'"
|
| 943 |
+
|
| 944 |
+
if as_cat:
|
| 945 |
+
with pytest.raises(TypeError, match=msg):
|
| 946 |
+
obj.where(mask, tdnat)
|
| 947 |
+
|
| 948 |
+
with pytest.raises(TypeError, match=msg):
|
| 949 |
+
obj.mask(mask, tdnat)
|
| 950 |
+
|
| 951 |
+
with pytest.raises(TypeError, match=msg):
|
| 952 |
+
obj.mask(mask, tdnat, inplace=True)
|
| 953 |
+
|
| 954 |
+
else:
|
| 955 |
+
# With PeriodDtype, ser[i] = tdnat coerces instead of raising,
|
| 956 |
+
# so for consistency, ser[mask] = tdnat must as well
|
| 957 |
+
expected = obj.astype(object).where(mask, tdnat)
|
| 958 |
+
result = obj.where(mask, tdnat)
|
| 959 |
+
tm.assert_equal(result, expected)
|
| 960 |
+
|
| 961 |
+
expected = obj.astype(object).mask(mask, tdnat)
|
| 962 |
+
result = obj.mask(mask, tdnat)
|
| 963 |
+
tm.assert_equal(result, expected)
|
| 964 |
+
|
| 965 |
+
with tm.assert_produces_warning(
|
| 966 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 967 |
+
):
|
| 968 |
+
obj.mask(mask, tdnat, inplace=True)
|
| 969 |
+
tm.assert_equal(obj, expected)
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
def test_where_nullable_invalid_na(frame_or_series, any_numeric_ea_dtype):
|
| 973 |
+
# GH#44697
|
| 974 |
+
arr = pd.array([1, 2, 3], dtype=any_numeric_ea_dtype)
|
| 975 |
+
obj = frame_or_series(arr)
|
| 976 |
+
|
| 977 |
+
mask = np.array([True, True, False], ndmin=obj.ndim).T
|
| 978 |
+
|
| 979 |
+
msg = r"Invalid value '.*' for dtype '(U?Int|Float)\d{1,2}'"
|
| 980 |
+
|
| 981 |
+
for null in tm.NP_NAT_OBJECTS + [pd.NaT]:
|
| 982 |
+
# NaT is an NA value that we should *not* cast to pd.NA dtype
|
| 983 |
+
with pytest.raises(TypeError, match=msg):
|
| 984 |
+
obj.where(mask, null)
|
| 985 |
+
|
| 986 |
+
with pytest.raises(TypeError, match=msg):
|
| 987 |
+
obj.mask(mask, null)
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
@given(data=OPTIONAL_ONE_OF_ALL)
|
| 991 |
+
def test_where_inplace_casting(data):
|
| 992 |
+
# GH 22051
|
| 993 |
+
df = DataFrame({"a": data})
|
| 994 |
+
df_copy = df.where(pd.notnull(df), None).copy()
|
| 995 |
+
df.where(pd.notnull(df), None, inplace=True)
|
| 996 |
+
tm.assert_equal(df, df_copy)
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
def test_where_downcast_to_td64():
|
| 1000 |
+
ser = Series([1, 2, 3])
|
| 1001 |
+
|
| 1002 |
+
mask = np.array([False, False, False])
|
| 1003 |
+
|
| 1004 |
+
td = pd.Timedelta(days=1)
|
| 1005 |
+
|
| 1006 |
+
msg = "Downcasting behavior in Series and DataFrame methods 'where'"
|
| 1007 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 1008 |
+
res = ser.where(mask, td)
|
| 1009 |
+
expected = Series([td, td, td], dtype="m8[ns]")
|
| 1010 |
+
tm.assert_series_equal(res, expected)
|
| 1011 |
+
|
| 1012 |
+
with pd.option_context("future.no_silent_downcasting", True):
|
| 1013 |
+
with tm.assert_produces_warning(None, match=msg):
|
| 1014 |
+
res2 = ser.where(mask, td)
|
| 1015 |
+
expected2 = expected.astype(object)
|
| 1016 |
+
tm.assert_series_equal(res2, expected2)
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
def _check_where_equivalences(df, mask, other, expected):
|
| 1020 |
+
# similar to tests.series.indexing.test_setitem.SetitemCastingEquivalences
|
| 1021 |
+
# but with DataFrame in mind and less fleshed-out
|
| 1022 |
+
res = df.where(mask, other)
|
| 1023 |
+
tm.assert_frame_equal(res, expected)
|
| 1024 |
+
|
| 1025 |
+
res = df.mask(~mask, other)
|
| 1026 |
+
tm.assert_frame_equal(res, expected)
|
| 1027 |
+
|
| 1028 |
+
# Note: frame.mask(~mask, other, inplace=True) takes some more work bc
|
| 1029 |
+
# Block.putmask does *not* downcast. The change to 'expected' here
|
| 1030 |
+
# is specific to the cases in test_where_dt64_2d.
|
| 1031 |
+
df = df.copy()
|
| 1032 |
+
df.mask(~mask, other, inplace=True)
|
| 1033 |
+
if not mask.all():
|
| 1034 |
+
# with mask.all(), Block.putmask is a no-op, so does not downcast
|
| 1035 |
+
expected = expected.copy()
|
| 1036 |
+
expected["A"] = expected["A"].astype(object)
|
| 1037 |
+
tm.assert_frame_equal(df, expected)
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
def test_where_dt64_2d():
|
| 1041 |
+
dti = date_range("2016-01-01", periods=6)
|
| 1042 |
+
dta = dti._data.reshape(3, 2)
|
| 1043 |
+
other = dta - dta[0, 0]
|
| 1044 |
+
|
| 1045 |
+
df = DataFrame(dta, columns=["A", "B"])
|
| 1046 |
+
|
| 1047 |
+
mask = np.asarray(df.isna()).copy()
|
| 1048 |
+
mask[:, 1] = True
|
| 1049 |
+
|
| 1050 |
+
# setting all of one column, none of the other
|
| 1051 |
+
expected = DataFrame({"A": other[:, 0], "B": dta[:, 1]})
|
| 1052 |
+
with tm.assert_produces_warning(
|
| 1053 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 1054 |
+
):
|
| 1055 |
+
_check_where_equivalences(df, mask, other, expected)
|
| 1056 |
+
|
| 1057 |
+
# setting part of one column, none of the other
|
| 1058 |
+
mask[1, 0] = True
|
| 1059 |
+
expected = DataFrame(
|
| 1060 |
+
{
|
| 1061 |
+
"A": np.array([other[0, 0], dta[1, 0], other[2, 0]], dtype=object),
|
| 1062 |
+
"B": dta[:, 1],
|
| 1063 |
+
}
|
| 1064 |
+
)
|
| 1065 |
+
with tm.assert_produces_warning(
|
| 1066 |
+
FutureWarning, match="Setting an item of incompatible dtype"
|
| 1067 |
+
):
|
| 1068 |
+
_check_where_equivalences(df, mask, other, expected)
|
| 1069 |
+
|
| 1070 |
+
# setting nothing in either column
|
| 1071 |
+
mask[:] = True
|
| 1072 |
+
expected = df
|
| 1073 |
+
_check_where_equivalences(df, mask, other, expected)
|
| 1074 |
+
|
| 1075 |
+
|
| 1076 |
+
def test_where_producing_ea_cond_for_np_dtype():
|
| 1077 |
+
# GH#44014
|
| 1078 |
+
df = DataFrame({"a": Series([1, pd.NA, 2], dtype="Int64"), "b": [1, 2, 3]})
|
| 1079 |
+
result = df.where(lambda x: x.apply(lambda y: y > 1, axis=1))
|
| 1080 |
+
expected = DataFrame(
|
| 1081 |
+
{"a": Series([pd.NA, pd.NA, 2], dtype="Int64"), "b": [np.nan, 2, 3]}
|
| 1082 |
+
)
|
| 1083 |
+
tm.assert_frame_equal(result, expected)
|
| 1084 |
+
|
| 1085 |
+
|
| 1086 |
+
@pytest.mark.parametrize(
|
| 1087 |
+
"replacement", [0.001, True, "snake", None, datetime(2022, 5, 4)]
|
| 1088 |
+
)
|
| 1089 |
+
def test_where_int_overflow(replacement):
|
| 1090 |
+
# GH 31687
|
| 1091 |
+
df = DataFrame([[1.0, 2e25, "nine"], [np.nan, 0.1, None]])
|
| 1092 |
+
result = df.where(pd.notnull(df), replacement)
|
| 1093 |
+
expected = DataFrame([[1.0, 2e25, "nine"], [replacement, 0.1, replacement]])
|
| 1094 |
+
|
| 1095 |
+
tm.assert_frame_equal(result, expected)
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
def test_where_inplace_no_other():
|
| 1099 |
+
# GH#51685
|
| 1100 |
+
df = DataFrame({"a": [1.0, 2.0], "b": ["x", "y"]})
|
| 1101 |
+
cond = DataFrame({"a": [True, False], "b": [False, True]})
|
| 1102 |
+
df.where(cond, inplace=True)
|
| 1103 |
+
expected = DataFrame({"a": [1, np.nan], "b": [np.nan, "y"]})
|
| 1104 |
+
tm.assert_frame_equal(df, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/indexing/test_xs.py
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas.errors import SettingWithCopyError
|
| 7 |
+
|
| 8 |
+
from pandas import (
|
| 9 |
+
DataFrame,
|
| 10 |
+
Index,
|
| 11 |
+
IndexSlice,
|
| 12 |
+
MultiIndex,
|
| 13 |
+
Series,
|
| 14 |
+
concat,
|
| 15 |
+
)
|
| 16 |
+
import pandas._testing as tm
|
| 17 |
+
|
| 18 |
+
from pandas.tseries.offsets import BDay
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@pytest.fixture
|
| 22 |
+
def four_level_index_dataframe():
|
| 23 |
+
arr = np.array(
|
| 24 |
+
[
|
| 25 |
+
[-0.5109, -2.3358, -0.4645, 0.05076, 0.364],
|
| 26 |
+
[0.4473, 1.4152, 0.2834, 1.00661, 0.1744],
|
| 27 |
+
[-0.6662, -0.5243, -0.358, 0.89145, 2.5838],
|
| 28 |
+
]
|
| 29 |
+
)
|
| 30 |
+
index = MultiIndex(
|
| 31 |
+
levels=[["a", "x"], ["b", "q"], [10.0032, 20.0, 30.0], [3, 4, 5]],
|
| 32 |
+
codes=[[0, 0, 1], [0, 1, 1], [0, 1, 2], [2, 1, 0]],
|
| 33 |
+
names=["one", "two", "three", "four"],
|
| 34 |
+
)
|
| 35 |
+
return DataFrame(arr, index=index, columns=list("ABCDE"))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestXS:
|
| 39 |
+
def test_xs(
|
| 40 |
+
self, float_frame, datetime_frame, using_copy_on_write, warn_copy_on_write
|
| 41 |
+
):
|
| 42 |
+
float_frame_orig = float_frame.copy()
|
| 43 |
+
idx = float_frame.index[5]
|
| 44 |
+
xs = float_frame.xs(idx)
|
| 45 |
+
for item, value in xs.items():
|
| 46 |
+
if np.isnan(value):
|
| 47 |
+
assert np.isnan(float_frame[item][idx])
|
| 48 |
+
else:
|
| 49 |
+
assert value == float_frame[item][idx]
|
| 50 |
+
|
| 51 |
+
# mixed-type xs
|
| 52 |
+
test_data = {"A": {"1": 1, "2": 2}, "B": {"1": "1", "2": "2", "3": "3"}}
|
| 53 |
+
frame = DataFrame(test_data)
|
| 54 |
+
xs = frame.xs("1")
|
| 55 |
+
assert xs.dtype == np.object_
|
| 56 |
+
assert xs["A"] == 1
|
| 57 |
+
assert xs["B"] == "1"
|
| 58 |
+
|
| 59 |
+
with pytest.raises(
|
| 60 |
+
KeyError, match=re.escape("Timestamp('1999-12-31 00:00:00')")
|
| 61 |
+
):
|
| 62 |
+
datetime_frame.xs(datetime_frame.index[0] - BDay())
|
| 63 |
+
|
| 64 |
+
# xs get column
|
| 65 |
+
series = float_frame.xs("A", axis=1)
|
| 66 |
+
expected = float_frame["A"]
|
| 67 |
+
tm.assert_series_equal(series, expected)
|
| 68 |
+
|
| 69 |
+
# view is returned if possible
|
| 70 |
+
series = float_frame.xs("A", axis=1)
|
| 71 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 72 |
+
series[:] = 5
|
| 73 |
+
if using_copy_on_write:
|
| 74 |
+
# but with CoW the view shouldn't propagate mutations
|
| 75 |
+
tm.assert_series_equal(float_frame["A"], float_frame_orig["A"])
|
| 76 |
+
assert not (expected == 5).all()
|
| 77 |
+
else:
|
| 78 |
+
assert (expected == 5).all()
|
| 79 |
+
|
| 80 |
+
def test_xs_corner(self):
|
| 81 |
+
# pathological mixed-type reordering case
|
| 82 |
+
df = DataFrame(index=[0], columns=Index([], dtype="str"))
|
| 83 |
+
df["A"] = 1.0
|
| 84 |
+
df["B"] = "foo"
|
| 85 |
+
df["C"] = 2.0
|
| 86 |
+
df["D"] = "bar"
|
| 87 |
+
df["E"] = 3.0
|
| 88 |
+
|
| 89 |
+
xs = df.xs(0)
|
| 90 |
+
exp = Series([1.0, "foo", 2.0, "bar", 3.0], index=list("ABCDE"), name=0)
|
| 91 |
+
tm.assert_series_equal(xs, exp)
|
| 92 |
+
|
| 93 |
+
# no columns but Index(dtype=object)
|
| 94 |
+
df = DataFrame(index=["a", "b", "c"])
|
| 95 |
+
result = df.xs("a")
|
| 96 |
+
expected = Series([], name="a", dtype=np.float64)
|
| 97 |
+
tm.assert_series_equal(result, expected)
|
| 98 |
+
|
| 99 |
+
def test_xs_duplicates(self):
|
| 100 |
+
df = DataFrame(
|
| 101 |
+
np.random.default_rng(2).standard_normal((5, 2)),
|
| 102 |
+
index=["b", "b", "c", "b", "a"],
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
cross = df.xs("c")
|
| 106 |
+
exp = df.iloc[2]
|
| 107 |
+
tm.assert_series_equal(cross, exp)
|
| 108 |
+
|
| 109 |
+
def test_xs_keep_level(self):
|
| 110 |
+
df = DataFrame(
|
| 111 |
+
{
|
| 112 |
+
"day": {0: "sat", 1: "sun"},
|
| 113 |
+
"flavour": {0: "strawberry", 1: "strawberry"},
|
| 114 |
+
"sales": {0: 10, 1: 12},
|
| 115 |
+
"year": {0: 2008, 1: 2008},
|
| 116 |
+
}
|
| 117 |
+
).set_index(["year", "flavour", "day"])
|
| 118 |
+
result = df.xs("sat", level="day", drop_level=False)
|
| 119 |
+
expected = df[:1]
|
| 120 |
+
tm.assert_frame_equal(result, expected)
|
| 121 |
+
|
| 122 |
+
result = df.xs((2008, "sat"), level=["year", "day"], drop_level=False)
|
| 123 |
+
tm.assert_frame_equal(result, expected)
|
| 124 |
+
|
| 125 |
+
def test_xs_view(
|
| 126 |
+
self, using_array_manager, using_copy_on_write, warn_copy_on_write
|
| 127 |
+
):
|
| 128 |
+
# in 0.14 this will return a view if possible a copy otherwise, but
|
| 129 |
+
# this is numpy dependent
|
| 130 |
+
|
| 131 |
+
dm = DataFrame(np.arange(20.0).reshape(4, 5), index=range(4), columns=range(5))
|
| 132 |
+
df_orig = dm.copy()
|
| 133 |
+
|
| 134 |
+
if using_copy_on_write:
|
| 135 |
+
with tm.raises_chained_assignment_error():
|
| 136 |
+
dm.xs(2)[:] = 20
|
| 137 |
+
tm.assert_frame_equal(dm, df_orig)
|
| 138 |
+
elif using_array_manager:
|
| 139 |
+
# INFO(ArrayManager) with ArrayManager getting a row as a view is
|
| 140 |
+
# not possible
|
| 141 |
+
msg = r"\nA value is trying to be set on a copy of a slice from a DataFrame"
|
| 142 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 143 |
+
dm.xs(2)[:] = 20
|
| 144 |
+
assert not (dm.xs(2) == 20).any()
|
| 145 |
+
else:
|
| 146 |
+
with tm.raises_chained_assignment_error():
|
| 147 |
+
dm.xs(2)[:] = 20
|
| 148 |
+
assert (dm.xs(2) == 20).all()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class TestXSWithMultiIndex:
|
| 152 |
+
def test_xs_doc_example(self):
|
| 153 |
+
# TODO: more descriptive name
|
| 154 |
+
# based on example in advanced.rst
|
| 155 |
+
arrays = [
|
| 156 |
+
["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
|
| 157 |
+
["one", "two", "one", "two", "one", "two", "one", "two"],
|
| 158 |
+
]
|
| 159 |
+
tuples = list(zip(*arrays))
|
| 160 |
+
|
| 161 |
+
index = MultiIndex.from_tuples(tuples, names=["first", "second"])
|
| 162 |
+
df = DataFrame(
|
| 163 |
+
np.random.default_rng(2).standard_normal((3, 8)),
|
| 164 |
+
index=["A", "B", "C"],
|
| 165 |
+
columns=index,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
result = df.xs(("one", "bar"), level=("second", "first"), axis=1)
|
| 169 |
+
|
| 170 |
+
expected = df.iloc[:, [0]]
|
| 171 |
+
tm.assert_frame_equal(result, expected)
|
| 172 |
+
|
| 173 |
+
def test_xs_integer_key(self):
|
| 174 |
+
# see GH#2107
|
| 175 |
+
dates = range(20111201, 20111205)
|
| 176 |
+
ids = list("abcde")
|
| 177 |
+
index = MultiIndex.from_product([dates, ids], names=["date", "secid"])
|
| 178 |
+
df = DataFrame(
|
| 179 |
+
np.random.default_rng(2).standard_normal((len(index), 3)),
|
| 180 |
+
index,
|
| 181 |
+
["X", "Y", "Z"],
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
result = df.xs(20111201, level="date")
|
| 185 |
+
expected = df.loc[20111201, :]
|
| 186 |
+
tm.assert_frame_equal(result, expected)
|
| 187 |
+
|
| 188 |
+
def test_xs_level(self, multiindex_dataframe_random_data):
|
| 189 |
+
df = multiindex_dataframe_random_data
|
| 190 |
+
result = df.xs("two", level="second")
|
| 191 |
+
expected = df[df.index.get_level_values(1) == "two"]
|
| 192 |
+
expected.index = Index(["foo", "bar", "baz", "qux"], name="first")
|
| 193 |
+
tm.assert_frame_equal(result, expected)
|
| 194 |
+
|
| 195 |
+
def test_xs_level_eq_2(self):
|
| 196 |
+
arr = np.random.default_rng(2).standard_normal((3, 5))
|
| 197 |
+
index = MultiIndex(
|
| 198 |
+
levels=[["a", "p", "x"], ["b", "q", "y"], ["c", "r", "z"]],
|
| 199 |
+
codes=[[2, 0, 1], [2, 0, 1], [2, 0, 1]],
|
| 200 |
+
)
|
| 201 |
+
df = DataFrame(arr, index=index)
|
| 202 |
+
expected = DataFrame(arr[1:2], index=[["a"], ["b"]])
|
| 203 |
+
result = df.xs("c", level=2)
|
| 204 |
+
tm.assert_frame_equal(result, expected)
|
| 205 |
+
|
| 206 |
+
def test_xs_setting_with_copy_error(
|
| 207 |
+
self,
|
| 208 |
+
multiindex_dataframe_random_data,
|
| 209 |
+
using_copy_on_write,
|
| 210 |
+
warn_copy_on_write,
|
| 211 |
+
):
|
| 212 |
+
# this is a copy in 0.14
|
| 213 |
+
df = multiindex_dataframe_random_data
|
| 214 |
+
df_orig = df.copy()
|
| 215 |
+
result = df.xs("two", level="second")
|
| 216 |
+
|
| 217 |
+
if using_copy_on_write or warn_copy_on_write:
|
| 218 |
+
result[:] = 10
|
| 219 |
+
else:
|
| 220 |
+
# setting this will give a SettingWithCopyError
|
| 221 |
+
# as we are trying to write a view
|
| 222 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
| 223 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 224 |
+
result[:] = 10
|
| 225 |
+
tm.assert_frame_equal(df, df_orig)
|
| 226 |
+
|
| 227 |
+
def test_xs_setting_with_copy_error_multiple(
|
| 228 |
+
self, four_level_index_dataframe, using_copy_on_write, warn_copy_on_write
|
| 229 |
+
):
|
| 230 |
+
# this is a copy in 0.14
|
| 231 |
+
df = four_level_index_dataframe
|
| 232 |
+
df_orig = df.copy()
|
| 233 |
+
result = df.xs(("a", 4), level=["one", "four"])
|
| 234 |
+
|
| 235 |
+
if using_copy_on_write or warn_copy_on_write:
|
| 236 |
+
result[:] = 10
|
| 237 |
+
else:
|
| 238 |
+
# setting this will give a SettingWithCopyError
|
| 239 |
+
# as we are trying to write a view
|
| 240 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
| 241 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 242 |
+
result[:] = 10
|
| 243 |
+
tm.assert_frame_equal(df, df_orig)
|
| 244 |
+
|
| 245 |
+
@pytest.mark.parametrize("key, level", [("one", "second"), (["one"], ["second"])])
|
| 246 |
+
def test_xs_with_duplicates(self, key, level, multiindex_dataframe_random_data):
|
| 247 |
+
# see GH#13719
|
| 248 |
+
frame = multiindex_dataframe_random_data
|
| 249 |
+
df = concat([frame] * 2)
|
| 250 |
+
assert df.index.is_unique is False
|
| 251 |
+
expected = concat([frame.xs("one", level="second")] * 2)
|
| 252 |
+
|
| 253 |
+
if isinstance(key, list):
|
| 254 |
+
result = df.xs(tuple(key), level=level)
|
| 255 |
+
else:
|
| 256 |
+
result = df.xs(key, level=level)
|
| 257 |
+
tm.assert_frame_equal(result, expected)
|
| 258 |
+
|
| 259 |
+
def test_xs_missing_values_in_index(self):
|
| 260 |
+
# see GH#6574
|
| 261 |
+
# missing values in returned index should be preserved
|
| 262 |
+
acc = [
|
| 263 |
+
("a", "abcde", 1),
|
| 264 |
+
("b", "bbcde", 2),
|
| 265 |
+
("y", "yzcde", 25),
|
| 266 |
+
("z", "xbcde", 24),
|
| 267 |
+
("z", None, 26),
|
| 268 |
+
("z", "zbcde", 25),
|
| 269 |
+
("z", "ybcde", 26),
|
| 270 |
+
]
|
| 271 |
+
df = DataFrame(acc, columns=["a1", "a2", "cnt"]).set_index(["a1", "a2"])
|
| 272 |
+
expected = DataFrame(
|
| 273 |
+
{"cnt": [24, 26, 25, 26]},
|
| 274 |
+
index=Index(["xbcde", np.nan, "zbcde", "ybcde"], name="a2"),
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
result = df.xs("z", level="a1")
|
| 278 |
+
tm.assert_frame_equal(result, expected)
|
| 279 |
+
|
| 280 |
+
@pytest.mark.parametrize(
|
| 281 |
+
"key, level, exp_arr, exp_index",
|
| 282 |
+
[
|
| 283 |
+
("a", "lvl0", lambda x: x[:, 0:2], Index(["bar", "foo"], name="lvl1")),
|
| 284 |
+
("foo", "lvl1", lambda x: x[:, 1:2], Index(["a"], name="lvl0")),
|
| 285 |
+
],
|
| 286 |
+
)
|
| 287 |
+
def test_xs_named_levels_axis_eq_1(self, key, level, exp_arr, exp_index):
|
| 288 |
+
# see GH#2903
|
| 289 |
+
arr = np.random.default_rng(2).standard_normal((4, 4))
|
| 290 |
+
index = MultiIndex(
|
| 291 |
+
levels=[["a", "b"], ["bar", "foo", "hello", "world"]],
|
| 292 |
+
codes=[[0, 0, 1, 1], [0, 1, 2, 3]],
|
| 293 |
+
names=["lvl0", "lvl1"],
|
| 294 |
+
)
|
| 295 |
+
df = DataFrame(arr, columns=index)
|
| 296 |
+
result = df.xs(key, level=level, axis=1)
|
| 297 |
+
expected = DataFrame(exp_arr(arr), columns=exp_index)
|
| 298 |
+
tm.assert_frame_equal(result, expected)
|
| 299 |
+
|
| 300 |
+
@pytest.mark.parametrize(
|
| 301 |
+
"indexer",
|
| 302 |
+
[
|
| 303 |
+
lambda df: df.xs(("a", 4), level=["one", "four"]),
|
| 304 |
+
lambda df: df.xs("a").xs(4, level="four"),
|
| 305 |
+
],
|
| 306 |
+
)
|
| 307 |
+
def test_xs_level_multiple(self, indexer, four_level_index_dataframe):
|
| 308 |
+
df = four_level_index_dataframe
|
| 309 |
+
expected_values = [[0.4473, 1.4152, 0.2834, 1.00661, 0.1744]]
|
| 310 |
+
expected_index = MultiIndex(
|
| 311 |
+
levels=[["q"], [20.0]], codes=[[0], [0]], names=["two", "three"]
|
| 312 |
+
)
|
| 313 |
+
expected = DataFrame(
|
| 314 |
+
expected_values, index=expected_index, columns=list("ABCDE")
|
| 315 |
+
)
|
| 316 |
+
result = indexer(df)
|
| 317 |
+
tm.assert_frame_equal(result, expected)
|
| 318 |
+
|
| 319 |
+
@pytest.mark.parametrize(
|
| 320 |
+
"indexer", [lambda df: df.xs("a", level=0), lambda df: df.xs("a")]
|
| 321 |
+
)
|
| 322 |
+
def test_xs_level0(self, indexer, four_level_index_dataframe):
|
| 323 |
+
df = four_level_index_dataframe
|
| 324 |
+
expected_values = [
|
| 325 |
+
[-0.5109, -2.3358, -0.4645, 0.05076, 0.364],
|
| 326 |
+
[0.4473, 1.4152, 0.2834, 1.00661, 0.1744],
|
| 327 |
+
]
|
| 328 |
+
expected_index = MultiIndex(
|
| 329 |
+
levels=[["b", "q"], [10.0032, 20.0], [4, 5]],
|
| 330 |
+
codes=[[0, 1], [0, 1], [1, 0]],
|
| 331 |
+
names=["two", "three", "four"],
|
| 332 |
+
)
|
| 333 |
+
expected = DataFrame(
|
| 334 |
+
expected_values, index=expected_index, columns=list("ABCDE")
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
result = indexer(df)
|
| 338 |
+
tm.assert_frame_equal(result, expected)
|
| 339 |
+
|
| 340 |
+
def test_xs_values(self, multiindex_dataframe_random_data):
|
| 341 |
+
df = multiindex_dataframe_random_data
|
| 342 |
+
result = df.xs(("bar", "two")).values
|
| 343 |
+
expected = df.values[4]
|
| 344 |
+
tm.assert_almost_equal(result, expected)
|
| 345 |
+
|
| 346 |
+
def test_xs_loc_equality(self, multiindex_dataframe_random_data):
|
| 347 |
+
df = multiindex_dataframe_random_data
|
| 348 |
+
result = df.xs(("bar", "two"))
|
| 349 |
+
expected = df.loc[("bar", "two")]
|
| 350 |
+
tm.assert_series_equal(result, expected)
|
| 351 |
+
|
| 352 |
+
def test_xs_IndexSlice_argument_not_implemented(self, frame_or_series):
|
| 353 |
+
# GH#35301
|
| 354 |
+
|
| 355 |
+
index = MultiIndex(
|
| 356 |
+
levels=[[("foo", "bar", 0), ("foo", "baz", 0), ("foo", "qux", 0)], [0, 1]],
|
| 357 |
+
codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
obj = DataFrame(np.random.default_rng(2).standard_normal((6, 4)), index=index)
|
| 361 |
+
if frame_or_series is Series:
|
| 362 |
+
obj = obj[0]
|
| 363 |
+
|
| 364 |
+
expected = obj.iloc[-2:].droplevel(0)
|
| 365 |
+
|
| 366 |
+
result = obj.xs(IndexSlice[("foo", "qux", 0), :])
|
| 367 |
+
tm.assert_equal(result, expected)
|
| 368 |
+
|
| 369 |
+
result = obj.loc[IndexSlice[("foo", "qux", 0), :]]
|
| 370 |
+
tm.assert_equal(result, expected)
|
| 371 |
+
|
| 372 |
+
def test_xs_levels_raises(self, frame_or_series):
|
| 373 |
+
obj = DataFrame({"A": [1, 2, 3]})
|
| 374 |
+
if frame_or_series is Series:
|
| 375 |
+
obj = obj["A"]
|
| 376 |
+
|
| 377 |
+
msg = "Index must be a MultiIndex"
|
| 378 |
+
with pytest.raises(TypeError, match=msg):
|
| 379 |
+
obj.xs(0, level="as")
|
| 380 |
+
|
| 381 |
+
def test_xs_multiindex_droplevel_false(self):
|
| 382 |
+
# GH#19056
|
| 383 |
+
mi = MultiIndex.from_tuples(
|
| 384 |
+
[("a", "x"), ("a", "y"), ("b", "x")], names=["level1", "level2"]
|
| 385 |
+
)
|
| 386 |
+
df = DataFrame([[1, 2, 3]], columns=mi)
|
| 387 |
+
result = df.xs("a", axis=1, drop_level=False)
|
| 388 |
+
expected = DataFrame(
|
| 389 |
+
[[1, 2]],
|
| 390 |
+
columns=MultiIndex.from_tuples(
|
| 391 |
+
[("a", "x"), ("a", "y")], names=["level1", "level2"]
|
| 392 |
+
),
|
| 393 |
+
)
|
| 394 |
+
tm.assert_frame_equal(result, expected)
|
| 395 |
+
|
| 396 |
+
def test_xs_droplevel_false(self):
|
| 397 |
+
# GH#19056
|
| 398 |
+
df = DataFrame([[1, 2, 3]], columns=Index(["a", "b", "c"]))
|
| 399 |
+
result = df.xs("a", axis=1, drop_level=False)
|
| 400 |
+
expected = DataFrame({"a": [1]})
|
| 401 |
+
tm.assert_frame_equal(result, expected)
|
| 402 |
+
|
| 403 |
+
def test_xs_droplevel_false_view(
|
| 404 |
+
self, using_array_manager, using_copy_on_write, warn_copy_on_write
|
| 405 |
+
):
|
| 406 |
+
# GH#37832
|
| 407 |
+
df = DataFrame([[1, 2, 3]], columns=Index(["a", "b", "c"]))
|
| 408 |
+
result = df.xs("a", axis=1, drop_level=False)
|
| 409 |
+
# check that result still views the same data as df
|
| 410 |
+
assert np.shares_memory(result.iloc[:, 0]._values, df.iloc[:, 0]._values)
|
| 411 |
+
|
| 412 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 413 |
+
df.iloc[0, 0] = 2
|
| 414 |
+
if using_copy_on_write:
|
| 415 |
+
# with copy on write the subset is never modified
|
| 416 |
+
expected = DataFrame({"a": [1]})
|
| 417 |
+
else:
|
| 418 |
+
# modifying original df also modifies result when having a single block
|
| 419 |
+
expected = DataFrame({"a": [2]})
|
| 420 |
+
tm.assert_frame_equal(result, expected)
|
| 421 |
+
|
| 422 |
+
# with mixed dataframe, modifying the parent doesn't modify result
|
| 423 |
+
# TODO the "split" path behaves differently here as with single block
|
| 424 |
+
df = DataFrame([[1, 2.5, "a"]], columns=Index(["a", "b", "c"]))
|
| 425 |
+
result = df.xs("a", axis=1, drop_level=False)
|
| 426 |
+
df.iloc[0, 0] = 2
|
| 427 |
+
if using_copy_on_write:
|
| 428 |
+
# with copy on write the subset is never modified
|
| 429 |
+
expected = DataFrame({"a": [1]})
|
| 430 |
+
elif using_array_manager:
|
| 431 |
+
# Here the behavior is consistent
|
| 432 |
+
expected = DataFrame({"a": [2]})
|
| 433 |
+
else:
|
| 434 |
+
# FIXME: iloc does not update the array inplace using
|
| 435 |
+
# "split" path
|
| 436 |
+
expected = DataFrame({"a": [1]})
|
| 437 |
+
tm.assert_frame_equal(result, expected)
|
| 438 |
+
|
| 439 |
+
def test_xs_list_indexer_droplevel_false(self):
|
| 440 |
+
# GH#41760
|
| 441 |
+
mi = MultiIndex.from_tuples([("x", "m", "a"), ("x", "n", "b"), ("y", "o", "c")])
|
| 442 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=mi)
|
| 443 |
+
with pytest.raises(KeyError, match="y"):
|
| 444 |
+
df.xs(("x", "y"), drop_level=False, axis=1)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test files dedicated to individual (stand-alone) DataFrame methods
|
| 3 |
+
|
| 4 |
+
Ideally these files/tests should correspond 1-to-1 with tests.series.methods
|
| 5 |
+
|
| 6 |
+
These may also present opportunities for sharing/de-duplicating test code.
|
| 7 |
+
"""
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_add_prefix_suffix.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from pandas import Index
|
| 4 |
+
import pandas._testing as tm
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_add_prefix_suffix(float_frame):
|
| 8 |
+
with_prefix = float_frame.add_prefix("foo#")
|
| 9 |
+
expected = Index([f"foo#{c}" for c in float_frame.columns])
|
| 10 |
+
tm.assert_index_equal(with_prefix.columns, expected)
|
| 11 |
+
|
| 12 |
+
with_suffix = float_frame.add_suffix("#foo")
|
| 13 |
+
expected = Index([f"{c}#foo" for c in float_frame.columns])
|
| 14 |
+
tm.assert_index_equal(with_suffix.columns, expected)
|
| 15 |
+
|
| 16 |
+
with_pct_prefix = float_frame.add_prefix("%")
|
| 17 |
+
expected = Index([f"%{c}" for c in float_frame.columns])
|
| 18 |
+
tm.assert_index_equal(with_pct_prefix.columns, expected)
|
| 19 |
+
|
| 20 |
+
with_pct_suffix = float_frame.add_suffix("%")
|
| 21 |
+
expected = Index([f"{c}%" for c in float_frame.columns])
|
| 22 |
+
tm.assert_index_equal(with_pct_suffix.columns, expected)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_add_prefix_suffix_axis(float_frame):
|
| 26 |
+
# GH 47819
|
| 27 |
+
with_prefix = float_frame.add_prefix("foo#", axis=0)
|
| 28 |
+
expected = Index([f"foo#{c}" for c in float_frame.index])
|
| 29 |
+
tm.assert_index_equal(with_prefix.index, expected)
|
| 30 |
+
|
| 31 |
+
with_prefix = float_frame.add_prefix("foo#", axis=1)
|
| 32 |
+
expected = Index([f"foo#{c}" for c in float_frame.columns])
|
| 33 |
+
tm.assert_index_equal(with_prefix.columns, expected)
|
| 34 |
+
|
| 35 |
+
with_pct_suffix = float_frame.add_suffix("#foo", axis=0)
|
| 36 |
+
expected = Index([f"{c}#foo" for c in float_frame.index])
|
| 37 |
+
tm.assert_index_equal(with_pct_suffix.index, expected)
|
| 38 |
+
|
| 39 |
+
with_pct_suffix = float_frame.add_suffix("#foo", axis=1)
|
| 40 |
+
expected = Index([f"{c}#foo" for c in float_frame.columns])
|
| 41 |
+
tm.assert_index_equal(with_pct_suffix.columns, expected)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_add_prefix_suffix_invalid_axis(float_frame):
|
| 45 |
+
with pytest.raises(ValueError, match="No axis named 2 for object type DataFrame"):
|
| 46 |
+
float_frame.add_prefix("foo#", axis=2)
|
| 47 |
+
|
| 48 |
+
with pytest.raises(ValueError, match="No axis named 2 for object type DataFrame"):
|
| 49 |
+
float_frame.add_suffix("foo#", axis=2)
|
miniconda3/envs/ladir/lib/python3.10/site-pack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Frame,
|
| 9 |
+
Index,
|
| 10 |
+
Series,
|
| 11 |
+
date_range,
|
| 12 |
+
)
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestDataFrameAlign:
|
| 17 |
+
def test_align_asfreq_method_raises(self):
|
| 18 |
+
df = DataFrame({"A": [1, np.nan, 2]})
|
| 19 |
+
msg = "Invalid fill method"
|
| 20 |
+
msg2 = "The 'method', 'limit', and 'fill_axis' keywords"
|
| 21 |
+
with pytest.raises(ValueError, match=msg):
|
| 22 |
+
with tm.assert_produces_warning(FutureWarning, match=msg2):
|
| 23 |
+
df.align(df.iloc[::-1], method="asfreq")
|
| 24 |
+
|
| 25 |
+
def test_frame_align_aware(self):
|
| 26 |
+
idx1 = date_range("2001", periods=5, freq="h", tz="US/Eastern")
|
| 27 |
+
idx2 = date_range("2001", periods=5, freq="2h", tz="US/Eastern")
|
| 28 |
+
df1 = DataFrame(np.random.default_rng(2).standard_normal((len(idx1), 3)), idx1)
|
| 29 |
+
df2 = DataFrame(np.random.default_rng(2).standard_normal((len(idx2), 3)), idx2)
|
| 30 |
+
new1, new2 = df1.align(df2)
|
| 31 |
+
assert df1.index.tz == new1.index.tz
|
| 32 |
+
assert df2.index.tz == new2.index.tz
|
| 33 |
+
|
| 34 |
+
# different timezones convert to UTC
|
| 35 |
+
|
| 36 |
+
# frame with frame
|
| 37 |
+
df1_central = df1.tz_convert("US/Central")
|
| 38 |
+
new1, new2 = df1.align(df1_central)
|
| 39 |
+
assert new1.index.tz is timezone.utc
|
| 40 |
+
assert new2.index.tz is timezone.utc
|
| 41 |
+
|
| 42 |
+
# frame with Series
|
| 43 |
+
new1, new2 = df1.align(df1_central[0], axis=0)
|
| 44 |
+
assert new1.index.tz is timezone.utc
|
| 45 |
+
assert new2.index.tz is timezone.utc
|
| 46 |
+
|
| 47 |
+
df1[0].align(df1_central, axis=0)
|
| 48 |
+
assert new1.index.tz is timezone.utc
|
| 49 |
+
assert new2.index.tz is timezone.utc
|
| 50 |
+
|
| 51 |
+
def test_align_float(self, float_frame, using_copy_on_write):
|
| 52 |
+
af, bf = float_frame.align(float_frame)
|
| 53 |
+
assert af._mgr is not float_frame._mgr
|
| 54 |
+
|
| 55 |
+
af, bf = float_frame.align(float_frame, copy=False)
|
| 56 |
+
if not using_copy_on_write:
|
| 57 |
+
assert af._mgr is float_frame._mgr
|
| 58 |
+
else:
|
| 59 |
+
assert af._mgr is not float_frame._mgr
|
| 60 |
+
|
| 61 |
+
# axis = 0
|
| 62 |
+
other = float_frame.iloc[:-5, :3]
|
| 63 |
+
af, bf = float_frame.align(other, axis=0, fill_value=-1)
|
| 64 |
+
|
| 65 |
+
tm.assert_index_equal(bf.columns, other.columns)
|
| 66 |
+
|
| 67 |
+
# test fill value
|
| 68 |
+
join_idx = float_frame.index.join(other.index)
|
| 69 |
+
diff_a = float_frame.index.difference(join_idx)
|
| 70 |
+
diff_a_vals = af.reindex(diff_a).values
|
| 71 |
+
assert (diff_a_vals == -1).all()
|
| 72 |
+
|
| 73 |
+
af, bf = float_frame.align(other, join="right", axis=0)
|
| 74 |
+
tm.assert_index_equal(bf.columns, other.columns)
|
| 75 |
+
tm.assert_index_equal(bf.index, other.index)
|
| 76 |
+
tm.assert_index_equal(af.index, other.index)
|
| 77 |
+
|
| 78 |
+
# axis = 1
|
| 79 |
+
other = float_frame.iloc[:-5, :3].copy()
|
| 80 |
+
af, bf = float_frame.align(other, axis=1)
|
| 81 |
+
tm.assert_index_equal(bf.columns, float_frame.columns)
|
| 82 |
+
tm.assert_index_equal(bf.index, other.index)
|
| 83 |
+
|
| 84 |
+
# test fill value
|
| 85 |
+
join_idx = float_frame.index.join(other.index)
|
| 86 |
+
diff_a = float_frame.index.difference(join_idx)
|
| 87 |
+
diff_a_vals = af.reindex(diff_a).values
|
| 88 |
+
|
| 89 |
+
assert (diff_a_vals == -1).all()
|
| 90 |
+
|
| 91 |
+
af, bf = float_frame.align(other, join="inner", axis=1)
|
| 92 |
+
tm.assert_index_equal(bf.columns, other.columns)
|
| 93 |
+
|
| 94 |
+
msg = (
|
| 95 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 96 |
+
"are deprecated"
|
| 97 |
+
)
|
| 98 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 99 |
+
af, bf = float_frame.align(other, join="inner", axis=1, method="pad")
|
| 100 |
+
tm.assert_index_equal(bf.columns, other.columns)
|
| 101 |
+
|
| 102 |
+
msg = (
|
| 103 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 104 |
+
"are deprecated"
|
| 105 |
+
)
|
| 106 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 107 |
+
af, bf = float_frame.align(
|
| 108 |
+
other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=None
|
| 109 |
+
)
|
| 110 |
+
tm.assert_index_equal(bf.index, Index([]).astype(bf.index.dtype))
|
| 111 |
+
|
| 112 |
+
msg = (
|
| 113 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 114 |
+
"are deprecated"
|
| 115 |
+
)
|
| 116 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 117 |
+
af, bf = float_frame.align(
|
| 118 |
+
other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0
|
| 119 |
+
)
|
| 120 |
+
tm.assert_index_equal(bf.index, Index([]).astype(bf.index.dtype))
|
| 121 |
+
|
| 122 |
+
# Try to align DataFrame to Series along bad axis
|
| 123 |
+
msg = "No axis named 2 for object type DataFrame"
|
| 124 |
+
with pytest.raises(ValueError, match=msg):
|
| 125 |
+
float_frame.align(af.iloc[0, :3], join="inner", axis=2)
|
| 126 |
+
|
| 127 |
+
def test_align_frame_with_series(self, float_frame):
|
| 128 |
+
# align dataframe to series with broadcast or not
|
| 129 |
+
idx = float_frame.index
|
| 130 |
+
s = Series(range(len(idx)), index=idx)
|
| 131 |
+
|
| 132 |
+
left, right = float_frame.align(s, axis=0)
|
| 133 |
+
tm.assert_index_equal(left.index, float_frame.index)
|
| 134 |
+
tm.assert_index_equal(right.index, float_frame.index)
|
| 135 |
+
assert isinstance(right, Series)
|
| 136 |
+
|
| 137 |
+
msg = "The 'broadcast_axis' keyword in DataFrame.align is deprecated"
|
| 138 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 139 |
+
left, right = float_frame.align(s, broadcast_axis=1)
|
| 140 |
+
tm.assert_index_equal(left.index, float_frame.index)
|
| 141 |
+
expected = {c: s for c in float_frame.columns}
|
| 142 |
+
expected = DataFrame(
|
| 143 |
+
expected, index=float_frame.index, columns=float_frame.columns
|
| 144 |
+
)
|
| 145 |
+
tm.assert_frame_equal(right, expected)
|
| 146 |
+
|
| 147 |
+
def test_align_series_condition(self):
|
| 148 |
+
# see gh-9558
|
| 149 |
+
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
|
| 150 |
+
result = df[df["a"] == 2]
|
| 151 |
+
expected = DataFrame([[2, 5]], index=[1], columns=["a", "b"])
|
| 152 |
+
tm.assert_frame_equal(result, expected)
|
| 153 |
+
|
| 154 |
+
result = df.where(df["a"] == 2, 0)
|
| 155 |
+
expected = DataFrame({"a": [0, 2, 0], "b": [0, 5, 0]})
|
| 156 |
+
tm.assert_frame_equal(result, expected)
|
| 157 |
+
|
| 158 |
+
def test_align_int(self, int_frame):
|
| 159 |
+
# test other non-float types
|
| 160 |
+
other = DataFrame(index=range(5), columns=["A", "B", "C"])
|
| 161 |
+
|
| 162 |
+
msg = (
|
| 163 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 164 |
+
"are deprecated"
|
| 165 |
+
)
|
| 166 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 167 |
+
af, bf = int_frame.align(other, join="inner", axis=1, method="pad")
|
| 168 |
+
tm.assert_index_equal(bf.columns, other.columns)
|
| 169 |
+
|
| 170 |
+
def test_align_mixed_type(self, float_string_frame):
|
| 171 |
+
msg = (
|
| 172 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 173 |
+
"are deprecated"
|
| 174 |
+
)
|
| 175 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 176 |
+
af, bf = float_string_frame.align(
|
| 177 |
+
float_string_frame, join="inner", axis=1, method="pad"
|
| 178 |
+
)
|
| 179 |
+
tm.assert_index_equal(bf.columns, float_string_frame.columns)
|
| 180 |
+
|
| 181 |
+
def test_align_mixed_float(self, mixed_float_frame):
|
| 182 |
+
# mixed floats/ints
|
| 183 |
+
other = DataFrame(index=range(5), columns=["A", "B", "C"])
|
| 184 |
+
|
| 185 |
+
msg = (
|
| 186 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 187 |
+
"are deprecated"
|
| 188 |
+
)
|
| 189 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 190 |
+
af, bf = mixed_float_frame.align(
|
| 191 |
+
other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0
|
| 192 |
+
)
|
| 193 |
+
tm.assert_index_equal(bf.index, Index([]))
|
| 194 |
+
|
| 195 |
+
def test_align_mixed_int(self, mixed_int_frame):
|
| 196 |
+
other = DataFrame(index=range(5), columns=["A", "B", "C"])
|
| 197 |
+
|
| 198 |
+
msg = (
|
| 199 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 200 |
+
"are deprecated"
|
| 201 |
+
)
|
| 202 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 203 |
+
af, bf = mixed_int_frame.align(
|
| 204 |
+
other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0
|
| 205 |
+
)
|
| 206 |
+
tm.assert_index_equal(bf.index, Index([]))
|
| 207 |
+
|
| 208 |
+
@pytest.mark.parametrize(
|
| 209 |
+
"l_ordered,r_ordered,expected",
|
| 210 |
+
[
|
| 211 |
+
[True, True, pd.CategoricalIndex],
|
| 212 |
+
[True, False, Index],
|
| 213 |
+
[False, True, Index],
|
| 214 |
+
[False, False, pd.CategoricalIndex],
|
| 215 |
+
],
|
| 216 |
+
)
|
| 217 |
+
def test_align_categorical(self, l_ordered, r_ordered, expected):
|
| 218 |
+
# GH-28397
|
| 219 |
+
df_1 = DataFrame(
|
| 220 |
+
{
|
| 221 |
+
"A": np.arange(6, dtype="int64"),
|
| 222 |
+
"B": Series(list("aabbca")).astype(
|
| 223 |
+
pd.CategoricalDtype(list("cab"), ordered=l_ordered)
|
| 224 |
+
),
|
| 225 |
+
}
|
| 226 |
+
).set_index("B")
|
| 227 |
+
df_2 = DataFrame(
|
| 228 |
+
{
|
| 229 |
+
"A": np.arange(5, dtype="int64"),
|
| 230 |
+
"B": Series(list("babca")).astype(
|
| 231 |
+
pd.CategoricalDtype(list("cab"), ordered=r_ordered)
|
| 232 |
+
),
|
| 233 |
+
}
|
| 234 |
+
).set_index("B")
|
| 235 |
+
|
| 236 |
+
aligned_1, aligned_2 = df_1.align(df_2)
|
| 237 |
+
assert isinstance(aligned_1.index, expected)
|
| 238 |
+
assert isinstance(aligned_2.index, expected)
|
| 239 |
+
tm.assert_index_equal(aligned_1.index, aligned_2.index)
|
| 240 |
+
|
| 241 |
+
def test_align_multiindex(self):
|
| 242 |
+
# GH#10665
|
| 243 |
+
# same test cases as test_align_multiindex in test_series.py
|
| 244 |
+
|
| 245 |
+
midx = pd.MultiIndex.from_product(
|
| 246 |
+
[range(2), range(3), range(2)], names=("a", "b", "c")
|
| 247 |
+
)
|
| 248 |
+
idx = Index(range(2), name="b")
|
| 249 |
+
df1 = DataFrame(np.arange(12, dtype="int64"), index=midx)
|
| 250 |
+
df2 = DataFrame(np.arange(2, dtype="int64"), index=idx)
|
| 251 |
+
|
| 252 |
+
# these must be the same results (but flipped)
|
| 253 |
+
res1l, res1r = df1.align(df2, join="left")
|
| 254 |
+
res2l, res2r = df2.align(df1, join="right")
|
| 255 |
+
|
| 256 |
+
expl = df1
|
| 257 |
+
tm.assert_frame_equal(expl, res1l)
|
| 258 |
+
tm.assert_frame_equal(expl, res2r)
|
| 259 |
+
expr = DataFrame([0, 0, 1, 1, np.nan, np.nan] * 2, index=midx)
|
| 260 |
+
tm.assert_frame_equal(expr, res1r)
|
| 261 |
+
tm.assert_frame_equal(expr, res2l)
|
| 262 |
+
|
| 263 |
+
res1l, res1r = df1.align(df2, join="right")
|
| 264 |
+
res2l, res2r = df2.align(df1, join="left")
|
| 265 |
+
|
| 266 |
+
exp_idx = pd.MultiIndex.from_product(
|
| 267 |
+
[range(2), range(2), range(2)], names=("a", "b", "c")
|
| 268 |
+
)
|
| 269 |
+
expl = DataFrame([0, 1, 2, 3, 6, 7, 8, 9], index=exp_idx)
|
| 270 |
+
tm.assert_frame_equal(expl, res1l)
|
| 271 |
+
tm.assert_frame_equal(expl, res2r)
|
| 272 |
+
expr = DataFrame([0, 0, 1, 1] * 2, index=exp_idx)
|
| 273 |
+
tm.assert_frame_equal(expr, res1r)
|
| 274 |
+
tm.assert_frame_equal(expr, res2l)
|
| 275 |
+
|
| 276 |
+
def test_align_series_combinations(self):
|
| 277 |
+
df = DataFrame({"a": [1, 3, 5], "b": [1, 3, 5]}, index=list("ACE"))
|
| 278 |
+
s = Series([1, 2, 4], index=list("ABD"), name="x")
|
| 279 |
+
|
| 280 |
+
# frame + series
|
| 281 |
+
res1, res2 = df.align(s, axis=0)
|
| 282 |
+
exp1 = DataFrame(
|
| 283 |
+
{"a": [1, np.nan, 3, np.nan, 5], "b": [1, np.nan, 3, np.nan, 5]},
|
| 284 |
+
index=list("ABCDE"),
|
| 285 |
+
)
|
| 286 |
+
exp2 = Series([1, 2, np.nan, 4, np.nan], index=list("ABCDE"), name="x")
|
| 287 |
+
|
| 288 |
+
tm.assert_frame_equal(res1, exp1)
|
| 289 |
+
tm.assert_series_equal(res2, exp2)
|
| 290 |
+
|
| 291 |
+
# series + frame
|
| 292 |
+
res1, res2 = s.align(df)
|
| 293 |
+
tm.assert_series_equal(res1, exp2)
|
| 294 |
+
tm.assert_frame_equal(res2, exp1)
|
| 295 |
+
|
| 296 |
+
def test_multiindex_align_to_series_with_common_index_level(self):
|
| 297 |
+
# GH-46001
|
| 298 |
+
foo_index = Index([1, 2, 3], name="foo")
|
| 299 |
+
bar_index = Index([1, 2], name="bar")
|
| 300 |
+
|
| 301 |
+
series = Series([1, 2], index=bar_index, name="foo_series")
|
| 302 |
+
df = DataFrame(
|
| 303 |
+
{"col": np.arange(6)},
|
| 304 |
+
index=pd.MultiIndex.from_product([foo_index, bar_index]),
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
expected_r = Series([1, 2] * 3, index=df.index, name="foo_series")
|
| 308 |
+
result_l, result_r = df.align(series, axis=0)
|
| 309 |
+
|
| 310 |
+
tm.assert_frame_equal(result_l, df)
|
| 311 |
+
tm.assert_series_equal(result_r, expected_r)
|
| 312 |
+
|
| 313 |
+
def test_multiindex_align_to_series_with_common_index_level_missing_in_left(self):
|
| 314 |
+
# GH-46001
|
| 315 |
+
foo_index = Index([1, 2, 3], name="foo")
|
| 316 |
+
bar_index = Index([1, 2], name="bar")
|
| 317 |
+
|
| 318 |
+
series = Series(
|
| 319 |
+
[1, 2, 3, 4], index=Index([1, 2, 3, 4], name="bar"), name="foo_series"
|
| 320 |
+
)
|
| 321 |
+
df = DataFrame(
|
| 322 |
+
{"col": np.arange(6)},
|
| 323 |
+
index=pd.MultiIndex.from_product([foo_index, bar_index]),
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
expected_r = Series([1, 2] * 3, index=df.index, name="foo_series")
|
| 327 |
+
result_l, result_r = df.align(series, axis=0)
|
| 328 |
+
|
| 329 |
+
tm.assert_frame_equal(result_l, df)
|
| 330 |
+
tm.assert_series_equal(result_r, expected_r)
|
| 331 |
+
|
| 332 |
+
def test_multiindex_align_to_series_with_common_index_level_missing_in_right(self):
|
| 333 |
+
# GH-46001
|
| 334 |
+
foo_index = Index([1, 2, 3], name="foo")
|
| 335 |
+
bar_index = Index([1, 2, 3, 4], name="bar")
|
| 336 |
+
|
| 337 |
+
series = Series([1, 2], index=Index([1, 2], name="bar"), name="foo_series")
|
| 338 |
+
df = DataFrame(
|
| 339 |
+
{"col": np.arange(12)},
|
| 340 |
+
index=pd.MultiIndex.from_product([foo_index, bar_index]),
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
expected_r = Series(
|
| 344 |
+
[1, 2, np.nan, np.nan] * 3, index=df.index, name="foo_series"
|
| 345 |
+
)
|
| 346 |
+
result_l, result_r = df.align(series, axis=0)
|
| 347 |
+
|
| 348 |
+
tm.assert_frame_equal(result_l, df)
|
| 349 |
+
tm.assert_series_equal(result_r, expected_r)
|
| 350 |
+
|
| 351 |
+
def test_multiindex_align_to_series_with_common_index_level_missing_in_both(self):
|
| 352 |
+
# GH-46001
|
| 353 |
+
foo_index = Index([1, 2, 3], name="foo")
|
| 354 |
+
bar_index = Index([1, 3, 4], name="bar")
|
| 355 |
+
|
| 356 |
+
series = Series(
|
| 357 |
+
[1, 2, 3], index=Index([1, 2, 4], name="bar"), name="foo_series"
|
| 358 |
+
)
|
| 359 |
+
df = DataFrame(
|
| 360 |
+
{"col": np.arange(9)},
|
| 361 |
+
index=pd.MultiIndex.from_product([foo_index, bar_index]),
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
expected_r = Series([1, np.nan, 3] * 3, index=df.index, name="foo_series")
|
| 365 |
+
result_l, result_r = df.align(series, axis=0)
|
| 366 |
+
|
| 367 |
+
tm.assert_frame_equal(result_l, df)
|
| 368 |
+
tm.assert_series_equal(result_r, expected_r)
|
| 369 |
+
|
| 370 |
+
def test_multiindex_align_to_series_with_common_index_level_non_unique_cols(self):
|
| 371 |
+
# GH-46001
|
| 372 |
+
foo_index = Index([1, 2, 3], name="foo")
|
| 373 |
+
bar_index = Index([1, 2], name="bar")
|
| 374 |
+
|
| 375 |
+
series = Series([1, 2], index=bar_index, name="foo_series")
|
| 376 |
+
df = DataFrame(
|
| 377 |
+
np.arange(18).reshape(6, 3),
|
| 378 |
+
index=pd.MultiIndex.from_product([foo_index, bar_index]),
|
| 379 |
+
)
|
| 380 |
+
df.columns = ["cfoo", "cbar", "cfoo"]
|
| 381 |
+
|
| 382 |
+
expected = Series([1, 2] * 3, index=df.index, name="foo_series")
|
| 383 |
+
result_left, result_right = df.align(series, axis=0)
|
| 384 |
+
|
| 385 |
+
tm.assert_series_equal(result_right, expected)
|
| 386 |
+
tm.assert_index_equal(result_left.columns, df.columns)
|
| 387 |
+
|
| 388 |
+
def test_missing_axis_specification_exception(self):
|
| 389 |
+
df = DataFrame(np.arange(50).reshape((10, 5)))
|
| 390 |
+
series = Series(np.arange(5))
|
| 391 |
+
|
| 392 |
+
with pytest.raises(ValueError, match=r"axis=0 or 1"):
|
| 393 |
+
df.align(series)
|
| 394 |
+
|
| 395 |
+
@pytest.mark.parametrize("method", ["pad", "bfill"])
|
| 396 |
+
@pytest.mark.parametrize("axis", [0, 1, None])
|
| 397 |
+
@pytest.mark.parametrize("fill_axis", [0, 1])
|
| 398 |
+
@pytest.mark.parametrize("how", ["inner", "outer", "left", "right"])
|
| 399 |
+
@pytest.mark.parametrize(
|
| 400 |
+
"left_slice",
|
| 401 |
+
[
|
| 402 |
+
[slice(4), slice(10)],
|
| 403 |
+
[slice(0), slice(0)],
|
| 404 |
+
],
|
| 405 |
+
)
|
| 406 |
+
@pytest.mark.parametrize(
|
| 407 |
+
"right_slice",
|
| 408 |
+
[
|
| 409 |
+
[slice(2, None), slice(6, None)],
|
| 410 |
+
[slice(0), slice(0)],
|
| 411 |
+
],
|
| 412 |
+
)
|
| 413 |
+
@pytest.mark.parametrize("limit", [1, None])
|
| 414 |
+
def test_align_fill_method(
|
| 415 |
+
self, how, method, axis, fill_axis, float_frame, left_slice, right_slice, limit
|
| 416 |
+
):
|
| 417 |
+
frame = float_frame
|
| 418 |
+
left = frame.iloc[left_slice[0], left_slice[1]]
|
| 419 |
+
right = frame.iloc[right_slice[0], right_slice[1]]
|
| 420 |
+
|
| 421 |
+
msg = (
|
| 422 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 423 |
+
"are deprecated"
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 427 |
+
aa, ab = left.align(
|
| 428 |
+
right,
|
| 429 |
+
axis=axis,
|
| 430 |
+
join=how,
|
| 431 |
+
method=method,
|
| 432 |
+
limit=limit,
|
| 433 |
+
fill_axis=fill_axis,
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
join_index, join_columns = None, None
|
| 437 |
+
|
| 438 |
+
ea, eb = left, right
|
| 439 |
+
if axis is None or axis == 0:
|
| 440 |
+
join_index = left.index.join(right.index, how=how)
|
| 441 |
+
ea = ea.reindex(index=join_index)
|
| 442 |
+
eb = eb.reindex(index=join_index)
|
| 443 |
+
|
| 444 |
+
if axis is None or axis == 1:
|
| 445 |
+
join_columns = left.columns.join(right.columns, how=how)
|
| 446 |
+
ea = ea.reindex(columns=join_columns)
|
| 447 |
+
eb = eb.reindex(columns=join_columns)
|
| 448 |
+
|
| 449 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 450 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 451 |
+
ea = ea.fillna(axis=fill_axis, method=method, limit=limit)
|
| 452 |
+
eb = eb.fillna(axis=fill_axis, method=method, limit=limit)
|
| 453 |
+
|
| 454 |
+
tm.assert_frame_equal(aa, ea)
|
| 455 |
+
tm.assert_frame_equal(ab, eb)
|
| 456 |
+
|
| 457 |
+
def test_align_series_check_copy(self):
|
| 458 |
+
# GH#
|
| 459 |
+
df = DataFrame({0: [1, 2]})
|
| 460 |
+
ser = Series([1], name=0)
|
| 461 |
+
expected = ser.copy()
|
| 462 |
+
result, other = df.align(ser, axis=1)
|
| 463 |
+
ser.iloc[0] = 100
|
| 464 |
+
tm.assert_series_equal(other, expected)
|
| 465 |
+
|
| 466 |
+
def test_align_identical_different_object(self):
|
| 467 |
+
# GH#51032
|
| 468 |
+
df = DataFrame({"a": [1, 2]})
|
| 469 |
+
ser = Series([3, 4])
|
| 470 |
+
result, result2 = df.align(ser, axis=0)
|
| 471 |
+
tm.assert_frame_equal(result, df)
|
| 472 |
+
tm.assert_series_equal(result2, ser)
|
| 473 |
+
assert df is not result
|
| 474 |
+
assert ser is not result2
|
| 475 |
+
|
| 476 |
+
def test_align_identical_different_object_columns(self):
|
| 477 |
+
# GH#51032
|
| 478 |
+
df = DataFrame({"a": [1, 2]})
|
| 479 |
+
ser = Series([1], index=["a"])
|
| 480 |
+
result, result2 = df.align(ser, axis=1)
|
| 481 |
+
tm.assert_frame_equal(result, df)
|
| 482 |
+
tm.assert_series_equal(result2, ser)
|
| 483 |
+
assert df is not result
|
| 484 |
+
assert ser is not result2
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_asfreq.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas._libs.tslibs.offsets import MonthEnd
|
| 7 |
+
|
| 8 |
+
from pandas import (
|
| 9 |
+
DataFrame,
|
| 10 |
+
DatetimeIndex,
|
| 11 |
+
Series,
|
| 12 |
+
date_range,
|
| 13 |
+
period_range,
|
| 14 |
+
to_datetime,
|
| 15 |
+
)
|
| 16 |
+
import pandas._testing as tm
|
| 17 |
+
|
| 18 |
+
from pandas.tseries import offsets
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TestAsFreq:
|
| 22 |
+
@pytest.fixture(params=["s", "ms", "us", "ns"])
|
| 23 |
+
def unit(self, request):
|
| 24 |
+
return request.param
|
| 25 |
+
|
| 26 |
+
def test_asfreq2(self, frame_or_series):
|
| 27 |
+
ts = frame_or_series(
|
| 28 |
+
[0.0, 1.0, 2.0],
|
| 29 |
+
index=DatetimeIndex(
|
| 30 |
+
[
|
| 31 |
+
datetime(2009, 10, 30),
|
| 32 |
+
datetime(2009, 11, 30),
|
| 33 |
+
datetime(2009, 12, 31),
|
| 34 |
+
],
|
| 35 |
+
dtype="M8[ns]",
|
| 36 |
+
freq="BME",
|
| 37 |
+
),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
daily_ts = ts.asfreq("B")
|
| 41 |
+
monthly_ts = daily_ts.asfreq("BME")
|
| 42 |
+
tm.assert_equal(monthly_ts, ts)
|
| 43 |
+
|
| 44 |
+
daily_ts = ts.asfreq("B", method="pad")
|
| 45 |
+
monthly_ts = daily_ts.asfreq("BME")
|
| 46 |
+
tm.assert_equal(monthly_ts, ts)
|
| 47 |
+
|
| 48 |
+
daily_ts = ts.asfreq(offsets.BDay())
|
| 49 |
+
monthly_ts = daily_ts.asfreq(offsets.BMonthEnd())
|
| 50 |
+
tm.assert_equal(monthly_ts, ts)
|
| 51 |
+
|
| 52 |
+
result = ts[:0].asfreq("ME")
|
| 53 |
+
assert len(result) == 0
|
| 54 |
+
assert result is not ts
|
| 55 |
+
|
| 56 |
+
if frame_or_series is Series:
|
| 57 |
+
daily_ts = ts.asfreq("D", fill_value=-1)
|
| 58 |
+
result = daily_ts.value_counts().sort_index()
|
| 59 |
+
expected = Series(
|
| 60 |
+
[60, 1, 1, 1], index=[-1.0, 2.0, 1.0, 0.0], name="count"
|
| 61 |
+
).sort_index()
|
| 62 |
+
tm.assert_series_equal(result, expected)
|
| 63 |
+
|
| 64 |
+
def test_asfreq_datetimeindex_empty(self, frame_or_series):
|
| 65 |
+
# GH#14320
|
| 66 |
+
index = DatetimeIndex(["2016-09-29 11:00"])
|
| 67 |
+
expected = frame_or_series(index=index, dtype=object).asfreq("h")
|
| 68 |
+
result = frame_or_series([3], index=index.copy()).asfreq("h")
|
| 69 |
+
tm.assert_index_equal(expected.index, result.index)
|
| 70 |
+
|
| 71 |
+
@pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"])
|
| 72 |
+
def test_tz_aware_asfreq_smoke(self, tz, frame_or_series):
|
| 73 |
+
dr = date_range("2011-12-01", "2012-07-20", freq="D", tz=tz)
|
| 74 |
+
|
| 75 |
+
obj = frame_or_series(
|
| 76 |
+
np.random.default_rng(2).standard_normal(len(dr)), index=dr
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# it works!
|
| 80 |
+
obj.asfreq("min")
|
| 81 |
+
|
| 82 |
+
def test_asfreq_normalize(self, frame_or_series):
|
| 83 |
+
rng = date_range("1/1/2000 09:30", periods=20)
|
| 84 |
+
norm = date_range("1/1/2000", periods=20)
|
| 85 |
+
|
| 86 |
+
vals = np.random.default_rng(2).standard_normal((20, 3))
|
| 87 |
+
|
| 88 |
+
obj = DataFrame(vals, index=rng)
|
| 89 |
+
expected = DataFrame(vals, index=norm)
|
| 90 |
+
if frame_or_series is Series:
|
| 91 |
+
obj = obj[0]
|
| 92 |
+
expected = expected[0]
|
| 93 |
+
|
| 94 |
+
result = obj.asfreq("D", normalize=True)
|
| 95 |
+
tm.assert_equal(result, expected)
|
| 96 |
+
|
| 97 |
+
def test_asfreq_keep_index_name(self, frame_or_series):
|
| 98 |
+
# GH#9854
|
| 99 |
+
index_name = "bar"
|
| 100 |
+
index = date_range("20130101", periods=20, name=index_name)
|
| 101 |
+
obj = DataFrame(list(range(20)), columns=["foo"], index=index)
|
| 102 |
+
obj = tm.get_obj(obj, frame_or_series)
|
| 103 |
+
|
| 104 |
+
assert index_name == obj.index.name
|
| 105 |
+
assert index_name == obj.asfreq("10D").index.name
|
| 106 |
+
|
| 107 |
+
def test_asfreq_ts(self, frame_or_series):
|
| 108 |
+
index = period_range(freq="Y", start="1/1/2001", end="12/31/2010")
|
| 109 |
+
obj = DataFrame(
|
| 110 |
+
np.random.default_rng(2).standard_normal((len(index), 3)), index=index
|
| 111 |
+
)
|
| 112 |
+
obj = tm.get_obj(obj, frame_or_series)
|
| 113 |
+
|
| 114 |
+
result = obj.asfreq("D", how="end")
|
| 115 |
+
exp_index = index.asfreq("D", how="end")
|
| 116 |
+
assert len(result) == len(obj)
|
| 117 |
+
tm.assert_index_equal(result.index, exp_index)
|
| 118 |
+
|
| 119 |
+
result = obj.asfreq("D", how="start")
|
| 120 |
+
exp_index = index.asfreq("D", how="start")
|
| 121 |
+
assert len(result) == len(obj)
|
| 122 |
+
tm.assert_index_equal(result.index, exp_index)
|
| 123 |
+
|
| 124 |
+
def test_asfreq_resample_set_correct_freq(self, frame_or_series):
|
| 125 |
+
# GH#5613
|
| 126 |
+
# we test if .asfreq() and .resample() set the correct value for .freq
|
| 127 |
+
dti = to_datetime(["2012-01-01", "2012-01-02", "2012-01-03"])
|
| 128 |
+
obj = DataFrame({"col": [1, 2, 3]}, index=dti)
|
| 129 |
+
obj = tm.get_obj(obj, frame_or_series)
|
| 130 |
+
|
| 131 |
+
# testing the settings before calling .asfreq() and .resample()
|
| 132 |
+
assert obj.index.freq is None
|
| 133 |
+
assert obj.index.inferred_freq == "D"
|
| 134 |
+
|
| 135 |
+
# does .asfreq() set .freq correctly?
|
| 136 |
+
assert obj.asfreq("D").index.freq == "D"
|
| 137 |
+
|
| 138 |
+
# does .resample() set .freq correctly?
|
| 139 |
+
assert obj.resample("D").asfreq().index.freq == "D"
|
| 140 |
+
|
| 141 |
+
def test_asfreq_empty(self, datetime_frame):
|
| 142 |
+
# test does not blow up on length-0 DataFrame
|
| 143 |
+
zero_length = datetime_frame.reindex([])
|
| 144 |
+
result = zero_length.asfreq("BME")
|
| 145 |
+
assert result is not zero_length
|
| 146 |
+
|
| 147 |
+
def test_asfreq(self, datetime_frame):
|
| 148 |
+
offset_monthly = datetime_frame.asfreq(offsets.BMonthEnd())
|
| 149 |
+
rule_monthly = datetime_frame.asfreq("BME")
|
| 150 |
+
|
| 151 |
+
tm.assert_frame_equal(offset_monthly, rule_monthly)
|
| 152 |
+
|
| 153 |
+
rule_monthly.asfreq("B", method="pad")
|
| 154 |
+
# TODO: actually check that this worked.
|
| 155 |
+
|
| 156 |
+
# don't forget!
|
| 157 |
+
rule_monthly.asfreq("B", method="pad")
|
| 158 |
+
|
| 159 |
+
def test_asfreq_datetimeindex(self):
|
| 160 |
+
df = DataFrame(
|
| 161 |
+
{"A": [1, 2, 3]},
|
| 162 |
+
index=[datetime(2011, 11, 1), datetime(2011, 11, 2), datetime(2011, 11, 3)],
|
| 163 |
+
)
|
| 164 |
+
df = df.asfreq("B")
|
| 165 |
+
assert isinstance(df.index, DatetimeIndex)
|
| 166 |
+
|
| 167 |
+
ts = df["A"].asfreq("B")
|
| 168 |
+
assert isinstance(ts.index, DatetimeIndex)
|
| 169 |
+
|
| 170 |
+
def test_asfreq_fillvalue(self):
|
| 171 |
+
# test for fill value during upsampling, related to issue 3715
|
| 172 |
+
|
| 173 |
+
# setup
|
| 174 |
+
rng = date_range("1/1/2016", periods=10, freq="2s")
|
| 175 |
+
# Explicit cast to 'float' to avoid implicit cast when setting None
|
| 176 |
+
ts = Series(np.arange(len(rng)), index=rng, dtype="float")
|
| 177 |
+
df = DataFrame({"one": ts})
|
| 178 |
+
|
| 179 |
+
# insert pre-existing missing value
|
| 180 |
+
df.loc["2016-01-01 00:00:08", "one"] = None
|
| 181 |
+
|
| 182 |
+
actual_df = df.asfreq(freq="1s", fill_value=9.0)
|
| 183 |
+
expected_df = df.asfreq(freq="1s").fillna(9.0)
|
| 184 |
+
expected_df.loc["2016-01-01 00:00:08", "one"] = None
|
| 185 |
+
tm.assert_frame_equal(expected_df, actual_df)
|
| 186 |
+
|
| 187 |
+
expected_series = ts.asfreq(freq="1s").fillna(9.0)
|
| 188 |
+
actual_series = ts.asfreq(freq="1s", fill_value=9.0)
|
| 189 |
+
tm.assert_series_equal(expected_series, actual_series)
|
| 190 |
+
|
| 191 |
+
def test_asfreq_with_date_object_index(self, frame_or_series):
|
| 192 |
+
rng = date_range("1/1/2000", periods=20)
|
| 193 |
+
ts = frame_or_series(np.random.default_rng(2).standard_normal(20), index=rng)
|
| 194 |
+
|
| 195 |
+
ts2 = ts.copy()
|
| 196 |
+
ts2.index = [x.date() for x in ts2.index]
|
| 197 |
+
|
| 198 |
+
result = ts2.asfreq("4h", method="ffill")
|
| 199 |
+
expected = ts.asfreq("4h", method="ffill")
|
| 200 |
+
tm.assert_equal(result, expected)
|
| 201 |
+
|
| 202 |
+
def test_asfreq_with_unsorted_index(self, frame_or_series):
|
| 203 |
+
# GH#39805
|
| 204 |
+
# Test that rows are not dropped when the datetime index is out of order
|
| 205 |
+
index = to_datetime(["2021-01-04", "2021-01-02", "2021-01-03", "2021-01-01"])
|
| 206 |
+
result = frame_or_series(range(4), index=index)
|
| 207 |
+
|
| 208 |
+
expected = result.reindex(sorted(index))
|
| 209 |
+
expected.index = expected.index._with_freq("infer")
|
| 210 |
+
|
| 211 |
+
result = result.asfreq("D")
|
| 212 |
+
tm.assert_equal(result, expected)
|
| 213 |
+
|
| 214 |
+
def test_asfreq_after_normalize(self, unit):
|
| 215 |
+
# https://github.com/pandas-dev/pandas/issues/50727
|
| 216 |
+
result = DatetimeIndex(
|
| 217 |
+
date_range("2000", periods=2).as_unit(unit).normalize(), freq="D"
|
| 218 |
+
)
|
| 219 |
+
expected = DatetimeIndex(["2000-01-01", "2000-01-02"], freq="D").as_unit(unit)
|
| 220 |
+
tm.assert_index_equal(result, expected)
|
| 221 |
+
|
| 222 |
+
@pytest.mark.parametrize(
|
| 223 |
+
"freq, freq_half",
|
| 224 |
+
[
|
| 225 |
+
("2ME", "ME"),
|
| 226 |
+
(MonthEnd(2), MonthEnd(1)),
|
| 227 |
+
],
|
| 228 |
+
)
|
| 229 |
+
def test_asfreq_2ME(self, freq, freq_half):
|
| 230 |
+
index = date_range("1/1/2000", periods=6, freq=freq_half)
|
| 231 |
+
df = DataFrame({"s": Series([0.0, 1.0, 2.0, 3.0, 4.0, 5.0], index=index)})
|
| 232 |
+
expected = df.asfreq(freq=freq)
|
| 233 |
+
|
| 234 |
+
index = date_range("1/1/2000", periods=3, freq=freq)
|
| 235 |
+
result = DataFrame({"s": Series([0.0, 2.0, 4.0], index=index)})
|
| 236 |
+
tm.assert_frame_equal(result, expected)
|
| 237 |
+
|
| 238 |
+
@pytest.mark.parametrize(
|
| 239 |
+
"freq, freq_depr",
|
| 240 |
+
[
|
| 241 |
+
("2ME", "2M"),
|
| 242 |
+
("2QE", "2Q"),
|
| 243 |
+
("2QE-SEP", "2Q-SEP"),
|
| 244 |
+
("1BQE", "1BQ"),
|
| 245 |
+
("2BQE-SEP", "2BQ-SEP"),
|
| 246 |
+
("1YE", "1Y"),
|
| 247 |
+
("2YE-MAR", "2Y-MAR"),
|
| 248 |
+
("1YE", "1A"),
|
| 249 |
+
("2YE-MAR", "2A-MAR"),
|
| 250 |
+
("2BYE-MAR", "2BA-MAR"),
|
| 251 |
+
],
|
| 252 |
+
)
|
| 253 |
+
def test_asfreq_frequency_M_Q_Y_A_deprecated(self, freq, freq_depr):
|
| 254 |
+
# GH#9586, #55978
|
| 255 |
+
depr_msg = f"'{freq_depr[1:]}' is deprecated and will be removed "
|
| 256 |
+
f"in a future version, please use '{freq[1:]}' instead."
|
| 257 |
+
|
| 258 |
+
index = date_range("1/1/2000", periods=4, freq=f"{freq[1:]}")
|
| 259 |
+
df = DataFrame({"s": Series([0.0, 1.0, 2.0, 3.0], index=index)})
|
| 260 |
+
expected = df.asfreq(freq=freq)
|
| 261 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 262 |
+
result = df.asfreq(freq=freq_depr)
|
| 263 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_asof.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas._libs.tslibs import IncompatibleFrequency
|
| 5 |
+
|
| 6 |
+
from pandas import (
|
| 7 |
+
DataFrame,
|
| 8 |
+
Period,
|
| 9 |
+
Series,
|
| 10 |
+
Timestamp,
|
| 11 |
+
date_range,
|
| 12 |
+
period_range,
|
| 13 |
+
to_datetime,
|
| 14 |
+
)
|
| 15 |
+
import pandas._testing as tm
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.fixture
|
| 19 |
+
def date_range_frame():
|
| 20 |
+
"""
|
| 21 |
+
Fixture for DataFrame of ints with date_range index
|
| 22 |
+
|
| 23 |
+
Columns are ['A', 'B'].
|
| 24 |
+
"""
|
| 25 |
+
N = 50
|
| 26 |
+
rng = date_range("1/1/1990", periods=N, freq="53s")
|
| 27 |
+
return DataFrame({"A": np.arange(N), "B": np.arange(N)}, index=rng)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestFrameAsof:
|
| 31 |
+
def test_basic(self, date_range_frame):
|
| 32 |
+
# Explicitly cast to float to avoid implicit cast when setting np.nan
|
| 33 |
+
df = date_range_frame.astype({"A": "float"})
|
| 34 |
+
N = 50
|
| 35 |
+
df.loc[df.index[15:30], "A"] = np.nan
|
| 36 |
+
dates = date_range("1/1/1990", periods=N * 3, freq="25s")
|
| 37 |
+
|
| 38 |
+
result = df.asof(dates)
|
| 39 |
+
assert result.notna().all(1).all()
|
| 40 |
+
lb = df.index[14]
|
| 41 |
+
ub = df.index[30]
|
| 42 |
+
|
| 43 |
+
dates = list(dates)
|
| 44 |
+
|
| 45 |
+
result = df.asof(dates)
|
| 46 |
+
assert result.notna().all(1).all()
|
| 47 |
+
|
| 48 |
+
mask = (result.index >= lb) & (result.index < ub)
|
| 49 |
+
rs = result[mask]
|
| 50 |
+
assert (rs == 14).all(1).all()
|
| 51 |
+
|
| 52 |
+
def test_subset(self, date_range_frame):
|
| 53 |
+
N = 10
|
| 54 |
+
# explicitly cast to float to avoid implicit upcast when setting to np.nan
|
| 55 |
+
df = date_range_frame.iloc[:N].copy().astype({"A": "float"})
|
| 56 |
+
df.loc[df.index[4:8], "A"] = np.nan
|
| 57 |
+
dates = date_range("1/1/1990", periods=N * 3, freq="25s")
|
| 58 |
+
|
| 59 |
+
# with a subset of A should be the same
|
| 60 |
+
result = df.asof(dates, subset="A")
|
| 61 |
+
expected = df.asof(dates)
|
| 62 |
+
tm.assert_frame_equal(result, expected)
|
| 63 |
+
|
| 64 |
+
# same with A/B
|
| 65 |
+
result = df.asof(dates, subset=["A", "B"])
|
| 66 |
+
expected = df.asof(dates)
|
| 67 |
+
tm.assert_frame_equal(result, expected)
|
| 68 |
+
|
| 69 |
+
# B gives df.asof
|
| 70 |
+
result = df.asof(dates, subset="B")
|
| 71 |
+
expected = df.resample("25s", closed="right").ffill().reindex(dates)
|
| 72 |
+
expected.iloc[20:] = 9
|
| 73 |
+
# no "missing", so "B" can retain int dtype (df["A"].dtype platform-dependent)
|
| 74 |
+
expected["B"] = expected["B"].astype(df["B"].dtype)
|
| 75 |
+
|
| 76 |
+
tm.assert_frame_equal(result, expected)
|
| 77 |
+
|
| 78 |
+
def test_missing(self, date_range_frame):
|
| 79 |
+
# GH 15118
|
| 80 |
+
# no match found - `where` value before earliest date in index
|
| 81 |
+
N = 10
|
| 82 |
+
# Cast to 'float64' to avoid upcast when introducing nan in df.asof
|
| 83 |
+
df = date_range_frame.iloc[:N].copy().astype("float64")
|
| 84 |
+
|
| 85 |
+
result = df.asof("1989-12-31")
|
| 86 |
+
|
| 87 |
+
expected = Series(
|
| 88 |
+
index=["A", "B"], name=Timestamp("1989-12-31"), dtype=np.float64
|
| 89 |
+
)
|
| 90 |
+
tm.assert_series_equal(result, expected)
|
| 91 |
+
|
| 92 |
+
result = df.asof(to_datetime(["1989-12-31"]))
|
| 93 |
+
expected = DataFrame(
|
| 94 |
+
index=to_datetime(["1989-12-31"]), columns=["A", "B"], dtype="float64"
|
| 95 |
+
)
|
| 96 |
+
tm.assert_frame_equal(result, expected)
|
| 97 |
+
|
| 98 |
+
# Check that we handle PeriodIndex correctly, dont end up with
|
| 99 |
+
# period.ordinal for series name
|
| 100 |
+
df = df.to_period("D")
|
| 101 |
+
result = df.asof("1989-12-31")
|
| 102 |
+
assert isinstance(result.name, Period)
|
| 103 |
+
|
| 104 |
+
def test_asof_all_nans(self, frame_or_series):
|
| 105 |
+
# GH 15713
|
| 106 |
+
# DataFrame/Series is all nans
|
| 107 |
+
result = frame_or_series([np.nan]).asof([0])
|
| 108 |
+
expected = frame_or_series([np.nan])
|
| 109 |
+
tm.assert_equal(result, expected)
|
| 110 |
+
|
| 111 |
+
def test_all_nans(self, date_range_frame):
|
| 112 |
+
# GH 15713
|
| 113 |
+
# DataFrame is all nans
|
| 114 |
+
|
| 115 |
+
# testing non-default indexes, multiple inputs
|
| 116 |
+
N = 150
|
| 117 |
+
rng = date_range_frame.index
|
| 118 |
+
dates = date_range("1/1/1990", periods=N, freq="25s")
|
| 119 |
+
result = DataFrame(np.nan, index=rng, columns=["A"]).asof(dates)
|
| 120 |
+
expected = DataFrame(np.nan, index=dates, columns=["A"])
|
| 121 |
+
tm.assert_frame_equal(result, expected)
|
| 122 |
+
|
| 123 |
+
# testing multiple columns
|
| 124 |
+
dates = date_range("1/1/1990", periods=N, freq="25s")
|
| 125 |
+
result = DataFrame(np.nan, index=rng, columns=["A", "B", "C"]).asof(dates)
|
| 126 |
+
expected = DataFrame(np.nan, index=dates, columns=["A", "B", "C"])
|
| 127 |
+
tm.assert_frame_equal(result, expected)
|
| 128 |
+
|
| 129 |
+
# testing scalar input
|
| 130 |
+
result = DataFrame(np.nan, index=[1, 2], columns=["A", "B"]).asof([3])
|
| 131 |
+
expected = DataFrame(np.nan, index=[3], columns=["A", "B"])
|
| 132 |
+
tm.assert_frame_equal(result, expected)
|
| 133 |
+
|
| 134 |
+
result = DataFrame(np.nan, index=[1, 2], columns=["A", "B"]).asof(3)
|
| 135 |
+
expected = Series(np.nan, index=["A", "B"], name=3)
|
| 136 |
+
tm.assert_series_equal(result, expected)
|
| 137 |
+
|
| 138 |
+
@pytest.mark.parametrize(
|
| 139 |
+
"stamp,expected",
|
| 140 |
+
[
|
| 141 |
+
(
|
| 142 |
+
Timestamp("2018-01-01 23:22:43.325+00:00"),
|
| 143 |
+
Series(2, name=Timestamp("2018-01-01 23:22:43.325+00:00")),
|
| 144 |
+
),
|
| 145 |
+
(
|
| 146 |
+
Timestamp("2018-01-01 22:33:20.682+01:00"),
|
| 147 |
+
Series(1, name=Timestamp("2018-01-01 22:33:20.682+01:00")),
|
| 148 |
+
),
|
| 149 |
+
],
|
| 150 |
+
)
|
| 151 |
+
def test_time_zone_aware_index(self, stamp, expected):
|
| 152 |
+
# GH21194
|
| 153 |
+
# Testing awareness of DataFrame index considering different
|
| 154 |
+
# UTC and timezone
|
| 155 |
+
df = DataFrame(
|
| 156 |
+
data=[1, 2],
|
| 157 |
+
index=[
|
| 158 |
+
Timestamp("2018-01-01 21:00:05.001+00:00"),
|
| 159 |
+
Timestamp("2018-01-01 22:35:10.550+00:00"),
|
| 160 |
+
],
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
result = df.asof(stamp)
|
| 164 |
+
tm.assert_series_equal(result, expected)
|
| 165 |
+
|
| 166 |
+
def test_is_copy(self, date_range_frame):
|
| 167 |
+
# GH-27357, GH-30784: ensure the result of asof is an actual copy and
|
| 168 |
+
# doesn't track the parent dataframe / doesn't give SettingWithCopy warnings
|
| 169 |
+
df = date_range_frame.astype({"A": "float"})
|
| 170 |
+
N = 50
|
| 171 |
+
df.loc[df.index[15:30], "A"] = np.nan
|
| 172 |
+
dates = date_range("1/1/1990", periods=N * 3, freq="25s")
|
| 173 |
+
|
| 174 |
+
result = df.asof(dates)
|
| 175 |
+
|
| 176 |
+
with tm.assert_produces_warning(None):
|
| 177 |
+
result["C"] = 1
|
| 178 |
+
|
| 179 |
+
def test_asof_periodindex_mismatched_freq(self):
|
| 180 |
+
N = 50
|
| 181 |
+
rng = period_range("1/1/1990", periods=N, freq="h")
|
| 182 |
+
df = DataFrame(np.random.default_rng(2).standard_normal(N), index=rng)
|
| 183 |
+
|
| 184 |
+
# Mismatched freq
|
| 185 |
+
msg = "Input has different freq"
|
| 186 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
| 187 |
+
df.asof(rng.asfreq("D"))
|
| 188 |
+
|
| 189 |
+
def test_asof_preserves_bool_dtype(self):
|
| 190 |
+
# GH#16063 was casting bools to floats
|
| 191 |
+
dti = date_range("2017-01-01", freq="MS", periods=4)
|
| 192 |
+
ser = Series([True, False, True], index=dti[:-1])
|
| 193 |
+
|
| 194 |
+
ts = dti[-1]
|
| 195 |
+
res = ser.asof([ts])
|
| 196 |
+
|
| 197 |
+
expected = Series([True], index=[ts])
|
| 198 |
+
tm.assert_series_equal(res, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_assign.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from pandas import DataFrame
|
| 4 |
+
import pandas._testing as tm
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestAssign:
|
| 8 |
+
def test_assign(self):
|
| 9 |
+
df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
|
| 10 |
+
original = df.copy()
|
| 11 |
+
result = df.assign(C=df.B / df.A)
|
| 12 |
+
expected = df.copy()
|
| 13 |
+
expected["C"] = [4, 2.5, 2]
|
| 14 |
+
tm.assert_frame_equal(result, expected)
|
| 15 |
+
|
| 16 |
+
# lambda syntax
|
| 17 |
+
result = df.assign(C=lambda x: x.B / x.A)
|
| 18 |
+
tm.assert_frame_equal(result, expected)
|
| 19 |
+
|
| 20 |
+
# original is unmodified
|
| 21 |
+
tm.assert_frame_equal(df, original)
|
| 22 |
+
|
| 23 |
+
# Non-Series array-like
|
| 24 |
+
result = df.assign(C=[4, 2.5, 2])
|
| 25 |
+
tm.assert_frame_equal(result, expected)
|
| 26 |
+
# original is unmodified
|
| 27 |
+
tm.assert_frame_equal(df, original)
|
| 28 |
+
|
| 29 |
+
result = df.assign(B=df.B / df.A)
|
| 30 |
+
expected = expected.drop("B", axis=1).rename(columns={"C": "B"})
|
| 31 |
+
tm.assert_frame_equal(result, expected)
|
| 32 |
+
|
| 33 |
+
# overwrite
|
| 34 |
+
result = df.assign(A=df.A + df.B)
|
| 35 |
+
expected = df.copy()
|
| 36 |
+
expected["A"] = [5, 7, 9]
|
| 37 |
+
tm.assert_frame_equal(result, expected)
|
| 38 |
+
|
| 39 |
+
# lambda
|
| 40 |
+
result = df.assign(A=lambda x: x.A + x.B)
|
| 41 |
+
tm.assert_frame_equal(result, expected)
|
| 42 |
+
|
| 43 |
+
def test_assign_multiple(self):
|
| 44 |
+
df = DataFrame([[1, 4], [2, 5], [3, 6]], columns=["A", "B"])
|
| 45 |
+
result = df.assign(C=[7, 8, 9], D=df.A, E=lambda x: x.B)
|
| 46 |
+
expected = DataFrame(
|
| 47 |
+
[[1, 4, 7, 1, 4], [2, 5, 8, 2, 5], [3, 6, 9, 3, 6]], columns=list("ABCDE")
|
| 48 |
+
)
|
| 49 |
+
tm.assert_frame_equal(result, expected)
|
| 50 |
+
|
| 51 |
+
def test_assign_order(self):
|
| 52 |
+
# GH 9818
|
| 53 |
+
df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
|
| 54 |
+
result = df.assign(D=df.A + df.B, C=df.A - df.B)
|
| 55 |
+
|
| 56 |
+
expected = DataFrame([[1, 2, 3, -1], [3, 4, 7, -1]], columns=list("ABDC"))
|
| 57 |
+
tm.assert_frame_equal(result, expected)
|
| 58 |
+
result = df.assign(C=df.A - df.B, D=df.A + df.B)
|
| 59 |
+
|
| 60 |
+
expected = DataFrame([[1, 2, -1, 3], [3, 4, -1, 7]], columns=list("ABCD"))
|
| 61 |
+
|
| 62 |
+
tm.assert_frame_equal(result, expected)
|
| 63 |
+
|
| 64 |
+
def test_assign_bad(self):
|
| 65 |
+
df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
|
| 66 |
+
|
| 67 |
+
# non-keyword argument
|
| 68 |
+
msg = r"assign\(\) takes 1 positional argument but 2 were given"
|
| 69 |
+
with pytest.raises(TypeError, match=msg):
|
| 70 |
+
df.assign(lambda x: x.A)
|
| 71 |
+
msg = "'DataFrame' object has no attribute 'C'"
|
| 72 |
+
with pytest.raises(AttributeError, match=msg):
|
| 73 |
+
df.assign(C=df.A, D=df.A + df.C)
|
| 74 |
+
|
| 75 |
+
def test_assign_dependent(self):
|
| 76 |
+
df = DataFrame({"A": [1, 2], "B": [3, 4]})
|
| 77 |
+
|
| 78 |
+
result = df.assign(C=df.A, D=lambda x: x["A"] + x["C"])
|
| 79 |
+
expected = DataFrame([[1, 3, 1, 2], [2, 4, 2, 4]], columns=list("ABCD"))
|
| 80 |
+
tm.assert_frame_equal(result, expected)
|
| 81 |
+
|
| 82 |
+
result = df.assign(C=lambda df: df.A, D=lambda df: df["A"] + df["C"])
|
| 83 |
+
expected = DataFrame([[1, 3, 1, 2], [2, 4, 2, 4]], columns=list("ABCD"))
|
| 84 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_astype.py
ADDED
|
@@ -0,0 +1,924 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas._config import using_string_dtype
|
| 7 |
+
|
| 8 |
+
import pandas.util._test_decorators as td
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from pandas import (
|
| 12 |
+
Categorical,
|
| 13 |
+
CategoricalDtype,
|
| 14 |
+
DataFrame,
|
| 15 |
+
DatetimeTZDtype,
|
| 16 |
+
Index,
|
| 17 |
+
Interval,
|
| 18 |
+
IntervalDtype,
|
| 19 |
+
NaT,
|
| 20 |
+
Series,
|
| 21 |
+
Timedelta,
|
| 22 |
+
Timestamp,
|
| 23 |
+
concat,
|
| 24 |
+
date_range,
|
| 25 |
+
option_context,
|
| 26 |
+
)
|
| 27 |
+
import pandas._testing as tm
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _check_cast(df, v):
|
| 31 |
+
"""
|
| 32 |
+
Check if all dtypes of df are equal to v
|
| 33 |
+
"""
|
| 34 |
+
assert all(s.dtype.name == v for _, s in df.items())
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class TestAstype:
|
| 38 |
+
def test_astype_float(self, float_frame):
|
| 39 |
+
casted = float_frame.astype(int)
|
| 40 |
+
expected = DataFrame(
|
| 41 |
+
float_frame.values.astype(int),
|
| 42 |
+
index=float_frame.index,
|
| 43 |
+
columns=float_frame.columns,
|
| 44 |
+
)
|
| 45 |
+
tm.assert_frame_equal(casted, expected)
|
| 46 |
+
|
| 47 |
+
casted = float_frame.astype(np.int32)
|
| 48 |
+
expected = DataFrame(
|
| 49 |
+
float_frame.values.astype(np.int32),
|
| 50 |
+
index=float_frame.index,
|
| 51 |
+
columns=float_frame.columns,
|
| 52 |
+
)
|
| 53 |
+
tm.assert_frame_equal(casted, expected)
|
| 54 |
+
|
| 55 |
+
float_frame["foo"] = "5"
|
| 56 |
+
casted = float_frame.astype(int)
|
| 57 |
+
expected = DataFrame(
|
| 58 |
+
float_frame.values.astype(int),
|
| 59 |
+
index=float_frame.index,
|
| 60 |
+
columns=float_frame.columns,
|
| 61 |
+
)
|
| 62 |
+
tm.assert_frame_equal(casted, expected)
|
| 63 |
+
|
| 64 |
+
def test_astype_mixed_float(self, mixed_float_frame):
|
| 65 |
+
# mixed casting
|
| 66 |
+
casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float32")
|
| 67 |
+
_check_cast(casted, "float32")
|
| 68 |
+
|
| 69 |
+
casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float16")
|
| 70 |
+
_check_cast(casted, "float16")
|
| 71 |
+
|
| 72 |
+
def test_astype_mixed_type(self):
|
| 73 |
+
# mixed casting
|
| 74 |
+
df = DataFrame(
|
| 75 |
+
{
|
| 76 |
+
"a": 1.0,
|
| 77 |
+
"b": 2,
|
| 78 |
+
"c": "foo",
|
| 79 |
+
"float32": np.array([1.0] * 10, dtype="float32"),
|
| 80 |
+
"int32": np.array([1] * 10, dtype="int32"),
|
| 81 |
+
},
|
| 82 |
+
index=np.arange(10),
|
| 83 |
+
)
|
| 84 |
+
mn = df._get_numeric_data().copy()
|
| 85 |
+
mn["little_float"] = np.array(12345.0, dtype="float16")
|
| 86 |
+
mn["big_float"] = np.array(123456789101112.0, dtype="float64")
|
| 87 |
+
|
| 88 |
+
casted = mn.astype("float64")
|
| 89 |
+
_check_cast(casted, "float64")
|
| 90 |
+
|
| 91 |
+
casted = mn.astype("int64")
|
| 92 |
+
_check_cast(casted, "int64")
|
| 93 |
+
|
| 94 |
+
casted = mn.reindex(columns=["little_float"]).astype("float16")
|
| 95 |
+
_check_cast(casted, "float16")
|
| 96 |
+
|
| 97 |
+
casted = mn.astype("float32")
|
| 98 |
+
_check_cast(casted, "float32")
|
| 99 |
+
|
| 100 |
+
casted = mn.astype("int32")
|
| 101 |
+
_check_cast(casted, "int32")
|
| 102 |
+
|
| 103 |
+
# to object
|
| 104 |
+
casted = mn.astype("O")
|
| 105 |
+
_check_cast(casted, "object")
|
| 106 |
+
|
| 107 |
+
def test_astype_with_exclude_string(self, float_frame):
|
| 108 |
+
df = float_frame.copy()
|
| 109 |
+
expected = float_frame.astype(int)
|
| 110 |
+
df["string"] = "foo"
|
| 111 |
+
casted = df.astype(int, errors="ignore")
|
| 112 |
+
|
| 113 |
+
expected["string"] = "foo"
|
| 114 |
+
tm.assert_frame_equal(casted, expected)
|
| 115 |
+
|
| 116 |
+
df = float_frame.copy()
|
| 117 |
+
expected = float_frame.astype(np.int32)
|
| 118 |
+
df["string"] = "foo"
|
| 119 |
+
casted = df.astype(np.int32, errors="ignore")
|
| 120 |
+
|
| 121 |
+
expected["string"] = "foo"
|
| 122 |
+
tm.assert_frame_equal(casted, expected)
|
| 123 |
+
|
| 124 |
+
def test_astype_with_view_float(self, float_frame):
|
| 125 |
+
# this is the only real reason to do it this way
|
| 126 |
+
tf = np.round(float_frame).astype(np.int32)
|
| 127 |
+
tf.astype(np.float32, copy=False)
|
| 128 |
+
|
| 129 |
+
# TODO(wesm): verification?
|
| 130 |
+
tf = float_frame.astype(np.float64)
|
| 131 |
+
tf.astype(np.int64, copy=False)
|
| 132 |
+
|
| 133 |
+
def test_astype_with_view_mixed_float(self, mixed_float_frame):
|
| 134 |
+
tf = mixed_float_frame.reindex(columns=["A", "B", "C"])
|
| 135 |
+
|
| 136 |
+
tf.astype(np.int64)
|
| 137 |
+
tf.astype(np.float32)
|
| 138 |
+
|
| 139 |
+
@pytest.mark.parametrize("dtype", [np.int32, np.int64])
|
| 140 |
+
@pytest.mark.parametrize("val", [np.nan, np.inf])
|
| 141 |
+
def test_astype_cast_nan_inf_int(self, val, dtype):
|
| 142 |
+
# see GH#14265
|
| 143 |
+
#
|
| 144 |
+
# Check NaN and inf --> raise error when converting to int.
|
| 145 |
+
msg = "Cannot convert non-finite values \\(NA or inf\\) to integer"
|
| 146 |
+
df = DataFrame([val])
|
| 147 |
+
|
| 148 |
+
with pytest.raises(ValueError, match=msg):
|
| 149 |
+
df.astype(dtype)
|
| 150 |
+
|
| 151 |
+
def test_astype_str(self):
|
| 152 |
+
# see GH#9757
|
| 153 |
+
a = Series(date_range("2010-01-04", periods=5))
|
| 154 |
+
b = Series(date_range("3/6/2012 00:00", periods=5, tz="US/Eastern"))
|
| 155 |
+
c = Series([Timedelta(x, unit="d") for x in range(5)])
|
| 156 |
+
d = Series(range(5))
|
| 157 |
+
e = Series([0.0, 0.2, 0.4, 0.6, 0.8])
|
| 158 |
+
|
| 159 |
+
df = DataFrame({"a": a, "b": b, "c": c, "d": d, "e": e})
|
| 160 |
+
|
| 161 |
+
# Datetime-like
|
| 162 |
+
result = df.astype(str)
|
| 163 |
+
|
| 164 |
+
expected = DataFrame(
|
| 165 |
+
{
|
| 166 |
+
"a": list(map(str, (Timestamp(x)._date_repr for x in a._values))),
|
| 167 |
+
"b": list(map(str, map(Timestamp, b._values))),
|
| 168 |
+
"c": [Timedelta(x)._repr_base() for x in c._values],
|
| 169 |
+
"d": list(map(str, d._values)),
|
| 170 |
+
"e": list(map(str, e._values)),
|
| 171 |
+
},
|
| 172 |
+
dtype="str",
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
tm.assert_frame_equal(result, expected)
|
| 176 |
+
|
| 177 |
+
def test_astype_str_float(self, using_infer_string):
|
| 178 |
+
# see GH#11302
|
| 179 |
+
result = DataFrame([np.nan]).astype(str)
|
| 180 |
+
expected = DataFrame([np.nan if using_infer_string else "nan"], dtype="str")
|
| 181 |
+
|
| 182 |
+
tm.assert_frame_equal(result, expected)
|
| 183 |
+
result = DataFrame([1.12345678901234567890]).astype(str)
|
| 184 |
+
|
| 185 |
+
val = "1.1234567890123457"
|
| 186 |
+
expected = DataFrame([val], dtype="str")
|
| 187 |
+
tm.assert_frame_equal(result, expected)
|
| 188 |
+
|
| 189 |
+
@pytest.mark.parametrize("dtype_class", [dict, Series])
|
| 190 |
+
def test_astype_dict_like(self, dtype_class):
|
| 191 |
+
# GH7271 & GH16717
|
| 192 |
+
a = Series(date_range("2010-01-04", periods=5))
|
| 193 |
+
b = Series(range(5))
|
| 194 |
+
c = Series([0.0, 0.2, 0.4, 0.6, 0.8])
|
| 195 |
+
d = Series(["1.0", "2", "3.14", "4", "5.4"])
|
| 196 |
+
df = DataFrame({"a": a, "b": b, "c": c, "d": d})
|
| 197 |
+
original = df.copy(deep=True)
|
| 198 |
+
|
| 199 |
+
# change type of a subset of columns
|
| 200 |
+
dt1 = dtype_class({"b": "str", "d": "float32"})
|
| 201 |
+
result = df.astype(dt1)
|
| 202 |
+
expected = DataFrame(
|
| 203 |
+
{
|
| 204 |
+
"a": a,
|
| 205 |
+
"b": Series(["0", "1", "2", "3", "4"], dtype="str"),
|
| 206 |
+
"c": c,
|
| 207 |
+
"d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float32"),
|
| 208 |
+
}
|
| 209 |
+
)
|
| 210 |
+
tm.assert_frame_equal(result, expected)
|
| 211 |
+
tm.assert_frame_equal(df, original)
|
| 212 |
+
|
| 213 |
+
dt2 = dtype_class({"b": np.float32, "c": "float32", "d": np.float64})
|
| 214 |
+
result = df.astype(dt2)
|
| 215 |
+
expected = DataFrame(
|
| 216 |
+
{
|
| 217 |
+
"a": a,
|
| 218 |
+
"b": Series([0.0, 1.0, 2.0, 3.0, 4.0], dtype="float32"),
|
| 219 |
+
"c": Series([0.0, 0.2, 0.4, 0.6, 0.8], dtype="float32"),
|
| 220 |
+
"d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float64"),
|
| 221 |
+
}
|
| 222 |
+
)
|
| 223 |
+
tm.assert_frame_equal(result, expected)
|
| 224 |
+
tm.assert_frame_equal(df, original)
|
| 225 |
+
|
| 226 |
+
# change all columns
|
| 227 |
+
dt3 = dtype_class({"a": str, "b": str, "c": str, "d": str})
|
| 228 |
+
tm.assert_frame_equal(df.astype(dt3), df.astype(str))
|
| 229 |
+
tm.assert_frame_equal(df, original)
|
| 230 |
+
|
| 231 |
+
# error should be raised when using something other than column labels
|
| 232 |
+
# in the keys of the dtype dict
|
| 233 |
+
dt4 = dtype_class({"b": str, 2: str})
|
| 234 |
+
dt5 = dtype_class({"e": str})
|
| 235 |
+
msg_frame = (
|
| 236 |
+
"Only a column name can be used for the key in a dtype mappings argument. "
|
| 237 |
+
"'{}' not found in columns."
|
| 238 |
+
)
|
| 239 |
+
with pytest.raises(KeyError, match=msg_frame.format(2)):
|
| 240 |
+
df.astype(dt4)
|
| 241 |
+
with pytest.raises(KeyError, match=msg_frame.format("e")):
|
| 242 |
+
df.astype(dt5)
|
| 243 |
+
tm.assert_frame_equal(df, original)
|
| 244 |
+
|
| 245 |
+
# if the dtypes provided are the same as the original dtypes, the
|
| 246 |
+
# resulting DataFrame should be the same as the original DataFrame
|
| 247 |
+
dt6 = dtype_class({col: df[col].dtype for col in df.columns})
|
| 248 |
+
equiv = df.astype(dt6)
|
| 249 |
+
tm.assert_frame_equal(df, equiv)
|
| 250 |
+
tm.assert_frame_equal(df, original)
|
| 251 |
+
|
| 252 |
+
# GH#16717
|
| 253 |
+
# if dtypes provided is empty, the resulting DataFrame
|
| 254 |
+
# should be the same as the original DataFrame
|
| 255 |
+
dt7 = dtype_class({}) if dtype_class is dict else dtype_class({}, dtype=object)
|
| 256 |
+
equiv = df.astype(dt7)
|
| 257 |
+
tm.assert_frame_equal(df, equiv)
|
| 258 |
+
tm.assert_frame_equal(df, original)
|
| 259 |
+
|
| 260 |
+
def test_astype_duplicate_col(self):
|
| 261 |
+
a1 = Series([1, 2, 3, 4, 5], name="a")
|
| 262 |
+
b = Series([0.1, 0.2, 0.4, 0.6, 0.8], name="b")
|
| 263 |
+
a2 = Series([0, 1, 2, 3, 4], name="a")
|
| 264 |
+
df = concat([a1, b, a2], axis=1)
|
| 265 |
+
|
| 266 |
+
result = df.astype("str")
|
| 267 |
+
a1_str = Series(["1", "2", "3", "4", "5"], dtype="str", name="a")
|
| 268 |
+
b_str = Series(["0.1", "0.2", "0.4", "0.6", "0.8"], dtype="str", name="b")
|
| 269 |
+
a2_str = Series(["0", "1", "2", "3", "4"], dtype="str", name="a")
|
| 270 |
+
expected = concat([a1_str, b_str, a2_str], axis=1)
|
| 271 |
+
tm.assert_frame_equal(result, expected)
|
| 272 |
+
|
| 273 |
+
result = df.astype({"a": "str"})
|
| 274 |
+
expected = concat([a1_str, b, a2_str], axis=1)
|
| 275 |
+
tm.assert_frame_equal(result, expected)
|
| 276 |
+
|
| 277 |
+
def test_astype_duplicate_col_series_arg(self):
|
| 278 |
+
# GH#44417
|
| 279 |
+
vals = np.random.default_rng(2).standard_normal((3, 4))
|
| 280 |
+
df = DataFrame(vals, columns=["A", "B", "C", "A"])
|
| 281 |
+
dtypes = df.dtypes
|
| 282 |
+
dtypes.iloc[0] = str
|
| 283 |
+
dtypes.iloc[2] = "Float64"
|
| 284 |
+
|
| 285 |
+
result = df.astype(dtypes)
|
| 286 |
+
expected = DataFrame(
|
| 287 |
+
{
|
| 288 |
+
0: Series(vals[:, 0].astype(str), dtype="str"),
|
| 289 |
+
1: vals[:, 1],
|
| 290 |
+
2: pd.array(vals[:, 2], dtype="Float64"),
|
| 291 |
+
3: vals[:, 3],
|
| 292 |
+
}
|
| 293 |
+
)
|
| 294 |
+
expected.columns = df.columns
|
| 295 |
+
tm.assert_frame_equal(result, expected)
|
| 296 |
+
|
| 297 |
+
@pytest.mark.parametrize(
|
| 298 |
+
"dtype",
|
| 299 |
+
[
|
| 300 |
+
"category",
|
| 301 |
+
CategoricalDtype(),
|
| 302 |
+
CategoricalDtype(ordered=True),
|
| 303 |
+
CategoricalDtype(ordered=False),
|
| 304 |
+
CategoricalDtype(categories=list("abcdef")),
|
| 305 |
+
CategoricalDtype(categories=list("edba"), ordered=False),
|
| 306 |
+
CategoricalDtype(categories=list("edcb"), ordered=True),
|
| 307 |
+
],
|
| 308 |
+
ids=repr,
|
| 309 |
+
)
|
| 310 |
+
def test_astype_categorical(self, dtype):
|
| 311 |
+
# GH#18099
|
| 312 |
+
d = {"A": list("abbc"), "B": list("bccd"), "C": list("cdde")}
|
| 313 |
+
df = DataFrame(d)
|
| 314 |
+
result = df.astype(dtype)
|
| 315 |
+
expected = DataFrame({k: Categorical(v, dtype=dtype) for k, v in d.items()})
|
| 316 |
+
tm.assert_frame_equal(result, expected)
|
| 317 |
+
|
| 318 |
+
@pytest.mark.parametrize("cls", [CategoricalDtype, DatetimeTZDtype, IntervalDtype])
|
| 319 |
+
def test_astype_categoricaldtype_class_raises(self, cls):
|
| 320 |
+
df = DataFrame({"A": ["a", "a", "b", "c"]})
|
| 321 |
+
xpr = f"Expected an instance of {cls.__name__}"
|
| 322 |
+
with pytest.raises(TypeError, match=xpr):
|
| 323 |
+
df.astype({"A": cls})
|
| 324 |
+
|
| 325 |
+
with pytest.raises(TypeError, match=xpr):
|
| 326 |
+
df["A"].astype(cls)
|
| 327 |
+
|
| 328 |
+
@pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"])
|
| 329 |
+
def test_astype_extension_dtypes(self, dtype):
|
| 330 |
+
# GH#22578
|
| 331 |
+
df = DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"])
|
| 332 |
+
|
| 333 |
+
expected1 = DataFrame(
|
| 334 |
+
{
|
| 335 |
+
"a": pd.array([1, 3, 5], dtype=dtype),
|
| 336 |
+
"b": pd.array([2, 4, 6], dtype=dtype),
|
| 337 |
+
}
|
| 338 |
+
)
|
| 339 |
+
tm.assert_frame_equal(df.astype(dtype), expected1)
|
| 340 |
+
tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
|
| 341 |
+
tm.assert_frame_equal(df.astype(dtype).astype("float64"), df)
|
| 342 |
+
|
| 343 |
+
df = DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"])
|
| 344 |
+
df["b"] = df["b"].astype(dtype)
|
| 345 |
+
expected2 = DataFrame(
|
| 346 |
+
{"a": [1.0, 3.0, 5.0], "b": pd.array([2, 4, 6], dtype=dtype)}
|
| 347 |
+
)
|
| 348 |
+
tm.assert_frame_equal(df, expected2)
|
| 349 |
+
|
| 350 |
+
tm.assert_frame_equal(df.astype(dtype), expected1)
|
| 351 |
+
tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
|
| 352 |
+
|
| 353 |
+
@pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"])
|
| 354 |
+
def test_astype_extension_dtypes_1d(self, dtype):
|
| 355 |
+
# GH#22578
|
| 356 |
+
df = DataFrame({"a": [1.0, 2.0, 3.0]})
|
| 357 |
+
|
| 358 |
+
expected1 = DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)})
|
| 359 |
+
tm.assert_frame_equal(df.astype(dtype), expected1)
|
| 360 |
+
tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
|
| 361 |
+
|
| 362 |
+
df = DataFrame({"a": [1.0, 2.0, 3.0]})
|
| 363 |
+
df["a"] = df["a"].astype(dtype)
|
| 364 |
+
expected2 = DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)})
|
| 365 |
+
tm.assert_frame_equal(df, expected2)
|
| 366 |
+
|
| 367 |
+
tm.assert_frame_equal(df.astype(dtype), expected1)
|
| 368 |
+
tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
|
| 369 |
+
|
| 370 |
+
@pytest.mark.parametrize("dtype", ["category", "Int64"])
|
| 371 |
+
def test_astype_extension_dtypes_duplicate_col(self, dtype):
|
| 372 |
+
# GH#24704
|
| 373 |
+
a1 = Series([0, np.nan, 4], name="a")
|
| 374 |
+
a2 = Series([np.nan, 3, 5], name="a")
|
| 375 |
+
df = concat([a1, a2], axis=1)
|
| 376 |
+
|
| 377 |
+
result = df.astype(dtype)
|
| 378 |
+
expected = concat([a1.astype(dtype), a2.astype(dtype)], axis=1)
|
| 379 |
+
tm.assert_frame_equal(result, expected)
|
| 380 |
+
|
| 381 |
+
@pytest.mark.parametrize(
|
| 382 |
+
"dtype", [{100: "float64", 200: "uint64"}, "category", "float64"]
|
| 383 |
+
)
|
| 384 |
+
def test_astype_column_metadata(self, dtype):
|
| 385 |
+
# GH#19920
|
| 386 |
+
columns = Index([100, 200, 300], dtype=np.uint64, name="foo")
|
| 387 |
+
df = DataFrame(np.arange(15).reshape(5, 3), columns=columns)
|
| 388 |
+
df = df.astype(dtype)
|
| 389 |
+
tm.assert_index_equal(df.columns, columns)
|
| 390 |
+
|
| 391 |
+
@pytest.mark.parametrize("unit", ["Y", "M", "W", "D", "h", "m"])
|
| 392 |
+
def test_astype_from_object_to_datetime_unit(self, unit):
|
| 393 |
+
vals = [
|
| 394 |
+
["2015-01-01", "2015-01-02", "2015-01-03"],
|
| 395 |
+
["2017-01-01", "2017-01-02", "2017-02-03"],
|
| 396 |
+
]
|
| 397 |
+
df = DataFrame(vals, dtype=object)
|
| 398 |
+
msg = (
|
| 399 |
+
rf"Unexpected value for 'dtype': 'datetime64\[{unit}\]'. "
|
| 400 |
+
r"Must be 'datetime64\[s\]', 'datetime64\[ms\]', 'datetime64\[us\]', "
|
| 401 |
+
r"'datetime64\[ns\]' or DatetimeTZDtype"
|
| 402 |
+
)
|
| 403 |
+
with pytest.raises(ValueError, match=msg):
|
| 404 |
+
df.astype(f"M8[{unit}]")
|
| 405 |
+
|
| 406 |
+
@pytest.mark.parametrize("unit", ["Y", "M", "W", "D", "h", "m"])
|
| 407 |
+
def test_astype_from_object_to_timedelta_unit(self, unit):
|
| 408 |
+
vals = [
|
| 409 |
+
["1 Day", "2 Days", "3 Days"],
|
| 410 |
+
["4 Days", "5 Days", "6 Days"],
|
| 411 |
+
]
|
| 412 |
+
df = DataFrame(vals, dtype=object)
|
| 413 |
+
msg = (
|
| 414 |
+
r"Cannot convert from timedelta64\[ns\] to timedelta64\[.*\]. "
|
| 415 |
+
"Supported resolutions are 's', 'ms', 'us', 'ns'"
|
| 416 |
+
)
|
| 417 |
+
with pytest.raises(ValueError, match=msg):
|
| 418 |
+
# TODO: this is ValueError while for DatetimeArray it is TypeError;
|
| 419 |
+
# get these consistent
|
| 420 |
+
df.astype(f"m8[{unit}]")
|
| 421 |
+
|
| 422 |
+
@pytest.mark.parametrize("dtype", ["M8", "m8"])
|
| 423 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
|
| 424 |
+
def test_astype_from_datetimelike_to_object(self, dtype, unit):
|
| 425 |
+
# tests astype to object dtype
|
| 426 |
+
# GH#19223 / GH#12425
|
| 427 |
+
dtype = f"{dtype}[{unit}]"
|
| 428 |
+
arr = np.array([[1, 2, 3]], dtype=dtype)
|
| 429 |
+
df = DataFrame(arr)
|
| 430 |
+
result = df.astype(object)
|
| 431 |
+
assert (result.dtypes == object).all()
|
| 432 |
+
|
| 433 |
+
if dtype.startswith("M8"):
|
| 434 |
+
assert result.iloc[0, 0] == Timestamp(1, unit=unit)
|
| 435 |
+
else:
|
| 436 |
+
assert result.iloc[0, 0] == Timedelta(1, unit=unit)
|
| 437 |
+
|
| 438 |
+
@pytest.mark.parametrize("arr_dtype", [np.int64, np.float64])
|
| 439 |
+
@pytest.mark.parametrize("dtype", ["M8", "m8"])
|
| 440 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
|
| 441 |
+
def test_astype_to_datetimelike_unit(self, arr_dtype, dtype, unit):
|
| 442 |
+
# tests all units from numeric origination
|
| 443 |
+
# GH#19223 / GH#12425
|
| 444 |
+
dtype = f"{dtype}[{unit}]"
|
| 445 |
+
arr = np.array([[1, 2, 3]], dtype=arr_dtype)
|
| 446 |
+
df = DataFrame(arr)
|
| 447 |
+
result = df.astype(dtype)
|
| 448 |
+
expected = DataFrame(arr.astype(dtype))
|
| 449 |
+
|
| 450 |
+
tm.assert_frame_equal(result, expected)
|
| 451 |
+
|
| 452 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
|
| 453 |
+
def test_astype_to_datetime_unit(self, unit):
|
| 454 |
+
# tests all units from datetime origination
|
| 455 |
+
# GH#19223
|
| 456 |
+
dtype = f"M8[{unit}]"
|
| 457 |
+
arr = np.array([[1, 2, 3]], dtype=dtype)
|
| 458 |
+
df = DataFrame(arr)
|
| 459 |
+
ser = df.iloc[:, 0]
|
| 460 |
+
idx = Index(ser)
|
| 461 |
+
dta = ser._values
|
| 462 |
+
|
| 463 |
+
if unit in ["ns", "us", "ms", "s"]:
|
| 464 |
+
# GH#48928
|
| 465 |
+
result = df.astype(dtype)
|
| 466 |
+
else:
|
| 467 |
+
# we use the nearest supported dtype (i.e. M8[s])
|
| 468 |
+
msg = rf"Cannot cast DatetimeArray to dtype datetime64\[{unit}\]"
|
| 469 |
+
with pytest.raises(TypeError, match=msg):
|
| 470 |
+
df.astype(dtype)
|
| 471 |
+
|
| 472 |
+
with pytest.raises(TypeError, match=msg):
|
| 473 |
+
ser.astype(dtype)
|
| 474 |
+
|
| 475 |
+
with pytest.raises(TypeError, match=msg.replace("Array", "Index")):
|
| 476 |
+
idx.astype(dtype)
|
| 477 |
+
|
| 478 |
+
with pytest.raises(TypeError, match=msg):
|
| 479 |
+
dta.astype(dtype)
|
| 480 |
+
|
| 481 |
+
return
|
| 482 |
+
|
| 483 |
+
exp_df = DataFrame(arr.astype(dtype))
|
| 484 |
+
assert (exp_df.dtypes == dtype).all()
|
| 485 |
+
tm.assert_frame_equal(result, exp_df)
|
| 486 |
+
|
| 487 |
+
res_ser = ser.astype(dtype)
|
| 488 |
+
exp_ser = exp_df.iloc[:, 0]
|
| 489 |
+
assert exp_ser.dtype == dtype
|
| 490 |
+
tm.assert_series_equal(res_ser, exp_ser)
|
| 491 |
+
|
| 492 |
+
exp_dta = exp_ser._values
|
| 493 |
+
|
| 494 |
+
res_index = idx.astype(dtype)
|
| 495 |
+
exp_index = Index(exp_ser)
|
| 496 |
+
assert exp_index.dtype == dtype
|
| 497 |
+
tm.assert_index_equal(res_index, exp_index)
|
| 498 |
+
|
| 499 |
+
res_dta = dta.astype(dtype)
|
| 500 |
+
assert exp_dta.dtype == dtype
|
| 501 |
+
tm.assert_extension_array_equal(res_dta, exp_dta)
|
| 502 |
+
|
| 503 |
+
@pytest.mark.parametrize("unit", ["ns"])
|
| 504 |
+
def test_astype_to_timedelta_unit_ns(self, unit):
|
| 505 |
+
# preserver the timedelta conversion
|
| 506 |
+
# GH#19223
|
| 507 |
+
dtype = f"m8[{unit}]"
|
| 508 |
+
arr = np.array([[1, 2, 3]], dtype=dtype)
|
| 509 |
+
df = DataFrame(arr)
|
| 510 |
+
result = df.astype(dtype)
|
| 511 |
+
expected = DataFrame(arr.astype(dtype))
|
| 512 |
+
|
| 513 |
+
tm.assert_frame_equal(result, expected)
|
| 514 |
+
|
| 515 |
+
@pytest.mark.parametrize("unit", ["us", "ms", "s", "h", "m", "D"])
|
| 516 |
+
def test_astype_to_timedelta_unit(self, unit):
|
| 517 |
+
# coerce to float
|
| 518 |
+
# GH#19223 until 2.0 used to coerce to float
|
| 519 |
+
dtype = f"m8[{unit}]"
|
| 520 |
+
arr = np.array([[1, 2, 3]], dtype=dtype)
|
| 521 |
+
df = DataFrame(arr)
|
| 522 |
+
ser = df.iloc[:, 0]
|
| 523 |
+
tdi = Index(ser)
|
| 524 |
+
tda = tdi._values
|
| 525 |
+
|
| 526 |
+
if unit in ["us", "ms", "s"]:
|
| 527 |
+
assert (df.dtypes == dtype).all()
|
| 528 |
+
result = df.astype(dtype)
|
| 529 |
+
else:
|
| 530 |
+
# We get the nearest supported unit, i.e. "s"
|
| 531 |
+
assert (df.dtypes == "m8[s]").all()
|
| 532 |
+
|
| 533 |
+
msg = (
|
| 534 |
+
rf"Cannot convert from timedelta64\[s\] to timedelta64\[{unit}\]. "
|
| 535 |
+
"Supported resolutions are 's', 'ms', 'us', 'ns'"
|
| 536 |
+
)
|
| 537 |
+
with pytest.raises(ValueError, match=msg):
|
| 538 |
+
df.astype(dtype)
|
| 539 |
+
with pytest.raises(ValueError, match=msg):
|
| 540 |
+
ser.astype(dtype)
|
| 541 |
+
with pytest.raises(ValueError, match=msg):
|
| 542 |
+
tdi.astype(dtype)
|
| 543 |
+
with pytest.raises(ValueError, match=msg):
|
| 544 |
+
tda.astype(dtype)
|
| 545 |
+
|
| 546 |
+
return
|
| 547 |
+
|
| 548 |
+
result = df.astype(dtype)
|
| 549 |
+
# The conversion is a no-op, so we just get a copy
|
| 550 |
+
expected = df
|
| 551 |
+
tm.assert_frame_equal(result, expected)
|
| 552 |
+
|
| 553 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
|
| 554 |
+
def test_astype_to_incorrect_datetimelike(self, unit):
|
| 555 |
+
# trying to astype a m to a M, or vice-versa
|
| 556 |
+
# GH#19224
|
| 557 |
+
dtype = f"M8[{unit}]"
|
| 558 |
+
other = f"m8[{unit}]"
|
| 559 |
+
|
| 560 |
+
df = DataFrame(np.array([[1, 2, 3]], dtype=dtype))
|
| 561 |
+
msg = "|".join(
|
| 562 |
+
[
|
| 563 |
+
# BlockManager path
|
| 564 |
+
rf"Cannot cast DatetimeArray to dtype timedelta64\[{unit}\]",
|
| 565 |
+
# ArrayManager path
|
| 566 |
+
"cannot astype a datetimelike from "
|
| 567 |
+
rf"\[datetime64\[ns\]\] to \[timedelta64\[{unit}\]\]",
|
| 568 |
+
]
|
| 569 |
+
)
|
| 570 |
+
with pytest.raises(TypeError, match=msg):
|
| 571 |
+
df.astype(other)
|
| 572 |
+
|
| 573 |
+
msg = "|".join(
|
| 574 |
+
[
|
| 575 |
+
# BlockManager path
|
| 576 |
+
rf"Cannot cast TimedeltaArray to dtype datetime64\[{unit}\]",
|
| 577 |
+
# ArrayManager path
|
| 578 |
+
"cannot astype a timedelta from "
|
| 579 |
+
rf"\[timedelta64\[ns\]\] to \[datetime64\[{unit}\]\]",
|
| 580 |
+
]
|
| 581 |
+
)
|
| 582 |
+
df = DataFrame(np.array([[1, 2, 3]], dtype=other))
|
| 583 |
+
with pytest.raises(TypeError, match=msg):
|
| 584 |
+
df.astype(dtype)
|
| 585 |
+
|
| 586 |
+
def test_astype_arg_for_errors(self):
|
| 587 |
+
# GH#14878
|
| 588 |
+
|
| 589 |
+
df = DataFrame([1, 2, 3])
|
| 590 |
+
|
| 591 |
+
msg = (
|
| 592 |
+
"Expected value of kwarg 'errors' to be one of "
|
| 593 |
+
"['raise', 'ignore']. Supplied value is 'True'"
|
| 594 |
+
)
|
| 595 |
+
with pytest.raises(ValueError, match=re.escape(msg)):
|
| 596 |
+
df.astype(np.float64, errors=True)
|
| 597 |
+
|
| 598 |
+
df.astype(np.int8, errors="ignore")
|
| 599 |
+
|
| 600 |
+
def test_astype_invalid_conversion(self):
|
| 601 |
+
# GH#47571
|
| 602 |
+
df = DataFrame({"a": [1, 2, "text"], "b": [1, 2, 3]})
|
| 603 |
+
|
| 604 |
+
msg = (
|
| 605 |
+
"invalid literal for int() with base 10: 'text': "
|
| 606 |
+
"Error while type casting for column 'a'"
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
with pytest.raises(ValueError, match=re.escape(msg)):
|
| 610 |
+
df.astype({"a": int})
|
| 611 |
+
|
| 612 |
+
def test_astype_arg_for_errors_dictlist(self):
|
| 613 |
+
# GH#25905
|
| 614 |
+
df = DataFrame(
|
| 615 |
+
[
|
| 616 |
+
{"a": "1", "b": "16.5%", "c": "test"},
|
| 617 |
+
{"a": "2.2", "b": "15.3", "c": "another_test"},
|
| 618 |
+
]
|
| 619 |
+
)
|
| 620 |
+
expected = DataFrame(
|
| 621 |
+
[
|
| 622 |
+
{"a": 1.0, "b": "16.5%", "c": "test"},
|
| 623 |
+
{"a": 2.2, "b": "15.3", "c": "another_test"},
|
| 624 |
+
]
|
| 625 |
+
)
|
| 626 |
+
expected["c"] = expected["c"].astype("object")
|
| 627 |
+
type_dict = {"a": "float64", "b": "float64", "c": "object"}
|
| 628 |
+
|
| 629 |
+
result = df.astype(dtype=type_dict, errors="ignore")
|
| 630 |
+
|
| 631 |
+
tm.assert_frame_equal(result, expected)
|
| 632 |
+
|
| 633 |
+
def test_astype_dt64tz(self, timezone_frame):
|
| 634 |
+
# astype
|
| 635 |
+
expected = np.array(
|
| 636 |
+
[
|
| 637 |
+
[
|
| 638 |
+
Timestamp("2013-01-01 00:00:00"),
|
| 639 |
+
Timestamp("2013-01-02 00:00:00"),
|
| 640 |
+
Timestamp("2013-01-03 00:00:00"),
|
| 641 |
+
],
|
| 642 |
+
[
|
| 643 |
+
Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),
|
| 644 |
+
NaT,
|
| 645 |
+
Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),
|
| 646 |
+
],
|
| 647 |
+
[
|
| 648 |
+
Timestamp("2013-01-01 00:00:00+0100", tz="CET"),
|
| 649 |
+
NaT,
|
| 650 |
+
Timestamp("2013-01-03 00:00:00+0100", tz="CET"),
|
| 651 |
+
],
|
| 652 |
+
],
|
| 653 |
+
dtype=object,
|
| 654 |
+
).T
|
| 655 |
+
expected = DataFrame(
|
| 656 |
+
expected,
|
| 657 |
+
index=timezone_frame.index,
|
| 658 |
+
columns=timezone_frame.columns,
|
| 659 |
+
dtype=object,
|
| 660 |
+
)
|
| 661 |
+
result = timezone_frame.astype(object)
|
| 662 |
+
tm.assert_frame_equal(result, expected)
|
| 663 |
+
|
| 664 |
+
msg = "Cannot use .astype to convert from timezone-aware dtype to timezone-"
|
| 665 |
+
with pytest.raises(TypeError, match=msg):
|
| 666 |
+
# dt64tz->dt64 deprecated
|
| 667 |
+
timezone_frame.astype("datetime64[ns]")
|
| 668 |
+
|
| 669 |
+
def test_astype_dt64tz_to_str(self, timezone_frame, using_infer_string):
|
| 670 |
+
# str formatting
|
| 671 |
+
result = timezone_frame.astype(str)
|
| 672 |
+
na_value = np.nan if using_infer_string else "NaT"
|
| 673 |
+
expected = DataFrame(
|
| 674 |
+
[
|
| 675 |
+
[
|
| 676 |
+
"2013-01-01",
|
| 677 |
+
"2013-01-01 00:00:00-05:00",
|
| 678 |
+
"2013-01-01 00:00:00+01:00",
|
| 679 |
+
],
|
| 680 |
+
["2013-01-02", na_value, na_value],
|
| 681 |
+
[
|
| 682 |
+
"2013-01-03",
|
| 683 |
+
"2013-01-03 00:00:00-05:00",
|
| 684 |
+
"2013-01-03 00:00:00+01:00",
|
| 685 |
+
],
|
| 686 |
+
],
|
| 687 |
+
columns=timezone_frame.columns,
|
| 688 |
+
dtype="str",
|
| 689 |
+
)
|
| 690 |
+
tm.assert_frame_equal(result, expected)
|
| 691 |
+
|
| 692 |
+
with option_context("display.max_columns", 20):
|
| 693 |
+
result = str(timezone_frame)
|
| 694 |
+
assert (
|
| 695 |
+
"0 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00+01:00"
|
| 696 |
+
) in result
|
| 697 |
+
assert (
|
| 698 |
+
"1 2013-01-02 NaT NaT"
|
| 699 |
+
) in result
|
| 700 |
+
assert (
|
| 701 |
+
"2 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-03 00:00:00+01:00"
|
| 702 |
+
) in result
|
| 703 |
+
|
| 704 |
+
def test_astype_empty_dtype_dict(self):
|
| 705 |
+
# issue mentioned further down in the following issue's thread
|
| 706 |
+
# https://github.com/pandas-dev/pandas/issues/33113
|
| 707 |
+
df = DataFrame()
|
| 708 |
+
result = df.astype({})
|
| 709 |
+
tm.assert_frame_equal(result, df)
|
| 710 |
+
assert result is not df
|
| 711 |
+
|
| 712 |
+
@pytest.mark.parametrize(
|
| 713 |
+
"data, dtype",
|
| 714 |
+
[
|
| 715 |
+
(["x", "y", "z"], "string[python]"),
|
| 716 |
+
pytest.param(
|
| 717 |
+
["x", "y", "z"],
|
| 718 |
+
"string[pyarrow]",
|
| 719 |
+
marks=td.skip_if_no("pyarrow"),
|
| 720 |
+
),
|
| 721 |
+
(["x", "y", "z"], "category"),
|
| 722 |
+
(3 * [Timestamp("2020-01-01", tz="UTC")], None),
|
| 723 |
+
(3 * [Interval(0, 1)], None),
|
| 724 |
+
],
|
| 725 |
+
)
|
| 726 |
+
@pytest.mark.parametrize("errors", ["raise", "ignore"])
|
| 727 |
+
def test_astype_ignores_errors_for_extension_dtypes(self, data, dtype, errors):
|
| 728 |
+
# https://github.com/pandas-dev/pandas/issues/35471
|
| 729 |
+
df = DataFrame(Series(data, dtype=dtype))
|
| 730 |
+
if errors == "ignore":
|
| 731 |
+
expected = df
|
| 732 |
+
result = df.astype(float, errors=errors)
|
| 733 |
+
tm.assert_frame_equal(result, expected)
|
| 734 |
+
else:
|
| 735 |
+
msg = "(Cannot cast)|(could not convert)"
|
| 736 |
+
with pytest.raises((ValueError, TypeError), match=msg):
|
| 737 |
+
df.astype(float, errors=errors)
|
| 738 |
+
|
| 739 |
+
def test_astype_tz_conversion(self):
|
| 740 |
+
# GH 35973
|
| 741 |
+
val = {"tz": date_range("2020-08-30", freq="d", periods=2, tz="Europe/London")}
|
| 742 |
+
df = DataFrame(val)
|
| 743 |
+
result = df.astype({"tz": "datetime64[ns, Europe/Berlin]"})
|
| 744 |
+
|
| 745 |
+
expected = df
|
| 746 |
+
expected["tz"] = expected["tz"].dt.tz_convert("Europe/Berlin")
|
| 747 |
+
tm.assert_frame_equal(result, expected)
|
| 748 |
+
|
| 749 |
+
@pytest.mark.parametrize("tz", ["UTC", "Europe/Berlin"])
|
| 750 |
+
def test_astype_tz_object_conversion(self, tz):
|
| 751 |
+
# GH 35973
|
| 752 |
+
val = {"tz": date_range("2020-08-30", freq="d", periods=2, tz="Europe/London")}
|
| 753 |
+
expected = DataFrame(val)
|
| 754 |
+
|
| 755 |
+
# convert expected to object dtype from other tz str (independently tested)
|
| 756 |
+
result = expected.astype({"tz": f"datetime64[ns, {tz}]"})
|
| 757 |
+
result = result.astype({"tz": "object"})
|
| 758 |
+
|
| 759 |
+
# do real test: object dtype to a specified tz, different from construction tz.
|
| 760 |
+
result = result.astype({"tz": "datetime64[ns, Europe/London]"})
|
| 761 |
+
tm.assert_frame_equal(result, expected)
|
| 762 |
+
|
| 763 |
+
@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string) GH#60639")
|
| 764 |
+
def test_astype_dt64_to_string(
|
| 765 |
+
self, frame_or_series, tz_naive_fixture, using_infer_string
|
| 766 |
+
):
|
| 767 |
+
# GH#41409
|
| 768 |
+
tz = tz_naive_fixture
|
| 769 |
+
|
| 770 |
+
dti = date_range("2016-01-01", periods=3, tz=tz)
|
| 771 |
+
dta = dti._data
|
| 772 |
+
dta[0] = NaT
|
| 773 |
+
|
| 774 |
+
obj = frame_or_series(dta)
|
| 775 |
+
result = obj.astype("string")
|
| 776 |
+
|
| 777 |
+
# Check that Series/DataFrame.astype matches DatetimeArray.astype
|
| 778 |
+
expected = frame_or_series(dta.astype("string"))
|
| 779 |
+
tm.assert_equal(result, expected)
|
| 780 |
+
|
| 781 |
+
item = result.iloc[0]
|
| 782 |
+
if frame_or_series is DataFrame:
|
| 783 |
+
item = item.iloc[0]
|
| 784 |
+
if using_infer_string:
|
| 785 |
+
assert item is np.nan
|
| 786 |
+
else:
|
| 787 |
+
assert item is pd.NA
|
| 788 |
+
|
| 789 |
+
# For non-NA values, we should match what we get for non-EA str
|
| 790 |
+
alt = obj.astype(str)
|
| 791 |
+
assert np.all(alt.iloc[1:] == result.iloc[1:])
|
| 792 |
+
|
| 793 |
+
def test_astype_td64_to_string(self, frame_or_series):
|
| 794 |
+
# GH#41409
|
| 795 |
+
tdi = pd.timedelta_range("1 Day", periods=3)
|
| 796 |
+
obj = frame_or_series(tdi)
|
| 797 |
+
|
| 798 |
+
expected = frame_or_series(["1 days", "2 days", "3 days"], dtype="string")
|
| 799 |
+
result = obj.astype("string")
|
| 800 |
+
tm.assert_equal(result, expected)
|
| 801 |
+
|
| 802 |
+
def test_astype_bytes(self):
|
| 803 |
+
# GH#39474
|
| 804 |
+
result = DataFrame(["foo", "bar", "baz"]).astype(bytes)
|
| 805 |
+
assert result.dtypes[0] == np.dtype("S3")
|
| 806 |
+
|
| 807 |
+
@pytest.mark.parametrize(
|
| 808 |
+
"index_slice",
|
| 809 |
+
[
|
| 810 |
+
np.s_[:2, :2],
|
| 811 |
+
np.s_[:1, :2],
|
| 812 |
+
np.s_[:2, :1],
|
| 813 |
+
np.s_[::2, ::2],
|
| 814 |
+
np.s_[::1, ::2],
|
| 815 |
+
np.s_[::2, ::1],
|
| 816 |
+
],
|
| 817 |
+
)
|
| 818 |
+
def test_astype_noncontiguous(self, index_slice):
|
| 819 |
+
# GH#42396
|
| 820 |
+
data = np.arange(16).reshape(4, 4)
|
| 821 |
+
df = DataFrame(data)
|
| 822 |
+
|
| 823 |
+
result = df.iloc[index_slice].astype("int16")
|
| 824 |
+
expected = df.iloc[index_slice]
|
| 825 |
+
tm.assert_frame_equal(result, expected, check_dtype=False)
|
| 826 |
+
|
| 827 |
+
def test_astype_retain_attrs(self, any_numpy_dtype):
|
| 828 |
+
# GH#44414
|
| 829 |
+
df = DataFrame({"a": [0, 1, 2], "b": [3, 4, 5]})
|
| 830 |
+
df.attrs["Location"] = "Michigan"
|
| 831 |
+
|
| 832 |
+
result = df.astype({"a": any_numpy_dtype}).attrs
|
| 833 |
+
expected = df.attrs
|
| 834 |
+
|
| 835 |
+
tm.assert_dict_equal(expected, result)
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
class TestAstypeCategorical:
|
| 839 |
+
def test_astype_from_categorical3(self):
|
| 840 |
+
df = DataFrame({"cats": [1, 2, 3, 4, 5, 6], "vals": [1, 2, 3, 4, 5, 6]})
|
| 841 |
+
cats = Categorical([1, 2, 3, 4, 5, 6])
|
| 842 |
+
exp_df = DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]})
|
| 843 |
+
df["cats"] = df["cats"].astype("category")
|
| 844 |
+
tm.assert_frame_equal(exp_df, df)
|
| 845 |
+
|
| 846 |
+
def test_astype_from_categorical4(self):
|
| 847 |
+
df = DataFrame(
|
| 848 |
+
{"cats": ["a", "b", "b", "a", "a", "d"], "vals": [1, 2, 3, 4, 5, 6]}
|
| 849 |
+
)
|
| 850 |
+
cats = Categorical(["a", "b", "b", "a", "a", "d"])
|
| 851 |
+
exp_df = DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]})
|
| 852 |
+
df["cats"] = df["cats"].astype("category")
|
| 853 |
+
tm.assert_frame_equal(exp_df, df)
|
| 854 |
+
|
| 855 |
+
def test_categorical_astype_to_int(self, any_int_dtype):
|
| 856 |
+
# GH#39402
|
| 857 |
+
|
| 858 |
+
df = DataFrame(data={"col1": pd.array([2.0, 1.0, 3.0])})
|
| 859 |
+
df.col1 = df.col1.astype("category")
|
| 860 |
+
df.col1 = df.col1.astype(any_int_dtype)
|
| 861 |
+
expected = DataFrame({"col1": pd.array([2, 1, 3], dtype=any_int_dtype)})
|
| 862 |
+
tm.assert_frame_equal(df, expected)
|
| 863 |
+
|
| 864 |
+
def test_astype_categorical_to_string_missing(self):
|
| 865 |
+
# https://github.com/pandas-dev/pandas/issues/41797
|
| 866 |
+
df = DataFrame(["a", "b", np.nan])
|
| 867 |
+
expected = df.astype(str)
|
| 868 |
+
cat = df.astype("category")
|
| 869 |
+
result = cat.astype(str)
|
| 870 |
+
tm.assert_frame_equal(result, expected)
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
class IntegerArrayNoCopy(pd.core.arrays.IntegerArray):
|
| 874 |
+
# GH 42501
|
| 875 |
+
|
| 876 |
+
def copy(self):
|
| 877 |
+
assert False
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
class Int16DtypeNoCopy(pd.Int16Dtype):
|
| 881 |
+
# GH 42501
|
| 882 |
+
|
| 883 |
+
@classmethod
|
| 884 |
+
def construct_array_type(cls):
|
| 885 |
+
return IntegerArrayNoCopy
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
def test_frame_astype_no_copy():
|
| 889 |
+
# GH 42501
|
| 890 |
+
df = DataFrame({"a": [1, 4, None, 5], "b": [6, 7, 8, 9]}, dtype=object)
|
| 891 |
+
result = df.astype({"a": Int16DtypeNoCopy()}, copy=False)
|
| 892 |
+
|
| 893 |
+
assert result.a.dtype == pd.Int16Dtype()
|
| 894 |
+
assert np.shares_memory(df.b.values, result.b.values)
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
@pytest.mark.parametrize("dtype", ["int64", "Int64"])
|
| 898 |
+
def test_astype_copies(dtype):
|
| 899 |
+
# GH#50984
|
| 900 |
+
pytest.importorskip("pyarrow")
|
| 901 |
+
df = DataFrame({"a": [1, 2, 3]}, dtype=dtype)
|
| 902 |
+
result = df.astype("int64[pyarrow]", copy=True)
|
| 903 |
+
df.iloc[0, 0] = 100
|
| 904 |
+
expected = DataFrame({"a": [1, 2, 3]}, dtype="int64[pyarrow]")
|
| 905 |
+
tm.assert_frame_equal(result, expected)
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
@pytest.mark.parametrize("val", [None, 1, 1.5, np.nan, NaT])
|
| 909 |
+
def test_astype_to_string_not_modifying_input(string_storage, val):
|
| 910 |
+
# GH#51073
|
| 911 |
+
df = DataFrame({"a": ["a", "b", val]})
|
| 912 |
+
expected = df.copy()
|
| 913 |
+
with option_context("mode.string_storage", string_storage):
|
| 914 |
+
df.astype("string", copy=False)
|
| 915 |
+
tm.assert_frame_equal(df, expected)
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
@pytest.mark.parametrize("val", [None, 1, 1.5, np.nan, NaT])
|
| 919 |
+
def test_astype_to_string_dtype_not_modifying_input(any_string_dtype, val):
|
| 920 |
+
# GH#51073 - variant of the above test with explicit dtype instances
|
| 921 |
+
df = DataFrame({"a": ["a", "b", val]})
|
| 922 |
+
expected = df.copy()
|
| 923 |
+
df.astype(any_string_dtype)
|
| 924 |
+
tm.assert_frame_equal(df, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_at_time.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import time
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
import pytz
|
| 6 |
+
|
| 7 |
+
from pandas._libs.tslibs import timezones
|
| 8 |
+
|
| 9 |
+
from pandas import (
|
| 10 |
+
DataFrame,
|
| 11 |
+
date_range,
|
| 12 |
+
)
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestAtTime:
|
| 17 |
+
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
|
| 18 |
+
def test_localized_at_time(self, tzstr, frame_or_series):
|
| 19 |
+
tz = timezones.maybe_get_tz(tzstr)
|
| 20 |
+
|
| 21 |
+
rng = date_range("4/16/2012", "5/1/2012", freq="h")
|
| 22 |
+
ts = frame_or_series(
|
| 23 |
+
np.random.default_rng(2).standard_normal(len(rng)), index=rng
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
ts_local = ts.tz_localize(tzstr)
|
| 27 |
+
|
| 28 |
+
result = ts_local.at_time(time(10, 0))
|
| 29 |
+
expected = ts.at_time(time(10, 0)).tz_localize(tzstr)
|
| 30 |
+
tm.assert_equal(result, expected)
|
| 31 |
+
assert timezones.tz_compare(result.index.tz, tz)
|
| 32 |
+
|
| 33 |
+
def test_at_time(self, frame_or_series):
|
| 34 |
+
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
|
| 35 |
+
ts = DataFrame(
|
| 36 |
+
np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng
|
| 37 |
+
)
|
| 38 |
+
ts = tm.get_obj(ts, frame_or_series)
|
| 39 |
+
rs = ts.at_time(rng[1])
|
| 40 |
+
assert (rs.index.hour == rng[1].hour).all()
|
| 41 |
+
assert (rs.index.minute == rng[1].minute).all()
|
| 42 |
+
assert (rs.index.second == rng[1].second).all()
|
| 43 |
+
|
| 44 |
+
result = ts.at_time("9:30")
|
| 45 |
+
expected = ts.at_time(time(9, 30))
|
| 46 |
+
tm.assert_equal(result, expected)
|
| 47 |
+
|
| 48 |
+
def test_at_time_midnight(self, frame_or_series):
|
| 49 |
+
# midnight, everything
|
| 50 |
+
rng = date_range("1/1/2000", "1/31/2000")
|
| 51 |
+
ts = DataFrame(
|
| 52 |
+
np.random.default_rng(2).standard_normal((len(rng), 3)), index=rng
|
| 53 |
+
)
|
| 54 |
+
ts = tm.get_obj(ts, frame_or_series)
|
| 55 |
+
|
| 56 |
+
result = ts.at_time(time(0, 0))
|
| 57 |
+
tm.assert_equal(result, ts)
|
| 58 |
+
|
| 59 |
+
def test_at_time_nonexistent(self, frame_or_series):
|
| 60 |
+
# time doesn't exist
|
| 61 |
+
rng = date_range("1/1/2012", freq="23Min", periods=384)
|
| 62 |
+
ts = DataFrame(np.random.default_rng(2).standard_normal(len(rng)), rng)
|
| 63 |
+
ts = tm.get_obj(ts, frame_or_series)
|
| 64 |
+
rs = ts.at_time("16:00")
|
| 65 |
+
assert len(rs) == 0
|
| 66 |
+
|
| 67 |
+
@pytest.mark.parametrize(
|
| 68 |
+
"hour", ["1:00", "1:00AM", time(1), time(1, tzinfo=pytz.UTC)]
|
| 69 |
+
)
|
| 70 |
+
def test_at_time_errors(self, hour):
|
| 71 |
+
# GH#24043
|
| 72 |
+
dti = date_range("2018", periods=3, freq="h")
|
| 73 |
+
df = DataFrame(list(range(len(dti))), index=dti)
|
| 74 |
+
if getattr(hour, "tzinfo", None) is None:
|
| 75 |
+
result = df.at_time(hour)
|
| 76 |
+
expected = df.iloc[1:2]
|
| 77 |
+
tm.assert_frame_equal(result, expected)
|
| 78 |
+
else:
|
| 79 |
+
with pytest.raises(ValueError, match="Index must be timezone"):
|
| 80 |
+
df.at_time(hour)
|
| 81 |
+
|
| 82 |
+
def test_at_time_tz(self):
|
| 83 |
+
# GH#24043
|
| 84 |
+
dti = date_range("2018", periods=3, freq="h", tz="US/Pacific")
|
| 85 |
+
df = DataFrame(list(range(len(dti))), index=dti)
|
| 86 |
+
result = df.at_time(time(4, tzinfo=pytz.timezone("US/Eastern")))
|
| 87 |
+
expected = df.iloc[1:2]
|
| 88 |
+
tm.assert_frame_equal(result, expected)
|
| 89 |
+
|
| 90 |
+
def test_at_time_raises(self, frame_or_series):
|
| 91 |
+
# GH#20725
|
| 92 |
+
obj = DataFrame([[1, 2, 3], [4, 5, 6]])
|
| 93 |
+
obj = tm.get_obj(obj, frame_or_series)
|
| 94 |
+
msg = "Index must be DatetimeIndex"
|
| 95 |
+
with pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex
|
| 96 |
+
obj.at_time("00:00")
|
| 97 |
+
|
| 98 |
+
@pytest.mark.parametrize("axis", ["index", "columns", 0, 1])
|
| 99 |
+
def test_at_time_axis(self, axis):
|
| 100 |
+
# issue 8839
|
| 101 |
+
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
|
| 102 |
+
ts = DataFrame(np.random.default_rng(2).standard_normal((len(rng), len(rng))))
|
| 103 |
+
ts.index, ts.columns = rng, rng
|
| 104 |
+
|
| 105 |
+
indices = rng[(rng.hour == 9) & (rng.minute == 30) & (rng.second == 0)]
|
| 106 |
+
|
| 107 |
+
if axis in ["index", 0]:
|
| 108 |
+
expected = ts.loc[indices, :]
|
| 109 |
+
elif axis in ["columns", 1]:
|
| 110 |
+
expected = ts.loc[:, indices]
|
| 111 |
+
|
| 112 |
+
result = ts.at_time("9:30", axis=axis)
|
| 113 |
+
|
| 114 |
+
# Without clearing freq, result has freq 1440T and expected 5T
|
| 115 |
+
result.index = result.index._with_freq(None)
|
| 116 |
+
expected.index = expected.index._with_freq(None)
|
| 117 |
+
tm.assert_frame_equal(result, expected)
|
| 118 |
+
|
| 119 |
+
def test_at_time_datetimeindex(self):
|
| 120 |
+
index = date_range("2012-01-01", "2012-01-05", freq="30min")
|
| 121 |
+
df = DataFrame(
|
| 122 |
+
np.random.default_rng(2).standard_normal((len(index), 5)), index=index
|
| 123 |
+
)
|
| 124 |
+
akey = time(12, 0, 0)
|
| 125 |
+
ainds = [24, 72, 120, 168]
|
| 126 |
+
|
| 127 |
+
result = df.at_time(akey)
|
| 128 |
+
expected = df.loc[akey]
|
| 129 |
+
expected2 = df.iloc[ainds]
|
| 130 |
+
tm.assert_frame_equal(result, expected)
|
| 131 |
+
tm.assert_frame_equal(result, expected2)
|
| 132 |
+
assert len(result) == 4
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_between_time.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import (
|
| 2 |
+
datetime,
|
| 3 |
+
time,
|
| 4 |
+
)
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from pandas._libs.tslibs import timezones
|
| 10 |
+
import pandas.util._test_decorators as td
|
| 11 |
+
|
| 12 |
+
from pandas import (
|
| 13 |
+
DataFrame,
|
| 14 |
+
Series,
|
| 15 |
+
date_range,
|
| 16 |
+
)
|
| 17 |
+
import pandas._testing as tm
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class TestBetweenTime:
|
| 21 |
+
@td.skip_if_not_us_locale
|
| 22 |
+
def test_between_time_formats(self, frame_or_series):
|
| 23 |
+
# GH#11818
|
| 24 |
+
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
|
| 25 |
+
ts = DataFrame(
|
| 26 |
+
np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng
|
| 27 |
+
)
|
| 28 |
+
ts = tm.get_obj(ts, frame_or_series)
|
| 29 |
+
|
| 30 |
+
strings = [
|
| 31 |
+
("2:00", "2:30"),
|
| 32 |
+
("0200", "0230"),
|
| 33 |
+
("2:00am", "2:30am"),
|
| 34 |
+
("0200am", "0230am"),
|
| 35 |
+
("2:00:00", "2:30:00"),
|
| 36 |
+
("020000", "023000"),
|
| 37 |
+
("2:00:00am", "2:30:00am"),
|
| 38 |
+
("020000am", "023000am"),
|
| 39 |
+
]
|
| 40 |
+
expected_length = 28
|
| 41 |
+
|
| 42 |
+
for time_string in strings:
|
| 43 |
+
assert len(ts.between_time(*time_string)) == expected_length
|
| 44 |
+
|
| 45 |
+
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
|
| 46 |
+
def test_localized_between_time(self, tzstr, frame_or_series):
|
| 47 |
+
tz = timezones.maybe_get_tz(tzstr)
|
| 48 |
+
|
| 49 |
+
rng = date_range("4/16/2012", "5/1/2012", freq="h")
|
| 50 |
+
ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
|
| 51 |
+
if frame_or_series is DataFrame:
|
| 52 |
+
ts = ts.to_frame()
|
| 53 |
+
|
| 54 |
+
ts_local = ts.tz_localize(tzstr)
|
| 55 |
+
|
| 56 |
+
t1, t2 = time(10, 0), time(11, 0)
|
| 57 |
+
result = ts_local.between_time(t1, t2)
|
| 58 |
+
expected = ts.between_time(t1, t2).tz_localize(tzstr)
|
| 59 |
+
tm.assert_equal(result, expected)
|
| 60 |
+
assert timezones.tz_compare(result.index.tz, tz)
|
| 61 |
+
|
| 62 |
+
def test_between_time_types(self, frame_or_series):
|
| 63 |
+
# GH11818
|
| 64 |
+
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
|
| 65 |
+
obj = DataFrame({"A": 0}, index=rng)
|
| 66 |
+
obj = tm.get_obj(obj, frame_or_series)
|
| 67 |
+
|
| 68 |
+
msg = r"Cannot convert arg \[datetime\.datetime\(2010, 1, 2, 1, 0\)\] to a time"
|
| 69 |
+
with pytest.raises(ValueError, match=msg):
|
| 70 |
+
obj.between_time(datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5))
|
| 71 |
+
|
| 72 |
+
def test_between_time(self, inclusive_endpoints_fixture, frame_or_series):
|
| 73 |
+
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
|
| 74 |
+
ts = DataFrame(
|
| 75 |
+
np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng
|
| 76 |
+
)
|
| 77 |
+
ts = tm.get_obj(ts, frame_or_series)
|
| 78 |
+
|
| 79 |
+
stime = time(0, 0)
|
| 80 |
+
etime = time(1, 0)
|
| 81 |
+
inclusive = inclusive_endpoints_fixture
|
| 82 |
+
|
| 83 |
+
filtered = ts.between_time(stime, etime, inclusive=inclusive)
|
| 84 |
+
exp_len = 13 * 4 + 1
|
| 85 |
+
|
| 86 |
+
if inclusive in ["right", "neither"]:
|
| 87 |
+
exp_len -= 5
|
| 88 |
+
if inclusive in ["left", "neither"]:
|
| 89 |
+
exp_len -= 4
|
| 90 |
+
|
| 91 |
+
assert len(filtered) == exp_len
|
| 92 |
+
for rs in filtered.index:
|
| 93 |
+
t = rs.time()
|
| 94 |
+
if inclusive in ["left", "both"]:
|
| 95 |
+
assert t >= stime
|
| 96 |
+
else:
|
| 97 |
+
assert t > stime
|
| 98 |
+
|
| 99 |
+
if inclusive in ["right", "both"]:
|
| 100 |
+
assert t <= etime
|
| 101 |
+
else:
|
| 102 |
+
assert t < etime
|
| 103 |
+
|
| 104 |
+
result = ts.between_time("00:00", "01:00")
|
| 105 |
+
expected = ts.between_time(stime, etime)
|
| 106 |
+
tm.assert_equal(result, expected)
|
| 107 |
+
|
| 108 |
+
# across midnight
|
| 109 |
+
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
|
| 110 |
+
ts = DataFrame(
|
| 111 |
+
np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng
|
| 112 |
+
)
|
| 113 |
+
ts = tm.get_obj(ts, frame_or_series)
|
| 114 |
+
stime = time(22, 0)
|
| 115 |
+
etime = time(9, 0)
|
| 116 |
+
|
| 117 |
+
filtered = ts.between_time(stime, etime, inclusive=inclusive)
|
| 118 |
+
exp_len = (12 * 11 + 1) * 4 + 1
|
| 119 |
+
if inclusive in ["right", "neither"]:
|
| 120 |
+
exp_len -= 4
|
| 121 |
+
if inclusive in ["left", "neither"]:
|
| 122 |
+
exp_len -= 4
|
| 123 |
+
|
| 124 |
+
assert len(filtered) == exp_len
|
| 125 |
+
for rs in filtered.index:
|
| 126 |
+
t = rs.time()
|
| 127 |
+
if inclusive in ["left", "both"]:
|
| 128 |
+
assert (t >= stime) or (t <= etime)
|
| 129 |
+
else:
|
| 130 |
+
assert (t > stime) or (t <= etime)
|
| 131 |
+
|
| 132 |
+
if inclusive in ["right", "both"]:
|
| 133 |
+
assert (t <= etime) or (t >= stime)
|
| 134 |
+
else:
|
| 135 |
+
assert (t < etime) or (t >= stime)
|
| 136 |
+
|
| 137 |
+
def test_between_time_raises(self, frame_or_series):
|
| 138 |
+
# GH#20725
|
| 139 |
+
obj = DataFrame([[1, 2, 3], [4, 5, 6]])
|
| 140 |
+
obj = tm.get_obj(obj, frame_or_series)
|
| 141 |
+
|
| 142 |
+
msg = "Index must be DatetimeIndex"
|
| 143 |
+
with pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex
|
| 144 |
+
obj.between_time(start_time="00:00", end_time="12:00")
|
| 145 |
+
|
| 146 |
+
def test_between_time_axis(self, frame_or_series):
|
| 147 |
+
# GH#8839
|
| 148 |
+
rng = date_range("1/1/2000", periods=100, freq="10min")
|
| 149 |
+
ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)
|
| 150 |
+
if frame_or_series is DataFrame:
|
| 151 |
+
ts = ts.to_frame()
|
| 152 |
+
|
| 153 |
+
stime, etime = ("08:00:00", "09:00:00")
|
| 154 |
+
expected_length = 7
|
| 155 |
+
|
| 156 |
+
assert len(ts.between_time(stime, etime)) == expected_length
|
| 157 |
+
assert len(ts.between_time(stime, etime, axis=0)) == expected_length
|
| 158 |
+
msg = f"No axis named {ts.ndim} for object type {type(ts).__name__}"
|
| 159 |
+
with pytest.raises(ValueError, match=msg):
|
| 160 |
+
ts.between_time(stime, etime, axis=ts.ndim)
|
| 161 |
+
|
| 162 |
+
def test_between_time_axis_aliases(self, axis):
|
| 163 |
+
# GH#8839
|
| 164 |
+
rng = date_range("1/1/2000", periods=100, freq="10min")
|
| 165 |
+
ts = DataFrame(np.random.default_rng(2).standard_normal((len(rng), len(rng))))
|
| 166 |
+
stime, etime = ("08:00:00", "09:00:00")
|
| 167 |
+
exp_len = 7
|
| 168 |
+
|
| 169 |
+
if axis in ["index", 0]:
|
| 170 |
+
ts.index = rng
|
| 171 |
+
assert len(ts.between_time(stime, etime)) == exp_len
|
| 172 |
+
assert len(ts.between_time(stime, etime, axis=0)) == exp_len
|
| 173 |
+
|
| 174 |
+
if axis in ["columns", 1]:
|
| 175 |
+
ts.columns = rng
|
| 176 |
+
selected = ts.between_time(stime, etime, axis=1).columns
|
| 177 |
+
assert len(selected) == exp_len
|
| 178 |
+
|
| 179 |
+
def test_between_time_axis_raises(self, axis):
|
| 180 |
+
# issue 8839
|
| 181 |
+
rng = date_range("1/1/2000", periods=100, freq="10min")
|
| 182 |
+
mask = np.arange(0, len(rng))
|
| 183 |
+
rand_data = np.random.default_rng(2).standard_normal((len(rng), len(rng)))
|
| 184 |
+
ts = DataFrame(rand_data, index=rng, columns=rng)
|
| 185 |
+
stime, etime = ("08:00:00", "09:00:00")
|
| 186 |
+
|
| 187 |
+
msg = "Index must be DatetimeIndex"
|
| 188 |
+
if axis in ["columns", 1]:
|
| 189 |
+
ts.index = mask
|
| 190 |
+
with pytest.raises(TypeError, match=msg):
|
| 191 |
+
ts.between_time(stime, etime)
|
| 192 |
+
with pytest.raises(TypeError, match=msg):
|
| 193 |
+
ts.between_time(stime, etime, axis=0)
|
| 194 |
+
|
| 195 |
+
if axis in ["index", 0]:
|
| 196 |
+
ts.columns = mask
|
| 197 |
+
with pytest.raises(TypeError, match=msg):
|
| 198 |
+
ts.between_time(stime, etime, axis=1)
|
| 199 |
+
|
| 200 |
+
def test_between_time_datetimeindex(self):
|
| 201 |
+
index = date_range("2012-01-01", "2012-01-05", freq="30min")
|
| 202 |
+
df = DataFrame(
|
| 203 |
+
np.random.default_rng(2).standard_normal((len(index), 5)), index=index
|
| 204 |
+
)
|
| 205 |
+
bkey = slice(time(13, 0, 0), time(14, 0, 0))
|
| 206 |
+
binds = [26, 27, 28, 74, 75, 76, 122, 123, 124, 170, 171, 172]
|
| 207 |
+
|
| 208 |
+
result = df.between_time(bkey.start, bkey.stop)
|
| 209 |
+
expected = df.loc[bkey]
|
| 210 |
+
expected2 = df.iloc[binds]
|
| 211 |
+
tm.assert_frame_equal(result, expected)
|
| 212 |
+
tm.assert_frame_equal(result, expected2)
|
| 213 |
+
assert len(result) == 12
|
| 214 |
+
|
| 215 |
+
def test_between_time_incorrect_arg_inclusive(self):
|
| 216 |
+
# GH40245
|
| 217 |
+
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
|
| 218 |
+
ts = DataFrame(
|
| 219 |
+
np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
stime = time(0, 0)
|
| 223 |
+
etime = time(1, 0)
|
| 224 |
+
inclusive = "bad_string"
|
| 225 |
+
msg = "Inclusive has to be either 'both', 'neither', 'left' or 'right'"
|
| 226 |
+
with pytest.raises(ValueError, match=msg):
|
| 227 |
+
ts.between_time(stime, etime, inclusive=inclusive)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_clip.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
class TestDataFrameClip:
|
| 12 |
+
def test_clip(self, float_frame):
|
| 13 |
+
median = float_frame.median().median()
|
| 14 |
+
original = float_frame.copy()
|
| 15 |
+
|
| 16 |
+
double = float_frame.clip(upper=median, lower=median)
|
| 17 |
+
assert not (double.values != median).any()
|
| 18 |
+
|
| 19 |
+
# Verify that float_frame was not changed inplace
|
| 20 |
+
assert (float_frame.values == original.values).all()
|
| 21 |
+
|
| 22 |
+
def test_inplace_clip(self, float_frame):
|
| 23 |
+
# GH#15388
|
| 24 |
+
median = float_frame.median().median()
|
| 25 |
+
frame_copy = float_frame.copy()
|
| 26 |
+
|
| 27 |
+
return_value = frame_copy.clip(upper=median, lower=median, inplace=True)
|
| 28 |
+
assert return_value is None
|
| 29 |
+
assert not (frame_copy.values != median).any()
|
| 30 |
+
|
| 31 |
+
def test_dataframe_clip(self):
|
| 32 |
+
# GH#2747
|
| 33 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((1000, 2)))
|
| 34 |
+
|
| 35 |
+
for lb, ub in [(-1, 1), (1, -1)]:
|
| 36 |
+
clipped_df = df.clip(lb, ub)
|
| 37 |
+
|
| 38 |
+
lb, ub = min(lb, ub), max(ub, lb)
|
| 39 |
+
lb_mask = df.values <= lb
|
| 40 |
+
ub_mask = df.values >= ub
|
| 41 |
+
mask = ~lb_mask & ~ub_mask
|
| 42 |
+
assert (clipped_df.values[lb_mask] == lb).all()
|
| 43 |
+
assert (clipped_df.values[ub_mask] == ub).all()
|
| 44 |
+
assert (clipped_df.values[mask] == df.values[mask]).all()
|
| 45 |
+
|
| 46 |
+
def test_clip_mixed_numeric(self):
|
| 47 |
+
# clip on mixed integer or floats
|
| 48 |
+
# GH#24162, clipping now preserves numeric types per column
|
| 49 |
+
df = DataFrame({"A": [1, 2, 3], "B": [1.0, np.nan, 3.0]})
|
| 50 |
+
result = df.clip(1, 2)
|
| 51 |
+
expected = DataFrame({"A": [1, 2, 2], "B": [1.0, np.nan, 2.0]})
|
| 52 |
+
tm.assert_frame_equal(result, expected)
|
| 53 |
+
|
| 54 |
+
df = DataFrame([[1, 2, 3.4], [3, 4, 5.6]], columns=["foo", "bar", "baz"])
|
| 55 |
+
expected = df.dtypes
|
| 56 |
+
result = df.clip(upper=3).dtypes
|
| 57 |
+
tm.assert_series_equal(result, expected)
|
| 58 |
+
|
| 59 |
+
@pytest.mark.parametrize("inplace", [True, False])
|
| 60 |
+
def test_clip_against_series(self, inplace):
|
| 61 |
+
# GH#6966
|
| 62 |
+
|
| 63 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((1000, 2)))
|
| 64 |
+
lb = Series(np.random.default_rng(2).standard_normal(1000))
|
| 65 |
+
ub = lb + 1
|
| 66 |
+
|
| 67 |
+
original = df.copy()
|
| 68 |
+
clipped_df = df.clip(lb, ub, axis=0, inplace=inplace)
|
| 69 |
+
|
| 70 |
+
if inplace:
|
| 71 |
+
clipped_df = df
|
| 72 |
+
|
| 73 |
+
for i in range(2):
|
| 74 |
+
lb_mask = original.iloc[:, i] <= lb
|
| 75 |
+
ub_mask = original.iloc[:, i] >= ub
|
| 76 |
+
mask = ~lb_mask & ~ub_mask
|
| 77 |
+
|
| 78 |
+
result = clipped_df.loc[lb_mask, i]
|
| 79 |
+
tm.assert_series_equal(result, lb[lb_mask], check_names=False)
|
| 80 |
+
assert result.name == i
|
| 81 |
+
|
| 82 |
+
result = clipped_df.loc[ub_mask, i]
|
| 83 |
+
tm.assert_series_equal(result, ub[ub_mask], check_names=False)
|
| 84 |
+
assert result.name == i
|
| 85 |
+
|
| 86 |
+
tm.assert_series_equal(clipped_df.loc[mask, i], df.loc[mask, i])
|
| 87 |
+
|
| 88 |
+
@pytest.mark.parametrize("inplace", [True, False])
|
| 89 |
+
@pytest.mark.parametrize("lower", [[2, 3, 4], np.asarray([2, 3, 4])])
|
| 90 |
+
@pytest.mark.parametrize(
|
| 91 |
+
"axis,res",
|
| 92 |
+
[
|
| 93 |
+
(0, [[2.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 7.0, 7.0]]),
|
| 94 |
+
(1, [[2.0, 3.0, 4.0], [4.0, 5.0, 6.0], [5.0, 6.0, 7.0]]),
|
| 95 |
+
],
|
| 96 |
+
)
|
| 97 |
+
def test_clip_against_list_like(self, inplace, lower, axis, res):
|
| 98 |
+
# GH#15390
|
| 99 |
+
arr = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
|
| 100 |
+
|
| 101 |
+
original = DataFrame(
|
| 102 |
+
arr, columns=["one", "two", "three"], index=["a", "b", "c"]
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
result = original.clip(lower=lower, upper=[5, 6, 7], axis=axis, inplace=inplace)
|
| 106 |
+
|
| 107 |
+
expected = DataFrame(res, columns=original.columns, index=original.index)
|
| 108 |
+
if inplace:
|
| 109 |
+
result = original
|
| 110 |
+
tm.assert_frame_equal(result, expected, check_exact=True)
|
| 111 |
+
|
| 112 |
+
@pytest.mark.parametrize("axis", [0, 1, None])
|
| 113 |
+
def test_clip_against_frame(self, axis):
|
| 114 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((1000, 2)))
|
| 115 |
+
lb = DataFrame(np.random.default_rng(2).standard_normal((1000, 2)))
|
| 116 |
+
ub = lb + 1
|
| 117 |
+
|
| 118 |
+
clipped_df = df.clip(lb, ub, axis=axis)
|
| 119 |
+
|
| 120 |
+
lb_mask = df <= lb
|
| 121 |
+
ub_mask = df >= ub
|
| 122 |
+
mask = ~lb_mask & ~ub_mask
|
| 123 |
+
|
| 124 |
+
tm.assert_frame_equal(clipped_df[lb_mask], lb[lb_mask])
|
| 125 |
+
tm.assert_frame_equal(clipped_df[ub_mask], ub[ub_mask])
|
| 126 |
+
tm.assert_frame_equal(clipped_df[mask], df[mask])
|
| 127 |
+
|
| 128 |
+
def test_clip_against_unordered_columns(self):
|
| 129 |
+
# GH#20911
|
| 130 |
+
df1 = DataFrame(
|
| 131 |
+
np.random.default_rng(2).standard_normal((1000, 4)),
|
| 132 |
+
columns=["A", "B", "C", "D"],
|
| 133 |
+
)
|
| 134 |
+
df2 = DataFrame(
|
| 135 |
+
np.random.default_rng(2).standard_normal((1000, 4)),
|
| 136 |
+
columns=["D", "A", "B", "C"],
|
| 137 |
+
)
|
| 138 |
+
df3 = DataFrame(df2.values - 1, columns=["B", "D", "C", "A"])
|
| 139 |
+
result_upper = df1.clip(lower=0, upper=df2)
|
| 140 |
+
expected_upper = df1.clip(lower=0, upper=df2[df1.columns])
|
| 141 |
+
result_lower = df1.clip(lower=df3, upper=3)
|
| 142 |
+
expected_lower = df1.clip(lower=df3[df1.columns], upper=3)
|
| 143 |
+
result_lower_upper = df1.clip(lower=df3, upper=df2)
|
| 144 |
+
expected_lower_upper = df1.clip(lower=df3[df1.columns], upper=df2[df1.columns])
|
| 145 |
+
tm.assert_frame_equal(result_upper, expected_upper)
|
| 146 |
+
tm.assert_frame_equal(result_lower, expected_lower)
|
| 147 |
+
tm.assert_frame_equal(result_lower_upper, expected_lower_upper)
|
| 148 |
+
|
| 149 |
+
def test_clip_with_na_args(self, float_frame):
|
| 150 |
+
"""Should process np.nan argument as None"""
|
| 151 |
+
# GH#17276
|
| 152 |
+
tm.assert_frame_equal(float_frame.clip(np.nan), float_frame)
|
| 153 |
+
tm.assert_frame_equal(float_frame.clip(upper=np.nan, lower=np.nan), float_frame)
|
| 154 |
+
|
| 155 |
+
# GH#19992 and adjusted in GH#40420
|
| 156 |
+
df = DataFrame({"col_0": [1, 2, 3], "col_1": [4, 5, 6], "col_2": [7, 8, 9]})
|
| 157 |
+
|
| 158 |
+
msg = "Downcasting behavior in Series and DataFrame methods 'where'"
|
| 159 |
+
# TODO: avoid this warning here? seems like we should never be upcasting
|
| 160 |
+
# in the first place?
|
| 161 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 162 |
+
result = df.clip(lower=[4, 5, np.nan], axis=0)
|
| 163 |
+
expected = DataFrame(
|
| 164 |
+
{"col_0": [4, 5, 3], "col_1": [4, 5, 6], "col_2": [7, 8, 9]}
|
| 165 |
+
)
|
| 166 |
+
tm.assert_frame_equal(result, expected)
|
| 167 |
+
|
| 168 |
+
result = df.clip(lower=[4, 5, np.nan], axis=1)
|
| 169 |
+
expected = DataFrame(
|
| 170 |
+
{"col_0": [4, 4, 4], "col_1": [5, 5, 6], "col_2": [7, 8, 9]}
|
| 171 |
+
)
|
| 172 |
+
tm.assert_frame_equal(result, expected)
|
| 173 |
+
|
| 174 |
+
# GH#40420
|
| 175 |
+
data = {"col_0": [9, -3, 0, -1, 5], "col_1": [-2, -7, 6, 8, -5]}
|
| 176 |
+
df = DataFrame(data)
|
| 177 |
+
t = Series([2, -4, np.nan, 6, 3])
|
| 178 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 179 |
+
result = df.clip(lower=t, axis=0)
|
| 180 |
+
expected = DataFrame({"col_0": [9, -3, 0, 6, 5], "col_1": [2, -4, 6, 8, 3]})
|
| 181 |
+
tm.assert_frame_equal(result, expected)
|
| 182 |
+
|
| 183 |
+
def test_clip_int_data_with_float_bound(self):
|
| 184 |
+
# GH51472
|
| 185 |
+
df = DataFrame({"a": [1, 2, 3]})
|
| 186 |
+
result = df.clip(lower=1.5)
|
| 187 |
+
expected = DataFrame({"a": [1.5, 2.0, 3.0]})
|
| 188 |
+
tm.assert_frame_equal(result, expected)
|
| 189 |
+
|
| 190 |
+
def test_clip_with_list_bound(self):
|
| 191 |
+
# GH#54817
|
| 192 |
+
df = DataFrame([1, 5])
|
| 193 |
+
expected = DataFrame([3, 5])
|
| 194 |
+
result = df.clip([3])
|
| 195 |
+
tm.assert_frame_equal(result, expected)
|
| 196 |
+
|
| 197 |
+
expected = DataFrame([1, 3])
|
| 198 |
+
result = df.clip(upper=[3])
|
| 199 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_combine.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestCombine:
|
| 9 |
+
@pytest.mark.parametrize(
|
| 10 |
+
"data",
|
| 11 |
+
[
|
| 12 |
+
pd.date_range("2000", periods=4),
|
| 13 |
+
pd.date_range("2000", periods=4, tz="US/Central"),
|
| 14 |
+
pd.period_range("2000", periods=4),
|
| 15 |
+
pd.timedelta_range(0, periods=4),
|
| 16 |
+
],
|
| 17 |
+
)
|
| 18 |
+
def test_combine_datetlike_udf(self, data):
|
| 19 |
+
# GH#23079
|
| 20 |
+
df = pd.DataFrame({"A": data})
|
| 21 |
+
other = df.copy()
|
| 22 |
+
df.iloc[1, 0] = None
|
| 23 |
+
|
| 24 |
+
def combiner(a, b):
|
| 25 |
+
return b
|
| 26 |
+
|
| 27 |
+
result = df.combine(other, combiner)
|
| 28 |
+
tm.assert_frame_equal(result, other)
|
| 29 |
+
|
| 30 |
+
def test_combine_generic(self, float_frame):
|
| 31 |
+
df1 = float_frame
|
| 32 |
+
df2 = float_frame.loc[float_frame.index[:-5], ["A", "B", "C"]]
|
| 33 |
+
|
| 34 |
+
combined = df1.combine(df2, np.add)
|
| 35 |
+
combined2 = df2.combine(df1, np.add)
|
| 36 |
+
assert combined["D"].isna().all()
|
| 37 |
+
assert combined2["D"].isna().all()
|
| 38 |
+
|
| 39 |
+
chunk = combined.loc[combined.index[:-5], ["A", "B", "C"]]
|
| 40 |
+
chunk2 = combined2.loc[combined2.index[:-5], ["A", "B", "C"]]
|
| 41 |
+
|
| 42 |
+
exp = (
|
| 43 |
+
float_frame.loc[float_frame.index[:-5], ["A", "B", "C"]].reindex_like(chunk)
|
| 44 |
+
* 2
|
| 45 |
+
)
|
| 46 |
+
tm.assert_frame_equal(chunk, exp)
|
| 47 |
+
tm.assert_frame_equal(chunk2, exp)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_combine_first.py
ADDED
|
@@ -0,0 +1,556 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas.core.dtypes.cast import find_common_type
|
| 7 |
+
from pandas.core.dtypes.common import is_dtype_equal
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from pandas import (
|
| 11 |
+
DataFrame,
|
| 12 |
+
Index,
|
| 13 |
+
MultiIndex,
|
| 14 |
+
Series,
|
| 15 |
+
)
|
| 16 |
+
import pandas._testing as tm
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestDataFrameCombineFirst:
|
| 20 |
+
def test_combine_first_mixed(self):
|
| 21 |
+
a = Series(["a", "b"], index=range(2))
|
| 22 |
+
b = Series(range(2), index=range(2))
|
| 23 |
+
f = DataFrame({"A": a, "B": b})
|
| 24 |
+
|
| 25 |
+
a = Series(["a", "b"], index=range(5, 7))
|
| 26 |
+
b = Series(range(2), index=range(5, 7))
|
| 27 |
+
g = DataFrame({"A": a, "B": b})
|
| 28 |
+
|
| 29 |
+
exp = DataFrame({"A": list("abab"), "B": [0, 1, 0, 1]}, index=[0, 1, 5, 6])
|
| 30 |
+
combined = f.combine_first(g)
|
| 31 |
+
tm.assert_frame_equal(combined, exp)
|
| 32 |
+
|
| 33 |
+
def test_combine_first(self, float_frame, using_infer_string):
|
| 34 |
+
# disjoint
|
| 35 |
+
head, tail = float_frame[:5], float_frame[5:]
|
| 36 |
+
|
| 37 |
+
combined = head.combine_first(tail)
|
| 38 |
+
reordered_frame = float_frame.reindex(combined.index)
|
| 39 |
+
tm.assert_frame_equal(combined, reordered_frame)
|
| 40 |
+
tm.assert_index_equal(combined.columns, float_frame.columns)
|
| 41 |
+
tm.assert_series_equal(combined["A"], reordered_frame["A"])
|
| 42 |
+
|
| 43 |
+
# same index
|
| 44 |
+
fcopy = float_frame.copy()
|
| 45 |
+
fcopy["A"] = 1
|
| 46 |
+
del fcopy["C"]
|
| 47 |
+
|
| 48 |
+
fcopy2 = float_frame.copy()
|
| 49 |
+
fcopy2["B"] = 0
|
| 50 |
+
del fcopy2["D"]
|
| 51 |
+
|
| 52 |
+
combined = fcopy.combine_first(fcopy2)
|
| 53 |
+
|
| 54 |
+
assert (combined["A"] == 1).all()
|
| 55 |
+
tm.assert_series_equal(combined["B"], fcopy["B"])
|
| 56 |
+
tm.assert_series_equal(combined["C"], fcopy2["C"])
|
| 57 |
+
tm.assert_series_equal(combined["D"], fcopy["D"])
|
| 58 |
+
|
| 59 |
+
# overlap
|
| 60 |
+
head, tail = reordered_frame[:10].copy(), reordered_frame
|
| 61 |
+
head["A"] = 1
|
| 62 |
+
|
| 63 |
+
combined = head.combine_first(tail)
|
| 64 |
+
assert (combined["A"][:10] == 1).all()
|
| 65 |
+
|
| 66 |
+
# reverse overlap
|
| 67 |
+
tail.iloc[:10, tail.columns.get_loc("A")] = 0
|
| 68 |
+
combined = tail.combine_first(head)
|
| 69 |
+
assert (combined["A"][:10] == 0).all()
|
| 70 |
+
|
| 71 |
+
# no overlap
|
| 72 |
+
f = float_frame[:10]
|
| 73 |
+
g = float_frame[10:]
|
| 74 |
+
combined = f.combine_first(g)
|
| 75 |
+
tm.assert_series_equal(combined["A"].reindex(f.index), f["A"])
|
| 76 |
+
tm.assert_series_equal(combined["A"].reindex(g.index), g["A"])
|
| 77 |
+
|
| 78 |
+
# corner cases
|
| 79 |
+
warning = FutureWarning if using_infer_string else None
|
| 80 |
+
with tm.assert_produces_warning(warning, match="empty entries"):
|
| 81 |
+
comb = float_frame.combine_first(DataFrame())
|
| 82 |
+
tm.assert_frame_equal(comb, float_frame)
|
| 83 |
+
|
| 84 |
+
comb = DataFrame().combine_first(float_frame)
|
| 85 |
+
tm.assert_frame_equal(comb, float_frame.sort_index())
|
| 86 |
+
|
| 87 |
+
comb = float_frame.combine_first(DataFrame(index=["faz", "boo"]))
|
| 88 |
+
assert "faz" in comb.index
|
| 89 |
+
|
| 90 |
+
# #2525
|
| 91 |
+
df = DataFrame({"a": [1]}, index=[datetime(2012, 1, 1)])
|
| 92 |
+
df2 = DataFrame(columns=["b"])
|
| 93 |
+
result = df.combine_first(df2)
|
| 94 |
+
assert "b" in result
|
| 95 |
+
|
| 96 |
+
def test_combine_first_mixed_bug(self):
|
| 97 |
+
idx = Index(["a", "b", "c", "e"])
|
| 98 |
+
ser1 = Series([5.0, -9.0, 4.0, 100.0], index=idx)
|
| 99 |
+
ser2 = Series(["a", "b", "c", "e"], index=idx)
|
| 100 |
+
ser3 = Series([12, 4, 5, 97], index=idx)
|
| 101 |
+
|
| 102 |
+
frame1 = DataFrame({"col0": ser1, "col2": ser2, "col3": ser3})
|
| 103 |
+
|
| 104 |
+
idx = Index(["a", "b", "c", "f"])
|
| 105 |
+
ser1 = Series([5.0, -9.0, 4.0, 100.0], index=idx)
|
| 106 |
+
ser2 = Series(["a", "b", "c", "f"], index=idx)
|
| 107 |
+
ser3 = Series([12, 4, 5, 97], index=idx)
|
| 108 |
+
|
| 109 |
+
frame2 = DataFrame({"col1": ser1, "col2": ser2, "col5": ser3})
|
| 110 |
+
|
| 111 |
+
combined = frame1.combine_first(frame2)
|
| 112 |
+
assert len(combined.columns) == 5
|
| 113 |
+
|
| 114 |
+
def test_combine_first_same_as_in_update(self):
|
| 115 |
+
# gh 3016 (same as in update)
|
| 116 |
+
df = DataFrame(
|
| 117 |
+
[[1.0, 2.0, False, True], [4.0, 5.0, True, False]],
|
| 118 |
+
columns=["A", "B", "bool1", "bool2"],
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
other = DataFrame([[45, 45]], index=[0], columns=["A", "B"])
|
| 122 |
+
result = df.combine_first(other)
|
| 123 |
+
tm.assert_frame_equal(result, df)
|
| 124 |
+
|
| 125 |
+
df.loc[0, "A"] = np.nan
|
| 126 |
+
result = df.combine_first(other)
|
| 127 |
+
df.loc[0, "A"] = 45
|
| 128 |
+
tm.assert_frame_equal(result, df)
|
| 129 |
+
|
| 130 |
+
def test_combine_first_doc_example(self):
|
| 131 |
+
# doc example
|
| 132 |
+
df1 = DataFrame(
|
| 133 |
+
{"A": [1.0, np.nan, 3.0, 5.0, np.nan], "B": [np.nan, 2.0, 3.0, np.nan, 6.0]}
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
df2 = DataFrame(
|
| 137 |
+
{
|
| 138 |
+
"A": [5.0, 2.0, 4.0, np.nan, 3.0, 7.0],
|
| 139 |
+
"B": [np.nan, np.nan, 3.0, 4.0, 6.0, 8.0],
|
| 140 |
+
}
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
result = df1.combine_first(df2)
|
| 144 |
+
expected = DataFrame({"A": [1, 2, 3, 5, 3, 7.0], "B": [np.nan, 2, 3, 4, 6, 8]})
|
| 145 |
+
tm.assert_frame_equal(result, expected)
|
| 146 |
+
|
| 147 |
+
def test_combine_first_return_obj_type_with_bools(self):
|
| 148 |
+
# GH3552
|
| 149 |
+
|
| 150 |
+
df1 = DataFrame(
|
| 151 |
+
[[np.nan, 3.0, True], [-4.6, np.nan, True], [np.nan, 7.0, False]]
|
| 152 |
+
)
|
| 153 |
+
df2 = DataFrame([[-42.6, np.nan, True], [-5.0, 1.6, False]], index=[1, 2])
|
| 154 |
+
|
| 155 |
+
expected = Series([True, True, False], name=2, dtype=bool)
|
| 156 |
+
|
| 157 |
+
result_12 = df1.combine_first(df2)[2]
|
| 158 |
+
tm.assert_series_equal(result_12, expected)
|
| 159 |
+
|
| 160 |
+
result_21 = df2.combine_first(df1)[2]
|
| 161 |
+
tm.assert_series_equal(result_21, expected)
|
| 162 |
+
|
| 163 |
+
@pytest.mark.parametrize(
|
| 164 |
+
"data1, data2, data_expected",
|
| 165 |
+
(
|
| 166 |
+
(
|
| 167 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 168 |
+
[pd.NaT, pd.NaT, pd.NaT],
|
| 169 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 170 |
+
),
|
| 171 |
+
(
|
| 172 |
+
[pd.NaT, pd.NaT, pd.NaT],
|
| 173 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 174 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 175 |
+
),
|
| 176 |
+
(
|
| 177 |
+
[datetime(2000, 1, 2), pd.NaT, pd.NaT],
|
| 178 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 179 |
+
[datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 180 |
+
),
|
| 181 |
+
(
|
| 182 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 183 |
+
[datetime(2000, 1, 2), pd.NaT, pd.NaT],
|
| 184 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
| 185 |
+
),
|
| 186 |
+
),
|
| 187 |
+
)
|
| 188 |
+
def test_combine_first_convert_datatime_correctly(
|
| 189 |
+
self, data1, data2, data_expected
|
| 190 |
+
):
|
| 191 |
+
# GH 3593
|
| 192 |
+
|
| 193 |
+
df1, df2 = DataFrame({"a": data1}), DataFrame({"a": data2})
|
| 194 |
+
result = df1.combine_first(df2)
|
| 195 |
+
expected = DataFrame({"a": data_expected})
|
| 196 |
+
tm.assert_frame_equal(result, expected)
|
| 197 |
+
|
| 198 |
+
def test_combine_first_align_nan(self):
|
| 199 |
+
# GH 7509 (not fixed)
|
| 200 |
+
dfa = DataFrame([[pd.Timestamp("2011-01-01"), 2]], columns=["a", "b"])
|
| 201 |
+
dfb = DataFrame([[4], [5]], columns=["b"])
|
| 202 |
+
assert dfa["a"].dtype == "datetime64[ns]"
|
| 203 |
+
assert dfa["b"].dtype == "int64"
|
| 204 |
+
|
| 205 |
+
res = dfa.combine_first(dfb)
|
| 206 |
+
exp = DataFrame(
|
| 207 |
+
{"a": [pd.Timestamp("2011-01-01"), pd.NaT], "b": [2, 5]},
|
| 208 |
+
columns=["a", "b"],
|
| 209 |
+
)
|
| 210 |
+
tm.assert_frame_equal(res, exp)
|
| 211 |
+
assert res["a"].dtype == "datetime64[ns]"
|
| 212 |
+
# TODO: this must be int64
|
| 213 |
+
assert res["b"].dtype == "int64"
|
| 214 |
+
|
| 215 |
+
res = dfa.iloc[:0].combine_first(dfb)
|
| 216 |
+
exp = DataFrame({"a": [np.nan, np.nan], "b": [4, 5]}, columns=["a", "b"])
|
| 217 |
+
tm.assert_frame_equal(res, exp)
|
| 218 |
+
# TODO: this must be datetime64
|
| 219 |
+
assert res["a"].dtype == "float64"
|
| 220 |
+
# TODO: this must be int64
|
| 221 |
+
assert res["b"].dtype == "int64"
|
| 222 |
+
|
| 223 |
+
def test_combine_first_timezone(self, unit):
|
| 224 |
+
# see gh-7630
|
| 225 |
+
data1 = pd.to_datetime("20100101 01:01").tz_localize("UTC").as_unit(unit)
|
| 226 |
+
df1 = DataFrame(
|
| 227 |
+
columns=["UTCdatetime", "abc"],
|
| 228 |
+
data=data1,
|
| 229 |
+
index=pd.date_range("20140627", periods=1),
|
| 230 |
+
)
|
| 231 |
+
data2 = pd.to_datetime("20121212 12:12").tz_localize("UTC").as_unit(unit)
|
| 232 |
+
df2 = DataFrame(
|
| 233 |
+
columns=["UTCdatetime", "xyz"],
|
| 234 |
+
data=data2,
|
| 235 |
+
index=pd.date_range("20140628", periods=1),
|
| 236 |
+
)
|
| 237 |
+
res = df2[["UTCdatetime"]].combine_first(df1)
|
| 238 |
+
exp = DataFrame(
|
| 239 |
+
{
|
| 240 |
+
"UTCdatetime": [
|
| 241 |
+
pd.Timestamp("2010-01-01 01:01", tz="UTC"),
|
| 242 |
+
pd.Timestamp("2012-12-12 12:12", tz="UTC"),
|
| 243 |
+
],
|
| 244 |
+
"abc": [pd.Timestamp("2010-01-01 01:01:00", tz="UTC"), pd.NaT],
|
| 245 |
+
},
|
| 246 |
+
columns=["UTCdatetime", "abc"],
|
| 247 |
+
index=pd.date_range("20140627", periods=2, freq="D"),
|
| 248 |
+
dtype=f"datetime64[{unit}, UTC]",
|
| 249 |
+
)
|
| 250 |
+
assert res["UTCdatetime"].dtype == f"datetime64[{unit}, UTC]"
|
| 251 |
+
assert res["abc"].dtype == f"datetime64[{unit}, UTC]"
|
| 252 |
+
|
| 253 |
+
tm.assert_frame_equal(res, exp)
|
| 254 |
+
|
| 255 |
+
def test_combine_first_timezone2(self, unit):
|
| 256 |
+
# see gh-10567
|
| 257 |
+
dts1 = pd.date_range("2015-01-01", "2015-01-05", tz="UTC", unit=unit)
|
| 258 |
+
df1 = DataFrame({"DATE": dts1})
|
| 259 |
+
dts2 = pd.date_range("2015-01-03", "2015-01-05", tz="UTC", unit=unit)
|
| 260 |
+
df2 = DataFrame({"DATE": dts2})
|
| 261 |
+
|
| 262 |
+
res = df1.combine_first(df2)
|
| 263 |
+
tm.assert_frame_equal(res, df1)
|
| 264 |
+
assert res["DATE"].dtype == f"datetime64[{unit}, UTC]"
|
| 265 |
+
|
| 266 |
+
def test_combine_first_timezone3(self, unit):
|
| 267 |
+
dts1 = pd.DatetimeIndex(
|
| 268 |
+
["2011-01-01", "NaT", "2011-01-03", "2011-01-04"], tz="US/Eastern"
|
| 269 |
+
).as_unit(unit)
|
| 270 |
+
df1 = DataFrame({"DATE": dts1}, index=[1, 3, 5, 7])
|
| 271 |
+
dts2 = pd.DatetimeIndex(
|
| 272 |
+
["2012-01-01", "2012-01-02", "2012-01-03"], tz="US/Eastern"
|
| 273 |
+
).as_unit(unit)
|
| 274 |
+
df2 = DataFrame({"DATE": dts2}, index=[2, 4, 5])
|
| 275 |
+
|
| 276 |
+
res = df1.combine_first(df2)
|
| 277 |
+
exp_dts = pd.DatetimeIndex(
|
| 278 |
+
[
|
| 279 |
+
"2011-01-01",
|
| 280 |
+
"2012-01-01",
|
| 281 |
+
"NaT",
|
| 282 |
+
"2012-01-02",
|
| 283 |
+
"2011-01-03",
|
| 284 |
+
"2011-01-04",
|
| 285 |
+
],
|
| 286 |
+
tz="US/Eastern",
|
| 287 |
+
).as_unit(unit)
|
| 288 |
+
exp = DataFrame({"DATE": exp_dts}, index=[1, 2, 3, 4, 5, 7])
|
| 289 |
+
tm.assert_frame_equal(res, exp)
|
| 290 |
+
|
| 291 |
+
# FIXME: parametrizing over unit breaks on non-nano
|
| 292 |
+
def test_combine_first_timezone4(self):
|
| 293 |
+
# different tz
|
| 294 |
+
dts1 = pd.date_range("2015-01-01", "2015-01-05", tz="US/Eastern")
|
| 295 |
+
df1 = DataFrame({"DATE": dts1})
|
| 296 |
+
dts2 = pd.date_range("2015-01-03", "2015-01-05")
|
| 297 |
+
df2 = DataFrame({"DATE": dts2})
|
| 298 |
+
|
| 299 |
+
# if df1 doesn't have NaN, keep its dtype
|
| 300 |
+
res = df1.combine_first(df2)
|
| 301 |
+
tm.assert_frame_equal(res, df1)
|
| 302 |
+
assert res["DATE"].dtype == "datetime64[ns, US/Eastern]"
|
| 303 |
+
|
| 304 |
+
def test_combine_first_timezone5(self, unit):
|
| 305 |
+
dts1 = pd.date_range("2015-01-01", "2015-01-02", tz="US/Eastern", unit=unit)
|
| 306 |
+
df1 = DataFrame({"DATE": dts1})
|
| 307 |
+
dts2 = pd.date_range("2015-01-01", "2015-01-03", unit=unit)
|
| 308 |
+
df2 = DataFrame({"DATE": dts2})
|
| 309 |
+
|
| 310 |
+
res = df1.combine_first(df2)
|
| 311 |
+
exp_dts = [
|
| 312 |
+
pd.Timestamp("2015-01-01", tz="US/Eastern"),
|
| 313 |
+
pd.Timestamp("2015-01-02", tz="US/Eastern"),
|
| 314 |
+
pd.Timestamp("2015-01-03"),
|
| 315 |
+
]
|
| 316 |
+
exp = DataFrame({"DATE": exp_dts})
|
| 317 |
+
tm.assert_frame_equal(res, exp)
|
| 318 |
+
assert res["DATE"].dtype == "object"
|
| 319 |
+
|
| 320 |
+
def test_combine_first_timedelta(self):
|
| 321 |
+
data1 = pd.TimedeltaIndex(["1 day", "NaT", "3 day", "4day"])
|
| 322 |
+
df1 = DataFrame({"TD": data1}, index=[1, 3, 5, 7])
|
| 323 |
+
data2 = pd.TimedeltaIndex(["10 day", "11 day", "12 day"])
|
| 324 |
+
df2 = DataFrame({"TD": data2}, index=[2, 4, 5])
|
| 325 |
+
|
| 326 |
+
res = df1.combine_first(df2)
|
| 327 |
+
exp_dts = pd.TimedeltaIndex(
|
| 328 |
+
["1 day", "10 day", "NaT", "11 day", "3 day", "4 day"]
|
| 329 |
+
)
|
| 330 |
+
exp = DataFrame({"TD": exp_dts}, index=[1, 2, 3, 4, 5, 7])
|
| 331 |
+
tm.assert_frame_equal(res, exp)
|
| 332 |
+
assert res["TD"].dtype == "timedelta64[ns]"
|
| 333 |
+
|
| 334 |
+
def test_combine_first_period(self):
|
| 335 |
+
data1 = pd.PeriodIndex(["2011-01", "NaT", "2011-03", "2011-04"], freq="M")
|
| 336 |
+
df1 = DataFrame({"P": data1}, index=[1, 3, 5, 7])
|
| 337 |
+
data2 = pd.PeriodIndex(["2012-01-01", "2012-02", "2012-03"], freq="M")
|
| 338 |
+
df2 = DataFrame({"P": data2}, index=[2, 4, 5])
|
| 339 |
+
|
| 340 |
+
res = df1.combine_first(df2)
|
| 341 |
+
exp_dts = pd.PeriodIndex(
|
| 342 |
+
["2011-01", "2012-01", "NaT", "2012-02", "2011-03", "2011-04"], freq="M"
|
| 343 |
+
)
|
| 344 |
+
exp = DataFrame({"P": exp_dts}, index=[1, 2, 3, 4, 5, 7])
|
| 345 |
+
tm.assert_frame_equal(res, exp)
|
| 346 |
+
assert res["P"].dtype == data1.dtype
|
| 347 |
+
|
| 348 |
+
# different freq
|
| 349 |
+
dts2 = pd.PeriodIndex(["2012-01-01", "2012-01-02", "2012-01-03"], freq="D")
|
| 350 |
+
df2 = DataFrame({"P": dts2}, index=[2, 4, 5])
|
| 351 |
+
|
| 352 |
+
res = df1.combine_first(df2)
|
| 353 |
+
exp_dts = [
|
| 354 |
+
pd.Period("2011-01", freq="M"),
|
| 355 |
+
pd.Period("2012-01-01", freq="D"),
|
| 356 |
+
pd.NaT,
|
| 357 |
+
pd.Period("2012-01-02", freq="D"),
|
| 358 |
+
pd.Period("2011-03", freq="M"),
|
| 359 |
+
pd.Period("2011-04", freq="M"),
|
| 360 |
+
]
|
| 361 |
+
exp = DataFrame({"P": exp_dts}, index=[1, 2, 3, 4, 5, 7])
|
| 362 |
+
tm.assert_frame_equal(res, exp)
|
| 363 |
+
assert res["P"].dtype == "object"
|
| 364 |
+
|
| 365 |
+
def test_combine_first_int(self):
|
| 366 |
+
# GH14687 - integer series that do no align exactly
|
| 367 |
+
|
| 368 |
+
df1 = DataFrame({"a": [0, 1, 3, 5]}, dtype="int64")
|
| 369 |
+
df2 = DataFrame({"a": [1, 4]}, dtype="int64")
|
| 370 |
+
|
| 371 |
+
result_12 = df1.combine_first(df2)
|
| 372 |
+
expected_12 = DataFrame({"a": [0, 1, 3, 5]})
|
| 373 |
+
tm.assert_frame_equal(result_12, expected_12)
|
| 374 |
+
|
| 375 |
+
result_21 = df2.combine_first(df1)
|
| 376 |
+
expected_21 = DataFrame({"a": [1, 4, 3, 5]})
|
| 377 |
+
tm.assert_frame_equal(result_21, expected_21)
|
| 378 |
+
|
| 379 |
+
@pytest.mark.parametrize("val", [1, 1.0])
|
| 380 |
+
def test_combine_first_with_asymmetric_other(self, val):
|
| 381 |
+
# see gh-20699
|
| 382 |
+
df1 = DataFrame({"isNum": [val]})
|
| 383 |
+
df2 = DataFrame({"isBool": [True]})
|
| 384 |
+
|
| 385 |
+
res = df1.combine_first(df2)
|
| 386 |
+
exp = DataFrame({"isBool": [True], "isNum": [val]})
|
| 387 |
+
|
| 388 |
+
tm.assert_frame_equal(res, exp)
|
| 389 |
+
|
| 390 |
+
def test_combine_first_string_dtype_only_na(self, nullable_string_dtype):
|
| 391 |
+
# GH: 37519
|
| 392 |
+
df = DataFrame(
|
| 393 |
+
{"a": ["962", "85"], "b": [pd.NA] * 2}, dtype=nullable_string_dtype
|
| 394 |
+
)
|
| 395 |
+
df2 = DataFrame({"a": ["85"], "b": [pd.NA]}, dtype=nullable_string_dtype)
|
| 396 |
+
df.set_index(["a", "b"], inplace=True)
|
| 397 |
+
df2.set_index(["a", "b"], inplace=True)
|
| 398 |
+
result = df.combine_first(df2)
|
| 399 |
+
expected = DataFrame(
|
| 400 |
+
{"a": ["962", "85"], "b": [pd.NA] * 2}, dtype=nullable_string_dtype
|
| 401 |
+
).set_index(["a", "b"])
|
| 402 |
+
tm.assert_frame_equal(result, expected)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
@pytest.mark.parametrize(
|
| 406 |
+
"scalar1, scalar2",
|
| 407 |
+
[
|
| 408 |
+
(datetime(2020, 1, 1), datetime(2020, 1, 2)),
|
| 409 |
+
(pd.Period("2020-01-01", "D"), pd.Period("2020-01-02", "D")),
|
| 410 |
+
(pd.Timedelta("89 days"), pd.Timedelta("60 min")),
|
| 411 |
+
(pd.Interval(left=0, right=1), pd.Interval(left=2, right=3, closed="left")),
|
| 412 |
+
],
|
| 413 |
+
)
|
| 414 |
+
def test_combine_first_timestamp_bug(scalar1, scalar2, nulls_fixture):
|
| 415 |
+
# GH28481
|
| 416 |
+
na_value = nulls_fixture
|
| 417 |
+
|
| 418 |
+
frame = DataFrame([[na_value, na_value]], columns=["a", "b"])
|
| 419 |
+
other = DataFrame([[scalar1, scalar2]], columns=["b", "c"])
|
| 420 |
+
|
| 421 |
+
common_dtype = find_common_type([frame.dtypes["b"], other.dtypes["b"]])
|
| 422 |
+
|
| 423 |
+
if is_dtype_equal(common_dtype, "object") or frame.dtypes["b"] == other.dtypes["b"]:
|
| 424 |
+
val = scalar1
|
| 425 |
+
else:
|
| 426 |
+
val = na_value
|
| 427 |
+
|
| 428 |
+
result = frame.combine_first(other)
|
| 429 |
+
|
| 430 |
+
expected = DataFrame([[na_value, val, scalar2]], columns=["a", "b", "c"])
|
| 431 |
+
|
| 432 |
+
expected["b"] = expected["b"].astype(common_dtype)
|
| 433 |
+
|
| 434 |
+
tm.assert_frame_equal(result, expected)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def test_combine_first_timestamp_bug_NaT():
|
| 438 |
+
# GH28481
|
| 439 |
+
frame = DataFrame([[pd.NaT, pd.NaT]], columns=["a", "b"])
|
| 440 |
+
other = DataFrame(
|
| 441 |
+
[[datetime(2020, 1, 1), datetime(2020, 1, 2)]], columns=["b", "c"]
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
result = frame.combine_first(other)
|
| 445 |
+
expected = DataFrame(
|
| 446 |
+
[[pd.NaT, datetime(2020, 1, 1), datetime(2020, 1, 2)]], columns=["a", "b", "c"]
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
tm.assert_frame_equal(result, expected)
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def test_combine_first_with_nan_multiindex():
|
| 453 |
+
# gh-36562
|
| 454 |
+
|
| 455 |
+
mi1 = MultiIndex.from_arrays(
|
| 456 |
+
[["b", "b", "c", "a", "b", np.nan], [1, 2, 3, 4, 5, 6]], names=["a", "b"]
|
| 457 |
+
)
|
| 458 |
+
df = DataFrame({"c": [1, 1, 1, 1, 1, 1]}, index=mi1)
|
| 459 |
+
mi2 = MultiIndex.from_arrays(
|
| 460 |
+
[["a", "b", "c", "a", "b", "d"], [1, 1, 1, 1, 1, 1]], names=["a", "b"]
|
| 461 |
+
)
|
| 462 |
+
s = Series([1, 2, 3, 4, 5, 6], index=mi2)
|
| 463 |
+
res = df.combine_first(DataFrame({"d": s}))
|
| 464 |
+
mi_expected = MultiIndex.from_arrays(
|
| 465 |
+
[
|
| 466 |
+
["a", "a", "a", "b", "b", "b", "b", "c", "c", "d", np.nan],
|
| 467 |
+
[1, 1, 4, 1, 1, 2, 5, 1, 3, 1, 6],
|
| 468 |
+
],
|
| 469 |
+
names=["a", "b"],
|
| 470 |
+
)
|
| 471 |
+
expected = DataFrame(
|
| 472 |
+
{
|
| 473 |
+
"c": [np.nan, np.nan, 1, 1, 1, 1, 1, np.nan, 1, np.nan, 1],
|
| 474 |
+
"d": [1.0, 4.0, np.nan, 2.0, 5.0, np.nan, np.nan, 3.0, np.nan, 6.0, np.nan],
|
| 475 |
+
},
|
| 476 |
+
index=mi_expected,
|
| 477 |
+
)
|
| 478 |
+
tm.assert_frame_equal(res, expected)
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def test_combine_preserve_dtypes():
|
| 482 |
+
# GH7509
|
| 483 |
+
a_column = Series(["a", "b"], index=range(2))
|
| 484 |
+
b_column = Series(range(2), index=range(2))
|
| 485 |
+
df1 = DataFrame({"A": a_column, "B": b_column})
|
| 486 |
+
|
| 487 |
+
c_column = Series(["a", "b"], index=range(5, 7))
|
| 488 |
+
b_column = Series(range(-1, 1), index=range(5, 7))
|
| 489 |
+
df2 = DataFrame({"B": b_column, "C": c_column})
|
| 490 |
+
|
| 491 |
+
expected = DataFrame(
|
| 492 |
+
{
|
| 493 |
+
"A": ["a", "b", np.nan, np.nan],
|
| 494 |
+
"B": [0, 1, -1, 0],
|
| 495 |
+
"C": [np.nan, np.nan, "a", "b"],
|
| 496 |
+
},
|
| 497 |
+
index=[0, 1, 5, 6],
|
| 498 |
+
)
|
| 499 |
+
combined = df1.combine_first(df2)
|
| 500 |
+
tm.assert_frame_equal(combined, expected)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def test_combine_first_duplicates_rows_for_nan_index_values():
|
| 504 |
+
# GH39881
|
| 505 |
+
df1 = DataFrame(
|
| 506 |
+
{"x": [9, 10, 11]},
|
| 507 |
+
index=MultiIndex.from_arrays([[1, 2, 3], [np.nan, 5, 6]], names=["a", "b"]),
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
df2 = DataFrame(
|
| 511 |
+
{"y": [12, 13, 14]},
|
| 512 |
+
index=MultiIndex.from_arrays([[1, 2, 4], [np.nan, 5, 7]], names=["a", "b"]),
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
expected = DataFrame(
|
| 516 |
+
{
|
| 517 |
+
"x": [9.0, 10.0, 11.0, np.nan],
|
| 518 |
+
"y": [12.0, 13.0, np.nan, 14.0],
|
| 519 |
+
},
|
| 520 |
+
index=MultiIndex.from_arrays(
|
| 521 |
+
[[1, 2, 3, 4], [np.nan, 5, 6, 7]], names=["a", "b"]
|
| 522 |
+
),
|
| 523 |
+
)
|
| 524 |
+
combined = df1.combine_first(df2)
|
| 525 |
+
tm.assert_frame_equal(combined, expected)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def test_combine_first_int64_not_cast_to_float64():
|
| 529 |
+
# GH 28613
|
| 530 |
+
df_1 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
|
| 531 |
+
df_2 = DataFrame({"A": [1, 20, 30], "B": [40, 50, 60], "C": [12, 34, 65]})
|
| 532 |
+
result = df_1.combine_first(df_2)
|
| 533 |
+
expected = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [12, 34, 65]})
|
| 534 |
+
tm.assert_frame_equal(result, expected)
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def test_midx_losing_dtype():
|
| 538 |
+
# GH#49830
|
| 539 |
+
midx = MultiIndex.from_arrays([[0, 0], [np.nan, np.nan]])
|
| 540 |
+
midx2 = MultiIndex.from_arrays([[1, 1], [np.nan, np.nan]])
|
| 541 |
+
df1 = DataFrame({"a": [None, 4]}, index=midx)
|
| 542 |
+
df2 = DataFrame({"a": [3, 3]}, index=midx2)
|
| 543 |
+
result = df1.combine_first(df2)
|
| 544 |
+
expected_midx = MultiIndex.from_arrays(
|
| 545 |
+
[[0, 0, 1, 1], [np.nan, np.nan, np.nan, np.nan]]
|
| 546 |
+
)
|
| 547 |
+
expected = DataFrame({"a": [np.nan, 4, 3, 3]}, index=expected_midx)
|
| 548 |
+
tm.assert_frame_equal(result, expected)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def test_combine_first_empty_columns():
|
| 552 |
+
left = DataFrame(columns=["a", "b"])
|
| 553 |
+
right = DataFrame(columns=["a", "c"])
|
| 554 |
+
result = left.combine_first(right)
|
| 555 |
+
expected = DataFrame(columns=["a", "b", "c"])
|
| 556 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_compare.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas.compat.numpy import np_version_gte1p25
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pandas._testing as tm
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@pytest.mark.parametrize("align_axis", [0, 1, "index", "columns"])
|
| 11 |
+
def test_compare_axis(align_axis):
|
| 12 |
+
# GH#30429
|
| 13 |
+
df = pd.DataFrame(
|
| 14 |
+
{"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},
|
| 15 |
+
columns=["col1", "col2", "col3"],
|
| 16 |
+
)
|
| 17 |
+
df2 = df.copy()
|
| 18 |
+
df2.loc[0, "col1"] = "c"
|
| 19 |
+
df2.loc[2, "col3"] = 4.0
|
| 20 |
+
|
| 21 |
+
result = df.compare(df2, align_axis=align_axis)
|
| 22 |
+
|
| 23 |
+
if align_axis in (1, "columns"):
|
| 24 |
+
indices = pd.Index([0, 2])
|
| 25 |
+
columns = pd.MultiIndex.from_product([["col1", "col3"], ["self", "other"]])
|
| 26 |
+
expected = pd.DataFrame(
|
| 27 |
+
[["a", "c", np.nan, np.nan], [np.nan, np.nan, 3.0, 4.0]],
|
| 28 |
+
index=indices,
|
| 29 |
+
columns=columns,
|
| 30 |
+
)
|
| 31 |
+
else:
|
| 32 |
+
indices = pd.MultiIndex.from_product([[0, 2], ["self", "other"]])
|
| 33 |
+
columns = pd.Index(["col1", "col3"])
|
| 34 |
+
expected = pd.DataFrame(
|
| 35 |
+
[["a", np.nan], ["c", np.nan], [np.nan, 3.0], [np.nan, 4.0]],
|
| 36 |
+
index=indices,
|
| 37 |
+
columns=columns,
|
| 38 |
+
)
|
| 39 |
+
tm.assert_frame_equal(result, expected)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@pytest.mark.parametrize(
|
| 43 |
+
"keep_shape, keep_equal",
|
| 44 |
+
[
|
| 45 |
+
(True, False),
|
| 46 |
+
(False, True),
|
| 47 |
+
(True, True),
|
| 48 |
+
# False, False case is already covered in test_compare_axis
|
| 49 |
+
],
|
| 50 |
+
)
|
| 51 |
+
def test_compare_various_formats(keep_shape, keep_equal):
|
| 52 |
+
df = pd.DataFrame(
|
| 53 |
+
{"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},
|
| 54 |
+
columns=["col1", "col2", "col3"],
|
| 55 |
+
)
|
| 56 |
+
df2 = df.copy()
|
| 57 |
+
df2.loc[0, "col1"] = "c"
|
| 58 |
+
df2.loc[2, "col3"] = 4.0
|
| 59 |
+
|
| 60 |
+
result = df.compare(df2, keep_shape=keep_shape, keep_equal=keep_equal)
|
| 61 |
+
|
| 62 |
+
if keep_shape:
|
| 63 |
+
indices = pd.Index([0, 1, 2])
|
| 64 |
+
columns = pd.MultiIndex.from_product(
|
| 65 |
+
[["col1", "col2", "col3"], ["self", "other"]]
|
| 66 |
+
)
|
| 67 |
+
if keep_equal:
|
| 68 |
+
expected = pd.DataFrame(
|
| 69 |
+
[
|
| 70 |
+
["a", "c", 1.0, 1.0, 1.0, 1.0],
|
| 71 |
+
["b", "b", 2.0, 2.0, 2.0, 2.0],
|
| 72 |
+
["c", "c", np.nan, np.nan, 3.0, 4.0],
|
| 73 |
+
],
|
| 74 |
+
index=indices,
|
| 75 |
+
columns=columns,
|
| 76 |
+
)
|
| 77 |
+
else:
|
| 78 |
+
expected = pd.DataFrame(
|
| 79 |
+
[
|
| 80 |
+
["a", "c", np.nan, np.nan, np.nan, np.nan],
|
| 81 |
+
[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
|
| 82 |
+
[np.nan, np.nan, np.nan, np.nan, 3.0, 4.0],
|
| 83 |
+
],
|
| 84 |
+
index=indices,
|
| 85 |
+
columns=columns,
|
| 86 |
+
)
|
| 87 |
+
else:
|
| 88 |
+
indices = pd.Index([0, 2])
|
| 89 |
+
columns = pd.MultiIndex.from_product([["col1", "col3"], ["self", "other"]])
|
| 90 |
+
expected = pd.DataFrame(
|
| 91 |
+
[["a", "c", 1.0, 1.0], ["c", "c", 3.0, 4.0]], index=indices, columns=columns
|
| 92 |
+
)
|
| 93 |
+
tm.assert_frame_equal(result, expected)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_compare_with_equal_nulls():
|
| 97 |
+
# We want to make sure two NaNs are considered the same
|
| 98 |
+
# and dropped where applicable
|
| 99 |
+
df = pd.DataFrame(
|
| 100 |
+
{"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},
|
| 101 |
+
columns=["col1", "col2", "col3"],
|
| 102 |
+
)
|
| 103 |
+
df2 = df.copy()
|
| 104 |
+
df2.loc[0, "col1"] = "c"
|
| 105 |
+
|
| 106 |
+
result = df.compare(df2)
|
| 107 |
+
indices = pd.Index([0])
|
| 108 |
+
columns = pd.MultiIndex.from_product([["col1"], ["self", "other"]])
|
| 109 |
+
expected = pd.DataFrame([["a", "c"]], index=indices, columns=columns)
|
| 110 |
+
tm.assert_frame_equal(result, expected)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_compare_with_non_equal_nulls():
|
| 114 |
+
# We want to make sure the relevant NaNs do not get dropped
|
| 115 |
+
# even if the entire row or column are NaNs
|
| 116 |
+
df = pd.DataFrame(
|
| 117 |
+
{"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},
|
| 118 |
+
columns=["col1", "col2", "col3"],
|
| 119 |
+
)
|
| 120 |
+
df2 = df.copy()
|
| 121 |
+
df2.loc[0, "col1"] = "c"
|
| 122 |
+
df2.loc[2, "col3"] = np.nan
|
| 123 |
+
|
| 124 |
+
result = df.compare(df2)
|
| 125 |
+
|
| 126 |
+
indices = pd.Index([0, 2])
|
| 127 |
+
columns = pd.MultiIndex.from_product([["col1", "col3"], ["self", "other"]])
|
| 128 |
+
expected = pd.DataFrame(
|
| 129 |
+
[["a", "c", np.nan, np.nan], [np.nan, np.nan, 3.0, np.nan]],
|
| 130 |
+
index=indices,
|
| 131 |
+
columns=columns,
|
| 132 |
+
)
|
| 133 |
+
tm.assert_frame_equal(result, expected)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@pytest.mark.parametrize("align_axis", [0, 1])
|
| 137 |
+
def test_compare_multi_index(align_axis):
|
| 138 |
+
df = pd.DataFrame(
|
| 139 |
+
{"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]}
|
| 140 |
+
)
|
| 141 |
+
df.columns = pd.MultiIndex.from_arrays([["a", "a", "b"], ["col1", "col2", "col3"]])
|
| 142 |
+
df.index = pd.MultiIndex.from_arrays([["x", "x", "y"], [0, 1, 2]])
|
| 143 |
+
|
| 144 |
+
df2 = df.copy()
|
| 145 |
+
df2.iloc[0, 0] = "c"
|
| 146 |
+
df2.iloc[2, 2] = 4.0
|
| 147 |
+
|
| 148 |
+
result = df.compare(df2, align_axis=align_axis)
|
| 149 |
+
|
| 150 |
+
if align_axis == 0:
|
| 151 |
+
indices = pd.MultiIndex.from_arrays(
|
| 152 |
+
[["x", "x", "y", "y"], [0, 0, 2, 2], ["self", "other", "self", "other"]]
|
| 153 |
+
)
|
| 154 |
+
columns = pd.MultiIndex.from_arrays([["a", "b"], ["col1", "col3"]])
|
| 155 |
+
data = [["a", np.nan], ["c", np.nan], [np.nan, 3.0], [np.nan, 4.0]]
|
| 156 |
+
else:
|
| 157 |
+
indices = pd.MultiIndex.from_arrays([["x", "y"], [0, 2]])
|
| 158 |
+
columns = pd.MultiIndex.from_arrays(
|
| 159 |
+
[
|
| 160 |
+
["a", "a", "b", "b"],
|
| 161 |
+
["col1", "col1", "col3", "col3"],
|
| 162 |
+
["self", "other", "self", "other"],
|
| 163 |
+
]
|
| 164 |
+
)
|
| 165 |
+
data = [["a", "c", np.nan, np.nan], [np.nan, np.nan, 3.0, 4.0]]
|
| 166 |
+
|
| 167 |
+
expected = pd.DataFrame(data=data, index=indices, columns=columns)
|
| 168 |
+
tm.assert_frame_equal(result, expected)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def test_compare_unaligned_objects():
|
| 172 |
+
# test DataFrames with different indices
|
| 173 |
+
msg = (
|
| 174 |
+
r"Can only compare identically-labeled \(both index and columns\) DataFrame "
|
| 175 |
+
"objects"
|
| 176 |
+
)
|
| 177 |
+
with pytest.raises(ValueError, match=msg):
|
| 178 |
+
df1 = pd.DataFrame([1, 2, 3], index=["a", "b", "c"])
|
| 179 |
+
df2 = pd.DataFrame([1, 2, 3], index=["a", "b", "d"])
|
| 180 |
+
df1.compare(df2)
|
| 181 |
+
|
| 182 |
+
# test DataFrames with different shapes
|
| 183 |
+
msg = (
|
| 184 |
+
r"Can only compare identically-labeled \(both index and columns\) DataFrame "
|
| 185 |
+
"objects"
|
| 186 |
+
)
|
| 187 |
+
with pytest.raises(ValueError, match=msg):
|
| 188 |
+
df1 = pd.DataFrame(np.ones((3, 3)))
|
| 189 |
+
df2 = pd.DataFrame(np.zeros((2, 1)))
|
| 190 |
+
df1.compare(df2)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_compare_result_names():
|
| 194 |
+
# GH 44354
|
| 195 |
+
df1 = pd.DataFrame(
|
| 196 |
+
{"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},
|
| 197 |
+
)
|
| 198 |
+
df2 = pd.DataFrame(
|
| 199 |
+
{
|
| 200 |
+
"col1": ["c", "b", "c"],
|
| 201 |
+
"col2": [1.0, 2.0, np.nan],
|
| 202 |
+
"col3": [1.0, 2.0, np.nan],
|
| 203 |
+
},
|
| 204 |
+
)
|
| 205 |
+
result = df1.compare(df2, result_names=("left", "right"))
|
| 206 |
+
expected = pd.DataFrame(
|
| 207 |
+
{
|
| 208 |
+
("col1", "left"): {0: "a", 2: np.nan},
|
| 209 |
+
("col1", "right"): {0: "c", 2: np.nan},
|
| 210 |
+
("col3", "left"): {0: np.nan, 2: 3.0},
|
| 211 |
+
("col3", "right"): {0: np.nan, 2: np.nan},
|
| 212 |
+
}
|
| 213 |
+
)
|
| 214 |
+
tm.assert_frame_equal(result, expected)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@pytest.mark.parametrize(
|
| 218 |
+
"result_names",
|
| 219 |
+
[
|
| 220 |
+
[1, 2],
|
| 221 |
+
"HK",
|
| 222 |
+
{"2": 2, "3": 3},
|
| 223 |
+
3,
|
| 224 |
+
3.0,
|
| 225 |
+
],
|
| 226 |
+
)
|
| 227 |
+
def test_invalid_input_result_names(result_names):
|
| 228 |
+
# GH 44354
|
| 229 |
+
df1 = pd.DataFrame(
|
| 230 |
+
{"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},
|
| 231 |
+
)
|
| 232 |
+
df2 = pd.DataFrame(
|
| 233 |
+
{
|
| 234 |
+
"col1": ["c", "b", "c"],
|
| 235 |
+
"col2": [1.0, 2.0, np.nan],
|
| 236 |
+
"col3": [1.0, 2.0, np.nan],
|
| 237 |
+
},
|
| 238 |
+
)
|
| 239 |
+
with pytest.raises(
|
| 240 |
+
TypeError,
|
| 241 |
+
match=(
|
| 242 |
+
f"Passing 'result_names' as a {type(result_names)} is not "
|
| 243 |
+
"supported. Provide 'result_names' as a tuple instead."
|
| 244 |
+
),
|
| 245 |
+
):
|
| 246 |
+
df1.compare(df2, result_names=result_names)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
@pytest.mark.parametrize(
|
| 250 |
+
"val1,val2",
|
| 251 |
+
[(4, pd.NA), (pd.NA, pd.NA), (pd.NA, 4)],
|
| 252 |
+
)
|
| 253 |
+
def test_compare_ea_and_np_dtype(val1, val2):
|
| 254 |
+
# GH 48966
|
| 255 |
+
arr = [4.0, val1]
|
| 256 |
+
ser = pd.Series([1, val2], dtype="Int64")
|
| 257 |
+
|
| 258 |
+
df1 = pd.DataFrame({"a": arr, "b": [1.0, 2]})
|
| 259 |
+
df2 = pd.DataFrame({"a": ser, "b": [1.0, 2]})
|
| 260 |
+
expected = pd.DataFrame(
|
| 261 |
+
{
|
| 262 |
+
("a", "self"): arr,
|
| 263 |
+
("a", "other"): ser,
|
| 264 |
+
("b", "self"): np.nan,
|
| 265 |
+
("b", "other"): np.nan,
|
| 266 |
+
}
|
| 267 |
+
)
|
| 268 |
+
if val1 is pd.NA and val2 is pd.NA:
|
| 269 |
+
# GH#18463 TODO: is this really the desired behavior?
|
| 270 |
+
expected.loc[1, ("a", "self")] = np.nan
|
| 271 |
+
|
| 272 |
+
if val1 is pd.NA and np_version_gte1p25:
|
| 273 |
+
# can't compare with numpy array if it contains pd.NA
|
| 274 |
+
with pytest.raises(TypeError, match="boolean value of NA is ambiguous"):
|
| 275 |
+
result = df1.compare(df2, keep_shape=True)
|
| 276 |
+
else:
|
| 277 |
+
result = df1.compare(df2, keep_shape=True)
|
| 278 |
+
tm.assert_frame_equal(result, expected)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@pytest.mark.parametrize(
|
| 282 |
+
"df1_val,df2_val,diff_self,diff_other",
|
| 283 |
+
[
|
| 284 |
+
(4, 3, 4, 3),
|
| 285 |
+
(4, 4, pd.NA, pd.NA),
|
| 286 |
+
(4, pd.NA, 4, pd.NA),
|
| 287 |
+
(pd.NA, pd.NA, pd.NA, pd.NA),
|
| 288 |
+
],
|
| 289 |
+
)
|
| 290 |
+
def test_compare_nullable_int64_dtype(df1_val, df2_val, diff_self, diff_other):
|
| 291 |
+
# GH 48966
|
| 292 |
+
df1 = pd.DataFrame({"a": pd.Series([df1_val, pd.NA], dtype="Int64"), "b": [1.0, 2]})
|
| 293 |
+
df2 = df1.copy()
|
| 294 |
+
df2.loc[0, "a"] = df2_val
|
| 295 |
+
|
| 296 |
+
expected = pd.DataFrame(
|
| 297 |
+
{
|
| 298 |
+
("a", "self"): pd.Series([diff_self, pd.NA], dtype="Int64"),
|
| 299 |
+
("a", "other"): pd.Series([diff_other, pd.NA], dtype="Int64"),
|
| 300 |
+
("b", "self"): np.nan,
|
| 301 |
+
("b", "other"): np.nan,
|
| 302 |
+
}
|
| 303 |
+
)
|
| 304 |
+
result = df1.compare(df2, keep_shape=True)
|
| 305 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_convert_dtypes.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pandas._testing as tm
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestConvertDtypes:
|
| 11 |
+
@pytest.mark.parametrize(
|
| 12 |
+
"convert_integer, expected", [(False, np.dtype("int32")), (True, "Int32")]
|
| 13 |
+
)
|
| 14 |
+
def test_convert_dtypes(self, convert_integer, expected, string_storage):
|
| 15 |
+
# Specific types are tested in tests/series/test_dtypes.py
|
| 16 |
+
# Just check that it works for DataFrame here
|
| 17 |
+
df = pd.DataFrame(
|
| 18 |
+
{
|
| 19 |
+
"a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
|
| 20 |
+
"b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
|
| 21 |
+
}
|
| 22 |
+
)
|
| 23 |
+
with pd.option_context("string_storage", string_storage):
|
| 24 |
+
result = df.convert_dtypes(True, True, convert_integer, False)
|
| 25 |
+
expected = pd.DataFrame(
|
| 26 |
+
{
|
| 27 |
+
"a": pd.Series([1, 2, 3], dtype=expected),
|
| 28 |
+
"b": pd.Series(["x", "y", "z"], dtype=f"string[{string_storage}]"),
|
| 29 |
+
}
|
| 30 |
+
)
|
| 31 |
+
tm.assert_frame_equal(result, expected)
|
| 32 |
+
|
| 33 |
+
def test_convert_empty(self):
|
| 34 |
+
# Empty DataFrame can pass convert_dtypes, see GH#40393
|
| 35 |
+
empty_df = pd.DataFrame()
|
| 36 |
+
tm.assert_frame_equal(empty_df, empty_df.convert_dtypes())
|
| 37 |
+
|
| 38 |
+
def test_convert_dtypes_retain_column_names(self):
|
| 39 |
+
# GH#41435
|
| 40 |
+
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
|
| 41 |
+
df.columns.name = "cols"
|
| 42 |
+
|
| 43 |
+
result = df.convert_dtypes()
|
| 44 |
+
tm.assert_index_equal(result.columns, df.columns)
|
| 45 |
+
assert result.columns.name == "cols"
|
| 46 |
+
|
| 47 |
+
def test_pyarrow_dtype_backend(self):
|
| 48 |
+
pa = pytest.importorskip("pyarrow")
|
| 49 |
+
df = pd.DataFrame(
|
| 50 |
+
{
|
| 51 |
+
"a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
|
| 52 |
+
"b": pd.Series(["x", "y", None], dtype=np.dtype("O")),
|
| 53 |
+
"c": pd.Series([True, False, None], dtype=np.dtype("O")),
|
| 54 |
+
"d": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
|
| 55 |
+
"e": pd.Series(pd.date_range("2022", periods=3)),
|
| 56 |
+
"f": pd.Series(pd.date_range("2022", periods=3, tz="UTC").as_unit("s")),
|
| 57 |
+
"g": pd.Series(pd.timedelta_range("1D", periods=3)),
|
| 58 |
+
}
|
| 59 |
+
)
|
| 60 |
+
result = df.convert_dtypes(dtype_backend="pyarrow")
|
| 61 |
+
expected = pd.DataFrame(
|
| 62 |
+
{
|
| 63 |
+
"a": pd.arrays.ArrowExtensionArray(
|
| 64 |
+
pa.array([1, 2, 3], type=pa.int32())
|
| 65 |
+
),
|
| 66 |
+
"b": pd.arrays.ArrowExtensionArray(pa.array(["x", "y", None])),
|
| 67 |
+
"c": pd.arrays.ArrowExtensionArray(pa.array([True, False, None])),
|
| 68 |
+
"d": pd.arrays.ArrowExtensionArray(pa.array([None, 100.5, 200.0])),
|
| 69 |
+
"e": pd.arrays.ArrowExtensionArray(
|
| 70 |
+
pa.array(
|
| 71 |
+
[
|
| 72 |
+
datetime.datetime(2022, 1, 1),
|
| 73 |
+
datetime.datetime(2022, 1, 2),
|
| 74 |
+
datetime.datetime(2022, 1, 3),
|
| 75 |
+
],
|
| 76 |
+
type=pa.timestamp(unit="ns"),
|
| 77 |
+
)
|
| 78 |
+
),
|
| 79 |
+
"f": pd.arrays.ArrowExtensionArray(
|
| 80 |
+
pa.array(
|
| 81 |
+
[
|
| 82 |
+
datetime.datetime(2022, 1, 1),
|
| 83 |
+
datetime.datetime(2022, 1, 2),
|
| 84 |
+
datetime.datetime(2022, 1, 3),
|
| 85 |
+
],
|
| 86 |
+
type=pa.timestamp(unit="s", tz="UTC"),
|
| 87 |
+
)
|
| 88 |
+
),
|
| 89 |
+
"g": pd.arrays.ArrowExtensionArray(
|
| 90 |
+
pa.array(
|
| 91 |
+
[
|
| 92 |
+
datetime.timedelta(1),
|
| 93 |
+
datetime.timedelta(2),
|
| 94 |
+
datetime.timedelta(3),
|
| 95 |
+
],
|
| 96 |
+
type=pa.duration("ns"),
|
| 97 |
+
)
|
| 98 |
+
),
|
| 99 |
+
}
|
| 100 |
+
)
|
| 101 |
+
tm.assert_frame_equal(result, expected)
|
| 102 |
+
|
| 103 |
+
def test_pyarrow_dtype_backend_already_pyarrow(self):
|
| 104 |
+
pytest.importorskip("pyarrow")
|
| 105 |
+
expected = pd.DataFrame([1, 2, 3], dtype="int64[pyarrow]")
|
| 106 |
+
result = expected.convert_dtypes(dtype_backend="pyarrow")
|
| 107 |
+
tm.assert_frame_equal(result, expected)
|
| 108 |
+
|
| 109 |
+
def test_pyarrow_dtype_backend_from_pandas_nullable(self):
|
| 110 |
+
pa = pytest.importorskip("pyarrow")
|
| 111 |
+
df = pd.DataFrame(
|
| 112 |
+
{
|
| 113 |
+
"a": pd.Series([1, 2, None], dtype="Int32"),
|
| 114 |
+
"b": pd.Series(["x", "y", None], dtype="string[python]"),
|
| 115 |
+
"c": pd.Series([True, False, None], dtype="boolean"),
|
| 116 |
+
"d": pd.Series([None, 100.5, 200], dtype="Float64"),
|
| 117 |
+
}
|
| 118 |
+
)
|
| 119 |
+
result = df.convert_dtypes(dtype_backend="pyarrow")
|
| 120 |
+
expected = pd.DataFrame(
|
| 121 |
+
{
|
| 122 |
+
"a": pd.arrays.ArrowExtensionArray(
|
| 123 |
+
pa.array([1, 2, None], type=pa.int32())
|
| 124 |
+
),
|
| 125 |
+
"b": pd.arrays.ArrowExtensionArray(pa.array(["x", "y", None])),
|
| 126 |
+
"c": pd.arrays.ArrowExtensionArray(pa.array([True, False, None])),
|
| 127 |
+
"d": pd.arrays.ArrowExtensionArray(pa.array([None, 100.5, 200.0])),
|
| 128 |
+
}
|
| 129 |
+
)
|
| 130 |
+
tm.assert_frame_equal(result, expected)
|
| 131 |
+
|
| 132 |
+
def test_pyarrow_dtype_empty_object(self):
|
| 133 |
+
# GH 50970
|
| 134 |
+
pytest.importorskip("pyarrow")
|
| 135 |
+
expected = pd.DataFrame(columns=[0])
|
| 136 |
+
result = expected.convert_dtypes(dtype_backend="pyarrow")
|
| 137 |
+
tm.assert_frame_equal(result, expected)
|
| 138 |
+
|
| 139 |
+
def test_pyarrow_engine_lines_false(self):
|
| 140 |
+
# GH 48893
|
| 141 |
+
df = pd.DataFrame({"a": [1, 2, 3]})
|
| 142 |
+
msg = (
|
| 143 |
+
"dtype_backend numpy is invalid, only 'numpy_nullable' and "
|
| 144 |
+
"'pyarrow' are allowed."
|
| 145 |
+
)
|
| 146 |
+
with pytest.raises(ValueError, match=msg):
|
| 147 |
+
df.convert_dtypes(dtype_backend="numpy")
|
| 148 |
+
|
| 149 |
+
def test_pyarrow_backend_no_conversion(self):
|
| 150 |
+
# GH#52872
|
| 151 |
+
pytest.importorskip("pyarrow")
|
| 152 |
+
df = pd.DataFrame({"a": [1, 2], "b": 1.5, "c": True, "d": "x"})
|
| 153 |
+
expected = df.copy()
|
| 154 |
+
result = df.convert_dtypes(
|
| 155 |
+
convert_floating=False,
|
| 156 |
+
convert_integer=False,
|
| 157 |
+
convert_boolean=False,
|
| 158 |
+
convert_string=False,
|
| 159 |
+
dtype_backend="pyarrow",
|
| 160 |
+
)
|
| 161 |
+
tm.assert_frame_equal(result, expected)
|
| 162 |
+
|
| 163 |
+
def test_convert_dtypes_pyarrow_to_np_nullable(self):
|
| 164 |
+
# GH 53648
|
| 165 |
+
pytest.importorskip("pyarrow")
|
| 166 |
+
ser = pd.DataFrame(range(2), dtype="int32[pyarrow]")
|
| 167 |
+
result = ser.convert_dtypes(dtype_backend="numpy_nullable")
|
| 168 |
+
expected = pd.DataFrame(range(2), dtype="Int32")
|
| 169 |
+
tm.assert_frame_equal(result, expected)
|
| 170 |
+
|
| 171 |
+
def test_convert_dtypes_pyarrow_timestamp(self):
|
| 172 |
+
# GH 54191
|
| 173 |
+
pytest.importorskip("pyarrow")
|
| 174 |
+
ser = pd.Series(pd.date_range("2020-01-01", "2020-01-02", freq="1min"))
|
| 175 |
+
expected = ser.astype("timestamp[ms][pyarrow]")
|
| 176 |
+
result = expected.convert_dtypes(dtype_backend="pyarrow")
|
| 177 |
+
tm.assert_series_equal(result, expected)
|
| 178 |
+
|
| 179 |
+
def test_convert_dtypes_avoid_block_splitting(self):
|
| 180 |
+
# GH#55341
|
| 181 |
+
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": "a"})
|
| 182 |
+
result = df.convert_dtypes(convert_integer=False)
|
| 183 |
+
expected = pd.DataFrame(
|
| 184 |
+
{
|
| 185 |
+
"a": [1, 2, 3],
|
| 186 |
+
"b": [4, 5, 6],
|
| 187 |
+
"c": pd.Series(["a"] * 3, dtype="string[python]"),
|
| 188 |
+
}
|
| 189 |
+
)
|
| 190 |
+
tm.assert_frame_equal(result, expected)
|
| 191 |
+
assert result._mgr.nblocks == 2
|
| 192 |
+
|
| 193 |
+
def test_convert_dtypes_from_arrow(self):
|
| 194 |
+
# GH#56581
|
| 195 |
+
df = pd.DataFrame([["a", datetime.time(18, 12)]], columns=["a", "b"])
|
| 196 |
+
result = df.convert_dtypes()
|
| 197 |
+
expected = df.astype({"a": "string[python]"})
|
| 198 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_copy.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas.util._test_decorators as td
|
| 5 |
+
|
| 6 |
+
from pandas import DataFrame
|
| 7 |
+
import pandas._testing as tm
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestCopy:
|
| 11 |
+
@pytest.mark.parametrize("attr", ["index", "columns"])
|
| 12 |
+
def test_copy_index_name_checking(self, float_frame, attr):
|
| 13 |
+
# don't want to be able to modify the index stored elsewhere after
|
| 14 |
+
# making a copy
|
| 15 |
+
ind = getattr(float_frame, attr)
|
| 16 |
+
ind.name = None
|
| 17 |
+
cp = float_frame.copy()
|
| 18 |
+
getattr(cp, attr).name = "foo"
|
| 19 |
+
assert getattr(float_frame, attr).name is None
|
| 20 |
+
|
| 21 |
+
@td.skip_copy_on_write_invalid_test
|
| 22 |
+
def test_copy_cache(self):
|
| 23 |
+
# GH#31784 _item_cache not cleared on copy causes incorrect reads after updates
|
| 24 |
+
df = DataFrame({"a": [1]})
|
| 25 |
+
|
| 26 |
+
df["x"] = [0]
|
| 27 |
+
df["a"]
|
| 28 |
+
|
| 29 |
+
df.copy()
|
| 30 |
+
|
| 31 |
+
df["a"].values[0] = -1
|
| 32 |
+
|
| 33 |
+
tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0]}))
|
| 34 |
+
|
| 35 |
+
df["y"] = [0]
|
| 36 |
+
|
| 37 |
+
assert df["a"].values[0] == -1
|
| 38 |
+
tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0], "y": [0]}))
|
| 39 |
+
|
| 40 |
+
def test_copy(self, float_frame, float_string_frame):
|
| 41 |
+
cop = float_frame.copy()
|
| 42 |
+
cop["E"] = cop["A"]
|
| 43 |
+
assert "E" not in float_frame
|
| 44 |
+
|
| 45 |
+
# copy objects
|
| 46 |
+
copy = float_string_frame.copy()
|
| 47 |
+
assert copy._mgr is not float_string_frame._mgr
|
| 48 |
+
|
| 49 |
+
@td.skip_array_manager_invalid_test
|
| 50 |
+
def test_copy_consolidates(self):
|
| 51 |
+
# GH#42477
|
| 52 |
+
df = DataFrame(
|
| 53 |
+
{
|
| 54 |
+
"a": np.random.default_rng(2).integers(0, 100, size=55),
|
| 55 |
+
"b": np.random.default_rng(2).integers(0, 100, size=55),
|
| 56 |
+
}
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
for i in range(10):
|
| 60 |
+
df.loc[:, f"n_{i}"] = np.random.default_rng(2).integers(0, 100, size=55)
|
| 61 |
+
|
| 62 |
+
assert len(df._mgr.blocks) == 11
|
| 63 |
+
result = df.copy()
|
| 64 |
+
assert len(result._mgr.blocks) == 1
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_count.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pandas import (
|
| 2 |
+
DataFrame,
|
| 3 |
+
Series,
|
| 4 |
+
)
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestDataFrameCount:
|
| 9 |
+
def test_count(self):
|
| 10 |
+
# corner case
|
| 11 |
+
frame = DataFrame()
|
| 12 |
+
ct1 = frame.count(1)
|
| 13 |
+
assert isinstance(ct1, Series)
|
| 14 |
+
|
| 15 |
+
ct2 = frame.count(0)
|
| 16 |
+
assert isinstance(ct2, Series)
|
| 17 |
+
|
| 18 |
+
# GH#423
|
| 19 |
+
df = DataFrame(index=range(10))
|
| 20 |
+
result = df.count(1)
|
| 21 |
+
expected = Series(0, index=df.index)
|
| 22 |
+
tm.assert_series_equal(result, expected)
|
| 23 |
+
|
| 24 |
+
df = DataFrame(columns=range(10))
|
| 25 |
+
result = df.count(0)
|
| 26 |
+
expected = Series(0, index=df.columns)
|
| 27 |
+
tm.assert_series_equal(result, expected)
|
| 28 |
+
|
| 29 |
+
df = DataFrame()
|
| 30 |
+
result = df.count()
|
| 31 |
+
expected = Series(dtype="int64")
|
| 32 |
+
tm.assert_series_equal(result, expected)
|
| 33 |
+
|
| 34 |
+
def test_count_objects(self, float_string_frame):
|
| 35 |
+
dm = DataFrame(float_string_frame._series)
|
| 36 |
+
df = DataFrame(float_string_frame._series)
|
| 37 |
+
|
| 38 |
+
tm.assert_series_equal(dm.count(), df.count())
|
| 39 |
+
tm.assert_series_equal(dm.count(1), df.count(1))
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_cov_corr.py
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas.util._test_decorators as td
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from pandas import (
|
| 8 |
+
DataFrame,
|
| 9 |
+
Index,
|
| 10 |
+
Series,
|
| 11 |
+
date_range,
|
| 12 |
+
isna,
|
| 13 |
+
)
|
| 14 |
+
import pandas._testing as tm
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TestDataFrameCov:
|
| 18 |
+
def test_cov(self, float_frame, float_string_frame):
|
| 19 |
+
# min_periods no NAs (corner case)
|
| 20 |
+
expected = float_frame.cov()
|
| 21 |
+
result = float_frame.cov(min_periods=len(float_frame))
|
| 22 |
+
|
| 23 |
+
tm.assert_frame_equal(expected, result)
|
| 24 |
+
|
| 25 |
+
result = float_frame.cov(min_periods=len(float_frame) + 1)
|
| 26 |
+
assert isna(result.values).all()
|
| 27 |
+
|
| 28 |
+
# with NAs
|
| 29 |
+
frame = float_frame.copy()
|
| 30 |
+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
|
| 31 |
+
frame.iloc[5:10, frame.columns.get_loc("B")] = np.nan
|
| 32 |
+
result = frame.cov(min_periods=len(frame) - 8)
|
| 33 |
+
expected = frame.cov()
|
| 34 |
+
expected.loc["A", "B"] = np.nan
|
| 35 |
+
expected.loc["B", "A"] = np.nan
|
| 36 |
+
tm.assert_frame_equal(result, expected)
|
| 37 |
+
|
| 38 |
+
# regular
|
| 39 |
+
result = frame.cov()
|
| 40 |
+
expected = frame["A"].cov(frame["C"])
|
| 41 |
+
tm.assert_almost_equal(result["A"]["C"], expected)
|
| 42 |
+
|
| 43 |
+
# fails on non-numeric types
|
| 44 |
+
with pytest.raises(ValueError, match="could not convert string to float"):
|
| 45 |
+
float_string_frame.cov()
|
| 46 |
+
result = float_string_frame.cov(numeric_only=True)
|
| 47 |
+
expected = float_string_frame.loc[:, ["A", "B", "C", "D"]].cov()
|
| 48 |
+
tm.assert_frame_equal(result, expected)
|
| 49 |
+
|
| 50 |
+
# Single column frame
|
| 51 |
+
df = DataFrame(np.linspace(0.0, 1.0, 10))
|
| 52 |
+
result = df.cov()
|
| 53 |
+
expected = DataFrame(
|
| 54 |
+
np.cov(df.values.T).reshape((1, 1)), index=df.columns, columns=df.columns
|
| 55 |
+
)
|
| 56 |
+
tm.assert_frame_equal(result, expected)
|
| 57 |
+
df.loc[0] = np.nan
|
| 58 |
+
result = df.cov()
|
| 59 |
+
expected = DataFrame(
|
| 60 |
+
np.cov(df.values[1:].T).reshape((1, 1)),
|
| 61 |
+
index=df.columns,
|
| 62 |
+
columns=df.columns,
|
| 63 |
+
)
|
| 64 |
+
tm.assert_frame_equal(result, expected)
|
| 65 |
+
|
| 66 |
+
@pytest.mark.parametrize("test_ddof", [None, 0, 1, 2, 3])
|
| 67 |
+
def test_cov_ddof(self, test_ddof):
|
| 68 |
+
# GH#34611
|
| 69 |
+
np_array1 = np.random.default_rng(2).random(10)
|
| 70 |
+
np_array2 = np.random.default_rng(2).random(10)
|
| 71 |
+
df = DataFrame({0: np_array1, 1: np_array2})
|
| 72 |
+
result = df.cov(ddof=test_ddof)
|
| 73 |
+
expected_np = np.cov(np_array1, np_array2, ddof=test_ddof)
|
| 74 |
+
expected = DataFrame(expected_np)
|
| 75 |
+
tm.assert_frame_equal(result, expected)
|
| 76 |
+
|
| 77 |
+
@pytest.mark.parametrize(
|
| 78 |
+
"other_column", [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0])]
|
| 79 |
+
)
|
| 80 |
+
def test_cov_nullable_integer(self, other_column):
|
| 81 |
+
# https://github.com/pandas-dev/pandas/issues/33803
|
| 82 |
+
data = DataFrame({"a": pd.array([1, 2, None]), "b": other_column})
|
| 83 |
+
result = data.cov()
|
| 84 |
+
arr = np.array([[0.5, 0.5], [0.5, 1.0]])
|
| 85 |
+
expected = DataFrame(arr, columns=["a", "b"], index=["a", "b"])
|
| 86 |
+
tm.assert_frame_equal(result, expected)
|
| 87 |
+
|
| 88 |
+
@pytest.mark.parametrize("numeric_only", [True, False])
|
| 89 |
+
def test_cov_numeric_only(self, numeric_only):
|
| 90 |
+
# when dtypes of pandas series are different
|
| 91 |
+
# then ndarray will have dtype=object,
|
| 92 |
+
# so it need to be properly handled
|
| 93 |
+
df = DataFrame({"a": [1, 0], "c": ["x", "y"]})
|
| 94 |
+
expected = DataFrame(0.5, index=["a"], columns=["a"])
|
| 95 |
+
if numeric_only:
|
| 96 |
+
result = df.cov(numeric_only=numeric_only)
|
| 97 |
+
tm.assert_frame_equal(result, expected)
|
| 98 |
+
else:
|
| 99 |
+
with pytest.raises(ValueError, match="could not convert string to float"):
|
| 100 |
+
df.cov(numeric_only=numeric_only)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class TestDataFrameCorr:
|
| 104 |
+
# DataFrame.corr(), as opposed to DataFrame.corrwith
|
| 105 |
+
|
| 106 |
+
@pytest.mark.parametrize("method", ["pearson", "kendall", "spearman"])
|
| 107 |
+
def test_corr_scipy_method(self, float_frame, method):
|
| 108 |
+
pytest.importorskip("scipy")
|
| 109 |
+
float_frame.loc[float_frame.index[:5], "A"] = np.nan
|
| 110 |
+
float_frame.loc[float_frame.index[5:10], "B"] = np.nan
|
| 111 |
+
float_frame.loc[float_frame.index[:10], "A"] = float_frame["A"][10:20].copy()
|
| 112 |
+
|
| 113 |
+
correls = float_frame.corr(method=method)
|
| 114 |
+
expected = float_frame["A"].corr(float_frame["C"], method=method)
|
| 115 |
+
tm.assert_almost_equal(correls["A"]["C"], expected)
|
| 116 |
+
|
| 117 |
+
# ---------------------------------------------------------------------
|
| 118 |
+
|
| 119 |
+
def test_corr_non_numeric(self, float_string_frame):
|
| 120 |
+
with pytest.raises(ValueError, match="could not convert string to float"):
|
| 121 |
+
float_string_frame.corr()
|
| 122 |
+
result = float_string_frame.corr(numeric_only=True)
|
| 123 |
+
expected = float_string_frame.loc[:, ["A", "B", "C", "D"]].corr()
|
| 124 |
+
tm.assert_frame_equal(result, expected)
|
| 125 |
+
|
| 126 |
+
@pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"])
|
| 127 |
+
def test_corr_nooverlap(self, meth):
|
| 128 |
+
# nothing in common
|
| 129 |
+
pytest.importorskip("scipy")
|
| 130 |
+
df = DataFrame(
|
| 131 |
+
{
|
| 132 |
+
"A": [1, 1.5, 1, np.nan, np.nan, np.nan],
|
| 133 |
+
"B": [np.nan, np.nan, np.nan, 1, 1.5, 1],
|
| 134 |
+
"C": [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
|
| 135 |
+
}
|
| 136 |
+
)
|
| 137 |
+
rs = df.corr(meth)
|
| 138 |
+
assert isna(rs.loc["A", "B"])
|
| 139 |
+
assert isna(rs.loc["B", "A"])
|
| 140 |
+
assert rs.loc["A", "A"] == 1
|
| 141 |
+
assert rs.loc["B", "B"] == 1
|
| 142 |
+
assert isna(rs.loc["C", "C"])
|
| 143 |
+
|
| 144 |
+
@pytest.mark.parametrize("meth", ["pearson", "spearman"])
|
| 145 |
+
def test_corr_constant(self, meth):
|
| 146 |
+
# constant --> all NA
|
| 147 |
+
df = DataFrame(
|
| 148 |
+
{
|
| 149 |
+
"A": [1, 1, 1, np.nan, np.nan, np.nan],
|
| 150 |
+
"B": [np.nan, np.nan, np.nan, 1, 1, 1],
|
| 151 |
+
}
|
| 152 |
+
)
|
| 153 |
+
rs = df.corr(meth)
|
| 154 |
+
assert isna(rs.values).all()
|
| 155 |
+
|
| 156 |
+
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
|
| 157 |
+
@pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"])
|
| 158 |
+
def test_corr_int_and_boolean(self, meth):
|
| 159 |
+
# when dtypes of pandas series are different
|
| 160 |
+
# then ndarray will have dtype=object,
|
| 161 |
+
# so it need to be properly handled
|
| 162 |
+
pytest.importorskip("scipy")
|
| 163 |
+
df = DataFrame({"a": [True, False], "b": [1, 0]})
|
| 164 |
+
|
| 165 |
+
expected = DataFrame(np.ones((2, 2)), index=["a", "b"], columns=["a", "b"])
|
| 166 |
+
result = df.corr(meth)
|
| 167 |
+
tm.assert_frame_equal(result, expected)
|
| 168 |
+
|
| 169 |
+
@pytest.mark.parametrize("method", ["cov", "corr"])
|
| 170 |
+
def test_corr_cov_independent_index_column(self, method):
|
| 171 |
+
# GH#14617
|
| 172 |
+
df = DataFrame(
|
| 173 |
+
np.random.default_rng(2).standard_normal(4 * 10).reshape(10, 4),
|
| 174 |
+
columns=list("abcd"),
|
| 175 |
+
)
|
| 176 |
+
result = getattr(df, method)()
|
| 177 |
+
assert result.index is not result.columns
|
| 178 |
+
assert result.index.equals(result.columns)
|
| 179 |
+
|
| 180 |
+
def test_corr_invalid_method(self):
|
| 181 |
+
# GH#22298
|
| 182 |
+
df = DataFrame(np.random.default_rng(2).normal(size=(10, 2)))
|
| 183 |
+
msg = "method must be either 'pearson', 'spearman', 'kendall', or a callable, "
|
| 184 |
+
with pytest.raises(ValueError, match=msg):
|
| 185 |
+
df.corr(method="____")
|
| 186 |
+
|
| 187 |
+
def test_corr_int(self):
|
| 188 |
+
# dtypes other than float64 GH#1761
|
| 189 |
+
df = DataFrame({"a": [1, 2, 3, 4], "b": [1, 2, 3, 4]})
|
| 190 |
+
|
| 191 |
+
df.cov()
|
| 192 |
+
df.corr()
|
| 193 |
+
|
| 194 |
+
@pytest.mark.parametrize(
|
| 195 |
+
"nullable_column", [pd.array([1, 2, 3]), pd.array([1, 2, None])]
|
| 196 |
+
)
|
| 197 |
+
@pytest.mark.parametrize(
|
| 198 |
+
"other_column",
|
| 199 |
+
[pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]), np.array([1.0, 2.0, np.nan])],
|
| 200 |
+
)
|
| 201 |
+
@pytest.mark.parametrize("method", ["pearson", "spearman", "kendall"])
|
| 202 |
+
def test_corr_nullable_integer(self, nullable_column, other_column, method):
|
| 203 |
+
# https://github.com/pandas-dev/pandas/issues/33803
|
| 204 |
+
pytest.importorskip("scipy")
|
| 205 |
+
data = DataFrame({"a": nullable_column, "b": other_column})
|
| 206 |
+
result = data.corr(method=method)
|
| 207 |
+
expected = DataFrame(np.ones((2, 2)), columns=["a", "b"], index=["a", "b"])
|
| 208 |
+
tm.assert_frame_equal(result, expected)
|
| 209 |
+
|
| 210 |
+
def test_corr_item_cache(self, using_copy_on_write, warn_copy_on_write):
|
| 211 |
+
# Check that corr does not lead to incorrect entries in item_cache
|
| 212 |
+
|
| 213 |
+
df = DataFrame({"A": range(10)})
|
| 214 |
+
df["B"] = range(10)[::-1]
|
| 215 |
+
|
| 216 |
+
ser = df["A"] # populate item_cache
|
| 217 |
+
assert len(df._mgr.arrays) == 2 # i.e. 2 blocks
|
| 218 |
+
|
| 219 |
+
_ = df.corr(numeric_only=True)
|
| 220 |
+
|
| 221 |
+
if using_copy_on_write:
|
| 222 |
+
ser.iloc[0] = 99
|
| 223 |
+
assert df.loc[0, "A"] == 0
|
| 224 |
+
else:
|
| 225 |
+
# Check that the corr didn't break link between ser and df
|
| 226 |
+
ser.values[0] = 99
|
| 227 |
+
assert df.loc[0, "A"] == 99
|
| 228 |
+
if not warn_copy_on_write:
|
| 229 |
+
assert df["A"] is ser
|
| 230 |
+
assert df.values[0, 0] == 99
|
| 231 |
+
|
| 232 |
+
@pytest.mark.parametrize("length", [2, 20, 200, 2000])
|
| 233 |
+
def test_corr_for_constant_columns(self, length):
|
| 234 |
+
# GH: 37448
|
| 235 |
+
df = DataFrame(length * [[0.4, 0.1]], columns=["A", "B"])
|
| 236 |
+
result = df.corr()
|
| 237 |
+
expected = DataFrame(
|
| 238 |
+
{"A": [np.nan, np.nan], "B": [np.nan, np.nan]}, index=["A", "B"]
|
| 239 |
+
)
|
| 240 |
+
tm.assert_frame_equal(result, expected)
|
| 241 |
+
|
| 242 |
+
def test_calc_corr_small_numbers(self):
|
| 243 |
+
# GH: 37452
|
| 244 |
+
df = DataFrame(
|
| 245 |
+
{"A": [1.0e-20, 2.0e-20, 3.0e-20], "B": [1.0e-20, 2.0e-20, 3.0e-20]}
|
| 246 |
+
)
|
| 247 |
+
result = df.corr()
|
| 248 |
+
expected = DataFrame({"A": [1.0, 1.0], "B": [1.0, 1.0]}, index=["A", "B"])
|
| 249 |
+
tm.assert_frame_equal(result, expected)
|
| 250 |
+
|
| 251 |
+
@pytest.mark.parametrize("method", ["pearson", "spearman", "kendall"])
|
| 252 |
+
def test_corr_min_periods_greater_than_length(self, method):
|
| 253 |
+
pytest.importorskip("scipy")
|
| 254 |
+
df = DataFrame({"A": [1, 2], "B": [1, 2]})
|
| 255 |
+
result = df.corr(method=method, min_periods=3)
|
| 256 |
+
expected = DataFrame(
|
| 257 |
+
{"A": [np.nan, np.nan], "B": [np.nan, np.nan]}, index=["A", "B"]
|
| 258 |
+
)
|
| 259 |
+
tm.assert_frame_equal(result, expected)
|
| 260 |
+
|
| 261 |
+
@pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"])
|
| 262 |
+
@pytest.mark.parametrize("numeric_only", [True, False])
|
| 263 |
+
def test_corr_numeric_only(self, meth, numeric_only):
|
| 264 |
+
# when dtypes of pandas series are different
|
| 265 |
+
# then ndarray will have dtype=object,
|
| 266 |
+
# so it need to be properly handled
|
| 267 |
+
pytest.importorskip("scipy")
|
| 268 |
+
df = DataFrame({"a": [1, 0], "b": [1, 0], "c": ["x", "y"]})
|
| 269 |
+
expected = DataFrame(np.ones((2, 2)), index=["a", "b"], columns=["a", "b"])
|
| 270 |
+
if numeric_only:
|
| 271 |
+
result = df.corr(meth, numeric_only=numeric_only)
|
| 272 |
+
tm.assert_frame_equal(result, expected)
|
| 273 |
+
else:
|
| 274 |
+
with pytest.raises(ValueError, match="could not convert string to float"):
|
| 275 |
+
df.corr(meth, numeric_only=numeric_only)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class TestDataFrameCorrWith:
|
| 279 |
+
@pytest.mark.parametrize(
|
| 280 |
+
"dtype",
|
| 281 |
+
[
|
| 282 |
+
"float64",
|
| 283 |
+
"Float64",
|
| 284 |
+
pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow")),
|
| 285 |
+
],
|
| 286 |
+
)
|
| 287 |
+
def test_corrwith(self, datetime_frame, dtype):
|
| 288 |
+
datetime_frame = datetime_frame.astype(dtype)
|
| 289 |
+
|
| 290 |
+
a = datetime_frame
|
| 291 |
+
noise = Series(np.random.default_rng(2).standard_normal(len(a)), index=a.index)
|
| 292 |
+
|
| 293 |
+
b = datetime_frame.add(noise, axis=0)
|
| 294 |
+
|
| 295 |
+
# make sure order does not matter
|
| 296 |
+
b = b.reindex(columns=b.columns[::-1], index=b.index[::-1][10:])
|
| 297 |
+
del b["B"]
|
| 298 |
+
|
| 299 |
+
colcorr = a.corrwith(b, axis=0)
|
| 300 |
+
tm.assert_almost_equal(colcorr["A"], a["A"].corr(b["A"]))
|
| 301 |
+
|
| 302 |
+
rowcorr = a.corrwith(b, axis=1)
|
| 303 |
+
tm.assert_series_equal(rowcorr, a.T.corrwith(b.T, axis=0))
|
| 304 |
+
|
| 305 |
+
dropped = a.corrwith(b, axis=0, drop=True)
|
| 306 |
+
tm.assert_almost_equal(dropped["A"], a["A"].corr(b["A"]))
|
| 307 |
+
assert "B" not in dropped
|
| 308 |
+
|
| 309 |
+
dropped = a.corrwith(b, axis=1, drop=True)
|
| 310 |
+
assert a.index[-1] not in dropped.index
|
| 311 |
+
|
| 312 |
+
# non time-series data
|
| 313 |
+
index = ["a", "b", "c", "d", "e"]
|
| 314 |
+
columns = ["one", "two", "three", "four"]
|
| 315 |
+
df1 = DataFrame(
|
| 316 |
+
np.random.default_rng(2).standard_normal((5, 4)),
|
| 317 |
+
index=index,
|
| 318 |
+
columns=columns,
|
| 319 |
+
)
|
| 320 |
+
df2 = DataFrame(
|
| 321 |
+
np.random.default_rng(2).standard_normal((4, 4)),
|
| 322 |
+
index=index[:4],
|
| 323 |
+
columns=columns,
|
| 324 |
+
)
|
| 325 |
+
correls = df1.corrwith(df2, axis=1)
|
| 326 |
+
for row in index[:4]:
|
| 327 |
+
tm.assert_almost_equal(correls[row], df1.loc[row].corr(df2.loc[row]))
|
| 328 |
+
|
| 329 |
+
def test_corrwith_with_objects(self, using_infer_string):
|
| 330 |
+
df1 = DataFrame(
|
| 331 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
| 332 |
+
columns=Index(list("ABCD"), dtype=object),
|
| 333 |
+
index=date_range("2000-01-01", periods=10, freq="B"),
|
| 334 |
+
)
|
| 335 |
+
df2 = df1.copy()
|
| 336 |
+
cols = ["A", "B", "C", "D"]
|
| 337 |
+
|
| 338 |
+
df1["obj"] = "foo"
|
| 339 |
+
df2["obj"] = "bar"
|
| 340 |
+
|
| 341 |
+
if using_infer_string:
|
| 342 |
+
msg = "Cannot perform reduction 'mean' with string dtype"
|
| 343 |
+
with pytest.raises(TypeError, match=msg):
|
| 344 |
+
df1.corrwith(df2)
|
| 345 |
+
else:
|
| 346 |
+
with pytest.raises(TypeError, match="Could not convert"):
|
| 347 |
+
df1.corrwith(df2)
|
| 348 |
+
result = df1.corrwith(df2, numeric_only=True)
|
| 349 |
+
expected = df1.loc[:, cols].corrwith(df2.loc[:, cols])
|
| 350 |
+
tm.assert_series_equal(result, expected)
|
| 351 |
+
|
| 352 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 353 |
+
df1.corrwith(df2, axis=1)
|
| 354 |
+
result = df1.corrwith(df2, axis=1, numeric_only=True)
|
| 355 |
+
expected = df1.loc[:, cols].corrwith(df2.loc[:, cols], axis=1)
|
| 356 |
+
tm.assert_series_equal(result, expected)
|
| 357 |
+
|
| 358 |
+
def test_corrwith_series(self, datetime_frame):
|
| 359 |
+
result = datetime_frame.corrwith(datetime_frame["A"])
|
| 360 |
+
expected = datetime_frame.apply(datetime_frame["A"].corr)
|
| 361 |
+
|
| 362 |
+
tm.assert_series_equal(result, expected)
|
| 363 |
+
|
| 364 |
+
def test_corrwith_matches_corrcoef(self):
|
| 365 |
+
df1 = DataFrame(np.arange(10000), columns=["a"])
|
| 366 |
+
df2 = DataFrame(np.arange(10000) ** 2, columns=["a"])
|
| 367 |
+
c1 = df1.corrwith(df2)["a"]
|
| 368 |
+
c2 = np.corrcoef(df1["a"], df2["a"])[0][1]
|
| 369 |
+
|
| 370 |
+
tm.assert_almost_equal(c1, c2)
|
| 371 |
+
assert c1 < 1
|
| 372 |
+
|
| 373 |
+
@pytest.mark.parametrize("numeric_only", [True, False])
|
| 374 |
+
def test_corrwith_mixed_dtypes(self, numeric_only):
|
| 375 |
+
# GH#18570
|
| 376 |
+
df = DataFrame(
|
| 377 |
+
{"a": [1, 4, 3, 2], "b": [4, 6, 7, 3], "c": ["a", "b", "c", "d"]}
|
| 378 |
+
)
|
| 379 |
+
s = Series([0, 6, 7, 3])
|
| 380 |
+
if numeric_only:
|
| 381 |
+
result = df.corrwith(s, numeric_only=numeric_only)
|
| 382 |
+
corrs = [df["a"].corr(s), df["b"].corr(s)]
|
| 383 |
+
expected = Series(data=corrs, index=["a", "b"])
|
| 384 |
+
tm.assert_series_equal(result, expected)
|
| 385 |
+
else:
|
| 386 |
+
with pytest.raises(
|
| 387 |
+
ValueError,
|
| 388 |
+
match="could not convert string to float",
|
| 389 |
+
):
|
| 390 |
+
df.corrwith(s, numeric_only=numeric_only)
|
| 391 |
+
|
| 392 |
+
def test_corrwith_index_intersection(self):
|
| 393 |
+
df1 = DataFrame(
|
| 394 |
+
np.random.default_rng(2).random(size=(10, 2)), columns=["a", "b"]
|
| 395 |
+
)
|
| 396 |
+
df2 = DataFrame(
|
| 397 |
+
np.random.default_rng(2).random(size=(10, 3)), columns=["a", "b", "c"]
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
result = df1.corrwith(df2, drop=True).index.sort_values()
|
| 401 |
+
expected = df1.columns.intersection(df2.columns).sort_values()
|
| 402 |
+
tm.assert_index_equal(result, expected)
|
| 403 |
+
|
| 404 |
+
def test_corrwith_index_union(self):
|
| 405 |
+
df1 = DataFrame(
|
| 406 |
+
np.random.default_rng(2).random(size=(10, 2)), columns=["a", "b"]
|
| 407 |
+
)
|
| 408 |
+
df2 = DataFrame(
|
| 409 |
+
np.random.default_rng(2).random(size=(10, 3)), columns=["a", "b", "c"]
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
result = df1.corrwith(df2, drop=False).index.sort_values()
|
| 413 |
+
expected = df1.columns.union(df2.columns).sort_values()
|
| 414 |
+
tm.assert_index_equal(result, expected)
|
| 415 |
+
|
| 416 |
+
def test_corrwith_dup_cols(self):
|
| 417 |
+
# GH#21925
|
| 418 |
+
df1 = DataFrame(np.vstack([np.arange(10)] * 3).T)
|
| 419 |
+
df2 = df1.copy()
|
| 420 |
+
df2 = pd.concat((df2, df2[0]), axis=1)
|
| 421 |
+
|
| 422 |
+
result = df1.corrwith(df2)
|
| 423 |
+
expected = Series(np.ones(4), index=[0, 0, 1, 2])
|
| 424 |
+
tm.assert_series_equal(result, expected)
|
| 425 |
+
|
| 426 |
+
def test_corr_numerical_instabilities(self):
|
| 427 |
+
# GH#45640
|
| 428 |
+
df = DataFrame([[0.2, 0.4], [0.4, 0.2]])
|
| 429 |
+
result = df.corr()
|
| 430 |
+
expected = DataFrame({0: [1.0, -1.0], 1: [-1.0, 1.0]})
|
| 431 |
+
tm.assert_frame_equal(result - 1, expected - 1, atol=1e-17)
|
| 432 |
+
|
| 433 |
+
def test_corrwith_spearman(self):
|
| 434 |
+
# GH#21925
|
| 435 |
+
pytest.importorskip("scipy")
|
| 436 |
+
df = DataFrame(np.random.default_rng(2).random(size=(100, 3)))
|
| 437 |
+
result = df.corrwith(df**2, method="spearman")
|
| 438 |
+
expected = Series(np.ones(len(result)))
|
| 439 |
+
tm.assert_series_equal(result, expected)
|
| 440 |
+
|
| 441 |
+
def test_corrwith_kendall(self):
|
| 442 |
+
# GH#21925
|
| 443 |
+
pytest.importorskip("scipy")
|
| 444 |
+
df = DataFrame(np.random.default_rng(2).random(size=(100, 3)))
|
| 445 |
+
result = df.corrwith(df**2, method="kendall")
|
| 446 |
+
expected = Series(np.ones(len(result)))
|
| 447 |
+
tm.assert_series_equal(result, expected)
|
| 448 |
+
|
| 449 |
+
def test_corrwith_spearman_with_tied_data(self):
|
| 450 |
+
# GH#48826
|
| 451 |
+
pytest.importorskip("scipy")
|
| 452 |
+
df1 = DataFrame(
|
| 453 |
+
{
|
| 454 |
+
"A": [1, np.nan, 7, 8],
|
| 455 |
+
"B": [False, True, True, False],
|
| 456 |
+
"C": [10, 4, 9, 3],
|
| 457 |
+
}
|
| 458 |
+
)
|
| 459 |
+
df2 = df1[["B", "C"]]
|
| 460 |
+
result = (df1 + 1).corrwith(df2.B, method="spearman")
|
| 461 |
+
expected = Series([0.0, 1.0, 0.0], index=["A", "B", "C"])
|
| 462 |
+
tm.assert_series_equal(result, expected)
|
| 463 |
+
|
| 464 |
+
df_bool = DataFrame(
|
| 465 |
+
{"A": [True, True, False, False], "B": [True, False, False, True]}
|
| 466 |
+
)
|
| 467 |
+
ser_bool = Series([True, True, False, True])
|
| 468 |
+
result = df_bool.corrwith(ser_bool)
|
| 469 |
+
expected = Series([0.57735, 0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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas import (
|
| 6 |
+
Categorical,
|
| 7 |
+
DataFrame,
|
| 8 |
+
Series,
|
| 9 |
+
Timestamp,
|
| 10 |
+
date_range,
|
| 11 |
+
)
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TestDataFrameDescribe:
|
| 16 |
+
def test_describe_bool_in_mixed_frame(self):
|
| 17 |
+
df = DataFrame(
|
| 18 |
+
{
|
| 19 |
+
"string_data": ["a", "b", "c", "d", "e"],
|
| 20 |
+
"bool_data": [True, True, False, False, False],
|
| 21 |
+
"int_data": [10, 20, 30, 40, 50],
|
| 22 |
+
}
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
# Integer data are included in .describe() output,
|
| 26 |
+
# Boolean and string data are not.
|
| 27 |
+
result = df.describe()
|
| 28 |
+
expected = DataFrame(
|
| 29 |
+
{"int_data": [5, 30, df.int_data.std(), 10, 20, 30, 40, 50]},
|
| 30 |
+
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
|
| 31 |
+
)
|
| 32 |
+
tm.assert_frame_equal(result, expected)
|
| 33 |
+
|
| 34 |
+
# Top value is a boolean value that is False
|
| 35 |
+
result = df.describe(include=["bool"])
|
| 36 |
+
|
| 37 |
+
expected = DataFrame(
|
| 38 |
+
{"bool_data": [5, 2, False, 3]}, index=["count", "unique", "top", "freq"]
|
| 39 |
+
)
|
| 40 |
+
tm.assert_frame_equal(result, expected)
|
| 41 |
+
|
| 42 |
+
def test_describe_empty_object(self):
|
| 43 |
+
# GH#27183
|
| 44 |
+
df = DataFrame({"A": [None, None]}, dtype=object)
|
| 45 |
+
result = df.describe()
|
| 46 |
+
expected = DataFrame(
|
| 47 |
+
{"A": [0, 0, np.nan, np.nan]},
|
| 48 |
+
dtype=object,
|
| 49 |
+
index=["count", "unique", "top", "freq"],
|
| 50 |
+
)
|
| 51 |
+
tm.assert_frame_equal(result, expected)
|
| 52 |
+
|
| 53 |
+
result = df.iloc[:0].describe()
|
| 54 |
+
tm.assert_frame_equal(result, expected)
|
| 55 |
+
|
| 56 |
+
def test_describe_bool_frame(self):
|
| 57 |
+
# GH#13891
|
| 58 |
+
df = DataFrame(
|
| 59 |
+
{
|
| 60 |
+
"bool_data_1": [False, False, True, True],
|
| 61 |
+
"bool_data_2": [False, True, True, True],
|
| 62 |
+
}
|
| 63 |
+
)
|
| 64 |
+
result = df.describe()
|
| 65 |
+
expected = DataFrame(
|
| 66 |
+
{"bool_data_1": [4, 2, False, 2], "bool_data_2": [4, 2, True, 3]},
|
| 67 |
+
index=["count", "unique", "top", "freq"],
|
| 68 |
+
)
|
| 69 |
+
tm.assert_frame_equal(result, expected)
|
| 70 |
+
|
| 71 |
+
df = DataFrame(
|
| 72 |
+
{
|
| 73 |
+
"bool_data": [False, False, True, True, False],
|
| 74 |
+
"int_data": [0, 1, 2, 3, 4],
|
| 75 |
+
}
|
| 76 |
+
)
|
| 77 |
+
result = df.describe()
|
| 78 |
+
expected = DataFrame(
|
| 79 |
+
{"int_data": [5, 2, df.int_data.std(), 0, 1, 2, 3, 4]},
|
| 80 |
+
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
|
| 81 |
+
)
|
| 82 |
+
tm.assert_frame_equal(result, expected)
|
| 83 |
+
|
| 84 |
+
df = DataFrame(
|
| 85 |
+
{"bool_data": [False, False, True, True], "str_data": ["a", "b", "c", "a"]}
|
| 86 |
+
)
|
| 87 |
+
result = df.describe()
|
| 88 |
+
expected = DataFrame(
|
| 89 |
+
{"bool_data": [4, 2, False, 2], "str_data": [4, 3, "a", 2]},
|
| 90 |
+
index=["count", "unique", "top", "freq"],
|
| 91 |
+
)
|
| 92 |
+
tm.assert_frame_equal(result, expected)
|
| 93 |
+
|
| 94 |
+
def test_describe_categorical(self):
|
| 95 |
+
df = DataFrame({"value": np.random.default_rng(2).integers(0, 10000, 100)})
|
| 96 |
+
labels = [f"{i} - {i + 499}" for i in range(0, 10000, 500)]
|
| 97 |
+
cat_labels = Categorical(labels, labels)
|
| 98 |
+
|
| 99 |
+
df = df.sort_values(by=["value"], ascending=True)
|
| 100 |
+
df["value_group"] = pd.cut(
|
| 101 |
+
df.value, range(0, 10500, 500), right=False, labels=cat_labels
|
| 102 |
+
)
|
| 103 |
+
cat = df
|
| 104 |
+
|
| 105 |
+
# Categoricals should not show up together with numerical columns
|
| 106 |
+
result = cat.describe()
|
| 107 |
+
assert len(result.columns) == 1
|
| 108 |
+
|
| 109 |
+
# In a frame, describe() for the cat should be the same as for string
|
| 110 |
+
# arrays (count, unique, top, freq)
|
| 111 |
+
|
| 112 |
+
cat = Categorical(
|
| 113 |
+
["a", "b", "b", "b"], categories=["a", "b", "c"], ordered=True
|
| 114 |
+
)
|
| 115 |
+
s = Series(cat)
|
| 116 |
+
result = s.describe()
|
| 117 |
+
expected = Series([4, 2, "b", 3], index=["count", "unique", "top", "freq"])
|
| 118 |
+
tm.assert_series_equal(result, expected)
|
| 119 |
+
|
| 120 |
+
cat = Series(Categorical(["a", "b", "c", "c"]))
|
| 121 |
+
df3 = DataFrame({"cat": cat, "s": ["a", "b", "c", "c"]})
|
| 122 |
+
result = df3.describe()
|
| 123 |
+
tm.assert_numpy_array_equal(result["cat"].values, result["s"].values)
|
| 124 |
+
|
| 125 |
+
def test_describe_empty_categorical_column(self):
|
| 126 |
+
# GH#26397
|
| 127 |
+
# Ensure the index of an empty categorical DataFrame column
|
| 128 |
+
# also contains (count, unique, top, freq)
|
| 129 |
+
df = DataFrame({"empty_col": Categorical([])})
|
| 130 |
+
result = df.describe()
|
| 131 |
+
expected = DataFrame(
|
| 132 |
+
{"empty_col": [0, 0, np.nan, np.nan]},
|
| 133 |
+
index=["count", "unique", "top", "freq"],
|
| 134 |
+
dtype="object",
|
| 135 |
+
)
|
| 136 |
+
tm.assert_frame_equal(result, expected)
|
| 137 |
+
# ensure NaN, not None
|
| 138 |
+
assert np.isnan(result.iloc[2, 0])
|
| 139 |
+
assert np.isnan(result.iloc[3, 0])
|
| 140 |
+
|
| 141 |
+
def test_describe_categorical_columns(self):
|
| 142 |
+
# GH#11558
|
| 143 |
+
columns = pd.CategoricalIndex(["int1", "int2", "obj"], ordered=True, name="XXX")
|
| 144 |
+
df = DataFrame(
|
| 145 |
+
{
|
| 146 |
+
"int1": [10, 20, 30, 40, 50],
|
| 147 |
+
"int2": [10, 20, 30, 40, 50],
|
| 148 |
+
"obj": ["A", 0, None, "X", 1],
|
| 149 |
+
},
|
| 150 |
+
columns=columns,
|
| 151 |
+
)
|
| 152 |
+
result = df.describe()
|
| 153 |
+
|
| 154 |
+
exp_columns = pd.CategoricalIndex(
|
| 155 |
+
["int1", "int2"],
|
| 156 |
+
categories=["int1", "int2", "obj"],
|
| 157 |
+
ordered=True,
|
| 158 |
+
name="XXX",
|
| 159 |
+
)
|
| 160 |
+
expected = DataFrame(
|
| 161 |
+
{
|
| 162 |
+
"int1": [5, 30, df.int1.std(), 10, 20, 30, 40, 50],
|
| 163 |
+
"int2": [5, 30, df.int2.std(), 10, 20, 30, 40, 50],
|
| 164 |
+
},
|
| 165 |
+
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
|
| 166 |
+
columns=exp_columns,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
tm.assert_frame_equal(result, expected)
|
| 170 |
+
tm.assert_categorical_equal(result.columns.values, expected.columns.values)
|
| 171 |
+
|
| 172 |
+
def test_describe_datetime_columns(self):
|
| 173 |
+
columns = pd.DatetimeIndex(
|
| 174 |
+
["2011-01-01", "2011-02-01", "2011-03-01"],
|
| 175 |
+
freq="MS",
|
| 176 |
+
tz="US/Eastern",
|
| 177 |
+
name="XXX",
|
| 178 |
+
)
|
| 179 |
+
df = DataFrame(
|
| 180 |
+
{
|
| 181 |
+
0: [10, 20, 30, 40, 50],
|
| 182 |
+
1: [10, 20, 30, 40, 50],
|
| 183 |
+
2: ["A", 0, None, "X", 1],
|
| 184 |
+
}
|
| 185 |
+
)
|
| 186 |
+
df.columns = columns
|
| 187 |
+
result = df.describe()
|
| 188 |
+
|
| 189 |
+
exp_columns = pd.DatetimeIndex(
|
| 190 |
+
["2011-01-01", "2011-02-01"], freq="MS", tz="US/Eastern", name="XXX"
|
| 191 |
+
)
|
| 192 |
+
expected = DataFrame(
|
| 193 |
+
{
|
| 194 |
+
0: [5, 30, df.iloc[:, 0].std(), 10, 20, 30, 40, 50],
|
| 195 |
+
1: [5, 30, df.iloc[:, 1].std(), 10, 20, 30, 40, 50],
|
| 196 |
+
},
|
| 197 |
+
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
|
| 198 |
+
)
|
| 199 |
+
expected.columns = exp_columns
|
| 200 |
+
tm.assert_frame_equal(result, expected)
|
| 201 |
+
assert result.columns.freq == "MS"
|
| 202 |
+
assert result.columns.tz == expected.columns.tz
|
| 203 |
+
|
| 204 |
+
def test_describe_timedelta_values(self):
|
| 205 |
+
# GH#6145
|
| 206 |
+
t1 = pd.timedelta_range("1 days", freq="D", periods=5)
|
| 207 |
+
t2 = pd.timedelta_range("1 hours", freq="h", periods=5)
|
| 208 |
+
df = DataFrame({"t1": t1, "t2": t2})
|
| 209 |
+
|
| 210 |
+
expected = DataFrame(
|
| 211 |
+
{
|
| 212 |
+
"t1": [
|
| 213 |
+
5,
|
| 214 |
+
pd.Timedelta("3 days"),
|
| 215 |
+
df.iloc[:, 0].std(),
|
| 216 |
+
pd.Timedelta("1 days"),
|
| 217 |
+
pd.Timedelta("2 days"),
|
| 218 |
+
pd.Timedelta("3 days"),
|
| 219 |
+
pd.Timedelta("4 days"),
|
| 220 |
+
pd.Timedelta("5 days"),
|
| 221 |
+
],
|
| 222 |
+
"t2": [
|
| 223 |
+
5,
|
| 224 |
+
pd.Timedelta("3 hours"),
|
| 225 |
+
df.iloc[:, 1].std(),
|
| 226 |
+
pd.Timedelta("1 hours"),
|
| 227 |
+
pd.Timedelta("2 hours"),
|
| 228 |
+
pd.Timedelta("3 hours"),
|
| 229 |
+
pd.Timedelta("4 hours"),
|
| 230 |
+
pd.Timedelta("5 hours"),
|
| 231 |
+
],
|
| 232 |
+
},
|
| 233 |
+
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
result = df.describe()
|
| 237 |
+
tm.assert_frame_equal(result, expected)
|
| 238 |
+
|
| 239 |
+
exp_repr = (
|
| 240 |
+
" t1 t2\n"
|
| 241 |
+
"count 5 5\n"
|
| 242 |
+
"mean 3 days 00:00:00 0 days 03:00:00\n"
|
| 243 |
+
"std 1 days 13:56:50.394919273 0 days 01:34:52.099788303\n"
|
| 244 |
+
"min 1 days 00:00:00 0 days 01:00:00\n"
|
| 245 |
+
"25% 2 days 00:00:00 0 days 02:00:00\n"
|
| 246 |
+
"50% 3 days 00:00:00 0 days 03:00:00\n"
|
| 247 |
+
"75% 4 days 00:00:00 0 days 04:00:00\n"
|
| 248 |
+
"max 5 days 00:00:00 0 days 05:00:00"
|
| 249 |
+
)
|
| 250 |
+
assert repr(result) == exp_repr
|
| 251 |
+
|
| 252 |
+
def test_describe_tz_values(self, tz_naive_fixture):
|
| 253 |
+
# GH#21332
|
| 254 |
+
tz = tz_naive_fixture
|
| 255 |
+
s1 = Series(range(5))
|
| 256 |
+
start = Timestamp(2018, 1, 1)
|
| 257 |
+
end = Timestamp(2018, 1, 5)
|
| 258 |
+
s2 = Series(date_range(start, end, tz=tz))
|
| 259 |
+
df = DataFrame({"s1": s1, "s2": s2})
|
| 260 |
+
|
| 261 |
+
expected = DataFrame(
|
| 262 |
+
{
|
| 263 |
+
"s1": [5, 2, 0, 1, 2, 3, 4, 1.581139],
|
| 264 |
+
"s2": [
|
| 265 |
+
5,
|
| 266 |
+
Timestamp(2018, 1, 3).tz_localize(tz),
|
| 267 |
+
start.tz_localize(tz),
|
| 268 |
+
s2[1],
|
| 269 |
+
s2[2],
|
| 270 |
+
s2[3],
|
| 271 |
+
end.tz_localize(tz),
|
| 272 |
+
np.nan,
|
| 273 |
+
],
|
| 274 |
+
},
|
| 275 |
+
index=["count", "mean", "min", "25%", "50%", "75%", "max", "std"],
|
| 276 |
+
)
|
| 277 |
+
result = df.describe(include="all")
|
| 278 |
+
tm.assert_frame_equal(result, expected)
|
| 279 |
+
|
| 280 |
+
def test_datetime_is_numeric_includes_datetime(self):
|
| 281 |
+
df = DataFrame({"a": date_range("2012", periods=3), "b": [1, 2, 3]})
|
| 282 |
+
result = df.describe()
|
| 283 |
+
expected = DataFrame(
|
| 284 |
+
{
|
| 285 |
+
"a": [
|
| 286 |
+
3,
|
| 287 |
+
Timestamp("2012-01-02"),
|
| 288 |
+
Timestamp("2012-01-01"),
|
| 289 |
+
Timestamp("2012-01-01T12:00:00"),
|
| 290 |
+
Timestamp("2012-01-02"),
|
| 291 |
+
Timestamp("2012-01-02T12:00:00"),
|
| 292 |
+
Timestamp("2012-01-03"),
|
| 293 |
+
np.nan,
|
| 294 |
+
],
|
| 295 |
+
"b": [3, 2, 1, 1.5, 2, 2.5, 3, 1],
|
| 296 |
+
},
|
| 297 |
+
index=["count", "mean", "min", "25%", "50%", "75%", "max", "std"],
|
| 298 |
+
)
|
| 299 |
+
tm.assert_frame_equal(result, expected)
|
| 300 |
+
|
| 301 |
+
def test_describe_tz_values2(self):
|
| 302 |
+
tz = "CET"
|
| 303 |
+
s1 = Series(range(5))
|
| 304 |
+
start = Timestamp(2018, 1, 1)
|
| 305 |
+
end = Timestamp(2018, 1, 5)
|
| 306 |
+
s2 = Series(date_range(start, end, tz=tz))
|
| 307 |
+
df = DataFrame({"s1": s1, "s2": s2})
|
| 308 |
+
|
| 309 |
+
s1_ = s1.describe()
|
| 310 |
+
s2_ = s2.describe()
|
| 311 |
+
idx = [
|
| 312 |
+
"count",
|
| 313 |
+
"mean",
|
| 314 |
+
"min",
|
| 315 |
+
"25%",
|
| 316 |
+
"50%",
|
| 317 |
+
"75%",
|
| 318 |
+
"max",
|
| 319 |
+
"std",
|
| 320 |
+
]
|
| 321 |
+
expected = pd.concat([s1_, s2_], axis=1, keys=["s1", "s2"]).reindex(
|
| 322 |
+
idx, copy=False
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
result = df.describe(include="all")
|
| 326 |
+
tm.assert_frame_equal(result, expected)
|
| 327 |
+
|
| 328 |
+
def test_describe_percentiles_integer_idx(self):
|
| 329 |
+
# GH#26660
|
| 330 |
+
df = DataFrame({"x": [1]})
|
| 331 |
+
pct = np.linspace(0, 1, 10 + 1)
|
| 332 |
+
result = df.describe(percentiles=pct)
|
| 333 |
+
|
| 334 |
+
expected = DataFrame(
|
| 335 |
+
{"x": [1.0, 1.0, np.nan, 1.0, *(1.0 for _ in pct), 1.0]},
|
| 336 |
+
index=[
|
| 337 |
+
"count",
|
| 338 |
+
"mean",
|
| 339 |
+
"std",
|
| 340 |
+
"min",
|
| 341 |
+
"0%",
|
| 342 |
+
"10%",
|
| 343 |
+
"20%",
|
| 344 |
+
"30%",
|
| 345 |
+
"40%",
|
| 346 |
+
"50%",
|
| 347 |
+
"60%",
|
| 348 |
+
"70%",
|
| 349 |
+
"80%",
|
| 350 |
+
"90%",
|
| 351 |
+
"100%",
|
| 352 |
+
"max",
|
| 353 |
+
],
|
| 354 |
+
)
|
| 355 |
+
tm.assert_frame_equal(result, expected)
|
| 356 |
+
|
| 357 |
+
def test_describe_does_not_raise_error_for_dictlike_elements(self):
|
| 358 |
+
# GH#32409
|
| 359 |
+
df = DataFrame([{"test": {"a": "1"}}, {"test": {"a": "2"}}])
|
| 360 |
+
expected = DataFrame(
|
| 361 |
+
{"test": [2, 2, {"a": "1"}, 1]}, index=["count", "unique", "top", "freq"]
|
| 362 |
+
)
|
| 363 |
+
result = df.describe()
|
| 364 |
+
tm.assert_frame_equal(result, expected)
|
| 365 |
+
|
| 366 |
+
@pytest.mark.parametrize("exclude", ["x", "y", ["x", "y"], ["x", "z"]])
|
| 367 |
+
def test_describe_when_include_all_exclude_not_allowed(self, exclude):
|
| 368 |
+
"""
|
| 369 |
+
When include is 'all', then setting exclude != None is not allowed.
|
| 370 |
+
"""
|
| 371 |
+
df = DataFrame({"x": [1], "y": [2], "z": [3]})
|
| 372 |
+
msg = "exclude must be None when include is 'all'"
|
| 373 |
+
with pytest.raises(ValueError, match=msg):
|
| 374 |
+
df.describe(include="all", exclude=exclude)
|
| 375 |
+
|
| 376 |
+
def test_describe_with_duplicate_columns(self):
|
| 377 |
+
df = DataFrame(
|
| 378 |
+
[[1, 1, 1], [2, 2, 2], [3, 3, 3]],
|
| 379 |
+
columns=["bar", "a", "a"],
|
| 380 |
+
dtype="float64",
|
| 381 |
+
)
|
| 382 |
+
result = df.describe()
|
| 383 |
+
ser = df.iloc[:, 0].describe()
|
| 384 |
+
expected = pd.concat([ser, ser, ser], keys=df.columns, axis=1)
|
| 385 |
+
tm.assert_frame_equal(result, expected)
|
| 386 |
+
|
| 387 |
+
def test_ea_with_na(self, any_numeric_ea_dtype):
|
| 388 |
+
# GH#48778
|
| 389 |
+
|
| 390 |
+
df = DataFrame({"a": [1, pd.NA, pd.NA], "b": pd.NA}, dtype=any_numeric_ea_dtype)
|
| 391 |
+
result = df.describe()
|
| 392 |
+
expected = DataFrame(
|
| 393 |
+
{"a": [1.0, 1.0, pd.NA] + [1.0] * 5, "b": [0.0] + [pd.NA] * 7},
|
| 394 |
+
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
|
| 395 |
+
dtype="Float64",
|
| 396 |
+
)
|
| 397 |
+
tm.assert_frame_equal(result, expected)
|
| 398 |
+
|
| 399 |
+
def test_describe_exclude_pa_dtype(self):
|
| 400 |
+
# GH#52570
|
| 401 |
+
pa = pytest.importorskip("pyarrow")
|
| 402 |
+
df = DataFrame(
|
| 403 |
+
{
|
| 404 |
+
"a": Series([1, 2, 3], dtype=pd.ArrowDtype(pa.int8())),
|
| 405 |
+
"b": Series([1, 2, 3], dtype=pd.ArrowDtype(pa.int16())),
|
| 406 |
+
"c": Series([1, 2, 3], dtype=pd.ArrowDtype(pa.int32())),
|
| 407 |
+
}
|
| 408 |
+
)
|
| 409 |
+
result = df.describe(
|
| 410 |
+
include=pd.ArrowDtype(pa.int8()), exclude=pd.ArrowDtype(pa.int32())
|
| 411 |
+
)
|
| 412 |
+
expected = DataFrame(
|
| 413 |
+
{"a": [3, 2, 1, 1, 1.5, 2, 2.5, 3]},
|
| 414 |
+
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
|
| 415 |
+
dtype=pd.ArrowDtype(pa.float64()),
|
| 416 |
+
)
|
| 417 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_diff.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas import (
|
| 6 |
+
DataFrame,
|
| 7 |
+
Series,
|
| 8 |
+
Timestamp,
|
| 9 |
+
date_range,
|
| 10 |
+
)
|
| 11 |
+
import pandas._testing as tm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestDataFrameDiff:
|
| 15 |
+
def test_diff_requires_integer(self):
|
| 16 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((2, 2)))
|
| 17 |
+
with pytest.raises(ValueError, match="periods must be an integer"):
|
| 18 |
+
df.diff(1.5)
|
| 19 |
+
|
| 20 |
+
# GH#44572 np.int64 is accepted
|
| 21 |
+
@pytest.mark.parametrize("num", [1, np.int64(1)])
|
| 22 |
+
def test_diff(self, datetime_frame, num):
|
| 23 |
+
df = datetime_frame
|
| 24 |
+
the_diff = df.diff(num)
|
| 25 |
+
|
| 26 |
+
expected = df["A"] - df["A"].shift(num)
|
| 27 |
+
tm.assert_series_equal(the_diff["A"], expected)
|
| 28 |
+
|
| 29 |
+
def test_diff_int_dtype(self):
|
| 30 |
+
# int dtype
|
| 31 |
+
a = 10_000_000_000_000_000
|
| 32 |
+
b = a + 1
|
| 33 |
+
ser = Series([a, b])
|
| 34 |
+
|
| 35 |
+
rs = DataFrame({"s": ser}).diff()
|
| 36 |
+
assert rs.s[1] == 1
|
| 37 |
+
|
| 38 |
+
def test_diff_mixed_numeric(self, datetime_frame):
|
| 39 |
+
# mixed numeric
|
| 40 |
+
tf = datetime_frame.astype("float32")
|
| 41 |
+
the_diff = tf.diff(1)
|
| 42 |
+
tm.assert_series_equal(the_diff["A"], tf["A"] - tf["A"].shift(1))
|
| 43 |
+
|
| 44 |
+
def test_diff_axis1_nonconsolidated(self):
|
| 45 |
+
# GH#10907
|
| 46 |
+
df = DataFrame({"y": Series([2]), "z": Series([3])})
|
| 47 |
+
df.insert(0, "x", 1)
|
| 48 |
+
result = df.diff(axis=1)
|
| 49 |
+
expected = DataFrame({"x": np.nan, "y": Series(1), "z": Series(1)})
|
| 50 |
+
tm.assert_frame_equal(result, expected)
|
| 51 |
+
|
| 52 |
+
def test_diff_timedelta64_with_nat(self):
|
| 53 |
+
# GH#32441
|
| 54 |
+
arr = np.arange(6).reshape(3, 2).astype("timedelta64[ns]")
|
| 55 |
+
arr[:, 0] = np.timedelta64("NaT", "ns")
|
| 56 |
+
|
| 57 |
+
df = DataFrame(arr)
|
| 58 |
+
result = df.diff(1, axis=0)
|
| 59 |
+
|
| 60 |
+
expected = DataFrame({0: df[0], 1: [pd.NaT, pd.Timedelta(2), pd.Timedelta(2)]})
|
| 61 |
+
tm.assert_equal(result, expected)
|
| 62 |
+
|
| 63 |
+
result = df.diff(0)
|
| 64 |
+
expected = df - df
|
| 65 |
+
assert expected[0].isna().all()
|
| 66 |
+
tm.assert_equal(result, expected)
|
| 67 |
+
|
| 68 |
+
result = df.diff(-1, axis=1)
|
| 69 |
+
expected = df * np.nan
|
| 70 |
+
tm.assert_equal(result, expected)
|
| 71 |
+
|
| 72 |
+
@pytest.mark.parametrize("tz", [None, "UTC"])
|
| 73 |
+
def test_diff_datetime_axis0_with_nat(self, tz, unit):
|
| 74 |
+
# GH#32441
|
| 75 |
+
dti = pd.DatetimeIndex(["NaT", "2019-01-01", "2019-01-02"], tz=tz).as_unit(unit)
|
| 76 |
+
ser = Series(dti)
|
| 77 |
+
|
| 78 |
+
df = ser.to_frame()
|
| 79 |
+
|
| 80 |
+
result = df.diff()
|
| 81 |
+
ex_index = pd.TimedeltaIndex([pd.NaT, pd.NaT, pd.Timedelta(days=1)]).as_unit(
|
| 82 |
+
unit
|
| 83 |
+
)
|
| 84 |
+
expected = Series(ex_index).to_frame()
|
| 85 |
+
tm.assert_frame_equal(result, expected)
|
| 86 |
+
|
| 87 |
+
@pytest.mark.parametrize("tz", [None, "UTC"])
|
| 88 |
+
def test_diff_datetime_with_nat_zero_periods(self, tz):
|
| 89 |
+
# diff on NaT values should give NaT, not timedelta64(0)
|
| 90 |
+
dti = date_range("2016-01-01", periods=4, tz=tz)
|
| 91 |
+
ser = Series(dti)
|
| 92 |
+
df = ser.to_frame().copy()
|
| 93 |
+
|
| 94 |
+
df[1] = ser.copy()
|
| 95 |
+
|
| 96 |
+
df.iloc[:, 0] = pd.NaT
|
| 97 |
+
|
| 98 |
+
expected = df - df
|
| 99 |
+
assert expected[0].isna().all()
|
| 100 |
+
|
| 101 |
+
result = df.diff(0, axis=0)
|
| 102 |
+
tm.assert_frame_equal(result, expected)
|
| 103 |
+
|
| 104 |
+
result = df.diff(0, axis=1)
|
| 105 |
+
tm.assert_frame_equal(result, expected)
|
| 106 |
+
|
| 107 |
+
@pytest.mark.parametrize("tz", [None, "UTC"])
|
| 108 |
+
def test_diff_datetime_axis0(self, tz):
|
| 109 |
+
# GH#18578
|
| 110 |
+
df = DataFrame(
|
| 111 |
+
{
|
| 112 |
+
0: date_range("2010", freq="D", periods=2, tz=tz),
|
| 113 |
+
1: date_range("2010", freq="D", periods=2, tz=tz),
|
| 114 |
+
}
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
result = df.diff(axis=0)
|
| 118 |
+
expected = DataFrame(
|
| 119 |
+
{
|
| 120 |
+
0: pd.TimedeltaIndex(["NaT", "1 days"]),
|
| 121 |
+
1: pd.TimedeltaIndex(["NaT", "1 days"]),
|
| 122 |
+
}
|
| 123 |
+
)
|
| 124 |
+
tm.assert_frame_equal(result, expected)
|
| 125 |
+
|
| 126 |
+
@pytest.mark.parametrize("tz", [None, "UTC"])
|
| 127 |
+
def test_diff_datetime_axis1(self, tz):
|
| 128 |
+
# GH#18578
|
| 129 |
+
df = DataFrame(
|
| 130 |
+
{
|
| 131 |
+
0: date_range("2010", freq="D", periods=2, tz=tz),
|
| 132 |
+
1: date_range("2010", freq="D", periods=2, tz=tz),
|
| 133 |
+
}
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
result = df.diff(axis=1)
|
| 137 |
+
expected = DataFrame(
|
| 138 |
+
{
|
| 139 |
+
0: pd.TimedeltaIndex(["NaT", "NaT"]),
|
| 140 |
+
1: pd.TimedeltaIndex(["0 days", "0 days"]),
|
| 141 |
+
}
|
| 142 |
+
)
|
| 143 |
+
tm.assert_frame_equal(result, expected)
|
| 144 |
+
|
| 145 |
+
def test_diff_timedelta(self, unit):
|
| 146 |
+
# GH#4533
|
| 147 |
+
df = DataFrame(
|
| 148 |
+
{
|
| 149 |
+
"time": [Timestamp("20130101 9:01"), Timestamp("20130101 9:02")],
|
| 150 |
+
"value": [1.0, 2.0],
|
| 151 |
+
}
|
| 152 |
+
)
|
| 153 |
+
df["time"] = df["time"].dt.as_unit(unit)
|
| 154 |
+
|
| 155 |
+
res = df.diff()
|
| 156 |
+
exp = DataFrame(
|
| 157 |
+
[[pd.NaT, np.nan], [pd.Timedelta("00:01:00"), 1]], columns=["time", "value"]
|
| 158 |
+
)
|
| 159 |
+
exp["time"] = exp["time"].dt.as_unit(unit)
|
| 160 |
+
tm.assert_frame_equal(res, exp)
|
| 161 |
+
|
| 162 |
+
def test_diff_mixed_dtype(self):
|
| 163 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
|
| 164 |
+
df["A"] = np.array([1, 2, 3, 4, 5], dtype=object)
|
| 165 |
+
|
| 166 |
+
result = df.diff()
|
| 167 |
+
assert result[0].dtype == np.float64
|
| 168 |
+
|
| 169 |
+
def test_diff_neg_n(self, datetime_frame):
|
| 170 |
+
rs = datetime_frame.diff(-1)
|
| 171 |
+
xp = datetime_frame - datetime_frame.shift(-1)
|
| 172 |
+
tm.assert_frame_equal(rs, xp)
|
| 173 |
+
|
| 174 |
+
def test_diff_float_n(self, datetime_frame):
|
| 175 |
+
rs = datetime_frame.diff(1.0)
|
| 176 |
+
xp = datetime_frame.diff(1)
|
| 177 |
+
tm.assert_frame_equal(rs, xp)
|
| 178 |
+
|
| 179 |
+
def test_diff_axis(self):
|
| 180 |
+
# GH#9727
|
| 181 |
+
df = DataFrame([[1.0, 2.0], [3.0, 4.0]])
|
| 182 |
+
tm.assert_frame_equal(
|
| 183 |
+
df.diff(axis=1), DataFrame([[np.nan, 1.0], [np.nan, 1.0]])
|
| 184 |
+
)
|
| 185 |
+
tm.assert_frame_equal(
|
| 186 |
+
df.diff(axis=0), DataFrame([[np.nan, np.nan], [2.0, 2.0]])
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
def test_diff_period(self):
|
| 190 |
+
# GH#32995 Don't pass an incorrect axis
|
| 191 |
+
pi = date_range("2016-01-01", periods=3).to_period("D")
|
| 192 |
+
df = DataFrame({"A": pi})
|
| 193 |
+
|
| 194 |
+
result = df.diff(1, axis=1)
|
| 195 |
+
|
| 196 |
+
expected = (df - pd.NaT).astype(object)
|
| 197 |
+
tm.assert_frame_equal(result, expected)
|
| 198 |
+
|
| 199 |
+
def test_diff_axis1_mixed_dtypes(self):
|
| 200 |
+
# GH#32995 operate column-wise when we have mixed dtypes and axis=1
|
| 201 |
+
df = DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)})
|
| 202 |
+
|
| 203 |
+
expected = DataFrame({"A": [np.nan, np.nan, np.nan], "B": df["B"] / 2})
|
| 204 |
+
|
| 205 |
+
result = df.diff(axis=1)
|
| 206 |
+
tm.assert_frame_equal(result, expected)
|
| 207 |
+
|
| 208 |
+
# GH#21437 mixed-float-dtypes
|
| 209 |
+
df = DataFrame(
|
| 210 |
+
{"a": np.arange(3, dtype="float32"), "b": np.arange(3, dtype="float64")}
|
| 211 |
+
)
|
| 212 |
+
result = df.diff(axis=1)
|
| 213 |
+
expected = DataFrame({"a": df["a"] * np.nan, "b": df["b"] * 0})
|
| 214 |
+
tm.assert_frame_equal(result, expected)
|
| 215 |
+
|
| 216 |
+
def test_diff_axis1_mixed_dtypes_large_periods(self):
|
| 217 |
+
# GH#32995 operate column-wise when we have mixed dtypes and axis=1
|
| 218 |
+
df = DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)})
|
| 219 |
+
|
| 220 |
+
expected = df * np.nan
|
| 221 |
+
|
| 222 |
+
result = df.diff(axis=1, periods=3)
|
| 223 |
+
tm.assert_frame_equal(result, expected)
|
| 224 |
+
|
| 225 |
+
def test_diff_axis1_mixed_dtypes_negative_periods(self):
|
| 226 |
+
# GH#32995 operate column-wise when we have mixed dtypes and axis=1
|
| 227 |
+
df = DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)})
|
| 228 |
+
|
| 229 |
+
expected = DataFrame({"A": -1.0 * df["A"], "B": df["B"] * np.nan})
|
| 230 |
+
|
| 231 |
+
result = df.diff(axis=1, periods=-1)
|
| 232 |
+
tm.assert_frame_equal(result, expected)
|
| 233 |
+
|
| 234 |
+
def test_diff_sparse(self):
|
| 235 |
+
# GH#28813 .diff() should work for sparse dataframes as well
|
| 236 |
+
sparse_df = DataFrame([[0, 1], [1, 0]], dtype="Sparse[int]")
|
| 237 |
+
|
| 238 |
+
result = sparse_df.diff()
|
| 239 |
+
expected = DataFrame(
|
| 240 |
+
[[np.nan, np.nan], [1.0, -1.0]], dtype=pd.SparseDtype("float", 0.0)
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
tm.assert_frame_equal(result, expected)
|
| 244 |
+
|
| 245 |
+
@pytest.mark.parametrize(
|
| 246 |
+
"axis,expected",
|
| 247 |
+
[
|
| 248 |
+
(
|
| 249 |
+
0,
|
| 250 |
+
DataFrame(
|
| 251 |
+
{
|
| 252 |
+
"a": [np.nan, 0, 1, 0, np.nan, np.nan, np.nan, 0],
|
| 253 |
+
"b": [np.nan, 1, np.nan, np.nan, -2, 1, np.nan, np.nan],
|
| 254 |
+
"c": np.repeat(np.nan, 8),
|
| 255 |
+
"d": [np.nan, 3, 5, 7, 9, 11, 13, 15],
|
| 256 |
+
},
|
| 257 |
+
dtype="Int64",
|
| 258 |
+
),
|
| 259 |
+
),
|
| 260 |
+
(
|
| 261 |
+
1,
|
| 262 |
+
DataFrame(
|
| 263 |
+
{
|
| 264 |
+
"a": np.repeat(np.nan, 8),
|
| 265 |
+
"b": [0, 1, np.nan, 1, np.nan, np.nan, np.nan, 0],
|
| 266 |
+
"c": np.repeat(np.nan, 8),
|
| 267 |
+
"d": np.repeat(np.nan, 8),
|
| 268 |
+
},
|
| 269 |
+
dtype="Int64",
|
| 270 |
+
),
|
| 271 |
+
),
|
| 272 |
+
],
|
| 273 |
+
)
|
| 274 |
+
def test_diff_integer_na(self, axis, expected):
|
| 275 |
+
# GH#24171 IntegerNA Support for DataFrame.diff()
|
| 276 |
+
df = DataFrame(
|
| 277 |
+
{
|
| 278 |
+
"a": np.repeat([0, 1, np.nan, 2], 2),
|
| 279 |
+
"b": np.tile([0, 1, np.nan, 2], 2),
|
| 280 |
+
"c": np.repeat(np.nan, 8),
|
| 281 |
+
"d": np.arange(1, 9) ** 2,
|
| 282 |
+
},
|
| 283 |
+
dtype="Int64",
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
# Test case for default behaviour of diff
|
| 287 |
+
result = df.diff(axis=axis)
|
| 288 |
+
tm.assert_frame_equal(result, expected)
|
| 289 |
+
|
| 290 |
+
def test_diff_readonly(self):
|
| 291 |
+
# https://github.com/pandas-dev/pandas/issues/35559
|
| 292 |
+
arr = np.random.default_rng(2).standard_normal((5, 2))
|
| 293 |
+
arr.flags.writeable = False
|
| 294 |
+
df = DataFrame(arr)
|
| 295 |
+
result = df.diff()
|
| 296 |
+
expected = DataFrame(np.array(df)).diff()
|
| 297 |
+
tm.assert_frame_equal(result, expected)
|
| 298 |
+
|
| 299 |
+
def test_diff_all_int_dtype(self, any_int_numpy_dtype):
|
| 300 |
+
# GH 14773
|
| 301 |
+
df = DataFrame(range(5))
|
| 302 |
+
df = df.astype(any_int_numpy_dtype)
|
| 303 |
+
result = df.diff()
|
| 304 |
+
expected_dtype = (
|
| 305 |
+
"float32" if any_int_numpy_dtype in ("int8", "int16") else "float64"
|
| 306 |
+
)
|
| 307 |
+
expected = DataFrame([np.nan, 1.0, 1.0, 1.0, 1.0], dtype=expected_dtype)
|
| 308 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_dot.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
raise NotImplementedError
|
| 15 |
+
|
| 16 |
+
@pytest.fixture
|
| 17 |
+
def other(self) -> DataFrame:
|
| 18 |
+
"""
|
| 19 |
+
other is a DataFrame that is indexed so that obj.dot(other) is valid
|
| 20 |
+
"""
|
| 21 |
+
raise NotImplementedError
|
| 22 |
+
|
| 23 |
+
@pytest.fixture
|
| 24 |
+
def expected(self, obj, other) -> DataFrame:
|
| 25 |
+
"""
|
| 26 |
+
The expected result of obj.dot(other)
|
| 27 |
+
"""
|
| 28 |
+
raise NotImplementedError
|
| 29 |
+
|
| 30 |
+
@classmethod
|
| 31 |
+
def reduced_dim_assert(cls, result, expected):
|
| 32 |
+
"""
|
| 33 |
+
Assertion about results with 1 fewer dimension that self.obj
|
| 34 |
+
"""
|
| 35 |
+
raise NotImplementedError
|
| 36 |
+
|
| 37 |
+
def test_dot_equiv_values_dot(self, obj, other, expected):
|
| 38 |
+
# `expected` is constructed from obj.values.dot(other.values)
|
| 39 |
+
result = obj.dot(other)
|
| 40 |
+
tm.assert_equal(result, expected)
|
| 41 |
+
|
| 42 |
+
def test_dot_2d_ndarray(self, obj, other, expected):
|
| 43 |
+
# Check ndarray argument; in this case we get matching values,
|
| 44 |
+
# but index/columns may not match
|
| 45 |
+
result = obj.dot(other.values)
|
| 46 |
+
assert np.all(result == expected.values)
|
| 47 |
+
|
| 48 |
+
def test_dot_1d_ndarray(self, obj, expected):
|
| 49 |
+
# can pass correct-length array
|
| 50 |
+
row = obj.iloc[0] if obj.ndim == 2 else obj
|
| 51 |
+
|
| 52 |
+
result = obj.dot(row.values)
|
| 53 |
+
expected = obj.dot(row)
|
| 54 |
+
self.reduced_dim_assert(result, expected)
|
| 55 |
+
|
| 56 |
+
def test_dot_series(self, obj, other, expected):
|
| 57 |
+
# Check series argument
|
| 58 |
+
result = obj.dot(other["1"])
|
| 59 |
+
self.reduced_dim_assert(result, expected["1"])
|
| 60 |
+
|
| 61 |
+
def test_dot_series_alignment(self, obj, other, expected):
|
| 62 |
+
result = obj.dot(other.iloc[::-1]["1"])
|
| 63 |
+
self.reduced_dim_assert(result, expected["1"])
|
| 64 |
+
|
| 65 |
+
def test_dot_aligns(self, obj, other, expected):
|
| 66 |
+
# Check index alignment
|
| 67 |
+
other2 = other.iloc[::-1]
|
| 68 |
+
result = obj.dot(other2)
|
| 69 |
+
tm.assert_equal(result, expected)
|
| 70 |
+
|
| 71 |
+
def test_dot_shape_mismatch(self, obj):
|
| 72 |
+
msg = "Dot product shape mismatch"
|
| 73 |
+
# exception raised is of type Exception
|
| 74 |
+
with pytest.raises(Exception, match=msg):
|
| 75 |
+
obj.dot(obj.values[:3])
|
| 76 |
+
|
| 77 |
+
def test_dot_misaligned(self, obj, other):
|
| 78 |
+
msg = "matrices are not aligned"
|
| 79 |
+
with pytest.raises(ValueError, match=msg):
|
| 80 |
+
obj.dot(other.T)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class TestSeriesDot(DotSharedTests):
|
| 84 |
+
@pytest.fixture
|
| 85 |
+
def obj(self):
|
| 86 |
+
return Series(
|
| 87 |
+
np.random.default_rng(2).standard_normal(4), index=["p", "q", "r", "s"]
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
@pytest.fixture
|
| 91 |
+
def other(self):
|
| 92 |
+
return DataFrame(
|
| 93 |
+
np.random.default_rng(2).standard_normal((3, 4)),
|
| 94 |
+
index=["1", "2", "3"],
|
| 95 |
+
columns=["p", "q", "r", "s"],
|
| 96 |
+
).T
|
| 97 |
+
|
| 98 |
+
@pytest.fixture
|
| 99 |
+
def expected(self, obj, other):
|
| 100 |
+
return Series(np.dot(obj.values, other.values), index=other.columns)
|
| 101 |
+
|
| 102 |
+
@classmethod
|
| 103 |
+
def reduced_dim_assert(cls, result, expected):
|
| 104 |
+
"""
|
| 105 |
+
Assertion about results with 1 fewer dimension that self.obj
|
| 106 |
+
"""
|
| 107 |
+
tm.assert_almost_equal(result, expected)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class TestDataFrameDot(DotSharedTests):
|
| 111 |
+
@pytest.fixture
|
| 112 |
+
def obj(self):
|
| 113 |
+
return DataFrame(
|
| 114 |
+
np.random.default_rng(2).standard_normal((3, 4)),
|
| 115 |
+
index=["a", "b", "c"],
|
| 116 |
+
columns=["p", "q", "r", "s"],
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
@pytest.fixture
|
| 120 |
+
def other(self):
|
| 121 |
+
return DataFrame(
|
| 122 |
+
np.random.default_rng(2).standard_normal((4, 2)),
|
| 123 |
+
index=["p", "q", "r", "s"],
|
| 124 |
+
columns=["1", "2"],
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
@pytest.fixture
|
| 128 |
+
def expected(self, obj, other):
|
| 129 |
+
return DataFrame(
|
| 130 |
+
np.dot(obj.values, other.values), index=obj.index, columns=other.columns
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
@classmethod
|
| 134 |
+
def reduced_dim_assert(cls, result, expected):
|
| 135 |
+
"""
|
| 136 |
+
Assertion about results with 1 fewer dimension that self.obj
|
| 137 |
+
"""
|
| 138 |
+
tm.assert_series_equal(result, expected, check_names=False)
|
| 139 |
+
assert result.name is None
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@pytest.mark.parametrize(
|
| 143 |
+
"dtype,exp_dtype",
|
| 144 |
+
[("Float32", "Float64"), ("Int16", "Int32"), ("float[pyarrow]", "double[pyarrow]")],
|
| 145 |
+
)
|
| 146 |
+
def test_arrow_dtype(dtype, exp_dtype):
|
| 147 |
+
pytest.importorskip("pyarrow")
|
| 148 |
+
|
| 149 |
+
cols = ["a", "b"]
|
| 150 |
+
df_a = DataFrame([[1, 2], [3, 4], [5, 6]], columns=cols, dtype="int32")
|
| 151 |
+
df_b = DataFrame([[1, 0], [0, 1]], index=cols, dtype=dtype)
|
| 152 |
+
result = df_a.dot(df_b)
|
| 153 |
+
expected = DataFrame([[1, 2], [3, 4], [5, 6]], dtype=exp_dtype)
|
| 154 |
+
|
| 155 |
+
tm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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas.errors import PerformanceWarning
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from pandas import (
|
| 10 |
+
DataFrame,
|
| 11 |
+
DatetimeIndex,
|
| 12 |
+
Index,
|
| 13 |
+
MultiIndex,
|
| 14 |
+
Series,
|
| 15 |
+
Timestamp,
|
| 16 |
+
)
|
| 17 |
+
import pandas._testing as tm
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.mark.parametrize(
|
| 21 |
+
"msg,labels,level",
|
| 22 |
+
[
|
| 23 |
+
(r"labels \[4\] not found in level", 4, "a"),
|
| 24 |
+
(r"labels \[7\] not found in level", 7, "b"),
|
| 25 |
+
],
|
| 26 |
+
)
|
| 27 |
+
def test_drop_raise_exception_if_labels_not_in_level(msg, labels, level):
|
| 28 |
+
# GH 8594
|
| 29 |
+
mi = MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"])
|
| 30 |
+
s = Series([10, 20, 30], index=mi)
|
| 31 |
+
df = DataFrame([10, 20, 30], index=mi)
|
| 32 |
+
|
| 33 |
+
with pytest.raises(KeyError, match=msg):
|
| 34 |
+
s.drop(labels, level=level)
|
| 35 |
+
with pytest.raises(KeyError, match=msg):
|
| 36 |
+
df.drop(labels, level=level)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize("labels,level", [(4, "a"), (7, "b")])
|
| 40 |
+
def test_drop_errors_ignore(labels, level):
|
| 41 |
+
# GH 8594
|
| 42 |
+
mi = MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"])
|
| 43 |
+
s = Series([10, 20, 30], index=mi)
|
| 44 |
+
df = DataFrame([10, 20, 30], index=mi)
|
| 45 |
+
|
| 46 |
+
expected_s = s.drop(labels, level=level, errors="ignore")
|
| 47 |
+
tm.assert_series_equal(s, expected_s)
|
| 48 |
+
|
| 49 |
+
expected_df = df.drop(labels, level=level, errors="ignore")
|
| 50 |
+
tm.assert_frame_equal(df, expected_df)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_drop_with_non_unique_datetime_index_and_invalid_keys():
|
| 54 |
+
# GH 30399
|
| 55 |
+
|
| 56 |
+
# define dataframe with unique datetime index
|
| 57 |
+
df = DataFrame(
|
| 58 |
+
np.random.default_rng(2).standard_normal((5, 3)),
|
| 59 |
+
columns=["a", "b", "c"],
|
| 60 |
+
index=pd.date_range("2012", freq="h", periods=5),
|
| 61 |
+
)
|
| 62 |
+
# create dataframe with non-unique datetime index
|
| 63 |
+
df = df.iloc[[0, 2, 2, 3]].copy()
|
| 64 |
+
|
| 65 |
+
with pytest.raises(KeyError, match="not found in axis"):
|
| 66 |
+
df.drop(["a", "b"]) # Dropping with labels not exist in the index
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class TestDataFrameDrop:
|
| 70 |
+
def test_drop_names(self):
|
| 71 |
+
df = DataFrame(
|
| 72 |
+
[[1, 2, 3], [3, 4, 5], [5, 6, 7]],
|
| 73 |
+
index=["a", "b", "c"],
|
| 74 |
+
columns=["d", "e", "f"],
|
| 75 |
+
)
|
| 76 |
+
df.index.name, df.columns.name = "first", "second"
|
| 77 |
+
df_dropped_b = df.drop("b")
|
| 78 |
+
df_dropped_e = df.drop("e", axis=1)
|
| 79 |
+
df_inplace_b, df_inplace_e = df.copy(), df.copy()
|
| 80 |
+
return_value = df_inplace_b.drop("b", inplace=True)
|
| 81 |
+
assert return_value is None
|
| 82 |
+
return_value = df_inplace_e.drop("e", axis=1, inplace=True)
|
| 83 |
+
assert return_value is None
|
| 84 |
+
for obj in (df_dropped_b, df_dropped_e, df_inplace_b, df_inplace_e):
|
| 85 |
+
assert obj.index.name == "first"
|
| 86 |
+
assert obj.columns.name == "second"
|
| 87 |
+
assert list(df.columns) == ["d", "e", "f"]
|
| 88 |
+
|
| 89 |
+
msg = r"\['g'\] not found in axis"
|
| 90 |
+
with pytest.raises(KeyError, match=msg):
|
| 91 |
+
df.drop(["g"])
|
| 92 |
+
with pytest.raises(KeyError, match=msg):
|
| 93 |
+
df.drop(["g"], axis=1)
|
| 94 |
+
|
| 95 |
+
# errors = 'ignore'
|
| 96 |
+
dropped = df.drop(["g"], errors="ignore")
|
| 97 |
+
expected = Index(["a", "b", "c"], name="first")
|
| 98 |
+
tm.assert_index_equal(dropped.index, expected)
|
| 99 |
+
|
| 100 |
+
dropped = df.drop(["b", "g"], errors="ignore")
|
| 101 |
+
expected = Index(["a", "c"], name="first")
|
| 102 |
+
tm.assert_index_equal(dropped.index, expected)
|
| 103 |
+
|
| 104 |
+
dropped = df.drop(["g"], axis=1, errors="ignore")
|
| 105 |
+
expected = Index(["d", "e", "f"], name="second")
|
| 106 |
+
tm.assert_index_equal(dropped.columns, expected)
|
| 107 |
+
|
| 108 |
+
dropped = df.drop(["d", "g"], axis=1, errors="ignore")
|
| 109 |
+
expected = Index(["e", "f"], name="second")
|
| 110 |
+
tm.assert_index_equal(dropped.columns, expected)
|
| 111 |
+
|
| 112 |
+
# GH 16398
|
| 113 |
+
dropped = df.drop([], errors="ignore")
|
| 114 |
+
expected = Index(["a", "b", "c"], name="first")
|
| 115 |
+
tm.assert_index_equal(dropped.index, expected)
|
| 116 |
+
|
| 117 |
+
def test_drop(self):
|
| 118 |
+
simple = DataFrame({"A": [1, 2, 3, 4], "B": [0, 1, 2, 3]})
|
| 119 |
+
tm.assert_frame_equal(simple.drop("A", axis=1), simple[["B"]])
|
| 120 |
+
tm.assert_frame_equal(simple.drop(["A", "B"], axis="columns"), simple[[]])
|
| 121 |
+
tm.assert_frame_equal(simple.drop([0, 1, 3], axis=0), simple.loc[[2], :])
|
| 122 |
+
tm.assert_frame_equal(simple.drop([0, 3], axis="index"), simple.loc[[1, 2], :])
|
| 123 |
+
|
| 124 |
+
with pytest.raises(KeyError, match=r"\[5\] not found in axis"):
|
| 125 |
+
simple.drop(5)
|
| 126 |
+
with pytest.raises(KeyError, match=r"\['C'\] not found in axis"):
|
| 127 |
+
simple.drop("C", axis=1)
|
| 128 |
+
with pytest.raises(KeyError, match=r"\[5\] not found in axis"):
|
| 129 |
+
simple.drop([1, 5])
|
| 130 |
+
with pytest.raises(KeyError, match=r"\['C'\] not found in axis"):
|
| 131 |
+
simple.drop(["A", "C"], axis=1)
|
| 132 |
+
|
| 133 |
+
# GH 42881
|
| 134 |
+
with pytest.raises(KeyError, match=r"\['C', 'D', 'F'\] not found in axis"):
|
| 135 |
+
simple.drop(["C", "D", "F"], axis=1)
|
| 136 |
+
|
| 137 |
+
# errors = 'ignore'
|
| 138 |
+
tm.assert_frame_equal(simple.drop(5, errors="ignore"), simple)
|
| 139 |
+
tm.assert_frame_equal(
|
| 140 |
+
simple.drop([0, 5], errors="ignore"), simple.loc[[1, 2, 3], :]
|
| 141 |
+
)
|
| 142 |
+
tm.assert_frame_equal(simple.drop("C", axis=1, errors="ignore"), simple)
|
| 143 |
+
tm.assert_frame_equal(
|
| 144 |
+
simple.drop(["A", "C"], axis=1, errors="ignore"), simple[["B"]]
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# non-unique - wheee!
|
| 148 |
+
nu_df = DataFrame(
|
| 149 |
+
list(zip(range(3), range(-3, 1), list("abc"))), columns=["a", "a", "b"]
|
| 150 |
+
)
|
| 151 |
+
tm.assert_frame_equal(nu_df.drop("a", axis=1), nu_df[["b"]])
|
| 152 |
+
tm.assert_frame_equal(nu_df.drop("b", axis="columns"), nu_df["a"])
|
| 153 |
+
tm.assert_frame_equal(nu_df.drop([]), nu_df) # GH 16398
|
| 154 |
+
|
| 155 |
+
nu_df = nu_df.set_index(Index(["X", "Y", "X"]))
|
| 156 |
+
nu_df.columns = list("abc")
|
| 157 |
+
tm.assert_frame_equal(nu_df.drop("X", axis="rows"), nu_df.loc[["Y"], :])
|
| 158 |
+
tm.assert_frame_equal(nu_df.drop(["X", "Y"], axis=0), nu_df.loc[[], :])
|
| 159 |
+
|
| 160 |
+
# inplace cache issue
|
| 161 |
+
# GH#5628
|
| 162 |
+
df = DataFrame(
|
| 163 |
+
np.random.default_rng(2).standard_normal((10, 3)), columns=list("abc")
|
| 164 |
+
)
|
| 165 |
+
expected = df[~(df.b > 0)]
|
| 166 |
+
return_value = df.drop(labels=df[df.b > 0].index, inplace=True)
|
| 167 |
+
assert return_value is None
|
| 168 |
+
tm.assert_frame_equal(df, expected)
|
| 169 |
+
|
| 170 |
+
def test_drop_multiindex_not_lexsorted(self):
|
| 171 |
+
# GH#11640
|
| 172 |
+
|
| 173 |
+
# define the lexsorted version
|
| 174 |
+
lexsorted_mi = MultiIndex.from_tuples(
|
| 175 |
+
[("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"]
|
| 176 |
+
)
|
| 177 |
+
lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi)
|
| 178 |
+
assert lexsorted_df.columns._is_lexsorted()
|
| 179 |
+
|
| 180 |
+
# define the non-lexsorted version
|
| 181 |
+
not_lexsorted_df = DataFrame(
|
| 182 |
+
columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]]
|
| 183 |
+
)
|
| 184 |
+
not_lexsorted_df = not_lexsorted_df.pivot_table(
|
| 185 |
+
index="a", columns=["b", "c"], values="d"
|
| 186 |
+
)
|
| 187 |
+
not_lexsorted_df = not_lexsorted_df.reset_index()
|
| 188 |
+
assert not not_lexsorted_df.columns._is_lexsorted()
|
| 189 |
+
|
| 190 |
+
expected = lexsorted_df.drop("a", axis=1).astype(float)
|
| 191 |
+
with tm.assert_produces_warning(PerformanceWarning):
|
| 192 |
+
result = not_lexsorted_df.drop("a", axis=1)
|
| 193 |
+
|
| 194 |
+
tm.assert_frame_equal(result, expected)
|
| 195 |
+
|
| 196 |
+
def test_drop_api_equivalence(self):
|
| 197 |
+
# equivalence of the labels/axis and index/columns API's (GH#12392)
|
| 198 |
+
df = DataFrame(
|
| 199 |
+
[[1, 2, 3], [3, 4, 5], [5, 6, 7]],
|
| 200 |
+
index=["a", "b", "c"],
|
| 201 |
+
columns=["d", "e", "f"],
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
res1 = df.drop("a")
|
| 205 |
+
res2 = df.drop(index="a")
|
| 206 |
+
tm.assert_frame_equal(res1, res2)
|
| 207 |
+
|
| 208 |
+
res1 = df.drop("d", axis=1)
|
| 209 |
+
res2 = df.drop(columns="d")
|
| 210 |
+
tm.assert_frame_equal(res1, res2)
|
| 211 |
+
|
| 212 |
+
res1 = df.drop(labels="e", axis=1)
|
| 213 |
+
res2 = df.drop(columns="e")
|
| 214 |
+
tm.assert_frame_equal(res1, res2)
|
| 215 |
+
|
| 216 |
+
res1 = df.drop(["a"], axis=0)
|
| 217 |
+
res2 = df.drop(index=["a"])
|
| 218 |
+
tm.assert_frame_equal(res1, res2)
|
| 219 |
+
|
| 220 |
+
res1 = df.drop(["a"], axis=0).drop(["d"], axis=1)
|
| 221 |
+
res2 = df.drop(index=["a"], columns=["d"])
|
| 222 |
+
tm.assert_frame_equal(res1, res2)
|
| 223 |
+
|
| 224 |
+
msg = "Cannot specify both 'labels' and 'index'/'columns'"
|
| 225 |
+
with pytest.raises(ValueError, match=msg):
|
| 226 |
+
df.drop(labels="a", index="b")
|
| 227 |
+
|
| 228 |
+
with pytest.raises(ValueError, match=msg):
|
| 229 |
+
df.drop(labels="a", columns="b")
|
| 230 |
+
|
| 231 |
+
msg = "Need to specify at least one of 'labels', 'index' or 'columns'"
|
| 232 |
+
with pytest.raises(ValueError, match=msg):
|
| 233 |
+
df.drop(axis=1)
|
| 234 |
+
|
| 235 |
+
data = [[1, 2, 3], [1, 2, 3]]
|
| 236 |
+
|
| 237 |
+
@pytest.mark.parametrize(
|
| 238 |
+
"actual",
|
| 239 |
+
[
|
| 240 |
+
DataFrame(data=data, index=["a", "a"]),
|
| 241 |
+
DataFrame(data=data, index=["a", "b"]),
|
| 242 |
+
DataFrame(data=data, index=["a", "b"]).set_index([0, 1]),
|
| 243 |
+
DataFrame(data=data, index=["a", "a"]).set_index([0, 1]),
|
| 244 |
+
],
|
| 245 |
+
)
|
| 246 |
+
def test_raise_on_drop_duplicate_index(self, actual):
|
| 247 |
+
# GH#19186
|
| 248 |
+
level = 0 if isinstance(actual.index, MultiIndex) else None
|
| 249 |
+
msg = re.escape("\"['c'] not found in axis\"")
|
| 250 |
+
with pytest.raises(KeyError, match=msg):
|
| 251 |
+
actual.drop("c", level=level, axis=0)
|
| 252 |
+
with pytest.raises(KeyError, match=msg):
|
| 253 |
+
actual.T.drop("c", level=level, axis=1)
|
| 254 |
+
expected_no_err = actual.drop("c", axis=0, level=level, errors="ignore")
|
| 255 |
+
tm.assert_frame_equal(expected_no_err, actual)
|
| 256 |
+
expected_no_err = actual.T.drop("c", axis=1, level=level, errors="ignore")
|
| 257 |
+
tm.assert_frame_equal(expected_no_err.T, actual)
|
| 258 |
+
|
| 259 |
+
@pytest.mark.parametrize("index", [[1, 2, 3], [1, 1, 2]])
|
| 260 |
+
@pytest.mark.parametrize("drop_labels", [[], [1], [2]])
|
| 261 |
+
def test_drop_empty_list(self, index, drop_labels):
|
| 262 |
+
# GH#21494
|
| 263 |
+
expected_index = [i for i in index if i not in drop_labels]
|
| 264 |
+
frame = DataFrame(index=index).drop(drop_labels)
|
| 265 |
+
tm.assert_frame_equal(frame, DataFrame(index=expected_index))
|
| 266 |
+
|
| 267 |
+
@pytest.mark.parametrize("index", [[1, 2, 3], [1, 2, 2]])
|
| 268 |
+
@pytest.mark.parametrize("drop_labels", [[1, 4], [4, 5]])
|
| 269 |
+
def test_drop_non_empty_list(self, index, drop_labels):
|
| 270 |
+
# GH# 21494
|
| 271 |
+
with pytest.raises(KeyError, match="not found in axis"):
|
| 272 |
+
DataFrame(index=index).drop(drop_labels)
|
| 273 |
+
|
| 274 |
+
@pytest.mark.parametrize(
|
| 275 |
+
"empty_listlike",
|
| 276 |
+
[
|
| 277 |
+
[],
|
| 278 |
+
{},
|
| 279 |
+
np.array([]),
|
| 280 |
+
Series([], dtype="datetime64[ns]"),
|
| 281 |
+
Index([]),
|
| 282 |
+
DatetimeIndex([]),
|
| 283 |
+
],
|
| 284 |
+
)
|
| 285 |
+
def test_drop_empty_listlike_non_unique_datetime_index(self, empty_listlike):
|
| 286 |
+
# GH#27994
|
| 287 |
+
data = {"column_a": [5, 10], "column_b": ["one", "two"]}
|
| 288 |
+
index = [Timestamp("2021-01-01"), Timestamp("2021-01-01")]
|
| 289 |
+
df = DataFrame(data, index=index)
|
| 290 |
+
|
| 291 |
+
# Passing empty list-like should return the same DataFrame.
|
| 292 |
+
expected = df.copy()
|
| 293 |
+
result = df.drop(empty_listlike)
|
| 294 |
+
tm.assert_frame_equal(result, expected)
|
| 295 |
+
|
| 296 |
+
def test_mixed_depth_drop(self):
|
| 297 |
+
arrays = [
|
| 298 |
+
["a", "top", "top", "routine1", "routine1", "routine2"],
|
| 299 |
+
["", "OD", "OD", "result1", "result2", "result1"],
|
| 300 |
+
["", "wx", "wy", "", "", ""],
|
| 301 |
+
]
|
| 302 |
+
|
| 303 |
+
tuples = sorted(zip(*arrays))
|
| 304 |
+
index = MultiIndex.from_tuples(tuples)
|
| 305 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((4, 6)), columns=index)
|
| 306 |
+
|
| 307 |
+
result = df.drop("a", axis=1)
|
| 308 |
+
expected = df.drop([("a", "", "")], axis=1)
|
| 309 |
+
tm.assert_frame_equal(expected, result)
|
| 310 |
+
|
| 311 |
+
result = df.drop(["top"], axis=1)
|
| 312 |
+
expected = df.drop([("top", "OD", "wx")], axis=1)
|
| 313 |
+
expected = expected.drop([("top", "OD", "wy")], axis=1)
|
| 314 |
+
tm.assert_frame_equal(expected, result)
|
| 315 |
+
|
| 316 |
+
result = df.drop(("top", "OD", "wx"), axis=1)
|
| 317 |
+
expected = df.drop([("top", "OD", "wx")], axis=1)
|
| 318 |
+
tm.assert_frame_equal(expected, result)
|
| 319 |
+
|
| 320 |
+
expected = df.drop([("top", "OD", "wy")], axis=1)
|
| 321 |
+
expected = df.drop("top", axis=1)
|
| 322 |
+
|
| 323 |
+
result = df.drop("result1", level=1, axis=1)
|
| 324 |
+
expected = df.drop(
|
| 325 |
+
[("routine1", "result1", ""), ("routine2", "result1", "")], axis=1
|
| 326 |
+
)
|
| 327 |
+
tm.assert_frame_equal(expected, result)
|
| 328 |
+
|
| 329 |
+
def test_drop_multiindex_other_level_nan(self):
|
| 330 |
+
# GH#12754
|
| 331 |
+
df = (
|
| 332 |
+
DataFrame(
|
| 333 |
+
{
|
| 334 |
+
"A": ["one", "one", "two", "two"],
|
| 335 |
+
"B": [np.nan, 0.0, 1.0, 2.0],
|
| 336 |
+
"C": ["a", "b", "c", "c"],
|
| 337 |
+
"D": [1, 2, 3, 4],
|
| 338 |
+
}
|
| 339 |
+
)
|
| 340 |
+
.set_index(["A", "B", "C"])
|
| 341 |
+
.sort_index()
|
| 342 |
+
)
|
| 343 |
+
result = df.drop("c", level="C")
|
| 344 |
+
expected = DataFrame(
|
| 345 |
+
[2, 1],
|
| 346 |
+
columns=["D"],
|
| 347 |
+
index=MultiIndex.from_tuples(
|
| 348 |
+
[("one", 0.0, "b"), ("one", np.nan, "a")], names=["A", "B", "C"]
|
| 349 |
+
),
|
| 350 |
+
)
|
| 351 |
+
tm.assert_frame_equal(result, expected)
|
| 352 |
+
|
| 353 |
+
def test_drop_nonunique(self):
|
| 354 |
+
df = DataFrame(
|
| 355 |
+
[
|
| 356 |
+
["x-a", "x", "a", 1.5],
|
| 357 |
+
["x-a", "x", "a", 1.2],
|
| 358 |
+
["z-c", "z", "c", 3.1],
|
| 359 |
+
["x-a", "x", "a", 4.1],
|
| 360 |
+
["x-b", "x", "b", 5.1],
|
| 361 |
+
["x-b", "x", "b", 4.1],
|
| 362 |
+
["x-b", "x", "b", 2.2],
|
| 363 |
+
["y-a", "y", "a", 1.2],
|
| 364 |
+
["z-b", "z", "b", 2.1],
|
| 365 |
+
],
|
| 366 |
+
columns=["var1", "var2", "var3", "var4"],
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
grp_size = df.groupby("var1").size()
|
| 370 |
+
drop_idx = grp_size.loc[grp_size == 1]
|
| 371 |
+
|
| 372 |
+
idf = df.set_index(["var1", "var2", "var3"])
|
| 373 |
+
|
| 374 |
+
# it works! GH#2101
|
| 375 |
+
result = idf.drop(drop_idx.index, level=0).reset_index()
|
| 376 |
+
expected = df[-df.var1.isin(drop_idx.index)]
|
| 377 |
+
|
| 378 |
+
result.index = expected.index
|
| 379 |
+
|
| 380 |
+
tm.assert_frame_equal(result, expected)
|
| 381 |
+
|
| 382 |
+
def test_drop_level(self, multiindex_dataframe_random_data):
|
| 383 |
+
frame = multiindex_dataframe_random_data
|
| 384 |
+
|
| 385 |
+
result = frame.drop(["bar", "qux"], level="first")
|
| 386 |
+
expected = frame.iloc[[0, 1, 2, 5, 6]]
|
| 387 |
+
tm.assert_frame_equal(result, expected)
|
| 388 |
+
|
| 389 |
+
result = frame.drop(["two"], level="second")
|
| 390 |
+
expected = frame.iloc[[0, 2, 3, 6, 7, 9]]
|
| 391 |
+
tm.assert_frame_equal(result, expected)
|
| 392 |
+
|
| 393 |
+
result = frame.T.drop(["bar", "qux"], axis=1, level="first")
|
| 394 |
+
expected = frame.iloc[[0, 1, 2, 5, 6]].T
|
| 395 |
+
tm.assert_frame_equal(result, expected)
|
| 396 |
+
|
| 397 |
+
result = frame.T.drop(["two"], axis=1, level="second")
|
| 398 |
+
expected = frame.iloc[[0, 2, 3, 6, 7, 9]].T
|
| 399 |
+
tm.assert_frame_equal(result, expected)
|
| 400 |
+
|
| 401 |
+
def test_drop_level_nonunique_datetime(self):
|
| 402 |
+
# GH#12701
|
| 403 |
+
idx = Index([2, 3, 4, 4, 5], name="id")
|
| 404 |
+
idxdt = pd.to_datetime(
|
| 405 |
+
[
|
| 406 |
+
"2016-03-23 14:00",
|
| 407 |
+
"2016-03-23 15:00",
|
| 408 |
+
"2016-03-23 16:00",
|
| 409 |
+
"2016-03-23 16:00",
|
| 410 |
+
"2016-03-23 17:00",
|
| 411 |
+
]
|
| 412 |
+
)
|
| 413 |
+
df = DataFrame(np.arange(10).reshape(5, 2), columns=list("ab"), index=idx)
|
| 414 |
+
df["tstamp"] = idxdt
|
| 415 |
+
df = df.set_index("tstamp", append=True)
|
| 416 |
+
ts = Timestamp("201603231600")
|
| 417 |
+
assert df.index.is_unique is False
|
| 418 |
+
|
| 419 |
+
result = df.drop(ts, level="tstamp")
|
| 420 |
+
expected = df.loc[idx != 4]
|
| 421 |
+
tm.assert_frame_equal(result, expected)
|
| 422 |
+
|
| 423 |
+
def test_drop_tz_aware_timestamp_across_dst(self, frame_or_series):
|
| 424 |
+
# GH#21761
|
| 425 |
+
start = Timestamp("2017-10-29", tz="Europe/Berlin")
|
| 426 |
+
end = Timestamp("2017-10-29 04:00:00", tz="Europe/Berlin")
|
| 427 |
+
index = pd.date_range(start, end, freq="15min")
|
| 428 |
+
data = frame_or_series(data=[1] * len(index), index=index)
|
| 429 |
+
result = data.drop(start)
|
| 430 |
+
expected_start = Timestamp("2017-10-29 00:15:00", tz="Europe/Berlin")
|
| 431 |
+
expected_idx = pd.date_range(expected_start, end, freq="15min")
|
| 432 |
+
expected = frame_or_series(data=[1] * len(expected_idx), index=expected_idx)
|
| 433 |
+
tm.assert_equal(result, expected)
|
| 434 |
+
|
| 435 |
+
def test_drop_preserve_names(self):
|
| 436 |
+
index = MultiIndex.from_arrays(
|
| 437 |
+
[[0, 0, 0, 1, 1, 1], [1, 2, 3, 1, 2, 3]], names=["one", "two"]
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((6, 3)), index=index)
|
| 441 |
+
|
| 442 |
+
result = df.drop([(0, 2)])
|
| 443 |
+
assert result.index.names == ("one", "two")
|
| 444 |
+
|
| 445 |
+
@pytest.mark.parametrize(
|
| 446 |
+
"operation", ["__iadd__", "__isub__", "__imul__", "__ipow__"]
|
| 447 |
+
)
|
| 448 |
+
@pytest.mark.parametrize("inplace", [False, True])
|
| 449 |
+
def test_inplace_drop_and_operation(self, operation, inplace):
|
| 450 |
+
# GH#30484
|
| 451 |
+
df = DataFrame({"x": range(5)})
|
| 452 |
+
expected = df.copy()
|
| 453 |
+
df["y"] = range(5)
|
| 454 |
+
y = df["y"]
|
| 455 |
+
|
| 456 |
+
with tm.assert_produces_warning(None):
|
| 457 |
+
if inplace:
|
| 458 |
+
df.drop("y", axis=1, inplace=inplace)
|
| 459 |
+
else:
|
| 460 |
+
df = df.drop("y", axis=1, inplace=inplace)
|
| 461 |
+
|
| 462 |
+
# Perform operation and check result
|
| 463 |
+
getattr(y, operation)(1)
|
| 464 |
+
tm.assert_frame_equal(df, expected)
|
| 465 |
+
|
| 466 |
+
def test_drop_with_non_unique_multiindex(self):
|
| 467 |
+
# GH#36293
|
| 468 |
+
mi = MultiIndex.from_arrays([["x", "y", "x"], ["i", "j", "i"]])
|
| 469 |
+
df = DataFrame([1, 2, 3], index=mi)
|
| 470 |
+
result = df.drop(index="x")
|
| 471 |
+
expected = DataFrame([2], index=MultiIndex.from_arrays([["y"], ["j"]]))
|
| 472 |
+
tm.assert_frame_equal(result, expected)
|
| 473 |
+
|
| 474 |
+
@pytest.mark.parametrize("indexer", [("a", "a"), [("a", "a")]])
|
| 475 |
+
def test_drop_tuple_with_non_unique_multiindex(self, indexer):
|
| 476 |
+
# GH#42771
|
| 477 |
+
idx = MultiIndex.from_product([["a", "b"], ["a", "a"]])
|
| 478 |
+
df = DataFrame({"x": range(len(idx))}, index=idx)
|
| 479 |
+
result = df.drop(index=[("a", "a")])
|
| 480 |
+
expected = DataFrame(
|
| 481 |
+
{"x": [2, 3]}, index=MultiIndex.from_tuples([("b", "a"), ("b", "a")])
|
| 482 |
+
)
|
| 483 |
+
tm.assert_frame_equal(result, expected)
|
| 484 |
+
|
| 485 |
+
def test_drop_with_duplicate_columns(self):
|
| 486 |
+
df = DataFrame(
|
| 487 |
+
[[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"]
|
| 488 |
+
)
|
| 489 |
+
result = df.drop(["a"], axis=1)
|
| 490 |
+
expected = DataFrame([[1], [1], [1]], columns=["bar"])
|
| 491 |
+
tm.assert_frame_equal(result, expected)
|
| 492 |
+
result = df.drop("a", axis=1)
|
| 493 |
+
tm.assert_frame_equal(result, expected)
|
| 494 |
+
|
| 495 |
+
def test_drop_with_duplicate_columns2(self):
|
| 496 |
+
# drop buggy GH#6240
|
| 497 |
+
df = DataFrame(
|
| 498 |
+
{
|
| 499 |
+
"A": np.random.default_rng(2).standard_normal(5),
|
| 500 |
+
"B": np.random.default_rng(2).standard_normal(5),
|
| 501 |
+
"C": np.random.default_rng(2).standard_normal(5),
|
| 502 |
+
"D": ["a", "b", "c", "d", "e"],
|
| 503 |
+
}
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
expected = df.take([0, 1, 1], axis=1)
|
| 507 |
+
df2 = df.take([2, 0, 1, 2, 1], axis=1)
|
| 508 |
+
result = df2.drop("C", axis=1)
|
| 509 |
+
tm.assert_frame_equal(result, expected)
|
| 510 |
+
|
| 511 |
+
def test_drop_inplace_no_leftover_column_reference(self):
|
| 512 |
+
# GH 13934
|
| 513 |
+
df = DataFrame({"a": [1, 2, 3]}, columns=Index(["a"], dtype="object"))
|
| 514 |
+
a = df.a
|
| 515 |
+
df.drop(["a"], axis=1, inplace=True)
|
| 516 |
+
tm.assert_index_equal(df.columns, Index([], dtype="object"))
|
| 517 |
+
a -= a.mean()
|
| 518 |
+
tm.assert_index_equal(df.columns, Index([], dtype="object"))
|
| 519 |
+
|
| 520 |
+
def test_drop_level_missing_label_multiindex(self):
|
| 521 |
+
# GH 18561
|
| 522 |
+
df = DataFrame(index=MultiIndex.from_product([range(3), range(3)]))
|
| 523 |
+
with pytest.raises(KeyError, match="labels \\[5\\] not found in level"):
|
| 524 |
+
df.drop(5, level=0)
|
| 525 |
+
|
| 526 |
+
@pytest.mark.parametrize("idx, level", [(["a", "b"], 0), (["a"], None)])
|
| 527 |
+
def test_drop_index_ea_dtype(self, any_numeric_ea_dtype, idx, level):
|
| 528 |
+
# GH#45860
|
| 529 |
+
df = DataFrame(
|
| 530 |
+
{"a": [1, 2, 2, pd.NA], "b": 100}, dtype=any_numeric_ea_dtype
|
| 531 |
+
).set_index(idx)
|
| 532 |
+
result = df.drop(Index([2, pd.NA]), level=level)
|
| 533 |
+
expected = DataFrame(
|
| 534 |
+
{"a": [1], "b": 100}, dtype=any_numeric_ea_dtype
|
| 535 |
+
).set_index(idx)
|
| 536 |
+
tm.assert_frame_equal(result, expected)
|
| 537 |
+
|
| 538 |
+
def test_drop_parse_strings_datetime_index(self):
|
| 539 |
+
# GH #5355
|
| 540 |
+
df = DataFrame(
|
| 541 |
+
{"a": [1, 2], "b": [1, 2]},
|
| 542 |
+
index=[Timestamp("2000-01-03"), Timestamp("2000-01-04")],
|
| 543 |
+
)
|
| 544 |
+
result = df.drop("2000-01-03", axis=0)
|
| 545 |
+
expected = DataFrame({"a": [2], "b": [2]}, index=[Timestamp("2000-01-04")])
|
| 546 |
+
tm.assert_frame_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_drop_duplicates.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from pandas import (
|
| 8 |
+
DataFrame,
|
| 9 |
+
NaT,
|
| 10 |
+
concat,
|
| 11 |
+
)
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.mark.parametrize("subset", ["a", ["a"], ["a", "B"]])
|
| 16 |
+
def test_drop_duplicates_with_misspelled_column_name(subset):
|
| 17 |
+
# GH 19730
|
| 18 |
+
df = DataFrame({"A": [0, 0, 1], "B": [0, 0, 1], "C": [0, 0, 1]})
|
| 19 |
+
msg = re.escape("Index(['a'], dtype=")
|
| 20 |
+
|
| 21 |
+
with pytest.raises(KeyError, match=msg):
|
| 22 |
+
df.drop_duplicates(subset)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_drop_duplicates():
|
| 26 |
+
df = DataFrame(
|
| 27 |
+
{
|
| 28 |
+
"AAA": ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"],
|
| 29 |
+
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
|
| 30 |
+
"C": [1, 1, 2, 2, 2, 2, 1, 2],
|
| 31 |
+
"D": range(8),
|
| 32 |
+
}
|
| 33 |
+
)
|
| 34 |
+
# single column
|
| 35 |
+
result = df.drop_duplicates("AAA")
|
| 36 |
+
expected = df[:2]
|
| 37 |
+
tm.assert_frame_equal(result, expected)
|
| 38 |
+
|
| 39 |
+
result = df.drop_duplicates("AAA", keep="last")
|
| 40 |
+
expected = df.loc[[6, 7]]
|
| 41 |
+
tm.assert_frame_equal(result, expected)
|
| 42 |
+
|
| 43 |
+
result = df.drop_duplicates("AAA", keep=False)
|
| 44 |
+
expected = df.loc[[]]
|
| 45 |
+
tm.assert_frame_equal(result, expected)
|
| 46 |
+
assert len(result) == 0
|
| 47 |
+
|
| 48 |
+
# multi column
|
| 49 |
+
expected = df.loc[[0, 1, 2, 3]]
|
| 50 |
+
result = df.drop_duplicates(np.array(["AAA", "B"]))
|
| 51 |
+
tm.assert_frame_equal(result, expected)
|
| 52 |
+
result = df.drop_duplicates(["AAA", "B"])
|
| 53 |
+
tm.assert_frame_equal(result, expected)
|
| 54 |
+
|
| 55 |
+
result = df.drop_duplicates(("AAA", "B"), keep="last")
|
| 56 |
+
expected = df.loc[[0, 5, 6, 7]]
|
| 57 |
+
tm.assert_frame_equal(result, expected)
|
| 58 |
+
|
| 59 |
+
result = df.drop_duplicates(("AAA", "B"), keep=False)
|
| 60 |
+
expected = df.loc[[0]]
|
| 61 |
+
tm.assert_frame_equal(result, expected)
|
| 62 |
+
|
| 63 |
+
# consider everything
|
| 64 |
+
df2 = df.loc[:, ["AAA", "B", "C"]]
|
| 65 |
+
|
| 66 |
+
result = df2.drop_duplicates()
|
| 67 |
+
# in this case only
|
| 68 |
+
expected = df2.drop_duplicates(["AAA", "B"])
|
| 69 |
+
tm.assert_frame_equal(result, expected)
|
| 70 |
+
|
| 71 |
+
result = df2.drop_duplicates(keep="last")
|
| 72 |
+
expected = df2.drop_duplicates(["AAA", "B"], keep="last")
|
| 73 |
+
tm.assert_frame_equal(result, expected)
|
| 74 |
+
|
| 75 |
+
result = df2.drop_duplicates(keep=False)
|
| 76 |
+
expected = df2.drop_duplicates(["AAA", "B"], keep=False)
|
| 77 |
+
tm.assert_frame_equal(result, expected)
|
| 78 |
+
|
| 79 |
+
# integers
|
| 80 |
+
result = df.drop_duplicates("C")
|
| 81 |
+
expected = df.iloc[[0, 2]]
|
| 82 |
+
tm.assert_frame_equal(result, expected)
|
| 83 |
+
result = df.drop_duplicates("C", keep="last")
|
| 84 |
+
expected = df.iloc[[-2, -1]]
|
| 85 |
+
tm.assert_frame_equal(result, expected)
|
| 86 |
+
|
| 87 |
+
df["E"] = df["C"].astype("int8")
|
| 88 |
+
result = df.drop_duplicates("E")
|
| 89 |
+
expected = df.iloc[[0, 2]]
|
| 90 |
+
tm.assert_frame_equal(result, expected)
|
| 91 |
+
result = df.drop_duplicates("E", keep="last")
|
| 92 |
+
expected = df.iloc[[-2, -1]]
|
| 93 |
+
tm.assert_frame_equal(result, expected)
|
| 94 |
+
|
| 95 |
+
# GH 11376
|
| 96 |
+
df = DataFrame({"x": [7, 6, 3, 3, 4, 8, 0], "y": [0, 6, 5, 5, 9, 1, 2]})
|
| 97 |
+
expected = df.loc[df.index != 3]
|
| 98 |
+
tm.assert_frame_equal(df.drop_duplicates(), expected)
|
| 99 |
+
|
| 100 |
+
df = DataFrame([[1, 0], [0, 2]])
|
| 101 |
+
tm.assert_frame_equal(df.drop_duplicates(), df)
|
| 102 |
+
|
| 103 |
+
df = DataFrame([[-2, 0], [0, -4]])
|
| 104 |
+
tm.assert_frame_equal(df.drop_duplicates(), df)
|
| 105 |
+
|
| 106 |
+
x = np.iinfo(np.int64).max / 3 * 2
|
| 107 |
+
df = DataFrame([[-x, x], [0, x + 4]])
|
| 108 |
+
tm.assert_frame_equal(df.drop_duplicates(), df)
|
| 109 |
+
|
| 110 |
+
df = DataFrame([[-x, x], [x, x + 4]])
|
| 111 |
+
tm.assert_frame_equal(df.drop_duplicates(), df)
|
| 112 |
+
|
| 113 |
+
# GH 11864
|
| 114 |
+
df = DataFrame([i] * 9 for i in range(16))
|
| 115 |
+
df = concat([df, DataFrame([[1] + [0] * 8])], ignore_index=True)
|
| 116 |
+
|
| 117 |
+
for keep in ["first", "last", False]:
|
| 118 |
+
assert df.duplicated(keep=keep).sum() == 0
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def test_drop_duplicates_with_duplicate_column_names():
|
| 122 |
+
# GH17836
|
| 123 |
+
df = DataFrame([[1, 2, 5], [3, 4, 6], [3, 4, 7]], columns=["a", "a", "b"])
|
| 124 |
+
|
| 125 |
+
result0 = df.drop_duplicates()
|
| 126 |
+
tm.assert_frame_equal(result0, df)
|
| 127 |
+
|
| 128 |
+
result1 = df.drop_duplicates("a")
|
| 129 |
+
expected1 = df[:2]
|
| 130 |
+
tm.assert_frame_equal(result1, expected1)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_drop_duplicates_for_take_all():
|
| 134 |
+
df = DataFrame(
|
| 135 |
+
{
|
| 136 |
+
"AAA": ["foo", "bar", "baz", "bar", "foo", "bar", "qux", "foo"],
|
| 137 |
+
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
|
| 138 |
+
"C": [1, 1, 2, 2, 2, 2, 1, 2],
|
| 139 |
+
"D": range(8),
|
| 140 |
+
}
|
| 141 |
+
)
|
| 142 |
+
# single column
|
| 143 |
+
result = df.drop_duplicates("AAA")
|
| 144 |
+
expected = df.iloc[[0, 1, 2, 6]]
|
| 145 |
+
tm.assert_frame_equal(result, expected)
|
| 146 |
+
|
| 147 |
+
result = df.drop_duplicates("AAA", keep="last")
|
| 148 |
+
expected = df.iloc[[2, 5, 6, 7]]
|
| 149 |
+
tm.assert_frame_equal(result, expected)
|
| 150 |
+
|
| 151 |
+
result = df.drop_duplicates("AAA", keep=False)
|
| 152 |
+
expected = df.iloc[[2, 6]]
|
| 153 |
+
tm.assert_frame_equal(result, expected)
|
| 154 |
+
|
| 155 |
+
# multiple columns
|
| 156 |
+
result = df.drop_duplicates(["AAA", "B"])
|
| 157 |
+
expected = df.iloc[[0, 1, 2, 3, 4, 6]]
|
| 158 |
+
tm.assert_frame_equal(result, expected)
|
| 159 |
+
|
| 160 |
+
result = df.drop_duplicates(["AAA", "B"], keep="last")
|
| 161 |
+
expected = df.iloc[[0, 1, 2, 5, 6, 7]]
|
| 162 |
+
tm.assert_frame_equal(result, expected)
|
| 163 |
+
|
| 164 |
+
result = df.drop_duplicates(["AAA", "B"], keep=False)
|
| 165 |
+
expected = df.iloc[[0, 1, 2, 6]]
|
| 166 |
+
tm.assert_frame_equal(result, expected)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def test_drop_duplicates_tuple():
|
| 170 |
+
df = DataFrame(
|
| 171 |
+
{
|
| 172 |
+
("AA", "AB"): ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"],
|
| 173 |
+
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
|
| 174 |
+
"C": [1, 1, 2, 2, 2, 2, 1, 2],
|
| 175 |
+
"D": range(8),
|
| 176 |
+
}
|
| 177 |
+
)
|
| 178 |
+
# single column
|
| 179 |
+
result = df.drop_duplicates(("AA", "AB"))
|
| 180 |
+
expected = df[:2]
|
| 181 |
+
tm.assert_frame_equal(result, expected)
|
| 182 |
+
|
| 183 |
+
result = df.drop_duplicates(("AA", "AB"), keep="last")
|
| 184 |
+
expected = df.loc[[6, 7]]
|
| 185 |
+
tm.assert_frame_equal(result, expected)
|
| 186 |
+
|
| 187 |
+
result = df.drop_duplicates(("AA", "AB"), keep=False)
|
| 188 |
+
expected = df.loc[[]] # empty df
|
| 189 |
+
assert len(result) == 0
|
| 190 |
+
tm.assert_frame_equal(result, expected)
|
| 191 |
+
|
| 192 |
+
# multi column
|
| 193 |
+
expected = df.loc[[0, 1, 2, 3]]
|
| 194 |
+
result = df.drop_duplicates((("AA", "AB"), "B"))
|
| 195 |
+
tm.assert_frame_equal(result, expected)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@pytest.mark.parametrize(
|
| 199 |
+
"df",
|
| 200 |
+
[
|
| 201 |
+
DataFrame(),
|
| 202 |
+
DataFrame(columns=[]),
|
| 203 |
+
DataFrame(columns=["A", "B", "C"]),
|
| 204 |
+
DataFrame(index=[]),
|
| 205 |
+
DataFrame(index=["A", "B", "C"]),
|
| 206 |
+
],
|
| 207 |
+
)
|
| 208 |
+
def test_drop_duplicates_empty(df):
|
| 209 |
+
# GH 20516
|
| 210 |
+
result = df.drop_duplicates()
|
| 211 |
+
tm.assert_frame_equal(result, df)
|
| 212 |
+
|
| 213 |
+
result = df.copy()
|
| 214 |
+
result.drop_duplicates(inplace=True)
|
| 215 |
+
tm.assert_frame_equal(result, df)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def test_drop_duplicates_NA():
|
| 219 |
+
# none
|
| 220 |
+
df = DataFrame(
|
| 221 |
+
{
|
| 222 |
+
"A": [None, None, "foo", "bar", "foo", "bar", "bar", "foo"],
|
| 223 |
+
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
|
| 224 |
+
"C": [1.0, np.nan, np.nan, np.nan, 1.0, 1.0, 1, 1.0],
|
| 225 |
+
"D": range(8),
|
| 226 |
+
}
|
| 227 |
+
)
|
| 228 |
+
# single column
|
| 229 |
+
result = df.drop_duplicates("A")
|
| 230 |
+
expected = df.loc[[0, 2, 3]]
|
| 231 |
+
tm.assert_frame_equal(result, expected)
|
| 232 |
+
|
| 233 |
+
result = df.drop_duplicates("A", keep="last")
|
| 234 |
+
expected = df.loc[[1, 6, 7]]
|
| 235 |
+
tm.assert_frame_equal(result, expected)
|
| 236 |
+
|
| 237 |
+
result = df.drop_duplicates("A", keep=False)
|
| 238 |
+
expected = df.loc[[]] # empty df
|
| 239 |
+
tm.assert_frame_equal(result, expected)
|
| 240 |
+
assert len(result) == 0
|
| 241 |
+
|
| 242 |
+
# multi column
|
| 243 |
+
result = df.drop_duplicates(["A", "B"])
|
| 244 |
+
expected = df.loc[[0, 2, 3, 6]]
|
| 245 |
+
tm.assert_frame_equal(result, expected)
|
| 246 |
+
|
| 247 |
+
result = df.drop_duplicates(["A", "B"], keep="last")
|
| 248 |
+
expected = df.loc[[1, 5, 6, 7]]
|
| 249 |
+
tm.assert_frame_equal(result, expected)
|
| 250 |
+
|
| 251 |
+
result = df.drop_duplicates(["A", "B"], keep=False)
|
| 252 |
+
expected = df.loc[[6]]
|
| 253 |
+
tm.assert_frame_equal(result, expected)
|
| 254 |
+
|
| 255 |
+
# nan
|
| 256 |
+
df = DataFrame(
|
| 257 |
+
{
|
| 258 |
+
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"],
|
| 259 |
+
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
|
| 260 |
+
"C": [1.0, np.nan, np.nan, np.nan, 1.0, 1.0, 1, 1.0],
|
| 261 |
+
"D": range(8),
|
| 262 |
+
}
|
| 263 |
+
)
|
| 264 |
+
# single column
|
| 265 |
+
result = df.drop_duplicates("C")
|
| 266 |
+
expected = df[:2]
|
| 267 |
+
tm.assert_frame_equal(result, expected)
|
| 268 |
+
|
| 269 |
+
result = df.drop_duplicates("C", keep="last")
|
| 270 |
+
expected = df.loc[[3, 7]]
|
| 271 |
+
tm.assert_frame_equal(result, expected)
|
| 272 |
+
|
| 273 |
+
result = df.drop_duplicates("C", keep=False)
|
| 274 |
+
expected = df.loc[[]] # empty df
|
| 275 |
+
tm.assert_frame_equal(result, expected)
|
| 276 |
+
assert len(result) == 0
|
| 277 |
+
|
| 278 |
+
# multi column
|
| 279 |
+
result = df.drop_duplicates(["C", "B"])
|
| 280 |
+
expected = df.loc[[0, 1, 2, 4]]
|
| 281 |
+
tm.assert_frame_equal(result, expected)
|
| 282 |
+
|
| 283 |
+
result = df.drop_duplicates(["C", "B"], keep="last")
|
| 284 |
+
expected = df.loc[[1, 3, 6, 7]]
|
| 285 |
+
tm.assert_frame_equal(result, expected)
|
| 286 |
+
|
| 287 |
+
result = df.drop_duplicates(["C", "B"], keep=False)
|
| 288 |
+
expected = df.loc[[1]]
|
| 289 |
+
tm.assert_frame_equal(result, expected)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def test_drop_duplicates_NA_for_take_all():
|
| 293 |
+
# none
|
| 294 |
+
df = DataFrame(
|
| 295 |
+
{
|
| 296 |
+
"A": [None, None, "foo", "bar", "foo", "baz", "bar", "qux"],
|
| 297 |
+
"C": [1.0, np.nan, np.nan, np.nan, 1.0, 2.0, 3, 1.0],
|
| 298 |
+
}
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
# single column
|
| 302 |
+
result = df.drop_duplicates("A")
|
| 303 |
+
expected = df.iloc[[0, 2, 3, 5, 7]]
|
| 304 |
+
tm.assert_frame_equal(result, expected)
|
| 305 |
+
|
| 306 |
+
result = df.drop_duplicates("A", keep="last")
|
| 307 |
+
expected = df.iloc[[1, 4, 5, 6, 7]]
|
| 308 |
+
tm.assert_frame_equal(result, expected)
|
| 309 |
+
|
| 310 |
+
result = df.drop_duplicates("A", keep=False)
|
| 311 |
+
expected = df.iloc[[5, 7]]
|
| 312 |
+
tm.assert_frame_equal(result, expected)
|
| 313 |
+
|
| 314 |
+
# nan
|
| 315 |
+
|
| 316 |
+
# single column
|
| 317 |
+
result = df.drop_duplicates("C")
|
| 318 |
+
expected = df.iloc[[0, 1, 5, 6]]
|
| 319 |
+
tm.assert_frame_equal(result, expected)
|
| 320 |
+
|
| 321 |
+
result = df.drop_duplicates("C", keep="last")
|
| 322 |
+
expected = df.iloc[[3, 5, 6, 7]]
|
| 323 |
+
tm.assert_frame_equal(result, expected)
|
| 324 |
+
|
| 325 |
+
result = df.drop_duplicates("C", keep=False)
|
| 326 |
+
expected = df.iloc[[5, 6]]
|
| 327 |
+
tm.assert_frame_equal(result, expected)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def test_drop_duplicates_inplace():
|
| 331 |
+
orig = DataFrame(
|
| 332 |
+
{
|
| 333 |
+
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"],
|
| 334 |
+
"B": ["one", "one", "two", "two", "two", "two", "one", "two"],
|
| 335 |
+
"C": [1, 1, 2, 2, 2, 2, 1, 2],
|
| 336 |
+
"D": range(8),
|
| 337 |
+
}
|
| 338 |
+
)
|
| 339 |
+
# single column
|
| 340 |
+
df = orig.copy()
|
| 341 |
+
return_value = df.drop_duplicates("A", inplace=True)
|
| 342 |
+
expected = orig[:2]
|
| 343 |
+
result = df
|
| 344 |
+
tm.assert_frame_equal(result, expected)
|
| 345 |
+
assert return_value is None
|
| 346 |
+
|
| 347 |
+
df = orig.copy()
|
| 348 |
+
return_value = df.drop_duplicates("A", keep="last", inplace=True)
|
| 349 |
+
expected = orig.loc[[6, 7]]
|
| 350 |
+
result = df
|
| 351 |
+
tm.assert_frame_equal(result, expected)
|
| 352 |
+
assert return_value is None
|
| 353 |
+
|
| 354 |
+
df = orig.copy()
|
| 355 |
+
return_value = df.drop_duplicates("A", keep=False, inplace=True)
|
| 356 |
+
expected = orig.loc[[]]
|
| 357 |
+
result = df
|
| 358 |
+
tm.assert_frame_equal(result, expected)
|
| 359 |
+
assert len(df) == 0
|
| 360 |
+
assert return_value is None
|
| 361 |
+
|
| 362 |
+
# multi column
|
| 363 |
+
df = orig.copy()
|
| 364 |
+
return_value = df.drop_duplicates(["A", "B"], inplace=True)
|
| 365 |
+
expected = orig.loc[[0, 1, 2, 3]]
|
| 366 |
+
result = df
|
| 367 |
+
tm.assert_frame_equal(result, expected)
|
| 368 |
+
assert return_value is None
|
| 369 |
+
|
| 370 |
+
df = orig.copy()
|
| 371 |
+
return_value = df.drop_duplicates(["A", "B"], keep="last", inplace=True)
|
| 372 |
+
expected = orig.loc[[0, 5, 6, 7]]
|
| 373 |
+
result = df
|
| 374 |
+
tm.assert_frame_equal(result, expected)
|
| 375 |
+
assert return_value is None
|
| 376 |
+
|
| 377 |
+
df = orig.copy()
|
| 378 |
+
return_value = df.drop_duplicates(["A", "B"], keep=False, inplace=True)
|
| 379 |
+
expected = orig.loc[[0]]
|
| 380 |
+
result = df
|
| 381 |
+
tm.assert_frame_equal(result, expected)
|
| 382 |
+
assert return_value is None
|
| 383 |
+
|
| 384 |
+
# consider everything
|
| 385 |
+
orig2 = orig.loc[:, ["A", "B", "C"]].copy()
|
| 386 |
+
|
| 387 |
+
df2 = orig2.copy()
|
| 388 |
+
return_value = df2.drop_duplicates(inplace=True)
|
| 389 |
+
# in this case only
|
| 390 |
+
expected = orig2.drop_duplicates(["A", "B"])
|
| 391 |
+
result = df2
|
| 392 |
+
tm.assert_frame_equal(result, expected)
|
| 393 |
+
assert return_value is None
|
| 394 |
+
|
| 395 |
+
df2 = orig2.copy()
|
| 396 |
+
return_value = df2.drop_duplicates(keep="last", inplace=True)
|
| 397 |
+
expected = orig2.drop_duplicates(["A", "B"], keep="last")
|
| 398 |
+
result = df2
|
| 399 |
+
tm.assert_frame_equal(result, expected)
|
| 400 |
+
assert return_value is None
|
| 401 |
+
|
| 402 |
+
df2 = orig2.copy()
|
| 403 |
+
return_value = df2.drop_duplicates(keep=False, inplace=True)
|
| 404 |
+
expected = orig2.drop_duplicates(["A", "B"], keep=False)
|
| 405 |
+
result = df2
|
| 406 |
+
tm.assert_frame_equal(result, expected)
|
| 407 |
+
assert return_value is None
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
@pytest.mark.parametrize("inplace", [True, False])
|
| 411 |
+
@pytest.mark.parametrize(
|
| 412 |
+
"origin_dict, output_dict, ignore_index, output_index",
|
| 413 |
+
[
|
| 414 |
+
({"A": [2, 2, 3]}, {"A": [2, 3]}, True, [0, 1]),
|
| 415 |
+
({"A": [2, 2, 3]}, {"A": [2, 3]}, False, [0, 2]),
|
| 416 |
+
({"A": [2, 2, 3], "B": [2, 2, 4]}, {"A": [2, 3], "B": [2, 4]}, True, [0, 1]),
|
| 417 |
+
({"A": [2, 2, 3], "B": [2, 2, 4]}, {"A": [2, 3], "B": [2, 4]}, False, [0, 2]),
|
| 418 |
+
],
|
| 419 |
+
)
|
| 420 |
+
def test_drop_duplicates_ignore_index(
|
| 421 |
+
inplace, origin_dict, output_dict, ignore_index, output_index
|
| 422 |
+
):
|
| 423 |
+
# GH 30114
|
| 424 |
+
df = DataFrame(origin_dict)
|
| 425 |
+
expected = DataFrame(output_dict, index=output_index)
|
| 426 |
+
|
| 427 |
+
if inplace:
|
| 428 |
+
result_df = df.copy()
|
| 429 |
+
result_df.drop_duplicates(ignore_index=ignore_index, inplace=inplace)
|
| 430 |
+
else:
|
| 431 |
+
result_df = df.drop_duplicates(ignore_index=ignore_index, inplace=inplace)
|
| 432 |
+
|
| 433 |
+
tm.assert_frame_equal(result_df, expected)
|
| 434 |
+
tm.assert_frame_equal(df, DataFrame(origin_dict))
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def test_drop_duplicates_null_in_object_column(nulls_fixture):
|
| 438 |
+
# https://github.com/pandas-dev/pandas/issues/32992
|
| 439 |
+
df = DataFrame([[1, nulls_fixture], [2, "a"]], dtype=object)
|
| 440 |
+
result = df.drop_duplicates()
|
| 441 |
+
tm.assert_frame_equal(result, df)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def test_drop_duplicates_series_vs_dataframe(keep):
|
| 445 |
+
# GH#14192
|
| 446 |
+
df = DataFrame(
|
| 447 |
+
{
|
| 448 |
+
"a": [1, 1, 1, "one", "one"],
|
| 449 |
+
"b": [2, 2, np.nan, np.nan, np.nan],
|
| 450 |
+
"c": [3, 3, np.nan, np.nan, "three"],
|
| 451 |
+
"d": [1, 2, 3, 4, 4],
|
| 452 |
+
"e": [
|
| 453 |
+
datetime(2015, 1, 1),
|
| 454 |
+
datetime(2015, 1, 1),
|
| 455 |
+
datetime(2015, 2, 1),
|
| 456 |
+
NaT,
|
| 457 |
+
NaT,
|
| 458 |
+
],
|
| 459 |
+
}
|
| 460 |
+
)
|
| 461 |
+
for column in df.columns:
|
| 462 |
+
dropped_frame = df[[column]].drop_duplicates(keep=keep)
|
| 463 |
+
dropped_series = df[column].drop_duplicates(keep=keep)
|
| 464 |
+
tm.assert_frame_equal(dropped_frame, dropped_series.to_frame())
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
@pytest.mark.parametrize("arg", [[1], 1, "True", [], 0])
|
| 468 |
+
def test_drop_duplicates_non_boolean_ignore_index(arg):
|
| 469 |
+
# GH#38274
|
| 470 |
+
df = DataFrame({"a": [1, 2, 1, 3]})
|
| 471 |
+
msg = '^For argument "ignore_index" expected type bool, received type .*.$'
|
| 472 |
+
with pytest.raises(ValueError, match=msg):
|
| 473 |
+
df.drop_duplicates(ignore_index=arg)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_droplevel.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from pandas import (
|
| 4 |
+
DataFrame,
|
| 5 |
+
Index,
|
| 6 |
+
MultiIndex,
|
| 7 |
+
)
|
| 8 |
+
import pandas._testing as tm
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TestDropLevel:
|
| 12 |
+
def test_droplevel(self, frame_or_series):
|
| 13 |
+
# GH#20342
|
| 14 |
+
cols = MultiIndex.from_tuples(
|
| 15 |
+
[("c", "e"), ("d", "f")], names=["level_1", "level_2"]
|
| 16 |
+
)
|
| 17 |
+
mi = MultiIndex.from_tuples([(1, 2), (5, 6), (9, 10)], names=["a", "b"])
|
| 18 |
+
df = DataFrame([[3, 4], [7, 8], [11, 12]], index=mi, columns=cols)
|
| 19 |
+
if frame_or_series is not DataFrame:
|
| 20 |
+
df = df.iloc[:, 0]
|
| 21 |
+
|
| 22 |
+
# test that dropping of a level in index works
|
| 23 |
+
expected = df.reset_index("a", drop=True)
|
| 24 |
+
result = df.droplevel("a", axis="index")
|
| 25 |
+
tm.assert_equal(result, expected)
|
| 26 |
+
|
| 27 |
+
if frame_or_series is DataFrame:
|
| 28 |
+
# test that dropping of a level in columns works
|
| 29 |
+
expected = df.copy()
|
| 30 |
+
expected.columns = Index(["c", "d"], name="level_1")
|
| 31 |
+
result = df.droplevel("level_2", axis="columns")
|
| 32 |
+
tm.assert_equal(result, expected)
|
| 33 |
+
else:
|
| 34 |
+
# test that droplevel raises ValueError on axis != 0
|
| 35 |
+
with pytest.raises(ValueError, match="No axis named columns"):
|
| 36 |
+
df.droplevel(1, axis="columns")
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_dropna.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
|
| 3 |
+
import dateutil
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from pandas import (
|
| 9 |
+
DataFrame,
|
| 10 |
+
Series,
|
| 11 |
+
)
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TestDataFrameMissingData:
|
| 16 |
+
def test_dropEmptyRows(self, float_frame):
|
| 17 |
+
N = len(float_frame.index)
|
| 18 |
+
mat = np.random.default_rng(2).standard_normal(N)
|
| 19 |
+
mat[:5] = np.nan
|
| 20 |
+
|
| 21 |
+
frame = DataFrame({"foo": mat}, index=float_frame.index)
|
| 22 |
+
original = Series(mat, index=float_frame.index, name="foo")
|
| 23 |
+
expected = original.dropna()
|
| 24 |
+
inplace_frame1, inplace_frame2 = frame.copy(), frame.copy()
|
| 25 |
+
|
| 26 |
+
smaller_frame = frame.dropna(how="all")
|
| 27 |
+
# check that original was preserved
|
| 28 |
+
tm.assert_series_equal(frame["foo"], original)
|
| 29 |
+
return_value = inplace_frame1.dropna(how="all", inplace=True)
|
| 30 |
+
tm.assert_series_equal(smaller_frame["foo"], expected)
|
| 31 |
+
tm.assert_series_equal(inplace_frame1["foo"], expected)
|
| 32 |
+
assert return_value is None
|
| 33 |
+
|
| 34 |
+
smaller_frame = frame.dropna(how="all", subset=["foo"])
|
| 35 |
+
return_value = inplace_frame2.dropna(how="all", subset=["foo"], inplace=True)
|
| 36 |
+
tm.assert_series_equal(smaller_frame["foo"], expected)
|
| 37 |
+
tm.assert_series_equal(inplace_frame2["foo"], expected)
|
| 38 |
+
assert return_value is None
|
| 39 |
+
|
| 40 |
+
def test_dropIncompleteRows(self, float_frame):
|
| 41 |
+
N = len(float_frame.index)
|
| 42 |
+
mat = np.random.default_rng(2).standard_normal(N)
|
| 43 |
+
mat[:5] = np.nan
|
| 44 |
+
|
| 45 |
+
frame = DataFrame({"foo": mat}, index=float_frame.index)
|
| 46 |
+
frame["bar"] = 5
|
| 47 |
+
original = Series(mat, index=float_frame.index, name="foo")
|
| 48 |
+
inp_frame1, inp_frame2 = frame.copy(), frame.copy()
|
| 49 |
+
|
| 50 |
+
smaller_frame = frame.dropna()
|
| 51 |
+
tm.assert_series_equal(frame["foo"], original)
|
| 52 |
+
return_value = inp_frame1.dropna(inplace=True)
|
| 53 |
+
|
| 54 |
+
exp = Series(mat[5:], index=float_frame.index[5:], name="foo")
|
| 55 |
+
tm.assert_series_equal(smaller_frame["foo"], exp)
|
| 56 |
+
tm.assert_series_equal(inp_frame1["foo"], exp)
|
| 57 |
+
assert return_value is None
|
| 58 |
+
|
| 59 |
+
samesize_frame = frame.dropna(subset=["bar"])
|
| 60 |
+
tm.assert_series_equal(frame["foo"], original)
|
| 61 |
+
assert (frame["bar"] == 5).all()
|
| 62 |
+
return_value = inp_frame2.dropna(subset=["bar"], inplace=True)
|
| 63 |
+
tm.assert_index_equal(samesize_frame.index, float_frame.index)
|
| 64 |
+
tm.assert_index_equal(inp_frame2.index, float_frame.index)
|
| 65 |
+
assert return_value is None
|
| 66 |
+
|
| 67 |
+
def test_dropna(self):
|
| 68 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((6, 4)))
|
| 69 |
+
df.iloc[:2, 2] = np.nan
|
| 70 |
+
|
| 71 |
+
dropped = df.dropna(axis=1)
|
| 72 |
+
expected = df.loc[:, [0, 1, 3]]
|
| 73 |
+
inp = df.copy()
|
| 74 |
+
return_value = inp.dropna(axis=1, inplace=True)
|
| 75 |
+
tm.assert_frame_equal(dropped, expected)
|
| 76 |
+
tm.assert_frame_equal(inp, expected)
|
| 77 |
+
assert return_value is None
|
| 78 |
+
|
| 79 |
+
dropped = df.dropna(axis=0)
|
| 80 |
+
expected = df.loc[list(range(2, 6))]
|
| 81 |
+
inp = df.copy()
|
| 82 |
+
return_value = inp.dropna(axis=0, inplace=True)
|
| 83 |
+
tm.assert_frame_equal(dropped, expected)
|
| 84 |
+
tm.assert_frame_equal(inp, expected)
|
| 85 |
+
assert return_value is None
|
| 86 |
+
|
| 87 |
+
# threshold
|
| 88 |
+
dropped = df.dropna(axis=1, thresh=5)
|
| 89 |
+
expected = df.loc[:, [0, 1, 3]]
|
| 90 |
+
inp = df.copy()
|
| 91 |
+
return_value = inp.dropna(axis=1, thresh=5, inplace=True)
|
| 92 |
+
tm.assert_frame_equal(dropped, expected)
|
| 93 |
+
tm.assert_frame_equal(inp, expected)
|
| 94 |
+
assert return_value is None
|
| 95 |
+
|
| 96 |
+
dropped = df.dropna(axis=0, thresh=4)
|
| 97 |
+
expected = df.loc[range(2, 6)]
|
| 98 |
+
inp = df.copy()
|
| 99 |
+
return_value = inp.dropna(axis=0, thresh=4, inplace=True)
|
| 100 |
+
tm.assert_frame_equal(dropped, expected)
|
| 101 |
+
tm.assert_frame_equal(inp, expected)
|
| 102 |
+
assert return_value is None
|
| 103 |
+
|
| 104 |
+
dropped = df.dropna(axis=1, thresh=4)
|
| 105 |
+
tm.assert_frame_equal(dropped, df)
|
| 106 |
+
|
| 107 |
+
dropped = df.dropna(axis=1, thresh=3)
|
| 108 |
+
tm.assert_frame_equal(dropped, df)
|
| 109 |
+
|
| 110 |
+
# subset
|
| 111 |
+
dropped = df.dropna(axis=0, subset=[0, 1, 3])
|
| 112 |
+
inp = df.copy()
|
| 113 |
+
return_value = inp.dropna(axis=0, subset=[0, 1, 3], inplace=True)
|
| 114 |
+
tm.assert_frame_equal(dropped, df)
|
| 115 |
+
tm.assert_frame_equal(inp, df)
|
| 116 |
+
assert return_value is None
|
| 117 |
+
|
| 118 |
+
# all
|
| 119 |
+
dropped = df.dropna(axis=1, how="all")
|
| 120 |
+
tm.assert_frame_equal(dropped, df)
|
| 121 |
+
|
| 122 |
+
df[2] = np.nan
|
| 123 |
+
dropped = df.dropna(axis=1, how="all")
|
| 124 |
+
expected = df.loc[:, [0, 1, 3]]
|
| 125 |
+
tm.assert_frame_equal(dropped, expected)
|
| 126 |
+
|
| 127 |
+
# bad input
|
| 128 |
+
msg = "No axis named 3 for object type DataFrame"
|
| 129 |
+
with pytest.raises(ValueError, match=msg):
|
| 130 |
+
df.dropna(axis=3)
|
| 131 |
+
|
| 132 |
+
def test_drop_and_dropna_caching(self):
|
| 133 |
+
# tst that cacher updates
|
| 134 |
+
original = Series([1, 2, np.nan], name="A")
|
| 135 |
+
expected = Series([1, 2], dtype=original.dtype, name="A")
|
| 136 |
+
df = DataFrame({"A": original.values.copy()})
|
| 137 |
+
df2 = df.copy()
|
| 138 |
+
df["A"].dropna()
|
| 139 |
+
tm.assert_series_equal(df["A"], original)
|
| 140 |
+
|
| 141 |
+
ser = df["A"]
|
| 142 |
+
return_value = ser.dropna(inplace=True)
|
| 143 |
+
tm.assert_series_equal(ser, expected)
|
| 144 |
+
tm.assert_series_equal(df["A"], original)
|
| 145 |
+
assert return_value is None
|
| 146 |
+
|
| 147 |
+
df2["A"].drop([1])
|
| 148 |
+
tm.assert_series_equal(df2["A"], original)
|
| 149 |
+
|
| 150 |
+
ser = df2["A"]
|
| 151 |
+
return_value = ser.drop([1], inplace=True)
|
| 152 |
+
tm.assert_series_equal(ser, original.drop([1]))
|
| 153 |
+
tm.assert_series_equal(df2["A"], original)
|
| 154 |
+
assert return_value is None
|
| 155 |
+
|
| 156 |
+
def test_dropna_corner(self, float_frame):
|
| 157 |
+
# bad input
|
| 158 |
+
msg = "invalid how option: foo"
|
| 159 |
+
with pytest.raises(ValueError, match=msg):
|
| 160 |
+
float_frame.dropna(how="foo")
|
| 161 |
+
# non-existent column - 8303
|
| 162 |
+
with pytest.raises(KeyError, match=r"^\['X'\]$"):
|
| 163 |
+
float_frame.dropna(subset=["A", "X"])
|
| 164 |
+
|
| 165 |
+
def test_dropna_multiple_axes(self):
|
| 166 |
+
df = DataFrame(
|
| 167 |
+
[
|
| 168 |
+
[1, np.nan, 2, 3],
|
| 169 |
+
[4, np.nan, 5, 6],
|
| 170 |
+
[np.nan, np.nan, np.nan, np.nan],
|
| 171 |
+
[7, np.nan, 8, 9],
|
| 172 |
+
]
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
# GH20987
|
| 176 |
+
with pytest.raises(TypeError, match="supplying multiple axes"):
|
| 177 |
+
df.dropna(how="all", axis=[0, 1])
|
| 178 |
+
with pytest.raises(TypeError, match="supplying multiple axes"):
|
| 179 |
+
df.dropna(how="all", axis=(0, 1))
|
| 180 |
+
|
| 181 |
+
inp = df.copy()
|
| 182 |
+
with pytest.raises(TypeError, match="supplying multiple axes"):
|
| 183 |
+
inp.dropna(how="all", axis=(0, 1), inplace=True)
|
| 184 |
+
|
| 185 |
+
def test_dropna_tz_aware_datetime(self):
|
| 186 |
+
# GH13407
|
| 187 |
+
df = DataFrame()
|
| 188 |
+
dt1 = datetime.datetime(2015, 1, 1, tzinfo=dateutil.tz.tzutc())
|
| 189 |
+
dt2 = datetime.datetime(2015, 2, 2, tzinfo=dateutil.tz.tzutc())
|
| 190 |
+
df["Time"] = [dt1]
|
| 191 |
+
result = df.dropna(axis=0)
|
| 192 |
+
expected = DataFrame({"Time": [dt1]})
|
| 193 |
+
tm.assert_frame_equal(result, expected)
|
| 194 |
+
|
| 195 |
+
# Ex2
|
| 196 |
+
df = DataFrame({"Time": [dt1, None, np.nan, dt2]})
|
| 197 |
+
result = df.dropna(axis=0)
|
| 198 |
+
expected = DataFrame([dt1, dt2], columns=["Time"], index=[0, 3])
|
| 199 |
+
tm.assert_frame_equal(result, expected)
|
| 200 |
+
|
| 201 |
+
def test_dropna_categorical_interval_index(self):
|
| 202 |
+
# GH 25087
|
| 203 |
+
ii = pd.IntervalIndex.from_breaks([0, 2.78, 3.14, 6.28])
|
| 204 |
+
ci = pd.CategoricalIndex(ii)
|
| 205 |
+
df = DataFrame({"A": list("abc")}, index=ci)
|
| 206 |
+
|
| 207 |
+
expected = df
|
| 208 |
+
result = df.dropna()
|
| 209 |
+
tm.assert_frame_equal(result, expected)
|
| 210 |
+
|
| 211 |
+
def test_dropna_with_duplicate_columns(self):
|
| 212 |
+
df = DataFrame(
|
| 213 |
+
{
|
| 214 |
+
"A": np.random.default_rng(2).standard_normal(5),
|
| 215 |
+
"B": np.random.default_rng(2).standard_normal(5),
|
| 216 |
+
"C": np.random.default_rng(2).standard_normal(5),
|
| 217 |
+
"D": ["a", "b", "c", "d", "e"],
|
| 218 |
+
}
|
| 219 |
+
)
|
| 220 |
+
df.iloc[2, [0, 1, 2]] = np.nan
|
| 221 |
+
df.iloc[0, 0] = np.nan
|
| 222 |
+
df.iloc[1, 1] = np.nan
|
| 223 |
+
df.iloc[:, 3] = np.nan
|
| 224 |
+
expected = df.dropna(subset=["A", "B", "C"], how="all")
|
| 225 |
+
expected.columns = ["A", "A", "B", "C"]
|
| 226 |
+
|
| 227 |
+
df.columns = ["A", "A", "B", "C"]
|
| 228 |
+
|
| 229 |
+
result = df.dropna(subset=["A", "C"], how="all")
|
| 230 |
+
tm.assert_frame_equal(result, expected)
|
| 231 |
+
|
| 232 |
+
def test_set_single_column_subset(self):
|
| 233 |
+
# GH 41021
|
| 234 |
+
df = DataFrame({"A": [1, 2, 3], "B": list("abc"), "C": [4, np.nan, 5]})
|
| 235 |
+
expected = DataFrame(
|
| 236 |
+
{"A": [1, 3], "B": list("ac"), "C": [4.0, 5.0]}, index=[0, 2]
|
| 237 |
+
)
|
| 238 |
+
result = df.dropna(subset="C")
|
| 239 |
+
tm.assert_frame_equal(result, expected)
|
| 240 |
+
|
| 241 |
+
def test_single_column_not_present_in_axis(self):
|
| 242 |
+
# GH 41021
|
| 243 |
+
df = DataFrame({"A": [1, 2, 3]})
|
| 244 |
+
|
| 245 |
+
# Column not present
|
| 246 |
+
with pytest.raises(KeyError, match="['D']"):
|
| 247 |
+
df.dropna(subset="D", axis=0)
|
| 248 |
+
|
| 249 |
+
def test_subset_is_nparray(self):
|
| 250 |
+
# GH 41021
|
| 251 |
+
df = DataFrame({"A": [1, 2, np.nan], "B": list("abc"), "C": [4, np.nan, 5]})
|
| 252 |
+
expected = DataFrame({"A": [1.0], "B": ["a"], "C": [4.0]})
|
| 253 |
+
result = df.dropna(subset=np.array(["A", "C"]))
|
| 254 |
+
tm.assert_frame_equal(result, expected)
|
| 255 |
+
|
| 256 |
+
def test_no_nans_in_frame(self, axis):
|
| 257 |
+
# GH#41965
|
| 258 |
+
df = DataFrame([[1, 2], [3, 4]], columns=pd.RangeIndex(0, 2))
|
| 259 |
+
expected = df.copy()
|
| 260 |
+
result = df.dropna(axis=axis)
|
| 261 |
+
tm.assert_frame_equal(result, expected, check_index_type=True)
|
| 262 |
+
|
| 263 |
+
def test_how_thresh_param_incompatible(self):
|
| 264 |
+
# GH46575
|
| 265 |
+
df = DataFrame([1, 2, pd.NA])
|
| 266 |
+
msg = "You cannot set both the how and thresh arguments at the same time"
|
| 267 |
+
with pytest.raises(TypeError, match=msg):
|
| 268 |
+
df.dropna(how="all", thresh=2)
|
| 269 |
+
|
| 270 |
+
with pytest.raises(TypeError, match=msg):
|
| 271 |
+
df.dropna(how="any", thresh=2)
|
| 272 |
+
|
| 273 |
+
with pytest.raises(TypeError, match=msg):
|
| 274 |
+
df.dropna(how=None, thresh=None)
|
| 275 |
+
|
| 276 |
+
@pytest.mark.parametrize("val", [1, 1.5])
|
| 277 |
+
def test_dropna_ignore_index(self, val):
|
| 278 |
+
# GH#31725
|
| 279 |
+
df = DataFrame({"a": [1, 2, val]}, index=[3, 2, 1])
|
| 280 |
+
result = df.dropna(ignore_index=True)
|
| 281 |
+
expected = DataFrame({"a": [1, 2, val]})
|
| 282 |
+
tm.assert_frame_equal(result, expected)
|
| 283 |
+
|
| 284 |
+
df.dropna(ignore_index=True, inplace=True)
|
| 285 |
+
tm.assert_frame_equal(df, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_dtypes.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import timedelta
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas.core.dtypes.dtypes import DatetimeTZDtype
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from pandas import (
|
| 10 |
+
DataFrame,
|
| 11 |
+
Series,
|
| 12 |
+
date_range,
|
| 13 |
+
option_context,
|
| 14 |
+
)
|
| 15 |
+
import pandas._testing as tm
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TestDataFrameDataTypes:
|
| 19 |
+
def test_empty_frame_dtypes(self):
|
| 20 |
+
empty_df = DataFrame()
|
| 21 |
+
tm.assert_series_equal(empty_df.dtypes, Series(dtype=object))
|
| 22 |
+
|
| 23 |
+
nocols_df = DataFrame(index=[1, 2, 3])
|
| 24 |
+
tm.assert_series_equal(nocols_df.dtypes, Series(dtype=object))
|
| 25 |
+
|
| 26 |
+
norows_df = DataFrame(columns=list("abc"))
|
| 27 |
+
tm.assert_series_equal(norows_df.dtypes, Series(object, index=list("abc")))
|
| 28 |
+
|
| 29 |
+
norows_int_df = DataFrame(columns=list("abc")).astype(np.int32)
|
| 30 |
+
tm.assert_series_equal(
|
| 31 |
+
norows_int_df.dtypes, Series(np.dtype("int32"), index=list("abc"))
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
df = DataFrame({"a": 1, "b": True, "c": 1.0}, index=[1, 2, 3])
|
| 35 |
+
ex_dtypes = Series({"a": np.int64, "b": np.bool_, "c": np.float64})
|
| 36 |
+
tm.assert_series_equal(df.dtypes, ex_dtypes)
|
| 37 |
+
|
| 38 |
+
# same but for empty slice of df
|
| 39 |
+
tm.assert_series_equal(df[:0].dtypes, ex_dtypes)
|
| 40 |
+
|
| 41 |
+
def test_datetime_with_tz_dtypes(self):
|
| 42 |
+
tzframe = DataFrame(
|
| 43 |
+
{
|
| 44 |
+
"A": date_range("20130101", periods=3),
|
| 45 |
+
"B": date_range("20130101", periods=3, tz="US/Eastern"),
|
| 46 |
+
"C": date_range("20130101", periods=3, tz="CET"),
|
| 47 |
+
}
|
| 48 |
+
)
|
| 49 |
+
tzframe.iloc[1, 1] = pd.NaT
|
| 50 |
+
tzframe.iloc[1, 2] = pd.NaT
|
| 51 |
+
result = tzframe.dtypes.sort_index()
|
| 52 |
+
expected = Series(
|
| 53 |
+
[
|
| 54 |
+
np.dtype("datetime64[ns]"),
|
| 55 |
+
DatetimeTZDtype("ns", "US/Eastern"),
|
| 56 |
+
DatetimeTZDtype("ns", "CET"),
|
| 57 |
+
],
|
| 58 |
+
["A", "B", "C"],
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
tm.assert_series_equal(result, expected)
|
| 62 |
+
|
| 63 |
+
def test_dtypes_are_correct_after_column_slice(self):
|
| 64 |
+
# GH6525
|
| 65 |
+
df = DataFrame(index=range(5), columns=list("abc"), dtype=np.float64)
|
| 66 |
+
tm.assert_series_equal(
|
| 67 |
+
df.dtypes,
|
| 68 |
+
Series({"a": np.float64, "b": np.float64, "c": np.float64}),
|
| 69 |
+
)
|
| 70 |
+
tm.assert_series_equal(df.iloc[:, 2:].dtypes, Series({"c": np.float64}))
|
| 71 |
+
tm.assert_series_equal(
|
| 72 |
+
df.dtypes,
|
| 73 |
+
Series({"a": np.float64, "b": np.float64, "c": np.float64}),
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
@pytest.mark.parametrize(
|
| 77 |
+
"data",
|
| 78 |
+
[pd.NA, True],
|
| 79 |
+
)
|
| 80 |
+
def test_dtypes_are_correct_after_groupby_last(self, data):
|
| 81 |
+
# GH46409
|
| 82 |
+
df = DataFrame(
|
| 83 |
+
{"id": [1, 2, 3, 4], "test": [True, pd.NA, data, False]}
|
| 84 |
+
).convert_dtypes()
|
| 85 |
+
result = df.groupby("id").last().test
|
| 86 |
+
expected = df.set_index("id").test
|
| 87 |
+
assert result.dtype == pd.BooleanDtype()
|
| 88 |
+
tm.assert_series_equal(expected, result)
|
| 89 |
+
|
| 90 |
+
def test_dtypes_gh8722(self, float_string_frame):
|
| 91 |
+
float_string_frame["bool"] = float_string_frame["A"] > 0
|
| 92 |
+
result = float_string_frame.dtypes
|
| 93 |
+
expected = Series(
|
| 94 |
+
{k: v.dtype for k, v in float_string_frame.items()}, index=result.index
|
| 95 |
+
)
|
| 96 |
+
tm.assert_series_equal(result, expected)
|
| 97 |
+
|
| 98 |
+
# compat, GH 8722
|
| 99 |
+
msg = "use_inf_as_na option is deprecated"
|
| 100 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 101 |
+
with option_context("use_inf_as_na", True):
|
| 102 |
+
df = DataFrame([[1]])
|
| 103 |
+
result = df.dtypes
|
| 104 |
+
tm.assert_series_equal(result, Series({0: np.dtype("int64")}))
|
| 105 |
+
|
| 106 |
+
def test_dtypes_timedeltas(self):
|
| 107 |
+
df = DataFrame(
|
| 108 |
+
{
|
| 109 |
+
"A": Series(date_range("2012-1-1", periods=3, freq="D")),
|
| 110 |
+
"B": Series([timedelta(days=i) for i in range(3)]),
|
| 111 |
+
}
|
| 112 |
+
)
|
| 113 |
+
result = df.dtypes
|
| 114 |
+
expected = Series(
|
| 115 |
+
[np.dtype("datetime64[ns]"), np.dtype("timedelta64[ns]")], index=list("AB")
|
| 116 |
+
)
|
| 117 |
+
tm.assert_series_equal(result, expected)
|
| 118 |
+
|
| 119 |
+
df["C"] = df["A"] + df["B"]
|
| 120 |
+
result = df.dtypes
|
| 121 |
+
expected = Series(
|
| 122 |
+
[
|
| 123 |
+
np.dtype("datetime64[ns]"),
|
| 124 |
+
np.dtype("timedelta64[ns]"),
|
| 125 |
+
np.dtype("datetime64[ns]"),
|
| 126 |
+
],
|
| 127 |
+
index=list("ABC"),
|
| 128 |
+
)
|
| 129 |
+
tm.assert_series_equal(result, expected)
|
| 130 |
+
|
| 131 |
+
# mixed int types
|
| 132 |
+
df["D"] = 1
|
| 133 |
+
result = df.dtypes
|
| 134 |
+
expected = Series(
|
| 135 |
+
[
|
| 136 |
+
np.dtype("datetime64[ns]"),
|
| 137 |
+
np.dtype("timedelta64[ns]"),
|
| 138 |
+
np.dtype("datetime64[ns]"),
|
| 139 |
+
np.dtype("int64"),
|
| 140 |
+
],
|
| 141 |
+
index=list("ABCD"),
|
| 142 |
+
)
|
| 143 |
+
tm.assert_series_equal(result, expected)
|
| 144 |
+
|
| 145 |
+
def test_frame_apply_np_array_return_type(self, using_infer_string):
|
| 146 |
+
# GH 35517
|
| 147 |
+
df = DataFrame([["foo"]])
|
| 148 |
+
result = df.apply(lambda col: np.array("bar"))
|
| 149 |
+
expected = Series(np.array("bar"))
|
| 150 |
+
tm.assert_series_equal(result, expected)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/pandas/tests/frame/methods/test_duplicated.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from pandas import (
|
| 8 |
+
DataFrame,
|
| 9 |
+
Series,
|
| 10 |
+
date_range,
|
| 11 |
+
)
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.mark.parametrize("subset", ["a", ["a"], ["a", "B"]])
|
| 16 |
+
def test_duplicated_with_misspelled_column_name(subset):
|
| 17 |
+
# GH 19730
|
| 18 |
+
df = DataFrame({"A": [0, 0, 1], "B": [0, 0, 1], "C": [0, 0, 1]})
|
| 19 |
+
msg = re.escape("Index(['a'], dtype=")
|
| 20 |
+
|
| 21 |
+
with pytest.raises(KeyError, match=msg):
|
| 22 |
+
df.duplicated(subset)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_duplicated_implemented_no_recursion():
|
| 26 |
+
# gh-21524
|
| 27 |
+
# Ensure duplicated isn't implemented using recursion that
|
| 28 |
+
# can fail on wide frames
|
| 29 |
+
df = DataFrame(np.random.default_rng(2).integers(0, 1000, (10, 1000)))
|
| 30 |
+
rec_limit = sys.getrecursionlimit()
|
| 31 |
+
try:
|
| 32 |
+
sys.setrecursionlimit(100)
|
| 33 |
+
result = df.duplicated()
|
| 34 |
+
finally:
|
| 35 |
+
sys.setrecursionlimit(rec_limit)
|
| 36 |
+
|
| 37 |
+
# Then duplicates produce the bool Series as a result and don't fail during
|
| 38 |
+
# calculation. Actual values doesn't matter here, though usually it's all
|
| 39 |
+
# False in this case
|
| 40 |
+
assert isinstance(result, Series)
|
| 41 |
+
assert result.dtype == np.bool_
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@pytest.mark.parametrize(
|
| 45 |
+
"keep, expected",
|
| 46 |
+
[
|
| 47 |
+
("first", Series([False, False, True, False, True])),
|
| 48 |
+
("last", Series([True, True, False, False, False])),
|
| 49 |
+
(False, Series([True, True, True, False, True])),
|
| 50 |
+
],
|
| 51 |
+
)
|
| 52 |
+
def test_duplicated_keep(keep, expected):
|
| 53 |
+
df = DataFrame({"A": [0, 1, 1, 2, 0], "B": ["a", "b", "b", "c", "a"]})
|
| 54 |
+
|
| 55 |
+
result = df.duplicated(keep=keep)
|
| 56 |
+
tm.assert_series_equal(result, expected)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@pytest.mark.xfail(reason="GH#21720; nan/None falsely considered equal")
|
| 60 |
+
@pytest.mark.parametrize(
|
| 61 |
+
"keep, expected",
|
| 62 |
+
[
|
| 63 |
+
("first", Series([False, False, True, False, True])),
|
| 64 |
+
("last", Series([True, True, False, False, False])),
|
| 65 |
+
(False, Series([True, True, True, False, True])),
|
| 66 |
+
],
|
| 67 |
+
)
|
| 68 |
+
def test_duplicated_nan_none(keep, expected):
|
| 69 |
+
df = DataFrame({"C": [np.nan, 3, 3, None, np.nan], "x": 1}, dtype=object)
|
| 70 |
+
|
| 71 |
+
result = df.duplicated(keep=keep)
|
| 72 |
+
tm.assert_series_equal(result, expected)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@pytest.mark.parametrize("subset", [None, ["A", "B"], "A"])
|
| 76 |
+
def test_duplicated_subset(subset, keep):
|
| 77 |
+
df = DataFrame(
|
| 78 |
+
{
|
| 79 |
+
"A": [0, 1, 1, 2, 0],
|
| 80 |
+
"B": ["a", "b", "b", "c", "a"],
|
| 81 |
+
"C": [np.nan, 3, 3, None, np.nan],
|
| 82 |
+
}
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
if subset is None:
|
| 86 |
+
subset = list(df.columns)
|
| 87 |
+
elif isinstance(subset, str):
|
| 88 |
+
# need to have a DataFrame, not a Series
|
| 89 |
+
# -> select columns with singleton list, not string
|
| 90 |
+
subset = [subset]
|
| 91 |
+
|
| 92 |
+
expected = df[subset].duplicated(keep=keep)
|
| 93 |
+
result = df.duplicated(keep=keep, subset=subset)
|
| 94 |
+
tm.assert_series_equal(result, expected)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_duplicated_on_empty_frame():
|
| 98 |
+
# GH 25184
|
| 99 |
+
|
| 100 |
+
df = DataFrame(columns=["a", "b"])
|
| 101 |
+
dupes = df.duplicated("a")
|
| 102 |
+
|
| 103 |
+
result = df[dupes]
|
| 104 |
+
expected = df.copy()
|
| 105 |
+
tm.assert_frame_equal(result, expected)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_frame_datetime64_duplicated():
|
| 109 |
+
dates = date_range("2010-07-01", end="2010-08-05")
|
| 110 |
+
|
| 111 |
+
tst = DataFrame({"symbol": "AAA", "date": dates})
|
| 112 |
+
result = tst.duplicated(["date", "symbol"])
|
| 113 |
+
assert (-result).all()
|
| 114 |
+
|
| 115 |
+
tst = DataFrame({"date": dates})
|
| 116 |
+
result = tst.date.duplicated()
|
| 117 |
+
assert (-result).all()
|