Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub (part 14)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/INSTALLER +1 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/METADATA +308 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/RECORD +0 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/REQUESTED +0 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/WHEEL +6 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/entry_points.txt +3 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSE +31 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/BOTTLENECK_LICENCE +25 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/DATEUTIL_LICENSE +54 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_LICENSE +21 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_MIT +32 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/KLIB_LICENSE +23 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/MUSL_LICENSE +193 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/NUMPY_LICENSE +30 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PACKAGING_LICENSE +202 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PSF_LICENSE +279 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PYPERCLIP_LICENSE +27 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PYUPGRADE_LICENSE +19 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/SAS7BDAT_LICENSE +19 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/STATSBASE_JL_LICENSE +23 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/ULTRAJSON_LICENSE +114 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/XSIMD_LICENSE +29 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-APACHE +190 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-BOOST +23 -0
- .venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-MIT +27 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/common/test_index.py +310 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/common/test_inf.py +79 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/common/test_ints.py +265 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/common/test_iterator.py +152 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/common/test_read_errors.py +446 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/conftest.py +326 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/dtypes/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/dtypes/test_categorical.py +873 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/dtypes/test_dtypes_basic.py +1037 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/dtypes/test_empty.py +183 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_c_parser_only.py +1866 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_comment.py +214 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_compression.py +209 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_concatenate_chunks.py +38 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_converters.py +440 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_dialect.py +230 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_encoding.py +409 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_header.py +792 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_index_col.py +426 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_mangle_dupes.py +167 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_multi_thread.py +153 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_na_values.py +939 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_network.py +237 -0
- .venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_parallel_read.py +2256 -0
.gitattributes
CHANGED
|
@@ -123,3 +123,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 123 |
.venv/lib/python3.12/site-packages/pandas/_libs/tslibs/vectorized.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 124 |
.venv/lib/python3.12/site-packages/pandas/_libs/window/aggregations.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 125 |
.venv/lib/python3.12/site-packages/pandas/_libs/writers.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 123 |
.venv/lib/python3.12/site-packages/pandas/_libs/tslibs/vectorized.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 124 |
.venv/lib/python3.12/site-packages/pandas/_libs/window/aggregations.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 125 |
.venv/lib/python3.12/site-packages/pandas/_libs/writers.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 126 |
+
.venv/lib/python3.12/site-packages/pydantic_core/_pydantic_core.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
uv
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: pandas
|
| 3 |
+
Version: 3.1.1
|
| 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-Expression: BSD-3-Clause
|
| 7 |
+
License-File: LICENSE
|
| 8 |
+
License-File: LICENSES/BOTTLENECK_LICENCE
|
| 9 |
+
License-File: LICENSES/DATEUTIL_LICENSE
|
| 10 |
+
License-File: LICENSES/HAVEN_LICENSE
|
| 11 |
+
License-File: LICENSES/HAVEN_MIT
|
| 12 |
+
License-File: LICENSES/KLIB_LICENSE
|
| 13 |
+
License-File: LICENSES/MUSL_LICENSE
|
| 14 |
+
License-File: LICENSES/NUMPY_LICENSE
|
| 15 |
+
License-File: LICENSES/PACKAGING_LICENSE
|
| 16 |
+
License-File: LICENSES/PSF_LICENSE
|
| 17 |
+
License-File: LICENSES/PYPERCLIP_LICENSE
|
| 18 |
+
License-File: LICENSES/PYUPGRADE_LICENSE
|
| 19 |
+
License-File: LICENSES/SAS7BDAT_LICENSE
|
| 20 |
+
License-File: LICENSES/STATSBASE_JL_LICENSE
|
| 21 |
+
License-File: LICENSES/ULTRAJSON_LICENSE
|
| 22 |
+
License-File: LICENSES/XSIMD_LICENSE
|
| 23 |
+
License-File: subprojects/fast_float-8.2.10/LICENSE-APACHE
|
| 24 |
+
License-File: subprojects/fast_float-8.2.10/LICENSE-BOOST
|
| 25 |
+
License-File: subprojects/fast_float-8.2.10/LICENSE-MIT
|
| 26 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 27 |
+
Classifier: Environment :: Console
|
| 28 |
+
Classifier: Intended Audience :: Science/Research
|
| 29 |
+
Classifier: Operating System :: OS Independent
|
| 30 |
+
Classifier: Programming Language :: Cython
|
| 31 |
+
Classifier: Programming Language :: Python
|
| 32 |
+
Classifier: Programming Language :: Python :: 3
|
| 33 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 34 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 35 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 36 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 37 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 38 |
+
Classifier: Programming Language :: Python :: 3.15
|
| 39 |
+
Classifier: Topic :: Scientific/Engineering
|
| 40 |
+
Project-URL: homepage, https://pandas.pydata.org
|
| 41 |
+
Project-URL: source, https://github.com/pandas-dev/pandas
|
| 42 |
+
Project-URL: documentation, https://pandas.pydata.org/docs/
|
| 43 |
+
Project-URL: changelog, https://pandas.pydata.org/docs/whatsnew/index.html
|
| 44 |
+
Project-URL: issues, https://github.com/pandas-dev/pandas/issues
|
| 45 |
+
Project-URL: funding, https://opencollective.com/pandas
|
| 46 |
+
Requires-Python: >=3.11
|
| 47 |
+
Requires-Dist: numpy>=2.0.2; python_version < "3.14"
|
| 48 |
+
Requires-Dist: numpy>=2.3.3; python_version >= "3.14"
|
| 49 |
+
Requires-Dist: python-dateutil>=2.9.0
|
| 50 |
+
Requires-Dist: tzdata; sys_platform == "win32"
|
| 51 |
+
Requires-Dist: tzdata; sys_platform == "emscripten"
|
| 52 |
+
Provides-Extra: test
|
| 53 |
+
Requires-Dist: pytest>=8.3.4; extra == "test"
|
| 54 |
+
Requires-Dist: pytest-xdist>=3.6.1; extra == "test"
|
| 55 |
+
Provides-Extra: pyarrow
|
| 56 |
+
Requires-Dist: pyarrow>=16.0.0; extra == "pyarrow"
|
| 57 |
+
Provides-Extra: performance
|
| 58 |
+
Requires-Dist: bottleneck>=1.5.0; extra == "performance"
|
| 59 |
+
Requires-Dist: numba>=0.61.2; extra == "performance"
|
| 60 |
+
Requires-Dist: numexpr!=2.14.1,>=2.11.0; extra == "performance"
|
| 61 |
+
Provides-Extra: computation
|
| 62 |
+
Requires-Dist: scipy>=1.16.1; extra == "computation"
|
| 63 |
+
Requires-Dist: xarray>=2025.7.1; extra == "computation"
|
| 64 |
+
Provides-Extra: fss
|
| 65 |
+
Requires-Dist: fsspec>=2025.7.0; extra == "fss"
|
| 66 |
+
Provides-Extra: aws
|
| 67 |
+
Requires-Dist: s3fs>=2025.7.0; extra == "aws"
|
| 68 |
+
Provides-Extra: gcp
|
| 69 |
+
Requires-Dist: gcsfs>=2025.7.0; extra == "gcp"
|
| 70 |
+
Provides-Extra: excel
|
| 71 |
+
Requires-Dist: odfpy>=1.4.1; extra == "excel"
|
| 72 |
+
Requires-Dist: openpyxl>=3.1.5; extra == "excel"
|
| 73 |
+
Requires-Dist: python-calamine>=0.4.0; extra == "excel"
|
| 74 |
+
Requires-Dist: pyxlsb>=1.0.10; extra == "excel"
|
| 75 |
+
Requires-Dist: xlrd>=2.0.2; extra == "excel"
|
| 76 |
+
Requires-Dist: xlsxwriter>=3.2.5; extra == "excel"
|
| 77 |
+
Provides-Extra: parquet
|
| 78 |
+
Requires-Dist: pandas[pyarrow]; extra == "parquet"
|
| 79 |
+
Provides-Extra: feather
|
| 80 |
+
Requires-Dist: pandas[pyarrow]; extra == "feather"
|
| 81 |
+
Provides-Extra: iceberg
|
| 82 |
+
Requires-Dist: pyiceberg>=0.9.1; extra == "iceberg"
|
| 83 |
+
Provides-Extra: hdf5
|
| 84 |
+
Requires-Dist: tables>=3.10.2; extra == "hdf5"
|
| 85 |
+
Provides-Extra: spss
|
| 86 |
+
Requires-Dist: pyreadstat>=1.3.0; extra == "spss"
|
| 87 |
+
Provides-Extra: postgresql
|
| 88 |
+
Requires-Dist: SQLAlchemy>=2.0.42; extra == "postgresql"
|
| 89 |
+
Requires-Dist: psycopg2>=2.9.10; extra == "postgresql"
|
| 90 |
+
Requires-Dist: adbc-driver-postgresql>=1.7.0; extra == "postgresql"
|
| 91 |
+
Provides-Extra: mysql
|
| 92 |
+
Requires-Dist: SQLAlchemy>=2.0.42; extra == "mysql"
|
| 93 |
+
Requires-Dist: pymysql>=1.1.1; extra == "mysql"
|
| 94 |
+
Provides-Extra: sql-other
|
| 95 |
+
Requires-Dist: SQLAlchemy>=2.0.42; extra == "sql-other"
|
| 96 |
+
Requires-Dist: adbc-driver-postgresql>=1.7.0; extra == "sql-other"
|
| 97 |
+
Requires-Dist: adbc-driver-sqlite>=1.7.0; extra == "sql-other"
|
| 98 |
+
Provides-Extra: html
|
| 99 |
+
Requires-Dist: beautifulsoup4>=4.13.4; extra == "html"
|
| 100 |
+
Requires-Dist: html5lib>=1.1; extra == "html"
|
| 101 |
+
Requires-Dist: lxml>=6.0.0; extra == "html"
|
| 102 |
+
Provides-Extra: xml
|
| 103 |
+
Requires-Dist: lxml>=6.0.0; extra == "xml"
|
| 104 |
+
Provides-Extra: plot
|
| 105 |
+
Requires-Dist: matplotlib>=3.10.5; extra == "plot"
|
| 106 |
+
Provides-Extra: output-formatting
|
| 107 |
+
Requires-Dist: jinja2>=3.1.6; extra == "output-formatting"
|
| 108 |
+
Requires-Dist: tabulate>=0.9.0; extra == "output-formatting"
|
| 109 |
+
Provides-Extra: clipboard
|
| 110 |
+
Requires-Dist: PyQt5>=5.15.11; extra == "clipboard"
|
| 111 |
+
Requires-Dist: qtpy>=2.4.3; extra == "clipboard"
|
| 112 |
+
Provides-Extra: compression
|
| 113 |
+
Requires-Dist: zstandard>=0.23.0; extra == "compression"
|
| 114 |
+
Provides-Extra: timezone
|
| 115 |
+
Requires-Dist: pytz>=2020.1; extra == "timezone"
|
| 116 |
+
Provides-Extra: all
|
| 117 |
+
Requires-Dist: pandas[aws,clipboard,compression,computation,excel,feather,fss,gcp,hdf5,html,iceberg,mysql,output-formatting,parquet,performance,plot,postgresql,pyarrow,spss,sql-other,test,timezone,xml]; extra == "all"
|
| 118 |
+
Requires-Dist: fastparquet>=2024.11.0; extra == "all"
|
| 119 |
+
Description-Content-Type: text/markdown
|
| 120 |
+
|
| 121 |
+
<picture align="center">
|
| 122 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://pandas.pydata.org/static/img/pandas_white.svg">
|
| 123 |
+
<img alt="Pandas Logo" src="https://pandas.pydata.org/static/img/pandas.svg">
|
| 124 |
+
</picture>
|
| 125 |
+
|
| 126 |
+
-----------------
|
| 127 |
+
|
| 128 |
+
# pandas: A Powerful Python Data Analysis Toolkit
|
| 129 |
+
|
| 130 |
+
| | |
|
| 131 |
+
| --- | --- |
|
| 132 |
+
| Testing | [](https://github.com/pandas-dev/pandas/actions/workflows/unit-tests.yml) [](https://codecov.io/gh/pandas-dev/pandas) |
|
| 133 |
+
| Package | [](https://pypi.org/project/pandas/) [](https://pypi.org/project/pandas/) [](https://anaconda.org/conda-forge/pandas) [](https://anaconda.org/conda-forge/pandas) |
|
| 134 |
+
| Meta | [](https://numfocus.org) [](https://doi.org/10.5281/zenodo.3509134) [](https://github.com/pandas-dev/pandas/blob/main/LICENSE) [](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) [](https://insights.linuxfoundation.org/project/pandas-dev-pandas) |
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
## What is it?
|
| 138 |
+
|
| 139 |
+
**pandas** is a Python package that provides fast, flexible, and expressive data
|
| 140 |
+
structures designed to make working with "relational" or "labeled" data both
|
| 141 |
+
easy and intuitive. It aims to be the fundamental high-level building block for
|
| 142 |
+
doing practical, **real-world** data analysis in Python. Additionally, it has
|
| 143 |
+
the broader goal of becoming **the most powerful and flexible open-source data
|
| 144 |
+
analysis/manipulation tool available in any language**. It is already well on
|
| 145 |
+
its way towards this goal.
|
| 146 |
+
|
| 147 |
+
## Table of Contents
|
| 148 |
+
|
| 149 |
+
- [Main Features](#main-features)
|
| 150 |
+
- [Where to get it](#where-to-get-it)
|
| 151 |
+
- [Dependencies](#dependencies)
|
| 152 |
+
- [Installation from sources](#installation-from-sources)
|
| 153 |
+
- [License](#license)
|
| 154 |
+
- [Documentation](#documentation)
|
| 155 |
+
- [Background](#background)
|
| 156 |
+
- [Getting Help](#getting-help)
|
| 157 |
+
- [Discussion and Development](#discussion-and-development)
|
| 158 |
+
- [Contributing to pandas](#contributing-to-pandas)
|
| 159 |
+
|
| 160 |
+
## Main Features
|
| 161 |
+
Here are just a few of the things that pandas does well:
|
| 162 |
+
|
| 163 |
+
- Easy handling of [**missing data**][missing-data] (represented as
|
| 164 |
+
`NaN`, `NA`, or `NaT`) in floating point as well as non-floating point data
|
| 165 |
+
- Size mutability: columns can be [**inserted and
|
| 166 |
+
deleted**][insertion-deletion] from DataFrame and higher dimensional
|
| 167 |
+
objects
|
| 168 |
+
- Automatic and explicit [**data alignment**][alignment]: objects can
|
| 169 |
+
be explicitly aligned to a set of labels, or the user can simply
|
| 170 |
+
ignore the labels and let `Series`, `DataFrame`, etc. automatically
|
| 171 |
+
align the data for you in computations
|
| 172 |
+
- Powerful, flexible [**group by**][groupby] functionality to perform
|
| 173 |
+
split-apply-combine operations on data sets, for both aggregating
|
| 174 |
+
and transforming data
|
| 175 |
+
- Make it [**easy to convert**][conversion] ragged,
|
| 176 |
+
differently-indexed data in other Python and NumPy data structures
|
| 177 |
+
into DataFrame objects
|
| 178 |
+
- Intelligent label-based [**slicing**][slicing], [**fancy
|
| 179 |
+
indexing**][fancy-indexing], and [**subsetting**][subsetting] of
|
| 180 |
+
large data sets
|
| 181 |
+
- Intuitive [**merging**][merging] and [**joining**][joining] data
|
| 182 |
+
sets
|
| 183 |
+
- Flexible [**reshaping**][reshape] and [**pivoting**][pivot-table] of
|
| 184 |
+
data sets
|
| 185 |
+
- [**Hierarchical**][mi] labeling of axes (possible to have multiple
|
| 186 |
+
labels per tick)
|
| 187 |
+
- Robust I/O tools for loading data from [**flat files**][flat-files]
|
| 188 |
+
(CSV and delimited), [**Excel files**][excel], [**databases**][db],
|
| 189 |
+
and saving/loading data from the ultrafast [**HDF5 format**][hdfstore]
|
| 190 |
+
- [**Time series**][timeseries]-specific functionality: date range
|
| 191 |
+
generation and frequency conversion, moving window statistics,
|
| 192 |
+
date shifting and lagging
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
[missing-data]: https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html
|
| 196 |
+
[insertion-deletion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#column-selection-addition-deletion
|
| 197 |
+
[alignment]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html?highlight=alignment#intro-to-data-structures
|
| 198 |
+
[groupby]: https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#group-by-split-apply-combine
|
| 199 |
+
[conversion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#dataframe
|
| 200 |
+
[slicing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#slicing-ranges
|
| 201 |
+
[fancy-indexing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced
|
| 202 |
+
[subsetting]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing
|
| 203 |
+
[merging]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#database-style-dataframe-or-named-series-joining-merging
|
| 204 |
+
[joining]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#joining-on-index
|
| 205 |
+
[reshape]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html
|
| 206 |
+
[pivot-table]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html
|
| 207 |
+
[mi]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#hierarchical-indexing-multiindex
|
| 208 |
+
[flat-files]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#csv-text-files
|
| 209 |
+
[excel]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#excel-files
|
| 210 |
+
[db]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#sql-queries
|
| 211 |
+
[hdfstore]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#hdf5-pytables
|
| 212 |
+
[timeseries]: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#time-series-date-functionality
|
| 213 |
+
|
| 214 |
+
## Where to get it
|
| 215 |
+
The source code is currently hosted on GitHub at:
|
| 216 |
+
https://github.com/pandas-dev/pandas
|
| 217 |
+
|
| 218 |
+
Binary installers for the latest released version are available at the [Python
|
| 219 |
+
Package Index (PyPI)](https://pypi.org/project/pandas) and on [Conda](https://anaconda.org/conda-forge/pandas).
|
| 220 |
+
|
| 221 |
+
```sh
|
| 222 |
+
# conda
|
| 223 |
+
conda install -c conda-forge pandas
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
```sh
|
| 227 |
+
# or PyPI
|
| 228 |
+
pip install pandas
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
The list of changes to pandas between each release can be found
|
| 232 |
+
[here](https://pandas.pydata.org/pandas-docs/stable/whatsnew/index.html). For full
|
| 233 |
+
details, see the commit logs at https://github.com/pandas-dev/pandas.
|
| 234 |
+
|
| 235 |
+
## Dependencies
|
| 236 |
+
- [NumPy - Adds support for large, multi-dimensional arrays, matrices and high-level mathematical functions to operate on these arrays](https://www.numpy.org)
|
| 237 |
+
- [python-dateutil - Provides powerful extensions to the standard datetime module](https://dateutil.readthedocs.io/en/stable/index.html)
|
| 238 |
+
- [tzdata - Provides an IANA time zone database](https://tzdata.python.org) (Only required on Windows/Emscripten)
|
| 239 |
+
|
| 240 |
+
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.
|
| 241 |
+
|
| 242 |
+
## Installation from sources
|
| 243 |
+
To install pandas from source you need [Cython](https://cython.org/) in addition to the normal
|
| 244 |
+
dependencies above. Cython can be installed from PyPI:
|
| 245 |
+
|
| 246 |
+
```sh
|
| 247 |
+
pip install cython
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
In the `pandas` directory (same one where you found this file after
|
| 251 |
+
cloning the git repo), execute:
|
| 252 |
+
|
| 253 |
+
```sh
|
| 254 |
+
pip install .
|
| 255 |
+
```
|
| 256 |
+
|
| 257 |
+
or for installing in [development mode](https://pip.pypa.io/en/latest/cli/pip_install/#install-editable):
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
```sh
|
| 261 |
+
python -m pip install -ve . --no-build-isolation --config-settings editable-verbose=true
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
See the full instructions for [installing from source](https://pandas.pydata.org/docs/dev/development/contributing_environment.html).
|
| 265 |
+
|
| 266 |
+
## License
|
| 267 |
+
[BSD 3](LICENSE)
|
| 268 |
+
|
| 269 |
+
## Documentation
|
| 270 |
+
The official documentation is hosted on [PyData.org](https://pandas.pydata.org/pandas-docs/stable/).
|
| 271 |
+
|
| 272 |
+
## Background
|
| 273 |
+
Work on ``pandas`` started at [AQR](https://www.aqr.com/) (a quantitative hedge fund) in 2008 and
|
| 274 |
+
has been under active development since then.
|
| 275 |
+
|
| 276 |
+
## Getting Help
|
| 277 |
+
|
| 278 |
+
For usage questions, the best place to go to is [Stack Overflow](https://stackoverflow.com/questions/tagged/pandas).
|
| 279 |
+
Further, general questions and discussions can also take place on the [pydata mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata).
|
| 280 |
+
|
| 281 |
+
## Discussion and Development
|
| 282 |
+
Most development discussions take place on GitHub in this repo, via the [GitHub issue tracker](https://github.com/pandas-dev/pandas/issues).
|
| 283 |
+
|
| 284 |
+
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.
|
| 285 |
+
|
| 286 |
+
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.
|
| 287 |
+
|
| 288 |
+
Additional information on the communication channels can be found on the [contributor community](https://pandas.pydata.org/docs/development/community.html) page.
|
| 289 |
+
|
| 290 |
+
## Contributing to pandas
|
| 291 |
+
|
| 292 |
+
[](https://www.codetriage.com/pandas-dev/pandas)
|
| 293 |
+
|
| 294 |
+
All contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome.
|
| 295 |
+
|
| 296 |
+
A detailed overview on how to contribute can be found in the **[contributing guide](https://pandas.pydata.org/docs/dev/development/contributing.html)**.
|
| 297 |
+
|
| 298 |
+
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).
|
| 299 |
+
|
| 300 |
+
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!
|
| 301 |
+
|
| 302 |
+
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).
|
| 303 |
+
|
| 304 |
+
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)
|
| 305 |
+
|
| 306 |
+
<hr>
|
| 307 |
+
|
| 308 |
+
[Go to Top](#table-of-contents)
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/RECORD
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/REQUESTED
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: meson
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp312-cp312-macosx_11_0_arm64
|
| 5 |
+
Generator: delocate 0.13.0
|
| 6 |
+
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pandas_plotting_backends]
|
| 2 |
+
matplotlib = pandas:plotting._matplotlib
|
| 3 |
+
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
BSD 3-Clause License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team
|
| 4 |
+
All rights reserved.
|
| 5 |
+
|
| 6 |
+
Copyright (c) 2011-2026, Open source contributors.
|
| 7 |
+
|
| 8 |
+
Redistribution and use in source and binary forms, with or without
|
| 9 |
+
modification, are permitted provided that the following conditions are met:
|
| 10 |
+
|
| 11 |
+
* Redistributions of source code must retain the above copyright notice, this
|
| 12 |
+
list of conditions and the following disclaimer.
|
| 13 |
+
|
| 14 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
| 15 |
+
this list of conditions and the following disclaimer in the documentation
|
| 16 |
+
and/or other materials provided with the distribution.
|
| 17 |
+
|
| 18 |
+
* Neither the name of the copyright holder nor the names of its
|
| 19 |
+
contributors may be used to endorse or promote products derived from
|
| 20 |
+
this software without specific prior written permission.
|
| 21 |
+
|
| 22 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 23 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 24 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 25 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 26 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 27 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 28 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 29 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 30 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 31 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/BOTTLENECK_LICENCE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2010-2019 Keith Goodman
|
| 2 |
+
Copyright (c) 2019 Bottleneck Developers
|
| 3 |
+
All rights reserved.
|
| 4 |
+
|
| 5 |
+
Redistribution and use in source and binary forms, with or without
|
| 6 |
+
modification, are permitted provided that the following conditions are met:
|
| 7 |
+
|
| 8 |
+
* Redistributions of source code must retain the above copyright notice,
|
| 9 |
+
this list of conditions and the following disclaimer.
|
| 10 |
+
|
| 11 |
+
* Redistributions in binary form must reproduce the above copyright
|
| 12 |
+
notice, this list of conditions and the following disclaimer in the
|
| 13 |
+
documentation and/or other materials provided with the distribution.
|
| 14 |
+
|
| 15 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 16 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 17 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
| 18 |
+
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
| 19 |
+
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
| 20 |
+
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
| 21 |
+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
| 22 |
+
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
| 23 |
+
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
| 24 |
+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 25 |
+
POSSIBILITY OF SUCH DAMAGE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/DATEUTIL_LICENSE
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright 2017- Paul Ganssle <paul@ganssle.io>
|
| 2 |
+
Copyright 2017- dateutil contributors (see AUTHORS file)
|
| 3 |
+
|
| 4 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
you may not use this file except in compliance with the License.
|
| 6 |
+
You may obtain a copy of the License at
|
| 7 |
+
|
| 8 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
|
| 10 |
+
Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
See the License for the specific language governing permissions and
|
| 14 |
+
limitations under the License.
|
| 15 |
+
|
| 16 |
+
The above license applies to all contributions after 2017-12-01, as well as
|
| 17 |
+
all contributions that have been re-licensed (see AUTHORS file for the list of
|
| 18 |
+
contributors who have re-licensed their code).
|
| 19 |
+
--------------------------------------------------------------------------------
|
| 20 |
+
dateutil - Extensions to the standard Python datetime module.
|
| 21 |
+
|
| 22 |
+
Copyright (c) 2003-2011 - Gustavo Niemeyer <gustavo@niemeyer.net>
|
| 23 |
+
Copyright (c) 2012-2014 - Tomi Pieviläinen <tomi.pievilainen@iki.fi>
|
| 24 |
+
Copyright (c) 2014-2016 - Yaron de Leeuw <me@jarondl.net>
|
| 25 |
+
Copyright (c) 2015- - Paul Ganssle <paul@ganssle.io>
|
| 26 |
+
Copyright (c) 2015- - dateutil contributors (see AUTHORS file)
|
| 27 |
+
|
| 28 |
+
All rights reserved.
|
| 29 |
+
|
| 30 |
+
Redistribution and use in source and binary forms, with or without
|
| 31 |
+
modification, are permitted provided that the following conditions are met:
|
| 32 |
+
|
| 33 |
+
* Redistributions of source code must retain the above copyright notice,
|
| 34 |
+
this list of conditions and the following disclaimer.
|
| 35 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
| 36 |
+
this list of conditions and the following disclaimer in the documentation
|
| 37 |
+
and/or other materials provided with the distribution.
|
| 38 |
+
* Neither the name of the copyright holder nor the names of its
|
| 39 |
+
contributors may be used to endorse or promote products derived from
|
| 40 |
+
this software without specific prior written permission.
|
| 41 |
+
|
| 42 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 43 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 44 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 45 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
| 46 |
+
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
| 47 |
+
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
| 48 |
+
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
| 49 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
| 50 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
| 51 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 52 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 53 |
+
|
| 54 |
+
The above BSD License Applies to all code, even that also covered by Apache 2.0.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2019 Hadley Wickham; RStudio; and Evan Miller
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/HAVEN_MIT
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Based on http://opensource.org/licenses/MIT
|
| 2 |
+
|
| 3 |
+
This is a template. Complete and ship as file LICENSE the following 2
|
| 4 |
+
lines (only)
|
| 5 |
+
|
| 6 |
+
YEAR:
|
| 7 |
+
COPYRIGHT HOLDER:
|
| 8 |
+
|
| 9 |
+
and specify as
|
| 10 |
+
|
| 11 |
+
License: MIT + file LICENSE
|
| 12 |
+
|
| 13 |
+
Copyright (c) <YEAR>, <COPYRIGHT HOLDER>
|
| 14 |
+
|
| 15 |
+
Permission is hereby granted, free of charge, to any person obtaining
|
| 16 |
+
a copy of this software and associated documentation files (the
|
| 17 |
+
"Software"), to deal in the Software without restriction, including
|
| 18 |
+
without limitation the rights to use, copy, modify, merge, publish,
|
| 19 |
+
distribute, sublicense, and/or sell copies of the Software, and to
|
| 20 |
+
permit persons to whom the Software is furnished to do so, subject to
|
| 21 |
+
the following conditions:
|
| 22 |
+
|
| 23 |
+
The above copyright notice and this permission notice shall be
|
| 24 |
+
included in all copies or substantial portions of the Software.
|
| 25 |
+
|
| 26 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 27 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 28 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 29 |
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
| 30 |
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
| 31 |
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
| 32 |
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/KLIB_LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2008- Attractive Chaos <attractor@live.co.uk>
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining
|
| 6 |
+
a copy of this software and associated documentation files (the
|
| 7 |
+
"Software"), to deal in the Software without restriction, including
|
| 8 |
+
without limitation the rights to use, copy, modify, merge, publish,
|
| 9 |
+
distribute, sublicense, and/or sell copies of the Software, and to
|
| 10 |
+
permit persons to whom the Software is furnished to do so, subject to
|
| 11 |
+
the following conditions:
|
| 12 |
+
|
| 13 |
+
The above copyright notice and this permission notice shall be
|
| 14 |
+
included in all copies or substantial portions of the Software.
|
| 15 |
+
|
| 16 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 17 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 18 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 19 |
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
| 20 |
+
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
| 21 |
+
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
| 22 |
+
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 23 |
+
SOFTWARE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/MUSL_LICENSE
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
musl as a whole is licensed under the following standard MIT license:
|
| 2 |
+
|
| 3 |
+
----------------------------------------------------------------------
|
| 4 |
+
Copyright © 2005-2020 Rich Felker, et al.
|
| 5 |
+
|
| 6 |
+
Permission is hereby granted, free of charge, to any person obtaining
|
| 7 |
+
a copy of this software and associated documentation files (the
|
| 8 |
+
"Software"), to deal in the Software without restriction, including
|
| 9 |
+
without limitation the rights to use, copy, modify, merge, publish,
|
| 10 |
+
distribute, sublicense, and/or sell copies of the Software, and to
|
| 11 |
+
permit persons to whom the Software is furnished to do so, subject to
|
| 12 |
+
the following conditions:
|
| 13 |
+
|
| 14 |
+
The above copyright notice and this permission notice shall be
|
| 15 |
+
included in all copies or substantial portions of the Software.
|
| 16 |
+
|
| 17 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 18 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 19 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
| 20 |
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
| 21 |
+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
| 22 |
+
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
| 23 |
+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
| 24 |
+
----------------------------------------------------------------------
|
| 25 |
+
|
| 26 |
+
Authors/contributors include:
|
| 27 |
+
|
| 28 |
+
A. Wilcox
|
| 29 |
+
Ada Worcester
|
| 30 |
+
Alex Dowad
|
| 31 |
+
Alex Suykov
|
| 32 |
+
Alexander Monakov
|
| 33 |
+
Andre McCurdy
|
| 34 |
+
Andrew Kelley
|
| 35 |
+
Anthony G. Basile
|
| 36 |
+
Aric Belsito
|
| 37 |
+
Arvid Picciani
|
| 38 |
+
Bartosz Brachaczek
|
| 39 |
+
Benjamin Peterson
|
| 40 |
+
Bobby Bingham
|
| 41 |
+
Boris Brezillon
|
| 42 |
+
Brent Cook
|
| 43 |
+
Chris Spiegel
|
| 44 |
+
Clément Vasseur
|
| 45 |
+
Daniel Micay
|
| 46 |
+
Daniel Sabogal
|
| 47 |
+
Daurnimator
|
| 48 |
+
David Carlier
|
| 49 |
+
David Edelsohn
|
| 50 |
+
Denys Vlasenko
|
| 51 |
+
Dmitry Ivanov
|
| 52 |
+
Dmitry V. Levin
|
| 53 |
+
Drew DeVault
|
| 54 |
+
Emil Renner Berthing
|
| 55 |
+
Fangrui Song
|
| 56 |
+
Felix Fietkau
|
| 57 |
+
Felix Janda
|
| 58 |
+
Gianluca Anzolin
|
| 59 |
+
Hauke Mehrtens
|
| 60 |
+
He X
|
| 61 |
+
Hiltjo Posthuma
|
| 62 |
+
Isaac Dunham
|
| 63 |
+
Jaydeep Patil
|
| 64 |
+
Jens Gustedt
|
| 65 |
+
Jeremy Huntwork
|
| 66 |
+
Jo-Philipp Wich
|
| 67 |
+
Joakim Sindholt
|
| 68 |
+
John Spencer
|
| 69 |
+
Julien Ramseier
|
| 70 |
+
Justin Cormack
|
| 71 |
+
Kaarle Ritvanen
|
| 72 |
+
Khem Raj
|
| 73 |
+
Kylie McClain
|
| 74 |
+
Leah Neukirchen
|
| 75 |
+
Luca Barbato
|
| 76 |
+
Luka Perkov
|
| 77 |
+
M Farkas-Dyck (Strake)
|
| 78 |
+
Mahesh Bodapati
|
| 79 |
+
Markus Wichmann
|
| 80 |
+
Masanori Ogino
|
| 81 |
+
Michael Clark
|
| 82 |
+
Michael Forney
|
| 83 |
+
Mikhail Kremnyov
|
| 84 |
+
Natanael Copa
|
| 85 |
+
Nicholas J. Kain
|
| 86 |
+
orc
|
| 87 |
+
Pascal Cuoq
|
| 88 |
+
Patrick Oppenlander
|
| 89 |
+
Petr Hosek
|
| 90 |
+
Petr Skocik
|
| 91 |
+
Pierre Carrier
|
| 92 |
+
Reini Urban
|
| 93 |
+
Rich Felker
|
| 94 |
+
Richard Pennington
|
| 95 |
+
Ryan Fairfax
|
| 96 |
+
Samuel Holland
|
| 97 |
+
Segev Finer
|
| 98 |
+
Shiz
|
| 99 |
+
sin
|
| 100 |
+
Solar Designer
|
| 101 |
+
Stefan Kristiansson
|
| 102 |
+
Stefan O'Rear
|
| 103 |
+
Szabolcs Nagy
|
| 104 |
+
Timo Teräs
|
| 105 |
+
Trutz Behn
|
| 106 |
+
Valentin Ochs
|
| 107 |
+
Will Dietz
|
| 108 |
+
William Haddon
|
| 109 |
+
William Pitcock
|
| 110 |
+
|
| 111 |
+
Portions of this software are derived from third-party works licensed
|
| 112 |
+
under terms compatible with the above MIT license:
|
| 113 |
+
|
| 114 |
+
The TRE regular expression implementation (src/regex/reg* and
|
| 115 |
+
src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed
|
| 116 |
+
under a 2-clause BSD license (license text in the source files). The
|
| 117 |
+
included version has been heavily modified by Rich Felker in 2012, in
|
| 118 |
+
the interests of size, simplicity, and namespace cleanliness.
|
| 119 |
+
|
| 120 |
+
Much of the math library code (src/math/* and src/complex/*) is
|
| 121 |
+
Copyright © 1993,2004 Sun Microsystems or
|
| 122 |
+
Copyright © 2003-2011 David Schultz or
|
| 123 |
+
Copyright © 2003-2009 Steven G. Kargl or
|
| 124 |
+
Copyright © 2003-2009 Bruce D. Evans or
|
| 125 |
+
Copyright © 2008 Stephen L. Moshier or
|
| 126 |
+
Copyright © 2017-2018 Arm Limited
|
| 127 |
+
and labelled as such in comments in the individual source files. All
|
| 128 |
+
have been licensed under extremely permissive terms.
|
| 129 |
+
|
| 130 |
+
The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008
|
| 131 |
+
The Android Open Source Project and is licensed under a two-clause BSD
|
| 132 |
+
license. It was taken from Bionic libc, used on Android.
|
| 133 |
+
|
| 134 |
+
The AArch64 memcpy and memset code (src/string/aarch64/*) are
|
| 135 |
+
Copyright © 1999-2019, Arm Limited.
|
| 136 |
+
|
| 137 |
+
The implementation of DES for crypt (src/crypt/crypt_des.c) is
|
| 138 |
+
Copyright © 1994 David Burren. It is licensed under a BSD license.
|
| 139 |
+
|
| 140 |
+
The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was
|
| 141 |
+
originally written by Solar Designer and placed into the public
|
| 142 |
+
domain. The code also comes with a fallback permissive license for use
|
| 143 |
+
in jurisdictions that may not recognize the public domain.
|
| 144 |
+
|
| 145 |
+
The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011
|
| 146 |
+
Valentin Ochs and is licensed under an MIT-style license.
|
| 147 |
+
|
| 148 |
+
The x86_64 port was written by Nicholas J. Kain and is licensed under
|
| 149 |
+
the standard MIT terms.
|
| 150 |
+
|
| 151 |
+
The mips and microblaze ports were originally written by Richard
|
| 152 |
+
Pennington for use in the ellcc project. The original code was adapted
|
| 153 |
+
by Rich Felker for build system and code conventions during upstream
|
| 154 |
+
integration. It is licensed under the standard MIT terms.
|
| 155 |
+
|
| 156 |
+
The mips64 port was contributed by Imagination Technologies and is
|
| 157 |
+
licensed under the standard MIT terms.
|
| 158 |
+
|
| 159 |
+
The powerpc port was also originally written by Richard Pennington,
|
| 160 |
+
and later supplemented and integrated by John Spencer. It is licensed
|
| 161 |
+
under the standard MIT terms.
|
| 162 |
+
|
| 163 |
+
All other files which have no copyright comments are original works
|
| 164 |
+
produced specifically for use as part of this library, written either
|
| 165 |
+
by Rich Felker, the main author of the library, or by one or more
|
| 166 |
+
contibutors listed above. Details on authorship of individual files
|
| 167 |
+
can be found in the git version control history of the project. The
|
| 168 |
+
omission of copyright and license comments in each file is in the
|
| 169 |
+
interest of source tree size.
|
| 170 |
+
|
| 171 |
+
In addition, permission is hereby granted for all public header files
|
| 172 |
+
(include/* and arch/*/bits/*) and crt files intended to be linked into
|
| 173 |
+
applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit
|
| 174 |
+
the copyright notice and permission notice otherwise required by the
|
| 175 |
+
license, and to use these files without any requirement of
|
| 176 |
+
attribution. These files include substantial contributions from:
|
| 177 |
+
|
| 178 |
+
Bobby Bingham
|
| 179 |
+
John Spencer
|
| 180 |
+
Nicholas J. Kain
|
| 181 |
+
Rich Felker
|
| 182 |
+
Richard Pennington
|
| 183 |
+
Stefan Kristiansson
|
| 184 |
+
Szabolcs Nagy
|
| 185 |
+
|
| 186 |
+
all of whom have explicitly granted such permission.
|
| 187 |
+
|
| 188 |
+
This file previously contained text expressing a belief that most of
|
| 189 |
+
the files covered by the above exception were sufficiently trivial not
|
| 190 |
+
to be subject to copyright, resulting in confusion over whether it
|
| 191 |
+
negated the permissions granted in the license. In the spirit of
|
| 192 |
+
permissive licensing, and of not having licensing issues being an
|
| 193 |
+
obstacle to adoption, that text has been removed.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/NUMPY_LICENSE
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2005-2023, NumPy Developers.
|
| 2 |
+
All rights reserved.
|
| 3 |
+
|
| 4 |
+
Redistribution and use in source and binary forms, with or without
|
| 5 |
+
modification, are permitted provided that the following conditions are
|
| 6 |
+
met:
|
| 7 |
+
|
| 8 |
+
* Redistributions of source code must retain the above copyright
|
| 9 |
+
notice, this list of conditions and the following disclaimer.
|
| 10 |
+
|
| 11 |
+
* Redistributions in binary form must reproduce the above
|
| 12 |
+
copyright notice, this list of conditions and the following
|
| 13 |
+
disclaimer in the documentation and/or other materials provided
|
| 14 |
+
with the distribution.
|
| 15 |
+
|
| 16 |
+
* Neither the name of the NumPy Developers nor the names of any
|
| 17 |
+
contributors may be used to endorse or promote products derived
|
| 18 |
+
from this software without specific prior written permission.
|
| 19 |
+
|
| 20 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 21 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 22 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 23 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 24 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 25 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
| 26 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 27 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
| 28 |
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 29 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 30 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PACKAGING_LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
Copyright (c) Donald Stufft and individual contributors.
|
| 181 |
+
All rights reserved.
|
| 182 |
+
|
| 183 |
+
Redistribution and use in source and binary forms, with or without
|
| 184 |
+
modification, are permitted provided that the following conditions are met:
|
| 185 |
+
|
| 186 |
+
1. Redistributions of source code must retain the above copyright notice,
|
| 187 |
+
this list of conditions and the following disclaimer.
|
| 188 |
+
|
| 189 |
+
2. Redistributions in binary form must reproduce the above copyright
|
| 190 |
+
notice, this list of conditions and the following disclaimer in the
|
| 191 |
+
documentation and/or other materials provided with the distribution.
|
| 192 |
+
|
| 193 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
| 194 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 195 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 196 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 197 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 198 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 199 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 200 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 201 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 202 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PSF_LICENSE
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A. HISTORY OF THE SOFTWARE
|
| 2 |
+
==========================
|
| 3 |
+
|
| 4 |
+
Python was created in the early 1990s by Guido van Rossum at Stichting
|
| 5 |
+
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
|
| 6 |
+
as a successor of a language called ABC. Guido remains Python's
|
| 7 |
+
principal author, although it includes many contributions from others.
|
| 8 |
+
|
| 9 |
+
In 1995, Guido continued his work on Python at the Corporation for
|
| 10 |
+
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
|
| 11 |
+
in Reston, Virginia where he released several versions of the
|
| 12 |
+
software.
|
| 13 |
+
|
| 14 |
+
In May 2000, Guido and the Python core development team moved to
|
| 15 |
+
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
|
| 16 |
+
year, the PythonLabs team moved to Digital Creations, which became
|
| 17 |
+
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
|
| 18 |
+
https://www.python.org/psf/) was formed, a non-profit organization
|
| 19 |
+
created specifically to own Python-related Intellectual Property.
|
| 20 |
+
Zope Corporation was a sponsoring member of the PSF.
|
| 21 |
+
|
| 22 |
+
All Python releases are Open Source (see https://opensource.org for
|
| 23 |
+
the Open Source Definition). Historically, most, but not all, Python
|
| 24 |
+
releases have also been GPL-compatible; the table below summarizes
|
| 25 |
+
the various releases.
|
| 26 |
+
|
| 27 |
+
Release Derived Year Owner GPL-
|
| 28 |
+
from compatible? (1)
|
| 29 |
+
|
| 30 |
+
0.9.0 thru 1.2 1991-1995 CWI yes
|
| 31 |
+
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
|
| 32 |
+
1.6 1.5.2 2000 CNRI no
|
| 33 |
+
2.0 1.6 2000 BeOpen.com no
|
| 34 |
+
1.6.1 1.6 2001 CNRI yes (2)
|
| 35 |
+
2.1 2.0+1.6.1 2001 PSF no
|
| 36 |
+
2.0.1 2.0+1.6.1 2001 PSF yes
|
| 37 |
+
2.1.1 2.1+2.0.1 2001 PSF yes
|
| 38 |
+
2.1.2 2.1.1 2002 PSF yes
|
| 39 |
+
2.1.3 2.1.2 2002 PSF yes
|
| 40 |
+
2.2 and above 2.1.1 2001-now PSF yes
|
| 41 |
+
|
| 42 |
+
Footnotes:
|
| 43 |
+
|
| 44 |
+
(1) GPL-compatible doesn't mean that we're distributing Python under
|
| 45 |
+
the GPL. All Python licenses, unlike the GPL, let you distribute
|
| 46 |
+
a modified version without making your changes open source. The
|
| 47 |
+
GPL-compatible licenses make it possible to combine Python with
|
| 48 |
+
other software that is released under the GPL; the others don't.
|
| 49 |
+
|
| 50 |
+
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
|
| 51 |
+
because its license has a choice of law clause. According to
|
| 52 |
+
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
|
| 53 |
+
is "not incompatible" with the GPL.
|
| 54 |
+
|
| 55 |
+
Thanks to the many outside volunteers who have worked under Guido's
|
| 56 |
+
direction to make these releases possible.
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
|
| 60 |
+
===============================================================
|
| 61 |
+
|
| 62 |
+
Python software and documentation are licensed under the
|
| 63 |
+
Python Software Foundation License Version 2.
|
| 64 |
+
|
| 65 |
+
Starting with Python 3.8.6, examples, recipes, and other code in
|
| 66 |
+
the documentation are dual licensed under the PSF License Version 2
|
| 67 |
+
and the Zero-Clause BSD license.
|
| 68 |
+
|
| 69 |
+
Some software incorporated into Python is under different licenses.
|
| 70 |
+
The licenses are listed with code falling under that license.
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
| 74 |
+
--------------------------------------------
|
| 75 |
+
|
| 76 |
+
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
| 77 |
+
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
| 78 |
+
otherwise using this software ("Python") in source or binary form and
|
| 79 |
+
its associated documentation.
|
| 80 |
+
|
| 81 |
+
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
| 82 |
+
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
| 83 |
+
analyze, test, perform and/or display publicly, prepare derivative works,
|
| 84 |
+
distribute, and otherwise use Python alone or in any derivative version,
|
| 85 |
+
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
| 86 |
+
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
|
| 87 |
+
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
|
| 88 |
+
All Rights Reserved" are retained in Python alone or in any derivative version
|
| 89 |
+
prepared by Licensee.
|
| 90 |
+
|
| 91 |
+
3. In the event Licensee prepares a derivative work that is based on
|
| 92 |
+
or incorporates Python or any part thereof, and wants to make
|
| 93 |
+
the derivative work available to others as provided herein, then
|
| 94 |
+
Licensee hereby agrees to include in any such work a brief summary of
|
| 95 |
+
the changes made to Python.
|
| 96 |
+
|
| 97 |
+
4. PSF is making Python available to Licensee on an "AS IS"
|
| 98 |
+
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
| 99 |
+
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
| 100 |
+
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
| 101 |
+
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
| 102 |
+
INFRINGE ANY THIRD PARTY RIGHTS.
|
| 103 |
+
|
| 104 |
+
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
| 105 |
+
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
| 106 |
+
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
| 107 |
+
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
| 108 |
+
|
| 109 |
+
6. This License Agreement will automatically terminate upon a material
|
| 110 |
+
breach of its terms and conditions.
|
| 111 |
+
|
| 112 |
+
7. Nothing in this License Agreement shall be deemed to create any
|
| 113 |
+
relationship of agency, partnership, or joint venture between PSF and
|
| 114 |
+
Licensee. This License Agreement does not grant permission to use PSF
|
| 115 |
+
trademarks or trade name in a trademark sense to endorse or promote
|
| 116 |
+
products or services of Licensee, or any third party.
|
| 117 |
+
|
| 118 |
+
8. By copying, installing or otherwise using Python, Licensee
|
| 119 |
+
agrees to be bound by the terms and conditions of this License
|
| 120 |
+
Agreement.
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
|
| 124 |
+
-------------------------------------------
|
| 125 |
+
|
| 126 |
+
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
|
| 127 |
+
|
| 128 |
+
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
|
| 129 |
+
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
|
| 130 |
+
Individual or Organization ("Licensee") accessing and otherwise using
|
| 131 |
+
this software in source or binary form and its associated
|
| 132 |
+
documentation ("the Software").
|
| 133 |
+
|
| 134 |
+
2. Subject to the terms and conditions of this BeOpen Python License
|
| 135 |
+
Agreement, BeOpen hereby grants Licensee a non-exclusive,
|
| 136 |
+
royalty-free, world-wide license to reproduce, analyze, test, perform
|
| 137 |
+
and/or display publicly, prepare derivative works, distribute, and
|
| 138 |
+
otherwise use the Software alone or in any derivative version,
|
| 139 |
+
provided, however, that the BeOpen Python License is retained in the
|
| 140 |
+
Software, alone or in any derivative version prepared by Licensee.
|
| 141 |
+
|
| 142 |
+
3. BeOpen is making the Software available to Licensee on an "AS IS"
|
| 143 |
+
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
| 144 |
+
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
|
| 145 |
+
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
| 146 |
+
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
|
| 147 |
+
INFRINGE ANY THIRD PARTY RIGHTS.
|
| 148 |
+
|
| 149 |
+
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
|
| 150 |
+
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
|
| 151 |
+
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
|
| 152 |
+
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
| 153 |
+
|
| 154 |
+
5. This License Agreement will automatically terminate upon a material
|
| 155 |
+
breach of its terms and conditions.
|
| 156 |
+
|
| 157 |
+
6. This License Agreement shall be governed by and interpreted in all
|
| 158 |
+
respects by the law of the State of California, excluding conflict of
|
| 159 |
+
law provisions. Nothing in this License Agreement shall be deemed to
|
| 160 |
+
create any relationship of agency, partnership, or joint venture
|
| 161 |
+
between BeOpen and Licensee. This License Agreement does not grant
|
| 162 |
+
permission to use BeOpen trademarks or trade names in a trademark
|
| 163 |
+
sense to endorse or promote products or services of Licensee, or any
|
| 164 |
+
third party. As an exception, the "BeOpen Python" logos available at
|
| 165 |
+
http://www.pythonlabs.com/logos.html may be used according to the
|
| 166 |
+
permissions granted on that web page.
|
| 167 |
+
|
| 168 |
+
7. By copying, installing or otherwise using the software, Licensee
|
| 169 |
+
agrees to be bound by the terms and conditions of this License
|
| 170 |
+
Agreement.
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
|
| 174 |
+
---------------------------------------
|
| 175 |
+
|
| 176 |
+
1. This LICENSE AGREEMENT is between the Corporation for National
|
| 177 |
+
Research Initiatives, having an office at 1895 Preston White Drive,
|
| 178 |
+
Reston, VA 20191 ("CNRI"), and the Individual or Organization
|
| 179 |
+
("Licensee") accessing and otherwise using Python 1.6.1 software in
|
| 180 |
+
source or binary form and its associated documentation.
|
| 181 |
+
|
| 182 |
+
2. Subject to the terms and conditions of this License Agreement, CNRI
|
| 183 |
+
hereby grants Licensee a nonexclusive, royalty-free, world-wide
|
| 184 |
+
license to reproduce, analyze, test, perform and/or display publicly,
|
| 185 |
+
prepare derivative works, distribute, and otherwise use Python 1.6.1
|
| 186 |
+
alone or in any derivative version, provided, however, that CNRI's
|
| 187 |
+
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
|
| 188 |
+
1995-2001 Corporation for National Research Initiatives; All Rights
|
| 189 |
+
Reserved" are retained in Python 1.6.1 alone or in any derivative
|
| 190 |
+
version prepared by Licensee. Alternately, in lieu of CNRI's License
|
| 191 |
+
Agreement, Licensee may substitute the following text (omitting the
|
| 192 |
+
quotes): "Python 1.6.1 is made available subject to the terms and
|
| 193 |
+
conditions in CNRI's License Agreement. This Agreement together with
|
| 194 |
+
Python 1.6.1 may be located on the internet using the following
|
| 195 |
+
unique, persistent identifier (known as a handle): 1895.22/1013. This
|
| 196 |
+
Agreement may also be obtained from a proxy server on the internet
|
| 197 |
+
using the following URL: http://hdl.handle.net/1895.22/1013".
|
| 198 |
+
|
| 199 |
+
3. In the event Licensee prepares a derivative work that is based on
|
| 200 |
+
or incorporates Python 1.6.1 or any part thereof, and wants to make
|
| 201 |
+
the derivative work available to others as provided herein, then
|
| 202 |
+
Licensee hereby agrees to include in any such work a brief summary of
|
| 203 |
+
the changes made to Python 1.6.1.
|
| 204 |
+
|
| 205 |
+
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
|
| 206 |
+
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
| 207 |
+
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
|
| 208 |
+
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
| 209 |
+
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
|
| 210 |
+
INFRINGE ANY THIRD PARTY RIGHTS.
|
| 211 |
+
|
| 212 |
+
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
| 213 |
+
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
| 214 |
+
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
|
| 215 |
+
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
| 216 |
+
|
| 217 |
+
6. This License Agreement will automatically terminate upon a material
|
| 218 |
+
breach of its terms and conditions.
|
| 219 |
+
|
| 220 |
+
7. This License Agreement shall be governed by the federal
|
| 221 |
+
intellectual property law of the United States, including without
|
| 222 |
+
limitation the federal copyright law, and, to the extent such
|
| 223 |
+
U.S. federal law does not apply, by the law of the Commonwealth of
|
| 224 |
+
Virginia, excluding Virginia's conflict of law provisions.
|
| 225 |
+
Notwithstanding the foregoing, with regard to derivative works based
|
| 226 |
+
on Python 1.6.1 that incorporate non-separable material that was
|
| 227 |
+
previously distributed under the GNU General Public License (GPL), the
|
| 228 |
+
law of the Commonwealth of Virginia shall govern this License
|
| 229 |
+
Agreement only as to issues arising under or with respect to
|
| 230 |
+
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
|
| 231 |
+
License Agreement shall be deemed to create any relationship of
|
| 232 |
+
agency, partnership, or joint venture between CNRI and Licensee. This
|
| 233 |
+
License Agreement does not grant permission to use CNRI trademarks or
|
| 234 |
+
trade name in a trademark sense to endorse or promote products or
|
| 235 |
+
services of Licensee, or any third party.
|
| 236 |
+
|
| 237 |
+
8. By clicking on the "ACCEPT" button where indicated, or by copying,
|
| 238 |
+
installing or otherwise using Python 1.6.1, Licensee agrees to be
|
| 239 |
+
bound by the terms and conditions of this License Agreement.
|
| 240 |
+
|
| 241 |
+
ACCEPT
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
|
| 245 |
+
--------------------------------------------------
|
| 246 |
+
|
| 247 |
+
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
|
| 248 |
+
The Netherlands. All rights reserved.
|
| 249 |
+
|
| 250 |
+
Permission to use, copy, modify, and distribute this software and its
|
| 251 |
+
documentation for any purpose and without fee is hereby granted,
|
| 252 |
+
provided that the above copyright notice appear in all copies and that
|
| 253 |
+
both that copyright notice and this permission notice appear in
|
| 254 |
+
supporting documentation, and that the name of Stichting Mathematisch
|
| 255 |
+
Centrum or CWI not be used in advertising or publicity pertaining to
|
| 256 |
+
distribution of the software without specific, written prior
|
| 257 |
+
permission.
|
| 258 |
+
|
| 259 |
+
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
|
| 260 |
+
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
| 261 |
+
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
|
| 262 |
+
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
| 263 |
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
| 264 |
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
| 265 |
+
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
| 266 |
+
|
| 267 |
+
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
|
| 268 |
+
----------------------------------------------------------------------
|
| 269 |
+
|
| 270 |
+
Permission to use, copy, modify, and/or distribute this software for any
|
| 271 |
+
purpose with or without fee is hereby granted.
|
| 272 |
+
|
| 273 |
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
| 274 |
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
| 275 |
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
| 276 |
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
| 277 |
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
| 278 |
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
| 279 |
+
PERFORMANCE OF THIS SOFTWARE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PYPERCLIP_LICENSE
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2014, Al Sweigart
|
| 2 |
+
All rights reserved.
|
| 3 |
+
|
| 4 |
+
Redistribution and use in source and binary forms, with or without
|
| 5 |
+
modification, are permitted provided that the following conditions are met:
|
| 6 |
+
|
| 7 |
+
* Redistributions of source code must retain the above copyright notice, this
|
| 8 |
+
list of conditions and the following disclaimer.
|
| 9 |
+
|
| 10 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
| 11 |
+
this list of conditions and the following disclaimer in the documentation
|
| 12 |
+
and/or other materials provided with the distribution.
|
| 13 |
+
|
| 14 |
+
* Neither the name of the {organization} nor the names of its
|
| 15 |
+
contributors may be used to endorse or promote products derived from
|
| 16 |
+
this software without specific prior written permission.
|
| 17 |
+
|
| 18 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 19 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 20 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 21 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 22 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 23 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 24 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 26 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 27 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/PYUPGRADE_LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2017 Anthony Sottile
|
| 2 |
+
|
| 3 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 4 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 5 |
+
in the Software without restriction, including without limitation the rights
|
| 6 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 7 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 8 |
+
furnished to do so, subject to the following conditions:
|
| 9 |
+
|
| 10 |
+
The above copyright notice and this permission notice shall be included in
|
| 11 |
+
all copies or substantial portions of the Software.
|
| 12 |
+
|
| 13 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 14 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 15 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 16 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 17 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 18 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 19 |
+
THE SOFTWARE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/SAS7BDAT_LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2015-2019 Jared Hobbs
|
| 2 |
+
|
| 3 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
| 4 |
+
this software and associated documentation files (the "Software"), to deal in
|
| 5 |
+
the Software without restriction, including without limitation the rights to
|
| 6 |
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
| 7 |
+
of the Software, and to permit persons to whom the Software is furnished to do
|
| 8 |
+
so, subject to the following conditions:
|
| 9 |
+
|
| 10 |
+
The above copyright notice and this permission notice shall be included in all
|
| 11 |
+
copies or substantial portions of the Software.
|
| 12 |
+
|
| 13 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 14 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 15 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 16 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 17 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 18 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 19 |
+
SOFTWARE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/STATSBASE_JL_LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
StatsBase.jl is licensed under the MIT License:
|
| 2 |
+
|
| 3 |
+
> Copyright (c) 2012-2016: Dahua Lin, Simon Byrne, Andreas Noack,
|
| 4 |
+
> Douglas Bates, John Myles White, Simon Kornblith, and other contributors.
|
| 5 |
+
|
| 6 |
+
> Permission is hereby granted, free of charge, to any person obtaining
|
| 7 |
+
> a copy of this software and associated documentation files (the
|
| 8 |
+
> "Software"), to deal in the Software without restriction, including
|
| 9 |
+
> without limitation the rights to use, copy, modify, merge, publish,
|
| 10 |
+
> distribute, sublicense, and/or sell copies of the Software, and to
|
| 11 |
+
> permit persons to whom the Software is furnished to do so, subject to
|
| 12 |
+
> the following conditions:
|
| 13 |
+
>
|
| 14 |
+
> The above copyright notice and this permission notice shall be
|
| 15 |
+
> included in all copies or substantial portions of the Software.
|
| 16 |
+
>
|
| 17 |
+
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 18 |
+
> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 19 |
+
> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 20 |
+
> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
| 21 |
+
> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
| 22 |
+
> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
| 23 |
+
> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/ULTRAJSON_LICENSE
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Developed by ESN, an Electronic Arts Inc. studio.
|
| 2 |
+
Copyright (c) 2014, Electronic Arts Inc.
|
| 3 |
+
All rights reserved.
|
| 4 |
+
|
| 5 |
+
Redistribution and use in source and binary forms, with or without
|
| 6 |
+
modification, are permitted provided that the following conditions are met:
|
| 7 |
+
* Redistributions of source code must retain the above copyright
|
| 8 |
+
notice, this list of conditions and the following disclaimer.
|
| 9 |
+
* Redistributions in binary form must reproduce the above copyright
|
| 10 |
+
notice, this list of conditions and the following disclaimer in the
|
| 11 |
+
documentation and/or other materials provided with the distribution.
|
| 12 |
+
* Neither the name of ESN, Electronic Arts Inc. nor the
|
| 13 |
+
names of its contributors may be used to endorse or promote products
|
| 14 |
+
derived from this software without specific prior written permission.
|
| 15 |
+
|
| 16 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
| 17 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 18 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 19 |
+
DISCLAIMED. IN NO EVENT SHALL ELECTRONIC ARTS INC. BE LIABLE
|
| 20 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
| 21 |
+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 22 |
+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
| 23 |
+
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 24 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 25 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 26 |
+
|
| 27 |
+
----
|
| 28 |
+
|
| 29 |
+
Portions of code from MODP_ASCII - Ascii transformations (upper/lower, etc)
|
| 30 |
+
https://github.com/client9/stringencoders
|
| 31 |
+
|
| 32 |
+
Copyright 2005, 2006, 2007
|
| 33 |
+
Nick Galbreath -- nickg [at] modp [dot] com
|
| 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
|
| 38 |
+
met:
|
| 39 |
+
|
| 40 |
+
Redistributions of source code must retain the above copyright
|
| 41 |
+
notice, this list of conditions and the following disclaimer.
|
| 42 |
+
|
| 43 |
+
Redistributions in binary form must reproduce the above copyright
|
| 44 |
+
notice, this list of conditions and the following disclaimer in the
|
| 45 |
+
documentation and/or other materials provided with the distribution.
|
| 46 |
+
|
| 47 |
+
Neither the name of the modp.com nor the names of its
|
| 48 |
+
contributors may be used to endorse or promote products derived from
|
| 49 |
+
this software without specific prior written permission.
|
| 50 |
+
|
| 51 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 52 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 53 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 54 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 55 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 56 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
| 57 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 58 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
| 59 |
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 60 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 61 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 62 |
+
|
| 63 |
+
This is the standard "new" BSD license:
|
| 64 |
+
http://www.opensource.org/licenses/bsd-license.php
|
| 65 |
+
|
| 66 |
+
https://github.com/client9/stringencoders/blob/cfd5c1507325ae497ea9bacdacba12c0ffd79d30/COPYING
|
| 67 |
+
|
| 68 |
+
----
|
| 69 |
+
|
| 70 |
+
Numeric decoder derived from from TCL library
|
| 71 |
+
https://opensource.apple.com/source/tcl/tcl-14/tcl/license.terms
|
| 72 |
+
* Copyright (c) 1988-1993 The Regents of the University of California.
|
| 73 |
+
* Copyright (c) 1994 Sun Microsystems, Inc.
|
| 74 |
+
|
| 75 |
+
This software is copyrighted by the Regents of the University of
|
| 76 |
+
California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
|
| 77 |
+
Corporation and other parties. The following terms apply to all files
|
| 78 |
+
associated with the software unless explicitly disclaimed in
|
| 79 |
+
individual files.
|
| 80 |
+
|
| 81 |
+
The authors hereby grant permission to use, copy, modify, distribute,
|
| 82 |
+
and license this software and its documentation for any purpose, provided
|
| 83 |
+
that existing copyright notices are retained in all copies and that this
|
| 84 |
+
notice is included verbatim in any distributions. No written agreement,
|
| 85 |
+
license, or royalty fee is required for any of the authorized uses.
|
| 86 |
+
Modifications to this software may be copyrighted by their authors
|
| 87 |
+
and need not follow the licensing terms described here, provided that
|
| 88 |
+
the new terms are clearly indicated on the first page of each file where
|
| 89 |
+
they apply.
|
| 90 |
+
|
| 91 |
+
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
|
| 92 |
+
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
|
| 93 |
+
ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
|
| 94 |
+
DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
|
| 95 |
+
POSSIBILITY OF SUCH DAMAGE.
|
| 96 |
+
|
| 97 |
+
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
|
| 98 |
+
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
|
| 99 |
+
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
|
| 100 |
+
IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
|
| 101 |
+
NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
|
| 102 |
+
MODIFICATIONS.
|
| 103 |
+
|
| 104 |
+
GOVERNMENT USE: If you are acquiring this software on behalf of the
|
| 105 |
+
U.S. government, the Government shall have only "Restricted Rights"
|
| 106 |
+
in the software and related documentation as defined in the Federal
|
| 107 |
+
Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
|
| 108 |
+
are acquiring the software on behalf of the Department of Defense, the
|
| 109 |
+
software shall be classified as "Commercial Computer Software" and the
|
| 110 |
+
Government shall have only "Restricted Rights" as defined in Clause
|
| 111 |
+
252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the
|
| 112 |
+
authors grant the U.S. Government and others acting in its behalf
|
| 113 |
+
permission to use and distribute the software in accordance with the
|
| 114 |
+
terms specified in this license.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/LICENSES/XSIMD_LICENSE
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2016, Johan Mabille, Sylvain Corlay, Wolf Vollprecht and Martin Renou
|
| 2 |
+
Copyright (c) 2016, QuantStack
|
| 3 |
+
Copyright (c) 2018, Serge Guelton
|
| 4 |
+
All rights reserved.
|
| 5 |
+
|
| 6 |
+
Redistribution and use in source and binary forms, with or without
|
| 7 |
+
modification, are permitted provided that the following conditions are met:
|
| 8 |
+
|
| 9 |
+
* Redistributions of source code must retain the above copyright notice, this
|
| 10 |
+
list of conditions and the following disclaimer.
|
| 11 |
+
|
| 12 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
| 13 |
+
this list of conditions and the following disclaimer in the documentation
|
| 14 |
+
and/or other materials provided with the distribution.
|
| 15 |
+
|
| 16 |
+
* Neither the name of the copyright holder nor the names of its
|
| 17 |
+
contributors may be used to endorse or promote products derived from
|
| 18 |
+
this software without specific prior written permission.
|
| 19 |
+
|
| 20 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 21 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 22 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 23 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 24 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 25 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 26 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 27 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 28 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 29 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
Copyright 2021 The fast_float authors
|
| 179 |
+
|
| 180 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 181 |
+
you may not use this file except in compliance with the License.
|
| 182 |
+
You may obtain a copy of the License at
|
| 183 |
+
|
| 184 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 185 |
+
|
| 186 |
+
Unless required by applicable law or agreed to in writing, software
|
| 187 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 188 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 189 |
+
See the License for the specific language governing permissions and
|
| 190 |
+
limitations under the License.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-BOOST
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Boost Software License - Version 1.0 - August 17th, 2003
|
| 2 |
+
|
| 3 |
+
Permission is hereby granted, free of charge, to any person or organization
|
| 4 |
+
obtaining a copy of the software and accompanying documentation covered by
|
| 5 |
+
this license (the "Software") to use, reproduce, display, distribute,
|
| 6 |
+
execute, and transmit the Software, and to prepare derivative works of the
|
| 7 |
+
Software, and to permit third-parties to whom the Software is furnished to
|
| 8 |
+
do so, all subject to the following:
|
| 9 |
+
|
| 10 |
+
The copyright notices in the Software and this entire statement, including
|
| 11 |
+
the above license grant, this restriction and the following disclaimer,
|
| 12 |
+
must be included in all copies of the Software, in whole or in part, and
|
| 13 |
+
all derivative works of the Software, unless such copies or derivative
|
| 14 |
+
works are solely in the form of machine-executable object code generated by
|
| 15 |
+
a source language processor.
|
| 16 |
+
|
| 17 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
|
| 20 |
+
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
|
| 21 |
+
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
|
| 22 |
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
| 23 |
+
DEALINGS IN THE SOFTWARE.
|
.venv/lib/python3.12/site-packages/pandas-3.1.1.dist-info/licenses/subprojects/fast_float-8.2.10/LICENSE-MIT
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2021 The fast_float authors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any
|
| 6 |
+
person obtaining a copy of this software and associated
|
| 7 |
+
documentation files (the "Software"), to deal in the
|
| 8 |
+
Software without restriction, including without
|
| 9 |
+
limitation the rights to use, copy, modify, merge,
|
| 10 |
+
publish, distribute, sublicense, and/or sell copies of
|
| 11 |
+
the Software, and to permit persons to whom the Software
|
| 12 |
+
is furnished to do so, subject to the following
|
| 13 |
+
conditions:
|
| 14 |
+
|
| 15 |
+
The above copyright notice and this permission notice
|
| 16 |
+
shall be included in all copies or substantial portions
|
| 17 |
+
of the Software.
|
| 18 |
+
|
| 19 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
| 20 |
+
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
| 21 |
+
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
| 22 |
+
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
| 23 |
+
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
| 24 |
+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
| 25 |
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
| 26 |
+
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
| 27 |
+
DEALINGS IN THE SOFTWARE.
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/common/test_index.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from io import StringIO
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 15 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.mark.parametrize(
|
| 19 |
+
"data,kwargs,expected",
|
| 20 |
+
[
|
| 21 |
+
(
|
| 22 |
+
"""foo,2,3,4,5
|
| 23 |
+
bar,7,8,9,10
|
| 24 |
+
baz,12,13,14,15
|
| 25 |
+
qux,12,13,14,15
|
| 26 |
+
foo2,12,13,14,15
|
| 27 |
+
bar2,12,13,14,15
|
| 28 |
+
""",
|
| 29 |
+
{"index_col": 0, "names": ["index", "A", "B", "C", "D"]},
|
| 30 |
+
pd.DataFrame(
|
| 31 |
+
[
|
| 32 |
+
[2, 3, 4, 5],
|
| 33 |
+
[7, 8, 9, 10],
|
| 34 |
+
[12, 13, 14, 15],
|
| 35 |
+
[12, 13, 14, 15],
|
| 36 |
+
[12, 13, 14, 15],
|
| 37 |
+
[12, 13, 14, 15],
|
| 38 |
+
],
|
| 39 |
+
index=pd.Index(
|
| 40 |
+
["foo", "bar", "baz", "qux", "foo2", "bar2"], name="index"
|
| 41 |
+
),
|
| 42 |
+
columns=["A", "B", "C", "D"],
|
| 43 |
+
),
|
| 44 |
+
),
|
| 45 |
+
(
|
| 46 |
+
"""foo,one,2,3,4,5
|
| 47 |
+
foo,two,7,8,9,10
|
| 48 |
+
foo,three,12,13,14,15
|
| 49 |
+
bar,one,12,13,14,15
|
| 50 |
+
bar,two,12,13,14,15
|
| 51 |
+
""",
|
| 52 |
+
{"index_col": [0, 1], "names": ["index1", "index2", "A", "B", "C", "D"]},
|
| 53 |
+
pd.DataFrame(
|
| 54 |
+
[
|
| 55 |
+
[2, 3, 4, 5],
|
| 56 |
+
[7, 8, 9, 10],
|
| 57 |
+
[12, 13, 14, 15],
|
| 58 |
+
[12, 13, 14, 15],
|
| 59 |
+
[12, 13, 14, 15],
|
| 60 |
+
],
|
| 61 |
+
index=pd.MultiIndex.from_tuples(
|
| 62 |
+
[
|
| 63 |
+
("foo", "one"),
|
| 64 |
+
("foo", "two"),
|
| 65 |
+
("foo", "three"),
|
| 66 |
+
("bar", "one"),
|
| 67 |
+
("bar", "two"),
|
| 68 |
+
],
|
| 69 |
+
names=["index1", "index2"],
|
| 70 |
+
),
|
| 71 |
+
columns=["A", "B", "C", "D"],
|
| 72 |
+
),
|
| 73 |
+
),
|
| 74 |
+
],
|
| 75 |
+
)
|
| 76 |
+
def test_pass_names_with_index(all_parsers, data, kwargs, expected):
|
| 77 |
+
parser = all_parsers
|
| 78 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 79 |
+
tm.assert_frame_equal(result, expected)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@pytest.mark.parametrize("index_col", [[0, 1], [1, 0]])
|
| 83 |
+
def test_multi_index_no_level_names(
|
| 84 |
+
request, all_parsers, index_col, using_infer_string
|
| 85 |
+
):
|
| 86 |
+
data = """index1,index2,A,B,C,D
|
| 87 |
+
foo,one,2,3,4,5
|
| 88 |
+
foo,two,7,8,9,10
|
| 89 |
+
foo,three,12,13,14,15
|
| 90 |
+
bar,one,12,13,14,15
|
| 91 |
+
bar,two,12,13,14,15
|
| 92 |
+
"""
|
| 93 |
+
headless_data = "\n".join(data.split("\n")[1:])
|
| 94 |
+
|
| 95 |
+
names = ["A", "B", "C", "D"]
|
| 96 |
+
parser = all_parsers
|
| 97 |
+
|
| 98 |
+
result = parser.read_csv(
|
| 99 |
+
StringIO(headless_data), index_col=index_col, header=None, names=names
|
| 100 |
+
)
|
| 101 |
+
expected = parser.read_csv(StringIO(data), index_col=index_col)
|
| 102 |
+
|
| 103 |
+
# No index names in headless data.
|
| 104 |
+
expected.index.names = [None] * 2
|
| 105 |
+
tm.assert_frame_equal(result, expected)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@skip_pyarrow
|
| 109 |
+
def test_multi_index_no_level_names_implicit(all_parsers):
|
| 110 |
+
parser = all_parsers
|
| 111 |
+
data = """A,B,C,D
|
| 112 |
+
foo,one,2,3,4,5
|
| 113 |
+
foo,two,7,8,9,10
|
| 114 |
+
foo,three,12,13,14,15
|
| 115 |
+
bar,one,12,13,14,15
|
| 116 |
+
bar,two,12,13,14,15
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
result = parser.read_csv(StringIO(data))
|
| 120 |
+
expected = pd.DataFrame(
|
| 121 |
+
[
|
| 122 |
+
[2, 3, 4, 5],
|
| 123 |
+
[7, 8, 9, 10],
|
| 124 |
+
[12, 13, 14, 15],
|
| 125 |
+
[12, 13, 14, 15],
|
| 126 |
+
[12, 13, 14, 15],
|
| 127 |
+
],
|
| 128 |
+
columns=["A", "B", "C", "D"],
|
| 129 |
+
index=pd.MultiIndex.from_tuples(
|
| 130 |
+
[
|
| 131 |
+
("foo", "one"),
|
| 132 |
+
("foo", "two"),
|
| 133 |
+
("foo", "three"),
|
| 134 |
+
("bar", "one"),
|
| 135 |
+
("bar", "two"),
|
| 136 |
+
]
|
| 137 |
+
),
|
| 138 |
+
)
|
| 139 |
+
tm.assert_frame_equal(result, expected)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@pytest.mark.parametrize(
|
| 143 |
+
"data,columns,header",
|
| 144 |
+
[
|
| 145 |
+
("a,b", ["a", "b"], [0]),
|
| 146 |
+
(
|
| 147 |
+
"a,b\nc,d",
|
| 148 |
+
pd.MultiIndex.from_tuples([("a", "c"), ("b", "d")]),
|
| 149 |
+
[0, 1],
|
| 150 |
+
),
|
| 151 |
+
],
|
| 152 |
+
)
|
| 153 |
+
@pytest.mark.parametrize("round_trip", [True, False])
|
| 154 |
+
def test_multi_index_blank_df(all_parsers, data, columns, header, round_trip, request):
|
| 155 |
+
# see gh-14545
|
| 156 |
+
parser = all_parsers
|
| 157 |
+
expected = pd.DataFrame(columns=columns)
|
| 158 |
+
data = expected.to_csv(index=False) if round_trip else data
|
| 159 |
+
|
| 160 |
+
if parser.engine == "pyarrow":
|
| 161 |
+
if len(header) > 1:
|
| 162 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 163 |
+
parser.read_csv(StringIO(data), header=header)
|
| 164 |
+
return
|
| 165 |
+
# header=[0] is a singleton, so it behaves like header=0, but the
|
| 166 |
+
# empty-frame dtypes still differ for the pyarrow engine
|
| 167 |
+
mark = pytest.mark.xfail(
|
| 168 |
+
reason="empty frame dtypes differ; apache/arrow#38676 without newline"
|
| 169 |
+
)
|
| 170 |
+
request.applymarker(mark)
|
| 171 |
+
|
| 172 |
+
result = parser.read_csv(StringIO(data), header=header)
|
| 173 |
+
tm.assert_frame_equal(result, expected)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def test_no_unnamed_index(all_parsers):
|
| 177 |
+
parser = all_parsers
|
| 178 |
+
data = """ id c0 c1 c2
|
| 179 |
+
0 1 0 a b
|
| 180 |
+
1 2 0 c d
|
| 181 |
+
2 2 2 e f
|
| 182 |
+
"""
|
| 183 |
+
result = parser.read_csv(StringIO(data), sep=" ")
|
| 184 |
+
expected = pd.DataFrame(
|
| 185 |
+
[[0, 1, 0, "a", "b"], [1, 2, 0, "c", "d"], [2, 2, 2, "e", "f"]],
|
| 186 |
+
columns=["Unnamed: 0", "id", "c0", "c1", "c2"],
|
| 187 |
+
)
|
| 188 |
+
tm.assert_frame_equal(result, expected)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_read_duplicate_index_explicit(all_parsers):
|
| 192 |
+
data = """index,A,B,C,D
|
| 193 |
+
foo,2,3,4,5
|
| 194 |
+
bar,7,8,9,10
|
| 195 |
+
baz,12,13,14,15
|
| 196 |
+
qux,12,13,14,15
|
| 197 |
+
foo,12,13,14,15
|
| 198 |
+
bar,12,13,14,15
|
| 199 |
+
"""
|
| 200 |
+
parser = all_parsers
|
| 201 |
+
result = parser.read_csv(StringIO(data), index_col=0)
|
| 202 |
+
|
| 203 |
+
expected = pd.DataFrame(
|
| 204 |
+
[
|
| 205 |
+
[2, 3, 4, 5],
|
| 206 |
+
[7, 8, 9, 10],
|
| 207 |
+
[12, 13, 14, 15],
|
| 208 |
+
[12, 13, 14, 15],
|
| 209 |
+
[12, 13, 14, 15],
|
| 210 |
+
[12, 13, 14, 15],
|
| 211 |
+
],
|
| 212 |
+
columns=["A", "B", "C", "D"],
|
| 213 |
+
index=pd.Index(["foo", "bar", "baz", "qux", "foo", "bar"], name="index"),
|
| 214 |
+
)
|
| 215 |
+
tm.assert_frame_equal(result, expected)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@skip_pyarrow
|
| 219 |
+
def test_read_duplicate_index_implicit(all_parsers):
|
| 220 |
+
data = """A,B,C,D
|
| 221 |
+
foo,2,3,4,5
|
| 222 |
+
bar,7,8,9,10
|
| 223 |
+
baz,12,13,14,15
|
| 224 |
+
qux,12,13,14,15
|
| 225 |
+
foo,12,13,14,15
|
| 226 |
+
bar,12,13,14,15
|
| 227 |
+
"""
|
| 228 |
+
parser = all_parsers
|
| 229 |
+
result = parser.read_csv(StringIO(data))
|
| 230 |
+
|
| 231 |
+
expected = pd.DataFrame(
|
| 232 |
+
[
|
| 233 |
+
[2, 3, 4, 5],
|
| 234 |
+
[7, 8, 9, 10],
|
| 235 |
+
[12, 13, 14, 15],
|
| 236 |
+
[12, 13, 14, 15],
|
| 237 |
+
[12, 13, 14, 15],
|
| 238 |
+
[12, 13, 14, 15],
|
| 239 |
+
],
|
| 240 |
+
columns=["A", "B", "C", "D"],
|
| 241 |
+
index=pd.Index(["foo", "bar", "baz", "qux", "foo", "bar"]),
|
| 242 |
+
)
|
| 243 |
+
tm.assert_frame_equal(result, expected)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@skip_pyarrow
|
| 247 |
+
def test_read_csv_no_index_name(all_parsers, datapath):
|
| 248 |
+
parser = all_parsers
|
| 249 |
+
csv2 = datapath("io", "parser", "data", "test2.csv")
|
| 250 |
+
result = parser.read_csv(csv2, index_col=0, parse_dates=True)
|
| 251 |
+
|
| 252 |
+
expected = pd.DataFrame(
|
| 253 |
+
[
|
| 254 |
+
[0.980269, 3.685731, -0.364216805298, -1.159738, "foo"],
|
| 255 |
+
[1.047916, -0.041232, -0.16181208307, 0.212549, "bar"],
|
| 256 |
+
[0.498581, 0.731168, -0.537677223318, 1.346270, "baz"],
|
| 257 |
+
[1.120202, 1.567621, 0.00364077397681, 0.675253, "qux"],
|
| 258 |
+
[-0.487094, 0.571455, -1.6116394093, 0.103469, "foo2"],
|
| 259 |
+
],
|
| 260 |
+
columns=["A", "B", "C", "D", "E"],
|
| 261 |
+
index=pd.Index(
|
| 262 |
+
[
|
| 263 |
+
datetime(2000, 1, 3),
|
| 264 |
+
datetime(2000, 1, 4),
|
| 265 |
+
datetime(2000, 1, 5),
|
| 266 |
+
datetime(2000, 1, 6),
|
| 267 |
+
datetime(2000, 1, 7),
|
| 268 |
+
],
|
| 269 |
+
dtype="M8[us]",
|
| 270 |
+
),
|
| 271 |
+
)
|
| 272 |
+
tm.assert_frame_equal(result, expected)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@skip_pyarrow
|
| 276 |
+
def test_empty_with_index(all_parsers):
|
| 277 |
+
# see gh-10184
|
| 278 |
+
data = "x,y"
|
| 279 |
+
parser = all_parsers
|
| 280 |
+
result = parser.read_csv(StringIO(data), index_col=0)
|
| 281 |
+
|
| 282 |
+
expected = pd.DataFrame(columns=["y"], index=pd.Index([], name="x"))
|
| 283 |
+
tm.assert_frame_equal(result, expected)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
# CSV parse error: Empty CSV file or block: cannot infer number of columns
|
| 287 |
+
@skip_pyarrow
|
| 288 |
+
def test_empty_with_multi_index(all_parsers):
|
| 289 |
+
# see gh-10467
|
| 290 |
+
data = "x,y,z"
|
| 291 |
+
parser = all_parsers
|
| 292 |
+
result = parser.read_csv(StringIO(data), index_col=["x", "y"])
|
| 293 |
+
|
| 294 |
+
expected = pd.DataFrame(
|
| 295 |
+
columns=["z"], index=pd.MultiIndex.from_arrays([[]] * 2, names=["x", "y"])
|
| 296 |
+
)
|
| 297 |
+
tm.assert_frame_equal(result, expected)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# CSV parse error: Empty CSV file or block: cannot infer number of columns
|
| 301 |
+
@skip_pyarrow
|
| 302 |
+
def test_empty_with_reversed_multi_index(all_parsers):
|
| 303 |
+
data = "x,y,z"
|
| 304 |
+
parser = all_parsers
|
| 305 |
+
result = parser.read_csv(StringIO(data), index_col=[1, 0])
|
| 306 |
+
|
| 307 |
+
expected = pd.DataFrame(
|
| 308 |
+
columns=["z"], index=pd.MultiIndex.from_arrays([[]] * 2, names=["y", "x"])
|
| 309 |
+
)
|
| 310 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/common/test_inf.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from io import StringIO
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import pandas._testing as tm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@pytest.mark.parametrize("na_filter", [True, False])
|
| 15 |
+
def test_inf_parsing(all_parsers, na_filter):
|
| 16 |
+
parser = all_parsers
|
| 17 |
+
data = """\
|
| 18 |
+
,A
|
| 19 |
+
a,inf
|
| 20 |
+
b,-inf
|
| 21 |
+
c,+Inf
|
| 22 |
+
d,-Inf
|
| 23 |
+
e,INF
|
| 24 |
+
f,-INF
|
| 25 |
+
g,+INf
|
| 26 |
+
h,-INf
|
| 27 |
+
i,inF
|
| 28 |
+
j,-inF"""
|
| 29 |
+
|
| 30 |
+
if parser.engine == "pyarrow" and na_filter is False:
|
| 31 |
+
msg = "The 'na_filter' option is not supported with the 'pyarrow' engine"
|
| 32 |
+
with pytest.raises(ValueError, match=msg):
|
| 33 |
+
parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter)
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
+
expected = pd.DataFrame(
|
| 37 |
+
{"A": [float("inf"), float("-inf")] * 5},
|
| 38 |
+
index=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
if parser.engine == "pyarrow" and na_filter is False:
|
| 42 |
+
msg = "The 'na_filter' option is not supported with the 'pyarrow' engine"
|
| 43 |
+
with pytest.raises(ValueError, match=msg):
|
| 44 |
+
parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter)
|
| 45 |
+
return
|
| 46 |
+
|
| 47 |
+
result = parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter)
|
| 48 |
+
tm.assert_frame_equal(result, expected)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@pytest.mark.parametrize("na_filter", [True, False])
|
| 52 |
+
def test_infinity_parsing(all_parsers, na_filter):
|
| 53 |
+
parser = all_parsers
|
| 54 |
+
data = """\
|
| 55 |
+
,A
|
| 56 |
+
a,Infinity
|
| 57 |
+
b,-Infinity
|
| 58 |
+
c,+Infinity
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
if parser.engine == "pyarrow" and na_filter is False:
|
| 62 |
+
msg = "The 'na_filter' option is not supported with the 'pyarrow' engine"
|
| 63 |
+
with pytest.raises(ValueError, match=msg):
|
| 64 |
+
parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter)
|
| 65 |
+
return
|
| 66 |
+
|
| 67 |
+
expected = pd.DataFrame(
|
| 68 |
+
{"A": [float("infinity"), float("-infinity"), float("+infinity")]},
|
| 69 |
+
index=["a", "b", "c"],
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
if parser.engine == "pyarrow" and na_filter is False:
|
| 73 |
+
msg = "The 'na_filter' option is not supported with the 'pyarrow' engine"
|
| 74 |
+
with pytest.raises(ValueError, match=msg):
|
| 75 |
+
parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter)
|
| 76 |
+
return
|
| 77 |
+
|
| 78 |
+
result = parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter)
|
| 79 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/common/test_ints.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from io import StringIO
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 15 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_int_conversion(all_parsers):
|
| 19 |
+
data = """A,B
|
| 20 |
+
1.0,1
|
| 21 |
+
2.0,2
|
| 22 |
+
3.0,3
|
| 23 |
+
"""
|
| 24 |
+
parser = all_parsers
|
| 25 |
+
result = parser.read_csv(StringIO(data))
|
| 26 |
+
|
| 27 |
+
expected = pd.DataFrame([[1.0, 1], [2.0, 2], [3.0, 3]], columns=["A", "B"])
|
| 28 |
+
tm.assert_frame_equal(result, expected)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@pytest.mark.parametrize(
|
| 32 |
+
"data,kwargs,expected",
|
| 33 |
+
[
|
| 34 |
+
(
|
| 35 |
+
"A,B\nTrue,1\nFalse,2\nTrue,3",
|
| 36 |
+
{},
|
| 37 |
+
[[True, 1], [False, 2], [True, 3]],
|
| 38 |
+
),
|
| 39 |
+
(
|
| 40 |
+
"A,B\nYES,1\nno,2\nyes,3\nNo,3\nYes,3",
|
| 41 |
+
{"true_values": ["yes", "Yes", "YES"], "false_values": ["no", "NO", "No"]},
|
| 42 |
+
[[True, 1], [False, 2], [True, 3], [False, 3], [True, 3]],
|
| 43 |
+
),
|
| 44 |
+
(
|
| 45 |
+
"A,B\nTRUE,1\nFALSE,2\nTRUE,3",
|
| 46 |
+
{},
|
| 47 |
+
[[True, 1], [False, 2], [True, 3]],
|
| 48 |
+
),
|
| 49 |
+
(
|
| 50 |
+
"A,B\nfoo,bar\nbar,foo",
|
| 51 |
+
{"true_values": ["foo"], "false_values": ["bar"]},
|
| 52 |
+
[[True, False], [False, True]],
|
| 53 |
+
),
|
| 54 |
+
],
|
| 55 |
+
)
|
| 56 |
+
def test_parse_bool(all_parsers, data, kwargs, expected):
|
| 57 |
+
parser = all_parsers
|
| 58 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 59 |
+
expected = pd.DataFrame(expected, columns=["A", "B"])
|
| 60 |
+
tm.assert_frame_equal(result, expected)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_parse_integers_above_fp_precision(all_parsers):
|
| 64 |
+
data = """Numbers
|
| 65 |
+
17007000002000191
|
| 66 |
+
17007000002000191
|
| 67 |
+
17007000002000191
|
| 68 |
+
17007000002000191
|
| 69 |
+
17007000002000192
|
| 70 |
+
17007000002000192
|
| 71 |
+
17007000002000192
|
| 72 |
+
17007000002000192
|
| 73 |
+
17007000002000192
|
| 74 |
+
17007000002000194"""
|
| 75 |
+
parser = all_parsers
|
| 76 |
+
result = parser.read_csv(StringIO(data))
|
| 77 |
+
expected = pd.DataFrame(
|
| 78 |
+
{
|
| 79 |
+
"Numbers": [
|
| 80 |
+
17007000002000191,
|
| 81 |
+
17007000002000191,
|
| 82 |
+
17007000002000191,
|
| 83 |
+
17007000002000191,
|
| 84 |
+
17007000002000192,
|
| 85 |
+
17007000002000192,
|
| 86 |
+
17007000002000192,
|
| 87 |
+
17007000002000192,
|
| 88 |
+
17007000002000192,
|
| 89 |
+
17007000002000194,
|
| 90 |
+
]
|
| 91 |
+
}
|
| 92 |
+
)
|
| 93 |
+
tm.assert_frame_equal(result, expected)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@pytest.mark.parametrize("sep", [" ", r"\s+"])
|
| 97 |
+
def test_integer_overflow_bug(all_parsers, sep):
|
| 98 |
+
# see gh-2601
|
| 99 |
+
data = "65248E10 11\n55555E55 22\n"
|
| 100 |
+
parser = all_parsers
|
| 101 |
+
if parser.engine == "pyarrow" and sep != " ":
|
| 102 |
+
msg = "the 'pyarrow' engine does not support separators > 1 char"
|
| 103 |
+
with pytest.raises(ValueError, match=msg):
|
| 104 |
+
parser.read_csv(StringIO(data), header=None, sep=sep)
|
| 105 |
+
return
|
| 106 |
+
|
| 107 |
+
result = parser.read_csv(StringIO(data), header=None, sep=sep)
|
| 108 |
+
expected = pd.DataFrame([[6.5248e14, 11], [5.5555e59, 22]])
|
| 109 |
+
tm.assert_frame_equal(result, expected)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_int64_min_issues(all_parsers):
|
| 113 |
+
# see gh-2599
|
| 114 |
+
parser = all_parsers
|
| 115 |
+
data = "A,B\n0,0\n0,"
|
| 116 |
+
result = parser.read_csv(StringIO(data))
|
| 117 |
+
|
| 118 |
+
expected = pd.DataFrame({"A": [0, 0], "B": [0, np.nan]})
|
| 119 |
+
tm.assert_frame_equal(result, expected)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@pytest.mark.parametrize("conv", [None, np.int64, np.uint64])
|
| 123 |
+
def test_int64_overflow(all_parsers, conv, request):
|
| 124 |
+
data = """ID
|
| 125 |
+
00013007854817840016671868
|
| 126 |
+
00013007854817840016749251
|
| 127 |
+
00013007854817840016754630
|
| 128 |
+
00013007854817840016781876
|
| 129 |
+
00013007854817840017028824
|
| 130 |
+
00013007854817840017963235
|
| 131 |
+
00013007854817840018860166"""
|
| 132 |
+
parser = all_parsers
|
| 133 |
+
|
| 134 |
+
if conv is None:
|
| 135 |
+
# 13007854817840016671868 > UINT64_MAX, so this
|
| 136 |
+
# will overflow and return object as the dtype.
|
| 137 |
+
if parser.engine == "pyarrow":
|
| 138 |
+
mark = pytest.mark.xfail(reason="parses to float64")
|
| 139 |
+
request.applymarker(mark)
|
| 140 |
+
|
| 141 |
+
result = parser.read_csv(StringIO(data))
|
| 142 |
+
expected = pd.DataFrame(
|
| 143 |
+
[
|
| 144 |
+
13007854817840016671868,
|
| 145 |
+
13007854817840016749251,
|
| 146 |
+
13007854817840016754630,
|
| 147 |
+
13007854817840016781876,
|
| 148 |
+
13007854817840017028824,
|
| 149 |
+
13007854817840017963235,
|
| 150 |
+
13007854817840018860166,
|
| 151 |
+
],
|
| 152 |
+
columns=["ID"],
|
| 153 |
+
)
|
| 154 |
+
tm.assert_frame_equal(result, expected)
|
| 155 |
+
else:
|
| 156 |
+
# 13007854817840016671868 > UINT64_MAX, so attempts
|
| 157 |
+
# to cast to either int64 or uint64 will result in
|
| 158 |
+
# an OverflowError being raised.
|
| 159 |
+
msg = "|".join(
|
| 160 |
+
[
|
| 161 |
+
"Python int too large to convert to C long",
|
| 162 |
+
"long too big to convert",
|
| 163 |
+
"int too big to convert",
|
| 164 |
+
]
|
| 165 |
+
)
|
| 166 |
+
err = OverflowError
|
| 167 |
+
if parser.engine == "pyarrow":
|
| 168 |
+
err = ValueError
|
| 169 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 170 |
+
|
| 171 |
+
with pytest.raises(err, match=msg):
|
| 172 |
+
parser.read_csv(StringIO(data), converters={"ID": conv})
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 176 |
+
@pytest.mark.parametrize(
|
| 177 |
+
"val", [np.iinfo(np.uint64).max, np.iinfo(np.int64).max, np.iinfo(np.int64).min]
|
| 178 |
+
)
|
| 179 |
+
def test_int64_uint64_range(all_parsers, val):
|
| 180 |
+
# These numbers fall right inside the int64-uint64
|
| 181 |
+
# range, so they should be parsed as integer.
|
| 182 |
+
parser = all_parsers
|
| 183 |
+
result = parser.read_csv(StringIO(str(val)), header=None)
|
| 184 |
+
|
| 185 |
+
expected = pd.DataFrame([val])
|
| 186 |
+
tm.assert_frame_equal(result, expected)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 190 |
+
@pytest.mark.parametrize(
|
| 191 |
+
"val",
|
| 192 |
+
[
|
| 193 |
+
np.iinfo(np.uint64).max + 1,
|
| 194 |
+
np.iinfo(np.int64).min - 1,
|
| 195 |
+
# 20-digit values that exceed uint64 by more than 2**64, so a parser
|
| 196 |
+
# accumulating into a 64-bit register wraps back into the range of
|
| 197 |
+
# valid 20-digit values and can miss the overflow (GH#66457)
|
| 198 |
+
30000000000000000000,
|
| 199 |
+
47386862472818278521,
|
| 200 |
+
# 5 * 2**64 - 10, whose residue is 10 below uint64 max and so looks
|
| 201 |
+
# maximally plausible (GH#66238)
|
| 202 |
+
92233720368547758070,
|
| 203 |
+
],
|
| 204 |
+
)
|
| 205 |
+
def test_outside_int64_uint64_range(all_parsers, val, request):
|
| 206 |
+
# These numbers fall just outside the int64-uint64
|
| 207 |
+
# range, so they should be parsed as object.
|
| 208 |
+
parser = all_parsers
|
| 209 |
+
|
| 210 |
+
result = parser.read_csv(StringIO(str(val)), header=None)
|
| 211 |
+
|
| 212 |
+
expected = pd.DataFrame([val])
|
| 213 |
+
tm.assert_frame_equal(result, expected)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 217 |
+
@pytest.mark.parametrize(
|
| 218 |
+
"val", [np.iinfo(np.uint64).max + 1, np.iinfo(np.int64).min - 1]
|
| 219 |
+
)
|
| 220 |
+
def test_outside_int64_uint64_range_follow_str(all_parsers, val):
|
| 221 |
+
parser = all_parsers
|
| 222 |
+
|
| 223 |
+
result = parser.read_csv(StringIO(f"{val}\nabc"), header=None)
|
| 224 |
+
|
| 225 |
+
expected = pd.DataFrame([str(val), "abc"])
|
| 226 |
+
tm.assert_frame_equal(result, expected)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@xfail_pyarrow # gets float64 dtype instead of object
|
| 230 |
+
@pytest.mark.parametrize("exp_data", [[str(-1), str(2**63)], [str(2**63), str(-1)]])
|
| 231 |
+
def test_numeric_range_too_wide(all_parsers, exp_data):
|
| 232 |
+
# No numerical dtype can hold both negative and uint64
|
| 233 |
+
# values, so they should be cast as string.
|
| 234 |
+
parser = all_parsers
|
| 235 |
+
data = "\n".join(exp_data)
|
| 236 |
+
expected = pd.DataFrame(exp_data)
|
| 237 |
+
|
| 238 |
+
result = parser.read_csv(StringIO(data), header=None)
|
| 239 |
+
tm.assert_frame_equal(result, expected)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def test_integer_precision(all_parsers):
|
| 243 |
+
# Gh 7072
|
| 244 |
+
s = """1,1;0;0;0;1;1;3844;3844;3844;1;1;1;1;1;1;0;0;1;1;0;0,,,4321583677327450765
|
| 245 |
+
5,1;0;0;0;1;1;843;843;843;1;1;1;1;1;1;0;0;1;1;0;0,64.0,;,4321113141090630389"""
|
| 246 |
+
parser = all_parsers
|
| 247 |
+
result = parser.read_csv(StringIO(s), header=None)[4]
|
| 248 |
+
expected = pd.Series([4321583677327450765, 4321113141090630389], name=4)
|
| 249 |
+
tm.assert_series_equal(result, expected)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def test_thousands_digit_char(all_parsers):
|
| 253 |
+
# GH#66487: a digit thousands separator is degenerate but accepted, and
|
| 254 |
+
# gets stripped like any other separator; the C engine's all-digits
|
| 255 |
+
# integer fast path must not swallow it
|
| 256 |
+
parser = all_parsers
|
| 257 |
+
data = "a\n1000\n"
|
| 258 |
+
if parser.engine == "pyarrow":
|
| 259 |
+
msg = "The 'thousands' option is not supported with the 'pyarrow' engine"
|
| 260 |
+
with pytest.raises(ValueError, match=msg):
|
| 261 |
+
parser.read_csv(StringIO(data), thousands="0")
|
| 262 |
+
return
|
| 263 |
+
result = parser.read_csv(StringIO(data), thousands="0")
|
| 264 |
+
expected = pd.DataFrame({"a": [1]})
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
| 2 |
+
Tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from io import StringIO
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import pandas._testing as tm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_iterator(all_parsers):
|
| 15 |
+
# see gh-6607
|
| 16 |
+
data = """index,A,B,C,D
|
| 17 |
+
foo,2,3,4,5
|
| 18 |
+
bar,7,8,9,10
|
| 19 |
+
baz,12,13,14,15
|
| 20 |
+
qux,12,13,14,15
|
| 21 |
+
foo2,12,13,14,15
|
| 22 |
+
bar2,12,13,14,15
|
| 23 |
+
"""
|
| 24 |
+
parser = all_parsers
|
| 25 |
+
kwargs = {"index_col": 0}
|
| 26 |
+
|
| 27 |
+
expected = parser.read_csv(StringIO(data), **kwargs)
|
| 28 |
+
|
| 29 |
+
if parser.engine == "pyarrow":
|
| 30 |
+
msg = "The 'iterator' option is not supported with the 'pyarrow' engine"
|
| 31 |
+
with pytest.raises(ValueError, match=msg):
|
| 32 |
+
parser.read_csv(StringIO(data), iterator=True, **kwargs)
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
with parser.read_csv(StringIO(data), iterator=True, **kwargs) as reader:
|
| 36 |
+
first_chunk = reader.read(3)
|
| 37 |
+
tm.assert_frame_equal(first_chunk, expected[:3])
|
| 38 |
+
|
| 39 |
+
last_chunk = reader.read(5)
|
| 40 |
+
tm.assert_frame_equal(last_chunk, expected[3:])
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_iterator2(all_parsers):
|
| 44 |
+
parser = all_parsers
|
| 45 |
+
data = """A,B,C
|
| 46 |
+
foo,1,2,3
|
| 47 |
+
bar,4,5,6
|
| 48 |
+
baz,7,8,9
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
if parser.engine == "pyarrow":
|
| 52 |
+
msg = "The 'iterator' option is not supported with the 'pyarrow' engine"
|
| 53 |
+
with pytest.raises(ValueError, match=msg):
|
| 54 |
+
parser.read_csv(StringIO(data), iterator=True)
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
with parser.read_csv(StringIO(data), iterator=True) as reader:
|
| 58 |
+
result = list(reader)
|
| 59 |
+
|
| 60 |
+
expected = pd.DataFrame(
|
| 61 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
|
| 62 |
+
index=["foo", "bar", "baz"],
|
| 63 |
+
columns=["A", "B", "C"],
|
| 64 |
+
)
|
| 65 |
+
tm.assert_frame_equal(result[0], expected)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_iterator_stop_on_chunksize(all_parsers):
|
| 69 |
+
# gh-3967: stopping iteration when chunksize is specified
|
| 70 |
+
parser = all_parsers
|
| 71 |
+
data = """A,B,C
|
| 72 |
+
foo,1,2,3
|
| 73 |
+
bar,4,5,6
|
| 74 |
+
baz,7,8,9
|
| 75 |
+
"""
|
| 76 |
+
if parser.engine == "pyarrow":
|
| 77 |
+
msg = "The 'chunksize' option is not supported with the 'pyarrow' engine"
|
| 78 |
+
with pytest.raises(ValueError, match=msg):
|
| 79 |
+
parser.read_csv(StringIO(data), chunksize=1)
|
| 80 |
+
return
|
| 81 |
+
|
| 82 |
+
with parser.read_csv(StringIO(data), chunksize=1) as reader:
|
| 83 |
+
result = list(reader)
|
| 84 |
+
|
| 85 |
+
assert len(result) == 3
|
| 86 |
+
expected = pd.DataFrame(
|
| 87 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
|
| 88 |
+
index=["foo", "bar", "baz"],
|
| 89 |
+
columns=["A", "B", "C"],
|
| 90 |
+
)
|
| 91 |
+
tm.assert_frame_equal(pd.concat(result), expected)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_nrows_iterator_without_chunksize(all_parsers):
|
| 95 |
+
# GH 59079
|
| 96 |
+
parser = all_parsers
|
| 97 |
+
data = """A,B,C
|
| 98 |
+
foo,1,2,3
|
| 99 |
+
bar,4,5,6
|
| 100 |
+
baz,7,8,9
|
| 101 |
+
"""
|
| 102 |
+
if parser.engine == "pyarrow":
|
| 103 |
+
msg = "The 'iterator' option is not supported with the 'pyarrow' engine"
|
| 104 |
+
with pytest.raises(ValueError, match=msg):
|
| 105 |
+
parser.read_csv(StringIO(data), iterator=True, nrows=2)
|
| 106 |
+
return
|
| 107 |
+
|
| 108 |
+
with parser.read_csv(StringIO(data), iterator=True, nrows=2) as reader:
|
| 109 |
+
result = reader.get_chunk()
|
| 110 |
+
|
| 111 |
+
expected = pd.DataFrame(
|
| 112 |
+
[[1, 2, 3], [4, 5, 6]],
|
| 113 |
+
index=["foo", "bar"],
|
| 114 |
+
columns=["A", "B", "C"],
|
| 115 |
+
)
|
| 116 |
+
tm.assert_frame_equal(result, expected)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@pytest.mark.parametrize(
|
| 120 |
+
"kwargs", [{"iterator": True, "chunksize": 1}, {"iterator": True}, {"chunksize": 1}]
|
| 121 |
+
)
|
| 122 |
+
def test_iterator_skipfooter_errors(all_parsers, kwargs):
|
| 123 |
+
msg = "'skipfooter' not supported for iteration"
|
| 124 |
+
parser = all_parsers
|
| 125 |
+
data = "a\n1\n2"
|
| 126 |
+
|
| 127 |
+
if parser.engine == "pyarrow":
|
| 128 |
+
msg = (
|
| 129 |
+
"The '(chunksize|iterator)' option is not supported with the "
|
| 130 |
+
"'pyarrow' engine"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
with pytest.raises(ValueError, match=msg):
|
| 134 |
+
with parser.read_csv(StringIO(data), skipfooter=1, **kwargs) as _:
|
| 135 |
+
pass
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def test_iteration_open_handle(temp_file, all_parsers):
|
| 139 |
+
parser = all_parsers
|
| 140 |
+
kwargs = {"header": None}
|
| 141 |
+
|
| 142 |
+
with open(temp_file, "w", encoding="utf-8") as f:
|
| 143 |
+
f.write("AAA\nBBB\nCCC\nDDD\nEEE\nFFF\nGGG")
|
| 144 |
+
|
| 145 |
+
with open(temp_file, encoding="utf-8") as f:
|
| 146 |
+
for line in f:
|
| 147 |
+
if "CCC" in line:
|
| 148 |
+
break
|
| 149 |
+
|
| 150 |
+
result = parser.read_csv(f, **kwargs)
|
| 151 |
+
expected = pd.DataFrame({0: ["DDD", "EEE", "FFF", "GGG"]})
|
| 152 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/common/test_read_errors.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 5 |
+
|
| 6 |
+
import codecs
|
| 7 |
+
import csv
|
| 8 |
+
from io import StringIO
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
from pandas.errors import (
|
| 14 |
+
EmptyDataError,
|
| 15 |
+
ParserError,
|
| 16 |
+
ParserWarning,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
import pandas as pd
|
| 20 |
+
import pandas._testing as tm
|
| 21 |
+
|
| 22 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 23 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_empty_decimal_marker(all_parsers):
|
| 27 |
+
data = """A|B|C
|
| 28 |
+
1|2,334|5
|
| 29 |
+
10|13|10.
|
| 30 |
+
"""
|
| 31 |
+
# Parsers support only length-1 decimals
|
| 32 |
+
msg = "Only length-1 decimal markers supported"
|
| 33 |
+
parser = all_parsers
|
| 34 |
+
|
| 35 |
+
with pytest.raises(ValueError, match=msg):
|
| 36 |
+
parser.read_csv(StringIO(data), decimal="")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize("escapechar", ["", "xx"])
|
| 40 |
+
def test_bad_escapechar(all_parsers, escapechar):
|
| 41 |
+
# GH#66317
|
| 42 |
+
data = "a,b\n1,2"
|
| 43 |
+
parser = all_parsers
|
| 44 |
+
|
| 45 |
+
if parser.engine == "python":
|
| 46 |
+
# message and exception type come from the csv module
|
| 47 |
+
err = TypeError
|
| 48 |
+
msg = '"escapechar" must be'
|
| 49 |
+
else:
|
| 50 |
+
err = ValueError
|
| 51 |
+
msg = "Only length-1 escapes supported"
|
| 52 |
+
|
| 53 |
+
with pytest.raises(err, match=msg):
|
| 54 |
+
parser.read_csv(StringIO(data), escapechar=escapechar)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_empty_sep(pyarrow_parser_only):
|
| 58 |
+
# GH#66317 previously leaked a cryptic error from pyarrow option
|
| 59 |
+
# conversion; the C engine has a similarly-cryptic error here and the
|
| 60 |
+
# python engine treats sep="" as a regex, so pyarrow-only.
|
| 61 |
+
data = "a,b\n1,2"
|
| 62 |
+
parser = pyarrow_parser_only
|
| 63 |
+
|
| 64 |
+
msg = "Only length-1 delimiters supported"
|
| 65 |
+
with pytest.raises(ValueError, match=msg):
|
| 66 |
+
parser.read_csv(StringIO(data), sep="")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_bad_stream_exception(all_parsers, datapath):
|
| 70 |
+
# see gh-13652
|
| 71 |
+
#
|
| 72 |
+
# This test validates that both the Python engine and C engine will
|
| 73 |
+
# raise UnicodeDecodeError instead of C engine raising ParserError
|
| 74 |
+
# and swallowing the exception that caused read to fail.
|
| 75 |
+
path = datapath("io", "parser", "data", "sauron.SHIFT_JIS.csv")
|
| 76 |
+
codec = codecs.lookup("utf-8")
|
| 77 |
+
utf8 = codecs.lookup("utf-8")
|
| 78 |
+
parser = all_parsers
|
| 79 |
+
msg = "'utf-8' codec can't decode byte"
|
| 80 |
+
|
| 81 |
+
# Stream must be binary UTF8.
|
| 82 |
+
with (
|
| 83 |
+
open(path, "rb") as handle,
|
| 84 |
+
codecs.StreamRecoder(
|
| 85 |
+
handle, utf8.encode, utf8.decode, codec.streamreader, codec.streamwriter
|
| 86 |
+
) as stream,
|
| 87 |
+
):
|
| 88 |
+
with pytest.raises(UnicodeDecodeError, match=msg):
|
| 89 |
+
parser.read_csv(stream)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_malformed(all_parsers):
|
| 93 |
+
# see gh-6607
|
| 94 |
+
parser = all_parsers
|
| 95 |
+
data = """ignore
|
| 96 |
+
A,B,C
|
| 97 |
+
1,2,3 # comment
|
| 98 |
+
1,2,3,4,5
|
| 99 |
+
2,3,4
|
| 100 |
+
"""
|
| 101 |
+
msg = "Expected 3 fields in line 4, saw 5"
|
| 102 |
+
err = ParserError
|
| 103 |
+
if parser.engine == "pyarrow":
|
| 104 |
+
msg = "The 'comment' option is not supported with the 'pyarrow' engine"
|
| 105 |
+
err = ValueError
|
| 106 |
+
with pytest.raises(err, match=msg):
|
| 107 |
+
parser.read_csv(StringIO(data), header=1, comment="#")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@pytest.mark.parametrize("nrows", [5, 3, None])
|
| 111 |
+
def test_malformed_chunks(all_parsers, nrows):
|
| 112 |
+
data = """ignore
|
| 113 |
+
A,B,C
|
| 114 |
+
skip
|
| 115 |
+
1,2,3
|
| 116 |
+
3,5,10 # comment
|
| 117 |
+
1,2,3,4,5
|
| 118 |
+
2,3,4
|
| 119 |
+
"""
|
| 120 |
+
parser = all_parsers
|
| 121 |
+
|
| 122 |
+
if parser.engine == "pyarrow":
|
| 123 |
+
msg = "The 'iterator' option is not supported with the 'pyarrow' engine"
|
| 124 |
+
with pytest.raises(ValueError, match=msg):
|
| 125 |
+
parser.read_csv(
|
| 126 |
+
StringIO(data),
|
| 127 |
+
header=1,
|
| 128 |
+
comment="#",
|
| 129 |
+
iterator=True,
|
| 130 |
+
chunksize=1,
|
| 131 |
+
skiprows=[2],
|
| 132 |
+
)
|
| 133 |
+
return
|
| 134 |
+
|
| 135 |
+
msg = "Expected 3 fields in line 6, saw 5"
|
| 136 |
+
with parser.read_csv(
|
| 137 |
+
StringIO(data), header=1, comment="#", iterator=True, chunksize=1, skiprows=[2]
|
| 138 |
+
) as reader:
|
| 139 |
+
with pytest.raises(ParserError, match=msg):
|
| 140 |
+
reader.read(nrows)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_catch_too_many_names(all_parsers):
|
| 144 |
+
# see gh-5156
|
| 145 |
+
data = """\
|
| 146 |
+
1,2,3
|
| 147 |
+
4,,6
|
| 148 |
+
7,8,9
|
| 149 |
+
10,11,12\n"""
|
| 150 |
+
parser = all_parsers
|
| 151 |
+
msg = (
|
| 152 |
+
"Too many columns specified: expected 4 and found 3"
|
| 153 |
+
if parser.engine == "c"
|
| 154 |
+
else "Number of passed names did not match number of header fields in the file"
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
with pytest.raises(ValueError, match=msg):
|
| 158 |
+
parser.read_csv(StringIO(data), header=0, names=["a", "b", "c", "d"])
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 162 |
+
@pytest.mark.parametrize("nrows", [0, 1, 2, 3, 4, 5])
|
| 163 |
+
def test_raise_on_no_columns(all_parsers, nrows):
|
| 164 |
+
parser = all_parsers
|
| 165 |
+
data = "\n" * nrows
|
| 166 |
+
|
| 167 |
+
msg = "No columns to parse from file"
|
| 168 |
+
with pytest.raises(EmptyDataError, match=msg):
|
| 169 |
+
parser.read_csv(StringIO(data))
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def test_unexpected_keyword_parameter_exception(all_parsers):
|
| 173 |
+
# GH-34976
|
| 174 |
+
parser = all_parsers
|
| 175 |
+
|
| 176 |
+
msg = "{}\\(\\) got an unexpected keyword argument 'foo'"
|
| 177 |
+
with pytest.raises(TypeError, match=msg.format("read_csv")):
|
| 178 |
+
parser.read_csv("foo.csv", foo=1)
|
| 179 |
+
with pytest.raises(TypeError, match=msg.format("read_table")):
|
| 180 |
+
parser.read_table("foo.tsv", foo=1)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def test_suppress_error_output(all_parsers):
|
| 184 |
+
# see gh-15925
|
| 185 |
+
parser = all_parsers
|
| 186 |
+
data = "a\n1\n1,2,3\n4\n5,6,7"
|
| 187 |
+
expected = pd.DataFrame({"a": [1, 4]})
|
| 188 |
+
|
| 189 |
+
result = parser.read_csv(StringIO(data), on_bad_lines="skip")
|
| 190 |
+
tm.assert_frame_equal(result, expected)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_error_bad_lines(all_parsers):
|
| 194 |
+
# see gh-15925
|
| 195 |
+
parser = all_parsers
|
| 196 |
+
data = "a\n1\n1,2,3\n4\n5,6,7"
|
| 197 |
+
|
| 198 |
+
msg = "Expected 1 fields in line 3, saw 3"
|
| 199 |
+
|
| 200 |
+
if parser.engine == "pyarrow":
|
| 201 |
+
# "CSV parse error: Expected 1 columns, got 3: 1,2,3"
|
| 202 |
+
pytest.skip(reason="https://github.com/apache/arrow/issues/38676")
|
| 203 |
+
|
| 204 |
+
with pytest.raises(ParserError, match=msg):
|
| 205 |
+
parser.read_csv(StringIO(data), on_bad_lines="error")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def test_warn_bad_lines(all_parsers):
|
| 209 |
+
# see gh-15925
|
| 210 |
+
parser = all_parsers
|
| 211 |
+
data = "a\n1\n1,2,3\n4\n5,6,7"
|
| 212 |
+
expected = pd.DataFrame({"a": [1, 4]})
|
| 213 |
+
match_msg = "Skipping line"
|
| 214 |
+
|
| 215 |
+
expected_warning = ParserWarning
|
| 216 |
+
if parser.engine == "pyarrow":
|
| 217 |
+
match_msg = "Expected 1 columns, but found 3: 1,2,3"
|
| 218 |
+
|
| 219 |
+
with tm.assert_produces_warning(
|
| 220 |
+
expected_warning, match=match_msg, check_stacklevel=False
|
| 221 |
+
):
|
| 222 |
+
result = parser.read_csv(StringIO(data), on_bad_lines="warn")
|
| 223 |
+
tm.assert_frame_equal(result, expected)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@skip_pyarrow # AttributeError: 'bool' object has no attribute 'copy'
|
| 227 |
+
def test_error_bad_lines_index_col_false(all_parsers):
|
| 228 |
+
# GH#49279
|
| 229 |
+
parser = all_parsers
|
| 230 |
+
data = "a,b\n1,2\n3,4,5\n6,7"
|
| 231 |
+
msg = "Expected 2 fields in line 3, saw 3"
|
| 232 |
+
|
| 233 |
+
with pytest.raises(ParserError, match=msg):
|
| 234 |
+
parser.read_csv(StringIO(data), index_col=False, on_bad_lines="error")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
@skip_pyarrow # AttributeError: 'bool' object has no attribute 'copy'
|
| 238 |
+
def test_skip_bad_lines_index_col_false(all_parsers):
|
| 239 |
+
# GH#49279
|
| 240 |
+
parser = all_parsers
|
| 241 |
+
data = "a,b\n1,2\n3,4,5\n6,7"
|
| 242 |
+
expected = pd.DataFrame({"a": [1, 6], "b": [2, 7]})
|
| 243 |
+
|
| 244 |
+
result = parser.read_csv(StringIO(data), index_col=False, on_bad_lines="skip")
|
| 245 |
+
tm.assert_frame_equal(result, expected)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
@skip_pyarrow # AttributeError: 'bool' object has no attribute 'copy'
|
| 249 |
+
def test_index_col_false_wider_rows_are_not_bad_lines(all_parsers):
|
| 250 |
+
# GH#2442, GH#49279 - wider rows are data to truncate, not bad lines
|
| 251 |
+
parser = all_parsers
|
| 252 |
+
data = "A,B,C\n1,2,3,4\n5,6,7,8"
|
| 253 |
+
expected = pd.DataFrame({"A": [1, 5], "B": [2, 6], "C": [3, 7]})
|
| 254 |
+
|
| 255 |
+
result = parser.read_csv_check_warnings(
|
| 256 |
+
ParserWarning,
|
| 257 |
+
"Length of header or names does not match length of data",
|
| 258 |
+
StringIO(data),
|
| 259 |
+
index_col=False,
|
| 260 |
+
on_bad_lines="error",
|
| 261 |
+
)
|
| 262 |
+
tm.assert_frame_equal(result, expected)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@skip_pyarrow # AttributeError: 'bool' object has no attribute 'copy'
|
| 266 |
+
def test_index_col_false_bad_line_counted_from_first_row(all_parsers):
|
| 267 |
+
# GH#49279 - the first data row is wider than the header, so it is the width
|
| 268 |
+
# the bad line is measured against and the one the message reports
|
| 269 |
+
parser = all_parsers
|
| 270 |
+
data = "A,B,C\n1,2,3,4\n5,6,7,8,9"
|
| 271 |
+
|
| 272 |
+
with pytest.raises(ParserError, match="Expected 4 fields in line 3, saw 5"):
|
| 273 |
+
parser.read_csv(StringIO(data), index_col=False, on_bad_lines="error")
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
@skip_pyarrow # AttributeError: 'bool' object has no attribute 'copy'
|
| 277 |
+
def test_index_col_false_bad_line_with_names(all_parsers):
|
| 278 |
+
# GH#49279 - with names the first data row is already buffered by the time the
|
| 279 |
+
# expected width is taken, so it must not be measured on the second row
|
| 280 |
+
parser = all_parsers
|
| 281 |
+
kwargs = {
|
| 282 |
+
"index_col": False,
|
| 283 |
+
"header": 1,
|
| 284 |
+
"names": ["x", "y"],
|
| 285 |
+
"on_bad_lines": "error",
|
| 286 |
+
}
|
| 287 |
+
expected = pd.DataFrame({"x": [1, 4, 6], "y": [2, 5, 7]})
|
| 288 |
+
|
| 289 |
+
result = parser.read_csv_check_warnings(
|
| 290 |
+
ParserWarning,
|
| 291 |
+
"Length of header or names does not match length of data",
|
| 292 |
+
StringIO("hdr\na,b\n1,2,3\n4,5\n6,7,8"),
|
| 293 |
+
**kwargs,
|
| 294 |
+
)
|
| 295 |
+
tm.assert_frame_equal(result, expected)
|
| 296 |
+
|
| 297 |
+
with pytest.raises(ParserError, match="Expected 3 fields in line 5, saw 4"):
|
| 298 |
+
parser.read_csv(StringIO("hdr\na,b\n1,2,3\n4,5\n6,7,8,9"), **kwargs)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@skip_pyarrow # AttributeError: 'bool' object has no attribute 'copy'
|
| 302 |
+
def test_index_col_false_single_data_row_with_names(all_parsers):
|
| 303 |
+
# GH#49279 - the only data row is already buffered and there is no second row
|
| 304 |
+
# to fall back on, so the expected width still has to come from the buffer
|
| 305 |
+
parser = all_parsers
|
| 306 |
+
kwargs = {"index_col": False, "header": 0, "names": ["x", "y"]}
|
| 307 |
+
expected = pd.DataFrame({"x": [1], "y": [2]})
|
| 308 |
+
|
| 309 |
+
result = parser.read_csv_check_warnings(
|
| 310 |
+
ParserWarning,
|
| 311 |
+
"Length of header or names does not match length of data",
|
| 312 |
+
StringIO("a,b\n1,2,3\n"),
|
| 313 |
+
**kwargs,
|
| 314 |
+
)
|
| 315 |
+
tm.assert_frame_equal(result, expected)
|
| 316 |
+
|
| 317 |
+
# GH#2442 - a trailing delimiter is truncated, not treated as a bad line
|
| 318 |
+
result = parser.read_csv(StringIO("a,b\n1,2,\n"), **kwargs)
|
| 319 |
+
tm.assert_frame_equal(result, expected)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
@skip_pyarrow # AttributeError: 'bool' object has no attribute 'copy'
|
| 323 |
+
def test_index_col_false_short_names_keep_header_width(all_parsers):
|
| 324 |
+
# GH#49279 - names replaces the column count, but the header line is still what
|
| 325 |
+
# a wider row is measured against, so this row is truncated rather than dropped
|
| 326 |
+
parser = all_parsers
|
| 327 |
+
expected = pd.DataFrame({"x": [1, 3], "y": [2, 4]})
|
| 328 |
+
|
| 329 |
+
result = parser.read_csv_check_warnings(
|
| 330 |
+
ParserWarning,
|
| 331 |
+
"Length of header or names does not match length of data",
|
| 332 |
+
StringIO("a,b,c\n1,2\n3,4,5\n"),
|
| 333 |
+
names=["x", "y"],
|
| 334 |
+
header=0,
|
| 335 |
+
index_col=False,
|
| 336 |
+
on_bad_lines="error",
|
| 337 |
+
)
|
| 338 |
+
tm.assert_frame_equal(result, expected)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def test_read_csv_wrong_num_columns(all_parsers):
|
| 342 |
+
# Too few columns.
|
| 343 |
+
data = """A,B,C,D,E,F
|
| 344 |
+
1,2,3,4,5,6
|
| 345 |
+
6,7,8,9,10,11,12
|
| 346 |
+
11,12,13,14,15,16
|
| 347 |
+
"""
|
| 348 |
+
parser = all_parsers
|
| 349 |
+
msg = "Expected 6 fields in line 3, saw 7"
|
| 350 |
+
|
| 351 |
+
if parser.engine == "pyarrow":
|
| 352 |
+
# Expected 6 columns, got 7: 6,7,8,9,10,11,12
|
| 353 |
+
pytest.skip(reason="https://github.com/apache/arrow/issues/38676")
|
| 354 |
+
|
| 355 |
+
with pytest.raises(ParserError, match=msg):
|
| 356 |
+
parser.read_csv(StringIO(data))
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def test_null_byte_char(all_parsers):
|
| 360 |
+
# see gh-2741
|
| 361 |
+
data = "\x00,foo"
|
| 362 |
+
names = ["a", "b"]
|
| 363 |
+
parser = all_parsers
|
| 364 |
+
|
| 365 |
+
if parser.engine in ["c", "python"]:
|
| 366 |
+
# GH#19886 a lone NUL is a one-character value, not the empty string,
|
| 367 |
+
# so it is not an na_value. The C engine used to compare the
|
| 368 |
+
# NUL-terminated word and report NaN here.
|
| 369 |
+
expected = pd.DataFrame([["\x00", "foo"]], columns=names)
|
| 370 |
+
out = parser.read_csv(StringIO(data), names=names)
|
| 371 |
+
tm.assert_frame_equal(out, expected)
|
| 372 |
+
else:
|
| 373 |
+
if parser.engine == "pyarrow":
|
| 374 |
+
# CSV parse error: Empty CSV file or block: "
|
| 375 |
+
# cannot infer number of columns"
|
| 376 |
+
pytest.skip(reason="https://github.com/apache/arrow/issues/38676")
|
| 377 |
+
else:
|
| 378 |
+
msg = "NULL byte detected"
|
| 379 |
+
with pytest.raises(ParserError, match=msg):
|
| 380 |
+
parser.read_csv(StringIO(data), names=names)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def test_open_file(all_parsers, temp_file):
|
| 384 |
+
# GH 39024
|
| 385 |
+
parser = all_parsers
|
| 386 |
+
|
| 387 |
+
msg = "Could not determine delimiter"
|
| 388 |
+
err = csv.Error
|
| 389 |
+
if parser.engine in ("c", "pyarrow"):
|
| 390 |
+
msg = f"the '{parser.engine}' engine does not support sep=None"
|
| 391 |
+
err = ValueError
|
| 392 |
+
|
| 393 |
+
file = Path(temp_file)
|
| 394 |
+
file.write_bytes(b"\xe4\na\n1")
|
| 395 |
+
|
| 396 |
+
with tm.assert_produces_warning(None):
|
| 397 |
+
# should not trigger a ResourceWarning
|
| 398 |
+
with pytest.raises(err, match=msg):
|
| 399 |
+
parser.read_csv(file, sep=None, encoding_errors="replace")
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def test_invalid_on_bad_line(all_parsers):
|
| 403 |
+
parser = all_parsers
|
| 404 |
+
data = "a\n1\n1,2,3\n4\n5,6,7"
|
| 405 |
+
with pytest.raises(ValueError, match="Argument abc is invalid for on_bad_lines"):
|
| 406 |
+
parser.read_csv(StringIO(data), on_bad_lines="abc")
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def test_bad_header_uniform_error(all_parsers):
|
| 410 |
+
parser = all_parsers
|
| 411 |
+
data = "+++123456789...\ncol1,col2,col3,col4\n1,2,3,4\n"
|
| 412 |
+
msg = "Expected 2 fields in line 2, saw 4"
|
| 413 |
+
if parser.engine == "c":
|
| 414 |
+
msg = (
|
| 415 |
+
"Could not construct index. Requested to use 1 "
|
| 416 |
+
"number of columns, but 3 left to parse."
|
| 417 |
+
)
|
| 418 |
+
elif parser.engine == "pyarrow":
|
| 419 |
+
# "CSV parse error: Expected 1 columns, got 4: col1,col2,col3,col4"
|
| 420 |
+
pytest.skip(reason="https://github.com/apache/arrow/issues/38676")
|
| 421 |
+
|
| 422 |
+
with pytest.raises(ParserError, match=msg):
|
| 423 |
+
parser.read_csv(StringIO(data), index_col=0, on_bad_lines="error")
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def test_on_bad_lines_warn_correct_formatting(all_parsers):
|
| 427 |
+
# see gh-15925
|
| 428 |
+
parser = all_parsers
|
| 429 |
+
data = """1,2
|
| 430 |
+
a,b
|
| 431 |
+
a,b,c
|
| 432 |
+
a,b,d
|
| 433 |
+
a,b
|
| 434 |
+
"""
|
| 435 |
+
expected = pd.DataFrame({"1": "a", "2": ["b"] * 2})
|
| 436 |
+
match_msg = "Skipping line"
|
| 437 |
+
|
| 438 |
+
expected_warning = ParserWarning
|
| 439 |
+
if parser.engine == "pyarrow":
|
| 440 |
+
match_msg = "Expected 2 columns, but found 3: a,b,c"
|
| 441 |
+
|
| 442 |
+
with tm.assert_produces_warning(
|
| 443 |
+
expected_warning, match=match_msg, check_stacklevel=False
|
| 444 |
+
):
|
| 445 |
+
result = parser.read_csv(StringIO(data), on_bad_lines="warn")
|
| 446 |
+
tm.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__future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from pandas.compat import HAS_PYARROW
|
| 8 |
+
from pandas.compat._optional import VERSIONS
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import pandas._testing as tm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class BaseParser:
|
| 15 |
+
engine: str | None = None
|
| 16 |
+
low_memory = True
|
| 17 |
+
float_precision_choices: list[str | None] = []
|
| 18 |
+
|
| 19 |
+
def update_kwargs(self, kwargs):
|
| 20 |
+
kwargs = kwargs.copy()
|
| 21 |
+
kwargs.update({"engine": self.engine, "low_memory": self.low_memory})
|
| 22 |
+
|
| 23 |
+
return kwargs
|
| 24 |
+
|
| 25 |
+
def read_csv(self, *args, **kwargs):
|
| 26 |
+
kwargs = self.update_kwargs(kwargs)
|
| 27 |
+
return pd.read_csv(*args, **kwargs)
|
| 28 |
+
|
| 29 |
+
def read_csv_check_warnings(
|
| 30 |
+
self,
|
| 31 |
+
warn_type: type[Warning],
|
| 32 |
+
warn_msg: str,
|
| 33 |
+
*args,
|
| 34 |
+
raise_on_extra_warnings=True,
|
| 35 |
+
check_stacklevel: bool = True,
|
| 36 |
+
**kwargs,
|
| 37 |
+
):
|
| 38 |
+
# We need to check the stacklevel here instead of in the tests
|
| 39 |
+
# since this is where read_csv is called and where the warning
|
| 40 |
+
# should point to.
|
| 41 |
+
kwargs = self.update_kwargs(kwargs)
|
| 42 |
+
with tm.assert_produces_warning(
|
| 43 |
+
warn_type,
|
| 44 |
+
match=warn_msg,
|
| 45 |
+
raise_on_extra_warnings=raise_on_extra_warnings,
|
| 46 |
+
check_stacklevel=check_stacklevel,
|
| 47 |
+
):
|
| 48 |
+
return pd.read_csv(*args, **kwargs)
|
| 49 |
+
|
| 50 |
+
def read_table(self, *args, **kwargs):
|
| 51 |
+
kwargs = self.update_kwargs(kwargs)
|
| 52 |
+
return pd.read_table(*args, **kwargs)
|
| 53 |
+
|
| 54 |
+
def read_table_check_warnings(
|
| 55 |
+
self,
|
| 56 |
+
warn_type: type[Warning],
|
| 57 |
+
warn_msg: str,
|
| 58 |
+
*args,
|
| 59 |
+
raise_on_extra_warnings=True,
|
| 60 |
+
**kwargs,
|
| 61 |
+
):
|
| 62 |
+
# We need to check the stacklevel here instead of in the tests
|
| 63 |
+
# since this is where read_table is called and where the warning
|
| 64 |
+
# should point to.
|
| 65 |
+
kwargs = self.update_kwargs(kwargs)
|
| 66 |
+
with tm.assert_produces_warning(
|
| 67 |
+
warn_type, match=warn_msg, raise_on_extra_warnings=raise_on_extra_warnings
|
| 68 |
+
):
|
| 69 |
+
return pd.read_table(*args, **kwargs)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class CParser(BaseParser):
|
| 73 |
+
engine = "c"
|
| 74 |
+
float_precision_choices = [None, "high", "round_trip"]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class CParserHighMemory(CParser):
|
| 78 |
+
low_memory = False
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class CParserLowMemory(CParser):
|
| 82 |
+
low_memory = True
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class PythonParser(BaseParser):
|
| 86 |
+
engine = "python"
|
| 87 |
+
float_precision_choices = [None]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class PyArrowParser(BaseParser):
|
| 91 |
+
engine = "pyarrow"
|
| 92 |
+
float_precision_choices = [None]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@pytest.fixture
|
| 96 |
+
def csv1(datapath):
|
| 97 |
+
"""
|
| 98 |
+
The path to the data file "test1.csv" needed for parser tests.
|
| 99 |
+
"""
|
| 100 |
+
return os.path.join(datapath("io", "data", "csv"), "test1.csv")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
_cParserHighMemory = CParserHighMemory
|
| 104 |
+
_cParserLowMemory = CParserLowMemory
|
| 105 |
+
_pythonParser = PythonParser
|
| 106 |
+
_pyarrowParser = PyArrowParser
|
| 107 |
+
|
| 108 |
+
_py_parsers_only = [_pythonParser]
|
| 109 |
+
_c_parsers_only = [_cParserHighMemory, _cParserLowMemory]
|
| 110 |
+
_pyarrow_parsers_only = [
|
| 111 |
+
pytest.param(
|
| 112 |
+
_pyarrowParser,
|
| 113 |
+
marks=[
|
| 114 |
+
pytest.mark.single_cpu,
|
| 115 |
+
pytest.mark.skipif(not HAS_PYARROW, reason="pyarrow is not installed"),
|
| 116 |
+
],
|
| 117 |
+
)
|
| 118 |
+
]
|
| 119 |
+
|
| 120 |
+
_all_parsers = [*_c_parsers_only, *_py_parsers_only, *_pyarrow_parsers_only]
|
| 121 |
+
|
| 122 |
+
_py_parser_ids = ["python"]
|
| 123 |
+
_c_parser_ids = ["c_high", "c_low"]
|
| 124 |
+
_pyarrow_parsers_ids = ["pyarrow"]
|
| 125 |
+
|
| 126 |
+
_all_parser_ids = [*_c_parser_ids, *_py_parser_ids, *_pyarrow_parsers_ids]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@pytest.fixture(params=_all_parsers, ids=_all_parser_ids)
|
| 130 |
+
def all_parsers(request):
|
| 131 |
+
"""
|
| 132 |
+
Fixture all of the CSV parsers.
|
| 133 |
+
"""
|
| 134 |
+
parser = request.param()
|
| 135 |
+
if parser.engine == "pyarrow":
|
| 136 |
+
pytest.importorskip("pyarrow", VERSIONS["pyarrow"])
|
| 137 |
+
# Try finding a way to disable threads all together
|
| 138 |
+
# for more stable CI runs
|
| 139 |
+
import pyarrow
|
| 140 |
+
|
| 141 |
+
pyarrow.set_cpu_count(1)
|
| 142 |
+
return parser
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@pytest.fixture(params=_c_parsers_only, ids=_c_parser_ids)
|
| 146 |
+
def c_parser_only(request):
|
| 147 |
+
"""
|
| 148 |
+
Fixture all of the CSV parsers using the C engine.
|
| 149 |
+
"""
|
| 150 |
+
return request.param()
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@pytest.fixture(params=_py_parsers_only, ids=_py_parser_ids)
|
| 154 |
+
def python_parser_only(request):
|
| 155 |
+
"""
|
| 156 |
+
Fixture all of the CSV parsers using the Python engine.
|
| 157 |
+
"""
|
| 158 |
+
return request.param()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@pytest.fixture(params=_pyarrow_parsers_only, ids=_pyarrow_parsers_ids)
|
| 162 |
+
def pyarrow_parser_only(request):
|
| 163 |
+
"""
|
| 164 |
+
Fixture all of the CSV parsers using the Pyarrow engine.
|
| 165 |
+
"""
|
| 166 |
+
return request.param()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _get_all_parser_float_precision_combinations():
|
| 170 |
+
"""
|
| 171 |
+
Return all allowable parser and float precision
|
| 172 |
+
combinations and corresponding ids.
|
| 173 |
+
"""
|
| 174 |
+
params = []
|
| 175 |
+
ids = []
|
| 176 |
+
for parser, parser_id in zip(_all_parsers, _all_parser_ids, strict=True):
|
| 177 |
+
if hasattr(parser, "values"):
|
| 178 |
+
# Wrapped in pytest.param, get the actual parser back
|
| 179 |
+
parser = parser.values[0]
|
| 180 |
+
for precision in parser.float_precision_choices:
|
| 181 |
+
# Re-wrap in pytest.param for pyarrow
|
| 182 |
+
mark = (
|
| 183 |
+
[
|
| 184 |
+
pytest.mark.single_cpu,
|
| 185 |
+
pytest.mark.skipif(
|
| 186 |
+
not HAS_PYARROW, reason="pyarrow is not installed"
|
| 187 |
+
),
|
| 188 |
+
]
|
| 189 |
+
if parser.engine == "pyarrow"
|
| 190 |
+
else ()
|
| 191 |
+
)
|
| 192 |
+
param = pytest.param((parser(), precision), marks=mark)
|
| 193 |
+
params.append(param)
|
| 194 |
+
ids.append(f"{parser_id}-{precision}")
|
| 195 |
+
|
| 196 |
+
return {"params": params, "ids": ids}
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
@pytest.fixture(
|
| 200 |
+
params=_get_all_parser_float_precision_combinations()["params"],
|
| 201 |
+
ids=_get_all_parser_float_precision_combinations()["ids"],
|
| 202 |
+
)
|
| 203 |
+
def all_parsers_all_precisions(request):
|
| 204 |
+
"""
|
| 205 |
+
Fixture for all allowable combinations of parser
|
| 206 |
+
and float precision
|
| 207 |
+
"""
|
| 208 |
+
return request.param
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
_utf_values = [8, 16, 32]
|
| 212 |
+
|
| 213 |
+
_encoding_seps = ["", "-", "_"]
|
| 214 |
+
_encoding_prefixes = ["utf", "UTF"]
|
| 215 |
+
|
| 216 |
+
_encoding_fmts = [
|
| 217 |
+
f"{prefix}{sep}{{0}}" for sep in _encoding_seps for prefix in _encoding_prefixes
|
| 218 |
+
]
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@pytest.fixture(params=_utf_values)
|
| 222 |
+
def utf_value(request):
|
| 223 |
+
"""
|
| 224 |
+
Fixture for all possible integer values for a UTF encoding.
|
| 225 |
+
"""
|
| 226 |
+
return request.param
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@pytest.fixture(params=_encoding_fmts)
|
| 230 |
+
def encoding_fmt(request):
|
| 231 |
+
"""
|
| 232 |
+
Fixture for all possible string formats of a UTF encoding.
|
| 233 |
+
"""
|
| 234 |
+
return request.param
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
@pytest.fixture(
|
| 238 |
+
params=[
|
| 239 |
+
("-1,0", -1.0),
|
| 240 |
+
("-1,2e0", -1.2),
|
| 241 |
+
("-1e0", -1.0),
|
| 242 |
+
("+1e0", 1.0),
|
| 243 |
+
("+1e+0", 1.0),
|
| 244 |
+
("+1e-1", 0.1),
|
| 245 |
+
("+,1e1", 1.0),
|
| 246 |
+
("+1,e0", 1.0),
|
| 247 |
+
("-,1e1", -1.0),
|
| 248 |
+
("-1,e0", -1.0),
|
| 249 |
+
("0,1", 0.1),
|
| 250 |
+
("1,", 1.0),
|
| 251 |
+
(",1", 0.1),
|
| 252 |
+
("-,1", -0.1),
|
| 253 |
+
("1_,", 1.0),
|
| 254 |
+
("1_234,56", 1234.56),
|
| 255 |
+
("1_234,56e0", 1234.56),
|
| 256 |
+
# negative cases; must not parse as float
|
| 257 |
+
("_", "_"),
|
| 258 |
+
("-_", "-_"),
|
| 259 |
+
("-_1", "-_1"),
|
| 260 |
+
("-_1e0", "-_1e0"),
|
| 261 |
+
("_1", "_1"),
|
| 262 |
+
("_1,", "_1,"),
|
| 263 |
+
("_1,_", "_1,_"),
|
| 264 |
+
("_1e0", "_1e0"),
|
| 265 |
+
("1,2e_1", "1,2e_1"),
|
| 266 |
+
("1,2e1_0", "1,2e1_0"),
|
| 267 |
+
("1,_2", "1,_2"),
|
| 268 |
+
(",1__2", ",1__2"),
|
| 269 |
+
(",1e", ",1e"),
|
| 270 |
+
("-,1e", "-,1e"),
|
| 271 |
+
("1_000,000_000", "1_000,000_000"),
|
| 272 |
+
("1,e1_2", "1,e1_2"),
|
| 273 |
+
("e11,2", "e11,2"),
|
| 274 |
+
("1e11,2", "1e11,2"),
|
| 275 |
+
("1,2,2", "1,2,2"),
|
| 276 |
+
("1,2_1", "1,2_1"),
|
| 277 |
+
("1,2e-10e1", "1,2e-10e1"),
|
| 278 |
+
("--1,2", "--1,2"),
|
| 279 |
+
("1a_2,1", "1a_2,1"),
|
| 280 |
+
("1,2E-1", 0.12),
|
| 281 |
+
("1,2E1", 12.0),
|
| 282 |
+
]
|
| 283 |
+
)
|
| 284 |
+
def numeric_decimal(request):
|
| 285 |
+
"""
|
| 286 |
+
Fixture for all numeric formats which should get recognized. The first entry
|
| 287 |
+
represents the value to read while the second represents the expected result.
|
| 288 |
+
"""
|
| 289 |
+
return request.param
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
@pytest.fixture
|
| 293 |
+
def pyarrow_xfail(request):
|
| 294 |
+
"""
|
| 295 |
+
Fixture that xfails a test if the engine is pyarrow.
|
| 296 |
+
|
| 297 |
+
Use if failure is do to unsupported keywords or inconsistent results.
|
| 298 |
+
"""
|
| 299 |
+
if "all_parsers" in request.fixturenames:
|
| 300 |
+
parser = request.getfixturevalue("all_parsers")
|
| 301 |
+
elif "all_parsers_all_precisions" in request.fixturenames:
|
| 302 |
+
# Return value is tuple of (engine, precision)
|
| 303 |
+
parser = request.getfixturevalue("all_parsers_all_precisions")[0]
|
| 304 |
+
else:
|
| 305 |
+
return
|
| 306 |
+
if parser.engine == "pyarrow":
|
| 307 |
+
mark = pytest.mark.xfail(reason="pyarrow doesn't support this.")
|
| 308 |
+
request.applymarker(mark)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
@pytest.fixture
|
| 312 |
+
def pyarrow_skip(request):
|
| 313 |
+
"""
|
| 314 |
+
Fixture that skips a test if the engine is pyarrow.
|
| 315 |
+
|
| 316 |
+
Use if failure is do a parsing failure from pyarrow.csv.read_csv
|
| 317 |
+
"""
|
| 318 |
+
if "all_parsers" in request.fixturenames:
|
| 319 |
+
parser = request.getfixturevalue("all_parsers")
|
| 320 |
+
elif "all_parsers_all_precisions" in request.fixturenames:
|
| 321 |
+
# Return value is tuple of (engine, precision)
|
| 322 |
+
parser = request.getfixturevalue("all_parsers_all_precisions")[0]
|
| 323 |
+
else:
|
| 324 |
+
return
|
| 325 |
+
if parser.engine == "pyarrow":
|
| 326 |
+
pytest.skip(reason="https://github.com/apache/arrow/issues/38676")
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/dtypes/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/dtypes/test_categorical.py
ADDED
|
@@ -0,0 +1,873 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from pandas._config import using_string_dtype
|
| 13 |
+
|
| 14 |
+
from pandas._libs import parsers as libparsers
|
| 15 |
+
from pandas.errors import Pandas4Warning
|
| 16 |
+
|
| 17 |
+
from pandas.core.dtypes.dtypes import CategoricalDtype
|
| 18 |
+
|
| 19 |
+
import pandas as pd
|
| 20 |
+
import pandas._testing as tm
|
| 21 |
+
|
| 22 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.mark.parametrize(
|
| 26 |
+
"dtype",
|
| 27 |
+
[
|
| 28 |
+
"category",
|
| 29 |
+
CategoricalDtype(),
|
| 30 |
+
{"a": "category", "b": "category", "c": CategoricalDtype()},
|
| 31 |
+
],
|
| 32 |
+
)
|
| 33 |
+
def test_categorical_dtype(all_parsers, dtype):
|
| 34 |
+
# see gh-10153, gh-56044
|
| 35 |
+
# categories should have inferred types (not strings) across all engines
|
| 36 |
+
parser = all_parsers
|
| 37 |
+
data = """a,b,c
|
| 38 |
+
1,a,3.4
|
| 39 |
+
1,a,3.4
|
| 40 |
+
2,b,4.5"""
|
| 41 |
+
expected = pd.DataFrame(
|
| 42 |
+
{
|
| 43 |
+
"a": pd.Categorical([1, 1, 2]),
|
| 44 |
+
"b": pd.Categorical(["a", "a", "b"]),
|
| 45 |
+
"c": pd.Categorical([3.4, 3.4, 4.5]),
|
| 46 |
+
}
|
| 47 |
+
)
|
| 48 |
+
actual = parser.read_csv(StringIO(data), dtype=dtype)
|
| 49 |
+
tm.assert_frame_equal(actual, expected)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@pytest.mark.parametrize("dtype", [{"b": "category"}, {1: "category"}])
|
| 53 |
+
def test_categorical_dtype_single(all_parsers, dtype, request):
|
| 54 |
+
# see gh-10153
|
| 55 |
+
parser = all_parsers
|
| 56 |
+
data = """a,b,c
|
| 57 |
+
1,a,3.4
|
| 58 |
+
1,a,3.4
|
| 59 |
+
2,b,4.5"""
|
| 60 |
+
expected = pd.DataFrame(
|
| 61 |
+
{"a": [1, 1, 2], "b": pd.Categorical(["a", "a", "b"]), "c": [3.4, 3.4, 4.5]}
|
| 62 |
+
)
|
| 63 |
+
if parser.engine == "pyarrow" and any(isinstance(key, int) for key in dtype):
|
| 64 |
+
mark = pytest.mark.xfail(
|
| 65 |
+
reason="pyarrow doesn't support specifying dtype by column index",
|
| 66 |
+
)
|
| 67 |
+
request.applymarker(mark)
|
| 68 |
+
|
| 69 |
+
actual = parser.read_csv(StringIO(data), dtype=dtype)
|
| 70 |
+
tm.assert_frame_equal(actual, expected)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def test_categorical_dtype_unsorted(all_parsers):
|
| 74 |
+
# see gh-10153, gh-56044
|
| 75 |
+
parser = all_parsers
|
| 76 |
+
data = """a,b,c
|
| 77 |
+
1,b,3.4
|
| 78 |
+
1,b,3.4
|
| 79 |
+
2,a,4.5"""
|
| 80 |
+
expected = pd.DataFrame(
|
| 81 |
+
{
|
| 82 |
+
"a": pd.Categorical([1, 1, 2]),
|
| 83 |
+
"b": pd.Categorical(["b", "b", "a"]),
|
| 84 |
+
"c": pd.Categorical([3.4, 3.4, 4.5]),
|
| 85 |
+
}
|
| 86 |
+
)
|
| 87 |
+
actual = parser.read_csv(StringIO(data), dtype="category")
|
| 88 |
+
tm.assert_frame_equal(actual, expected)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_categorical_dtype_missing(all_parsers):
|
| 92 |
+
# see gh-10153, gh-56044
|
| 93 |
+
parser = all_parsers
|
| 94 |
+
data = """a,b,c
|
| 95 |
+
1,b,3.4
|
| 96 |
+
1,nan,3.4
|
| 97 |
+
2,a,4.5"""
|
| 98 |
+
expected = pd.DataFrame(
|
| 99 |
+
{
|
| 100 |
+
"a": pd.Categorical([1, 1, 2]),
|
| 101 |
+
"b": pd.Categorical(["b", np.nan, "a"]),
|
| 102 |
+
"c": pd.Categorical([3.4, 3.4, 4.5]),
|
| 103 |
+
}
|
| 104 |
+
)
|
| 105 |
+
actual = parser.read_csv(StringIO(data), dtype="category")
|
| 106 |
+
tm.assert_frame_equal(actual, expected)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_categorical_dtype_numeric_duplicates(all_parsers):
|
| 110 |
+
# GH#56044 distinct strings that convert to the same number should be
|
| 111 |
+
# merged into a single category. The NA rows make the codes carry -1
|
| 112 |
+
# while the merge recodes the rest, exercising both together.
|
| 113 |
+
parser = all_parsers
|
| 114 |
+
data = "a,b\n1,x\n,x\n1.0,x\n2,x\n,x"
|
| 115 |
+
expected = pd.DataFrame(
|
| 116 |
+
{
|
| 117 |
+
"a": pd.Categorical([1.0, None, 1.0, 2.0, None]),
|
| 118 |
+
"b": pd.Categorical(["x"] * 5),
|
| 119 |
+
}
|
| 120 |
+
)
|
| 121 |
+
actual = parser.read_csv(StringIO(data), dtype="category")
|
| 122 |
+
tm.assert_frame_equal(actual, expected)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_categorical_dtype_signed_zero(all_parsers):
|
| 126 |
+
# GH#56044 "0.0" and "-0.0" converge on one category; which one survives
|
| 127 |
+
# must not depend on the engine or on low_memory chunking
|
| 128 |
+
parser = all_parsers
|
| 129 |
+
data = "a\n0.0\n-0.0"
|
| 130 |
+
result = parser.read_csv(StringIO(data), dtype="category")
|
| 131 |
+
assert not np.signbit(result["a"].cat.categories).any()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@pytest.mark.parametrize(
|
| 135 |
+
"data",
|
| 136 |
+
[
|
| 137 |
+
"a\nTrue\nFalse\nTrue",
|
| 138 |
+
"a\ntrue\nfalse\ntrue",
|
| 139 |
+
"a\nTRUE\nFALSE\nTRUE",
|
| 140 |
+
],
|
| 141 |
+
)
|
| 142 |
+
def test_categorical_dtype_infers_boolean(all_parsers, data):
|
| 143 |
+
# GH#56044 boolean-looking columns infer bool categories across all
|
| 144 |
+
# engines, matching non-categorical parsing
|
| 145 |
+
parser = all_parsers
|
| 146 |
+
expected = pd.DataFrame({"a": pd.Categorical([True, False, True])})
|
| 147 |
+
actual = parser.read_csv(StringIO(data), dtype="category")
|
| 148 |
+
tm.assert_frame_equal(actual, expected)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_categorical_dtype_boolean_duplicates(all_parsers):
|
| 152 |
+
# GH#56044 distinct strings that convert to the same bool should be
|
| 153 |
+
# merged into a single category
|
| 154 |
+
parser = all_parsers
|
| 155 |
+
data = "a\nTrue\nTRUE\ntrue\nFalse"
|
| 156 |
+
expected = pd.DataFrame({"a": pd.Categorical([True, True, True, False])})
|
| 157 |
+
actual = parser.read_csv(StringIO(data), dtype="category")
|
| 158 |
+
tm.assert_frame_equal(actual, expected)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_categorical_dtype_boolean_mixed_case(all_parsers):
|
| 162 |
+
# GH#56044 the c tokenizer matches the default True/False spellings in any
|
| 163 |
+
# case, so its category inference does too; each engine's categories
|
| 164 |
+
# follow its own plain read
|
| 165 |
+
parser = all_parsers
|
| 166 |
+
data = "a\ntRuE\nfAlSe"
|
| 167 |
+
plain = parser.read_csv(StringIO(data))["a"]
|
| 168 |
+
if parser.engine == "c":
|
| 169 |
+
assert plain.dtype == np.dtype("bool")
|
| 170 |
+
|
| 171 |
+
result = parser.read_csv(StringIO(data), dtype="category")
|
| 172 |
+
expected = pd.DataFrame({"a": pd.Categorical(plain)})
|
| 173 |
+
tm.assert_frame_equal(result, expected)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def test_categorical_dtype_boolean_mixed_case_custom_values(all_parsers):
|
| 177 |
+
# GH#56044 true_values and false_values are consulted before the c
|
| 178 |
+
# tokenizer's case-insensitive comparison, so a case variant spelled out
|
| 179 |
+
# there wins over the meaning the default spellings would give it
|
| 180 |
+
parser = all_parsers
|
| 181 |
+
data = "a\ntRuE\nFalse"
|
| 182 |
+
plain = parser.read_csv(StringIO(data), false_values=["tRuE"])["a"]
|
| 183 |
+
if parser.engine == "c":
|
| 184 |
+
assert list(plain) == [False, False]
|
| 185 |
+
|
| 186 |
+
result = parser.read_csv(StringIO(data), dtype="category", false_values=["tRuE"])
|
| 187 |
+
expected = pd.DataFrame({"a": pd.Categorical(plain)})
|
| 188 |
+
tm.assert_frame_equal(result, expected)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_categorical_dtype_boolean_custom_values(all_parsers):
|
| 192 |
+
# GH#56044 true_values/false_values are honored when inferring bool
|
| 193 |
+
# categories
|
| 194 |
+
parser = all_parsers
|
| 195 |
+
data = "a\nyes\nno\nyes"
|
| 196 |
+
expected = pd.DataFrame({"a": pd.Categorical([True, False, True])})
|
| 197 |
+
actual = parser.read_csv(
|
| 198 |
+
StringIO(data), dtype="category", true_values=["yes"], false_values=["no"]
|
| 199 |
+
)
|
| 200 |
+
tm.assert_frame_equal(actual, expected)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@xfail_pyarrow # ValueError: The 'thousands' option is not supported
|
| 204 |
+
def test_categorical_dtype_thousands(all_parsers):
|
| 205 |
+
# GH#56044 numeric inference is unaware of the thousands option,
|
| 206 |
+
# so categories stay strings rather than mis-parsing "1.000" as 1.0
|
| 207 |
+
parser = all_parsers
|
| 208 |
+
data = "a\n1.000\n2.000"
|
| 209 |
+
expected = pd.DataFrame({"a": pd.Categorical(["1.000", "2.000"])})
|
| 210 |
+
actual = parser.read_csv(StringIO(data), dtype="category", thousands=".")
|
| 211 |
+
tm.assert_frame_equal(actual, expected)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@xfail_pyarrow # pyarrow parses with decimal_point and infers numeric
|
| 215 |
+
def test_categorical_dtype_decimal(all_parsers):
|
| 216 |
+
# GH#56044 numeric inference is unaware of the decimal option,
|
| 217 |
+
# so categories stay strings rather than mis-parsing "1,5"
|
| 218 |
+
parser = all_parsers
|
| 219 |
+
data = "a;b\n1;1,5\n2;2,5"
|
| 220 |
+
expected = pd.DataFrame(
|
| 221 |
+
{"a": pd.Categorical(["1", "2"]), "b": pd.Categorical(["1,5", "2,5"])}
|
| 222 |
+
)
|
| 223 |
+
actual = parser.read_csv(StringIO(data), dtype="category", sep=";", decimal=",")
|
| 224 |
+
tm.assert_frame_equal(actual, expected)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
@xfail_pyarrow # pyarrow casts to float64, losing precision
|
| 228 |
+
@pytest.mark.parametrize(
|
| 229 |
+
"huge",
|
| 230 |
+
[
|
| 231 |
+
99999999999999999999999999,
|
| 232 |
+
# beyond the float64 range, which the inference used to choke on
|
| 233 |
+
# depending on where the value appeared in the column (GH#66519)
|
| 234 |
+
int("1" * 400),
|
| 235 |
+
],
|
| 236 |
+
)
|
| 237 |
+
def test_categorical_dtype_large_integers(all_parsers, huge):
|
| 238 |
+
# GH#56044 integers too large for int64/uint64 give object categories
|
| 239 |
+
parser = all_parsers
|
| 240 |
+
expected = pd.DataFrame({"a": pd.Categorical([huge, 1])})
|
| 241 |
+
actual = parser.read_csv(StringIO(f"a\n{huge}\n1"), dtype="category")
|
| 242 |
+
tm.assert_frame_equal(actual, expected)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@pytest.mark.parametrize(
|
| 246 |
+
"data, categories",
|
| 247 |
+
[
|
| 248 |
+
("a\n2\n1", [1, 2]),
|
| 249 |
+
("a\ny\nx", ["x", "y"]),
|
| 250 |
+
("a\nTrue\nFalse", [False, True]),
|
| 251 |
+
],
|
| 252 |
+
)
|
| 253 |
+
def test_categorical_dtype_ordered_inferred_categories(all_parsers, data, categories):
|
| 254 |
+
# GH#56044 ordered is honored when the CategoricalDtype leaves the
|
| 255 |
+
# categories to be inferred
|
| 256 |
+
parser = all_parsers
|
| 257 |
+
cat_dtype = CategoricalDtype(ordered=True)
|
| 258 |
+
expected = pd.DataFrame(
|
| 259 |
+
{"a": pd.Categorical(categories[::-1], categories=categories, ordered=True)}
|
| 260 |
+
)
|
| 261 |
+
actual = parser.read_csv(StringIO(data), dtype={"a": cat_dtype})
|
| 262 |
+
tm.assert_frame_equal(actual, expected)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@pytest.mark.parametrize(
|
| 266 |
+
"values",
|
| 267 |
+
[
|
| 268 |
+
list(reversed(range(60))),
|
| 269 |
+
[f"s{i:02d}" for i in reversed(range(60))],
|
| 270 |
+
],
|
| 271 |
+
)
|
| 272 |
+
def test_categorical_dtype_ordered_low_memory(all_parsers, monkeypatch, values):
|
| 273 |
+
# GH#56044 as above, through the deferred low-memory path. ordered is
|
| 274 |
+
# applied after concatenation because union_categoricals rejects ordered
|
| 275 |
+
# inputs whose categories differ.
|
| 276 |
+
parser = all_parsers
|
| 277 |
+
heuristic = 2**5
|
| 278 |
+
data = "a\n" + "\n".join(str(val) for val in values)
|
| 279 |
+
cat_dtype = CategoricalDtype(ordered=True)
|
| 280 |
+
expected = pd.DataFrame(
|
| 281 |
+
{"a": pd.Categorical(values, categories=sorted(values), ordered=True)}
|
| 282 |
+
)
|
| 283 |
+
with monkeypatch.context() as m:
|
| 284 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", heuristic)
|
| 285 |
+
actual = parser.read_csv(StringIO(data), dtype={"a": cat_dtype})
|
| 286 |
+
tm.assert_frame_equal(actual, expected)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def test_categorical_dtype_explicit_integer_ea_categories(all_parsers):
|
| 290 |
+
# GH#56136 explicitly-requested IntegerDtype categories are preserved
|
| 291 |
+
parser = all_parsers
|
| 292 |
+
cat_dtype = CategoricalDtype(pd.array([1, 2], dtype="Int64"))
|
| 293 |
+
data = "a\n1\n2\n1"
|
| 294 |
+
expected = pd.DataFrame(
|
| 295 |
+
{"a": pd.Categorical.from_codes([0, 1, 0], dtype=cat_dtype)}
|
| 296 |
+
)
|
| 297 |
+
actual = parser.read_csv(StringIO(data), dtype={"a": cat_dtype})
|
| 298 |
+
tm.assert_frame_equal(actual, expected)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def test_categorical_dtype_non_default_dtype_backend(all_parsers, dtype_backend):
|
| 302 |
+
# GH#56044 categories are inferred, but the c and python engines do not yet
|
| 303 |
+
# honor dtype_backend and give numpy categories where a non-categorical
|
| 304 |
+
# read would give Int64/int64[pyarrow]; pin the current behavior, see
|
| 305 |
+
# GH#66382
|
| 306 |
+
parser = all_parsers
|
| 307 |
+
data = "a\n1\n2"
|
| 308 |
+
result = parser.read_csv(
|
| 309 |
+
StringIO(data), dtype="category", dtype_backend=dtype_backend
|
| 310 |
+
)
|
| 311 |
+
cat_dtype = result["a"].cat.categories.dtype
|
| 312 |
+
if parser.engine == "pyarrow" and dtype_backend == "numpy_nullable":
|
| 313 |
+
assert cat_dtype == pd.Int64Dtype()
|
| 314 |
+
elif dtype_backend == "pyarrow" and parser.engine in ("pyarrow", "python"):
|
| 315 |
+
# the python parser's arrow-backed strings convert straight to arrow
|
| 316 |
+
pyarrow = pytest.importorskip("pyarrow")
|
| 317 |
+
assert cat_dtype == pd.ArrowDtype(pyarrow.int64())
|
| 318 |
+
else:
|
| 319 |
+
assert cat_dtype == np.dtype("int64")
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def test_categorical_dtype_non_default_dtype_backend_bool(all_parsers, dtype_backend):
|
| 323 |
+
# GH#56044 same divergence as the numeric case above for boolean
|
| 324 |
+
# categories, see GH#66382
|
| 325 |
+
parser = all_parsers
|
| 326 |
+
data = "a\nTrue\nFalse"
|
| 327 |
+
result = parser.read_csv(
|
| 328 |
+
StringIO(data), dtype="category", dtype_backend=dtype_backend
|
| 329 |
+
)
|
| 330 |
+
cat_dtype = result["a"].cat.categories.dtype
|
| 331 |
+
if parser.engine == "pyarrow" and dtype_backend == "numpy_nullable":
|
| 332 |
+
assert cat_dtype == pd.BooleanDtype()
|
| 333 |
+
elif dtype_backend == "pyarrow" and parser.engine in ("pyarrow", "python"):
|
| 334 |
+
pyarrow = pytest.importorskip("pyarrow")
|
| 335 |
+
assert cat_dtype == pd.ArrowDtype(pyarrow.bool_())
|
| 336 |
+
else:
|
| 337 |
+
assert cat_dtype == np.dtype("bool")
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def test_categorical_dtype_non_default_dtype_backend_str(all_parsers, dtype_backend):
|
| 341 |
+
# GH#56044 same divergence as the numeric case above for columns that keep
|
| 342 |
+
# string categories, see GH#66382
|
| 343 |
+
parser = all_parsers
|
| 344 |
+
data = "a\nx\ny"
|
| 345 |
+
result = parser.read_csv(
|
| 346 |
+
StringIO(data), dtype="category", dtype_backend=dtype_backend
|
| 347 |
+
)
|
| 348 |
+
cat_dtype = result["a"].cat.categories.dtype
|
| 349 |
+
if dtype_backend == "pyarrow" and parser.engine in ("pyarrow", "python"):
|
| 350 |
+
pyarrow = pytest.importorskip("pyarrow")
|
| 351 |
+
assert cat_dtype == pd.ArrowDtype(pyarrow.string())
|
| 352 |
+
elif parser.engine == "pyarrow":
|
| 353 |
+
assert cat_dtype == pd.StringDtype(na_value=pd.NA)
|
| 354 |
+
elif using_string_dtype():
|
| 355 |
+
assert cat_dtype == pd.StringDtype(na_value=np.nan)
|
| 356 |
+
else:
|
| 357 |
+
assert cat_dtype == np.dtype("object")
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
| 361 |
+
@pytest.mark.filterwarnings(
|
| 362 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 363 |
+
)
|
| 364 |
+
def test_categorical_dtype_infer_string_disabled(all_parsers, ordered):
|
| 365 |
+
# GH#56044 with the string dtype disabled the categories are object dtype,
|
| 366 |
+
# including for an ordered dtype, where CategoricalDtype.__eq__ ignores
|
| 367 |
+
# the categories' dtype
|
| 368 |
+
parser = all_parsers
|
| 369 |
+
data = "a\ny\nx"
|
| 370 |
+
with pd.option_context("future.infer_string", False):
|
| 371 |
+
result = parser.read_csv(
|
| 372 |
+
StringIO(data), dtype={"a": CategoricalDtype(ordered=ordered)}
|
| 373 |
+
)
|
| 374 |
+
expected = pd.DataFrame(
|
| 375 |
+
{"a": pd.Categorical(["y", "x"], categories=["x", "y"], ordered=ordered)}
|
| 376 |
+
)
|
| 377 |
+
tm.assert_frame_equal(result, expected)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def test_categorical_dtype_chunksize_inferred_dtypes_differ(all_parsers):
|
| 381 |
+
# GH#56044 chunks infer independently, as they do without dtype="category",
|
| 382 |
+
# so a value that only appears in a later chunk does not affect the
|
| 383 |
+
# earlier ones
|
| 384 |
+
parser = all_parsers
|
| 385 |
+
data = "a\n1\n2\n3\nx"
|
| 386 |
+
|
| 387 |
+
if parser.engine == "pyarrow":
|
| 388 |
+
msg = "The 'chunksize' option is not supported with the 'pyarrow' engine"
|
| 389 |
+
with pytest.raises(ValueError, match=msg):
|
| 390 |
+
parser.read_csv(StringIO(data), dtype="category", chunksize=3)
|
| 391 |
+
return
|
| 392 |
+
|
| 393 |
+
with parser.read_csv(StringIO(data), dtype="category", chunksize=3) as chunks:
|
| 394 |
+
cat_dtypes = [chunk["a"].cat.categories.dtype for chunk in chunks]
|
| 395 |
+
|
| 396 |
+
assert cat_dtypes[0] == np.dtype("int64")
|
| 397 |
+
assert cat_dtypes[1] != np.dtype("int64")
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@xfail_pyarrow # ValueError: The 'quoting' option is not supported
|
| 401 |
+
def test_categorical_dtype_quote_nonnumeric(all_parsers):
|
| 402 |
+
# GH#56044 QUOTE_NONNUMERIC casts every unquoted field to float, so the
|
| 403 |
+
# categories match what a non-categorical read gives
|
| 404 |
+
parser = all_parsers
|
| 405 |
+
data = '"a"\n1\n2'
|
| 406 |
+
result = parser.read_csv(
|
| 407 |
+
StringIO(data), dtype="category", quoting=csv.QUOTE_NONNUMERIC
|
| 408 |
+
)
|
| 409 |
+
expected = pd.DataFrame({"a": pd.Categorical([1.0, 2.0])})
|
| 410 |
+
tm.assert_frame_equal(result, expected)
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def test_categorical_dtype_low_memory_mixed_numeric_chunks(all_parsers, monkeypatch):
|
| 414 |
+
# GH#56044 in low-memory mode chunks can disagree on the inferred category
|
| 415 |
+
# dtype (int64 until "1.5" appears, then float64), which used to break
|
| 416 |
+
# union_categoricals; inference now happens after concatenation
|
| 417 |
+
parser = all_parsers
|
| 418 |
+
heuristic = 2**5
|
| 419 |
+
ints = [str(i) for i in range(40)]
|
| 420 |
+
rows = [*ints, "1.5", *ints]
|
| 421 |
+
expected = pd.DataFrame({"a": pd.Categorical([float(x) for x in rows])})
|
| 422 |
+
with monkeypatch.context() as m:
|
| 423 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", heuristic)
|
| 424 |
+
actual = parser.read_csv(StringIO("a\n" + "\n".join(rows)), dtype="category")
|
| 425 |
+
tm.assert_frame_equal(actual, expected)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def test_categorical_dtype_low_memory_all_na_chunk(all_parsers, monkeypatch):
|
| 429 |
+
# GH#56044 a chunk that is entirely NA infers no categories; it must not
|
| 430 |
+
# break the union against the chunks that did infer some
|
| 431 |
+
parser = all_parsers
|
| 432 |
+
heuristic = 2**5
|
| 433 |
+
rows = [",1"] * 40 + ["x,1"] * 40
|
| 434 |
+
expected = pd.DataFrame(
|
| 435 |
+
{
|
| 436 |
+
"a": pd.Categorical([None] * 40 + ["x"] * 40),
|
| 437 |
+
"b": pd.Categorical([1] * 80),
|
| 438 |
+
}
|
| 439 |
+
)
|
| 440 |
+
with monkeypatch.context() as m:
|
| 441 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", heuristic)
|
| 442 |
+
actual = parser.read_csv(StringIO("a,b\n" + "\n".join(rows)), dtype="category")
|
| 443 |
+
tm.assert_frame_equal(actual, expected)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
@pytest.mark.parametrize(
|
| 447 |
+
"rows,values",
|
| 448 |
+
[
|
| 449 |
+
(
|
| 450 |
+
[*(str(i) for i in range(40)), *(f"{i}.0" for i in range(40))],
|
| 451 |
+
[*(float(i) for i in range(40))] * 2,
|
| 452 |
+
),
|
| 453 |
+
(
|
| 454 |
+
[*["True"] * 25, *["TRUE"] * 25, *["False"] * 25],
|
| 455 |
+
[*[True] * 50, *[False] * 25],
|
| 456 |
+
),
|
| 457 |
+
# NA rows so the merge recodes alongside -1 codes
|
| 458 |
+
(
|
| 459 |
+
[*(row for i in range(40) for row in (str(i), f"{i}.0", "nan"))],
|
| 460 |
+
[*(val for i in range(40) for val in (float(i), float(i), None))],
|
| 461 |
+
),
|
| 462 |
+
],
|
| 463 |
+
)
|
| 464 |
+
def test_categorical_dtype_low_memory_duplicate_chunks(
|
| 465 |
+
all_parsers, monkeypatch, rows, values
|
| 466 |
+
):
|
| 467 |
+
# GH#56044 distinct strings that convert to the same value must merge into
|
| 468 |
+
# one category with recoded codes, even when union_categoricals collected
|
| 469 |
+
# them across chunks in file order
|
| 470 |
+
parser = all_parsers
|
| 471 |
+
heuristic = 2**5
|
| 472 |
+
expected = pd.DataFrame({"a": pd.Categorical(values)})
|
| 473 |
+
with monkeypatch.context() as m:
|
| 474 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", heuristic)
|
| 475 |
+
actual = parser.read_csv(StringIO("a\n" + "\n".join(rows)), dtype="category")
|
| 476 |
+
tm.assert_frame_equal(actual, expected)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
@pytest.mark.parametrize(
|
| 480 |
+
"rows",
|
| 481 |
+
[
|
| 482 |
+
[*(str(i) for i in range(40)), "apple", *(str(i) for i in range(40))],
|
| 483 |
+
[*["True", "False"] * 20, "maybe", *["True", "False"] * 20],
|
| 484 |
+
[*["True", "False"] * 20, "3", *["True", "False"] * 20],
|
| 485 |
+
],
|
| 486 |
+
)
|
| 487 |
+
def test_categorical_dtype_low_memory_mixed_type_chunks(all_parsers, monkeypatch, rows):
|
| 488 |
+
# GH#56044 a chunk whose values do not all parse as numeric or boolean
|
| 489 |
+
# keeps every chunk's categories strings
|
| 490 |
+
parser = all_parsers
|
| 491 |
+
heuristic = 2**5
|
| 492 |
+
expected = pd.DataFrame({"a": pd.Categorical(rows)})
|
| 493 |
+
with monkeypatch.context() as m:
|
| 494 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", heuristic)
|
| 495 |
+
actual = parser.read_csv(StringIO("a\n" + "\n".join(rows)), dtype="category")
|
| 496 |
+
tm.assert_frame_equal(actual, expected)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def test_categorical_dtype_low_memory_sorts_string_categories(all_parsers, monkeypatch):
|
| 500 |
+
# GH#56044 union_categoricals leaves categories in chunk order; they are
|
| 501 |
+
# sorted afterwards so low_memory=True agrees with low_memory=False
|
| 502 |
+
parser = all_parsers
|
| 503 |
+
heuristic = 2**5
|
| 504 |
+
rows = [f"s{i:02d}" for i in reversed(range(60))]
|
| 505 |
+
data = "a\n" + "\n".join(rows)
|
| 506 |
+
expected = pd.DataFrame({"a": pd.Categorical(rows)})
|
| 507 |
+
with monkeypatch.context() as m:
|
| 508 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", heuristic)
|
| 509 |
+
actual = parser.read_csv(StringIO(data), dtype="category")
|
| 510 |
+
assert actual["a"].cat.categories.is_monotonic_increasing
|
| 511 |
+
tm.assert_frame_equal(actual, expected)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def test_categorical_dtype_integer_with_missing(all_parsers):
|
| 515 |
+
# GH#56044 the codes already carry the missing values, so the categories
|
| 516 |
+
# stay int64 where a non-categorical read gives float64
|
| 517 |
+
parser = all_parsers
|
| 518 |
+
data = "a,b\n1,x\n,x\n2,x"
|
| 519 |
+
expected = pd.DataFrame(
|
| 520 |
+
{"a": pd.Categorical([1, None, 2]), "b": pd.Categorical(["x", "x", "x"])}
|
| 521 |
+
)
|
| 522 |
+
result = parser.read_csv(StringIO(data), dtype="category")
|
| 523 |
+
tm.assert_frame_equal(result, expected)
|
| 524 |
+
assert result["a"].cat.categories.dtype == np.dtype("int64")
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def test_categorical_dtype_boolean_with_missing(all_parsers):
|
| 528 |
+
# GH#56044 as above for booleans, where a non-categorical read gives object
|
| 529 |
+
parser = all_parsers
|
| 530 |
+
data = "a,b\nTrue,x\n,x\nFalse,x"
|
| 531 |
+
expected = pd.DataFrame(
|
| 532 |
+
{
|
| 533 |
+
"a": pd.Categorical([True, None, False]),
|
| 534 |
+
"b": pd.Categorical(["x", "x", "x"]),
|
| 535 |
+
}
|
| 536 |
+
)
|
| 537 |
+
result = parser.read_csv(StringIO(data), dtype="category")
|
| 538 |
+
tm.assert_frame_equal(result, expected)
|
| 539 |
+
assert result["a"].cat.categories.dtype == np.dtype("bool")
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
@xfail_pyarrow # ValueError: The 'quoting' option is not supported
|
| 543 |
+
def test_categorical_dtype_quote_nonnumeric_large_integers(all_parsers):
|
| 544 |
+
# GH#56044 QUOTE_NONNUMERIC converts integers too large for int64/uint64
|
| 545 |
+
# from their strings, since they arrive as Python ints that cannot be
|
| 546 |
+
# cast to float64 directly
|
| 547 |
+
parser = all_parsers
|
| 548 |
+
data = '"a"\n99999999999999999999999999\n1'
|
| 549 |
+
expected = pd.DataFrame({"a": pd.Categorical([1e26, 1.0])})
|
| 550 |
+
result = parser.read_csv(
|
| 551 |
+
StringIO(data), dtype="category", quoting=csv.QUOTE_NONNUMERIC
|
| 552 |
+
)
|
| 553 |
+
tm.assert_frame_equal(result, expected)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def test_categorical_dtype_empty_string_dtype_backend(all_parsers, dtype_backend):
|
| 557 |
+
# GH#56044 the NaN that to_numeric makes of "" cannot be a category, so
|
| 558 |
+
# string categories are kept even when it yields a NaN value rather than
|
| 559 |
+
# a null, as it does for the arrow-backed strings the python engine
|
| 560 |
+
# produces
|
| 561 |
+
parser = all_parsers
|
| 562 |
+
data = "a,b\n,1\n2,3"
|
| 563 |
+
result = parser.read_csv(
|
| 564 |
+
StringIO(data),
|
| 565 |
+
dtype="category",
|
| 566 |
+
keep_default_na=False,
|
| 567 |
+
dtype_backend=dtype_backend,
|
| 568 |
+
)
|
| 569 |
+
assert list(result["a"].cat.categories) == ["", "2"]
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
@pytest.mark.parametrize("kwargs", [{"na_filter": False}, {"keep_default_na": False}])
|
| 573 |
+
def test_categorical_dtype_empty_string(all_parsers, kwargs, request):
|
| 574 |
+
# GH#56044 to_numeric converts "" to NaN, which cannot be a category;
|
| 575 |
+
# keep string categories
|
| 576 |
+
parser = all_parsers
|
| 577 |
+
if parser.engine == "pyarrow" and "na_filter" in kwargs:
|
| 578 |
+
mark = pytest.mark.xfail(
|
| 579 |
+
reason="pyarrow treats '' as null regardless of na_filter",
|
| 580 |
+
)
|
| 581 |
+
request.applymarker(mark)
|
| 582 |
+
|
| 583 |
+
data = "a,b\n,1\n2,3"
|
| 584 |
+
expected = pd.DataFrame(
|
| 585 |
+
{"a": pd.Categorical(["", "2"]), "b": pd.Categorical([1, 3])}
|
| 586 |
+
)
|
| 587 |
+
actual = parser.read_csv(StringIO(data), dtype="category", **kwargs)
|
| 588 |
+
tm.assert_frame_equal(actual, expected)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
@xfail_pyarrow # pyarrow gives float64 categories for all-NA columns
|
| 592 |
+
def test_categorical_dtype_all_na(all_parsers):
|
| 593 |
+
# GH#56044 empty inferred categories keep object dtype
|
| 594 |
+
parser = all_parsers
|
| 595 |
+
data = "a,b\n,1\n,2"
|
| 596 |
+
expected = pd.DataFrame(
|
| 597 |
+
{
|
| 598 |
+
"a": pd.Categorical.from_codes([-1, -1], pd.Index([], dtype=object)),
|
| 599 |
+
"b": pd.Categorical([1, 2]),
|
| 600 |
+
}
|
| 601 |
+
)
|
| 602 |
+
actual = parser.read_csv(StringIO(data), dtype="category")
|
| 603 |
+
tm.assert_frame_equal(actual, expected)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
@pytest.mark.slow
|
| 607 |
+
def test_categorical_dtype_high_cardinality_numeric(all_parsers, monkeypatch):
|
| 608 |
+
# see gh-18186, gh-56044
|
| 609 |
+
# was an issue with C parser, due to DEFAULT_BUFFER_HEURISTIC
|
| 610 |
+
parser = all_parsers
|
| 611 |
+
heuristic = 2**5
|
| 612 |
+
data = np.sort([str(i) for i in range(heuristic + 1)])
|
| 613 |
+
csv_data = "a\n" + "\n".join(data)
|
| 614 |
+
int_data = np.array([int(x) for x in data])
|
| 615 |
+
expected = pd.DataFrame({"a": pd.Categorical(int_data)})
|
| 616 |
+
with monkeypatch.context() as m:
|
| 617 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", heuristic)
|
| 618 |
+
actual = parser.read_csv(StringIO(csv_data), dtype="category")
|
| 619 |
+
tm.assert_frame_equal(actual, expected)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def test_categorical_dtype_utf16(all_parsers, datapath):
|
| 623 |
+
# see gh-10153
|
| 624 |
+
pth = datapath("io", "parser", "data", "utf16_ex.txt")
|
| 625 |
+
parser = all_parsers
|
| 626 |
+
encoding = "utf-16"
|
| 627 |
+
sep = "\t"
|
| 628 |
+
|
| 629 |
+
expected = parser.read_csv(pth, sep=sep, encoding=encoding)
|
| 630 |
+
expected = expected.apply(pd.Categorical)
|
| 631 |
+
|
| 632 |
+
actual = parser.read_csv(pth, sep=sep, encoding=encoding, dtype="category")
|
| 633 |
+
tm.assert_frame_equal(actual, expected)
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
def test_categorical_dtype_chunksize_infer_categories(all_parsers):
|
| 637 |
+
# see gh-10153
|
| 638 |
+
parser = all_parsers
|
| 639 |
+
data = """a,b
|
| 640 |
+
1,a
|
| 641 |
+
1,b
|
| 642 |
+
1,b
|
| 643 |
+
2,c"""
|
| 644 |
+
expecteds = [
|
| 645 |
+
pd.DataFrame({"a": [1, 1], "b": pd.Categorical(["a", "b"])}),
|
| 646 |
+
pd.DataFrame({"a": [1, 2], "b": pd.Categorical(["b", "c"])}, index=[2, 3]),
|
| 647 |
+
]
|
| 648 |
+
|
| 649 |
+
if parser.engine == "pyarrow":
|
| 650 |
+
msg = "The 'chunksize' option is not supported with the 'pyarrow' engine"
|
| 651 |
+
with pytest.raises(ValueError, match=msg):
|
| 652 |
+
parser.read_csv(StringIO(data), dtype={"b": "category"}, chunksize=2)
|
| 653 |
+
return
|
| 654 |
+
|
| 655 |
+
with parser.read_csv(
|
| 656 |
+
StringIO(data), dtype={"b": "category"}, chunksize=2
|
| 657 |
+
) as actuals:
|
| 658 |
+
for actual, expected in zip(actuals, expecteds, strict=True):
|
| 659 |
+
tm.assert_frame_equal(actual, expected)
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def test_categorical_dtype_chunksize_explicit_categories(all_parsers):
|
| 663 |
+
# see gh-10153
|
| 664 |
+
parser = all_parsers
|
| 665 |
+
data = """a,b
|
| 666 |
+
1,a
|
| 667 |
+
1,b
|
| 668 |
+
1,b
|
| 669 |
+
2,c"""
|
| 670 |
+
cats = ["a", "b", "c"]
|
| 671 |
+
expecteds = [
|
| 672 |
+
pd.DataFrame({"a": [1, 1], "b": pd.Categorical(["a", "b"], categories=cats)}),
|
| 673 |
+
pd.DataFrame(
|
| 674 |
+
{"a": [1, 2], "b": pd.Categorical(["b", "c"], categories=cats)},
|
| 675 |
+
index=[2, 3],
|
| 676 |
+
),
|
| 677 |
+
]
|
| 678 |
+
dtype = CategoricalDtype(cats)
|
| 679 |
+
|
| 680 |
+
if parser.engine == "pyarrow":
|
| 681 |
+
msg = "The 'chunksize' option is not supported with the 'pyarrow' engine"
|
| 682 |
+
with pytest.raises(ValueError, match=msg):
|
| 683 |
+
parser.read_csv(StringIO(data), dtype={"b": dtype}, chunksize=2)
|
| 684 |
+
return
|
| 685 |
+
|
| 686 |
+
with parser.read_csv(StringIO(data), dtype={"b": dtype}, chunksize=2) as actuals:
|
| 687 |
+
for actual, expected in zip(actuals, expecteds, strict=True):
|
| 688 |
+
tm.assert_frame_equal(actual, expected)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def test_categorical_dtype_latin1(all_parsers, datapath):
|
| 692 |
+
# see gh-10153
|
| 693 |
+
pth = datapath("io", "parser", "data", "unicode_series.csv")
|
| 694 |
+
parser = all_parsers
|
| 695 |
+
encoding = "latin-1"
|
| 696 |
+
|
| 697 |
+
expected = parser.read_csv(pth, header=None, encoding=encoding)
|
| 698 |
+
expected[1] = pd.Categorical(expected[1])
|
| 699 |
+
|
| 700 |
+
actual = parser.read_csv(pth, header=None, encoding=encoding, dtype={1: "category"})
|
| 701 |
+
tm.assert_frame_equal(actual, expected)
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
@pytest.mark.parametrize("ordered", [False, True])
|
| 705 |
+
@pytest.mark.parametrize(
|
| 706 |
+
"categories",
|
| 707 |
+
[["a", "b", "c"], ["a", "c", "b"], ["a", "b", "c", "d"], ["c", "b", "a"]],
|
| 708 |
+
)
|
| 709 |
+
def test_categorical_category_dtype(all_parsers, categories, ordered):
|
| 710 |
+
parser = all_parsers
|
| 711 |
+
data = """a,b
|
| 712 |
+
1,a
|
| 713 |
+
1,b
|
| 714 |
+
1,b
|
| 715 |
+
2,c"""
|
| 716 |
+
expected = pd.DataFrame(
|
| 717 |
+
{
|
| 718 |
+
"a": [1, 1, 1, 2],
|
| 719 |
+
"b": pd.Categorical(
|
| 720 |
+
["a", "b", "b", "c"], categories=categories, ordered=ordered
|
| 721 |
+
),
|
| 722 |
+
}
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
dtype = {"b": CategoricalDtype(categories=categories, ordered=ordered)}
|
| 726 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 727 |
+
tm.assert_frame_equal(result, expected)
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
def test_categorical_category_dtype_unsorted(all_parsers):
|
| 731 |
+
parser = all_parsers
|
| 732 |
+
data = """a,b
|
| 733 |
+
1,a
|
| 734 |
+
1,b
|
| 735 |
+
1,b
|
| 736 |
+
2,c"""
|
| 737 |
+
dtype = CategoricalDtype(["c", "b", "a"])
|
| 738 |
+
expected = pd.DataFrame(
|
| 739 |
+
{
|
| 740 |
+
"a": [1, 1, 1, 2],
|
| 741 |
+
"b": pd.Categorical(["a", "b", "b", "c"], categories=["c", "b", "a"]),
|
| 742 |
+
}
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
result = parser.read_csv(StringIO(data), dtype={"b": dtype})
|
| 746 |
+
tm.assert_frame_equal(result, expected)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def test_categorical_coerces_numeric(all_parsers):
|
| 750 |
+
parser = all_parsers
|
| 751 |
+
dtype = {"b": CategoricalDtype([1, 2, 3])}
|
| 752 |
+
|
| 753 |
+
data = "b\n1\n1\n2\n3"
|
| 754 |
+
expected = pd.DataFrame({"b": pd.Categorical([1, 1, 2, 3])})
|
| 755 |
+
|
| 756 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 757 |
+
tm.assert_frame_equal(result, expected)
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
def test_categorical_coerces_datetime(all_parsers):
|
| 761 |
+
parser = all_parsers
|
| 762 |
+
dti = pd.DatetimeIndex(["2017-01-01", "2018-01-01", "2019-01-01"], freq=None)
|
| 763 |
+
dtype = {"b": CategoricalDtype(dti)}
|
| 764 |
+
|
| 765 |
+
data = "b\n2017-01-01\n2018-01-01\n2019-01-01"
|
| 766 |
+
expected = pd.DataFrame({"b": pd.Categorical(dtype["b"].categories)})
|
| 767 |
+
|
| 768 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 769 |
+
tm.assert_frame_equal(result, expected)
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
def test_categorical_coerces_timestamp(all_parsers):
|
| 773 |
+
parser = all_parsers
|
| 774 |
+
dtype = {"b": CategoricalDtype([pd.Timestamp("2014")])}
|
| 775 |
+
|
| 776 |
+
data = "b\n2014-01-01\n2014-01-01"
|
| 777 |
+
expected = pd.DataFrame({"b": pd.Categorical([pd.Timestamp("2014")] * 2)})
|
| 778 |
+
|
| 779 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 780 |
+
tm.assert_frame_equal(result, expected)
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
def test_categorical_coerces_timedelta(all_parsers):
|
| 784 |
+
parser = all_parsers
|
| 785 |
+
dtype = {"b": CategoricalDtype(pd.to_timedelta(["1h", "2h", "3h"]))}
|
| 786 |
+
|
| 787 |
+
data = "b\n1h\n2h\n3h"
|
| 788 |
+
expected = pd.DataFrame({"b": pd.Categorical(dtype["b"].categories)})
|
| 789 |
+
|
| 790 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 791 |
+
tm.assert_frame_equal(result, expected)
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
@pytest.mark.parametrize(
|
| 795 |
+
"data",
|
| 796 |
+
[
|
| 797 |
+
"b\nTrue\nFalse\nNA\nFalse",
|
| 798 |
+
"b\ntrue\nfalse\nNA\nfalse",
|
| 799 |
+
"b\nTRUE\nFALSE\nNA\nFALSE",
|
| 800 |
+
"b\nTrue\nFalse\nNA\nFALSE",
|
| 801 |
+
],
|
| 802 |
+
)
|
| 803 |
+
def test_categorical_dtype_coerces_boolean(all_parsers, data):
|
| 804 |
+
# see gh-20498
|
| 805 |
+
parser = all_parsers
|
| 806 |
+
dtype = {"b": CategoricalDtype([False, True])}
|
| 807 |
+
expected = pd.DataFrame({"b": pd.Categorical([True, False, None, False])})
|
| 808 |
+
|
| 809 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 810 |
+
tm.assert_frame_equal(result, expected)
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
def test_categorical_unexpected_categories(all_parsers):
|
| 814 |
+
parser = all_parsers
|
| 815 |
+
dtype = {"b": CategoricalDtype(["a", "b", "d", "e"])}
|
| 816 |
+
|
| 817 |
+
data = "b\nd\na\nc\nd" # Unexpected c
|
| 818 |
+
expected = pd.DataFrame(
|
| 819 |
+
{"b": pd.Categorical(["d", "a", None, "d"], dtype=dtype["b"])}
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
msg = "Constructing a Categorical with a dtype and values containing"
|
| 823 |
+
with tm.assert_produces_warning(Pandas4Warning, match=msg, check_stacklevel=False):
|
| 824 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 825 |
+
tm.assert_frame_equal(result, expected)
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
def test_categorical_dtype_leading_zeros(all_parsers):
|
| 829 |
+
# GH#56044 the categories are inferred like any other column, so the
|
| 830 |
+
# leading zeros are lost just as they are without dtype="category"
|
| 831 |
+
parser = all_parsers
|
| 832 |
+
data = """a,b
|
| 833 |
+
01,x
|
| 834 |
+
002,y"""
|
| 835 |
+
result = parser.read_csv(StringIO(data), dtype={"a": "category"})
|
| 836 |
+
expected = pd.DataFrame({"a": pd.Categorical([1, 2]), "b": ["x", "y"]})
|
| 837 |
+
tm.assert_frame_equal(result, expected)
|
| 838 |
+
# to keep the raw strings, ask for them
|
| 839 |
+
result = parser.read_csv(StringIO(data), dtype={"a": "str"}).astype(
|
| 840 |
+
{"a": "category"}
|
| 841 |
+
)
|
| 842 |
+
expected = pd.DataFrame({"a": pd.Categorical(["01", "002"]), "b": ["x", "y"]})
|
| 843 |
+
tm.assert_frame_equal(result, expected)
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def test_categorical_dtype_explicit_string_categories(all_parsers):
|
| 847 |
+
# GH#57666 explicitly typed string categories match against the raw
|
| 848 |
+
# text, not against inferred values
|
| 849 |
+
parser = all_parsers
|
| 850 |
+
dtype = CategoricalDtype(["01", "002"])
|
| 851 |
+
data = """a
|
| 852 |
+
01
|
| 853 |
+
002
|
| 854 |
+
01"""
|
| 855 |
+
result = parser.read_csv(StringIO(data), dtype={"a": dtype})
|
| 856 |
+
expected = pd.DataFrame(
|
| 857 |
+
{"a": pd.Categorical(["01", "002", "01"], categories=["01", "002"])}
|
| 858 |
+
)
|
| 859 |
+
tm.assert_frame_equal(result, expected)
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
def test_categorical_dtype_explicit_numeric_categories(all_parsers):
|
| 863 |
+
# GH#57666 explicitly typed numeric categories keep matching the
|
| 864 |
+
# parsed numeric values
|
| 865 |
+
parser = all_parsers
|
| 866 |
+
dtype = CategoricalDtype([1, 2, 3])
|
| 867 |
+
data = """a
|
| 868 |
+
1
|
| 869 |
+
2
|
| 870 |
+
3"""
|
| 871 |
+
result = parser.read_csv(StringIO(data), dtype={"a": dtype})
|
| 872 |
+
expected = pd.DataFrame({"a": pd.Categorical([1, 2, 3], categories=[1, 2, 3])})
|
| 873 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
ADDED
|
@@ -0,0 +1,1037 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests dtype specification during parsing
|
| 3 |
+
for all of the parsers defined in parsers.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from io import StringIO
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from pandas._libs import lib
|
| 13 |
+
from pandas.compat.pyarrow import pa_version_under25p0
|
| 14 |
+
from pandas.errors import (
|
| 15 |
+
EmptyDataError,
|
| 16 |
+
Pandas4Warning,
|
| 17 |
+
ParserWarning,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
import pandas._testing as tm
|
| 22 |
+
from pandas.core.arrays import IntegerArray
|
| 23 |
+
|
| 24 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@pytest.mark.parametrize("dtype", [str, object])
|
| 28 |
+
@pytest.mark.parametrize("check_orig", [True, False])
|
| 29 |
+
def test_dtype_all_columns(
|
| 30 |
+
all_parsers, dtype, check_orig, using_infer_string, temp_file, request
|
| 31 |
+
):
|
| 32 |
+
# see gh-3795, gh-6607
|
| 33 |
+
parser = all_parsers
|
| 34 |
+
|
| 35 |
+
if (
|
| 36 |
+
parser.engine == "pyarrow"
|
| 37 |
+
and dtype is object
|
| 38 |
+
and not check_orig
|
| 39 |
+
and pa_version_under25p0
|
| 40 |
+
):
|
| 41 |
+
# GH#58260 without pyarrow>=25.0 (ConvertOptions.default_column_type)
|
| 42 |
+
# the pyarrow engine cannot disable type inference, so a scalar
|
| 43 |
+
# object dtype yields the inferred (e.g. float) values rather than the
|
| 44 |
+
# raw strings the other engines preserve
|
| 45 |
+
request.applymarker(
|
| 46 |
+
pytest.mark.xfail(reason="Cannot disable type-inference for pyarrow engine")
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
df = pd.DataFrame(
|
| 50 |
+
np.random.default_rng(2).random((5, 2)).round(4),
|
| 51 |
+
columns=list("AB"),
|
| 52 |
+
index=["1A", "1B", "1C", "1D", "1E"],
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
df.to_csv(temp_file)
|
| 56 |
+
|
| 57 |
+
result = parser.read_csv(temp_file, dtype=dtype, index_col=0)
|
| 58 |
+
|
| 59 |
+
if check_orig:
|
| 60 |
+
expected = df.copy()
|
| 61 |
+
result = result.astype(float)
|
| 62 |
+
elif using_infer_string and dtype is str:
|
| 63 |
+
expected = df.astype(str)
|
| 64 |
+
else:
|
| 65 |
+
expected = df.astype(str).astype(object)
|
| 66 |
+
|
| 67 |
+
tm.assert_frame_equal(result, expected)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@pytest.mark.usefixtures("pyarrow_xfail")
|
| 71 |
+
def test_dtype_per_column(all_parsers):
|
| 72 |
+
parser = all_parsers
|
| 73 |
+
data = """\
|
| 74 |
+
one,two
|
| 75 |
+
1,2.5
|
| 76 |
+
2,3.5
|
| 77 |
+
3,4.5
|
| 78 |
+
4,5.5"""
|
| 79 |
+
expected = pd.DataFrame(
|
| 80 |
+
[[1, "2.5"], [2, "3.5"], [3, "4.5"], [4, "5.5"]], columns=["one", "two"]
|
| 81 |
+
)
|
| 82 |
+
expected["one"] = expected["one"].astype(np.float64)
|
| 83 |
+
|
| 84 |
+
result = parser.read_csv(StringIO(data), dtype={"one": np.float64, 1: str})
|
| 85 |
+
tm.assert_frame_equal(result, expected)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_invalid_dtype_per_column(all_parsers):
|
| 89 |
+
parser = all_parsers
|
| 90 |
+
data = """\
|
| 91 |
+
one,two
|
| 92 |
+
1,2.5
|
| 93 |
+
2,3.5
|
| 94 |
+
3,4.5
|
| 95 |
+
4,5.5"""
|
| 96 |
+
|
| 97 |
+
with pytest.raises(TypeError, match="data type [\"']foo[\"'] not understood"):
|
| 98 |
+
parser.read_csv(StringIO(data), dtype={"one": "foo", 1: "int"})
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_raise_on_passed_int_dtype_with_nas(all_parsers):
|
| 102 |
+
# see gh-2631
|
| 103 |
+
parser = all_parsers
|
| 104 |
+
data = """YEAR, DOY, a
|
| 105 |
+
2001,106380451,10
|
| 106 |
+
2001,,11
|
| 107 |
+
2001,106380451,67"""
|
| 108 |
+
|
| 109 |
+
if parser.engine == "c":
|
| 110 |
+
msg = "Integer column has NA values"
|
| 111 |
+
elif parser.engine == "pyarrow":
|
| 112 |
+
msg = "The 'skipinitialspace' option is not supported with the 'pyarrow' engine"
|
| 113 |
+
else:
|
| 114 |
+
msg = "Unable to convert column DOY"
|
| 115 |
+
|
| 116 |
+
with pytest.raises(ValueError, match=msg):
|
| 117 |
+
parser.read_csv(StringIO(data), dtype={"DOY": np.int64}, skipinitialspace=True)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def test_dtype_with_converters(all_parsers):
|
| 121 |
+
parser = all_parsers
|
| 122 |
+
data = """a,b
|
| 123 |
+
1.1,2.2
|
| 124 |
+
1.2,2.3"""
|
| 125 |
+
|
| 126 |
+
if parser.engine == "pyarrow":
|
| 127 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 128 |
+
with pytest.raises(ValueError, match=msg):
|
| 129 |
+
parser.read_csv(
|
| 130 |
+
StringIO(data), dtype={"a": "i8"}, converters={"a": lambda x: str(x)}
|
| 131 |
+
)
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
# Dtype spec ignored if converted specified.
|
| 135 |
+
result = parser.read_csv_check_warnings(
|
| 136 |
+
ParserWarning,
|
| 137 |
+
"Both a converter and dtype were specified for column a "
|
| 138 |
+
"- only the converter will be used.",
|
| 139 |
+
StringIO(data),
|
| 140 |
+
dtype={"a": "i8"},
|
| 141 |
+
converters={"a": lambda x: str(x)},
|
| 142 |
+
)
|
| 143 |
+
expected = pd.DataFrame({"a": ["1.1", "1.2"], "b": [2.2, 2.3]})
|
| 144 |
+
tm.assert_frame_equal(result, expected)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_numeric_dtype(all_parsers, any_real_numpy_dtype):
|
| 148 |
+
data = "0\n1"
|
| 149 |
+
parser = all_parsers
|
| 150 |
+
expected = pd.DataFrame([0, 1], dtype=any_real_numpy_dtype)
|
| 151 |
+
|
| 152 |
+
result = parser.read_csv(StringIO(data), header=None, dtype=any_real_numpy_dtype)
|
| 153 |
+
tm.assert_frame_equal(expected, result, check_column_type=False)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@pytest.mark.parametrize("dtype", ["complex64", "complex128"])
|
| 157 |
+
@pytest.mark.parametrize(
|
| 158 |
+
"data",
|
| 159 |
+
["a\n(1+2j)\n(2+3j)\n(3+4j)\n", "a\n1+2j\n2+3j\n3+4j\n"],
|
| 160 |
+
ids=["parenthesized", "bare"],
|
| 161 |
+
)
|
| 162 |
+
def test_complex_dtype(all_parsers, data, dtype):
|
| 163 |
+
# GH#9379 round-trip support for complex columns in read_csv
|
| 164 |
+
parser = all_parsers
|
| 165 |
+
expected = pd.DataFrame({"a": [1 + 2j, 2 + 3j, 3 + 4j]}, dtype=dtype)
|
| 166 |
+
|
| 167 |
+
result = parser.read_csv(StringIO(data), dtype={"a": dtype})
|
| 168 |
+
tm.assert_frame_equal(result, expected)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def test_complex_dtype_roundtrip(all_parsers, temp_file):
|
| 172 |
+
# GH#9379 read_csv reads back what to_csv writes for complex columns
|
| 173 |
+
parser = all_parsers
|
| 174 |
+
expected = pd.DataFrame({"a": [1 + 2j, 2 + 3j, 3 + 4j]}, dtype="complex128")
|
| 175 |
+
expected.to_csv(temp_file, index=False)
|
| 176 |
+
|
| 177 |
+
result = parser.read_csv(temp_file, dtype={"a": "complex128"})
|
| 178 |
+
tm.assert_frame_equal(result, expected)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def test_complex_dtype_with_na(all_parsers):
|
| 182 |
+
# GH#9379 empty cells in complex columns become nan+0j
|
| 183 |
+
parser = all_parsers
|
| 184 |
+
data = "a,b\n(1+2j),1\n,2\n(3+4j),3\n"
|
| 185 |
+
expected = pd.DataFrame(
|
| 186 |
+
{
|
| 187 |
+
"a": np.array([1 + 2j, complex(np.nan, 0), 3 + 4j], dtype="complex128"),
|
| 188 |
+
"b": [1, 2, 3],
|
| 189 |
+
}
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
result = parser.read_csv(StringIO(data), dtype={"a": "complex128"})
|
| 193 |
+
tm.assert_frame_equal(result, expected)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@pytest.mark.usefixtures("pyarrow_xfail")
|
| 197 |
+
def test_boolean_dtype(all_parsers):
|
| 198 |
+
parser = all_parsers
|
| 199 |
+
data = "\n".join(
|
| 200 |
+
[
|
| 201 |
+
"a",
|
| 202 |
+
"True",
|
| 203 |
+
"TRUE",
|
| 204 |
+
"true",
|
| 205 |
+
"1",
|
| 206 |
+
"1.0",
|
| 207 |
+
"False",
|
| 208 |
+
"FALSE",
|
| 209 |
+
"false",
|
| 210 |
+
"0",
|
| 211 |
+
"0.0",
|
| 212 |
+
"NaN",
|
| 213 |
+
"nan",
|
| 214 |
+
"NA",
|
| 215 |
+
"null",
|
| 216 |
+
"NULL",
|
| 217 |
+
]
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
result = parser.read_csv(StringIO(data), dtype="boolean")
|
| 221 |
+
expected = pd.DataFrame(
|
| 222 |
+
{
|
| 223 |
+
"a": pd.array(
|
| 224 |
+
[
|
| 225 |
+
True,
|
| 226 |
+
True,
|
| 227 |
+
True,
|
| 228 |
+
True,
|
| 229 |
+
True,
|
| 230 |
+
False,
|
| 231 |
+
False,
|
| 232 |
+
False,
|
| 233 |
+
False,
|
| 234 |
+
False,
|
| 235 |
+
None,
|
| 236 |
+
None,
|
| 237 |
+
None,
|
| 238 |
+
None,
|
| 239 |
+
None,
|
| 240 |
+
],
|
| 241 |
+
dtype="boolean",
|
| 242 |
+
)
|
| 243 |
+
}
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
tm.assert_frame_equal(result, expected)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def test_delimiter_with_usecols_and_parse_dates(all_parsers):
|
| 250 |
+
# GH#35873
|
| 251 |
+
if all_parsers.engine == "pyarrow":
|
| 252 |
+
# pyarrow cannot parse this single-line input with these options
|
| 253 |
+
msg = "No columns to parse from file"
|
| 254 |
+
with pytest.raises(EmptyDataError, match=msg):
|
| 255 |
+
all_parsers.read_csv(
|
| 256 |
+
StringIO('"dump","-9,1","-9,1",20101010'),
|
| 257 |
+
engine="python",
|
| 258 |
+
names=["col", "col1", "col2", "col3"],
|
| 259 |
+
usecols=["col1", "col2", "col3"],
|
| 260 |
+
parse_dates=["col3"],
|
| 261 |
+
decimal=",",
|
| 262 |
+
)
|
| 263 |
+
return
|
| 264 |
+
|
| 265 |
+
result = all_parsers.read_csv(
|
| 266 |
+
StringIO('"dump","-9,1","-9,1",20101010'),
|
| 267 |
+
engine="python",
|
| 268 |
+
names=["col", "col1", "col2", "col3"],
|
| 269 |
+
usecols=["col1", "col2", "col3"],
|
| 270 |
+
parse_dates=["col3"],
|
| 271 |
+
decimal=",",
|
| 272 |
+
)
|
| 273 |
+
expected = pd.DataFrame(
|
| 274 |
+
{"col1": [-9.1], "col2": [-9.1], "col3": [pd.Timestamp("2010-10-10")]}
|
| 275 |
+
)
|
| 276 |
+
tm.assert_frame_equal(result, expected)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
@pytest.mark.parametrize("thousands", ["_", None])
|
| 280 |
+
def test_decimal_and_exponential(
|
| 281 |
+
request, python_parser_only, numeric_decimal, thousands
|
| 282 |
+
):
|
| 283 |
+
# GH#31920
|
| 284 |
+
decimal_number_check(request, python_parser_only, numeric_decimal, thousands, None)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@pytest.mark.parametrize("thousands", ["_", None])
|
| 288 |
+
@pytest.mark.parametrize("float_precision", [None, "legacy", "high", "round_trip"])
|
| 289 |
+
def test_1000_sep_decimal_float_precision(
|
| 290 |
+
request, c_parser_only, numeric_decimal, float_precision, thousands
|
| 291 |
+
):
|
| 292 |
+
# test decimal and thousand sep handling in across 'float_precision'
|
| 293 |
+
# parsers
|
| 294 |
+
decimal_number_check(
|
| 295 |
+
request, c_parser_only, numeric_decimal, thousands, float_precision
|
| 296 |
+
)
|
| 297 |
+
text, value = numeric_decimal
|
| 298 |
+
text = " " + text + " "
|
| 299 |
+
if isinstance(value, str): # the negative cases (parse as text)
|
| 300 |
+
value = " " + value + " "
|
| 301 |
+
decimal_number_check(
|
| 302 |
+
request, c_parser_only, (text, value), thousands, float_precision
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def decimal_number_check(request, parser, numeric_decimal, thousands, float_precision):
|
| 307 |
+
# GH#31920
|
| 308 |
+
value = numeric_decimal[0]
|
| 309 |
+
if thousands is None and value in ("1_,", "1_234,56", "1_234,56e0"):
|
| 310 |
+
request.applymarker(
|
| 311 |
+
pytest.mark.xfail(reason=f"thousands={thousands} and sep is in {value}")
|
| 312 |
+
)
|
| 313 |
+
warn = Pandas4Warning if float_precision is not None else None
|
| 314 |
+
with tm.assert_produces_warning(
|
| 315 |
+
warn, match="float_precision", check_stacklevel=False
|
| 316 |
+
):
|
| 317 |
+
df = parser.read_csv(
|
| 318 |
+
StringIO(value),
|
| 319 |
+
float_precision=float_precision,
|
| 320 |
+
sep="|",
|
| 321 |
+
thousands=thousands,
|
| 322 |
+
decimal=",",
|
| 323 |
+
header=None,
|
| 324 |
+
)
|
| 325 |
+
val = df.iloc[0, 0]
|
| 326 |
+
assert val == numeric_decimal[1]
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@pytest.mark.parametrize("float_precision", [None, "legacy", "high", "round_trip"])
|
| 330 |
+
def test_skip_whitespace(c_parser_only, float_precision):
|
| 331 |
+
DATA = """id\tnum\t
|
| 332 |
+
1\t1.2 \t
|
| 333 |
+
1\t 2.1\t
|
| 334 |
+
2\t 1\t
|
| 335 |
+
2\t 1.2 \t
|
| 336 |
+
"""
|
| 337 |
+
warn = Pandas4Warning if float_precision is not None else None
|
| 338 |
+
with tm.assert_produces_warning(
|
| 339 |
+
warn, match="float_precision", check_stacklevel=False
|
| 340 |
+
):
|
| 341 |
+
df = c_parser_only.read_csv(
|
| 342 |
+
StringIO(DATA),
|
| 343 |
+
float_precision=float_precision,
|
| 344 |
+
sep="\t",
|
| 345 |
+
header=0,
|
| 346 |
+
dtype={1: np.float64},
|
| 347 |
+
)
|
| 348 |
+
tm.assert_series_equal(df.iloc[:, 1], pd.Series([1.2, 2.1, 1.0, 1.2], name="num"))
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
@pytest.mark.usefixtures("pyarrow_xfail")
|
| 352 |
+
def test_true_values_cast_to_bool(all_parsers):
|
| 353 |
+
# GH#34655
|
| 354 |
+
text = """a,b
|
| 355 |
+
yes,xxx
|
| 356 |
+
no,yyy
|
| 357 |
+
1,zzz
|
| 358 |
+
0,aaa
|
| 359 |
+
"""
|
| 360 |
+
parser = all_parsers
|
| 361 |
+
result = parser.read_csv(
|
| 362 |
+
StringIO(text),
|
| 363 |
+
true_values=["yes"],
|
| 364 |
+
false_values=["no"],
|
| 365 |
+
dtype={"a": "boolean"},
|
| 366 |
+
)
|
| 367 |
+
expected = pd.DataFrame(
|
| 368 |
+
{"a": [True, False, True, False], "b": ["xxx", "yyy", "zzz", "aaa"]}
|
| 369 |
+
)
|
| 370 |
+
expected["a"] = expected["a"].astype("boolean")
|
| 371 |
+
tm.assert_frame_equal(result, expected)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
@pytest.mark.parametrize("dtypes, exp_value", [({}, "1"), ({"a.1": "int64"}, 1)])
|
| 375 |
+
def test_dtype_mangle_dup_cols(all_parsers, dtypes, exp_value):
|
| 376 |
+
# GH#35211
|
| 377 |
+
parser = all_parsers
|
| 378 |
+
data = """a,a\n1,1"""
|
| 379 |
+
dtype_dict = {"a": str, **dtypes}
|
| 380 |
+
# GH#42462
|
| 381 |
+
dtype_dict_copy = dtype_dict.copy()
|
| 382 |
+
result = parser.read_csv(StringIO(data), dtype=dtype_dict)
|
| 383 |
+
expected = pd.DataFrame({"a": ["1"], "a.1": [exp_value]})
|
| 384 |
+
assert dtype_dict == dtype_dict_copy, "dtype dict changed"
|
| 385 |
+
tm.assert_frame_equal(result, expected)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def test_dtype_mangle_dup_cols_single_dtype(all_parsers):
|
| 389 |
+
# GH#42022
|
| 390 |
+
parser = all_parsers
|
| 391 |
+
data = """a,a\n1,1"""
|
| 392 |
+
result = parser.read_csv(StringIO(data), dtype=str)
|
| 393 |
+
expected = pd.DataFrame({"a": ["1"], "a.1": ["1"]})
|
| 394 |
+
tm.assert_frame_equal(result, expected)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def test_dtype_multi_index(all_parsers):
|
| 398 |
+
# GH 42446
|
| 399 |
+
parser = all_parsers
|
| 400 |
+
data = "A,B,B\nX,Y,Z\n1,2,3"
|
| 401 |
+
|
| 402 |
+
if parser.engine == "pyarrow":
|
| 403 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 404 |
+
parser.read_csv(
|
| 405 |
+
StringIO(data),
|
| 406 |
+
header=list(range(2)),
|
| 407 |
+
dtype={
|
| 408 |
+
("A", "X"): np.int32,
|
| 409 |
+
("B", "Y"): np.int32,
|
| 410 |
+
("B", "Z"): np.float32,
|
| 411 |
+
},
|
| 412 |
+
)
|
| 413 |
+
return
|
| 414 |
+
|
| 415 |
+
result = parser.read_csv(
|
| 416 |
+
StringIO(data),
|
| 417 |
+
header=list(range(2)),
|
| 418 |
+
dtype={
|
| 419 |
+
("A", "X"): np.int32,
|
| 420 |
+
("B", "Y"): np.int32,
|
| 421 |
+
("B", "Z"): np.float32,
|
| 422 |
+
},
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
expected = pd.DataFrame(
|
| 426 |
+
{
|
| 427 |
+
("A", "X"): np.int32([1]),
|
| 428 |
+
("B", "Y"): np.int32([2]),
|
| 429 |
+
("B", "Z"): np.float32([3]),
|
| 430 |
+
}
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
tm.assert_frame_equal(result, expected)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def test_nullable_int_dtype(all_parsers, any_int_ea_dtype):
|
| 437 |
+
# GH 25472
|
| 438 |
+
parser = all_parsers
|
| 439 |
+
dtype = any_int_ea_dtype
|
| 440 |
+
|
| 441 |
+
data = """a,b,c
|
| 442 |
+
,3,5
|
| 443 |
+
1,,6
|
| 444 |
+
2,4,"""
|
| 445 |
+
expected = pd.DataFrame(
|
| 446 |
+
{
|
| 447 |
+
"a": pd.array([pd.NA, 1, 2], dtype=dtype),
|
| 448 |
+
"b": pd.array([3, pd.NA, 4], dtype=dtype),
|
| 449 |
+
"c": pd.array([5, 6, pd.NA], dtype=dtype),
|
| 450 |
+
}
|
| 451 |
+
)
|
| 452 |
+
actual = parser.read_csv(StringIO(data), dtype=dtype)
|
| 453 |
+
tm.assert_frame_equal(actual, expected)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
@xfail_pyarrow # pyarrow engine reads uint64-max via float64 and cannot cast it
|
| 457 |
+
def test_nullable_int_dtype_boundary_values(all_parsers):
|
| 458 |
+
# A nullable-integer dtype whose boundary value coincides with the C
|
| 459 |
+
# parser's internal NA sentinel (int64 min / uint64 max) must be kept,
|
| 460 |
+
# not silently turned into NA.
|
| 461 |
+
parser = all_parsers
|
| 462 |
+
data = "a,b\n-9223372036854775808,18446744073709551615\n0,0\n"
|
| 463 |
+
result = parser.read_csv(StringIO(data), dtype={"a": "Int64", "b": "UInt64"})
|
| 464 |
+
expected = pd.DataFrame(
|
| 465 |
+
{
|
| 466 |
+
"a": pd.array([-9223372036854775808, 0], dtype="Int64"),
|
| 467 |
+
"b": pd.array([18446744073709551615, 0], dtype="UInt64"),
|
| 468 |
+
}
|
| 469 |
+
)
|
| 470 |
+
tm.assert_frame_equal(result, expected)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@xfail_pyarrow # pyarrow engine handles explicit ArrowDtype differently
|
| 474 |
+
def test_explicit_arrow_numeric_dtype(all_parsers):
|
| 475 |
+
# Explicitly requesting a pyarrow-backed numeric dtype parses identically to
|
| 476 |
+
# dtype_backend="pyarrow" (e.g. it does not adopt pyarrow's more lenient
|
| 477 |
+
# string casting).
|
| 478 |
+
pytest.importorskip("pyarrow")
|
| 479 |
+
parser = all_parsers
|
| 480 |
+
data = "a,b\n1,2.5\n,\n-3,4\n"
|
| 481 |
+
result = parser.read_csv(
|
| 482 |
+
StringIO(data), dtype={"a": "int64[pyarrow]", "b": "double[pyarrow]"}
|
| 483 |
+
)
|
| 484 |
+
expected = pd.DataFrame(
|
| 485 |
+
{
|
| 486 |
+
"a": pd.array([1, pd.NA, -3], dtype="int64[pyarrow]"),
|
| 487 |
+
"b": pd.array([2.5, pd.NA, 4.0], dtype="double[pyarrow]"),
|
| 488 |
+
}
|
| 489 |
+
)
|
| 490 |
+
tm.assert_frame_equal(result, expected)
|
| 491 |
+
|
| 492 |
+
# hex is rejected, matching dtype="int64" (not silently parsed as 31)
|
| 493 |
+
with pytest.raises(ValueError, match="Unable to parse string"):
|
| 494 |
+
parser.read_csv(StringIO("a\n0x1F\n"), dtype={"a": "int64[pyarrow]"})
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def test_explicit_arrow_int_dtype_precision_with_na(all_parsers):
|
| 498 |
+
# GH#56135 a missing value must not cost the column its precision
|
| 499 |
+
pytest.importorskip("pyarrow")
|
| 500 |
+
parser = all_parsers
|
| 501 |
+
data = "a\n1582218195625938945\n\n-1582218195625938945\n"
|
| 502 |
+
result = parser.read_csv(
|
| 503 |
+
StringIO(data), dtype={"a": "int64[pyarrow]"}, skip_blank_lines=False
|
| 504 |
+
)
|
| 505 |
+
expected = pd.DataFrame(
|
| 506 |
+
{
|
| 507 |
+
"a": pd.array(
|
| 508 |
+
[1582218195625938945, pd.NA, -1582218195625938945],
|
| 509 |
+
dtype="int64[pyarrow]",
|
| 510 |
+
)
|
| 511 |
+
}
|
| 512 |
+
)
|
| 513 |
+
tm.assert_frame_equal(result, expected)
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
@pytest.mark.parametrize("dtype", ["float", "double[pyarrow]"])
|
| 517 |
+
def test_empty_field_invalid_for_float_dtype(all_parsers, dtype):
|
| 518 |
+
# GH#66834 empty field with keep_default_na=False is not a valid float,
|
| 519 |
+
# for both numpy and pyarrow-backed float dtypes.
|
| 520 |
+
if dtype == "double[pyarrow]":
|
| 521 |
+
pytest.importorskip("pyarrow")
|
| 522 |
+
|
| 523 |
+
parser = all_parsers
|
| 524 |
+
data = "id,A\n1,1.5\n2,\n3,2.0\n"
|
| 525 |
+
|
| 526 |
+
if parser.engine == "python" and dtype == "float":
|
| 527 |
+
msg = "Unable to convert column A to type float64"
|
| 528 |
+
elif parser.engine == "pyarrow" and dtype == "double[pyarrow]":
|
| 529 |
+
msg = r"Failed to parse string: '' as a scalar of type double"
|
| 530 |
+
elif dtype == "double[pyarrow]":
|
| 531 |
+
msg = r"could not convert string to double"
|
| 532 |
+
else:
|
| 533 |
+
msg = r"could not convert string to float"
|
| 534 |
+
|
| 535 |
+
with pytest.raises(ValueError, match=msg):
|
| 536 |
+
parser.read_csv(StringIO(data), dtype={"A": dtype}, keep_default_na=False)
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def test_explicit_arrow_temporal_dtype(all_parsers):
|
| 540 |
+
# Non-numeric pyarrow-backed dtypes round-trip through read_csv.
|
| 541 |
+
pytest.importorskip("pyarrow")
|
| 542 |
+
parser = all_parsers
|
| 543 |
+
data = "a,b\n2020-01-01,1\n,2\n2021-06-15,3\n"
|
| 544 |
+
result = parser.read_csv(StringIO(data), dtype={"a": "timestamp[ns][pyarrow]"})
|
| 545 |
+
expected = pd.DataFrame(
|
| 546 |
+
{
|
| 547 |
+
"a": pd.array(
|
| 548 |
+
["2020-01-01", None, "2021-06-15"], dtype="timestamp[ns][pyarrow]"
|
| 549 |
+
),
|
| 550 |
+
"b": [1, 2, 3],
|
| 551 |
+
}
|
| 552 |
+
)
|
| 553 |
+
tm.assert_frame_equal(result, expected)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
@xfail_pyarrow # true_values/false_values not supported by the pyarrow engine
|
| 557 |
+
def test_nullable_boolean_dtype_with_true_false_values(all_parsers):
|
| 558 |
+
# User-supplied true_values/false_values augment the default token set.
|
| 559 |
+
parser = all_parsers
|
| 560 |
+
data = "a,b\nyes,1\nno,2\nTrue,3\n"
|
| 561 |
+
result = parser.read_csv(
|
| 562 |
+
StringIO(data),
|
| 563 |
+
dtype={"a": "boolean"},
|
| 564 |
+
true_values=["yes"],
|
| 565 |
+
false_values=["no"],
|
| 566 |
+
)
|
| 567 |
+
expected = pd.DataFrame(
|
| 568 |
+
{"a": pd.array([True, False, True], dtype="boolean"), "b": [1, 2, 3]}
|
| 569 |
+
)
|
| 570 |
+
tm.assert_frame_equal(result, expected)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
@pytest.mark.parametrize("default", ["float", "float64"])
|
| 574 |
+
def test_dtypes_defaultdict(all_parsers, default):
|
| 575 |
+
# GH#41574
|
| 576 |
+
data = """a,b
|
| 577 |
+
1,2
|
| 578 |
+
"""
|
| 579 |
+
dtype = defaultdict(lambda: default, a="int64")
|
| 580 |
+
parser = all_parsers
|
| 581 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 582 |
+
expected = pd.DataFrame({"a": [1], "b": 2.0})
|
| 583 |
+
tm.assert_frame_equal(result, expected)
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def test_dtypes_defaultdict_names_with_integer_header(all_parsers):
|
| 587 |
+
# GH#65862 the default must be materialized over the user's names,
|
| 588 |
+
# not pyarrow's autogenerated column names
|
| 589 |
+
data = """a,b
|
| 590 |
+
1,2
|
| 591 |
+
"""
|
| 592 |
+
dtype = defaultdict(lambda: "float64", x="int64")
|
| 593 |
+
parser = all_parsers
|
| 594 |
+
result = parser.read_csv(StringIO(data), header=0, names=["x", "y"], dtype=dtype)
|
| 595 |
+
expected = pd.DataFrame({"x": [1], "y": 2.0})
|
| 596 |
+
tm.assert_frame_equal(result, expected)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def test_dtypes_defaultdict_mangle_dup_cols(all_parsers):
|
| 600 |
+
# GH#41574
|
| 601 |
+
data = """a,b,a,b,b.1
|
| 602 |
+
1,2,3,4,5
|
| 603 |
+
"""
|
| 604 |
+
dtype = defaultdict(lambda: "float64", a="int64")
|
| 605 |
+
dtype["b.1"] = "int64"
|
| 606 |
+
parser = all_parsers
|
| 607 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 608 |
+
expected = pd.DataFrame(
|
| 609 |
+
{"a": [1], "b": [2.0], "a.1": [3], "b.2": [4.0], "b.1": [5]}
|
| 610 |
+
)
|
| 611 |
+
tm.assert_frame_equal(result, expected)
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def test_dtypes_defaultdict_invalid(all_parsers):
|
| 615 |
+
# GH#41574
|
| 616 |
+
data = """a,b
|
| 617 |
+
1,2
|
| 618 |
+
"""
|
| 619 |
+
dtype = defaultdict(lambda: "invalid_dtype", a="int64")
|
| 620 |
+
parser = all_parsers
|
| 621 |
+
with pytest.raises(TypeError, match="not understood"):
|
| 622 |
+
parser.read_csv(StringIO(data), dtype=dtype)
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def test_dtype_backend(all_parsers):
|
| 626 |
+
# GH#36712
|
| 627 |
+
|
| 628 |
+
parser = all_parsers
|
| 629 |
+
|
| 630 |
+
data = """a,b,c,d,e,f,g,h,i,j
|
| 631 |
+
1,2.5,True,a,,,,,12-31-2019,
|
| 632 |
+
3,4.5,False,b,6,7.5,True,a,12-31-2019,
|
| 633 |
+
"""
|
| 634 |
+
result = parser.read_csv(
|
| 635 |
+
StringIO(data), dtype_backend="numpy_nullable", parse_dates=["i"]
|
| 636 |
+
)
|
| 637 |
+
expected = pd.DataFrame(
|
| 638 |
+
{
|
| 639 |
+
"a": pd.Series([1, 3], dtype="Int64"),
|
| 640 |
+
"b": pd.Series([2.5, 4.5], dtype="Float64"),
|
| 641 |
+
"c": pd.Series([True, False], dtype="boolean"),
|
| 642 |
+
"d": pd.Series(["a", "b"], dtype="string"),
|
| 643 |
+
"e": pd.Series([pd.NA, 6], dtype="Int64"),
|
| 644 |
+
"f": pd.Series([pd.NA, 7.5], dtype="Float64"),
|
| 645 |
+
"g": pd.Series([pd.NA, True], dtype="boolean"),
|
| 646 |
+
"h": pd.Series([pd.NA, "a"], dtype="string"),
|
| 647 |
+
"i": pd.Series([pd.Timestamp("2019-12-31")] * 2),
|
| 648 |
+
"j": pd.Series([pd.NA, pd.NA], dtype="Int64"),
|
| 649 |
+
}
|
| 650 |
+
)
|
| 651 |
+
tm.assert_frame_equal(result, expected)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def test_dtype_backend_and_dtype(all_parsers):
|
| 655 |
+
# GH#36712
|
| 656 |
+
|
| 657 |
+
parser = all_parsers
|
| 658 |
+
|
| 659 |
+
data = """a,b
|
| 660 |
+
1,2.5
|
| 661 |
+
,
|
| 662 |
+
"""
|
| 663 |
+
result = parser.read_csv(
|
| 664 |
+
StringIO(data), dtype_backend="numpy_nullable", dtype="float64"
|
| 665 |
+
)
|
| 666 |
+
expected = pd.DataFrame({"a": [1.0, np.nan], "b": [2.5, np.nan]})
|
| 667 |
+
tm.assert_frame_equal(result, expected)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def test_dtype_backend_string(all_parsers, string_storage):
|
| 671 |
+
# GH#36712
|
| 672 |
+
with pd.option_context("mode.string_storage", string_storage):
|
| 673 |
+
parser = all_parsers
|
| 674 |
+
|
| 675 |
+
data = """a,b
|
| 676 |
+
a,x
|
| 677 |
+
b,
|
| 678 |
+
"""
|
| 679 |
+
result = parser.read_csv(StringIO(data), dtype_backend="numpy_nullable")
|
| 680 |
+
|
| 681 |
+
expected = pd.DataFrame(
|
| 682 |
+
{
|
| 683 |
+
"a": pd.array(["a", "b"], dtype=pd.StringDtype(string_storage)),
|
| 684 |
+
"b": pd.array(["x", pd.NA], dtype=pd.StringDtype(string_storage)),
|
| 685 |
+
},
|
| 686 |
+
)
|
| 687 |
+
tm.assert_frame_equal(result, expected)
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def test_dtype_backend_ea_dtype_specified(all_parsers):
|
| 691 |
+
# GH#491496
|
| 692 |
+
data = """a,b
|
| 693 |
+
1,2
|
| 694 |
+
"""
|
| 695 |
+
parser = all_parsers
|
| 696 |
+
result = parser.read_csv(
|
| 697 |
+
StringIO(data), dtype="Int64", dtype_backend="numpy_nullable"
|
| 698 |
+
)
|
| 699 |
+
expected = pd.DataFrame({"a": [1], "b": 2}, dtype="Int64")
|
| 700 |
+
tm.assert_frame_equal(result, expected)
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
@pytest.mark.parametrize("dtype", ["string", "string[pyarrow]"])
|
| 704 |
+
def test_dtype_string_int_column_with_na(all_parsers, dtype):
|
| 705 |
+
# GH#57100 the pyarrow engine inferred int64, widened it to float64 to hold
|
| 706 |
+
# the missing value and then cast to string, yielding "44794724.0"
|
| 707 |
+
if dtype == "string[pyarrow]":
|
| 708 |
+
pytest.importorskip("pyarrow")
|
| 709 |
+
parser = all_parsers
|
| 710 |
+
data = "var1,var2\n44794724,x\n,y\n"
|
| 711 |
+
|
| 712 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 713 |
+
|
| 714 |
+
expected = pd.DataFrame(
|
| 715 |
+
{"var1": ["44794724", None], "var2": ["x", "y"]}, dtype=dtype
|
| 716 |
+
)
|
| 717 |
+
tm.assert_frame_equal(result, expected)
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
def test_dtype_backend_pyarrow(all_parsers, request):
|
| 721 |
+
# GH#36712
|
| 722 |
+
pa = pytest.importorskip("pyarrow")
|
| 723 |
+
parser = all_parsers
|
| 724 |
+
|
| 725 |
+
data = """a,b,c,d,e,f,g,h,i,j
|
| 726 |
+
1,2.5,True,a,,,,,12-31-2019,
|
| 727 |
+
3,4.5,False,b,6,7.5,True,a,12-31-2019,
|
| 728 |
+
"""
|
| 729 |
+
result = parser.read_csv(StringIO(data), dtype_backend="pyarrow", parse_dates=["i"])
|
| 730 |
+
expected = pd.DataFrame(
|
| 731 |
+
{
|
| 732 |
+
"a": pd.Series([1, 3], dtype="int64[pyarrow]"),
|
| 733 |
+
"b": pd.Series([2.5, 4.5], dtype="float64[pyarrow]"),
|
| 734 |
+
"c": pd.Series([True, False], dtype="bool[pyarrow]"),
|
| 735 |
+
"d": pd.Series(["a", "b"], dtype=pd.ArrowDtype(pa.string())),
|
| 736 |
+
"e": pd.Series([pd.NA, 6], dtype="int64[pyarrow]"),
|
| 737 |
+
"f": pd.Series([pd.NA, 7.5], dtype="float64[pyarrow]"),
|
| 738 |
+
"g": pd.Series([pd.NA, True], dtype="bool[pyarrow]"),
|
| 739 |
+
"h": pd.Series(
|
| 740 |
+
[pd.NA, "a"],
|
| 741 |
+
dtype=pd.ArrowDtype(pa.string()),
|
| 742 |
+
),
|
| 743 |
+
"i": pd.Series([pd.Timestamp("2019-12-31")] * 2),
|
| 744 |
+
"j": pd.Series([pd.NA, pd.NA], dtype="null[pyarrow]"),
|
| 745 |
+
}
|
| 746 |
+
)
|
| 747 |
+
tm.assert_frame_equal(result, expected)
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
def test_ea_int_avoid_overflow(all_parsers):
|
| 751 |
+
# GH#32134
|
| 752 |
+
parser = all_parsers
|
| 753 |
+
data = """a,b
|
| 754 |
+
1,1
|
| 755 |
+
,1
|
| 756 |
+
1582218195625938945,1
|
| 757 |
+
"""
|
| 758 |
+
result = parser.read_csv(StringIO(data), dtype={"a": "Int64"})
|
| 759 |
+
expected = pd.DataFrame(
|
| 760 |
+
{
|
| 761 |
+
"a": IntegerArray(
|
| 762 |
+
np.array([1, 1, 1582218195625938945]), np.array([False, True, False])
|
| 763 |
+
),
|
| 764 |
+
"b": 1,
|
| 765 |
+
}
|
| 766 |
+
)
|
| 767 |
+
tm.assert_frame_equal(result, expected)
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def test_string_inference(all_parsers, using_infer_string):
|
| 771 |
+
# GH#54430
|
| 772 |
+
dtype = pd.StringDtype(na_value=np.nan) if using_infer_string else object
|
| 773 |
+
|
| 774 |
+
data = """a,b
|
| 775 |
+
x,1
|
| 776 |
+
y,2
|
| 777 |
+
,3"""
|
| 778 |
+
parser = all_parsers
|
| 779 |
+
result = parser.read_csv(StringIO(data))
|
| 780 |
+
|
| 781 |
+
expected = pd.DataFrame(
|
| 782 |
+
{
|
| 783 |
+
"a": pd.Series(
|
| 784 |
+
["x", "y", None if parser.engine == "pyarrow" else np.nan], dtype=dtype
|
| 785 |
+
),
|
| 786 |
+
"b": [1, 2, 3],
|
| 787 |
+
},
|
| 788 |
+
columns=pd.Index(["a", "b"], dtype=dtype),
|
| 789 |
+
)
|
| 790 |
+
tm.assert_frame_equal(result, expected)
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
@pytest.mark.parametrize("dtype", ["O", object, "object", np.object_, str, np.str_])
|
| 794 |
+
def test_string_inference_object_dtype(all_parsers, dtype, using_infer_string):
|
| 795 |
+
# GH#56047
|
| 796 |
+
data = """a,b
|
| 797 |
+
x,a
|
| 798 |
+
y,a
|
| 799 |
+
z,a"""
|
| 800 |
+
parser = all_parsers
|
| 801 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 802 |
+
|
| 803 |
+
expected_dtype = (
|
| 804 |
+
pd.StringDtype(na_value=np.nan)
|
| 805 |
+
if dtype is str and using_infer_string
|
| 806 |
+
else object
|
| 807 |
+
)
|
| 808 |
+
expected = pd.DataFrame(
|
| 809 |
+
{
|
| 810 |
+
"a": pd.Series(["x", "y", "z"], dtype=expected_dtype),
|
| 811 |
+
"b": pd.Series(["a", "a", "a"], dtype=expected_dtype),
|
| 812 |
+
},
|
| 813 |
+
columns=pd.Index(["a", "b"]),
|
| 814 |
+
)
|
| 815 |
+
tm.assert_frame_equal(result, expected)
|
| 816 |
+
|
| 817 |
+
result = parser.read_csv(StringIO(data), dtype={"a": dtype})
|
| 818 |
+
|
| 819 |
+
expected = pd.DataFrame(
|
| 820 |
+
{
|
| 821 |
+
"a": pd.Series(["x", "y", "z"], dtype=expected_dtype),
|
| 822 |
+
"b": pd.Series(["a", "a", "a"]),
|
| 823 |
+
},
|
| 824 |
+
columns=pd.Index(["a", "b"]),
|
| 825 |
+
)
|
| 826 |
+
tm.assert_frame_equal(result, expected)
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def test_accurate_parsing_of_large_integers(all_parsers):
|
| 830 |
+
# GH#52505
|
| 831 |
+
data = """SYMBOL,MOMENT,ID,ID_DEAL
|
| 832 |
+
AAPL,20230301181139587,1925036343869802844,
|
| 833 |
+
AAPL,20230301181139587,2023552585717889863,2023552585717263358
|
| 834 |
+
NVDA,20230301181139587,2023552585717889863,2023552585717263359
|
| 835 |
+
AMC,20230301181139587,2023552585717889863,2023552585717263360
|
| 836 |
+
AMZN,20230301181139587,2023552585717889759,2023552585717263360
|
| 837 |
+
MSFT,20230301181139587,2023552585717889863,2023552585717263361
|
| 838 |
+
NVDA,20230301181139587,2023552585717889827,2023552585717263361"""
|
| 839 |
+
orders = all_parsers.read_csv(StringIO(data), dtype={"ID_DEAL": pd.Int64Dtype()})
|
| 840 |
+
assert len(orders.loc[orders["ID_DEAL"] == 2023552585717263358, "ID_DEAL"]) == 1
|
| 841 |
+
assert len(orders.loc[orders["ID_DEAL"] == 2023552585717263359, "ID_DEAL"]) == 1
|
| 842 |
+
assert len(orders.loc[orders["ID_DEAL"] == 2023552585717263360, "ID_DEAL"]) == 2
|
| 843 |
+
assert len(orders.loc[orders["ID_DEAL"] == 2023552585717263361, "ID_DEAL"]) == 2
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def test_dtypes_with_usecols(all_parsers):
|
| 847 |
+
# GH#54868, GH#57666
|
| 848 |
+
|
| 849 |
+
parser = all_parsers
|
| 850 |
+
data = """a,b,c
|
| 851 |
+
1,2,3
|
| 852 |
+
4,5,6"""
|
| 853 |
+
|
| 854 |
+
result = parser.read_csv(StringIO(data), usecols=["a", "c"], dtype={"a": object})
|
| 855 |
+
expected = pd.DataFrame({"a": pd.Series(["1", "4"], dtype=object), "c": [3, 6]})
|
| 856 |
+
tm.assert_frame_equal(result, expected)
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def test_index_col_with_dtype_no_rangeindex(all_parsers):
|
| 860 |
+
data = StringIO("345.5,519.5,0\n519.5,726.5,1")
|
| 861 |
+
result = all_parsers.read_csv(
|
| 862 |
+
data,
|
| 863 |
+
header=None,
|
| 864 |
+
names=["start", "stop", "bin_id"],
|
| 865 |
+
dtype={"start": np.float32, "stop": np.float32, "bin_id": np.uint32},
|
| 866 |
+
index_col="bin_id",
|
| 867 |
+
).index
|
| 868 |
+
expected = pd.Index([0, 1], dtype=np.uint32, name="bin_id")
|
| 869 |
+
tm.assert_index_equal(result, expected)
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
@pytest.mark.parametrize("dtype", [str, "str", "string"])
|
| 873 |
+
def test_leading_zeros_preserved_with_scalar_string_dtype(all_parsers, dtype, request):
|
| 874 |
+
# GH#57666 values that look numeric but carry leading zeros must be
|
| 875 |
+
# read verbatim when a scalar string dtype is requested
|
| 876 |
+
parser = all_parsers
|
| 877 |
+
if parser.engine == "pyarrow" and pa_version_under25p0:
|
| 878 |
+
mark = pytest.mark.xfail(
|
| 879 |
+
reason="the pyarrow engine needs pyarrow>=25.0 "
|
| 880 |
+
"(ConvertOptions.default_column_type) to apply a scalar dtype "
|
| 881 |
+
"while parsing; older versions infer integers and lose the zeros"
|
| 882 |
+
)
|
| 883 |
+
request.applymarker(mark)
|
| 884 |
+
data = """col1,col2,col3,col4
|
| 885 |
+
AB,000388907,abc,0150
|
| 886 |
+
CD,101044572,def,0150
|
| 887 |
+
EF,000023607,ghi,0205
|
| 888 |
+
GH,100102040,jkl,0205"""
|
| 889 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 890 |
+
expected = pd.DataFrame(
|
| 891 |
+
{
|
| 892 |
+
"col1": ["AB", "CD", "EF", "GH"],
|
| 893 |
+
"col2": ["000388907", "101044572", "000023607", "100102040"],
|
| 894 |
+
"col3": ["abc", "def", "ghi", "jkl"],
|
| 895 |
+
"col4": ["0150", "0150", "0205", "0205"],
|
| 896 |
+
},
|
| 897 |
+
dtype=dtype,
|
| 898 |
+
)
|
| 899 |
+
tm.assert_frame_equal(result, expected)
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
def test_leading_zeros_preserved_with_dtype_str_no_header(all_parsers, request):
|
| 903 |
+
# GH#57666 a scalar dtype applies with autogenerated column names too
|
| 904 |
+
parser = all_parsers
|
| 905 |
+
if parser.engine == "pyarrow" and pa_version_under25p0:
|
| 906 |
+
request.applymarker(
|
| 907 |
+
pytest.mark.xfail(reason="pyarrow<25.0 lacks default_column_type")
|
| 908 |
+
)
|
| 909 |
+
data = "01,0150\n002,0205"
|
| 910 |
+
result = parser.read_csv(StringIO(data), header=None, dtype=str)
|
| 911 |
+
expected = pd.DataFrame([["01", "0150"], ["002", "0205"]], dtype=str)
|
| 912 |
+
tm.assert_frame_equal(result, expected)
|
| 913 |
+
|
| 914 |
+
|
| 915 |
+
def test_leading_zeros_with_missing_values_dtype_str(all_parsers, request):
|
| 916 |
+
# GH#57666 empty fields stay missing while other values keep their text
|
| 917 |
+
parser = all_parsers
|
| 918 |
+
if parser.engine == "pyarrow" and pa_version_under25p0:
|
| 919 |
+
request.applymarker(
|
| 920 |
+
pytest.mark.xfail(reason="pyarrow<25.0 lacks default_column_type")
|
| 921 |
+
)
|
| 922 |
+
data = "a,b\n01,\n,002"
|
| 923 |
+
result = parser.read_csv(StringIO(data), dtype=str)
|
| 924 |
+
expected = pd.DataFrame({"a": ["01", np.nan], "b": [np.nan, "002"]}, dtype=str)
|
| 925 |
+
tm.assert_frame_equal(result, expected)
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
def test_leading_zeros_preserved_with_dtype_defaultdict(all_parsers, request):
|
| 929 |
+
# GH#57666, GH#41574 the default of a defaultdict applies to columns
|
| 930 |
+
# not explicitly listed, like a scalar dtype
|
| 931 |
+
parser = all_parsers
|
| 932 |
+
if parser.engine == "pyarrow" and pa_version_under25p0:
|
| 933 |
+
request.applymarker(
|
| 934 |
+
pytest.mark.xfail(reason="pyarrow<25.0 lacks default_column_type")
|
| 935 |
+
)
|
| 936 |
+
dtype = defaultdict(lambda: str, col3="int64")
|
| 937 |
+
data = """col1,col2,col3
|
| 938 |
+
AB,000388907,199
|
| 939 |
+
CD,101044572,200"""
|
| 940 |
+
result = parser.read_csv(StringIO(data), dtype=dtype)
|
| 941 |
+
expected = pd.DataFrame(
|
| 942 |
+
{
|
| 943 |
+
"col1": pd.Series(["AB", "CD"], dtype=str),
|
| 944 |
+
"col2": pd.Series(["000388907", "101044572"], dtype=str),
|
| 945 |
+
"col3": pd.Series([199, 200], dtype="int64"),
|
| 946 |
+
}
|
| 947 |
+
)
|
| 948 |
+
tm.assert_frame_equal(result, expected)
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def test_object_dtype_dict_preserves_raw_strings(all_parsers):
|
| 952 |
+
# GH#57666, GH#9435 dtype=object holds the raw strings on every engine
|
| 953 |
+
parser = all_parsers
|
| 954 |
+
data = "a,b\n01,2\n002,3"
|
| 955 |
+
result = parser.read_csv(StringIO(data), dtype={"a": object})
|
| 956 |
+
expected = pd.DataFrame({"a": pd.Series(["01", "002"], dtype=object), "b": [2, 3]})
|
| 957 |
+
tm.assert_frame_equal(result, expected)
|
| 958 |
+
|
| 959 |
+
|
| 960 |
+
def test_dtype_dict_non_string_key_pyarrow(pyarrow_parser_only):
|
| 961 |
+
# GH#57666 pyarrow's ConvertOptions requires string column names, so
|
| 962 |
+
# non-string dtype keys must not raise; they are applied afterwards
|
| 963 |
+
# (here dropped, since positional keys are not supported by this engine)
|
| 964 |
+
parser = pyarrow_parser_only
|
| 965 |
+
data = "a,b\n01,2\n002,3"
|
| 966 |
+
result = parser.read_csv(StringIO(data), dtype={"a": str, 1: str})
|
| 967 |
+
expected = pd.DataFrame({"a": pd.Series(["01", "002"], dtype=str), "b": [2, 3]})
|
| 968 |
+
tm.assert_frame_equal(result, expected)
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
def test_leading_zeros_preserved_with_dtype_dict(all_parsers):
|
| 972 |
+
# GH#57666 per-column string dtypes must preserve leading zeros while
|
| 973 |
+
# other columns keep their requested dtypes
|
| 974 |
+
parser = all_parsers
|
| 975 |
+
data = """col1,col2,col3,col4
|
| 976 |
+
AB,000388907,199,0150
|
| 977 |
+
CD,101044572,200,0150
|
| 978 |
+
EF,000023607,201,0205
|
| 979 |
+
GH,100102040,202,0205"""
|
| 980 |
+
result = parser.read_csv(
|
| 981 |
+
StringIO(data), dtype={"col2": str, "col3": "int64", "col4": str}
|
| 982 |
+
)
|
| 983 |
+
expected = pd.DataFrame(
|
| 984 |
+
{
|
| 985 |
+
"col1": pd.Series(["AB", "CD", "EF", "GH"], dtype=str),
|
| 986 |
+
"col2": pd.Series(
|
| 987 |
+
["000388907", "101044572", "000023607", "100102040"], dtype=str
|
| 988 |
+
),
|
| 989 |
+
"col3": pd.Series([199, 200, 201, 202], dtype="int64"),
|
| 990 |
+
"col4": pd.Series(["0150", "0150", "0205", "0205"], dtype=str),
|
| 991 |
+
}
|
| 992 |
+
)
|
| 993 |
+
tm.assert_frame_equal(result, expected)
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
@xfail_pyarrow # pyarrow engine casts the parsed frame; wraps, or raises ValueError
|
| 997 |
+
@pytest.mark.parametrize("dtype_backend", [lib.no_default, "numpy_nullable", "pyarrow"])
|
| 998 |
+
@pytest.mark.parametrize(
|
| 999 |
+
"dtype, err, msg",
|
| 1000 |
+
[
|
| 1001 |
+
("UInt8", TypeError, "cannot safely cast non-equivalent int64 to uint8"),
|
| 1002 |
+
("Int8", TypeError, "cannot safely cast non-equivalent int64 to int8"),
|
| 1003 |
+
("uint8", ValueError, "cannot safely convert passed user dtype of uint8"),
|
| 1004 |
+
("int8", ValueError, "cannot safely convert passed user dtype of int8"),
|
| 1005 |
+
],
|
| 1006 |
+
)
|
| 1007 |
+
def test_out_of_range_integer_dtype_raises(all_parsers, dtype, err, msg, dtype_backend):
|
| 1008 |
+
# GH#55232 out-of-range values must raise instead of silently wrapping
|
| 1009 |
+
# around, matching the Series/array constructors. dtype_backend is
|
| 1010 |
+
# parametrized because it decides which cast the python engine takes.
|
| 1011 |
+
if dtype_backend == "pyarrow":
|
| 1012 |
+
pytest.importorskip("pyarrow")
|
| 1013 |
+
parser = all_parsers
|
| 1014 |
+
data = "x\n-1\n257\n"
|
| 1015 |
+
with pytest.raises(err, match=msg):
|
| 1016 |
+
parser.read_csv(StringIO(data), dtype={"x": dtype}, dtype_backend=dtype_backend)
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
@xfail_pyarrow # pyarrow engine casts the parsed frame; wraps, or raises ValueError
|
| 1020 |
+
@pytest.mark.parametrize(
|
| 1021 |
+
"data, dtype",
|
| 1022 |
+
[
|
| 1023 |
+
# only fits uint64, so the c engine falls back to _try_uint64
|
| 1024 |
+
("x\n18446744073709551615\n1\n", "uint8"),
|
| 1025 |
+
# the requested dtype is the int64 that overflowed into the fallback
|
| 1026 |
+
("x\n18446744073709551615\n1\n", "int64"),
|
| 1027 |
+
# parses as float rather than int, which both engines must check too
|
| 1028 |
+
("x\n300.0\n1.0\n", "uint8"),
|
| 1029 |
+
("x\n257.0\n1.0\n", "int8"),
|
| 1030 |
+
],
|
| 1031 |
+
)
|
| 1032 |
+
def test_unsafe_integer_dtype_raises_for_non_int64_source(all_parsers, data, dtype):
|
| 1033 |
+
# GH#55232 the check has to cover every dtype the parser itself can
|
| 1034 |
+
# produce, not only the int64 the common case parses to
|
| 1035 |
+
parser = all_parsers
|
| 1036 |
+
with pytest.raises(ValueError, match="cannot safely convert passed user dtype"):
|
| 1037 |
+
parser.read_csv(StringIO(data), dtype={"x": dtype})
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/dtypes/test_empty.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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IO
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 18 |
+
def test_dtype_all_columns_empty(all_parsers):
|
| 19 |
+
# see gh-12048
|
| 20 |
+
parser = all_parsers
|
| 21 |
+
result = parser.read_csv(StringIO("A,B"), dtype=str)
|
| 22 |
+
|
| 23 |
+
expected = pd.DataFrame({"A": [], "B": []}, dtype=str)
|
| 24 |
+
tm.assert_frame_equal(result, expected)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 28 |
+
def test_empty_pass_dtype(all_parsers):
|
| 29 |
+
parser = all_parsers
|
| 30 |
+
|
| 31 |
+
data = "one,two"
|
| 32 |
+
result = parser.read_csv(StringIO(data), dtype={"one": "u1"})
|
| 33 |
+
|
| 34 |
+
expected = pd.DataFrame(
|
| 35 |
+
{"one": np.empty(0, dtype="u1"), "two": np.empty(0, dtype=object)},
|
| 36 |
+
)
|
| 37 |
+
tm.assert_frame_equal(result, expected)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 41 |
+
def test_empty_with_index_pass_dtype(all_parsers):
|
| 42 |
+
parser = all_parsers
|
| 43 |
+
|
| 44 |
+
data = "one,two"
|
| 45 |
+
result = parser.read_csv(
|
| 46 |
+
StringIO(data), index_col=["one"], dtype={"one": "u1", 1: "f"}
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
expected = pd.DataFrame(
|
| 50 |
+
{"two": np.empty(0, dtype="f")}, index=pd.Index([], dtype="u1", name="one")
|
| 51 |
+
)
|
| 52 |
+
tm.assert_frame_equal(result, expected)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 56 |
+
def test_empty_with_multi_index_pass_dtype(all_parsers):
|
| 57 |
+
parser = all_parsers
|
| 58 |
+
|
| 59 |
+
data = "one,two,three"
|
| 60 |
+
result = parser.read_csv(
|
| 61 |
+
StringIO(data), index_col=["one", "two"], dtype={"one": "u1", 1: "f8"}
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
exp_idx = pd.MultiIndex.from_arrays(
|
| 65 |
+
[np.empty(0, dtype="u1"), np.empty(0, dtype=np.float64)],
|
| 66 |
+
names=["one", "two"],
|
| 67 |
+
)
|
| 68 |
+
expected = pd.DataFrame({"three": np.empty(0, dtype=object)}, index=exp_idx)
|
| 69 |
+
tm.assert_frame_equal(result, expected)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 73 |
+
def test_empty_with_mangled_column_pass_dtype_by_names(all_parsers):
|
| 74 |
+
parser = all_parsers
|
| 75 |
+
|
| 76 |
+
data = "one,one"
|
| 77 |
+
result = parser.read_csv(StringIO(data), dtype={"one": "u1", "one.1": "f"})
|
| 78 |
+
|
| 79 |
+
expected = pd.DataFrame(
|
| 80 |
+
{"one": np.empty(0, dtype="u1"), "one.1": np.empty(0, dtype="f")},
|
| 81 |
+
)
|
| 82 |
+
tm.assert_frame_equal(result, expected)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 86 |
+
def test_empty_with_mangled_column_pass_dtype_by_indexes(all_parsers):
|
| 87 |
+
parser = all_parsers
|
| 88 |
+
|
| 89 |
+
data = "one,one"
|
| 90 |
+
result = parser.read_csv(StringIO(data), dtype={0: "u1", 1: "f"})
|
| 91 |
+
|
| 92 |
+
expected = pd.DataFrame(
|
| 93 |
+
{"one": np.empty(0, dtype="u1"), "one.1": np.empty(0, dtype="f")},
|
| 94 |
+
)
|
| 95 |
+
tm.assert_frame_equal(result, expected)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 99 |
+
def test_empty_with_dup_column_pass_dtype_by_indexes(all_parsers):
|
| 100 |
+
# see gh-9424
|
| 101 |
+
parser = all_parsers
|
| 102 |
+
expected = pd.concat(
|
| 103 |
+
[pd.Series([], name="one", dtype="u1"), pd.Series([], name="one.1", dtype="f")],
|
| 104 |
+
axis=1,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
data = "one,one"
|
| 108 |
+
result = parser.read_csv(StringIO(data), dtype={0: "u1", 1: "f"})
|
| 109 |
+
tm.assert_frame_equal(result, expected)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_empty_with_dup_column_pass_dtype_by_indexes_raises(all_parsers):
|
| 113 |
+
# see gh-9424
|
| 114 |
+
parser = all_parsers
|
| 115 |
+
expected = pd.concat(
|
| 116 |
+
[pd.Series([], name="one", dtype="u1"), pd.Series([], name="one.1", dtype="f")],
|
| 117 |
+
axis=1,
|
| 118 |
+
)
|
| 119 |
+
expected.index = expected.index.astype(object)
|
| 120 |
+
|
| 121 |
+
with pytest.raises(ValueError, match="Duplicate names"):
|
| 122 |
+
parser.read_csv(StringIO(""), names=["one", "one"], dtype={0: "u1", 1: "f"})
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@pytest.mark.parametrize(
|
| 126 |
+
"dtype,expected",
|
| 127 |
+
[
|
| 128 |
+
(np.float64, pd.DataFrame(columns=["a", "b"], dtype=np.float64)),
|
| 129 |
+
(
|
| 130 |
+
"category",
|
| 131 |
+
pd.DataFrame({"a": pd.Categorical([]), "b": pd.Categorical([])}),
|
| 132 |
+
),
|
| 133 |
+
(
|
| 134 |
+
{"a": "category", "b": "category"},
|
| 135 |
+
pd.DataFrame({"a": pd.Categorical([]), "b": pd.Categorical([])}),
|
| 136 |
+
),
|
| 137 |
+
("datetime64[ns]", pd.DataFrame(columns=["a", "b"], dtype="datetime64[ns]")),
|
| 138 |
+
(
|
| 139 |
+
"timedelta64[ns]",
|
| 140 |
+
pd.DataFrame(
|
| 141 |
+
{
|
| 142 |
+
"a": pd.Series([], dtype="timedelta64[ns]"),
|
| 143 |
+
"b": pd.Series([], dtype="timedelta64[ns]"),
|
| 144 |
+
},
|
| 145 |
+
),
|
| 146 |
+
),
|
| 147 |
+
(
|
| 148 |
+
{"a": np.int64, "b": np.int32},
|
| 149 |
+
pd.DataFrame(
|
| 150 |
+
{
|
| 151 |
+
"a": pd.Series([], dtype=np.int64),
|
| 152 |
+
"b": pd.Series([], dtype=np.int32),
|
| 153 |
+
},
|
| 154 |
+
),
|
| 155 |
+
),
|
| 156 |
+
(
|
| 157 |
+
{0: np.int64, 1: np.int32},
|
| 158 |
+
pd.DataFrame(
|
| 159 |
+
{
|
| 160 |
+
"a": pd.Series([], dtype=np.int64),
|
| 161 |
+
"b": pd.Series([], dtype=np.int32),
|
| 162 |
+
},
|
| 163 |
+
),
|
| 164 |
+
),
|
| 165 |
+
(
|
| 166 |
+
{"a": np.int64, 1: np.int32},
|
| 167 |
+
pd.DataFrame(
|
| 168 |
+
{
|
| 169 |
+
"a": pd.Series([], dtype=np.int64),
|
| 170 |
+
"b": pd.Series([], dtype=np.int32),
|
| 171 |
+
},
|
| 172 |
+
),
|
| 173 |
+
),
|
| 174 |
+
],
|
| 175 |
+
)
|
| 176 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 177 |
+
def test_empty_dtype(all_parsers, dtype, expected):
|
| 178 |
+
# see gh-14712
|
| 179 |
+
parser = all_parsers
|
| 180 |
+
data = "a,b"
|
| 181 |
+
|
| 182 |
+
result = parser.read_csv(StringIO(data), header=0, dtype=dtype)
|
| 183 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_c_parser_only.py
ADDED
|
@@ -0,0 +1,1866 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that apply specifically to the CParser. Unless specifically stated
|
| 3 |
+
as a CParser-specific issue, the goal is to eventually move as many of
|
| 4 |
+
these tests out of this module as soon as the Python parser can accept
|
| 5 |
+
further arguments when parsing.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from decimal import Decimal
|
| 9 |
+
from io import (
|
| 10 |
+
BytesIO,
|
| 11 |
+
StringIO,
|
| 12 |
+
TextIOWrapper,
|
| 13 |
+
)
|
| 14 |
+
import mmap
|
| 15 |
+
import tarfile
|
| 16 |
+
import tracemalloc
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pytest
|
| 20 |
+
|
| 21 |
+
from pandas._libs import parsers as libparsers
|
| 22 |
+
from pandas._libs.hashtable import get_hashtable_trace_domain
|
| 23 |
+
from pandas.compat import WASM
|
| 24 |
+
from pandas.errors import (
|
| 25 |
+
DtypeWarning,
|
| 26 |
+
Pandas4Warning,
|
| 27 |
+
ParserError,
|
| 28 |
+
ParserWarning,
|
| 29 |
+
)
|
| 30 |
+
import pandas.util._test_decorators as td
|
| 31 |
+
|
| 32 |
+
import pandas as pd
|
| 33 |
+
import pandas._testing as tm
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@pytest.mark.parametrize(
|
| 37 |
+
"malformed,expected_data",
|
| 38 |
+
[
|
| 39 |
+
("1\r1\r1\r 1\r 1\r", [[1], [1], [1], [1], [1]]),
|
| 40 |
+
("1\r1\r1\r 1\r 1\r11\r", [[1], [1], [1], [1], [1], [11]]),
|
| 41 |
+
("1\r1\r1\r 1\r 1\r11\r1\r", [[1], [1], [1], [1], [1], [11], [1]]),
|
| 42 |
+
],
|
| 43 |
+
ids=["words pointer", "stream pointer", "lines pointer"],
|
| 44 |
+
)
|
| 45 |
+
def test_buffer_overflow(c_parser_only, malformed, expected_data):
|
| 46 |
+
# see gh-9205, gh-51141: test certain malformed input files that
|
| 47 |
+
# previously caused buffer overflows in tokenizer.c due to
|
| 48 |
+
# \r characters being treated as line terminators, then triggering
|
| 49 |
+
# an infinite re-parsing loop in the WHITESPACE_LINE state.
|
| 50 |
+
parser = c_parser_only
|
| 51 |
+
result = parser.read_csv(StringIO(malformed), header=None)
|
| 52 |
+
expected = pd.DataFrame(expected_data)
|
| 53 |
+
tm.assert_frame_equal(result, expected)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_cr_in_field_with_trailing_space(c_parser_only):
|
| 57 |
+
# GH#51141 - embedded \r followed by space in unquoted field
|
| 58 |
+
# should not cause infinite re-parsing or buffer overflow
|
| 59 |
+
parser = c_parser_only
|
| 60 |
+
data = "a,b,c\n1,2,3\n4,5\r X,6\n"
|
| 61 |
+
result = parser.read_csv(StringIO(data))
|
| 62 |
+
assert len(result) == 3
|
| 63 |
+
assert result.shape == (3, 3)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_delim_whitespace_custom_terminator(c_parser_only):
|
| 67 |
+
# See gh-12912
|
| 68 |
+
data = "a b c~1 2 3~4 5 6~7 8 9"
|
| 69 |
+
parser = c_parser_only
|
| 70 |
+
|
| 71 |
+
df = parser.read_csv(StringIO(data), lineterminator="~", sep=r"\s+")
|
| 72 |
+
expected = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "b", "c"])
|
| 73 |
+
tm.assert_frame_equal(df, expected)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_dtype_and_names_error(c_parser_only):
|
| 77 |
+
# see gh-8833: passing both dtype and names
|
| 78 |
+
# resulting in an error reporting issue
|
| 79 |
+
parser = c_parser_only
|
| 80 |
+
data = """
|
| 81 |
+
1.0 1
|
| 82 |
+
2.0 2
|
| 83 |
+
3.0 3
|
| 84 |
+
"""
|
| 85 |
+
# base cases
|
| 86 |
+
result = parser.read_csv(StringIO(data), sep=r"\s+", header=None)
|
| 87 |
+
expected = pd.DataFrame([[1.0, 1], [2.0, 2], [3.0, 3]])
|
| 88 |
+
tm.assert_frame_equal(result, expected)
|
| 89 |
+
|
| 90 |
+
result = parser.read_csv(StringIO(data), sep=r"\s+", header=None, names=["a", "b"])
|
| 91 |
+
expected = pd.DataFrame([[1.0, 1], [2.0, 2], [3.0, 3]], columns=["a", "b"])
|
| 92 |
+
tm.assert_frame_equal(result, expected)
|
| 93 |
+
|
| 94 |
+
# fallback casting
|
| 95 |
+
result = parser.read_csv(
|
| 96 |
+
StringIO(data), sep=r"\s+", header=None, names=["a", "b"], dtype={"a": np.int32}
|
| 97 |
+
)
|
| 98 |
+
expected = pd.DataFrame([[1, 1], [2, 2], [3, 3]], columns=["a", "b"])
|
| 99 |
+
expected["a"] = expected["a"].astype(np.int32)
|
| 100 |
+
tm.assert_frame_equal(result, expected)
|
| 101 |
+
|
| 102 |
+
data = """
|
| 103 |
+
1.0 1
|
| 104 |
+
nan 2
|
| 105 |
+
3.0 3
|
| 106 |
+
"""
|
| 107 |
+
# fallback casting, but not castable
|
| 108 |
+
if not WASM: # no fp exception support in wasm
|
| 109 |
+
warn_msg = "invalid value encountered in cast"
|
| 110 |
+
with pytest.raises(ValueError, match="cannot safely convert"):
|
| 111 |
+
with tm.assert_produces_warning(
|
| 112 |
+
RuntimeWarning, check_stacklevel=False, match=warn_msg
|
| 113 |
+
):
|
| 114 |
+
parser.read_csv(
|
| 115 |
+
StringIO(data),
|
| 116 |
+
sep=r"\s+",
|
| 117 |
+
header=None,
|
| 118 |
+
names=["a", "b"],
|
| 119 |
+
dtype={"a": np.int32},
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@pytest.mark.parametrize(
|
| 124 |
+
"match,kwargs",
|
| 125 |
+
[
|
| 126 |
+
# For each of these cases, all of the dtypes are valid, just unsupported.
|
| 127 |
+
(
|
| 128 |
+
(
|
| 129 |
+
"the dtype datetime64 is not supported for parsing, "
|
| 130 |
+
"pass this column using parse_dates instead"
|
| 131 |
+
),
|
| 132 |
+
{"dtype": {"A": "datetime64", "B": "float64"}},
|
| 133 |
+
),
|
| 134 |
+
(
|
| 135 |
+
(
|
| 136 |
+
"the dtype datetime64 is not supported for parsing, "
|
| 137 |
+
"pass this column using parse_dates instead"
|
| 138 |
+
),
|
| 139 |
+
{"dtype": {"A": "datetime64", "B": "float64"}, "parse_dates": ["B"]},
|
| 140 |
+
),
|
| 141 |
+
(
|
| 142 |
+
"the dtype timedelta64 is not supported for parsing",
|
| 143 |
+
{"dtype": {"A": "timedelta64", "B": "float64"}},
|
| 144 |
+
),
|
| 145 |
+
(
|
| 146 |
+
f"the dtype {tm.ENDIAN}U8 is not supported for parsing",
|
| 147 |
+
{"dtype": {"A": "U8"}},
|
| 148 |
+
),
|
| 149 |
+
],
|
| 150 |
+
ids=["dt64-0", "dt64-1", "td64", f"{tm.ENDIAN}U8"],
|
| 151 |
+
)
|
| 152 |
+
def test_unsupported_dtype(c_parser_only, match, kwargs, temp_file):
|
| 153 |
+
parser = c_parser_only
|
| 154 |
+
df = pd.DataFrame(
|
| 155 |
+
np.random.default_rng(2).random((5, 2)),
|
| 156 |
+
columns=list("AB"),
|
| 157 |
+
index=["1A", "1B", "1C", "1D", "1E"],
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
df.to_csv(temp_file)
|
| 161 |
+
|
| 162 |
+
with pytest.raises(TypeError, match=match):
|
| 163 |
+
parser.read_csv(temp_file, index_col=0, **kwargs)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@td.skip_if_32bit
|
| 167 |
+
@pytest.mark.slow
|
| 168 |
+
# test numbers between 1 and 2
|
| 169 |
+
@pytest.mark.parametrize("num", np.linspace(1.0, 2.0, num=21))
|
| 170 |
+
def test_precise_conversion(c_parser_only, num):
|
| 171 |
+
parser = c_parser_only
|
| 172 |
+
|
| 173 |
+
normal_errors = []
|
| 174 |
+
precise_errors = []
|
| 175 |
+
|
| 176 |
+
def error(val: float, actual_val: Decimal) -> Decimal:
|
| 177 |
+
return abs(Decimal(f"{val:.100}") - actual_val)
|
| 178 |
+
|
| 179 |
+
# 25 decimal digits of precision
|
| 180 |
+
text = f"a\n{num:.25}"
|
| 181 |
+
|
| 182 |
+
depr_msg = "float_precision"
|
| 183 |
+
with tm.assert_produces_warning(
|
| 184 |
+
Pandas4Warning, match=depr_msg, check_stacklevel=False
|
| 185 |
+
):
|
| 186 |
+
normal_val = float(
|
| 187 |
+
parser.read_csv(StringIO(text), float_precision="legacy")["a"][0]
|
| 188 |
+
)
|
| 189 |
+
with tm.assert_produces_warning(
|
| 190 |
+
Pandas4Warning, match=depr_msg, check_stacklevel=False
|
| 191 |
+
):
|
| 192 |
+
precise_val = float(
|
| 193 |
+
parser.read_csv(StringIO(text), float_precision="high")["a"][0]
|
| 194 |
+
)
|
| 195 |
+
with tm.assert_produces_warning(
|
| 196 |
+
Pandas4Warning, match=depr_msg, check_stacklevel=False
|
| 197 |
+
):
|
| 198 |
+
roundtrip_val = float(
|
| 199 |
+
parser.read_csv(StringIO(text), float_precision="round_trip")["a"][0]
|
| 200 |
+
)
|
| 201 |
+
actual_val = Decimal(text[2:])
|
| 202 |
+
|
| 203 |
+
normal_errors.append(error(normal_val, actual_val))
|
| 204 |
+
precise_errors.append(error(precise_val, actual_val))
|
| 205 |
+
|
| 206 |
+
# round-trip should match float()
|
| 207 |
+
assert roundtrip_val == float(text[2:])
|
| 208 |
+
|
| 209 |
+
assert sum(precise_errors) <= sum(normal_errors)
|
| 210 |
+
assert max(precise_errors) <= max(normal_errors)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def test_usecols_dtypes(c_parser_only, using_infer_string):
|
| 214 |
+
parser = c_parser_only
|
| 215 |
+
data = """\
|
| 216 |
+
1,2,3
|
| 217 |
+
4,5,6
|
| 218 |
+
7,8,9
|
| 219 |
+
10,11,12"""
|
| 220 |
+
|
| 221 |
+
result = parser.read_csv(
|
| 222 |
+
StringIO(data),
|
| 223 |
+
usecols=(0, 1, 2),
|
| 224 |
+
names=("a", "b", "c"),
|
| 225 |
+
header=None,
|
| 226 |
+
converters={"a": str},
|
| 227 |
+
dtype={"b": int, "c": float},
|
| 228 |
+
)
|
| 229 |
+
result2 = parser.read_csv(
|
| 230 |
+
StringIO(data),
|
| 231 |
+
usecols=(0, 2),
|
| 232 |
+
names=("a", "b", "c"),
|
| 233 |
+
header=None,
|
| 234 |
+
converters={"a": str},
|
| 235 |
+
dtype={"b": int, "c": float},
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
if using_infer_string:
|
| 239 |
+
assert (result.dtypes == ["string", int, float]).all()
|
| 240 |
+
assert (result2.dtypes == ["string", float]).all()
|
| 241 |
+
else:
|
| 242 |
+
assert (result.dtypes == [object, int, float]).all()
|
| 243 |
+
assert (result2.dtypes == [object, float]).all()
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def test_disable_bool_parsing(c_parser_only):
|
| 247 |
+
# see gh-2090
|
| 248 |
+
|
| 249 |
+
parser = c_parser_only
|
| 250 |
+
data = """A,B,C
|
| 251 |
+
Yes,No,Yes
|
| 252 |
+
No,Yes,Yes
|
| 253 |
+
Yes,,Yes
|
| 254 |
+
No,No,No"""
|
| 255 |
+
|
| 256 |
+
result = parser.read_csv(StringIO(data), dtype=object)
|
| 257 |
+
assert (result.dtypes == object).all()
|
| 258 |
+
|
| 259 |
+
result = parser.read_csv(StringIO(data), dtype=object, na_filter=False)
|
| 260 |
+
assert result["B"][2] == ""
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def test_custom_lineterminator(c_parser_only):
|
| 264 |
+
parser = c_parser_only
|
| 265 |
+
data = "a,b,c~1,2,3~4,5,6"
|
| 266 |
+
|
| 267 |
+
result = parser.read_csv(StringIO(data), lineterminator="~")
|
| 268 |
+
expected = parser.read_csv(StringIO(data.replace("~", "\n")))
|
| 269 |
+
|
| 270 |
+
tm.assert_frame_equal(result, expected)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
@pytest.mark.parametrize("key", ["sep", "delimiter"])
|
| 274 |
+
@pytest.mark.parametrize(
|
| 275 |
+
"sep, term", [("\n", "~"), ("\r", "~"), ("\n", "\r"), ("\r", "\n")]
|
| 276 |
+
)
|
| 277 |
+
def test_line_break_as_separator_with_custom_lineterminator(
|
| 278 |
+
key, sep, term, c_parser_only
|
| 279 |
+
):
|
| 280 |
+
# GH#51801 a custom lineterminator frees up "\n"/"\r" as a separator
|
| 281 |
+
parser = c_parser_only
|
| 282 |
+
data = f"a{sep}b{sep}c{term}1{sep}2{sep}3{term}4{sep}5{sep}6"
|
| 283 |
+
|
| 284 |
+
result = parser.read_csv(StringIO(data), lineterminator=term, **{key: sep})
|
| 285 |
+
expected = parser.read_csv(StringIO(data.replace(sep, ",").replace(term, "\n")))
|
| 286 |
+
|
| 287 |
+
tm.assert_frame_equal(result, expected)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def test_parse_ragged_csv(c_parser_only):
|
| 291 |
+
parser = c_parser_only
|
| 292 |
+
data = """1,2,3
|
| 293 |
+
1,2,3,4
|
| 294 |
+
1,2,3,4,5
|
| 295 |
+
1,2
|
| 296 |
+
1,2,3,4"""
|
| 297 |
+
|
| 298 |
+
nice_data = """1,2,3,,
|
| 299 |
+
1,2,3,4,
|
| 300 |
+
1,2,3,4,5
|
| 301 |
+
1,2,,,
|
| 302 |
+
1,2,3,4,"""
|
| 303 |
+
result = parser.read_csv(
|
| 304 |
+
StringIO(data), header=None, names=["a", "b", "c", "d", "e"]
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
expected = parser.read_csv(
|
| 308 |
+
StringIO(nice_data), header=None, names=["a", "b", "c", "d", "e"]
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
tm.assert_frame_equal(result, expected)
|
| 312 |
+
|
| 313 |
+
# too many columns, cause segfault if not careful
|
| 314 |
+
data = "1,2\n3,4,5"
|
| 315 |
+
|
| 316 |
+
result = parser.read_csv(StringIO(data), header=None, names=range(50))
|
| 317 |
+
expected = parser.read_csv(StringIO(data), header=None, names=range(3)).reindex(
|
| 318 |
+
columns=range(50)
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
tm.assert_frame_equal(result, expected)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def test_tokenize_CR_with_quoting(c_parser_only):
|
| 325 |
+
# see gh-3453
|
| 326 |
+
parser = c_parser_only
|
| 327 |
+
data = ' a,b,c\r"a,b","e,d","f,f"'
|
| 328 |
+
|
| 329 |
+
result = parser.read_csv(StringIO(data), header=None)
|
| 330 |
+
expected = parser.read_csv(StringIO(data.replace("\r", "\n")), header=None)
|
| 331 |
+
tm.assert_frame_equal(result, expected)
|
| 332 |
+
|
| 333 |
+
result = parser.read_csv(StringIO(data))
|
| 334 |
+
expected = parser.read_csv(StringIO(data.replace("\r", "\n")))
|
| 335 |
+
tm.assert_frame_equal(result, expected)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
@pytest.mark.slow
|
| 339 |
+
@pytest.mark.parametrize("count", [3 * 2**n for n in range(6)])
|
| 340 |
+
def test_grow_boundary_at_cap(c_parser_only, count):
|
| 341 |
+
# See gh-12494
|
| 342 |
+
#
|
| 343 |
+
# Cause of error was that the C parser
|
| 344 |
+
# was not increasing the buffer size when
|
| 345 |
+
# the desired space would fill the buffer
|
| 346 |
+
# to capacity, which would later cause a
|
| 347 |
+
# buffer overflow error when checking the
|
| 348 |
+
# EOF terminator of the CSV stream.
|
| 349 |
+
# 3 * 2^n commas was observed to break the parser
|
| 350 |
+
parser = c_parser_only
|
| 351 |
+
|
| 352 |
+
with StringIO("," * count) as s:
|
| 353 |
+
expected = pd.DataFrame(columns=[f"Unnamed: {i}" for i in range(count + 1)])
|
| 354 |
+
df = parser.read_csv(s)
|
| 355 |
+
tm.assert_frame_equal(df, expected)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@pytest.mark.slow
|
| 359 |
+
@pytest.mark.parametrize("encoding", [None, "utf-8"])
|
| 360 |
+
def test_parse_trim_buffers(c_parser_only, encoding):
|
| 361 |
+
# This test is part of a bugfix for gh-13703. It attempts to
|
| 362 |
+
# to stress the system memory allocator, to cause it to move the
|
| 363 |
+
# stream buffer and either let the OS reclaim the region, or let
|
| 364 |
+
# other memory requests of parser otherwise modify the contents
|
| 365 |
+
# of memory space, where it was formally located.
|
| 366 |
+
# This test is designed to cause a `segfault` with unpatched
|
| 367 |
+
# `tokenizer.c`. Sometimes the test fails on `segfault`, other
|
| 368 |
+
# times it fails due to memory corruption, which causes the
|
| 369 |
+
# loaded DataFrame to differ from the expected one.
|
| 370 |
+
|
| 371 |
+
# Also force 'utf-8' encoding, so that `_string_convert` would take
|
| 372 |
+
# a different execution branch.
|
| 373 |
+
|
| 374 |
+
parser = c_parser_only
|
| 375 |
+
|
| 376 |
+
# Generate a large mixed-type CSV file on-the-fly (one record is
|
| 377 |
+
# approx 1.5KiB).
|
| 378 |
+
record_ = (
|
| 379 |
+
"""9999-9,99:99,,,,ZZ,ZZ,,,ZZZ-ZZZZ,.Z-ZZZZ,-9.99,,,9.99,Z"""
|
| 380 |
+
"""ZZZZ,,-99,9,ZZZ-ZZZZ,ZZ-ZZZZ,,9.99,ZZZ-ZZZZZ,ZZZ-ZZZZZ,"""
|
| 381 |
+
"""ZZZ-ZZZZ,ZZZ-ZZZZ,ZZZ-ZZZZ,ZZZ-ZZZZ,ZZZ-ZZZZ,ZZZ-ZZZZ,9"""
|
| 382 |
+
"""99,ZZZ-ZZZZ,,ZZ-ZZZZ,,,,,ZZZZ,ZZZ-ZZZZZ,ZZZ-ZZZZ,,,9,9,"""
|
| 383 |
+
"""9,9,99,99,999,999,ZZZZZ,ZZZ-ZZZZZ,ZZZ-ZZZZ,9,ZZ-ZZZZ,9."""
|
| 384 |
+
"""99,ZZ-ZZZZ,ZZ-ZZZZ,,,,ZZZZ,,,ZZ,ZZ,,,,,,,,,,,,,9,,,999."""
|
| 385 |
+
"""99,999.99,,,ZZZZZ,,,Z9,,,,,,,ZZZ,ZZZ,,,,,,,,,,,ZZZZZ,ZZ"""
|
| 386 |
+
"""ZZZ,ZZZ-ZZZZZZ,ZZZ-ZZZZZZ,ZZ-ZZZZ,ZZ-ZZZZ,ZZ-ZZZZ,ZZ-ZZ"""
|
| 387 |
+
"""ZZ,,,999999,999999,ZZZ,ZZZ,,,Z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ZZ-ZZ"""
|
| 402 |
+
"""ZZZ,ZZZ-ZZZZZ,ZZZ-ZZZZZ,ZZZ,ZZZ,ZZZ,ZZZ,9.99,,,-9.99,ZZ"""
|
| 403 |
+
"""-ZZZZ,-999.99,,-9999,,999.99,,,,999.99,99.99,,,ZZ-ZZZZZ"""
|
| 404 |
+
"""ZZZ,ZZ-ZZZZ-ZZZZZZZ,,,,ZZ-ZZ-ZZZZZZZZ,ZZZZZZZZ,ZZZ-ZZZZ"""
|
| 405 |
+
""",9999,999.99,ZZZ-ZZZZ,-9.99,-9.99,ZZZ-ZZZZ,99:99:99,,99"""
|
| 406 |
+
""",99,,9.99,,-99.99,,,,,,9.99,ZZZ-ZZZZ,-9.99,-9.99,9.99,9"""
|
| 407 |
+
""".99,,ZZZ,,,,,,,ZZZ,ZZZ,,,,,"""
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
# Set the number of lines so that a call to `parser_trim_buffers`
|
| 411 |
+
# is triggered: after a couple of full chunks are consumed a
|
| 412 |
+
# relatively small 'residual' chunk would cause reallocation
|
| 413 |
+
# within the parser.
|
| 414 |
+
chunksize, n_lines = 128, 2 * 128 + 15
|
| 415 |
+
csv_data = "\n".join([record_] * n_lines) + "\n"
|
| 416 |
+
|
| 417 |
+
# We will use StringIO to load the CSV from this text buffer.
|
| 418 |
+
# pd.read_csv() will iterate over the file in chunks and will
|
| 419 |
+
# finally read a residual chunk of really small size.
|
| 420 |
+
|
| 421 |
+
# Generate the expected output: manually create the dataframe
|
| 422 |
+
# by splitting by comma and repeating the `n_lines` times.
|
| 423 |
+
row = tuple(val_ if val_ else np.nan for val_ in record_.split(","))
|
| 424 |
+
expected = pd.DataFrame(
|
| 425 |
+
[row for _ in range(n_lines)], dtype=object, columns=None, index=None
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
# Iterate over the CSV file in chunks of `chunksize` lines
|
| 429 |
+
with parser.read_csv(
|
| 430 |
+
StringIO(csv_data),
|
| 431 |
+
header=None,
|
| 432 |
+
dtype=object,
|
| 433 |
+
chunksize=chunksize,
|
| 434 |
+
encoding=encoding,
|
| 435 |
+
) as chunks_:
|
| 436 |
+
result = pd.concat(chunks_, axis=0, ignore_index=True)
|
| 437 |
+
|
| 438 |
+
# Check for data corruption if there was no segfault
|
| 439 |
+
tm.assert_frame_equal(result, expected)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def test_internal_null_byte(c_parser_only):
|
| 443 |
+
# see gh-14012
|
| 444 |
+
#
|
| 445 |
+
# The null byte ('\x00') should not be used as a
|
| 446 |
+
# true line terminator, escape character, or comment
|
| 447 |
+
# character, only as a placeholder to indicate that
|
| 448 |
+
# none was specified.
|
| 449 |
+
#
|
| 450 |
+
# This test should be moved to test_common.py ONLY when
|
| 451 |
+
# Python's csv class supports parsing '\x00'.
|
| 452 |
+
parser = c_parser_only
|
| 453 |
+
|
| 454 |
+
names = ["a", "b", "c"]
|
| 455 |
+
data = "1,2,3\n4,\x00,6\n7,8,9"
|
| 456 |
+
# GH#19886 the NUL field is a one-character value, not an na_value, so the
|
| 457 |
+
# column stays a string column rather than becoming float-with-NaN.
|
| 458 |
+
expected = pd.DataFrame(
|
| 459 |
+
{"a": [1, 4, 7], "b": ["2", "\x00", "8"], "c": [3, 6, 9]}, columns=names
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
result = parser.read_csv(StringIO(data), names=names)
|
| 463 |
+
tm.assert_frame_equal(result, expected)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def test_read_nrows_large(c_parser_only):
|
| 467 |
+
# gh-7626 - Read only nrows of data in for large inputs (>262144b)
|
| 468 |
+
parser = c_parser_only
|
| 469 |
+
header_narrow = "\t".join(["COL_HEADER_" + str(i) for i in range(10)]) + "\n"
|
| 470 |
+
data_narrow = "\t".join(["somedatasomedatasomedata1" for _ in range(10)]) + "\n"
|
| 471 |
+
header_wide = "\t".join(["COL_HEADER_" + str(i) for i in range(15)]) + "\n"
|
| 472 |
+
data_wide = "\t".join(["somedatasomedatasomedata2" for _ in range(15)]) + "\n"
|
| 473 |
+
test_input = header_narrow + data_narrow * 1050 + header_wide + data_wide * 2
|
| 474 |
+
|
| 475 |
+
df = parser.read_csv(StringIO(test_input), sep="\t", nrows=1010)
|
| 476 |
+
|
| 477 |
+
assert df.size == 1010 * 10
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def test_float_precision_round_trip_with_text(c_parser_only):
|
| 481 |
+
# see gh-15140
|
| 482 |
+
parser = c_parser_only
|
| 483 |
+
with tm.assert_produces_warning(
|
| 484 |
+
Pandas4Warning, match="float_precision", check_stacklevel=False
|
| 485 |
+
):
|
| 486 |
+
df = parser.read_csv(StringIO("a"), header=None, float_precision="round_trip")
|
| 487 |
+
tm.assert_frame_equal(df, pd.DataFrame({0: ["a"]}))
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def test_large_difference_in_columns(c_parser_only):
|
| 491 |
+
# see gh-14125
|
| 492 |
+
parser = c_parser_only
|
| 493 |
+
|
| 494 |
+
count = 10000
|
| 495 |
+
large_row = ("X," * count)[:-1] + "\n"
|
| 496 |
+
normal_row = "XXXXXX XXXXXX,111111111111111\n"
|
| 497 |
+
test_input = (large_row + normal_row * 6)[:-1]
|
| 498 |
+
|
| 499 |
+
result = parser.read_csv(StringIO(test_input), header=None, usecols=[0])
|
| 500 |
+
rows = test_input.split("\n")
|
| 501 |
+
|
| 502 |
+
expected = pd.DataFrame([row.split(",")[0] for row in rows])
|
| 503 |
+
tm.assert_frame_equal(result, expected)
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def test_data_after_quote(c_parser_only):
|
| 507 |
+
# see gh-15910
|
| 508 |
+
parser = c_parser_only
|
| 509 |
+
|
| 510 |
+
data = 'a\n1\n"b"a'
|
| 511 |
+
result = parser.read_csv(StringIO(data))
|
| 512 |
+
|
| 513 |
+
expected = pd.DataFrame({"a": ["1", "ba"]})
|
| 514 |
+
tm.assert_frame_equal(result, expected)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def test_comment_whitespace_delimited(c_parser_only):
|
| 518 |
+
parser = c_parser_only
|
| 519 |
+
test_input = """\
|
| 520 |
+
1 2
|
| 521 |
+
2 2 3
|
| 522 |
+
3 2 3 # 3 fields
|
| 523 |
+
4 2 3# 3 fields
|
| 524 |
+
5 2 # 2 fields
|
| 525 |
+
6 2# 2 fields
|
| 526 |
+
7 # 1 field, NaN
|
| 527 |
+
8# 1 field, NaN
|
| 528 |
+
9 2 3 # skipped line
|
| 529 |
+
# comment"""
|
| 530 |
+
with tm.assert_produces_warning(
|
| 531 |
+
ParserWarning, match="Skipping line", check_stacklevel=False
|
| 532 |
+
):
|
| 533 |
+
df = parser.read_csv(
|
| 534 |
+
StringIO(test_input),
|
| 535 |
+
comment="#",
|
| 536 |
+
header=None,
|
| 537 |
+
delimiter="\\s+",
|
| 538 |
+
skiprows=0,
|
| 539 |
+
on_bad_lines="warn",
|
| 540 |
+
)
|
| 541 |
+
expected = pd.DataFrame([[1, 2], [5, 2], [6, 2], [7, np.nan], [8, np.nan]])
|
| 542 |
+
tm.assert_frame_equal(df, expected)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def test_file_like_no_next(c_parser_only):
|
| 546 |
+
# gh-16530: the file-like need not have a "next" or "__next__"
|
| 547 |
+
# attribute despite having an "__iter__" attribute.
|
| 548 |
+
#
|
| 549 |
+
# NOTE: This is only true for the C engine, not Python engine.
|
| 550 |
+
class NoNextBuffer(StringIO):
|
| 551 |
+
def __next__(self):
|
| 552 |
+
raise AttributeError("No next method")
|
| 553 |
+
|
| 554 |
+
next = __next__
|
| 555 |
+
|
| 556 |
+
parser = c_parser_only
|
| 557 |
+
data = "a\n1"
|
| 558 |
+
|
| 559 |
+
expected = pd.DataFrame({"a": [1]})
|
| 560 |
+
result = parser.read_csv(NoNextBuffer(data))
|
| 561 |
+
|
| 562 |
+
tm.assert_frame_equal(result, expected)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def test_buffer_rd_bytes_bad_unicode(c_parser_only):
|
| 566 |
+
# see gh-22748
|
| 567 |
+
t = BytesIO(b"\xb0")
|
| 568 |
+
t = TextIOWrapper(t, encoding="UTF-8", errors="surrogateescape")
|
| 569 |
+
msg = "'utf-8' codec can't encode character"
|
| 570 |
+
with pytest.raises(UnicodeError, match=msg):
|
| 571 |
+
c_parser_only.read_csv(t, encoding="UTF-8")
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
@pytest.mark.parametrize("tar_suffix", [".tar", ".tar.gz"])
|
| 575 |
+
def test_read_tarfile(c_parser_only, datapath, tar_suffix):
|
| 576 |
+
# see gh-16530
|
| 577 |
+
#
|
| 578 |
+
# Unfortunately, Python's CSV library can't handle
|
| 579 |
+
# tarfile objects (expects string, not bytes when
|
| 580 |
+
# iterating through a file-like).
|
| 581 |
+
parser = c_parser_only
|
| 582 |
+
tar_path = datapath("io", "parser", "data", "tar_csv" + tar_suffix)
|
| 583 |
+
|
| 584 |
+
with tarfile.open(tar_path, "r") as tar:
|
| 585 |
+
data_file = tar.extractfile("tar_data.csv")
|
| 586 |
+
|
| 587 |
+
out = parser.read_csv(data_file)
|
| 588 |
+
expected = pd.DataFrame({"a": [1]})
|
| 589 |
+
tm.assert_frame_equal(out, expected)
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def test_chunk_whitespace_on_boundary(c_parser_only):
|
| 593 |
+
# see gh-9735: this issue is C parser-specific (bug when
|
| 594 |
+
# parsing whitespace and characters at chunk boundary)
|
| 595 |
+
#
|
| 596 |
+
# This test case has a field too large for the Python parser / CSV library.
|
| 597 |
+
parser = c_parser_only
|
| 598 |
+
|
| 599 |
+
chunk1 = "a" * (1024 * 256 - 2) + "\na"
|
| 600 |
+
chunk2 = "\n a"
|
| 601 |
+
result = parser.read_csv(StringIO(chunk1 + chunk2), header=None)
|
| 602 |
+
|
| 603 |
+
expected = pd.DataFrame(["a" * (1024 * 256 - 2), "a", " a"])
|
| 604 |
+
tm.assert_frame_equal(result, expected)
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
@pytest.mark.skipif(WASM, reason="limited file system access on WASM")
|
| 608 |
+
def test_file_handles_mmap(c_parser_only, csv1):
|
| 609 |
+
# gh-14418
|
| 610 |
+
#
|
| 611 |
+
# Don't close user provided file handles.
|
| 612 |
+
parser = c_parser_only
|
| 613 |
+
|
| 614 |
+
with open(csv1, encoding="utf-8") as f:
|
| 615 |
+
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m:
|
| 616 |
+
parser.read_csv(m)
|
| 617 |
+
assert not m.closed
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def test_file_binary_mode(c_parser_only, temp_file):
|
| 621 |
+
# see gh-23779
|
| 622 |
+
parser = c_parser_only
|
| 623 |
+
expected = pd.DataFrame([[1, 2, 3], [4, 5, 6]])
|
| 624 |
+
|
| 625 |
+
path = temp_file
|
| 626 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 627 |
+
f.write("1,2,3\n4,5,6")
|
| 628 |
+
|
| 629 |
+
with open(path, "rb") as f:
|
| 630 |
+
result = parser.read_csv(f, header=None)
|
| 631 |
+
tm.assert_frame_equal(result, expected)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def test_binary_file_handle_avoids_text_wrapping(c_parser_only):
|
| 635 |
+
# GH#46823 - binary file-like objects should not be wrapped in
|
| 636 |
+
# TextIOWrapper when using the C engine, as the small internal buffer
|
| 637 |
+
# causes many small reads that are very slow for remote filesystems.
|
| 638 |
+
parser = c_parser_only
|
| 639 |
+
data = BytesIO(b"a,b\n1,2\n3,4\n")
|
| 640 |
+
result = parser.read_csv(data)
|
| 641 |
+
expected = pd.DataFrame({"a": [1, 3], "b": [2, 4]})
|
| 642 |
+
tm.assert_frame_equal(result, expected)
|
| 643 |
+
|
| 644 |
+
# Verify the handle was not wrapped in TextIOWrapper
|
| 645 |
+
data = BytesIO(b"a,b\n1,2\n3,4\n")
|
| 646 |
+
with parser.read_csv(data, chunksize=2) as reader:
|
| 647 |
+
assert not isinstance(reader.handles.handle, TextIOWrapper)
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
def test_unix_style_breaks(c_parser_only, temp_file):
|
| 651 |
+
# GH 11020
|
| 652 |
+
parser = c_parser_only
|
| 653 |
+
path = temp_file
|
| 654 |
+
with open(path, "w", newline="\n", encoding="utf-8") as f:
|
| 655 |
+
f.write("blah\n\ncol_1,col_2,col_3\n\n")
|
| 656 |
+
result = parser.read_csv(path, skiprows=2, encoding="utf-8", engine="c")
|
| 657 |
+
expected = pd.DataFrame(columns=["col_1", "col_2", "col_3"])
|
| 658 |
+
tm.assert_frame_equal(result, expected)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
@pytest.mark.parametrize("float_precision", [None, "legacy", "high", "round_trip"])
|
| 662 |
+
@pytest.mark.parametrize(
|
| 663 |
+
"data,thousands,decimal",
|
| 664 |
+
[
|
| 665 |
+
(
|
| 666 |
+
"""A|B|C
|
| 667 |
+
1|2,334.01|5
|
| 668 |
+
10|13|10.
|
| 669 |
+
""",
|
| 670 |
+
",",
|
| 671 |
+
".",
|
| 672 |
+
),
|
| 673 |
+
(
|
| 674 |
+
"""A|B|C
|
| 675 |
+
1|2.334,01|5
|
| 676 |
+
10|13|10,
|
| 677 |
+
""",
|
| 678 |
+
".",
|
| 679 |
+
",",
|
| 680 |
+
),
|
| 681 |
+
],
|
| 682 |
+
)
|
| 683 |
+
def test_1000_sep_with_decimal(
|
| 684 |
+
c_parser_only, data, thousands, decimal, float_precision
|
| 685 |
+
):
|
| 686 |
+
parser = c_parser_only
|
| 687 |
+
expected = pd.DataFrame({"A": [1, 10], "B": [2334.01, 13], "C": [5, 10.0]})
|
| 688 |
+
|
| 689 |
+
warn = Pandas4Warning if float_precision is not None else None
|
| 690 |
+
with tm.assert_produces_warning(
|
| 691 |
+
warn, match="float_precision", check_stacklevel=False
|
| 692 |
+
):
|
| 693 |
+
result = parser.read_csv(
|
| 694 |
+
StringIO(data),
|
| 695 |
+
sep="|",
|
| 696 |
+
thousands=thousands,
|
| 697 |
+
decimal=decimal,
|
| 698 |
+
float_precision=float_precision,
|
| 699 |
+
)
|
| 700 |
+
tm.assert_frame_equal(result, expected)
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
def test_float_precision_options(c_parser_only):
|
| 704 |
+
# GH 17154, 36228
|
| 705 |
+
parser = c_parser_only
|
| 706 |
+
s = "foo\n243.164\n"
|
| 707 |
+
df = parser.read_csv(StringIO(s))
|
| 708 |
+
depr_msg = "float_precision"
|
| 709 |
+
with tm.assert_produces_warning(
|
| 710 |
+
Pandas4Warning, match=depr_msg, check_stacklevel=False
|
| 711 |
+
):
|
| 712 |
+
df2 = parser.read_csv(StringIO(s), float_precision="high")
|
| 713 |
+
|
| 714 |
+
tm.assert_frame_equal(df, df2)
|
| 715 |
+
|
| 716 |
+
# "legacy" now uses the same precise converter as "high"
|
| 717 |
+
with tm.assert_produces_warning(
|
| 718 |
+
Pandas4Warning, match=depr_msg, check_stacklevel=False
|
| 719 |
+
):
|
| 720 |
+
df3 = parser.read_csv(StringIO(s), float_precision="legacy")
|
| 721 |
+
tm.assert_frame_equal(df, df3)
|
| 722 |
+
|
| 723 |
+
msg = "Unrecognized float_precision option: junk"
|
| 724 |
+
|
| 725 |
+
with pytest.raises(ValueError, match=msg):
|
| 726 |
+
with tm.assert_produces_warning(
|
| 727 |
+
Pandas4Warning, match=depr_msg, check_stacklevel=False
|
| 728 |
+
):
|
| 729 |
+
parser.read_csv(StringIO(s), float_precision="junk")
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
# The C tokenizer copies runs of ordinary characters in bulk, scanning 16
|
| 733 |
+
# bytes at a time for special characters (delimiter, line terminator, quote,
|
| 734 |
+
# escape, comment). Fields shorter than 16 bytes never enter that stride, so
|
| 735 |
+
# the tests below deliberately use fields that span the 16-byte boundary to
|
| 736 |
+
# exercise the vectorized scan and its byte-offset arithmetic.
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
@pytest.mark.parametrize("length", [14, 15, 16, 17, 18, 31, 32, 33, 47, 48, 49, 64])
|
| 740 |
+
def test_bulk_scan_unquoted_field_boundaries(c_parser_only, length):
|
| 741 |
+
# GH#64515: a delimiter or line terminator ending a long unquoted field
|
| 742 |
+
# must be detected at the correct offset within a 16-byte scan chunk.
|
| 743 |
+
parser = c_parser_only
|
| 744 |
+
col_a = "a" * length
|
| 745 |
+
col_b = "b" * length
|
| 746 |
+
col_c = "c" * length
|
| 747 |
+
data = f"A,B,C\n{col_a},{col_b},{col_c}\n{col_a},{col_b},{col_c}\n"
|
| 748 |
+
result = parser.read_csv(StringIO(data))
|
| 749 |
+
expected = pd.DataFrame(
|
| 750 |
+
{"A": [col_a, col_a], "B": [col_b, col_b], "C": [col_c, col_c]}
|
| 751 |
+
)
|
| 752 |
+
tm.assert_frame_equal(result, expected)
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
@pytest.mark.parametrize("length", [8, 15, 16, 17, 32, 33, 48])
|
| 756 |
+
def test_bulk_scan_quoted_field_boundaries(c_parser_only, length):
|
| 757 |
+
# GH#64515: inside a quoted field only the quote/escape characters are
|
| 758 |
+
# special, so an embedded delimiter and an embedded line terminator that
|
| 759 |
+
# fall past the first 16-byte chunk must be copied verbatim rather than
|
| 760 |
+
# ending the field or the record.
|
| 761 |
+
parser = c_parser_only
|
| 762 |
+
inner = ("a" * length) + "," + ("b" * length) + "\n" + ("c" * length)
|
| 763 |
+
data = 'col\n"' + inner + '"\n'
|
| 764 |
+
result = parser.read_csv(StringIO(data))
|
| 765 |
+
expected = pd.DataFrame({"col": [inner]})
|
| 766 |
+
tm.assert_frame_equal(result, expected)
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
@pytest.mark.parametrize("length", [15, 16, 17, 32, 40])
|
| 770 |
+
def test_bulk_scan_comment_char_boundary(c_parser_only, length):
|
| 771 |
+
# GH#64515: a comment character terminating a long unquoted field must be
|
| 772 |
+
# detected at its offset within a 16-byte scan chunk.
|
| 773 |
+
parser = c_parser_only
|
| 774 |
+
field = "a" * length
|
| 775 |
+
data = f"A\n{field}# a fairly long trailing comment to skip\n"
|
| 776 |
+
result = parser.read_csv(StringIO(data), comment="#")
|
| 777 |
+
expected = pd.DataFrame({"A": [field]})
|
| 778 |
+
tm.assert_frame_equal(result, expected)
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
def test_invalid_utf8_raises(c_parser_only):
|
| 782 |
+
# GH#65283: the pyarrow string fast path memcpys raw bytes into arrow
|
| 783 |
+
# buffers; ensure invalid UTF-8 still raises like the object path
|
| 784 |
+
parser = c_parser_only
|
| 785 |
+
data = BytesIO(b"col\nabc\n\xff\xfe\n")
|
| 786 |
+
with pytest.raises(UnicodeDecodeError, match="invalid start byte"):
|
| 787 |
+
parser.read_csv(data)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
@pytest.mark.filterwarnings(
|
| 791 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 792 |
+
)
|
| 793 |
+
def test_string_storage_python_consistent(c_parser_only):
|
| 794 |
+
# GH#65283: the pyarrow string fast path must not produce an
|
| 795 |
+
# ArrowStringArray when mode.string_storage="python"
|
| 796 |
+
pytest.importorskip("pyarrow")
|
| 797 |
+
parser = c_parser_only
|
| 798 |
+
with pd.option_context(
|
| 799 |
+
"future.infer_string", True, "mode.string_storage", "python"
|
| 800 |
+
):
|
| 801 |
+
result = parser.read_csv(StringIO("col\nabc\nxyz\n"))
|
| 802 |
+
arr = result["col"].array
|
| 803 |
+
assert isinstance(arr.dtype, pd.StringDtype)
|
| 804 |
+
assert arr.dtype.storage == "python"
|
| 805 |
+
assert type(arr) is arr.dtype.construct_array_type()
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
@pytest.mark.parametrize("lineterm", ["\n", "\r\n"])
|
| 809 |
+
def test_block_lane_blank_and_whitespace_lines(c_parser_only, lineterm):
|
| 810 |
+
# The SIMD block fast lane defers lines led by blanks (or entirely
|
| 811 |
+
# blank) to the state machine; a no-progress lane exit must preserve
|
| 812 |
+
# the post-WHITESPACE_LINE state instead of ping-ponging (GH#66274).
|
| 813 |
+
parser = c_parser_only
|
| 814 |
+
rows = []
|
| 815 |
+
for i in range(200):
|
| 816 |
+
if i % 7 == 0:
|
| 817 |
+
rows.append("") # blank line, skipped by skip_blank_lines
|
| 818 |
+
elif i % 11 == 0:
|
| 819 |
+
rows.append(f" {i},{i * 2},{i * 3}") # leading whitespace
|
| 820 |
+
elif i % 13 == 0:
|
| 821 |
+
# trailing whitespace is inert for the lane (only line *starts*
|
| 822 |
+
# can begin a WHITESPACE_LINE); included to prove it
|
| 823 |
+
rows.append(f"{i},{i * 2},{i * 3} ")
|
| 824 |
+
else:
|
| 825 |
+
rows.append(f"{i},{i * 2},{i * 3}")
|
| 826 |
+
data = "a,b,c" + lineterm + lineterm.join(rows) + lineterm
|
| 827 |
+
result = parser.read_csv(StringIO(data))
|
| 828 |
+
expected = pd.read_csv(StringIO(data), engine="python")
|
| 829 |
+
tm.assert_frame_equal(result, expected)
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
def test_block_lane_chunked_reads_match(c_parser_only):
|
| 833 |
+
# A line-limited tokenize call can stop mid-lane; the parser state must
|
| 834 |
+
# be reset so the next chunk resumes cleanly (GH#66274).
|
| 835 |
+
parser = c_parser_only
|
| 836 |
+
n_rows = 500
|
| 837 |
+
data = "a,b\n" + "\n".join(f"value{i:04d},{i}" for i in range(n_rows)) + "\n"
|
| 838 |
+
expected = parser.read_csv(StringIO(data))
|
| 839 |
+
with parser.read_csv(StringIO(data), chunksize=7) as reader:
|
| 840 |
+
result = pd.concat(reader, ignore_index=True)
|
| 841 |
+
tm.assert_frame_equal(result, expected)
|
| 842 |
+
result = parser.read_csv(StringIO(data), low_memory=True)
|
| 843 |
+
tm.assert_frame_equal(result, expected)
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def test_block_lane_crlf_pairs_at_block_edges(c_parser_only):
|
| 847 |
+
# \r\n pairs are consumed in-lane; pairs split across a 16-byte block
|
| 848 |
+
# boundary or bare \r must defer to the state machine. Vary field
|
| 849 |
+
# widths so terminators land on every block offset.
|
| 850 |
+
parser = c_parser_only
|
| 851 |
+
rows = [f"{'x' * (i % 23)},{i}" for i in range(300)]
|
| 852 |
+
data = "a,b\r\n" + "\r\n".join(rows) + "\r\n"
|
| 853 |
+
result = parser.read_csv(StringIO(data))
|
| 854 |
+
expected = parser.read_csv(StringIO(data.replace("\r\n", "\n")))
|
| 855 |
+
tm.assert_frame_equal(result, expected)
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
def test_block_lane_quoted_specials_mid_block(c_parser_only):
|
| 859 |
+
# Any block containing a quote falls back to the state machine; quoted
|
| 860 |
+
# fields with embedded delimiters/newlines must round-trip regardless
|
| 861 |
+
# of their offset inside a 16-byte block.
|
| 862 |
+
parser = c_parser_only
|
| 863 |
+
rows = []
|
| 864 |
+
for i in range(200):
|
| 865 |
+
pad = "y" * (i % 19)
|
| 866 |
+
rows.append(f'{pad},"emb,{i}\nnext",{i}')
|
| 867 |
+
data = "a,b,c\n" + "\n".join(rows) + "\n"
|
| 868 |
+
result = parser.read_csv(StringIO(data))
|
| 869 |
+
expected = pd.read_csv(StringIO(data), engine="python")
|
| 870 |
+
tm.assert_frame_equal(result, expected)
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def test_block_lane_nrows_short_row(c_parser_only):
|
| 874 |
+
# GH#66274: the lane must honor nrows when the row hitting the limit is
|
| 875 |
+
# a short row (synthetic trailing fields); the over-wide final row raises
|
| 876 |
+
# only if the reader ignores nrows.
|
| 877 |
+
# This was originally tuned so that the short rows outran the stream
|
| 878 |
+
# reservation and the lane's capacity guard fired mid-parse. GH#66657
|
| 879 |
+
# made the padding restore that reservation, so the guard can no longer
|
| 880 |
+
# trip here -- the nrows/short-row path is what this still covers.
|
| 881 |
+
parser = c_parser_only
|
| 882 |
+
data = "a,b,c,d\n" + "2222\n" + "1\n" * 55_000 + "1,2,3,4,5,6,7,8,9,10\n"
|
| 883 |
+
for nrows in range(52_415, 52_431):
|
| 884 |
+
result = parser.read_csv(StringIO(data), nrows=nrows)
|
| 885 |
+
assert len(result) == nrows
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
def test_block_lane_nrows_checked_before_deferring(c_parser_only):
|
| 889 |
+
# GH#66274: block_after_line must test the line limit before any of its
|
| 890 |
+
# bails, because end_line has already counted the line and the state
|
| 891 |
+
# machine's ==-based limit check would never match again -- so a deferral
|
| 892 |
+
# taken first makes the reader overshoot nrows. Reaches the deferral via
|
| 893 |
+
# the whitespace-line probe (the leading blank on row 5); the sibling bail
|
| 894 |
+
# for a full token stream can no longer coincide with a limit hit now that
|
| 895 |
+
# GH#66657 keeps slack ahead of the unconsumed input.
|
| 896 |
+
# nrows is pinned: 4 stops exactly on the whitespace row, which is the
|
| 897 |
+
# only value that both reaches the probe and stays clear of the over-wide
|
| 898 |
+
# final row (that row legitimately raises for nrows > 5).
|
| 899 |
+
parser = c_parser_only
|
| 900 |
+
over_wide = ",".join(str(k) for k in range(12))
|
| 901 |
+
data = "a,b,c,d\n" + "1,2,3,4\n" * 4 + " 9,9,9\n" + over_wide + "\n"
|
| 902 |
+
result = parser.read_csv(StringIO(data), nrows=4)
|
| 903 |
+
expected = pd.DataFrame(
|
| 904 |
+
[[1, 2, 3, 4]] * 4, columns=["a", "b", "c", "d"], dtype="int64"
|
| 905 |
+
)
|
| 906 |
+
tm.assert_frame_equal(result, expected)
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def test_short_rows_before_wide_field(c_parser_only):
|
| 910 |
+
# GH#66657: closing the missing fields of a short row takes token stream
|
| 911 |
+
# space without consuming input, so a run of short rows used to eat into
|
| 912 |
+
# the reservation the unchecked bulk copies rely on. The wide field then
|
| 913 |
+
# overran the stream buffer and came back truncated.
|
| 914 |
+
parser = c_parser_only
|
| 915 |
+
wide = "X" * 100_000
|
| 916 |
+
data = "a\n" * 40 + wide + "\n"
|
| 917 |
+
names = [f"c{i}" for i in range(5000)]
|
| 918 |
+
result = parser.read_csv(StringIO(data), header=None, names=names)
|
| 919 |
+
assert result.shape == (41, 5000)
|
| 920 |
+
# length first: the truncation is off-by-one, and a bare inequality on a
|
| 921 |
+
# 100k-char field reports nothing useful
|
| 922 |
+
assert len(result.iloc[40, 0]) == len(wide)
|
| 923 |
+
assert result.iloc[40, 0] == wide
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
@pytest.mark.parametrize("terminator", ["\n", "\r\n", "\r"])
|
| 927 |
+
@pytest.mark.parametrize("n_cols", range(5, 12))
|
| 928 |
+
@pytest.mark.parametrize("n_short", [5, 8, 20])
|
| 929 |
+
def test_short_rows_do_not_exhaust_token_reservation(
|
| 930 |
+
c_parser_only, n_cols, n_short, terminator
|
| 931 |
+
):
|
| 932 |
+
# GH#66657: the padding also consumes one word per closed field, so short
|
| 933 |
+
# rows ate the word-vector reservation the same way they ate the stream's,
|
| 934 |
+
# and end_field has no growth path -- it just reports "Buffer overflow
|
| 935 |
+
# caught - possible malformed input file" on ordinary ragged input.
|
| 936 |
+
# Swept rather than pinned to the handful of shapes that reproduced: which
|
| 937 |
+
# ones do depends on where the buffers' power-of-two growth lands, so a
|
| 938 |
+
# pinned pair would quietly stop covering this if that sizing changed.
|
| 939 |
+
# Each terminator reaches end_line through a call site with its own
|
| 940 |
+
# expression for the unconsumed input, so an off-by-one in one of them
|
| 941 |
+
# survives testing the others.
|
| 942 |
+
parser = c_parser_only
|
| 943 |
+
header = ",".join(f"c{i}" for i in range(n_cols))
|
| 944 |
+
row = ",".join("1" for _ in range(n_cols))
|
| 945 |
+
body = header + "{0}" + "1{0}" * n_short + row + "{0}"
|
| 946 |
+
result = parser.read_csv(StringIO(body.format(terminator)))
|
| 947 |
+
# the terminator must not change the values; a lone \r is not readable
|
| 948 |
+
# through StringIO by the python engine, so oracle on the \n spelling
|
| 949 |
+
expected = pd.read_csv(StringIO(body.format("\n")), engine="python")
|
| 950 |
+
tm.assert_frame_equal(result, expected)
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
def test_short_rows_block_lane_tail_recopy_defer(c_parser_only):
|
| 954 |
+
# Not a GH#66657 reproducer -- this passes without that fix. It pins the
|
| 955 |
+
# one shape that reaches the block lane's tail-re-copy deferral, which
|
| 956 |
+
# GH#66657 turned from a rare capacity bail into the routine path: the
|
| 957 |
+
# lane hands the rest of the block back to the state machine mid-block,
|
| 958 |
+
# and that handoff carries a resume position, so getting it wrong
|
| 959 |
+
# duplicates or drops rows rather than raising. The sweep above never
|
| 960 |
+
# reaches the branch.
|
| 961 |
+
parser = c_parser_only
|
| 962 |
+
data = "c0,c1,c2,c3\n" + "1\n" * 9
|
| 963 |
+
result = parser.read_csv(StringIO(data))
|
| 964 |
+
expected = pd.read_csv(StringIO(data), engine="python")
|
| 965 |
+
tm.assert_frame_equal(result, expected)
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
@pytest.mark.parametrize("kwargs", [{}, {"dtype_backend": "pyarrow"}])
|
| 969 |
+
def test_pyarrow_string_non_ascii_eager_wrap_mutable(c_parser_only, kwargs):
|
| 970 |
+
# GH#66277: the eager wrap that bypasses the ExtensionArray constructor
|
| 971 |
+
# for non-ASCII columns did not set _cache, so mutating the result raised
|
| 972 |
+
# AttributeError (reachable with low_memory=False, where the array
|
| 973 |
+
# reaches the frame without an intermediate concat)
|
| 974 |
+
pytest.importorskip("pyarrow")
|
| 975 |
+
parser = c_parser_only
|
| 976 |
+
result = parser.read_csv(StringIO("a\ncafé\nnaïve\n"), **kwargs)
|
| 977 |
+
arr = result["a"].array
|
| 978 |
+
arr[0] = "x"
|
| 979 |
+
arr.sort()
|
| 980 |
+
assert list(arr) == ["naïve", "x"]
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
@pytest.mark.parametrize("tail", ["", "café\nnaïve\n" * 4])
|
| 984 |
+
def test_low_memory_string_chunks_combined(c_parser_only, monkeypatch, tail):
|
| 985 |
+
# GH#66277: with low_memory=True, deferred string chunks combine into a
|
| 986 |
+
# single column at the end of the read; all-ASCII chunks take the
|
| 987 |
+
# zero-copy path while non-ASCII chunks are wrapped eagerly, and either
|
| 988 |
+
# mix must match a single-chunk read
|
| 989 |
+
pytest.importorskip("pyarrow")
|
| 990 |
+
parser = c_parser_only
|
| 991 |
+
data = "a\n" + "foo\nbar\nNA\nbaz\n" * 8 + tail
|
| 992 |
+
expected = parser.read_csv(StringIO(data))
|
| 993 |
+
with monkeypatch.context() as m:
|
| 994 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", 2**3)
|
| 995 |
+
result = parser.read_csv(StringIO(data))
|
| 996 |
+
tm.assert_frame_equal(result, expected)
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
@pytest.mark.parametrize("kwargs", [{}, {"dtype_backend": "pyarrow"}])
|
| 1000 |
+
@pytest.mark.filterwarnings(
|
| 1001 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 1002 |
+
)
|
| 1003 |
+
def test_pyarrow_string_fast_path_mutable(kwargs):
|
| 1004 |
+
# GH#66619: the fast path builds its result without going through the
|
| 1005 |
+
# ExtensionArray constructor, so it must set every attribute the
|
| 1006 |
+
# constructor does; omitting _cache made mutating the result raise
|
| 1007 |
+
# AttributeError. low_memory=False is required, not incidental: the
|
| 1008 |
+
# low-memory path concatenates its chunks, which rebuilds the array and
|
| 1009 |
+
# would hide the omission.
|
| 1010 |
+
pytest.importorskip("pyarrow")
|
| 1011 |
+
# pinned rather than inherited: the default-kwargs case would otherwise get
|
| 1012 |
+
# an object-dtype column, and stop exercising the fast path at all, in the
|
| 1013 |
+
# PANDAS_FUTURE_INFER_STRING=0 build.
|
| 1014 |
+
with pd.option_context("future.infer_string", True):
|
| 1015 |
+
result = pd.read_csv(
|
| 1016 |
+
StringIO("a\nfoo\nbar\n"), engine="c", low_memory=False, **kwargs
|
| 1017 |
+
)
|
| 1018 |
+
arr = result["a"].array
|
| 1019 |
+
arr[0] = "zzz"
|
| 1020 |
+
arr.sort()
|
| 1021 |
+
assert list(arr) == ["bar", "zzz"]
|
| 1022 |
+
|
| 1023 |
+
|
| 1024 |
+
@pytest.mark.parametrize("kwargs", [{}, {"dtype_backend": "pyarrow"}])
|
| 1025 |
+
@pytest.mark.filterwarnings(
|
| 1026 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 1027 |
+
)
|
| 1028 |
+
def test_pyarrow_string_fast_path_attrs_match_constructor(kwargs):
|
| 1029 |
+
# GH#66619: the fast path sets the instance attributes itself instead of
|
| 1030 |
+
# calling __init__, so it has to track whatever set the constructor
|
| 1031 |
+
# establishes. Adding an attribute to ArrowStringArray.__init__ or
|
| 1032 |
+
# ArrowExtensionArray.__init__ without teaching parsers.pyx about it should
|
| 1033 |
+
# fail here rather than silently producing a half-built array.
|
| 1034 |
+
pytest.importorskip("pyarrow")
|
| 1035 |
+
with pd.option_context("future.infer_string", True):
|
| 1036 |
+
result = pd.read_csv(
|
| 1037 |
+
StringIO("a\nfoo\nbar\n"), engine="c", low_memory=False, **kwargs
|
| 1038 |
+
)
|
| 1039 |
+
arr = result["a"].array
|
| 1040 |
+
expected = type(arr)(arr._pa_array)
|
| 1041 |
+
assert vars(arr).keys() == vars(expected).keys()
|
| 1042 |
+
|
| 1043 |
+
|
| 1044 |
+
@pytest.mark.filterwarnings(
|
| 1045 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 1046 |
+
)
|
| 1047 |
+
def test_pyarrow_string_iterator_dtype_stable_across_chunks():
|
| 1048 |
+
# GH#66619: a reader resolves its pyarrow target once, when it converts its
|
| 1049 |
+
# first string column, so every chunk of one read gets the same dtype even
|
| 1050 |
+
# if the options change mid-iteration. Previously the target was looked up
|
| 1051 |
+
# per chunk and the second chunk here came back object-dtype.
|
| 1052 |
+
pytest.importorskip("pyarrow")
|
| 1053 |
+
with pd.option_context("future.infer_string", True):
|
| 1054 |
+
reader = pd.read_csv(
|
| 1055 |
+
StringIO("a\nfoo\nbar\n"), engine="c", chunksize=1, iterator=True
|
| 1056 |
+
)
|
| 1057 |
+
first = next(reader)
|
| 1058 |
+
with pd.option_context("future.infer_string", False):
|
| 1059 |
+
second = next(reader)
|
| 1060 |
+
assert first["a"].dtype == pd.StringDtype(na_value=np.nan)
|
| 1061 |
+
assert second["a"].dtype == first["a"].dtype
|
| 1062 |
+
|
| 1063 |
+
|
| 1064 |
+
@pytest.mark.parametrize("kwargs", [{}, {"dtype_backend": "pyarrow"}])
|
| 1065 |
+
@pytest.mark.filterwarnings(
|
| 1066 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 1067 |
+
)
|
| 1068 |
+
def test_pyarrow_string_fast_path_token_width_tiers(kwargs):
|
| 1069 |
+
# GH#66756: the fast path copies a short token at a compile-time-constant
|
| 1070 |
+
# 16 or 32 bytes and lets the copy overshoot into buffer slack, so a token
|
| 1071 |
+
# one byte either side of a tier boundary is where a mis-sized copy would
|
| 1072 |
+
# truncate the value or trail the following token's bytes into it.
|
| 1073 |
+
pa = pytest.importorskip("pyarrow")
|
| 1074 |
+
widths = [1, 2, 15, 16, 17, 31, 32, 33, 64]
|
| 1075 |
+
values = [
|
| 1076 |
+
"".join(chr(ord("a") + pos % 26) for pos in range(width)) for width in widths
|
| 1077 |
+
]
|
| 1078 |
+
data = "a,b\n" + "".join(f"{value},{value.upper()}\n" for value in values)
|
| 1079 |
+
# The fast path requires infer_string *and* pyarrow storage, so pin both;
|
| 1080 |
+
# the dtype check below turns any silent fall-back to the object path
|
| 1081 |
+
# (which would satisfy the value assertions) into a loud failure.
|
| 1082 |
+
with pd.option_context(
|
| 1083 |
+
"future.infer_string", True, "mode.string_storage", "pyarrow"
|
| 1084 |
+
):
|
| 1085 |
+
result = pd.read_csv(StringIO(data), engine="c", low_memory=False, **kwargs)
|
| 1086 |
+
expected_dtype = (
|
| 1087 |
+
pd.ArrowDtype(pa.string())
|
| 1088 |
+
if kwargs
|
| 1089 |
+
else pd.StringDtype("pyarrow", na_value=np.nan)
|
| 1090 |
+
)
|
| 1091 |
+
assert result["a"].dtype == expected_dtype
|
| 1092 |
+
assert result["a"].tolist() == values
|
| 1093 |
+
assert result["b"].tolist() == [value.upper() for value in values]
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
@pytest.mark.parametrize("kwargs", [{}, {"dtype_backend": "pyarrow"}])
|
| 1097 |
+
@pytest.mark.filterwarnings(
|
| 1098 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 1099 |
+
)
|
| 1100 |
+
def test_pyarrow_string_fast_path_column_outgrows_size_estimate(kwargs):
|
| 1101 |
+
# GH#66756: the fast path sizes its data buffer from the column's leading
|
| 1102 |
+
# tokens and grows it mid-pass when that estimate falls short, re-copying
|
| 1103 |
+
# what it has already written. A column whose first rows are far narrower
|
| 1104 |
+
# than the rest takes that path repeatedly, where a stale buffer pointer or
|
| 1105 |
+
# an undersized grow would corrupt everything written before it.
|
| 1106 |
+
pa = pytest.importorskip("pyarrow")
|
| 1107 |
+
values = ["ab"] * 20 + [f"{num:x}" * 900 for num in range(1, 200)]
|
| 1108 |
+
data = "a\n" + "".join(f"{value}\n" for value in values)
|
| 1109 |
+
with pd.option_context(
|
| 1110 |
+
"future.infer_string", True, "mode.string_storage", "pyarrow"
|
| 1111 |
+
):
|
| 1112 |
+
result = pd.read_csv(StringIO(data), engine="c", low_memory=False, **kwargs)
|
| 1113 |
+
expected_dtype = (
|
| 1114 |
+
pd.ArrowDtype(pa.string())
|
| 1115 |
+
if kwargs
|
| 1116 |
+
else pd.StringDtype("pyarrow", na_value=np.nan)
|
| 1117 |
+
)
|
| 1118 |
+
assert result["a"].dtype == expected_dtype
|
| 1119 |
+
assert result["a"].tolist() == values
|
| 1120 |
+
|
| 1121 |
+
|
| 1122 |
+
@pytest.mark.filterwarnings(
|
| 1123 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 1124 |
+
)
|
| 1125 |
+
@pytest.mark.parametrize("kwargs", [{}, {"dtype_backend": "pyarrow"}])
|
| 1126 |
+
@pytest.mark.parametrize("low_memory", [True, False])
|
| 1127 |
+
def test_pyarrow_string_fast_path_batched_columns(kwargs, low_memory):
|
| 1128 |
+
# GH#68379: string columns are converted together in one sweep, so this
|
| 1129 |
+
# mixes what each still handles on its own within it: per-column na_values,
|
| 1130 |
+
# an NA-free column (validity buffer dropped, unlike its neighbours'),
|
| 1131 |
+
# non-ASCII bytes, a numeric column between them, a short row and usecols.
|
| 1132 |
+
pa = pytest.importorskip("pyarrow")
|
| 1133 |
+
data = (
|
| 1134 |
+
"a,b,c,d,e\n"
|
| 1135 |
+
"foo,1,café,x,skip\n"
|
| 1136 |
+
"bar,2,naïve,y,skip\n"
|
| 1137 |
+
"present,3,\n"
|
| 1138 |
+
"baz,4,zzz,,skip\n"
|
| 1139 |
+
)
|
| 1140 |
+
with pd.option_context(
|
| 1141 |
+
"future.infer_string", True, "mode.string_storage", "pyarrow"
|
| 1142 |
+
):
|
| 1143 |
+
result = pd.read_csv(
|
| 1144 |
+
StringIO(data),
|
| 1145 |
+
engine="c",
|
| 1146 |
+
low_memory=low_memory,
|
| 1147 |
+
usecols=["a", "b", "c", "d"],
|
| 1148 |
+
na_values={"c": ["zzz"], "d": ["y"]},
|
| 1149 |
+
**kwargs,
|
| 1150 |
+
)
|
| 1151 |
+
if kwargs:
|
| 1152 |
+
str_dtype = pd.ArrowDtype(pa.string())
|
| 1153 |
+
int_dtype = "int64[pyarrow]"
|
| 1154 |
+
else:
|
| 1155 |
+
str_dtype = pd.StringDtype("pyarrow", na_value=np.nan)
|
| 1156 |
+
int_dtype = "int64"
|
| 1157 |
+
# inside the context so the columns Index dtype matches the result's
|
| 1158 |
+
expected = pd.DataFrame(
|
| 1159 |
+
{
|
| 1160 |
+
"a": ["foo", "bar", "present", "baz"],
|
| 1161 |
+
"b": [1, 2, 3, 4],
|
| 1162 |
+
"c": ["café", "naïve", None, None],
|
| 1163 |
+
"d": ["x", None, None, None],
|
| 1164 |
+
}
|
| 1165 |
+
).astype({"a": str_dtype, "b": int_dtype, "c": str_dtype, "d": str_dtype})
|
| 1166 |
+
tm.assert_frame_equal(result, expected)
|
| 1167 |
+
|
| 1168 |
+
|
| 1169 |
+
@pytest.mark.filterwarnings(
|
| 1170 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 1171 |
+
)
|
| 1172 |
+
@pytest.mark.parametrize("kwargs", [{}, {"dtype_backend": "pyarrow"}])
|
| 1173 |
+
@pytest.mark.parametrize("chunksize", [None, 10])
|
| 1174 |
+
def test_pyarrow_string_fast_path_batches_columns_together(chunksize, kwargs):
|
| 1175 |
+
# GH#68379: the batched sweep and the per-column path produce identical
|
| 1176 |
+
# output, so nothing else here notices if the queue in _convert_column_data
|
| 1177 |
+
# stops being wired up and every column silently goes back to its own pass.
|
| 1178 |
+
# The chunked read also pins that the queue is re-armed for every chunk.
|
| 1179 |
+
pytest.importorskip("pyarrow")
|
| 1180 |
+
data = "a,b,c,d\n" + "".join(f"p{num},q{num},{num},r{num}\n" for num in range(50))
|
| 1181 |
+
with pd.option_context(
|
| 1182 |
+
"future.infer_string", True, "mode.string_storage", "pyarrow"
|
| 1183 |
+
):
|
| 1184 |
+
reader = pd.read_csv(
|
| 1185 |
+
StringIO(data), engine="c", iterator=True, chunksize=chunksize, **kwargs
|
| 1186 |
+
)
|
| 1187 |
+
with reader:
|
| 1188 |
+
for _ in reader if chunksize else [reader.read()]:
|
| 1189 |
+
pass
|
| 1190 |
+
# the three string columns, converted in one sweep; "c" is numeric
|
| 1191 |
+
assert reader._engine._reader._largest_str_batch == 3
|
| 1192 |
+
|
| 1193 |
+
|
| 1194 |
+
@pytest.mark.filterwarnings(
|
| 1195 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 1196 |
+
)
|
| 1197 |
+
@pytest.mark.parametrize("kwargs", [{}, {"dtype_backend": "pyarrow"}])
|
| 1198 |
+
def test_pyarrow_string_fast_path_batch_spans_row_blocks(kwargs):
|
| 1199 |
+
# GH#68379: the sweep fills every queued column a block of rows at a time,
|
| 1200 |
+
# carrying each column's buffer pointer, capacity and running byte count
|
| 1201 |
+
# across blocks. Here "b" outgrows its size estimate mid-sweep while two
|
| 1202 |
+
# other columns are interleaved with it, so a pointer left stale by the
|
| 1203 |
+
# grow, or a count reloaded from the wrong column, corrupts a neighbour
|
| 1204 |
+
# rather than itself.
|
| 1205 |
+
pa = pytest.importorskip("pyarrow")
|
| 1206 |
+
lead = [f"n{num}" for num in range(500)]
|
| 1207 |
+
# first rows far narrower than the rest, so the estimate falls short
|
| 1208 |
+
grows = ["s"] * 20 + [f"{num:x}" * 400 for num in range(20, 500)]
|
| 1209 |
+
trail = [f"t{num}" for num in range(500)]
|
| 1210 |
+
rows = zip(lead, grows, trail, strict=True)
|
| 1211 |
+
data = "a,b,c\n" + "".join(f"{one},{two},{three}\n" for one, two, three in rows)
|
| 1212 |
+
with pd.option_context(
|
| 1213 |
+
"future.infer_string", True, "mode.string_storage", "pyarrow"
|
| 1214 |
+
):
|
| 1215 |
+
result = pd.read_csv(StringIO(data), engine="c", low_memory=False, **kwargs)
|
| 1216 |
+
expected_dtype = (
|
| 1217 |
+
pd.ArrowDtype(pa.string())
|
| 1218 |
+
if kwargs
|
| 1219 |
+
else pd.StringDtype("pyarrow", na_value=np.nan)
|
| 1220 |
+
)
|
| 1221 |
+
assert list(result.dtypes) == [expected_dtype] * 3
|
| 1222 |
+
assert result["a"].tolist() == lead
|
| 1223 |
+
assert result["b"].tolist() == grows
|
| 1224 |
+
assert result["c"].tolist() == trail
|
| 1225 |
+
|
| 1226 |
+
|
| 1227 |
+
@pytest.mark.filterwarnings(
|
| 1228 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 1229 |
+
)
|
| 1230 |
+
@pytest.mark.parametrize("kwargs", [{}, {"dtype_backend": "pyarrow"}])
|
| 1231 |
+
def test_pyarrow_string_fast_path_batch_mixed_na_filter(kwargs):
|
| 1232 |
+
# GH#68379: "b" reaches the string path from the uint64-overflow fallback,
|
| 1233 |
+
# which passes na_filter=0, so it is queued alongside "a" and "c" with no
|
| 1234 |
+
# validity buffer where theirs have one -- the case where a column's state
|
| 1235 |
+
# leaking across the sweep would dereference NULL rather than corrupt data.
|
| 1236 |
+
pa = pytest.importorskip("pyarrow")
|
| 1237 |
+
data = "a,b,c\nfoo,-1,zzz\nNA,18446744073709551615,qq\nbar,NA,\n"
|
| 1238 |
+
with pd.option_context(
|
| 1239 |
+
"future.infer_string", True, "mode.string_storage", "pyarrow"
|
| 1240 |
+
):
|
| 1241 |
+
reader = pd.read_csv(StringIO(data), engine="c", iterator=True, **kwargs)
|
| 1242 |
+
with reader:
|
| 1243 |
+
result = reader.read()
|
| 1244 |
+
# all three, so the na_filter=0 column really is in the batch
|
| 1245 |
+
assert reader._engine._reader._largest_str_batch == 3
|
| 1246 |
+
str_dtype = (
|
| 1247 |
+
pd.ArrowDtype(pa.string())
|
| 1248 |
+
if kwargs
|
| 1249 |
+
else pd.StringDtype("pyarrow", na_value=np.nan)
|
| 1250 |
+
)
|
| 1251 |
+
# inside the context so the columns Index dtype matches the result's
|
| 1252 |
+
expected = pd.DataFrame(
|
| 1253 |
+
{
|
| 1254 |
+
"a": ["foo", None, "bar"],
|
| 1255 |
+
# na_filter is off here, so this column's own "NA" stays literal
|
| 1256 |
+
"b": ["-1", "18446744073709551615", "NA"],
|
| 1257 |
+
"c": ["zzz", "qq", None],
|
| 1258 |
+
}
|
| 1259 |
+
).astype(str_dtype)
|
| 1260 |
+
tm.assert_frame_equal(result, expected)
|
| 1261 |
+
|
| 1262 |
+
|
| 1263 |
+
@pytest.mark.parametrize("kwargs", [{}, {"dtype_backend": "pyarrow"}])
|
| 1264 |
+
@pytest.mark.parametrize("prefix_len", [1, 200])
|
| 1265 |
+
def test_embedded_nul_byte_roundtrip(c_parser_only, kwargs, prefix_len):
|
| 1266 |
+
# GH#66415: the pyarrow string fast path computed token lengths with
|
| 1267 |
+
# strlen, so a quoted field with an embedded NUL byte was truncated at the
|
| 1268 |
+
# NUL. Column "a" takes its length from the next token's start and column
|
| 1269 |
+
# "b", last in the stream, from the stream end, covering both branches of
|
| 1270 |
+
# the length helper; the two prefix_len values keep a length-capped scan
|
| 1271 |
+
# from passing by accident.
|
| 1272 |
+
pytest.importorskip("pyarrow")
|
| 1273 |
+
parser = c_parser_only
|
| 1274 |
+
value = b"x" * prefix_len + b"\x00y"
|
| 1275 |
+
data = b'a,b\n"' + value + b'","' + value + b'"'
|
| 1276 |
+
result = parser.read_csv(BytesIO(data), **kwargs)
|
| 1277 |
+
# engine="python" shares none of the C tokenizer's length arithmetic, so it
|
| 1278 |
+
# is an independent reference for what the field should decode to
|
| 1279 |
+
expected = pd.read_csv(BytesIO(data), engine="python")
|
| 1280 |
+
assert result["a"][0] == value.decode()
|
| 1281 |
+
assert result["b"][0] == value.decode()
|
| 1282 |
+
assert expected["a"][0] == value.decode()
|
| 1283 |
+
assert expected["b"][0] == value.decode()
|
| 1284 |
+
|
| 1285 |
+
|
| 1286 |
+
def test_embedded_nul_fixed_width_bytes(c_parser_only):
|
| 1287 |
+
# GH#19886: the fixed-width "S" path copied with strncpy, which stops at an
|
| 1288 |
+
# embedded NUL even though numpy "S" can hold one.
|
| 1289 |
+
parser = c_parser_only
|
| 1290 |
+
data = b'a\n"x\x00y"\n"x\x00z"\n'
|
| 1291 |
+
|
| 1292 |
+
result = parser.read_csv(BytesIO(data), dtype="S5")
|
| 1293 |
+
assert result["a"].tolist() == [b"x\x00y", b"x\x00z"]
|
| 1294 |
+
tm.assert_frame_equal(
|
| 1295 |
+
result, pd.read_csv(BytesIO(data), dtype="S5", engine="python")
|
| 1296 |
+
)
|
| 1297 |
+
|
| 1298 |
+
# a token longer than the width is still truncated to the width
|
| 1299 |
+
assert parser.read_csv(BytesIO(b"a\nabcdef\n"), dtype="S3")["a"].tolist() == [
|
| 1300 |
+
b"abc"
|
| 1301 |
+
]
|
| 1302 |
+
|
| 1303 |
+
|
| 1304 |
+
def test_embedded_nul_converter(c_parser_only):
|
| 1305 |
+
# GH#19886: converters were handed a value truncated at the NUL, so they
|
| 1306 |
+
# disagreed with the object path on the same input.
|
| 1307 |
+
parser = c_parser_only
|
| 1308 |
+
data = b'a\n"x\x00y"\n"x\x00z"\n'
|
| 1309 |
+
|
| 1310 |
+
result = parser.read_csv(BytesIO(data), converters={"a": str})
|
| 1311 |
+
assert result["a"].tolist() == ["x\x00y", "x\x00z"]
|
| 1312 |
+
tm.assert_frame_equal(
|
| 1313 |
+
result, pd.read_csv(BytesIO(data), converters={"a": str}, engine="python")
|
| 1314 |
+
)
|
| 1315 |
+
|
| 1316 |
+
|
| 1317 |
+
def test_embedded_nul_column_name(c_parser_only):
|
| 1318 |
+
# GH#19886: a column name was truncated at an embedded NUL, which could
|
| 1319 |
+
# also collide two distinct names into one.
|
| 1320 |
+
parser = c_parser_only
|
| 1321 |
+
data = b'"h\x001","h\x002"\n1,2\n'
|
| 1322 |
+
|
| 1323 |
+
result = parser.read_csv(BytesIO(data))
|
| 1324 |
+
assert list(result.columns) == ["h\x001", "h\x002"]
|
| 1325 |
+
tm.assert_frame_equal(result, pd.read_csv(BytesIO(data), engine="python"))
|
| 1326 |
+
|
| 1327 |
+
|
| 1328 |
+
@pytest.mark.parametrize("dtype", [object, "str", "string", "category", None])
|
| 1329 |
+
@pytest.mark.parametrize(
|
| 1330 |
+
"data, expected",
|
| 1331 |
+
[
|
| 1332 |
+
(b'a\n"x\x00y"\n"x\x00z"\n"x"\n', ["x\x00y", "x\x00z", "x"]),
|
| 1333 |
+
(b'a\n"x\x00y"\n"x\x00z"\n"x\x00w"\n', ["x\x00y", "x\x00z", "x\x00w"]),
|
| 1334 |
+
],
|
| 1335 |
+
)
|
| 1336 |
+
def test_embedded_nul_distinct_values(c_parser_only, dtype, data, expected):
|
| 1337 |
+
# GH#66525: the object path interned fields in a hash table keyed on the
|
| 1338 |
+
# NUL-terminated word, so two fields differing only past an embedded NUL
|
| 1339 |
+
# were silently boxed to the same value. The second fixture is all
|
| 1340 |
+
# equal-length, so distinguishing it needs a comparison that reads past
|
| 1341 |
+
# the NUL rather than just a key-length check.
|
| 1342 |
+
parser = c_parser_only
|
| 1343 |
+
|
| 1344 |
+
result = parser.read_csv(BytesIO(data), dtype=dtype, keep_default_na=False)
|
| 1345 |
+
assert list(result["a"]) == expected
|
| 1346 |
+
|
| 1347 |
+
|
| 1348 |
+
@pytest.mark.parametrize(
|
| 1349 |
+
"data",
|
| 1350 |
+
[
|
| 1351 |
+
b'a\n"q\x00\xff"\n',
|
| 1352 |
+
b'a\n"q\xff"\n',
|
| 1353 |
+
# two *distinct* undecodable fields: the table dedupes on raw bytes, so
|
| 1354 |
+
# these stay separate keys but decode to one label
|
| 1355 |
+
b'a\n"q\xff"\n"q\xfe"\n',
|
| 1356 |
+
b'a\n"q\xff"\n"q\xfe"\n"z"\n"q\xff"\n',
|
| 1357 |
+
],
|
| 1358 |
+
)
|
| 1359 |
+
@pytest.mark.parametrize("encoding_errors", ["replace", "ignore"])
|
| 1360 |
+
def test_categorical_honors_encoding_errors(c_parser_only, data, encoding_errors):
|
| 1361 |
+
# GH#66525: _categorical_convert decoded its category labels with strict
|
| 1362 |
+
# errors regardless of encoding_errors, so an undecodable byte raised where
|
| 1363 |
+
# dtype=object honored the argument. Two keys that decode to the same label
|
| 1364 |
+
# must merge, or the Categorical is built with duplicate categories.
|
| 1365 |
+
parser = c_parser_only
|
| 1366 |
+
kwargs = {"keep_default_na": False, "encoding_errors": encoding_errors}
|
| 1367 |
+
|
| 1368 |
+
result = parser.read_csv(BytesIO(data), dtype="category", **kwargs)
|
| 1369 |
+
expected = parser.read_csv(BytesIO(data), dtype=object, **kwargs)
|
| 1370 |
+
assert list(result["a"]) == list(expected["a"])
|
| 1371 |
+
|
| 1372 |
+
|
| 1373 |
+
def test_categorical_encoding_errors_merge_with_na(c_parser_only):
|
| 1374 |
+
# GH#66525: a merged column that also contains NA exercises the sentinel
|
| 1375 |
+
# guard in the code remap -- a -1 code must not be looked up in the map.
|
| 1376 |
+
parser = c_parser_only
|
| 1377 |
+
data = b'a,b\n"q\xff",1\n,2\n"q\xfe",3\n"z",4\n'
|
| 1378 |
+
|
| 1379 |
+
result = parser.read_csv(
|
| 1380 |
+
BytesIO(data), dtype={"a": "category"}, encoding_errors="replace"
|
| 1381 |
+
)["a"]
|
| 1382 |
+
|
| 1383 |
+
assert list(result.cat.categories) == ["q�", "z"]
|
| 1384 |
+
assert list(result.cat.codes) == [0, -1, 0, 1]
|
| 1385 |
+
|
| 1386 |
+
|
| 1387 |
+
@pytest.mark.parametrize(
|
| 1388 |
+
"field,other",
|
| 1389 |
+
[
|
| 1390 |
+
("1\x00xyz", "2"),
|
| 1391 |
+
("-1\x00xyz", "2"),
|
| 1392 |
+
("18446744073709551615\x00xyz", "2"),
|
| 1393 |
+
("1.5\x00xyz", "2.5"),
|
| 1394 |
+
("1e3\x00xyz", "2.5"),
|
| 1395 |
+
("inf\x00xyz", "2.5"),
|
| 1396 |
+
("infinity\x00xyz", "2.5"),
|
| 1397 |
+
("True\x00xyz", "False"),
|
| 1398 |
+
# not a default true_values entry, so only to_boolean can accept it
|
| 1399 |
+
("TRue\x00xyz", "False"),
|
| 1400 |
+
],
|
| 1401 |
+
)
|
| 1402 |
+
def test_embedded_nul_is_not_a_numeric_or_boolean_literal(c_parser_only, field, other):
|
| 1403 |
+
# GH#66524: the numeric and boolean converters finished on a NUL rather
|
| 1404 |
+
# than on the end of the token, so a field was silently accepted at its
|
| 1405 |
+
# pre-NUL prefix and the trailing bytes were discarded. `other` keeps the
|
| 1406 |
+
# rest of the column parseable, so the column would convert if the bad
|
| 1407 |
+
# field were accepted.
|
| 1408 |
+
parser = c_parser_only
|
| 1409 |
+
data = f'a\n"{field}"\n{other}\n'.encode()
|
| 1410 |
+
|
| 1411 |
+
result = parser.read_csv(BytesIO(data))
|
| 1412 |
+
expected = pd.read_csv(BytesIO(data), engine="python")
|
| 1413 |
+
tm.assert_frame_equal(result, expected)
|
| 1414 |
+
assert result["a"][0] == field
|
| 1415 |
+
|
| 1416 |
+
|
| 1417 |
+
def test_embedded_nul_with_thousands_separator(c_parser_only):
|
| 1418 |
+
# GH#66524: the thousands-separator path strips the separator into a scratch
|
| 1419 |
+
# buffer, so it needs the same end-of-token check as the plain path.
|
| 1420 |
+
parser = c_parser_only
|
| 1421 |
+
data = b'a\n"1,234\x00xyz"\n2\n'
|
| 1422 |
+
|
| 1423 |
+
result = parser.read_csv(BytesIO(data), thousands=",")
|
| 1424 |
+
expected = pd.read_csv(BytesIO(data), engine="python", thousands=",")
|
| 1425 |
+
tm.assert_frame_equal(result, expected)
|
| 1426 |
+
assert result["a"][0] == "1,234\x00xyz"
|
| 1427 |
+
|
| 1428 |
+
|
| 1429 |
+
@pytest.mark.parametrize("na_filter", [True, False])
|
| 1430 |
+
@pytest.mark.parametrize(
|
| 1431 |
+
"good,field",
|
| 1432 |
+
[
|
| 1433 |
+
("2.5", "1.5\x00xyz"),
|
| 1434 |
+
("2.5", "inf\x00xyz"),
|
| 1435 |
+
# the long spelling takes a different arm of the infinity check
|
| 1436 |
+
("2.5", "-Infinity\x00x"),
|
| 1437 |
+
# default spelling: covers the true/false hashset lookup, which must
|
| 1438 |
+
# compare the full length rather than the pre-NUL prefix
|
| 1439 |
+
("True", "True\x00xyz"),
|
| 1440 |
+
("True", "TRue\x00xyz"),
|
| 1441 |
+
# neither spelling is in the default true_values/false_values, so each
|
| 1442 |
+
# reaches a different arm of to_boolean
|
| 1443 |
+
("True", "FAlse\x00xyz"),
|
| 1444 |
+
],
|
| 1445 |
+
)
|
| 1446 |
+
def test_embedded_nul_in_later_row(c_parser_only, good, field, na_filter):
|
| 1447 |
+
# GH#66524: the float and boolean converters probe only the first non-NA
|
| 1448 |
+
# token and bail out before their bulk loop when it rejects, so a NUL field
|
| 1449 |
+
# in the first row never reaches the per-row conversion. Put a good value
|
| 1450 |
+
# first so the bulk loop is the code under test; na_filter picks between
|
| 1451 |
+
# the two separate loops in each converter.
|
| 1452 |
+
parser = c_parser_only
|
| 1453 |
+
data = f'a\n{good}\n"{field}"\n'.encode()
|
| 1454 |
+
|
| 1455 |
+
result = parser.read_csv(BytesIO(data), na_filter=na_filter)
|
| 1456 |
+
expected = pd.read_csv(BytesIO(data), engine="python", na_filter=na_filter)
|
| 1457 |
+
tm.assert_frame_equal(result, expected)
|
| 1458 |
+
assert result["a"].tolist() == [good, field]
|
| 1459 |
+
|
| 1460 |
+
|
| 1461 |
+
@pytest.mark.parametrize(
|
| 1462 |
+
"field",
|
| 1463 |
+
[
|
| 1464 |
+
"1\x00xyz",
|
| 1465 |
+
"18446744073709551614\x00z",
|
| 1466 |
+
# the pre-NUL digits exceed uint64, so this leaves str_to_uint64 by the
|
| 1467 |
+
# overflow arm rather than by the end-of-token check the others take
|
| 1468 |
+
"18446744073709551616\x00z",
|
| 1469 |
+
],
|
| 1470 |
+
)
|
| 1471 |
+
def test_embedded_nul_is_not_a_uint64(c_parser_only, field):
|
| 1472 |
+
# GH#66524: str_to_uint64 is reached only after str_to_int64 reports a
|
| 1473 |
+
# *clean* overflow, which a NUL-bearing token can never produce, so the
|
| 1474 |
+
# leading row has to genuinely exceed int64 for the uint64 path to see the
|
| 1475 |
+
# NUL-bearing field at all.
|
| 1476 |
+
parser = c_parser_only
|
| 1477 |
+
data = f'a\n18446744073709551615\n"{field}"\n'.encode()
|
| 1478 |
+
|
| 1479 |
+
result = parser.read_csv(BytesIO(data))
|
| 1480 |
+
expected = pd.read_csv(BytesIO(data), engine="python")
|
| 1481 |
+
tm.assert_frame_equal(result, expected)
|
| 1482 |
+
assert result["a"].tolist() == ["18446744073709551615", field]
|
| 1483 |
+
|
| 1484 |
+
|
| 1485 |
+
def test_embedded_nul_int64_overflow(c_parser_only):
|
| 1486 |
+
# GH#66524: the pre-NUL digits are int64max + 1, so the token leaves
|
| 1487 |
+
# str_to_int64 by the overflow arm and its truncation has to be caught
|
| 1488 |
+
# before the uint64 retry, where the truncated value would fit.
|
| 1489 |
+
parser = c_parser_only
|
| 1490 |
+
data = b'a\n1\n"9223372036854775808\x00z"\n'
|
| 1491 |
+
|
| 1492 |
+
result = parser.read_csv(BytesIO(data))
|
| 1493 |
+
expected = pd.read_csv(BytesIO(data), engine="python")
|
| 1494 |
+
tm.assert_frame_equal(result, expected)
|
| 1495 |
+
assert result["a"].tolist() == ["1", "9223372036854775808\x00z"]
|
| 1496 |
+
|
| 1497 |
+
|
| 1498 |
+
def test_embedded_nul_is_not_a_python_int(c_parser_only):
|
| 1499 |
+
# GH#66524: a column containing a value too large for uint64 falls back to
|
| 1500 |
+
# a Python-int path built on PyLong_FromString, which also stops at a NUL.
|
| 1501 |
+
parser = c_parser_only
|
| 1502 |
+
data = b'a\n99999999999999999999999999\n"1\x00xyz"\n'
|
| 1503 |
+
|
| 1504 |
+
result = parser.read_csv(BytesIO(data))
|
| 1505 |
+
expected = pd.read_csv(BytesIO(data), engine="python")
|
| 1506 |
+
tm.assert_frame_equal(result, expected)
|
| 1507 |
+
assert result["a"].tolist() == ["99999999999999999999999999", "1\x00xyz"]
|
| 1508 |
+
|
| 1509 |
+
|
| 1510 |
+
def test_embedded_nul_raises_for_explicit_int_dtype(c_parser_only):
|
| 1511 |
+
# GH#66524: with the dtype pinned there is no string column to fall back
|
| 1512 |
+
# to, so the truncated value has to raise rather than parse.
|
| 1513 |
+
parser = c_parser_only
|
| 1514 |
+
data = b'a\n"1\x00xyz"\n2\n'
|
| 1515 |
+
|
| 1516 |
+
with pytest.raises(ValueError, match="Unable to parse string"):
|
| 1517 |
+
parser.read_csv(BytesIO(data), dtype="Int64")
|
| 1518 |
+
|
| 1519 |
+
|
| 1520 |
+
@pytest.mark.parametrize(
|
| 1521 |
+
"field", ["1\x00x", "0\x00x", "1.0\x00x", "0.0\x00x", "True\x00x"]
|
| 1522 |
+
)
|
| 1523 |
+
def test_embedded_nul_raises_for_boolean_dtype(c_parser_only, field):
|
| 1524 |
+
# GH#66524: "1"/"1.0"/"0"/"0.0" are the numeric spellings dtype="boolean"
|
| 1525 |
+
# accepts; none of these are one of them. The "1.0"/"0.0" spellings take a
|
| 1526 |
+
# separate arm of the literal check from the one-character ones.
|
| 1527 |
+
parser = c_parser_only
|
| 1528 |
+
data = f'a\nTrue\n"{field}"\n'.encode()
|
| 1529 |
+
|
| 1530 |
+
with pytest.raises(ValueError, match="cannot be cast to bool"):
|
| 1531 |
+
parser.read_csv(BytesIO(data), dtype="boolean")
|
| 1532 |
+
|
| 1533 |
+
|
| 1534 |
+
@pytest.mark.parametrize("value", [b"NA\x00x", b"nan\x00junk", b"null\x00z"])
|
| 1535 |
+
def test_default_na_value_prefix_is_not_na(c_parser_only, value):
|
| 1536 |
+
# GH#19886: a field was compared against na_values only up to its first
|
| 1537 |
+
# NUL, so a value merely *starting* with a default na_value -- needing no
|
| 1538 |
+
# custom na_values at all -- was read as NaN.
|
| 1539 |
+
parser = c_parser_only
|
| 1540 |
+
data = b'a\n"' + value + b'"\n'
|
| 1541 |
+
|
| 1542 |
+
result = parser.read_csv(BytesIO(data))
|
| 1543 |
+
assert result["a"][0] == value.decode()
|
| 1544 |
+
tm.assert_frame_equal(result, pd.read_csv(BytesIO(data), engine="python"))
|
| 1545 |
+
|
| 1546 |
+
|
| 1547 |
+
@pytest.mark.parametrize("value", [b"\x00y", b"\x00\x00\x00", b"\x00", b"\x00 "])
|
| 1548 |
+
def test_leading_nul_is_not_na(c_parser_only, value):
|
| 1549 |
+
# GH#19886: the na_values lookup compared the NUL-terminated word, so a
|
| 1550 |
+
# field starting with a NUL byte matched the empty string -- a default
|
| 1551 |
+
# na_value -- and was read as NaN.
|
| 1552 |
+
parser = c_parser_only
|
| 1553 |
+
data = b'a\n"' + value + b'"\n'
|
| 1554 |
+
|
| 1555 |
+
result = parser.read_csv(BytesIO(data))
|
| 1556 |
+
assert result["a"][0] == value.decode()
|
| 1557 |
+
tm.assert_frame_equal(result, parser.read_csv(BytesIO(data), na_filter=False))
|
| 1558 |
+
tm.assert_frame_equal(result, pd.read_csv(BytesIO(data), engine="python"))
|
| 1559 |
+
|
| 1560 |
+
|
| 1561 |
+
def test_na_values_with_embedded_nul(c_parser_only):
|
| 1562 |
+
# GH#19886: an na_value containing a NUL was itself truncated when added to
|
| 1563 |
+
# the hashset, so it matched any field sharing its pre-NUL prefix.
|
| 1564 |
+
parser = c_parser_only
|
| 1565 |
+
data = b'a\n"x\x00y"\n"x\x00z"\n"x"\n'
|
| 1566 |
+
|
| 1567 |
+
result = parser.read_csv(BytesIO(data), na_values=["x\x00y"], keep_default_na=False)
|
| 1568 |
+
assert result["a"].isna().tolist() == [True, False, False]
|
| 1569 |
+
assert result["a"][1] == "x\x00z"
|
| 1570 |
+
assert result["a"][2] == "x"
|
| 1571 |
+
|
| 1572 |
+
|
| 1573 |
+
def test_true_false_values_with_embedded_nul(c_parser_only):
|
| 1574 |
+
# GH#19886: a true_values/false_values entry containing a NUL was truncated
|
| 1575 |
+
# when added to the hashset, so it also matched a field equal to just the
|
| 1576 |
+
# prefix before that NUL. The field here must be prefix-only to be
|
| 1577 |
+
# load-bearing -- an exactly-matching field behaves the same either way.
|
| 1578 |
+
parser = c_parser_only
|
| 1579 |
+
|
| 1580 |
+
result = parser.read_csv(
|
| 1581 |
+
BytesIO(b"a\ny\nno\n"), true_values=["y\x00es"], false_values=["no"]
|
| 1582 |
+
)
|
| 1583 |
+
assert result["a"].tolist() == ["y", "no"]
|
| 1584 |
+
|
| 1585 |
+
matched = parser.read_csv(
|
| 1586 |
+
BytesIO(b'a\n"y\x00es"\nno\n'), true_values=["y\x00es"], false_values=["no"]
|
| 1587 |
+
)
|
| 1588 |
+
assert matched["a"].tolist() == [True, False]
|
| 1589 |
+
|
| 1590 |
+
|
| 1591 |
+
def test_na_values_leading_nul(c_parser_only):
|
| 1592 |
+
# GH#19886: exercises the first-byte prefilter for keys under '\x00' --
|
| 1593 |
+
# a leading-NUL na_value must not swallow the empty field or a different
|
| 1594 |
+
# leading-NUL value.
|
| 1595 |
+
parser = c_parser_only
|
| 1596 |
+
data = b'a\n"\x00y"\n"\x00z"\n""\n'
|
| 1597 |
+
|
| 1598 |
+
result = parser.read_csv(BytesIO(data), na_values=["\x00y"], keep_default_na=False)
|
| 1599 |
+
assert result["a"].isna().tolist() == [True, False, False]
|
| 1600 |
+
assert result["a"][1] == "\x00z"
|
| 1601 |
+
assert result["a"][2] == ""
|
| 1602 |
+
|
| 1603 |
+
|
| 1604 |
+
def _raise_on_five(value):
|
| 1605 |
+
if value == "5":
|
| 1606 |
+
raise RuntimeError("boom")
|
| 1607 |
+
return value
|
| 1608 |
+
|
| 1609 |
+
|
| 1610 |
+
@pytest.mark.parametrize(
|
| 1611 |
+
"data,kwargs,error,match",
|
| 1612 |
+
[
|
| 1613 |
+
(
|
| 1614 |
+
"a,b\n" + "".join(f"{i},{'oops' if i == 5 else i}\n" for i in range(20)),
|
| 1615 |
+
{"dtype": {"b": "int64"}},
|
| 1616 |
+
ValueError,
|
| 1617 |
+
"invalid literal for int",
|
| 1618 |
+
),
|
| 1619 |
+
(
|
| 1620 |
+
"a,b\n" + "".join(f"{i},{i}\n" for i in range(20)),
|
| 1621 |
+
{"converters": {"b": _raise_on_five}},
|
| 1622 |
+
RuntimeError,
|
| 1623 |
+
"boom",
|
| 1624 |
+
),
|
| 1625 |
+
(
|
| 1626 |
+
"a,b\n"
|
| 1627 |
+
+ "".join(
|
| 1628 |
+
(f"{i},{i},{i}\n" if i == 15 else f"{i},{i}\n") for i in range(20)
|
| 1629 |
+
),
|
| 1630 |
+
{},
|
| 1631 |
+
ParserError,
|
| 1632 |
+
"Expected 2 fields",
|
| 1633 |
+
),
|
| 1634 |
+
],
|
| 1635 |
+
)
|
| 1636 |
+
def test_read_after_chunk_raised(c_parser_only, data, kwargs, error, match):
|
| 1637 |
+
# GH#66622: a chunk that raised closed the reader, and reading again then
|
| 1638 |
+
# dereferenced the freed tokenizer buffers instead of raising.
|
| 1639 |
+
parser = c_parser_only
|
| 1640 |
+
|
| 1641 |
+
with parser.read_csv(StringIO(data), chunksize=10, **kwargs) as reader:
|
| 1642 |
+
with pytest.raises(error, match=match):
|
| 1643 |
+
for _ in reader:
|
| 1644 |
+
pass
|
| 1645 |
+
|
| 1646 |
+
with pytest.raises(ValueError, match="I/O operation on closed file"):
|
| 1647 |
+
next(reader)
|
| 1648 |
+
|
| 1649 |
+
|
| 1650 |
+
def test_read_after_close(c_parser_only):
|
| 1651 |
+
# GH#66622: reading from a closed reader crashed the interpreter.
|
| 1652 |
+
parser = c_parser_only
|
| 1653 |
+
data = "a,b\n" + "".join(f"{i},{i}\n" for i in range(20))
|
| 1654 |
+
|
| 1655 |
+
with parser.read_csv(StringIO(data), chunksize=10) as reader:
|
| 1656 |
+
assert len(next(reader)) == 10
|
| 1657 |
+
|
| 1658 |
+
with pytest.raises(ValueError, match="I/O operation on closed file"):
|
| 1659 |
+
next(reader)
|
| 1660 |
+
|
| 1661 |
+
|
| 1662 |
+
def test_exhausted_reader_keeps_raising_stop_iteration(c_parser_only):
|
| 1663 |
+
# GH#66622: exhausting a reader closes it, but it must keep behaving like a
|
| 1664 |
+
# spent iterator rather than reporting a closed file.
|
| 1665 |
+
parser = c_parser_only
|
| 1666 |
+
data = "a,b\n" + "".join(f"{i},{i}\n" for i in range(20))
|
| 1667 |
+
|
| 1668 |
+
reader = parser.read_csv(StringIO(data), chunksize=10)
|
| 1669 |
+
assert len(list(reader)) == 2
|
| 1670 |
+
|
| 1671 |
+
for _ in range(2):
|
| 1672 |
+
with pytest.raises(StopIteration):
|
| 1673 |
+
next(reader)
|
| 1674 |
+
|
| 1675 |
+
|
| 1676 |
+
@pytest.mark.parametrize("dtype", [None, "category"])
|
| 1677 |
+
def test_decode_failure_frees_string_table(c_parser_only, dtype):
|
| 1678 |
+
# GH#67931
|
| 1679 |
+
# the string columns are interned through a khash table that was freed only
|
| 1680 |
+
# on the success path, so a decode failure part-way through a column leaked
|
| 1681 |
+
# the whole table -- ~100 KiB per failed parse here, so ~5 MiB over the loop
|
| 1682 |
+
parser = c_parser_only
|
| 1683 |
+
rows = "\n".join(f"s{i}" for i in range(2000)).encode()
|
| 1684 |
+
data = b"a\n" + rows + b"\n\xff\n"
|
| 1685 |
+
|
| 1686 |
+
def read():
|
| 1687 |
+
with pytest.raises(UnicodeDecodeError):
|
| 1688 |
+
parser.read_csv(BytesIO(data), dtype=dtype, encoding_errors="strict")
|
| 1689 |
+
|
| 1690 |
+
# measure only the khash domain, so unrelated allocations cannot mask or
|
| 1691 |
+
# fake the leak
|
| 1692 |
+
khash_only = (tracemalloc.DomainFilter(True, get_hashtable_trace_domain()),)
|
| 1693 |
+
|
| 1694 |
+
tracemalloc.start()
|
| 1695 |
+
try:
|
| 1696 |
+
# warm up, so first-call caching lands outside the measured window
|
| 1697 |
+
read()
|
| 1698 |
+
before = tracemalloc.take_snapshot().filter_traces(khash_only)
|
| 1699 |
+
for _ in range(50):
|
| 1700 |
+
read()
|
| 1701 |
+
after = tracemalloc.take_snapshot().filter_traces(khash_only)
|
| 1702 |
+
finally:
|
| 1703 |
+
tracemalloc.stop()
|
| 1704 |
+
|
| 1705 |
+
assert sum(stat.size_diff for stat in after.compare_to(before, "filename")) == 0
|
| 1706 |
+
|
| 1707 |
+
|
| 1708 |
+
# small enough that DEFAULT_BUFFER_HEURISTIC // table_width leaves one line per
|
| 1709 |
+
# buffer, so the rows below land in separate low_memory chunks
|
| 1710 |
+
_MIXED_DTYPE_HEURISTIC = 2**3
|
| 1711 |
+
|
| 1712 |
+
|
| 1713 |
+
def _mixed_dtype_data(n_leading_names: int = 3) -> str:
|
| 1714 |
+
"""
|
| 1715 |
+
Build a csv whose middle chunk makes the second of three fields mixed-dtype.
|
| 1716 |
+
|
| 1717 |
+
Naming fewer than the three fields per row leaves an unnamed leading field,
|
| 1718 |
+
which the reader takes as an implicit index, shifting which name that field
|
| 1719 |
+
carries.
|
| 1720 |
+
"""
|
| 1721 |
+
names = ["a", "b", "c"][:n_leading_names]
|
| 1722 |
+
rows = [f"{i},{i},{i}" for i in range(_MIXED_DTYPE_HEURISTIC - 1)]
|
| 1723 |
+
return ",".join(names) + "\n" + "\n".join([*rows, "7,x,7", "8,y,8", *rows]) + "\n"
|
| 1724 |
+
|
| 1725 |
+
|
| 1726 |
+
@pytest.mark.parametrize("usecols", [["b"], ["b", "c"], [1], [1, 2]])
|
| 1727 |
+
def test_mixed_dtype_warning_with_usecols(c_parser_only, monkeypatch, usecols):
|
| 1728 |
+
# GH#67375: read_low_memory keys its chunks by field position in the source
|
| 1729 |
+
# row, so usecols leaves gaps in those keys. The mixed-dtype warning used
|
| 1730 |
+
# them to index the column names directly, which raised IndexError for any
|
| 1731 |
+
# selected column that was not still at its original position.
|
| 1732 |
+
parser = c_parser_only
|
| 1733 |
+
data = _mixed_dtype_data()
|
| 1734 |
+
|
| 1735 |
+
with monkeypatch.context() as m:
|
| 1736 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", _MIXED_DTYPE_HEURISTIC)
|
| 1737 |
+
if parser.low_memory:
|
| 1738 |
+
result = parser.read_csv_check_warnings(
|
| 1739 |
+
DtypeWarning,
|
| 1740 |
+
r"Columns \(1: b\) have mixed types\. "
|
| 1741 |
+
"Specify dtype option on import or set low_memory=False.",
|
| 1742 |
+
StringIO(data),
|
| 1743 |
+
usecols=usecols,
|
| 1744 |
+
)
|
| 1745 |
+
else:
|
| 1746 |
+
result = parser.read_csv(StringIO(data), usecols=usecols)
|
| 1747 |
+
|
| 1748 |
+
expected = ["b"] if len(usecols) == 1 else ["b", "c"]
|
| 1749 |
+
assert result.columns.tolist() == expected
|
| 1750 |
+
|
| 1751 |
+
|
| 1752 |
+
def test_mixed_dtype_warning_with_index_col(c_parser_only, monkeypatch):
|
| 1753 |
+
# GH#67375: an index column shifts the parsed field positions past the data
|
| 1754 |
+
# columns, so the same positional lookup named the column after the mixed
|
| 1755 |
+
# one instead of naming "b".
|
| 1756 |
+
parser = c_parser_only
|
| 1757 |
+
data = _mixed_dtype_data()
|
| 1758 |
+
|
| 1759 |
+
with monkeypatch.context() as m:
|
| 1760 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", _MIXED_DTYPE_HEURISTIC)
|
| 1761 |
+
if parser.low_memory:
|
| 1762 |
+
result = parser.read_csv_check_warnings(
|
| 1763 |
+
DtypeWarning,
|
| 1764 |
+
r"Columns \(1: b\) have mixed types\. "
|
| 1765 |
+
"Specify dtype option on import or set low_memory=False.",
|
| 1766 |
+
StringIO(data),
|
| 1767 |
+
index_col=0,
|
| 1768 |
+
)
|
| 1769 |
+
else:
|
| 1770 |
+
result = parser.read_csv(StringIO(data), index_col=0)
|
| 1771 |
+
|
| 1772 |
+
assert result.columns.tolist() == ["b", "c"]
|
| 1773 |
+
assert result.index.name == "a"
|
| 1774 |
+
|
| 1775 |
+
|
| 1776 |
+
def test_mixed_dtype_warning_with_implicit_index(c_parser_only, monkeypatch):
|
| 1777 |
+
# GH#67375: a header shorter than the rows makes the reader take the first
|
| 1778 |
+
# field as an implicit index. That field has no name, so the parsed
|
| 1779 |
+
# positions run one ahead of the column names and the warning named "b"
|
| 1780 |
+
# while the mixed column was "a".
|
| 1781 |
+
parser = c_parser_only
|
| 1782 |
+
data = _mixed_dtype_data(n_leading_names=2)
|
| 1783 |
+
|
| 1784 |
+
with monkeypatch.context() as m:
|
| 1785 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", _MIXED_DTYPE_HEURISTIC)
|
| 1786 |
+
if parser.low_memory:
|
| 1787 |
+
result = parser.read_csv_check_warnings(
|
| 1788 |
+
DtypeWarning,
|
| 1789 |
+
r"Columns \(1: a\) have mixed types\. "
|
| 1790 |
+
"Specify dtype option on import or set low_memory=False.",
|
| 1791 |
+
StringIO(data),
|
| 1792 |
+
)
|
| 1793 |
+
else:
|
| 1794 |
+
result = parser.read_csv(StringIO(data))
|
| 1795 |
+
|
| 1796 |
+
assert result.columns.tolist() == ["a", "b"]
|
| 1797 |
+
|
| 1798 |
+
|
| 1799 |
+
def test_mixed_dtype_warning_reports_source_positions(c_parser_only, monkeypatch):
|
| 1800 |
+
# GH#67375: the number before each name is the column's position in the
|
| 1801 |
+
# source row -- as GH#58174 asked for and as the pre-GH#58250 message
|
| 1802 |
+
# printed -- not a running count of the mixed columns. With two mixed
|
| 1803 |
+
# columns at positions 1 and 3 the two readings disagree.
|
| 1804 |
+
parser = c_parser_only
|
| 1805 |
+
rows = [f"{i},{i},{i},{i}" for i in range(_MIXED_DTYPE_HEURISTIC - 1)]
|
| 1806 |
+
data = "a,b,c,d\n" + "\n".join([*rows, "7,x,7,x", "8,y,8,y", *rows]) + "\n"
|
| 1807 |
+
|
| 1808 |
+
with monkeypatch.context() as m:
|
| 1809 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", _MIXED_DTYPE_HEURISTIC)
|
| 1810 |
+
if parser.low_memory:
|
| 1811 |
+
result = parser.read_csv_check_warnings(
|
| 1812 |
+
DtypeWarning,
|
| 1813 |
+
r"Columns \(1: b, 3: d\) have mixed types\. "
|
| 1814 |
+
"Specify dtype option on import or set low_memory=False.",
|
| 1815 |
+
StringIO(data),
|
| 1816 |
+
)
|
| 1817 |
+
else:
|
| 1818 |
+
result = parser.read_csv(StringIO(data))
|
| 1819 |
+
|
| 1820 |
+
assert result.columns.tolist() == ["a", "b", "c", "d"]
|
| 1821 |
+
|
| 1822 |
+
|
| 1823 |
+
def test_mixed_dtype_warning_with_mixed_implicit_index(c_parser_only, monkeypatch):
|
| 1824 |
+
# GH#67375: the implicit index column is parsed like any other field and can
|
| 1825 |
+
# itself be mixed, but it has no name to report. Naming it by position, as
|
| 1826 |
+
# the message did before GH#58250 added names, beats borrowing the name of
|
| 1827 |
+
# the first data column -- which is not the column that is mixed.
|
| 1828 |
+
parser = c_parser_only
|
| 1829 |
+
rows = [f"{i},{i},{i},{i}" for i in range(_MIXED_DTYPE_HEURISTIC - 1)]
|
| 1830 |
+
data = "a,b,c\n" + "\n".join([*rows, "x,7,7,7", "y,8,8,8", *rows]) + "\n"
|
| 1831 |
+
|
| 1832 |
+
with monkeypatch.context() as m:
|
| 1833 |
+
m.setattr(libparsers, "DEFAULT_BUFFER_HEURISTIC", _MIXED_DTYPE_HEURISTIC)
|
| 1834 |
+
if parser.low_memory:
|
| 1835 |
+
result = parser.read_csv_check_warnings(
|
| 1836 |
+
DtypeWarning,
|
| 1837 |
+
r"Columns \(0\) have mixed types\. "
|
| 1838 |
+
"Specify dtype option on import or set low_memory=False.",
|
| 1839 |
+
StringIO(data),
|
| 1840 |
+
)
|
| 1841 |
+
else:
|
| 1842 |
+
result = parser.read_csv(StringIO(data))
|
| 1843 |
+
|
| 1844 |
+
assert result.columns.tolist() == ["a", "b", "c"]
|
| 1845 |
+
assert result.index.name is None
|
| 1846 |
+
|
| 1847 |
+
|
| 1848 |
+
@pytest.mark.parametrize(
|
| 1849 |
+
"converter,values",
|
| 1850 |
+
[
|
| 1851 |
+
(lambda x: [x], [["1"], ["CAT"], ["3"]]),
|
| 1852 |
+
# hashable type whose __hash__ raises
|
| 1853 |
+
(lambda x: (x, [x]), [("1", ["1"]), ("CAT", ["CAT"]), ("3", ["3"])]),
|
| 1854 |
+
],
|
| 1855 |
+
)
|
| 1856 |
+
def test_converter_unhashable_output_with_na_values(c_parser_only, converter, values):
|
| 1857 |
+
# GH#13302 matching na_values against the converter's output must not
|
| 1858 |
+
# reject output that cannot be hashed. The python engine raises here.
|
| 1859 |
+
parser = c_parser_only
|
| 1860 |
+
data = "A\n1\nCAT\n3"
|
| 1861 |
+
|
| 1862 |
+
result = parser.read_csv(
|
| 1863 |
+
StringIO(data), converters={"A": converter}, na_values="CAT"
|
| 1864 |
+
)
|
| 1865 |
+
expected = pd.DataFrame({"A": values})
|
| 1866 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_comment.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that comments are properly handled during parsing
|
| 3 |
+
for all of the parsers defined in parsers.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from io import StringIO
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.mark.parametrize("na_values", [None, ["NaN"]])
|
| 16 |
+
def test_comment(all_parsers, na_values):
|
| 17 |
+
parser = all_parsers
|
| 18 |
+
data = """A,B,C
|
| 19 |
+
1,2.,4.#hello world
|
| 20 |
+
5.,NaN,10.0
|
| 21 |
+
"""
|
| 22 |
+
expected = pd.DataFrame(
|
| 23 |
+
[[1.0, 2.0, 4.0], [5.0, np.nan, 10.0]], columns=["A", "B", "C"]
|
| 24 |
+
)
|
| 25 |
+
if parser.engine == "pyarrow":
|
| 26 |
+
msg = "The 'comment' option is not supported with the 'pyarrow' engine"
|
| 27 |
+
with pytest.raises(ValueError, match=msg):
|
| 28 |
+
parser.read_csv(StringIO(data), comment="#", na_values=na_values)
|
| 29 |
+
return
|
| 30 |
+
result = parser.read_csv(StringIO(data), comment="#", na_values=na_values)
|
| 31 |
+
tm.assert_frame_equal(result, expected)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.mark.parametrize("read_kwargs", [{}, {"lineterminator": "*"}, {"sep": r"\s+"}])
|
| 35 |
+
def test_line_comment(all_parsers, read_kwargs):
|
| 36 |
+
parser = all_parsers
|
| 37 |
+
data = """# empty
|
| 38 |
+
A,B,C
|
| 39 |
+
1,2.,4.#hello world
|
| 40 |
+
#ignore this line
|
| 41 |
+
5.,NaN,10.0
|
| 42 |
+
"""
|
| 43 |
+
if read_kwargs.get("sep"):
|
| 44 |
+
data = data.replace(",", " ")
|
| 45 |
+
elif read_kwargs.get("lineterminator"):
|
| 46 |
+
data = data.replace("\n", read_kwargs.get("lineterminator"))
|
| 47 |
+
|
| 48 |
+
read_kwargs["comment"] = "#"
|
| 49 |
+
if parser.engine == "pyarrow":
|
| 50 |
+
if "lineterminator" in read_kwargs:
|
| 51 |
+
msg = (
|
| 52 |
+
"The 'lineterminator' option is not supported with the 'pyarrow' engine"
|
| 53 |
+
)
|
| 54 |
+
else:
|
| 55 |
+
msg = "The 'comment' option is not supported with the 'pyarrow' engine"
|
| 56 |
+
with pytest.raises(ValueError, match=msg):
|
| 57 |
+
parser.read_csv(StringIO(data), **read_kwargs)
|
| 58 |
+
return
|
| 59 |
+
elif parser.engine == "python" and read_kwargs.get("lineterminator"):
|
| 60 |
+
msg = r"Custom line terminators not supported in python parser \(yet\)"
|
| 61 |
+
with pytest.raises(ValueError, match=msg):
|
| 62 |
+
parser.read_csv(StringIO(data), **read_kwargs)
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
result = parser.read_csv(StringIO(data), **read_kwargs)
|
| 66 |
+
expected = pd.DataFrame(
|
| 67 |
+
[[1.0, 2.0, 4.0], [5.0, np.nan, 10.0]], columns=["A", "B", "C"]
|
| 68 |
+
)
|
| 69 |
+
tm.assert_frame_equal(result, expected)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_comment_skiprows(all_parsers):
|
| 73 |
+
parser = all_parsers
|
| 74 |
+
data = """# empty
|
| 75 |
+
random line
|
| 76 |
+
# second empty line
|
| 77 |
+
1,2,3
|
| 78 |
+
A,B,C
|
| 79 |
+
1,2.,4.
|
| 80 |
+
5.,NaN,10.0
|
| 81 |
+
"""
|
| 82 |
+
# This should ignore the first four lines (including comments).
|
| 83 |
+
expected = pd.DataFrame(
|
| 84 |
+
[[1.0, 2.0, 4.0], [5.0, np.nan, 10.0]], columns=["A", "B", "C"]
|
| 85 |
+
)
|
| 86 |
+
if parser.engine == "pyarrow":
|
| 87 |
+
msg = "The 'comment' option is not supported with the 'pyarrow' engine"
|
| 88 |
+
with pytest.raises(ValueError, match=msg):
|
| 89 |
+
parser.read_csv(StringIO(data), comment="#", skiprows=4)
|
| 90 |
+
return
|
| 91 |
+
|
| 92 |
+
result = parser.read_csv(StringIO(data), comment="#", skiprows=4)
|
| 93 |
+
tm.assert_frame_equal(result, expected)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_comment_header(all_parsers):
|
| 97 |
+
parser = all_parsers
|
| 98 |
+
data = """# empty
|
| 99 |
+
# second empty line
|
| 100 |
+
1,2,3
|
| 101 |
+
A,B,C
|
| 102 |
+
1,2.,4.
|
| 103 |
+
5.,NaN,10.0
|
| 104 |
+
"""
|
| 105 |
+
# Header should begin at the second non-comment line.
|
| 106 |
+
expected = pd.DataFrame(
|
| 107 |
+
[[1.0, 2.0, 4.0], [5.0, np.nan, 10.0]], columns=["A", "B", "C"]
|
| 108 |
+
)
|
| 109 |
+
if parser.engine == "pyarrow":
|
| 110 |
+
msg = "The 'comment' option is not supported with the 'pyarrow' engine"
|
| 111 |
+
with pytest.raises(ValueError, match=msg):
|
| 112 |
+
parser.read_csv(StringIO(data), comment="#", header=1)
|
| 113 |
+
return
|
| 114 |
+
result = parser.read_csv(StringIO(data), comment="#", header=1)
|
| 115 |
+
tm.assert_frame_equal(result, expected)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_comment_skiprows_header(all_parsers):
|
| 119 |
+
parser = all_parsers
|
| 120 |
+
data = """# empty
|
| 121 |
+
# second empty line
|
| 122 |
+
# third empty line
|
| 123 |
+
X,Y,Z
|
| 124 |
+
1,2,3
|
| 125 |
+
A,B,C
|
| 126 |
+
1,2.,4.
|
| 127 |
+
5.,NaN,10.0
|
| 128 |
+
"""
|
| 129 |
+
# Skiprows should skip the first 4 lines (including comments),
|
| 130 |
+
# while header should start from the second non-commented line,
|
| 131 |
+
# starting with line 5.
|
| 132 |
+
expected = pd.DataFrame(
|
| 133 |
+
[[1.0, 2.0, 4.0], [5.0, np.nan, 10.0]], columns=["A", "B", "C"]
|
| 134 |
+
)
|
| 135 |
+
if parser.engine == "pyarrow":
|
| 136 |
+
msg = "The 'comment' option is not supported with the 'pyarrow' engine"
|
| 137 |
+
with pytest.raises(ValueError, match=msg):
|
| 138 |
+
parser.read_csv(StringIO(data), comment="#", skiprows=4, header=1)
|
| 139 |
+
return
|
| 140 |
+
|
| 141 |
+
result = parser.read_csv(StringIO(data), comment="#", skiprows=4, header=1)
|
| 142 |
+
tm.assert_frame_equal(result, expected)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@pytest.mark.parametrize("comment_char", ["#", "~", "&", "^", "*", "@"])
|
| 146 |
+
def test_custom_comment_char(all_parsers, comment_char):
|
| 147 |
+
parser = all_parsers
|
| 148 |
+
data = "a,b,c\n1,2,3#ignore this!\n4,5,6#ignorethistoo"
|
| 149 |
+
|
| 150 |
+
if parser.engine == "pyarrow":
|
| 151 |
+
msg = "The 'comment' option is not supported with the 'pyarrow' engine"
|
| 152 |
+
with pytest.raises(ValueError, match=msg):
|
| 153 |
+
parser.read_csv(
|
| 154 |
+
StringIO(data.replace("#", comment_char)), comment=comment_char
|
| 155 |
+
)
|
| 156 |
+
return
|
| 157 |
+
result = parser.read_csv(
|
| 158 |
+
StringIO(data.replace("#", comment_char)), comment=comment_char
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
expected = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "b", "c"])
|
| 162 |
+
tm.assert_frame_equal(result, expected)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@pytest.mark.parametrize("header", ["infer", None])
|
| 166 |
+
def test_comment_first_line(all_parsers, header):
|
| 167 |
+
# see gh-4623
|
| 168 |
+
parser = all_parsers
|
| 169 |
+
data = "# notes\na,b,c\n# more notes\n1,2,3"
|
| 170 |
+
|
| 171 |
+
if header is None:
|
| 172 |
+
expected = pd.DataFrame({0: ["a", "1"], 1: ["b", "2"], 2: ["c", "3"]})
|
| 173 |
+
else:
|
| 174 |
+
expected = pd.DataFrame([[1, 2, 3]], columns=["a", "b", "c"])
|
| 175 |
+
|
| 176 |
+
if parser.engine == "pyarrow":
|
| 177 |
+
msg = "The 'comment' option is not supported with the 'pyarrow' engine"
|
| 178 |
+
with pytest.raises(ValueError, match=msg):
|
| 179 |
+
parser.read_csv(StringIO(data), comment="#", header=header)
|
| 180 |
+
return
|
| 181 |
+
result = parser.read_csv(StringIO(data), comment="#", header=header)
|
| 182 |
+
tm.assert_frame_equal(result, expected)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def test_comment_char_in_default_value(all_parsers, request):
|
| 186 |
+
# GH#34002
|
| 187 |
+
if all_parsers.engine == "c":
|
| 188 |
+
reason = "see gh-34002: works on the python engine but not the c engine"
|
| 189 |
+
# NA value containing comment char is interpreted as comment
|
| 190 |
+
request.applymarker(pytest.mark.xfail(reason=reason, raises=AssertionError))
|
| 191 |
+
parser = all_parsers
|
| 192 |
+
|
| 193 |
+
data = (
|
| 194 |
+
"# this is a comment\n"
|
| 195 |
+
"col1,col2,col3,col4\n"
|
| 196 |
+
"1,2,3,4#inline comment\n"
|
| 197 |
+
"4,5#,6,10\n"
|
| 198 |
+
"7,8,#N/A,11\n"
|
| 199 |
+
)
|
| 200 |
+
if parser.engine == "pyarrow":
|
| 201 |
+
msg = "The 'comment' option is not supported with the 'pyarrow' engine"
|
| 202 |
+
with pytest.raises(ValueError, match=msg):
|
| 203 |
+
parser.read_csv(StringIO(data), comment="#", na_values="#N/A")
|
| 204 |
+
return
|
| 205 |
+
result = parser.read_csv(StringIO(data), comment="#", na_values="#N/A")
|
| 206 |
+
expected = pd.DataFrame(
|
| 207 |
+
{
|
| 208 |
+
"col1": [1, 4, 7],
|
| 209 |
+
"col2": [2, 5, 8],
|
| 210 |
+
"col3": [3.0, np.nan, np.nan],
|
| 211 |
+
"col4": [4.0, np.nan, 11.0],
|
| 212 |
+
}
|
| 213 |
+
)
|
| 214 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_compression.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests compressed data parsing functionality for all
|
| 3 |
+
of the parsers defined in parsers.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import tarfile
|
| 8 |
+
import zipfile
|
| 9 |
+
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@pytest.fixture(params=[True, False])
|
| 17 |
+
def buffer(request):
|
| 18 |
+
return request.param
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@pytest.fixture
|
| 22 |
+
def parser_and_data(all_parsers, csv1):
|
| 23 |
+
parser = all_parsers
|
| 24 |
+
|
| 25 |
+
with open(csv1, "rb") as f:
|
| 26 |
+
data = f.read()
|
| 27 |
+
expected = parser.read_csv(csv1)
|
| 28 |
+
|
| 29 |
+
return parser, data, expected
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@pytest.mark.parametrize("compression", ["zip", "infer", "zip2"])
|
| 33 |
+
def test_zip(tmp_path, parser_and_data, compression):
|
| 34 |
+
parser, data, expected = parser_and_data
|
| 35 |
+
|
| 36 |
+
path = tmp_path / "test_file.zip"
|
| 37 |
+
with zipfile.ZipFile(path, mode="w") as tmp:
|
| 38 |
+
tmp.writestr("test_file", data)
|
| 39 |
+
|
| 40 |
+
if compression == "zip2":
|
| 41 |
+
with open(path, "rb") as f:
|
| 42 |
+
result = parser.read_csv(f, compression="zip")
|
| 43 |
+
else:
|
| 44 |
+
result = parser.read_csv(path, compression=compression)
|
| 45 |
+
|
| 46 |
+
tm.assert_frame_equal(result, expected)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@pytest.mark.parametrize("compression", ["zip", "infer"])
|
| 50 |
+
def test_zip_error_multiple_files(tmp_path, parser_and_data, compression):
|
| 51 |
+
parser, data, expected = parser_and_data
|
| 52 |
+
|
| 53 |
+
path = tmp_path / "combined_zip.zip"
|
| 54 |
+
inner_file_names = ["test_file", "second_file"]
|
| 55 |
+
|
| 56 |
+
with zipfile.ZipFile(path, mode="w") as tmp:
|
| 57 |
+
for file_name in inner_file_names:
|
| 58 |
+
tmp.writestr(file_name, data)
|
| 59 |
+
|
| 60 |
+
with pytest.raises(ValueError, match="Multiple files"):
|
| 61 |
+
parser.read_csv(path, compression=compression)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_zip_error_no_files(tmp_path, parser_and_data):
|
| 65 |
+
parser, _, _ = parser_and_data
|
| 66 |
+
|
| 67 |
+
path = tmp_path / "test_file.zip"
|
| 68 |
+
with zipfile.ZipFile(path, mode="w"):
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
with pytest.raises(ValueError, match="Zero files"):
|
| 72 |
+
parser.read_csv(path, compression="zip")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_zip_error_invalid_zip(tmp_path, parser_and_data):
|
| 76 |
+
parser, _, _ = parser_and_data
|
| 77 |
+
|
| 78 |
+
path = tmp_path / "invalid_file.zip"
|
| 79 |
+
path.touch()
|
| 80 |
+
with open(path, "rb") as f:
|
| 81 |
+
with pytest.raises(zipfile.BadZipFile, match="File is not a zip file"):
|
| 82 |
+
parser.read_csv(f, compression="zip")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@pytest.mark.parametrize("filename", [None, "test.{ext}"])
|
| 86 |
+
def test_compression(
|
| 87 |
+
tmp_path,
|
| 88 |
+
request,
|
| 89 |
+
parser_and_data,
|
| 90 |
+
compression_only,
|
| 91 |
+
buffer,
|
| 92 |
+
filename,
|
| 93 |
+
compression_to_extension,
|
| 94 |
+
):
|
| 95 |
+
parser, data, expected = parser_and_data
|
| 96 |
+
compress_type = compression_only
|
| 97 |
+
|
| 98 |
+
ext = compression_to_extension[compress_type]
|
| 99 |
+
filename = filename if filename is None else filename.format(ext=ext)
|
| 100 |
+
|
| 101 |
+
if filename and buffer:
|
| 102 |
+
request.applymarker(
|
| 103 |
+
pytest.mark.xfail(
|
| 104 |
+
reason="Cannot deduce compression from buffer of compressed data."
|
| 105 |
+
)
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
path = tmp_path / filename if filename else tmp_path / "test_file"
|
| 109 |
+
tm.write_to_compressed(compress_type, path, data)
|
| 110 |
+
compression = "infer" if filename else compress_type
|
| 111 |
+
|
| 112 |
+
if buffer:
|
| 113 |
+
with open(path, "rb") as f:
|
| 114 |
+
result = parser.read_csv(f, compression=compression)
|
| 115 |
+
else:
|
| 116 |
+
result = parser.read_csv(path, compression=compression)
|
| 117 |
+
|
| 118 |
+
tm.assert_frame_equal(result, expected)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@pytest.mark.parametrize("ext", [None, "gz", "bz2"])
|
| 122 |
+
def test_infer_compression(all_parsers, csv1, buffer, ext):
|
| 123 |
+
# see gh-9770
|
| 124 |
+
parser = all_parsers
|
| 125 |
+
kwargs = {"index_col": 0, "parse_dates": True}
|
| 126 |
+
|
| 127 |
+
expected = parser.read_csv(csv1, **kwargs)
|
| 128 |
+
kwargs["compression"] = "infer"
|
| 129 |
+
|
| 130 |
+
if buffer:
|
| 131 |
+
with open(csv1, encoding="utf-8") as f:
|
| 132 |
+
result = parser.read_csv(f, **kwargs)
|
| 133 |
+
else:
|
| 134 |
+
ext = "." + ext if ext else ""
|
| 135 |
+
result = parser.read_csv(csv1 + ext, **kwargs)
|
| 136 |
+
|
| 137 |
+
tm.assert_frame_equal(result, expected)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_compression_utf_encoding(all_parsers, datapath, utf_value, encoding_fmt):
|
| 141 |
+
# see gh-18071, gh-24130
|
| 142 |
+
parser = all_parsers
|
| 143 |
+
encoding = encoding_fmt.format(utf_value)
|
| 144 |
+
path = datapath("io", "parser", "data", f"utf{utf_value}_ex_small.zip")
|
| 145 |
+
|
| 146 |
+
result = parser.read_csv(path, encoding=encoding, compression="zip", sep="\t")
|
| 147 |
+
expected = pd.DataFrame(
|
| 148 |
+
{
|
| 149 |
+
"Country": ["Venezuela", "Venezuela"],
|
| 150 |
+
"Twitter": ["Hugo Chávez Frías", "Henrique Capriles R."],
|
| 151 |
+
}
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
tm.assert_frame_equal(result, expected)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
@pytest.mark.parametrize("invalid_compression", ["sfark", "bz3", "zipper"])
|
| 158 |
+
def test_invalid_compression(all_parsers, invalid_compression):
|
| 159 |
+
parser = all_parsers
|
| 160 |
+
compress_kwargs = {"compression": invalid_compression}
|
| 161 |
+
|
| 162 |
+
msg = f"Unrecognized compression type: {invalid_compression}"
|
| 163 |
+
|
| 164 |
+
with pytest.raises(ValueError, match=msg):
|
| 165 |
+
parser.read_csv("test_file.zip", **compress_kwargs)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_compression_tar_archive(all_parsers, datapath):
|
| 169 |
+
parser = all_parsers
|
| 170 |
+
path = datapath("io", "parser", "data", "tar_csv.tar.gz")
|
| 171 |
+
df = parser.read_csv(path)
|
| 172 |
+
assert list(df.columns) == ["a"]
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def test_ignore_compression_extension(tmp_path, all_parsers):
|
| 176 |
+
parser = all_parsers
|
| 177 |
+
df = pd.DataFrame({"a": [0, 1]})
|
| 178 |
+
|
| 179 |
+
path_csv = tmp_path / "test.csv"
|
| 180 |
+
path_zip = tmp_path / "test.csv.zip"
|
| 181 |
+
# make sure to create un-compressed file with zip extension
|
| 182 |
+
df.to_csv(path_csv, index=False)
|
| 183 |
+
Path(path_zip).write_text(
|
| 184 |
+
Path(path_csv).read_text(encoding="utf-8"), encoding="utf-8"
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
tm.assert_frame_equal(parser.read_csv(path_zip, compression=None), df)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_writes_tar_gz(tmp_path, all_parsers):
|
| 191 |
+
parser = all_parsers
|
| 192 |
+
data = pd.DataFrame(
|
| 193 |
+
{
|
| 194 |
+
"Country": ["Venezuela", "Venezuela"],
|
| 195 |
+
"Twitter": ["Hugo Chávez Frías", "Henrique Capriles R."],
|
| 196 |
+
}
|
| 197 |
+
)
|
| 198 |
+
tar_path = tmp_path / "test.tar.gz"
|
| 199 |
+
data.to_csv(tar_path, index=False)
|
| 200 |
+
|
| 201 |
+
# test that read_csv infers .tar.gz to gzip:
|
| 202 |
+
tm.assert_frame_equal(parser.read_csv(tar_path), data)
|
| 203 |
+
|
| 204 |
+
# test that file is indeed gzipped:
|
| 205 |
+
with tarfile.open(tar_path, "r:gz") as tar:
|
| 206 |
+
result = parser.read_csv(
|
| 207 |
+
tar.extractfile(tar.getnames()[0]), compression="infer"
|
| 208 |
+
)
|
| 209 |
+
tm.assert_frame_equal(result, data)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_concatenate_chunks.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas.errors import DtypeWarning
|
| 5 |
+
|
| 6 |
+
import pandas._testing as tm
|
| 7 |
+
from pandas.core.arrays import ArrowExtensionArray
|
| 8 |
+
|
| 9 |
+
from pandas.io.parsers.c_parser_wrapper import _concatenate_chunks
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_concatenate_chunks_pyarrow():
|
| 13 |
+
# GH#51876
|
| 14 |
+
pa = pytest.importorskip("pyarrow")
|
| 15 |
+
chunks = [
|
| 16 |
+
{0: ArrowExtensionArray(pa.array([1.5, 2.5]))},
|
| 17 |
+
{0: ArrowExtensionArray(pa.array([1, 2]))},
|
| 18 |
+
]
|
| 19 |
+
result = _concatenate_chunks(chunks, ["column_0", "column_1"])
|
| 20 |
+
expected = ArrowExtensionArray(pa.array([1.5, 2.5, 1.0, 2.0]))
|
| 21 |
+
tm.assert_extension_array_equal(result[0], expected)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_concatenate_chunks_pyarrow_strings():
|
| 25 |
+
# GH#51876
|
| 26 |
+
pa = pytest.importorskip("pyarrow")
|
| 27 |
+
chunks = [
|
| 28 |
+
{0: ArrowExtensionArray(pa.array([1.5, 2.5]))},
|
| 29 |
+
{0: ArrowExtensionArray(pa.array(["a", "b"]))},
|
| 30 |
+
]
|
| 31 |
+
with tm.assert_produces_warning(
|
| 32 |
+
DtypeWarning, match="Columns \\(0: column_0\\) have mixed types"
|
| 33 |
+
):
|
| 34 |
+
result = _concatenate_chunks(chunks, ["column_0", "column_1"])
|
| 35 |
+
expected = np.concatenate(
|
| 36 |
+
[np.array([1.5, 2.5], dtype=object), np.array(["a", "b"])]
|
| 37 |
+
)
|
| 38 |
+
tm.assert_numpy_array_equal(result[0], expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_converters.py
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests column conversion functionality during parsing
|
| 3 |
+
for all of the parsers defined in parsers.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from io import StringIO
|
| 7 |
+
|
| 8 |
+
from dateutil.parser import parse
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_converters_type_must_be_dict(all_parsers):
|
| 17 |
+
parser = all_parsers
|
| 18 |
+
data = """index,A,B,C,D
|
| 19 |
+
foo,2,3,4,5
|
| 20 |
+
"""
|
| 21 |
+
if parser.engine == "pyarrow":
|
| 22 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 23 |
+
with pytest.raises(ValueError, match=msg):
|
| 24 |
+
parser.read_csv(StringIO(data), converters=0)
|
| 25 |
+
return
|
| 26 |
+
with pytest.raises(TypeError, match="Type converters.+"):
|
| 27 |
+
parser.read_csv(StringIO(data), converters=0)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.mark.parametrize("column", [3, "D"])
|
| 31 |
+
@pytest.mark.parametrize(
|
| 32 |
+
"converter",
|
| 33 |
+
[parse, lambda x: int(x.split("/")[2])], # Produce integer.
|
| 34 |
+
)
|
| 35 |
+
def test_converters(all_parsers, column, converter):
|
| 36 |
+
parser = all_parsers
|
| 37 |
+
data = """A,B,C,D
|
| 38 |
+
a,1,2,01/01/2009
|
| 39 |
+
b,3,4,01/02/2009
|
| 40 |
+
c,4,5,01/03/2009
|
| 41 |
+
"""
|
| 42 |
+
if parser.engine == "pyarrow":
|
| 43 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 44 |
+
with pytest.raises(ValueError, match=msg):
|
| 45 |
+
parser.read_csv(StringIO(data), converters={column: converter})
|
| 46 |
+
return
|
| 47 |
+
|
| 48 |
+
result = parser.read_csv(StringIO(data), converters={column: converter})
|
| 49 |
+
|
| 50 |
+
expected = parser.read_csv(StringIO(data))
|
| 51 |
+
expected["D"] = expected["D"].map(converter)
|
| 52 |
+
|
| 53 |
+
tm.assert_frame_equal(result, expected)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_converters_no_implicit_conv(all_parsers):
|
| 57 |
+
# see gh-2184
|
| 58 |
+
parser = all_parsers
|
| 59 |
+
data = """000102,1.2,A\n001245,2,B"""
|
| 60 |
+
|
| 61 |
+
converters = {0: lambda x: x.strip()}
|
| 62 |
+
|
| 63 |
+
if parser.engine == "pyarrow":
|
| 64 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 65 |
+
with pytest.raises(ValueError, match=msg):
|
| 66 |
+
parser.read_csv(StringIO(data), header=None, converters=converters)
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
result = parser.read_csv(StringIO(data), header=None, converters=converters)
|
| 70 |
+
|
| 71 |
+
# Column 0 should not be casted to numeric and should remain as object.
|
| 72 |
+
expected = pd.DataFrame([["000102", 1.2, "A"], ["001245", 2, "B"]])
|
| 73 |
+
tm.assert_frame_equal(result, expected)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_converters_euro_decimal_format(all_parsers):
|
| 77 |
+
# see gh-583
|
| 78 |
+
converters = {}
|
| 79 |
+
parser = all_parsers
|
| 80 |
+
|
| 81 |
+
data = """Id;Number1;Number2;Text1;Text2;Number3
|
| 82 |
+
1;1521,1541;187101,9543;ABC;poi;4,7387
|
| 83 |
+
2;121,12;14897,76;DEF;uyt;0,3773
|
| 84 |
+
3;878,158;108013,434;GHI;rez;2,7356"""
|
| 85 |
+
converters["Number1"] = converters["Number2"] = converters["Number3"] = lambda x: (
|
| 86 |
+
float(x.replace(",", "."))
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if parser.engine == "pyarrow":
|
| 90 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 91 |
+
with pytest.raises(ValueError, match=msg):
|
| 92 |
+
parser.read_csv(StringIO(data), sep=";", converters=converters)
|
| 93 |
+
return
|
| 94 |
+
|
| 95 |
+
result = parser.read_csv(StringIO(data), sep=";", converters=converters)
|
| 96 |
+
expected = pd.DataFrame(
|
| 97 |
+
[
|
| 98 |
+
[1, 1521.1541, 187101.9543, "ABC", "poi", 4.7387],
|
| 99 |
+
[2, 121.12, 14897.76, "DEF", "uyt", 0.3773],
|
| 100 |
+
[3, 878.158, 108013.434, "GHI", "rez", 2.7356],
|
| 101 |
+
],
|
| 102 |
+
columns=["Id", "Number1", "Number2", "Text1", "Text2", "Number3"],
|
| 103 |
+
)
|
| 104 |
+
tm.assert_frame_equal(result, expected)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_converters_corner_with_nans(all_parsers):
|
| 108 |
+
parser = all_parsers
|
| 109 |
+
data = """id,score,days
|
| 110 |
+
1,2,12
|
| 111 |
+
2,2-5,
|
| 112 |
+
3,,14+
|
| 113 |
+
4,6-12,2"""
|
| 114 |
+
|
| 115 |
+
# Example converters.
|
| 116 |
+
def convert_days(x):
|
| 117 |
+
x = x.strip()
|
| 118 |
+
|
| 119 |
+
if not x:
|
| 120 |
+
return np.nan
|
| 121 |
+
|
| 122 |
+
is_plus = x.endswith("+")
|
| 123 |
+
|
| 124 |
+
if is_plus:
|
| 125 |
+
x = int(x[:-1]) + 1
|
| 126 |
+
else:
|
| 127 |
+
x = int(x)
|
| 128 |
+
|
| 129 |
+
return x
|
| 130 |
+
|
| 131 |
+
def convert_days_sentinel(x):
|
| 132 |
+
x = x.strip()
|
| 133 |
+
|
| 134 |
+
if not x:
|
| 135 |
+
return np.nan
|
| 136 |
+
|
| 137 |
+
is_plus = x.endswith("+")
|
| 138 |
+
|
| 139 |
+
if is_plus:
|
| 140 |
+
x = int(x[:-1]) + 1
|
| 141 |
+
else:
|
| 142 |
+
x = int(x)
|
| 143 |
+
|
| 144 |
+
return x
|
| 145 |
+
|
| 146 |
+
def convert_score(x):
|
| 147 |
+
x = x.strip()
|
| 148 |
+
|
| 149 |
+
if not x:
|
| 150 |
+
return np.nan
|
| 151 |
+
|
| 152 |
+
if x.find("-") > 0:
|
| 153 |
+
val_min, val_max = map(int, x.split("-"))
|
| 154 |
+
val = 0.5 * (val_min + val_max)
|
| 155 |
+
else:
|
| 156 |
+
val = float(x)
|
| 157 |
+
|
| 158 |
+
return val
|
| 159 |
+
|
| 160 |
+
results = []
|
| 161 |
+
|
| 162 |
+
for day_converter in [convert_days, convert_days_sentinel]:
|
| 163 |
+
if parser.engine == "pyarrow":
|
| 164 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 165 |
+
with pytest.raises(ValueError, match=msg):
|
| 166 |
+
parser.read_csv(
|
| 167 |
+
StringIO(data),
|
| 168 |
+
converters={"score": convert_score, "days": day_converter},
|
| 169 |
+
na_values=["", None],
|
| 170 |
+
)
|
| 171 |
+
continue
|
| 172 |
+
|
| 173 |
+
result = parser.read_csv(
|
| 174 |
+
StringIO(data),
|
| 175 |
+
converters={"score": convert_score, "days": day_converter},
|
| 176 |
+
na_values=["", None],
|
| 177 |
+
)
|
| 178 |
+
assert pd.isna(result["days"][1])
|
| 179 |
+
results.append(result)
|
| 180 |
+
|
| 181 |
+
if parser.engine != "pyarrow":
|
| 182 |
+
tm.assert_frame_equal(results[0], results[1])
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@pytest.mark.parametrize("conv_f", [lambda x: x, str])
|
| 186 |
+
def test_converter_index_col_bug(all_parsers, conv_f):
|
| 187 |
+
# see gh-1835 , GH#40589
|
| 188 |
+
parser = all_parsers
|
| 189 |
+
data = "A;B\n1;2\n3;4"
|
| 190 |
+
|
| 191 |
+
if parser.engine == "pyarrow":
|
| 192 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 193 |
+
with pytest.raises(ValueError, match=msg):
|
| 194 |
+
parser.read_csv(
|
| 195 |
+
StringIO(data), sep=";", index_col="A", converters={"A": conv_f}
|
| 196 |
+
)
|
| 197 |
+
return
|
| 198 |
+
|
| 199 |
+
rs = parser.read_csv(
|
| 200 |
+
StringIO(data), sep=";", index_col="A", converters={"A": conv_f}
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
xp = pd.DataFrame({"B": [2, 4]}, index=pd.Index(["1", "3"], name="A"))
|
| 204 |
+
tm.assert_frame_equal(rs, xp)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def test_converter_identity_object(all_parsers):
|
| 208 |
+
# GH#40589
|
| 209 |
+
parser = all_parsers
|
| 210 |
+
data = "A,B\n1,2\n3,4"
|
| 211 |
+
|
| 212 |
+
if parser.engine == "pyarrow":
|
| 213 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 214 |
+
with pytest.raises(ValueError, match=msg):
|
| 215 |
+
parser.read_csv(StringIO(data), converters={"A": lambda x: x})
|
| 216 |
+
return
|
| 217 |
+
|
| 218 |
+
rs = parser.read_csv(StringIO(data), converters={"A": lambda x: x})
|
| 219 |
+
|
| 220 |
+
xp = pd.DataFrame({"A": ["1", "3"], "B": [2, 4]})
|
| 221 |
+
tm.assert_frame_equal(rs, xp)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def test_converter_multi_index(all_parsers):
|
| 225 |
+
# GH 42446
|
| 226 |
+
parser = all_parsers
|
| 227 |
+
data = "A,B,B\nX,Y,Z\n1,2,3"
|
| 228 |
+
|
| 229 |
+
if parser.engine == "pyarrow":
|
| 230 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 231 |
+
with pytest.raises(ValueError, match=msg):
|
| 232 |
+
parser.read_csv(
|
| 233 |
+
StringIO(data),
|
| 234 |
+
header=list(range(2)),
|
| 235 |
+
converters={
|
| 236 |
+
("A", "X"): np.int32,
|
| 237 |
+
("B", "Y"): np.int32,
|
| 238 |
+
("B", "Z"): np.float32,
|
| 239 |
+
},
|
| 240 |
+
)
|
| 241 |
+
return
|
| 242 |
+
|
| 243 |
+
result = parser.read_csv(
|
| 244 |
+
StringIO(data),
|
| 245 |
+
header=list(range(2)),
|
| 246 |
+
converters={
|
| 247 |
+
("A", "X"): np.int32,
|
| 248 |
+
("B", "Y"): np.int32,
|
| 249 |
+
("B", "Z"): np.float32,
|
| 250 |
+
},
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
expected = pd.DataFrame(
|
| 254 |
+
{
|
| 255 |
+
("A", "X"): np.int32([1]),
|
| 256 |
+
("B", "Y"): np.int32([2]),
|
| 257 |
+
("B", "Z"): np.float32([3]),
|
| 258 |
+
}
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
tm.assert_frame_equal(result, expected)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
@pytest.mark.parametrize("keep_default_na", [True, False])
|
| 265 |
+
@pytest.mark.parametrize(
|
| 266 |
+
"na_values,values",
|
| 267 |
+
[
|
| 268 |
+
("CAT", ["1", np.nan, "3"]),
|
| 269 |
+
([-999, "CAT"], ["1", np.nan, "3"]),
|
| 270 |
+
({"A": ["CAT"]}, ["1", np.nan, "3"]),
|
| 271 |
+
({0: ["CAT"]}, ["1", np.nan, "3"]),
|
| 272 |
+
# no entry for the converter column, so it gets the defaults or nothing
|
| 273 |
+
({"B": ["CAT"]}, ["1", "CAT", "3"]),
|
| 274 |
+
],
|
| 275 |
+
)
|
| 276 |
+
def test_converters_na_values(all_parsers, na_values, values, keep_default_na):
|
| 277 |
+
# GH#13302 the c engine skipped na_values entirely on a converter column
|
| 278 |
+
parser = all_parsers
|
| 279 |
+
data = "A,B\nx1,x\nCAT,y\nx3,z"
|
| 280 |
+
converters = {"A": lambda x: x.lstrip("x")}
|
| 281 |
+
kwargs = {
|
| 282 |
+
"converters": converters,
|
| 283 |
+
"na_values": na_values,
|
| 284 |
+
"keep_default_na": keep_default_na,
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
if parser.engine == "pyarrow":
|
| 288 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 289 |
+
with pytest.raises(ValueError, match=msg):
|
| 290 |
+
parser.read_csv(StringIO(data), **kwargs)
|
| 291 |
+
return
|
| 292 |
+
|
| 293 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 294 |
+
expected = pd.DataFrame({"A": values, "B": ["x", "y", "z"]})
|
| 295 |
+
tm.assert_frame_equal(result, expected)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
@pytest.mark.parametrize(
|
| 299 |
+
"kwargs,values",
|
| 300 |
+
[
|
| 301 |
+
({}, ["1", np.nan, "CAT"]),
|
| 302 |
+
({"keep_default_na": False}, ["1", "", "CAT"]),
|
| 303 |
+
({"keep_default_na": False, "na_values": "CAT"}, ["1", "", np.nan]),
|
| 304 |
+
({"na_filter": False, "na_values": "CAT"}, ["1", "", "CAT"]),
|
| 305 |
+
],
|
| 306 |
+
)
|
| 307 |
+
def test_converters_default_na_values(all_parsers, kwargs, values):
|
| 308 |
+
# GH#13302 the default NA strings, keep_default_na and na_filter apply to
|
| 309 |
+
# a converter column as they do to any other
|
| 310 |
+
parser = all_parsers
|
| 311 |
+
data = "A,B\n1,x\n,y\nCAT,z"
|
| 312 |
+
converters = {"A": str}
|
| 313 |
+
|
| 314 |
+
if parser.engine == "pyarrow":
|
| 315 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 316 |
+
with pytest.raises(ValueError, match=msg):
|
| 317 |
+
parser.read_csv(StringIO(data), converters=converters, **kwargs)
|
| 318 |
+
return
|
| 319 |
+
|
| 320 |
+
result = parser.read_csv(StringIO(data), converters=converters, **kwargs)
|
| 321 |
+
expected = pd.DataFrame({"A": values, "B": ["x", "y", "z"]})
|
| 322 |
+
tm.assert_frame_equal(result, expected)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def test_converters_na_values_numeric_output(all_parsers):
|
| 326 |
+
# GH#13302 na_values are matched against the converter's output, so the
|
| 327 |
+
# column still infers a numeric dtype
|
| 328 |
+
parser = all_parsers
|
| 329 |
+
data = "A\n1\n-999\n3"
|
| 330 |
+
converters = {"A": int}
|
| 331 |
+
|
| 332 |
+
if parser.engine == "pyarrow":
|
| 333 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 334 |
+
with pytest.raises(ValueError, match=msg):
|
| 335 |
+
parser.read_csv(StringIO(data), converters=converters, na_values=[-999])
|
| 336 |
+
return
|
| 337 |
+
|
| 338 |
+
result = parser.read_csv(StringIO(data), converters=converters, na_values=[-999])
|
| 339 |
+
tm.assert_frame_equal(result, pd.DataFrame({"A": [1.0, np.nan, 3.0]}))
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
@pytest.mark.parametrize(
|
| 343 |
+
"data,converters,values",
|
| 344 |
+
[
|
| 345 |
+
("A,B\nCAT,x\nCAT,y", {"A": lambda x: x}, [np.nan, np.nan]),
|
| 346 |
+
(
|
| 347 |
+
"A,B\n1,x\nCAT,y",
|
| 348 |
+
{"A": lambda x: int(x) if x.isdigit() else x},
|
| 349 |
+
[1.0, np.nan],
|
| 350 |
+
),
|
| 351 |
+
],
|
| 352 |
+
)
|
| 353 |
+
def test_converters_na_values_dtype(all_parsers, request, data, converters, values):
|
| 354 |
+
# GH#13302 a converter column is re-inferred after the NA substitution, so
|
| 355 |
+
# it lands on the dtype the read without a converter would give
|
| 356 |
+
parser = all_parsers
|
| 357 |
+
|
| 358 |
+
if parser.engine == "pyarrow":
|
| 359 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 360 |
+
with pytest.raises(ValueError, match=msg):
|
| 361 |
+
parser.read_csv(StringIO(data), converters=converters, na_values="CAT")
|
| 362 |
+
return
|
| 363 |
+
|
| 364 |
+
if parser.engine == "python":
|
| 365 |
+
mark = pytest.mark.xfail(
|
| 366 |
+
reason="python engine does not re-infer a converter column"
|
| 367 |
+
)
|
| 368 |
+
request.applymarker(mark)
|
| 369 |
+
|
| 370 |
+
result = parser.read_csv(StringIO(data), converters=converters, na_values="CAT")
|
| 371 |
+
expected = pd.DataFrame({"A": values, "B": ["x", "y"]})
|
| 372 |
+
tm.assert_frame_equal(result, expected)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def test_converters_na_values_index_col(all_parsers):
|
| 376 |
+
# GH#13302 na_values apply to a converter column used as the index. The
|
| 377 |
+
# converter is an identity so that this passes on the python engine, which
|
| 378 |
+
# never calls a converter for an index column.
|
| 379 |
+
parser = all_parsers
|
| 380 |
+
data = "A,B\nq,x\nCAT,y"
|
| 381 |
+
converters = {"A": lambda x: x}
|
| 382 |
+
|
| 383 |
+
if parser.engine == "pyarrow":
|
| 384 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 385 |
+
with pytest.raises(ValueError, match=msg):
|
| 386 |
+
parser.read_csv(
|
| 387 |
+
StringIO(data), converters=converters, na_values=["CAT"], index_col=0
|
| 388 |
+
)
|
| 389 |
+
return
|
| 390 |
+
|
| 391 |
+
result = parser.read_csv(
|
| 392 |
+
StringIO(data), converters=converters, na_values=["CAT"], index_col=0
|
| 393 |
+
)
|
| 394 |
+
expected = pd.DataFrame({"B": ["x", "y"]}, index=pd.Index(["q", np.nan], name="A"))
|
| 395 |
+
tm.assert_frame_equal(result, expected)
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def test_converters_na_values_bool_output(all_parsers, request):
|
| 399 |
+
# GH#13302 True == 1, so bools a converter returns match a numeric
|
| 400 |
+
# na_values entry, the same cells the read without a converter drops
|
| 401 |
+
parser = all_parsers
|
| 402 |
+
data = "A\n1\n0\n1"
|
| 403 |
+
converters = {"A": lambda x: bool(int(x))}
|
| 404 |
+
|
| 405 |
+
if parser.engine == "pyarrow":
|
| 406 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 407 |
+
with pytest.raises(ValueError, match=msg):
|
| 408 |
+
parser.read_csv(StringIO(data), converters=converters, na_values=[1])
|
| 409 |
+
return
|
| 410 |
+
|
| 411 |
+
if parser.engine == "python":
|
| 412 |
+
# np.putmask writes the NaN into a bool array, where it reads as True
|
| 413 |
+
mark = pytest.mark.xfail(reason="python engine writes NaN into a bool array")
|
| 414 |
+
request.applymarker(mark)
|
| 415 |
+
|
| 416 |
+
result = parser.read_csv(StringIO(data), converters=converters, na_values=[1])
|
| 417 |
+
expected = pd.DataFrame({"A": [np.nan, False, np.nan]}, dtype=object)
|
| 418 |
+
tm.assert_frame_equal(result, expected)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def test_converters_raising_on_empty_field(all_parsers, request):
|
| 422 |
+
# GH#13302 na_values apply to the converter's output, so a converter that
|
| 423 |
+
# raises on an empty field still raises
|
| 424 |
+
parser = all_parsers
|
| 425 |
+
data = "a,b\n1,x\n,y\n3,z"
|
| 426 |
+
|
| 427 |
+
if parser.engine == "pyarrow":
|
| 428 |
+
msg = "The 'converters' option is not supported with the 'pyarrow' engine"
|
| 429 |
+
with pytest.raises(ValueError, match=msg):
|
| 430 |
+
parser.read_csv(StringIO(data), converters={"a": float})
|
| 431 |
+
return
|
| 432 |
+
|
| 433 |
+
if parser.engine == "python":
|
| 434 |
+
mark = pytest.mark.xfail(
|
| 435 |
+
reason="python engine retries with the NA tokens masked"
|
| 436 |
+
)
|
| 437 |
+
request.applymarker(mark)
|
| 438 |
+
|
| 439 |
+
with pytest.raises(ValueError, match="could not convert string to float"):
|
| 440 |
+
parser.read_csv(StringIO(data), converters={"a": float})
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_dialect.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that dialects are properly handled during parsing
|
| 3 |
+
for all of the parsers defined in parsers.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import csv
|
| 7 |
+
from io import StringIO
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
from pandas.errors import ParserWarning
|
| 12 |
+
|
| 13 |
+
import pandas as pd
|
| 14 |
+
import pandas._testing as tm
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.fixture
|
| 18 |
+
def custom_dialect():
|
| 19 |
+
dialect_name = "weird"
|
| 20 |
+
dialect_kwargs = {
|
| 21 |
+
"doublequote": False,
|
| 22 |
+
"escapechar": "~",
|
| 23 |
+
"delimiter": ":",
|
| 24 |
+
"skipinitialspace": False,
|
| 25 |
+
"quotechar": "`",
|
| 26 |
+
"quoting": 3,
|
| 27 |
+
}
|
| 28 |
+
return dialect_name, dialect_kwargs
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_dialect(all_parsers):
|
| 32 |
+
parser = all_parsers
|
| 33 |
+
data = """\
|
| 34 |
+
label1,label2,label3
|
| 35 |
+
index1,"a,c,e
|
| 36 |
+
index2,b,d,f
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
dia = csv.excel()
|
| 40 |
+
dia.quoting = csv.QUOTE_NONE
|
| 41 |
+
|
| 42 |
+
if parser.engine == "pyarrow":
|
| 43 |
+
msg = "The 'dialect' option is not supported with the 'pyarrow' engine"
|
| 44 |
+
with pytest.raises(ValueError, match=msg):
|
| 45 |
+
parser.read_csv(StringIO(data), dialect=dia)
|
| 46 |
+
return
|
| 47 |
+
|
| 48 |
+
df = parser.read_csv(StringIO(data), dialect=dia)
|
| 49 |
+
|
| 50 |
+
data = """\
|
| 51 |
+
label1,label2,label3
|
| 52 |
+
index1,a,c,e
|
| 53 |
+
index2,b,d,f
|
| 54 |
+
"""
|
| 55 |
+
exp = parser.read_csv(StringIO(data))
|
| 56 |
+
exp.replace("a", '"a', inplace=True)
|
| 57 |
+
tm.assert_frame_equal(df, exp)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_dialect_str(all_parsers):
|
| 61 |
+
dialect_name = "mydialect"
|
| 62 |
+
parser = all_parsers
|
| 63 |
+
data = """\
|
| 64 |
+
fruit:vegetable
|
| 65 |
+
apple:broccoli
|
| 66 |
+
pear:tomato
|
| 67 |
+
"""
|
| 68 |
+
exp = pd.DataFrame(
|
| 69 |
+
{"fruit": ["apple", "pear"], "vegetable": ["broccoli", "tomato"]}
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
with tm.with_csv_dialect(dialect_name, delimiter=":"):
|
| 73 |
+
if parser.engine == "pyarrow":
|
| 74 |
+
msg = "The 'dialect' option is not supported with the 'pyarrow' engine"
|
| 75 |
+
with pytest.raises(ValueError, match=msg):
|
| 76 |
+
parser.read_csv(StringIO(data), dialect=dialect_name)
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
df = parser.read_csv(StringIO(data), dialect=dialect_name)
|
| 80 |
+
tm.assert_frame_equal(df, exp)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def test_invalid_dialect(all_parsers):
|
| 84 |
+
class InvalidDialect:
|
| 85 |
+
pass
|
| 86 |
+
|
| 87 |
+
data = "a\n1"
|
| 88 |
+
parser = all_parsers
|
| 89 |
+
msg = "Invalid dialect"
|
| 90 |
+
|
| 91 |
+
with pytest.raises(ValueError, match=msg):
|
| 92 |
+
parser.read_csv(StringIO(data), dialect=InvalidDialect)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@pytest.mark.parametrize(
|
| 96 |
+
"arg",
|
| 97 |
+
[None, "doublequote", "escapechar", "skipinitialspace", "quotechar", "quoting"],
|
| 98 |
+
)
|
| 99 |
+
@pytest.mark.parametrize("value", ["dialect", "default", "other"])
|
| 100 |
+
def test_dialect_conflict_except_delimiter(all_parsers, custom_dialect, arg, value):
|
| 101 |
+
# see gh-23761.
|
| 102 |
+
dialect_name, dialect_kwargs = custom_dialect
|
| 103 |
+
parser = all_parsers
|
| 104 |
+
|
| 105 |
+
expected = pd.DataFrame({"a": [1], "b": [2]})
|
| 106 |
+
data = "a:b\n1:2"
|
| 107 |
+
|
| 108 |
+
warning_klass = None
|
| 109 |
+
kwds = {}
|
| 110 |
+
|
| 111 |
+
# arg=None tests when we pass in the dialect without any other arguments.
|
| 112 |
+
if arg is not None:
|
| 113 |
+
if value == "dialect": # No conflict --> no warning.
|
| 114 |
+
kwds[arg] = dialect_kwargs[arg]
|
| 115 |
+
elif value == "default": # Default --> no warning.
|
| 116 |
+
from pandas.io.parsers.base_parser import parser_defaults
|
| 117 |
+
|
| 118 |
+
kwds[arg] = parser_defaults[arg]
|
| 119 |
+
else: # Non-default + conflict with dialect --> warning.
|
| 120 |
+
warning_klass = ParserWarning
|
| 121 |
+
# skipinitialspace's dialect value and parser default are both
|
| 122 |
+
# False, so a valid True still conflicts
|
| 123 |
+
kwds[arg] = True if arg == "skipinitialspace" else "blah"
|
| 124 |
+
|
| 125 |
+
with tm.with_csv_dialect(dialect_name, **dialect_kwargs):
|
| 126 |
+
if arg == "doublequote" and value == "other":
|
| 127 |
+
# GH#68341 doublequote has no valid conflicting value left (the
|
| 128 |
+
# dialect says False, the parser default True), so its conflict is
|
| 129 |
+
# only reachable with a non-bool, which is now rejected
|
| 130 |
+
msg = f'For argument "{arg}" expected type bool'
|
| 131 |
+
with pytest.raises(ValueError, match=msg):
|
| 132 |
+
parser.read_csv(StringIO(data), dialect=dialect_name, **kwds)
|
| 133 |
+
return
|
| 134 |
+
|
| 135 |
+
if parser.engine == "pyarrow":
|
| 136 |
+
msg = "The 'dialect' option is not supported with the 'pyarrow' engine"
|
| 137 |
+
with pytest.raises(ValueError, match=msg):
|
| 138 |
+
parser.read_csv_check_warnings(
|
| 139 |
+
# No warning bc we raise
|
| 140 |
+
None,
|
| 141 |
+
"Conflicting values for",
|
| 142 |
+
StringIO(data),
|
| 143 |
+
dialect=dialect_name,
|
| 144 |
+
**kwds,
|
| 145 |
+
)
|
| 146 |
+
return
|
| 147 |
+
|
| 148 |
+
result = parser.read_csv_check_warnings(
|
| 149 |
+
warning_klass,
|
| 150 |
+
"Conflicting values for",
|
| 151 |
+
StringIO(data),
|
| 152 |
+
dialect=dialect_name,
|
| 153 |
+
**kwds,
|
| 154 |
+
)
|
| 155 |
+
tm.assert_frame_equal(result, expected)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def test_dialect_supplies_non_bool(all_parsers):
|
| 159 |
+
# GH#68341 a dialect object is not required to normalize its attributes the
|
| 160 |
+
# way csv.register_dialect does, so the post-merge check is the only thing
|
| 161 |
+
# standing between a non-bool it supplies and the parser
|
| 162 |
+
parser = all_parsers
|
| 163 |
+
|
| 164 |
+
class BadDialect:
|
| 165 |
+
delimiter = ","
|
| 166 |
+
doublequote = "False"
|
| 167 |
+
escapechar = None
|
| 168 |
+
skipinitialspace = False
|
| 169 |
+
quotechar = '"'
|
| 170 |
+
quoting = 0
|
| 171 |
+
|
| 172 |
+
if parser.engine == "pyarrow":
|
| 173 |
+
msg = "The 'dialect' option is not supported with the 'pyarrow' engine"
|
| 174 |
+
else:
|
| 175 |
+
msg = 'For argument "doublequote" expected type bool'
|
| 176 |
+
|
| 177 |
+
with pytest.raises(ValueError, match=msg):
|
| 178 |
+
parser.read_csv(StringIO('a\n"x""y"\n'), dialect=BadDialect)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@pytest.mark.parametrize(
|
| 182 |
+
"kwargs,warning_klass",
|
| 183 |
+
[
|
| 184 |
+
({"sep": ","}, None), # sep is default --> sep_override=True
|
| 185 |
+
({"sep": "."}, ParserWarning), # sep isn't default --> sep_override=False
|
| 186 |
+
({"delimiter": ":"}, None), # No conflict
|
| 187 |
+
({}, None), # Default arguments --> sep_override=True
|
| 188 |
+
({"delimiter": None}, None), # Matches the parser default --> no conflict
|
| 189 |
+
({"delimiter": ","}, ParserWarning), # Conflict
|
| 190 |
+
({"delimiter": "."}, ParserWarning), # Conflict
|
| 191 |
+
],
|
| 192 |
+
ids=[
|
| 193 |
+
"sep-override-true",
|
| 194 |
+
"sep-override-false",
|
| 195 |
+
"delimiter-no-conflict",
|
| 196 |
+
"no-sep-or-delimiter",
|
| 197 |
+
"delimiter-none",
|
| 198 |
+
"delimiter-conflict",
|
| 199 |
+
"delimiter-conflict2",
|
| 200 |
+
],
|
| 201 |
+
)
|
| 202 |
+
def test_dialect_conflict_delimiter(all_parsers, custom_dialect, kwargs, warning_klass):
|
| 203 |
+
# see gh-23761.
|
| 204 |
+
dialect_name, dialect_kwargs = custom_dialect
|
| 205 |
+
parser = all_parsers
|
| 206 |
+
|
| 207 |
+
expected = pd.DataFrame({"a": [1], "b": [2]})
|
| 208 |
+
data = "a:b\n1:2"
|
| 209 |
+
|
| 210 |
+
with tm.with_csv_dialect(dialect_name, **dialect_kwargs):
|
| 211 |
+
if parser.engine == "pyarrow":
|
| 212 |
+
msg = "The 'dialect' option is not supported with the 'pyarrow' engine"
|
| 213 |
+
with pytest.raises(ValueError, match=msg):
|
| 214 |
+
parser.read_csv_check_warnings(
|
| 215 |
+
# no warning bc we raise
|
| 216 |
+
None,
|
| 217 |
+
"Conflicting values for 'delimiter'",
|
| 218 |
+
StringIO(data),
|
| 219 |
+
dialect=dialect_name,
|
| 220 |
+
**kwargs,
|
| 221 |
+
)
|
| 222 |
+
return
|
| 223 |
+
result = parser.read_csv_check_warnings(
|
| 224 |
+
warning_klass,
|
| 225 |
+
"Conflicting values for 'delimiter'",
|
| 226 |
+
StringIO(data),
|
| 227 |
+
dialect=dialect_name,
|
| 228 |
+
**kwargs,
|
| 229 |
+
)
|
| 230 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_encoding.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests encoding functionality during parsing
|
| 3 |
+
for all of the parsers defined in parsers.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from io import (
|
| 7 |
+
BytesIO,
|
| 8 |
+
StringIO,
|
| 9 |
+
TextIOWrapper,
|
| 10 |
+
)
|
| 11 |
+
import sys
|
| 12 |
+
import tempfile
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pytest
|
| 16 |
+
|
| 17 |
+
from pandas.errors import (
|
| 18 |
+
EmptyDataError,
|
| 19 |
+
ParserWarning,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
import pandas as pd
|
| 23 |
+
import pandas._testing as tm
|
| 24 |
+
|
| 25 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_bytes_io_input(all_parsers):
|
| 29 |
+
encoding = "cp1255"
|
| 30 |
+
parser = all_parsers
|
| 31 |
+
|
| 32 |
+
data = BytesIO("שלום:1234\n562:123".encode(encoding))
|
| 33 |
+
result = parser.read_csv(data, sep=":", encoding=encoding)
|
| 34 |
+
|
| 35 |
+
expected = pd.DataFrame([[562, 123]], columns=["שלום", "1234"])
|
| 36 |
+
tm.assert_frame_equal(result, expected)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize(
|
| 40 |
+
"encoding_errors, expected", [("replace", "x?"), ("ignore", "x")]
|
| 41 |
+
)
|
| 42 |
+
def test_text_buffer_encoding_errors(all_parsers, encoding_errors, expected):
|
| 43 |
+
# GH#70405 the C and pyarrow engines encode a text buffer to bytes and
|
| 44 |
+
# must apply encoding_errors when doing so
|
| 45 |
+
parser = all_parsers
|
| 46 |
+
if parser.engine == "python":
|
| 47 |
+
pytest.skip("python engine reads text buffers without encoding them")
|
| 48 |
+
data = StringIO("a\nx\udcef\n")
|
| 49 |
+
result = parser.read_csv(data, encoding_errors=encoding_errors)
|
| 50 |
+
tm.assert_frame_equal(result, pd.DataFrame({"a": [expected]}))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 54 |
+
def test_read_csv_unicode(all_parsers):
|
| 55 |
+
parser = all_parsers
|
| 56 |
+
data = BytesIO("\u0141aski, Jan;1".encode())
|
| 57 |
+
|
| 58 |
+
result = parser.read_csv(data, sep=";", encoding="utf-8", header=None)
|
| 59 |
+
expected = pd.DataFrame([["\u0141aski, Jan", 1]])
|
| 60 |
+
tm.assert_frame_equal(result, expected)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@skip_pyarrow
|
| 64 |
+
@pytest.mark.parametrize("sep", [",", "\t"])
|
| 65 |
+
@pytest.mark.parametrize("encoding", ["utf-16", "utf-16le", "utf-16be"])
|
| 66 |
+
def test_utf16_bom_skiprows(all_parsers, sep, encoding, temp_file):
|
| 67 |
+
# see gh-2298
|
| 68 |
+
parser = all_parsers
|
| 69 |
+
data = """skip this
|
| 70 |
+
skip this too
|
| 71 |
+
A,B,C
|
| 72 |
+
1,2,3
|
| 73 |
+
4,5,6""".replace(",", sep)
|
| 74 |
+
kwargs = {"sep": sep, "skiprows": 2}
|
| 75 |
+
utf8 = "utf-8"
|
| 76 |
+
|
| 77 |
+
bytes_data = data.encode(encoding)
|
| 78 |
+
|
| 79 |
+
with open(temp_file, "wb") as f:
|
| 80 |
+
f.write(bytes_data)
|
| 81 |
+
|
| 82 |
+
with TextIOWrapper(BytesIO(data.encode(utf8)), encoding=utf8) as bytes_buffer:
|
| 83 |
+
result = parser.read_csv(temp_file, encoding=encoding, **kwargs)
|
| 84 |
+
expected = parser.read_csv(bytes_buffer, encoding=utf8, **kwargs)
|
| 85 |
+
tm.assert_frame_equal(result, expected)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_utf16_example(all_parsers, datapath):
|
| 89 |
+
path = datapath("io", "parser", "data", "utf16_ex.txt")
|
| 90 |
+
parser = all_parsers
|
| 91 |
+
result = parser.read_csv(path, encoding="utf-16", sep="\t")
|
| 92 |
+
assert len(result) == 50
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_unicode_encoding(all_parsers, datapath):
|
| 96 |
+
path = datapath("io", "parser", "data", "unicode_series.csv")
|
| 97 |
+
parser = all_parsers
|
| 98 |
+
|
| 99 |
+
result = parser.read_csv(path, header=None, encoding="latin-1")
|
| 100 |
+
result = result.set_index(0)
|
| 101 |
+
got = result[1][1632]
|
| 102 |
+
|
| 103 |
+
expected = "\xc1 k\xf6ldum klaka (Cold Fever) (1994)"
|
| 104 |
+
assert got == expected
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@pytest.mark.parametrize(
|
| 108 |
+
"data,kwargs,expected",
|
| 109 |
+
[
|
| 110 |
+
# Basic test
|
| 111 |
+
("a\n1", {}, [1]),
|
| 112 |
+
# "Regular" quoting
|
| 113 |
+
('"a"\n1', {"quotechar": '"'}, [1]),
|
| 114 |
+
# Test in a data row instead of header
|
| 115 |
+
("b\n1", {"names": ["a"]}, ["b", "1"]),
|
| 116 |
+
# Test in empty data row with skipping
|
| 117 |
+
("\n1", {"names": ["a"], "skip_blank_lines": True}, [1]),
|
| 118 |
+
# Test in empty data row without skipping
|
| 119 |
+
(
|
| 120 |
+
"\n1",
|
| 121 |
+
{"names": ["a"], "skip_blank_lines": False},
|
| 122 |
+
[np.nan, 1],
|
| 123 |
+
),
|
| 124 |
+
],
|
| 125 |
+
)
|
| 126 |
+
@pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig"])
|
| 127 |
+
def test_utf8_bom_removal(all_parsers, data, kwargs, expected, encoding):
|
| 128 |
+
# see gh-4793
|
| 129 |
+
parser = all_parsers
|
| 130 |
+
bom = "\ufeff"
|
| 131 |
+
|
| 132 |
+
def _encode_data_with_bom(_data):
|
| 133 |
+
bom_data = (bom + _data).encode("utf-8")
|
| 134 |
+
return BytesIO(bom_data)
|
| 135 |
+
|
| 136 |
+
if (
|
| 137 |
+
parser.engine == "pyarrow"
|
| 138 |
+
and data == "\n1"
|
| 139 |
+
and kwargs.get("skip_blank_lines", True)
|
| 140 |
+
):
|
| 141 |
+
# CSV parse error: Empty CSV file or block: cannot infer number of columns
|
| 142 |
+
pytest.skip(reason="https://github.com/apache/arrow/issues/38676")
|
| 143 |
+
|
| 144 |
+
result = parser.read_csv(
|
| 145 |
+
_encode_data_with_bom(data),
|
| 146 |
+
encoding=encoding,
|
| 147 |
+
**kwargs,
|
| 148 |
+
)
|
| 149 |
+
expected = pd.DataFrame({"a": expected})
|
| 150 |
+
tm.assert_frame_equal(result, expected)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def test_latin1_bom_preserved(all_parsers):
|
| 154 |
+
parser = all_parsers
|
| 155 |
+
if parser.engine == "pyarrow":
|
| 156 |
+
pytest.skip(reason="pyarrow does not support latin-1 encoding")
|
| 157 |
+
|
| 158 |
+
bom_bytes = b"\xef\xbb\xbf"
|
| 159 |
+
bom_text = bom_bytes.decode("latin1")
|
| 160 |
+
data = b"a\n1"
|
| 161 |
+
bio = BytesIO(bom_bytes + data)
|
| 162 |
+
|
| 163 |
+
result = parser.read_csv(bio, encoding="latin1")
|
| 164 |
+
expected = pd.DataFrame({f"{bom_text}a": [1]})
|
| 165 |
+
tm.assert_frame_equal(result, expected)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt):
|
| 169 |
+
# see gh-13549
|
| 170 |
+
expected = pd.DataFrame({"mb_num": [4.8], "multibyte": ["test"]})
|
| 171 |
+
parser = all_parsers
|
| 172 |
+
|
| 173 |
+
encoding = encoding_fmt.format(utf_value)
|
| 174 |
+
data = "mb_num,multibyte\n4.8,test".encode(encoding)
|
| 175 |
+
|
| 176 |
+
result = parser.read_csv(BytesIO(data), encoding=encoding)
|
| 177 |
+
tm.assert_frame_equal(result, expected)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
@pytest.mark.parametrize(
|
| 181 |
+
"file_path,encoding",
|
| 182 |
+
[
|
| 183 |
+
(("io", "data", "csv", "test1.csv"), "utf-8"),
|
| 184 |
+
(("io", "parser", "data", "unicode_series.csv"), "latin-1"),
|
| 185 |
+
(("io", "parser", "data", "sauron.SHIFT_JIS.csv"), "shiftjis"),
|
| 186 |
+
],
|
| 187 |
+
)
|
| 188 |
+
def test_binary_mode_file_buffers(all_parsers, file_path, encoding, datapath):
|
| 189 |
+
# gh-23779: Python csv engine shouldn't error on files opened in binary.
|
| 190 |
+
# gh-31575: Python csv engine shouldn't error on files opened in raw binary.
|
| 191 |
+
parser = all_parsers
|
| 192 |
+
|
| 193 |
+
fpath = datapath(*file_path)
|
| 194 |
+
expected = parser.read_csv(fpath, encoding=encoding)
|
| 195 |
+
|
| 196 |
+
with open(fpath, encoding=encoding) as fa:
|
| 197 |
+
result = parser.read_csv(fa)
|
| 198 |
+
assert not fa.closed
|
| 199 |
+
tm.assert_frame_equal(expected, result)
|
| 200 |
+
|
| 201 |
+
with open(fpath, mode="rb") as fb:
|
| 202 |
+
result = parser.read_csv(fb, encoding=encoding)
|
| 203 |
+
assert not fb.closed
|
| 204 |
+
tm.assert_frame_equal(expected, result)
|
| 205 |
+
|
| 206 |
+
with open(fpath, mode="rb", buffering=0) as fb:
|
| 207 |
+
result = parser.read_csv(fb, encoding=encoding)
|
| 208 |
+
assert not fb.closed
|
| 209 |
+
tm.assert_frame_equal(expected, result)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@pytest.mark.parametrize("pass_encoding", [True, False])
|
| 213 |
+
def test_encoding_temp_file(
|
| 214 |
+
all_parsers, utf_value, encoding_fmt, pass_encoding, temp_file
|
| 215 |
+
):
|
| 216 |
+
# see gh-24130
|
| 217 |
+
parser = all_parsers
|
| 218 |
+
encoding = encoding_fmt.format(utf_value)
|
| 219 |
+
|
| 220 |
+
if parser.engine == "pyarrow" and pass_encoding is True and utf_value in [16, 32]:
|
| 221 |
+
# GH#24130: pyarrow's CSV reader splits the input into byte-blocks
|
| 222 |
+
# before decoding, which corrupts multi-byte utf-16/utf-32 sequences
|
| 223 |
+
# (raises "straddling object straddles two block boundaries"). The
|
| 224 |
+
# error path is slow (~9s per case), so skip rather than xfail.
|
| 225 |
+
pytest.skip("pyarrow utf-16/32 block-boundary error is slow to surface")
|
| 226 |
+
|
| 227 |
+
expected = pd.DataFrame({"foo": ["bar"]})
|
| 228 |
+
|
| 229 |
+
with temp_file.open(mode="w+", encoding=encoding) as f:
|
| 230 |
+
f.write("foo\nbar")
|
| 231 |
+
f.seek(0)
|
| 232 |
+
|
| 233 |
+
result = parser.read_csv(f, encoding=encoding if pass_encoding else None)
|
| 234 |
+
tm.assert_frame_equal(result, expected)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def test_encoding_named_temp_file(all_parsers):
|
| 238 |
+
# see gh-31819
|
| 239 |
+
parser = all_parsers
|
| 240 |
+
encoding = "shift-jis"
|
| 241 |
+
|
| 242 |
+
title = "てすと"
|
| 243 |
+
data = "こむ"
|
| 244 |
+
|
| 245 |
+
expected = pd.DataFrame({title: [data]})
|
| 246 |
+
|
| 247 |
+
with tempfile.NamedTemporaryFile() as f:
|
| 248 |
+
f.write(f"{title}\n{data}".encode(encoding))
|
| 249 |
+
|
| 250 |
+
f.seek(0)
|
| 251 |
+
|
| 252 |
+
result = parser.read_csv(f, encoding=encoding)
|
| 253 |
+
tm.assert_frame_equal(result, expected)
|
| 254 |
+
assert not f.closed
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
@pytest.mark.parametrize(
|
| 258 |
+
"encoding", ["utf-8", "utf-16", "utf-16-be", "utf-16-le", "utf-32"]
|
| 259 |
+
)
|
| 260 |
+
def test_parse_encoded_special_characters(encoding):
|
| 261 |
+
# GH16218 Verify parsing of data with encoded special characters
|
| 262 |
+
# Data contains a Unicode 'FULLWIDTH COLON' (U+FF1A) at position (0,"a")
|
| 263 |
+
data = "a\tb\n:foo\t0\nbar\t1\nbaz\t2" # noqa: RUF001
|
| 264 |
+
encoded_data = BytesIO(data.encode(encoding))
|
| 265 |
+
result = pd.read_csv(encoded_data, delimiter="\t", encoding=encoding)
|
| 266 |
+
|
| 267 |
+
expected = pd.DataFrame(
|
| 268 |
+
data=[[":foo", 0], ["bar", 1], ["baz", 2]], # noqa: RUF001
|
| 269 |
+
columns=["a", "b"],
|
| 270 |
+
)
|
| 271 |
+
tm.assert_frame_equal(result, expected)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
@pytest.mark.parametrize("encoding", ["utf-8", None, "utf-16", "cp1255", "latin-1"])
|
| 275 |
+
def test_encoding_memory_map(all_parsers, encoding, temp_file):
|
| 276 |
+
# GH40986
|
| 277 |
+
parser = all_parsers
|
| 278 |
+
expected = pd.DataFrame(
|
| 279 |
+
{
|
| 280 |
+
"name": ["Raphael", "Donatello", "Miguel Angel", "Leonardo"],
|
| 281 |
+
"mask": ["red", "purple", "orange", "blue"],
|
| 282 |
+
"weapon": ["sai", "bo staff", "nunchunk", "katana"],
|
| 283 |
+
}
|
| 284 |
+
)
|
| 285 |
+
expected.to_csv(temp_file, index=False, encoding=encoding)
|
| 286 |
+
|
| 287 |
+
if parser.engine == "pyarrow":
|
| 288 |
+
msg = "The 'memory_map' option is not supported with the 'pyarrow' engine"
|
| 289 |
+
with pytest.raises(ValueError, match=msg):
|
| 290 |
+
parser.read_csv(temp_file, encoding=encoding, memory_map=True)
|
| 291 |
+
return
|
| 292 |
+
|
| 293 |
+
df = parser.read_csv(temp_file, encoding=encoding, memory_map=True)
|
| 294 |
+
tm.assert_frame_equal(df, expected)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def test_chunk_splits_multibyte_char(all_parsers, temp_file):
|
| 298 |
+
"""
|
| 299 |
+
Chunk splits a multibyte character with memory_map=True
|
| 300 |
+
|
| 301 |
+
GH 43540
|
| 302 |
+
"""
|
| 303 |
+
parser = all_parsers
|
| 304 |
+
# DEFAULT_CHUNKSIZE = 262144, defined in parsers.pyx
|
| 305 |
+
df = pd.DataFrame(data=["a" * 127] * 2048)
|
| 306 |
+
|
| 307 |
+
# Put two-bytes utf-8 encoded character "ą" at the end of chunk
|
| 308 |
+
# utf-8 encoding of "ą" is b'\xc4\x85'
|
| 309 |
+
df.iloc[2047] = "a" * 127 + "ą"
|
| 310 |
+
df.to_csv(temp_file, index=False, header=False, encoding="utf-8")
|
| 311 |
+
|
| 312 |
+
if parser.engine == "pyarrow":
|
| 313 |
+
msg = "The 'memory_map' option is not supported with the 'pyarrow' engine"
|
| 314 |
+
with pytest.raises(ValueError, match=msg):
|
| 315 |
+
parser.read_csv(temp_file, header=None, memory_map=True)
|
| 316 |
+
return
|
| 317 |
+
|
| 318 |
+
dfr = parser.read_csv(temp_file, header=None, memory_map=True)
|
| 319 |
+
tm.assert_frame_equal(dfr, df)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def test_readcsv_memmap_utf8(all_parsers, temp_file):
|
| 323 |
+
"""
|
| 324 |
+
GH 43787
|
| 325 |
+
|
| 326 |
+
Test correct handling of UTF-8 chars when memory_map=True and encoding is UTF-8
|
| 327 |
+
"""
|
| 328 |
+
lines = []
|
| 329 |
+
line_length = 128
|
| 330 |
+
start_char = " "
|
| 331 |
+
end_char = "\U00010080"
|
| 332 |
+
# This for loop creates a list of 128-char strings
|
| 333 |
+
# consisting of consecutive Unicode chars
|
| 334 |
+
for lnum in range(ord(start_char), ord(end_char), line_length):
|
| 335 |
+
line = "".join([chr(c) for c in range(lnum, lnum + 0x80)]) + "\n"
|
| 336 |
+
try:
|
| 337 |
+
line.encode("utf-8")
|
| 338 |
+
except UnicodeEncodeError:
|
| 339 |
+
continue
|
| 340 |
+
lines.append(line)
|
| 341 |
+
parser = all_parsers
|
| 342 |
+
df = pd.DataFrame(lines)
|
| 343 |
+
df.to_csv(temp_file, index=False, header=False, encoding="utf-8")
|
| 344 |
+
|
| 345 |
+
if parser.engine == "pyarrow":
|
| 346 |
+
msg = "The 'memory_map' option is not supported with the 'pyarrow' engine"
|
| 347 |
+
with pytest.raises(ValueError, match=msg):
|
| 348 |
+
parser.read_csv(temp_file, header=None, memory_map=True, encoding="utf-8")
|
| 349 |
+
return
|
| 350 |
+
|
| 351 |
+
dfr = parser.read_csv(temp_file, header=None, memory_map=True, encoding="utf-8")
|
| 352 |
+
tm.assert_frame_equal(df, dfr)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
@pytest.mark.parametrize("mode", ["w+b", "w+t"])
|
| 356 |
+
def test_not_readable(all_parsers, mode):
|
| 357 |
+
# GH43439
|
| 358 |
+
parser = all_parsers
|
| 359 |
+
content = b"abcd"
|
| 360 |
+
if "t" in mode:
|
| 361 |
+
content = "abcd"
|
| 362 |
+
with tempfile.SpooledTemporaryFile(mode=mode, encoding="utf-8") as handle:
|
| 363 |
+
handle.write(content)
|
| 364 |
+
handle.seek(0)
|
| 365 |
+
if parser.engine == "pyarrow":
|
| 366 |
+
# pyarrow's CSV reader cannot read from a SpooledTemporaryFile
|
| 367 |
+
if "t" in mode:
|
| 368 |
+
msg = "The 'pyarrow' engine can only read from a binary file object"
|
| 369 |
+
with pytest.raises(TypeError, match=msg):
|
| 370 |
+
parser.read_csv(handle)
|
| 371 |
+
else:
|
| 372 |
+
msg = "No columns to parse from file"
|
| 373 |
+
with pytest.raises(EmptyDataError, match=msg):
|
| 374 |
+
parser.read_csv(handle)
|
| 375 |
+
return
|
| 376 |
+
df = parser.read_csv(handle)
|
| 377 |
+
expected = pd.DataFrame([], columns=["abcd"])
|
| 378 |
+
tm.assert_frame_equal(df, expected)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def test_sep_encodeable_check_ignores_filesystem_encoding(monkeypatch, temp_file):
|
| 382 |
+
# GH#46456 whether the "c" engine can handle the separator depends on utf-8,
|
| 383 |
+
# not on the platform's filesystem encoding
|
| 384 |
+
monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "latin-1")
|
| 385 |
+
temp_file.write_text(
|
| 386 |
+
"key\u00a5value\ntables\u00a5rectangular\n", encoding="latin-1"
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
with tm.assert_produces_warning(
|
| 390 |
+
ParserWarning, match="encoded in utf-8", check_stacklevel=False
|
| 391 |
+
):
|
| 392 |
+
result = pd.read_csv(temp_file, sep="\u00a5", encoding="latin-1")
|
| 393 |
+
expected = pd.DataFrame([["tables", "rectangular"]], columns=["key", "value"])
|
| 394 |
+
tm.assert_frame_equal(result, expected)
|
| 395 |
+
|
| 396 |
+
with pytest.raises(ValueError, match="encoded in utf-8"):
|
| 397 |
+
pd.read_csv(temp_file, sep="\u00a5", encoding="latin-1", engine="c")
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def test_sep_unencodeable_falls_back(temp_file):
|
| 401 |
+
# GH#46456 a separator that cannot be encoded at all falls back instead of raising
|
| 402 |
+
temp_file.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 403 |
+
|
| 404 |
+
with tm.assert_produces_warning(
|
| 405 |
+
ParserWarning, match="encoded in utf-8", check_stacklevel=False
|
| 406 |
+
):
|
| 407 |
+
result = pd.read_csv(temp_file, sep="\udcff")
|
| 408 |
+
expected = pd.DataFrame({"a,b": ["1,2"]})
|
| 409 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_header.py
ADDED
|
@@ -0,0 +1,792 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that the file header is properly handled or inferred
|
| 3 |
+
during parsing for all of the parsers defined in parsers.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from collections import namedtuple
|
| 7 |
+
from io import StringIO
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from pandas.errors import ParserError
|
| 13 |
+
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import pandas._testing as tm
|
| 16 |
+
|
| 17 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 18 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_read_with_bad_header(all_parsers):
|
| 22 |
+
parser = all_parsers
|
| 23 |
+
|
| 24 |
+
if parser.engine == "pyarrow":
|
| 25 |
+
# header=[10] is a singleton, so it behaves like header=10; pyarrow
|
| 26 |
+
# cannot skip 10 rows in a 1-line file
|
| 27 |
+
with pytest.raises(ParserError, match="Could not skip initial 10 rows"):
|
| 28 |
+
parser.read_csv(StringIO(",,"), header=[10])
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
msg = r"but only \d+ lines in file"
|
| 32 |
+
with pytest.raises(ValueError, match=msg):
|
| 33 |
+
parser.read_csv(StringIO(",,"), header=[10])
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_negative_header(all_parsers):
|
| 37 |
+
# see gh-27779
|
| 38 |
+
parser = all_parsers
|
| 39 |
+
data = """1,2,3,4,5
|
| 40 |
+
6,7,8,9,10
|
| 41 |
+
11,12,13,14,15
|
| 42 |
+
"""
|
| 43 |
+
with pytest.raises(
|
| 44 |
+
ValueError,
|
| 45 |
+
match="Passing negative integer to header is invalid. "
|
| 46 |
+
"For no header, use header=None instead",
|
| 47 |
+
):
|
| 48 |
+
parser.read_csv(StringIO(data), header=-1)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@pytest.mark.parametrize("header", [([-1, 2, 4]), ([-5, 0])])
|
| 52 |
+
def test_negative_multi_index_header(all_parsers, header):
|
| 53 |
+
# see gh-27779
|
| 54 |
+
parser = all_parsers
|
| 55 |
+
data = """1,2,3,4,5
|
| 56 |
+
6,7,8,9,10
|
| 57 |
+
11,12,13,14,15
|
| 58 |
+
"""
|
| 59 |
+
with pytest.raises(
|
| 60 |
+
ValueError, match="cannot specify multi-index header with negative integers"
|
| 61 |
+
):
|
| 62 |
+
parser.read_csv(StringIO(data), header=header)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@pytest.mark.parametrize("header", [True, False])
|
| 66 |
+
def test_bool_header_arg(all_parsers, header):
|
| 67 |
+
# see gh-6114
|
| 68 |
+
parser = all_parsers
|
| 69 |
+
data = """\
|
| 70 |
+
MyColumn
|
| 71 |
+
a
|
| 72 |
+
b
|
| 73 |
+
a
|
| 74 |
+
b"""
|
| 75 |
+
msg = "Passing a bool to header is invalid"
|
| 76 |
+
with pytest.raises(TypeError, match=msg):
|
| 77 |
+
parser.read_csv(StringIO(data), header=header)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_header_with_index_col(all_parsers):
|
| 81 |
+
parser = all_parsers
|
| 82 |
+
data = """foo,1,2,3
|
| 83 |
+
bar,4,5,6
|
| 84 |
+
baz,7,8,9
|
| 85 |
+
"""
|
| 86 |
+
names = ["A", "B", "C"]
|
| 87 |
+
result = parser.read_csv(StringIO(data), names=names)
|
| 88 |
+
|
| 89 |
+
expected = pd.DataFrame(
|
| 90 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
|
| 91 |
+
index=["foo", "bar", "baz"],
|
| 92 |
+
columns=["A", "B", "C"],
|
| 93 |
+
)
|
| 94 |
+
tm.assert_frame_equal(result, expected)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_header_not_first_line(all_parsers):
|
| 98 |
+
parser = all_parsers
|
| 99 |
+
data = """got,to,ignore,this,line
|
| 100 |
+
got,to,ignore,this,line
|
| 101 |
+
index,A,B,C,D
|
| 102 |
+
foo,2,3,4,5
|
| 103 |
+
bar,7,8,9,10
|
| 104 |
+
baz,12,13,14,15
|
| 105 |
+
"""
|
| 106 |
+
data2 = """index,A,B,C,D
|
| 107 |
+
foo,2,3,4,5
|
| 108 |
+
bar,7,8,9,10
|
| 109 |
+
baz,12,13,14,15
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
result = parser.read_csv(StringIO(data), header=2, index_col=0)
|
| 113 |
+
expected = parser.read_csv(StringIO(data2), header=0, index_col=0)
|
| 114 |
+
tm.assert_frame_equal(result, expected)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_header_multi_index(all_parsers):
|
| 118 |
+
parser = all_parsers
|
| 119 |
+
|
| 120 |
+
data = """\
|
| 121 |
+
C0,,C_l0_g0,C_l0_g1,C_l0_g2
|
| 122 |
+
|
| 123 |
+
C1,,C_l1_g0,C_l1_g1,C_l1_g2
|
| 124 |
+
C2,,C_l2_g0,C_l2_g1,C_l2_g2
|
| 125 |
+
C3,,C_l3_g0,C_l3_g1,C_l3_g2
|
| 126 |
+
R0,R1,,,
|
| 127 |
+
R_l0_g0,R_l1_g0,R0C0,R0C1,R0C2
|
| 128 |
+
R_l0_g1,R_l1_g1,R1C0,R1C1,R1C2
|
| 129 |
+
R_l0_g2,R_l1_g2,R2C0,R2C1,R2C2
|
| 130 |
+
R_l0_g3,R_l1_g3,R3C0,R3C1,R3C2
|
| 131 |
+
R_l0_g4,R_l1_g4,R4C0,R4C1,R4C2
|
| 132 |
+
"""
|
| 133 |
+
if parser.engine == "pyarrow":
|
| 134 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 135 |
+
parser.read_csv(StringIO(data), header=[0, 1, 2, 3], index_col=[0, 1])
|
| 136 |
+
return
|
| 137 |
+
|
| 138 |
+
result = parser.read_csv(StringIO(data), header=[0, 1, 2, 3], index_col=[0, 1])
|
| 139 |
+
data_gen_f = lambda r, c: f"R{r}C{c}"
|
| 140 |
+
|
| 141 |
+
data = [[data_gen_f(r, c) for c in range(3)] for r in range(5)]
|
| 142 |
+
index = pd.MultiIndex.from_arrays(
|
| 143 |
+
[[f"R_l0_g{i}" for i in range(5)], [f"R_l1_g{i}" for i in range(5)]],
|
| 144 |
+
names=["R0", "R1"],
|
| 145 |
+
)
|
| 146 |
+
columns = pd.MultiIndex.from_arrays(
|
| 147 |
+
[
|
| 148 |
+
[f"C_l0_g{i}" for i in range(3)],
|
| 149 |
+
[f"C_l1_g{i}" for i in range(3)],
|
| 150 |
+
[f"C_l2_g{i}" for i in range(3)],
|
| 151 |
+
[f"C_l3_g{i}" for i in range(3)],
|
| 152 |
+
],
|
| 153 |
+
names=["C0", "C1", "C2", "C3"],
|
| 154 |
+
)
|
| 155 |
+
expected = pd.DataFrame(data, columns=columns, index=index)
|
| 156 |
+
tm.assert_frame_equal(result, expected)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@pytest.mark.parametrize(
|
| 160 |
+
"kwargs,msg",
|
| 161 |
+
[
|
| 162 |
+
(
|
| 163 |
+
{"index_col": ["foo", "bar"]},
|
| 164 |
+
(
|
| 165 |
+
"index_col must only contain "
|
| 166 |
+
"integers of column positions when specifying "
|
| 167 |
+
"a multi-index header"
|
| 168 |
+
),
|
| 169 |
+
),
|
| 170 |
+
(
|
| 171 |
+
{"index_col": [0, 1], "names": ["foo", "bar"]},
|
| 172 |
+
("cannot specify names when specifying a multi-index header"),
|
| 173 |
+
),
|
| 174 |
+
(
|
| 175 |
+
{"index_col": [0, 1], "usecols": ["foo", "bar"]},
|
| 176 |
+
("cannot specify usecols when specifying a multi-index header"),
|
| 177 |
+
),
|
| 178 |
+
],
|
| 179 |
+
)
|
| 180 |
+
def test_header_multi_index_invalid(all_parsers, kwargs, msg):
|
| 181 |
+
data = """\
|
| 182 |
+
C0,,C_l0_g0,C_l0_g1,C_l0_g2
|
| 183 |
+
|
| 184 |
+
C1,,C_l1_g0,C_l1_g1,C_l1_g2
|
| 185 |
+
C2,,C_l2_g0,C_l2_g1,C_l2_g2
|
| 186 |
+
C3,,C_l3_g0,C_l3_g1,C_l3_g2
|
| 187 |
+
R0,R1,,,
|
| 188 |
+
R_l0_g0,R_l1_g0,R0C0,R0C1,R0C2
|
| 189 |
+
R_l0_g1,R_l1_g1,R1C0,R1C1,R1C2
|
| 190 |
+
R_l0_g2,R_l1_g2,R2C0,R2C1,R2C2
|
| 191 |
+
R_l0_g3,R_l1_g3,R3C0,R3C1,R3C2
|
| 192 |
+
R_l0_g4,R_l1_g4,R4C0,R4C1,R4C2
|
| 193 |
+
"""
|
| 194 |
+
parser = all_parsers
|
| 195 |
+
|
| 196 |
+
with pytest.raises(ValueError, match=msg):
|
| 197 |
+
parser.read_csv(StringIO(data), header=[0, 1, 2, 3], **kwargs)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
_TestTuple = namedtuple("_TestTuple", ["first", "second"])
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@pytest.mark.parametrize(
|
| 204 |
+
"kwargs",
|
| 205 |
+
[
|
| 206 |
+
{"header": [0, 1]},
|
| 207 |
+
{
|
| 208 |
+
"skiprows": 3,
|
| 209 |
+
"names": [
|
| 210 |
+
("a", "q"),
|
| 211 |
+
("a", "r"),
|
| 212 |
+
("a", "s"),
|
| 213 |
+
("b", "t"),
|
| 214 |
+
("c", "u"),
|
| 215 |
+
("c", "v"),
|
| 216 |
+
],
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"skiprows": 3,
|
| 220 |
+
"names": [
|
| 221 |
+
_TestTuple("a", "q"),
|
| 222 |
+
_TestTuple("a", "r"),
|
| 223 |
+
_TestTuple("a", "s"),
|
| 224 |
+
_TestTuple("b", "t"),
|
| 225 |
+
_TestTuple("c", "u"),
|
| 226 |
+
_TestTuple("c", "v"),
|
| 227 |
+
],
|
| 228 |
+
},
|
| 229 |
+
],
|
| 230 |
+
)
|
| 231 |
+
def test_header_multi_index_common_format1(all_parsers, kwargs):
|
| 232 |
+
parser = all_parsers
|
| 233 |
+
expected = pd.DataFrame(
|
| 234 |
+
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]],
|
| 235 |
+
index=["one", "two"],
|
| 236 |
+
columns=pd.MultiIndex.from_tuples(
|
| 237 |
+
[("a", "q"), ("a", "r"), ("a", "s"), ("b", "t"), ("c", "u"), ("c", "v")]
|
| 238 |
+
),
|
| 239 |
+
)
|
| 240 |
+
data = """,a,a,a,b,c,c
|
| 241 |
+
,q,r,s,t,u,v
|
| 242 |
+
,,,,,,
|
| 243 |
+
one,1,2,3,4,5,6
|
| 244 |
+
two,7,8,9,10,11,12"""
|
| 245 |
+
|
| 246 |
+
if parser.engine == "pyarrow" and "header" in kwargs:
|
| 247 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 248 |
+
parser.read_csv(StringIO(data), index_col=0, **kwargs)
|
| 249 |
+
return
|
| 250 |
+
|
| 251 |
+
result = parser.read_csv(StringIO(data), index_col=0, **kwargs)
|
| 252 |
+
tm.assert_frame_equal(result, expected)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@pytest.mark.parametrize(
|
| 256 |
+
"kwargs",
|
| 257 |
+
[
|
| 258 |
+
{"header": [0, 1]},
|
| 259 |
+
{
|
| 260 |
+
"skiprows": 2,
|
| 261 |
+
"names": [
|
| 262 |
+
("a", "q"),
|
| 263 |
+
("a", "r"),
|
| 264 |
+
("a", "s"),
|
| 265 |
+
("b", "t"),
|
| 266 |
+
("c", "u"),
|
| 267 |
+
("c", "v"),
|
| 268 |
+
],
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"skiprows": 2,
|
| 272 |
+
"names": [
|
| 273 |
+
_TestTuple("a", "q"),
|
| 274 |
+
_TestTuple("a", "r"),
|
| 275 |
+
_TestTuple("a", "s"),
|
| 276 |
+
_TestTuple("b", "t"),
|
| 277 |
+
_TestTuple("c", "u"),
|
| 278 |
+
_TestTuple("c", "v"),
|
| 279 |
+
],
|
| 280 |
+
},
|
| 281 |
+
],
|
| 282 |
+
)
|
| 283 |
+
def test_header_multi_index_common_format2(all_parsers, kwargs):
|
| 284 |
+
parser = all_parsers
|
| 285 |
+
expected = pd.DataFrame(
|
| 286 |
+
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]],
|
| 287 |
+
index=["one", "two"],
|
| 288 |
+
columns=pd.MultiIndex.from_tuples(
|
| 289 |
+
[("a", "q"), ("a", "r"), ("a", "s"), ("b", "t"), ("c", "u"), ("c", "v")]
|
| 290 |
+
),
|
| 291 |
+
)
|
| 292 |
+
data = """,a,a,a,b,c,c
|
| 293 |
+
,q,r,s,t,u,v
|
| 294 |
+
one,1,2,3,4,5,6
|
| 295 |
+
two,7,8,9,10,11,12"""
|
| 296 |
+
|
| 297 |
+
if parser.engine == "pyarrow" and "header" in kwargs:
|
| 298 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 299 |
+
parser.read_csv(StringIO(data), index_col=0, **kwargs)
|
| 300 |
+
return
|
| 301 |
+
|
| 302 |
+
result = parser.read_csv(StringIO(data), index_col=0, **kwargs)
|
| 303 |
+
tm.assert_frame_equal(result, expected)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@pytest.mark.parametrize(
|
| 307 |
+
"kwargs",
|
| 308 |
+
[
|
| 309 |
+
{"header": [0, 1]},
|
| 310 |
+
{
|
| 311 |
+
"skiprows": 2,
|
| 312 |
+
"names": [
|
| 313 |
+
("a", "q"),
|
| 314 |
+
("a", "r"),
|
| 315 |
+
("a", "s"),
|
| 316 |
+
("b", "t"),
|
| 317 |
+
("c", "u"),
|
| 318 |
+
("c", "v"),
|
| 319 |
+
],
|
| 320 |
+
},
|
| 321 |
+
{
|
| 322 |
+
"skiprows": 2,
|
| 323 |
+
"names": [
|
| 324 |
+
_TestTuple("a", "q"),
|
| 325 |
+
_TestTuple("a", "r"),
|
| 326 |
+
_TestTuple("a", "s"),
|
| 327 |
+
_TestTuple("b", "t"),
|
| 328 |
+
_TestTuple("c", "u"),
|
| 329 |
+
_TestTuple("c", "v"),
|
| 330 |
+
],
|
| 331 |
+
},
|
| 332 |
+
],
|
| 333 |
+
)
|
| 334 |
+
def test_header_multi_index_common_format3(all_parsers, kwargs):
|
| 335 |
+
parser = all_parsers
|
| 336 |
+
expected = pd.DataFrame(
|
| 337 |
+
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]],
|
| 338 |
+
index=["one", "two"],
|
| 339 |
+
columns=pd.MultiIndex.from_tuples(
|
| 340 |
+
[("a", "q"), ("a", "r"), ("a", "s"), ("b", "t"), ("c", "u"), ("c", "v")]
|
| 341 |
+
),
|
| 342 |
+
)
|
| 343 |
+
expected = expected.reset_index(drop=True)
|
| 344 |
+
data = """a,a,a,b,c,c
|
| 345 |
+
q,r,s,t,u,v
|
| 346 |
+
1,2,3,4,5,6
|
| 347 |
+
7,8,9,10,11,12"""
|
| 348 |
+
|
| 349 |
+
if parser.engine == "pyarrow" and "header" in kwargs:
|
| 350 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 351 |
+
parser.read_csv(StringIO(data), index_col=None, **kwargs)
|
| 352 |
+
return
|
| 353 |
+
|
| 354 |
+
result = parser.read_csv(StringIO(data), index_col=None, **kwargs)
|
| 355 |
+
tm.assert_frame_equal(result, expected)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def test_header_multi_index_common_format_malformed1(all_parsers):
|
| 359 |
+
parser = all_parsers
|
| 360 |
+
expected = pd.DataFrame(
|
| 361 |
+
np.array([[2, 3, 4, 5, 6], [8, 9, 10, 11, 12]], dtype="int64"),
|
| 362 |
+
index=pd.Index([1, 7]),
|
| 363 |
+
columns=pd.MultiIndex(
|
| 364 |
+
levels=[["a", "b", "c"], ["r", "s", "t", "u", "v"]],
|
| 365 |
+
codes=[[0, 0, 1, 2, 2], [0, 1, 2, 3, 4]],
|
| 366 |
+
names=["a", "q"],
|
| 367 |
+
),
|
| 368 |
+
)
|
| 369 |
+
data = """a,a,a,b,c,c
|
| 370 |
+
q,r,s,t,u,v
|
| 371 |
+
1,2,3,4,5,6
|
| 372 |
+
7,8,9,10,11,12"""
|
| 373 |
+
|
| 374 |
+
if parser.engine == "pyarrow":
|
| 375 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 376 |
+
parser.read_csv(StringIO(data), header=[0, 1], index_col=0)
|
| 377 |
+
return
|
| 378 |
+
|
| 379 |
+
result = parser.read_csv(StringIO(data), header=[0, 1], index_col=0)
|
| 380 |
+
tm.assert_frame_equal(expected, result)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def test_header_multi_index_common_format_malformed2(all_parsers):
|
| 384 |
+
parser = all_parsers
|
| 385 |
+
expected = pd.DataFrame(
|
| 386 |
+
np.array([[2, 3, 4, 5, 6], [8, 9, 10, 11, 12]], dtype="int64"),
|
| 387 |
+
index=range(1, 13, 6),
|
| 388 |
+
columns=pd.MultiIndex(
|
| 389 |
+
levels=[["a", "b", "c"], ["r", "s", "t", "u", "v"]],
|
| 390 |
+
codes=[[0, 0, 1, 2, 2], [0, 1, 2, 3, 4]],
|
| 391 |
+
names=[None, "q"],
|
| 392 |
+
),
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
data = """,a,a,b,c,c
|
| 396 |
+
q,r,s,t,u,v
|
| 397 |
+
1,2,3,4,5,6
|
| 398 |
+
7,8,9,10,11,12"""
|
| 399 |
+
|
| 400 |
+
if parser.engine == "pyarrow":
|
| 401 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 402 |
+
parser.read_csv(StringIO(data), header=[0, 1], index_col=0)
|
| 403 |
+
return
|
| 404 |
+
|
| 405 |
+
result = parser.read_csv(StringIO(data), header=[0, 1], index_col=0)
|
| 406 |
+
tm.assert_frame_equal(expected, result)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def test_header_multi_index_common_format_malformed3(all_parsers):
|
| 410 |
+
parser = all_parsers
|
| 411 |
+
expected = pd.DataFrame(
|
| 412 |
+
np.array([[3, 4, 5, 6], [9, 10, 11, 12]], dtype="int64"),
|
| 413 |
+
index=pd.MultiIndex(levels=[[1, 7], [2, 8]], codes=[[0, 1], [0, 1]]),
|
| 414 |
+
columns=pd.MultiIndex(
|
| 415 |
+
levels=[["a", "b", "c"], ["s", "t", "u", "v"]],
|
| 416 |
+
codes=[[0, 1, 2, 2], [0, 1, 2, 3]],
|
| 417 |
+
names=[None, "q"],
|
| 418 |
+
),
|
| 419 |
+
)
|
| 420 |
+
data = """,a,a,b,c,c
|
| 421 |
+
q,r,s,t,u,v
|
| 422 |
+
1,2,3,4,5,6
|
| 423 |
+
7,8,9,10,11,12"""
|
| 424 |
+
|
| 425 |
+
if parser.engine == "pyarrow":
|
| 426 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 427 |
+
parser.read_csv(StringIO(data), header=[0, 1], index_col=[0, 1])
|
| 428 |
+
return
|
| 429 |
+
|
| 430 |
+
result = parser.read_csv(StringIO(data), header=[0, 1], index_col=[0, 1])
|
| 431 |
+
tm.assert_frame_equal(expected, result)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def test_header_multi_index_blank_line(all_parsers):
|
| 435 |
+
# GH 40442
|
| 436 |
+
parser = all_parsers
|
| 437 |
+
data = [[None, None], [1, 2], [3, 4]]
|
| 438 |
+
columns = pd.MultiIndex.from_tuples([("a", "A"), ("b", "B")])
|
| 439 |
+
expected = pd.DataFrame(data, columns=columns)
|
| 440 |
+
data = "a,b\nA,B\n,\n1,2\n3,4"
|
| 441 |
+
|
| 442 |
+
if parser.engine == "pyarrow":
|
| 443 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 444 |
+
parser.read_csv(StringIO(data), header=[0, 1])
|
| 445 |
+
return
|
| 446 |
+
|
| 447 |
+
result = parser.read_csv(StringIO(data), header=[0, 1])
|
| 448 |
+
tm.assert_frame_equal(expected, result)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
@pytest.mark.parametrize(
|
| 452 |
+
"data,header", [("1,2,3\n4,5,6", None), ("foo,bar,baz\n1,2,3\n4,5,6", 0)]
|
| 453 |
+
)
|
| 454 |
+
def test_header_names_backward_compat(all_parsers, data, header):
|
| 455 |
+
# see gh-2539
|
| 456 |
+
parser = all_parsers
|
| 457 |
+
|
| 458 |
+
expected = parser.read_csv(StringIO("1,2,3\n4,5,6"), names=["a", "b", "c"])
|
| 459 |
+
|
| 460 |
+
result = parser.read_csv(StringIO(data), names=["a", "b", "c"], header=header)
|
| 461 |
+
tm.assert_frame_equal(result, expected)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def test_header_int_names_no_trailing_newline(all_parsers):
|
| 465 |
+
# GH#65862 the data portion starting on the final, newline-less line
|
| 466 |
+
# trips pyarrow's skip_rows
|
| 467 |
+
parser = all_parsers
|
| 468 |
+
data = "foo,bar,baz\n1,2,3\n4,5,6"
|
| 469 |
+
|
| 470 |
+
result = parser.read_csv(StringIO(data), header=1, names=["a", "b", "c"])
|
| 471 |
+
|
| 472 |
+
expected = pd.DataFrame([[4, 5, 6]], columns=["a", "b", "c"])
|
| 473 |
+
tm.assert_frame_equal(result, expected)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block: cannot infer
|
| 477 |
+
@pytest.mark.parametrize("kwargs", [{}, {"index_col": False}])
|
| 478 |
+
def test_read_only_header_no_rows(all_parsers, kwargs):
|
| 479 |
+
# See gh-7773
|
| 480 |
+
parser = all_parsers
|
| 481 |
+
expected = pd.DataFrame(columns=["a", "b", "c"])
|
| 482 |
+
|
| 483 |
+
result = parser.read_csv(StringIO("a,b,c"), **kwargs)
|
| 484 |
+
tm.assert_frame_equal(result, expected)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
@pytest.mark.parametrize(
|
| 488 |
+
"kwargs,names",
|
| 489 |
+
[
|
| 490 |
+
({}, [0, 1, 2, 3, 4]),
|
| 491 |
+
(
|
| 492 |
+
{"names": ["foo", "bar", "baz", "quux", "panda"]},
|
| 493 |
+
["foo", "bar", "baz", "quux", "panda"],
|
| 494 |
+
),
|
| 495 |
+
],
|
| 496 |
+
)
|
| 497 |
+
def test_no_header(all_parsers, kwargs, names):
|
| 498 |
+
parser = all_parsers
|
| 499 |
+
data = """1,2,3,4,5
|
| 500 |
+
6,7,8,9,10
|
| 501 |
+
11,12,13,14,15
|
| 502 |
+
"""
|
| 503 |
+
expected = pd.DataFrame(
|
| 504 |
+
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]], columns=names
|
| 505 |
+
)
|
| 506 |
+
result = parser.read_csv(StringIO(data), header=None, **kwargs)
|
| 507 |
+
tm.assert_frame_equal(result, expected)
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
@pytest.mark.parametrize("header", [["a", "b"], "string_header"])
|
| 511 |
+
def test_non_int_header(all_parsers, header):
|
| 512 |
+
# see gh-16338
|
| 513 |
+
msg = "header must be integer or list of integers"
|
| 514 |
+
data = """1,2\n3,4"""
|
| 515 |
+
parser = all_parsers
|
| 516 |
+
|
| 517 |
+
with pytest.raises(ValueError, match=msg):
|
| 518 |
+
parser.read_csv(StringIO(data), header=header)
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def test_singleton_header(all_parsers):
|
| 522 |
+
# see gh-7757
|
| 523 |
+
# header=[0] is a singleton, so for the pyarrow engine it behaves like
|
| 524 |
+
# header=0 (rather than raising for a MultiIndex header)
|
| 525 |
+
data = """a,b,c\n0,1,2\n1,2,3"""
|
| 526 |
+
parser = all_parsers
|
| 527 |
+
|
| 528 |
+
expected = pd.DataFrame({"a": [0, 1], "b": [1, 2], "c": [2, 3]})
|
| 529 |
+
result = parser.read_csv(StringIO(data), header=[0])
|
| 530 |
+
tm.assert_frame_equal(result, expected)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
@pytest.mark.parametrize(
|
| 534 |
+
"data,expected",
|
| 535 |
+
[
|
| 536 |
+
(
|
| 537 |
+
"A,A,A,B\none,one,one,two\n0,40,34,0.1",
|
| 538 |
+
pd.DataFrame(
|
| 539 |
+
[[0, 40, 34, 0.1]],
|
| 540 |
+
columns=pd.MultiIndex.from_tuples(
|
| 541 |
+
[("A", "one"), ("A", "one.1"), ("A", "one.2"), ("B", "two")]
|
| 542 |
+
),
|
| 543 |
+
),
|
| 544 |
+
),
|
| 545 |
+
(
|
| 546 |
+
"A,A,A,B\none,one,one.1,two\n0,40,34,0.1",
|
| 547 |
+
pd.DataFrame(
|
| 548 |
+
[[0, 40, 34, 0.1]],
|
| 549 |
+
columns=pd.MultiIndex.from_tuples(
|
| 550 |
+
[("A", "one"), ("A", "one.1"), ("A", "one.1.1"), ("B", "two")]
|
| 551 |
+
),
|
| 552 |
+
),
|
| 553 |
+
),
|
| 554 |
+
(
|
| 555 |
+
"A,A,A,B,B\none,one,one.1,two,two\n0,40,34,0.1,0.1",
|
| 556 |
+
pd.DataFrame(
|
| 557 |
+
[[0, 40, 34, 0.1, 0.1]],
|
| 558 |
+
columns=pd.MultiIndex.from_tuples(
|
| 559 |
+
[
|
| 560 |
+
("A", "one"),
|
| 561 |
+
("A", "one.1"),
|
| 562 |
+
("A", "one.1.1"),
|
| 563 |
+
("B", "two"),
|
| 564 |
+
("B", "two.1"),
|
| 565 |
+
]
|
| 566 |
+
),
|
| 567 |
+
),
|
| 568 |
+
),
|
| 569 |
+
],
|
| 570 |
+
)
|
| 571 |
+
def test_mangles_multi_index(all_parsers, data, expected):
|
| 572 |
+
# see gh-18062
|
| 573 |
+
parser = all_parsers
|
| 574 |
+
|
| 575 |
+
if parser.engine == "pyarrow":
|
| 576 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 577 |
+
parser.read_csv(StringIO(data), header=[0, 1])
|
| 578 |
+
return
|
| 579 |
+
|
| 580 |
+
result = parser.read_csv(StringIO(data), header=[0, 1])
|
| 581 |
+
tm.assert_frame_equal(result, expected)
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
@pytest.mark.parametrize("index_col", [None, [0]])
|
| 585 |
+
@pytest.mark.parametrize(
|
| 586 |
+
"columns", [None, (["", "Unnamed"]), (["Unnamed", ""]), (["Unnamed", "NotUnnamed"])]
|
| 587 |
+
)
|
| 588 |
+
def test_multi_index_unnamed(all_parsers, index_col, columns):
|
| 589 |
+
# see gh-23687
|
| 590 |
+
#
|
| 591 |
+
# When specifying a multi-index header, make sure that
|
| 592 |
+
# we don't error just because one of the rows in our header
|
| 593 |
+
# has ALL column names containing the string "Unnamed". The
|
| 594 |
+
# correct condition to check is whether the row contains
|
| 595 |
+
# ALL columns that did not have names (and instead were given
|
| 596 |
+
# placeholder ones).
|
| 597 |
+
parser = all_parsers
|
| 598 |
+
header = [0, 1]
|
| 599 |
+
|
| 600 |
+
if index_col is None:
|
| 601 |
+
data = ",".join(columns or ["", ""]) + "\n0,1\n2,3\n4,5\n"
|
| 602 |
+
else:
|
| 603 |
+
data = ",".join([""] + (columns or ["", ""])) + "\n,0,1\n0,2,3\n1,4,5\n"
|
| 604 |
+
|
| 605 |
+
if parser.engine == "pyarrow":
|
| 606 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 607 |
+
parser.read_csv(StringIO(data), header=header, index_col=index_col)
|
| 608 |
+
return
|
| 609 |
+
|
| 610 |
+
result = parser.read_csv(StringIO(data), header=header, index_col=index_col)
|
| 611 |
+
exp_columns = []
|
| 612 |
+
|
| 613 |
+
if columns is None:
|
| 614 |
+
columns = ["", "", ""]
|
| 615 |
+
|
| 616 |
+
for i, col in enumerate(columns):
|
| 617 |
+
if not col: # Unnamed.
|
| 618 |
+
col = f"Unnamed: {i if index_col is None else i + 1}_level_0"
|
| 619 |
+
|
| 620 |
+
exp_columns.append(col)
|
| 621 |
+
|
| 622 |
+
columns = pd.MultiIndex.from_tuples(zip(exp_columns, ["0", "1"], strict=False))
|
| 623 |
+
expected = pd.DataFrame([[2, 3], [4, 5]], columns=columns)
|
| 624 |
+
tm.assert_frame_equal(result, expected)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
@skip_pyarrow # CSV parse error: Expected 2 columns, got 3
|
| 628 |
+
def test_names_longer_than_header_but_equal_with_data_rows(all_parsers):
|
| 629 |
+
# GH#38453
|
| 630 |
+
parser = all_parsers
|
| 631 |
+
data = """a, b
|
| 632 |
+
1,2,3
|
| 633 |
+
5,6,4
|
| 634 |
+
"""
|
| 635 |
+
result = parser.read_csv(StringIO(data), header=0, names=["A", "B", "C"])
|
| 636 |
+
expected = pd.DataFrame({"A": [1, 5], "B": [2, 6], "C": [3, 4]})
|
| 637 |
+
tm.assert_frame_equal(result, expected)
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def test_read_csv_multiindex_columns(all_parsers):
|
| 641 |
+
# GH#6051
|
| 642 |
+
parser = all_parsers
|
| 643 |
+
|
| 644 |
+
s1 = "Male, Male, Male, Female, Female\nR, R, L, R, R\n.86, .67, .88, .78, .81"
|
| 645 |
+
s2 = (
|
| 646 |
+
"Male, Male, Male, Female, Female\n"
|
| 647 |
+
"R, R, L, R, R\n"
|
| 648 |
+
".86, .67, .88, .78, .81\n"
|
| 649 |
+
".86, .67, .88, .78, .82"
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
mi = pd.MultiIndex.from_tuples(
|
| 653 |
+
[
|
| 654 |
+
("Male", "R"),
|
| 655 |
+
(" Male", " R"),
|
| 656 |
+
(" Male", " L"),
|
| 657 |
+
(" Female", " R"),
|
| 658 |
+
(" Female", " R.1"),
|
| 659 |
+
]
|
| 660 |
+
)
|
| 661 |
+
expected = pd.DataFrame(
|
| 662 |
+
[[0.86, 0.67, 0.88, 0.78, 0.81], [0.86, 0.67, 0.88, 0.78, 0.82]], columns=mi
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
if parser.engine == "pyarrow":
|
| 666 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 667 |
+
parser.read_csv(StringIO(s1), header=[0, 1])
|
| 668 |
+
return
|
| 669 |
+
|
| 670 |
+
df1 = parser.read_csv(StringIO(s1), header=[0, 1])
|
| 671 |
+
tm.assert_frame_equal(df1, expected.iloc[:1])
|
| 672 |
+
df2 = parser.read_csv(StringIO(s2), header=[0, 1])
|
| 673 |
+
tm.assert_frame_equal(df2, expected)
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def test_read_csv_multi_header_length_check(all_parsers):
|
| 677 |
+
# GH#43102
|
| 678 |
+
parser = all_parsers
|
| 679 |
+
|
| 680 |
+
case = """row11,row12,row13
|
| 681 |
+
row21,row22, row23
|
| 682 |
+
row31,row32
|
| 683 |
+
"""
|
| 684 |
+
|
| 685 |
+
if parser.engine == "pyarrow":
|
| 686 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 687 |
+
parser.read_csv(StringIO(case), header=[0, 2])
|
| 688 |
+
return
|
| 689 |
+
|
| 690 |
+
with pytest.raises(
|
| 691 |
+
ParserError, match="Header rows must have an equal number of columns."
|
| 692 |
+
):
|
| 693 |
+
parser.read_csv(StringIO(case), header=[0, 2])
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
@skip_pyarrow # CSV parse error: Expected 3 columns, got 2
|
| 697 |
+
def test_header_none_and_implicit_index(all_parsers):
|
| 698 |
+
# GH#22144
|
| 699 |
+
parser = all_parsers
|
| 700 |
+
data = "x,1,5\ny,2\nz,3\n"
|
| 701 |
+
result = parser.read_csv(StringIO(data), names=["a", "b"], header=None)
|
| 702 |
+
expected = pd.DataFrame(
|
| 703 |
+
{"a": [1, 2, 3], "b": [5, np.nan, np.nan]}, index=["x", "y", "z"]
|
| 704 |
+
)
|
| 705 |
+
tm.assert_frame_equal(result, expected)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
@skip_pyarrow # regex mismatch "CSV parse error: Expected 2 columns, got "
|
| 709 |
+
def test_header_none_and_implicit_index_in_second_row(all_parsers):
|
| 710 |
+
# GH#22144
|
| 711 |
+
parser = all_parsers
|
| 712 |
+
data = "x,1\ny,2,5\nz,3\n"
|
| 713 |
+
with pytest.raises(ParserError, match="Expected 2 fields in line 2, saw 3"):
|
| 714 |
+
parser.read_csv(StringIO(data), names=["a", "b"], header=None)
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
def test_header_none_and_on_bad_lines_skip(all_parsers):
|
| 718 |
+
# GH#22144
|
| 719 |
+
parser = all_parsers
|
| 720 |
+
data = "x,1\ny,2,5\nz,3\n"
|
| 721 |
+
result = parser.read_csv(
|
| 722 |
+
StringIO(data), names=["a", "b"], header=None, on_bad_lines="skip"
|
| 723 |
+
)
|
| 724 |
+
expected = pd.DataFrame({"a": ["x", "z"], "b": [1, 3]})
|
| 725 |
+
tm.assert_frame_equal(result, expected)
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def test_header_missing_rows(all_parsers):
|
| 729 |
+
# GH#47400
|
| 730 |
+
parser = all_parsers
|
| 731 |
+
data = """a,b
|
| 732 |
+
1,2
|
| 733 |
+
"""
|
| 734 |
+
if parser.engine == "pyarrow":
|
| 735 |
+
msg = "does not support a list of integers"
|
| 736 |
+
else:
|
| 737 |
+
msg = r"Passed header=\[0,1,2\], len of 3, but only 2 lines in file"
|
| 738 |
+
with pytest.raises(ValueError, match=msg):
|
| 739 |
+
parser.read_csv(StringIO(data), header=[0, 1, 2])
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def test_header_multiple_whitespaces(all_parsers):
|
| 743 |
+
# GH#54931
|
| 744 |
+
parser = all_parsers
|
| 745 |
+
data = """aa bb(1,1) cc(1,1)
|
| 746 |
+
0 2 3.5"""
|
| 747 |
+
|
| 748 |
+
if parser.engine == "pyarrow":
|
| 749 |
+
msg = "the 'pyarrow' engine does not support separators > 1 char"
|
| 750 |
+
with pytest.raises(ValueError, match=msg):
|
| 751 |
+
parser.read_csv(StringIO(data), sep=r"\s+")
|
| 752 |
+
return
|
| 753 |
+
|
| 754 |
+
result = parser.read_csv(StringIO(data), sep=r"\s+")
|
| 755 |
+
expected = pd.DataFrame({"aa": [0], "bb(1,1)": 2, "cc(1,1)": 3.5})
|
| 756 |
+
tm.assert_frame_equal(result, expected)
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
def test_header_delim_whitespace(all_parsers):
|
| 760 |
+
# GH#54918
|
| 761 |
+
parser = all_parsers
|
| 762 |
+
data = """a,b
|
| 763 |
+
1,2
|
| 764 |
+
3,4
|
| 765 |
+
"""
|
| 766 |
+
if parser.engine == "pyarrow":
|
| 767 |
+
msg = "the 'pyarrow' engine does not support separators > 1 char"
|
| 768 |
+
with pytest.raises(ValueError, match=msg):
|
| 769 |
+
parser.read_csv(StringIO(data), sep=r"\s+")
|
| 770 |
+
return
|
| 771 |
+
|
| 772 |
+
result = parser.read_csv(StringIO(data), sep=r"\s+")
|
| 773 |
+
expected = pd.DataFrame({"a,b": ["1,2", "3,4"]})
|
| 774 |
+
tm.assert_frame_equal(result, expected)
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def test_usecols_no_header_pyarrow(pyarrow_parser_only):
|
| 778 |
+
parser = pyarrow_parser_only
|
| 779 |
+
data = """
|
| 780 |
+
a,i,x
|
| 781 |
+
b,j,y
|
| 782 |
+
"""
|
| 783 |
+
result = parser.read_csv(
|
| 784 |
+
StringIO(data),
|
| 785 |
+
header=None,
|
| 786 |
+
usecols=[0, 1],
|
| 787 |
+
dtype="string[pyarrow]",
|
| 788 |
+
dtype_backend="pyarrow",
|
| 789 |
+
engine="pyarrow",
|
| 790 |
+
)
|
| 791 |
+
expected = pd.DataFrame([["a", "i"], ["b", "j"]], dtype="string[pyarrow]")
|
| 792 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_index_col.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that the specified index column (a.k.a "index_col")
|
| 3 |
+
is properly handled or inferred during parsing for all of
|
| 4 |
+
the parsers defined in parsers.py
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from io import StringIO
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
|
| 15 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 16 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest.mark.parametrize("with_header", [True, False])
|
| 20 |
+
def test_index_col_named(all_parsers, with_header):
|
| 21 |
+
parser = all_parsers
|
| 22 |
+
no_header = """\
|
| 23 |
+
KORD1,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
|
| 24 |
+
KORD2,19990127, 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
|
| 25 |
+
KORD3,19990127, 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000
|
| 26 |
+
KORD4,19990127, 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000
|
| 27 |
+
KORD5,19990127, 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000
|
| 28 |
+
KORD6,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000"""
|
| 29 |
+
header = "ID,date,NominalTime,ActualTime,TDew,TAir,Windspeed,Precip,WindDir\n"
|
| 30 |
+
|
| 31 |
+
if with_header:
|
| 32 |
+
data = header + no_header
|
| 33 |
+
|
| 34 |
+
result = parser.read_csv(StringIO(data), index_col="ID")
|
| 35 |
+
expected = parser.read_csv(StringIO(data), header=0).set_index("ID")
|
| 36 |
+
tm.assert_frame_equal(result, expected)
|
| 37 |
+
else:
|
| 38 |
+
data = no_header
|
| 39 |
+
msg = "Index ID invalid"
|
| 40 |
+
|
| 41 |
+
with pytest.raises(ValueError, match=msg):
|
| 42 |
+
parser.read_csv(StringIO(data), index_col="ID")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_index_col_named2(all_parsers):
|
| 46 |
+
parser = all_parsers
|
| 47 |
+
data = """\
|
| 48 |
+
1,2,3,4,hello
|
| 49 |
+
5,6,7,8,world
|
| 50 |
+
9,10,11,12,foo
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
expected = pd.DataFrame(
|
| 54 |
+
{"a": [1, 5, 9], "b": [2, 6, 10], "c": [3, 7, 11], "d": [4, 8, 12]},
|
| 55 |
+
index=pd.Index(["hello", "world", "foo"], name="message"),
|
| 56 |
+
)
|
| 57 |
+
names = ["a", "b", "c", "d", "message"]
|
| 58 |
+
|
| 59 |
+
result = parser.read_csv(StringIO(data), names=names, index_col=["message"])
|
| 60 |
+
tm.assert_frame_equal(result, expected)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_index_col_is_true(all_parsers):
|
| 64 |
+
# see gh-9798
|
| 65 |
+
data = "a,b\n1,2"
|
| 66 |
+
parser = all_parsers
|
| 67 |
+
|
| 68 |
+
msg = "The value of index_col couldn't be 'True'"
|
| 69 |
+
with pytest.raises(ValueError, match=msg):
|
| 70 |
+
parser.read_csv(StringIO(data), index_col=True)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@skip_pyarrow # CSV parse error: Expected 3 columns, got 4
|
| 74 |
+
def test_infer_index_col(all_parsers):
|
| 75 |
+
data = """A,B,C
|
| 76 |
+
foo,1,2,3
|
| 77 |
+
bar,4,5,6
|
| 78 |
+
baz,7,8,9
|
| 79 |
+
"""
|
| 80 |
+
parser = all_parsers
|
| 81 |
+
result = parser.read_csv(StringIO(data))
|
| 82 |
+
|
| 83 |
+
expected = pd.DataFrame(
|
| 84 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
|
| 85 |
+
index=["foo", "bar", "baz"],
|
| 86 |
+
columns=["A", "B", "C"],
|
| 87 |
+
)
|
| 88 |
+
tm.assert_frame_equal(result, expected)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 92 |
+
@pytest.mark.parametrize(
|
| 93 |
+
"index_col,kwargs",
|
| 94 |
+
[
|
| 95 |
+
(None, {"columns": ["x", "y", "z"]}),
|
| 96 |
+
(False, {"columns": ["x", "y", "z"]}),
|
| 97 |
+
(0, {"columns": ["y", "z"], "index": pd.Index([], name="x")}),
|
| 98 |
+
(1, {"columns": ["x", "z"], "index": pd.Index([], name="y")}),
|
| 99 |
+
("x", {"columns": ["y", "z"], "index": pd.Index([], name="x")}),
|
| 100 |
+
("y", {"columns": ["x", "z"], "index": pd.Index([], name="y")}),
|
| 101 |
+
(
|
| 102 |
+
[0, 1],
|
| 103 |
+
{
|
| 104 |
+
"columns": ["z"],
|
| 105 |
+
"index": pd.MultiIndex.from_arrays([[]] * 2, names=["x", "y"]),
|
| 106 |
+
},
|
| 107 |
+
),
|
| 108 |
+
(
|
| 109 |
+
["x", "y"],
|
| 110 |
+
{
|
| 111 |
+
"columns": ["z"],
|
| 112 |
+
"index": pd.MultiIndex.from_arrays([[]] * 2, names=["x", "y"]),
|
| 113 |
+
},
|
| 114 |
+
),
|
| 115 |
+
(
|
| 116 |
+
[1, 0],
|
| 117 |
+
{
|
| 118 |
+
"columns": ["z"],
|
| 119 |
+
"index": pd.MultiIndex.from_arrays([[]] * 2, names=["y", "x"]),
|
| 120 |
+
},
|
| 121 |
+
),
|
| 122 |
+
(
|
| 123 |
+
["y", "x"],
|
| 124 |
+
{
|
| 125 |
+
"columns": ["z"],
|
| 126 |
+
"index": pd.MultiIndex.from_arrays([[]] * 2, names=["y", "x"]),
|
| 127 |
+
},
|
| 128 |
+
),
|
| 129 |
+
],
|
| 130 |
+
)
|
| 131 |
+
def test_index_col_empty_data(all_parsers, index_col, kwargs):
|
| 132 |
+
data = "x,y,z"
|
| 133 |
+
parser = all_parsers
|
| 134 |
+
result = parser.read_csv(StringIO(data), index_col=index_col)
|
| 135 |
+
|
| 136 |
+
expected = pd.DataFrame(**kwargs)
|
| 137 |
+
tm.assert_frame_equal(result, expected)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 141 |
+
def test_empty_with_index_col_false(all_parsers):
|
| 142 |
+
# see gh-10413
|
| 143 |
+
data = "x,y"
|
| 144 |
+
parser = all_parsers
|
| 145 |
+
result = parser.read_csv(StringIO(data), index_col=False)
|
| 146 |
+
|
| 147 |
+
expected = pd.DataFrame(columns=["x", "y"])
|
| 148 |
+
tm.assert_frame_equal(result, expected)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@pytest.mark.parametrize(
|
| 152 |
+
"index_names",
|
| 153 |
+
[
|
| 154 |
+
["", ""],
|
| 155 |
+
["foo", ""],
|
| 156 |
+
["", "bar"],
|
| 157 |
+
["foo", "bar"],
|
| 158 |
+
["NotReallyUnnamed", "Unnamed: 0"],
|
| 159 |
+
],
|
| 160 |
+
)
|
| 161 |
+
def test_multi_index_naming(all_parsers, index_names):
|
| 162 |
+
parser = all_parsers
|
| 163 |
+
|
| 164 |
+
# We don't want empty index names being replaced with "Unnamed: 0"
|
| 165 |
+
data = ",".join([*index_names, "col\na,c,1\na,d,2\nb,c,3\nb,d,4"])
|
| 166 |
+
result = parser.read_csv(StringIO(data), index_col=[0, 1])
|
| 167 |
+
|
| 168 |
+
expected = pd.DataFrame(
|
| 169 |
+
{"col": [1, 2, 3, 4]},
|
| 170 |
+
index=pd.MultiIndex.from_product([["a", "b"], ["c", "d"]]),
|
| 171 |
+
)
|
| 172 |
+
expected.index.names = [name if name else None for name in index_names]
|
| 173 |
+
tm.assert_frame_equal(result, expected)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def test_multi_index_naming_not_all_at_beginning(all_parsers):
|
| 177 |
+
parser = all_parsers
|
| 178 |
+
data = ",Unnamed: 2,\na,c,1\na,d,2\nb,c,3\nb,d,4"
|
| 179 |
+
result = parser.read_csv(StringIO(data), index_col=[0, 2])
|
| 180 |
+
|
| 181 |
+
expected = pd.DataFrame(
|
| 182 |
+
{"Unnamed: 2": ["c", "d", "c", "d"]},
|
| 183 |
+
index=pd.MultiIndex(
|
| 184 |
+
levels=[["a", "b"], [1, 2, 3, 4]], codes=[[0, 0, 1, 1], [0, 1, 2, 3]]
|
| 185 |
+
),
|
| 186 |
+
)
|
| 187 |
+
tm.assert_frame_equal(result, expected)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_no_multi_index_level_names_empty(temp_file, all_parsers):
|
| 191 |
+
# GH 10984
|
| 192 |
+
parser = all_parsers
|
| 193 |
+
midx = pd.MultiIndex.from_tuples([("A", 1, 2), ("A", 1, 2), ("B", 1, 2)])
|
| 194 |
+
expected = pd.DataFrame(
|
| 195 |
+
np.random.default_rng(2).standard_normal((3, 3)),
|
| 196 |
+
index=midx,
|
| 197 |
+
columns=["x", "y", "z"],
|
| 198 |
+
)
|
| 199 |
+
expected.to_csv(temp_file)
|
| 200 |
+
result = parser.read_csv(temp_file, index_col=[0, 1, 2])
|
| 201 |
+
tm.assert_frame_equal(result, expected)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
@xfail_pyarrow # TypeError: an integer is required
|
| 205 |
+
def test_header_with_index_col(all_parsers):
|
| 206 |
+
# GH 33476
|
| 207 |
+
parser = all_parsers
|
| 208 |
+
data = """
|
| 209 |
+
I11,A,A
|
| 210 |
+
I12,B,B
|
| 211 |
+
I2,1,3
|
| 212 |
+
"""
|
| 213 |
+
midx = pd.MultiIndex.from_tuples([("A", "B"), ("A", "B.1")], names=["I11", "I12"])
|
| 214 |
+
idx = pd.Index(["I2"])
|
| 215 |
+
expected = pd.DataFrame([[1, 3]], index=idx, columns=midx)
|
| 216 |
+
|
| 217 |
+
result = parser.read_csv(StringIO(data), index_col=0, header=[0, 1])
|
| 218 |
+
tm.assert_frame_equal(result, expected)
|
| 219 |
+
|
| 220 |
+
col_idx = pd.Index(["A", "A.1"])
|
| 221 |
+
idx = pd.Index(["I12", "I2"], name="I11")
|
| 222 |
+
expected = pd.DataFrame([["B", "B"], ["1", "3"]], index=idx, columns=col_idx)
|
| 223 |
+
|
| 224 |
+
result = parser.read_csv(StringIO(data), index_col="I11", header=0)
|
| 225 |
+
tm.assert_frame_equal(result, expected)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
@pytest.mark.slow
|
| 229 |
+
def test_index_col_large_csv(temp_file, all_parsers, monkeypatch):
|
| 230 |
+
# https://github.com/pandas-dev/pandas/issues/37094
|
| 231 |
+
parser = all_parsers
|
| 232 |
+
|
| 233 |
+
ARR_LEN = 100
|
| 234 |
+
df = pd.DataFrame(
|
| 235 |
+
{
|
| 236 |
+
"a": range(ARR_LEN + 1),
|
| 237 |
+
"b": np.random.default_rng(2).standard_normal(ARR_LEN + 1),
|
| 238 |
+
}
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
df.to_csv(temp_file, index=False)
|
| 242 |
+
with monkeypatch.context() as m:
|
| 243 |
+
m.setattr("pandas.core.algorithms._MINIMUM_COMP_ARR_LEN", ARR_LEN)
|
| 244 |
+
result = parser.read_csv(temp_file, index_col=[0])
|
| 245 |
+
|
| 246 |
+
tm.assert_frame_equal(result, df.set_index("a"))
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def test_index_col_multiindex_columns_no_data(all_parsers):
|
| 250 |
+
# GH#38292
|
| 251 |
+
parser = all_parsers
|
| 252 |
+
if parser.engine == "pyarrow":
|
| 253 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 254 |
+
parser.read_csv(
|
| 255 |
+
StringIO("a0,a1,a2\nb0,b1,b2\n"), header=[0, 1], index_col=0
|
| 256 |
+
)
|
| 257 |
+
return
|
| 258 |
+
|
| 259 |
+
result = parser.read_csv(
|
| 260 |
+
StringIO("a0,a1,a2\nb0,b1,b2\n"), header=[0, 1], index_col=0
|
| 261 |
+
)
|
| 262 |
+
expected = pd.DataFrame(
|
| 263 |
+
[],
|
| 264 |
+
index=pd.Index([]),
|
| 265 |
+
columns=pd.MultiIndex.from_arrays(
|
| 266 |
+
[["a1", "a2"], ["b1", "b2"]], names=["a0", "b0"]
|
| 267 |
+
),
|
| 268 |
+
)
|
| 269 |
+
tm.assert_frame_equal(result, expected)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# header=[0] is a singleton, so it behaves like header=0; the empty-frame
|
| 273 |
+
# index dtype still differs for the pyarrow engine (float64 vs object)
|
| 274 |
+
@xfail_pyarrow # AssertionError: DataFrame.index are different
|
| 275 |
+
def test_index_col_header_no_data(all_parsers):
|
| 276 |
+
# GH#38292
|
| 277 |
+
parser = all_parsers
|
| 278 |
+
result = parser.read_csv(StringIO("a0,a1,a2\n"), header=[0], index_col=0)
|
| 279 |
+
expected = pd.DataFrame(
|
| 280 |
+
[],
|
| 281 |
+
columns=["a1", "a2"],
|
| 282 |
+
index=pd.Index([], name="a0"),
|
| 283 |
+
)
|
| 284 |
+
tm.assert_frame_equal(result, expected)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def test_multiindex_columns_no_data(all_parsers):
|
| 288 |
+
# GH#38292
|
| 289 |
+
parser = all_parsers
|
| 290 |
+
if parser.engine == "pyarrow":
|
| 291 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 292 |
+
parser.read_csv(StringIO("a0,a1,a2\nb0,b1,b2\n"), header=[0, 1])
|
| 293 |
+
return
|
| 294 |
+
|
| 295 |
+
result = parser.read_csv(StringIO("a0,a1,a2\nb0,b1,b2\n"), header=[0, 1])
|
| 296 |
+
expected = pd.DataFrame(
|
| 297 |
+
[], columns=pd.MultiIndex.from_arrays([["a0", "a1", "a2"], ["b0", "b1", "b2"]])
|
| 298 |
+
)
|
| 299 |
+
tm.assert_frame_equal(result, expected)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def test_multiindex_columns_index_col_with_data(all_parsers):
|
| 303 |
+
# GH#38292
|
| 304 |
+
parser = all_parsers
|
| 305 |
+
if parser.engine == "pyarrow":
|
| 306 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 307 |
+
parser.read_csv(
|
| 308 |
+
StringIO("a0,a1,a2\nb0,b1,b2\ndata,data,data"),
|
| 309 |
+
header=[0, 1],
|
| 310 |
+
index_col=0,
|
| 311 |
+
)
|
| 312 |
+
return
|
| 313 |
+
|
| 314 |
+
result = parser.read_csv(
|
| 315 |
+
StringIO("a0,a1,a2\nb0,b1,b2\ndata,data,data"), header=[0, 1], index_col=0
|
| 316 |
+
)
|
| 317 |
+
expected = pd.DataFrame(
|
| 318 |
+
[["data", "data"]],
|
| 319 |
+
columns=pd.MultiIndex.from_arrays(
|
| 320 |
+
[["a1", "a2"], ["b1", "b2"]], names=["a0", "b0"]
|
| 321 |
+
),
|
| 322 |
+
index=pd.Index(["data"]),
|
| 323 |
+
)
|
| 324 |
+
tm.assert_frame_equal(result, expected)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
@skip_pyarrow # CSV parse error: Empty CSV file or block
|
| 328 |
+
def test_infer_types_boolean_sum(all_parsers):
|
| 329 |
+
# GH#44079
|
| 330 |
+
parser = all_parsers
|
| 331 |
+
result = parser.read_csv(
|
| 332 |
+
StringIO("0,1"),
|
| 333 |
+
names=["a", "b"],
|
| 334 |
+
index_col=["a"],
|
| 335 |
+
dtype={"a": "UInt8"},
|
| 336 |
+
)
|
| 337 |
+
expected = pd.DataFrame(
|
| 338 |
+
data={
|
| 339 |
+
"a": [
|
| 340 |
+
0,
|
| 341 |
+
],
|
| 342 |
+
"b": [1],
|
| 343 |
+
}
|
| 344 |
+
).set_index("a")
|
| 345 |
+
# Not checking index type now, because the C parser will return a
|
| 346 |
+
# index column of dtype 'object', and the Python parser will return a
|
| 347 |
+
# index column of dtype 'int64'.
|
| 348 |
+
tm.assert_frame_equal(result, expected, check_index_type=False)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
@pytest.mark.parametrize("dtype, val", [(object, "01"), ("int64", 1)])
|
| 352 |
+
def test_specify_dtype_for_index_col(all_parsers, dtype, val):
|
| 353 |
+
# GH#9435, GH#57666
|
| 354 |
+
data = "a,b\n01,2"
|
| 355 |
+
parser = all_parsers
|
| 356 |
+
result = parser.read_csv(StringIO(data), index_col="a", dtype={"a": dtype})
|
| 357 |
+
expected = pd.DataFrame({"b": [2]}, index=pd.Index([val], name="a", dtype=dtype))
|
| 358 |
+
tm.assert_frame_equal(result, expected)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
@pytest.mark.parametrize("dtype", [str, object])
|
| 362 |
+
def test_scalar_dtype_for_index_col(all_parsers, dtype, using_infer_string, request):
|
| 363 |
+
# GH#45801 a scalar dtype applies to the index column too, like the c
|
| 364 |
+
# engine, except when it resolves to object (dtype=object always;
|
| 365 |
+
# dtype=str with infer_string disabled), in which case index columns
|
| 366 |
+
# keep their inferred values
|
| 367 |
+
parser = all_parsers
|
| 368 |
+
data = "a,b\n1,x\n2,y"
|
| 369 |
+
apply_to_index = dtype is str and using_infer_string
|
| 370 |
+
if parser.engine == "python" and apply_to_index:
|
| 371 |
+
request.applymarker(
|
| 372 |
+
pytest.mark.xfail(
|
| 373 |
+
reason="python engine does not apply scalar dtype to index_col"
|
| 374 |
+
)
|
| 375 |
+
)
|
| 376 |
+
result = parser.read_csv(StringIO(data), index_col="a", dtype=dtype)
|
| 377 |
+
if apply_to_index:
|
| 378 |
+
expected_index = pd.Index(["1", "2"], name="a", dtype=dtype)
|
| 379 |
+
else:
|
| 380 |
+
expected_index = pd.Index([1, 2], name="a")
|
| 381 |
+
expected = pd.DataFrame({"b": ["x", "y"]}, index=expected_index, dtype=dtype)
|
| 382 |
+
tm.assert_frame_equal(result, expected)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
@pytest.mark.parametrize("dtype", ["float64", "Int64"])
|
| 386 |
+
def test_scalar_numeric_dtype_for_index_col(all_parsers, dtype, request):
|
| 387 |
+
# GH#45801 a scalar dtype applies to the index column too, like the c
|
| 388 |
+
# engine
|
| 389 |
+
parser = all_parsers
|
| 390 |
+
data = "a,b\n1,2\n3,4"
|
| 391 |
+
if parser.engine == "python":
|
| 392 |
+
request.applymarker(
|
| 393 |
+
pytest.mark.xfail(
|
| 394 |
+
reason="python engine does not apply scalar dtype to index_col"
|
| 395 |
+
)
|
| 396 |
+
)
|
| 397 |
+
result = parser.read_csv(StringIO(data), index_col="a", dtype=dtype)
|
| 398 |
+
expected = pd.DataFrame(
|
| 399 |
+
{"b": [2, 4]}, index=pd.Index([1, 3], name="a"), dtype=dtype
|
| 400 |
+
)
|
| 401 |
+
expected.index = expected.index.astype(dtype)
|
| 402 |
+
tm.assert_frame_equal(result, expected)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def test_multiindex_columns_not_leading_index_col(all_parsers):
|
| 406 |
+
# GH#38549
|
| 407 |
+
parser = all_parsers
|
| 408 |
+
data = """a,b,c,d
|
| 409 |
+
e,f,g,h
|
| 410 |
+
x,y,1,2
|
| 411 |
+
"""
|
| 412 |
+
if parser.engine == "pyarrow":
|
| 413 |
+
with pytest.raises(ValueError, match="does not support a list of integers"):
|
| 414 |
+
parser.read_csv(StringIO(data), header=[0, 1], index_col=1)
|
| 415 |
+
return
|
| 416 |
+
|
| 417 |
+
result = parser.read_csv(
|
| 418 |
+
StringIO(data),
|
| 419 |
+
header=[0, 1],
|
| 420 |
+
index_col=1,
|
| 421 |
+
)
|
| 422 |
+
cols = pd.MultiIndex.from_tuples(
|
| 423 |
+
[("a", "e"), ("c", "g"), ("d", "h")], names=["b", "f"]
|
| 424 |
+
)
|
| 425 |
+
expected = pd.DataFrame([["x", 1, 2]], columns=cols, index=["y"])
|
| 426 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_mangle_dupes.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that duplicate columns are handled appropriately when parsed by the
|
| 3 |
+
CSV engine. In general, the expected result is that they are either thoroughly
|
| 4 |
+
de-duplicated (if mangling requested) or ignored otherwise.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from io import StringIO
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_basic(all_parsers):
|
| 16 |
+
parser = all_parsers
|
| 17 |
+
|
| 18 |
+
data = "a,a,b,b,b\n1,2,3,4,5"
|
| 19 |
+
result = parser.read_csv(StringIO(data), sep=",")
|
| 20 |
+
|
| 21 |
+
expected = pd.DataFrame([[1, 2, 3, 4, 5]], columns=["a", "a.1", "b", "b.1", "b.2"])
|
| 22 |
+
tm.assert_frame_equal(result, expected)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_basic_names(all_parsers):
|
| 26 |
+
# See gh-7160
|
| 27 |
+
parser = all_parsers
|
| 28 |
+
|
| 29 |
+
data = "a,b,a\n0,1,2\n3,4,5"
|
| 30 |
+
expected = pd.DataFrame([[0, 1, 2], [3, 4, 5]], columns=["a", "b", "a.1"])
|
| 31 |
+
|
| 32 |
+
result = parser.read_csv(StringIO(data))
|
| 33 |
+
tm.assert_frame_equal(result, expected)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_basic_names_raise(all_parsers):
|
| 37 |
+
# See gh-7160
|
| 38 |
+
parser = all_parsers
|
| 39 |
+
|
| 40 |
+
data = "0,1,2\n3,4,5"
|
| 41 |
+
with pytest.raises(ValueError, match="Duplicate names"):
|
| 42 |
+
parser.read_csv(StringIO(data), names=["a", "b", "a"])
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@pytest.mark.parametrize(
|
| 46 |
+
"data,expected",
|
| 47 |
+
[
|
| 48 |
+
("a,a,a.1\n1,2,3", pd.DataFrame([[1, 2, 3]], columns=["a", "a.2", "a.1"])),
|
| 49 |
+
(
|
| 50 |
+
"a,a,a.1,a.1.1,a.1.1.1,a.1.1.1.1\n1,2,3,4,5,6",
|
| 51 |
+
pd.DataFrame(
|
| 52 |
+
[[1, 2, 3, 4, 5, 6]],
|
| 53 |
+
columns=["a", "a.2", "a.1", "a.1.1", "a.1.1.1", "a.1.1.1.1"],
|
| 54 |
+
),
|
| 55 |
+
),
|
| 56 |
+
(
|
| 57 |
+
"a,a,a.3,a.1,a.2,a,a\n1,2,3,4,5,6,7",
|
| 58 |
+
pd.DataFrame(
|
| 59 |
+
[[1, 2, 3, 4, 5, 6, 7]],
|
| 60 |
+
columns=["a", "a.4", "a.3", "a.1", "a.2", "a.5", "a.6"],
|
| 61 |
+
),
|
| 62 |
+
),
|
| 63 |
+
],
|
| 64 |
+
)
|
| 65 |
+
def test_thorough_mangle_columns(all_parsers, data, expected):
|
| 66 |
+
# see gh-17060
|
| 67 |
+
parser = all_parsers
|
| 68 |
+
|
| 69 |
+
result = parser.read_csv(StringIO(data))
|
| 70 |
+
tm.assert_frame_equal(result, expected)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@pytest.mark.parametrize(
|
| 74 |
+
"data,names,expected",
|
| 75 |
+
[
|
| 76 |
+
(
|
| 77 |
+
"a,b,b\n1,2,3",
|
| 78 |
+
["a.1", "a.1", "a.1.1"],
|
| 79 |
+
pd.DataFrame(
|
| 80 |
+
[["a", "b", "b"], ["1", "2", "3"]], columns=["a.1", "a.1.1", "a.1.1.1"]
|
| 81 |
+
),
|
| 82 |
+
),
|
| 83 |
+
(
|
| 84 |
+
"a,b,c,d,e,f\n1,2,3,4,5,6",
|
| 85 |
+
["a", "a", "a.1", "a.1.1", "a.1.1.1", "a.1.1.1.1"],
|
| 86 |
+
pd.DataFrame(
|
| 87 |
+
[["a", "b", "c", "d", "e", "f"], ["1", "2", "3", "4", "5", "6"]],
|
| 88 |
+
columns=["a", "a.1", "a.1.1", "a.1.1.1", "a.1.1.1.1", "a.1.1.1.1.1"],
|
| 89 |
+
),
|
| 90 |
+
),
|
| 91 |
+
(
|
| 92 |
+
"a,b,c,d,e,f,g\n1,2,3,4,5,6,7",
|
| 93 |
+
["a", "a", "a.3", "a.1", "a.2", "a", "a"],
|
| 94 |
+
pd.DataFrame(
|
| 95 |
+
[
|
| 96 |
+
["a", "b", "c", "d", "e", "f", "g"],
|
| 97 |
+
["1", "2", "3", "4", "5", "6", "7"],
|
| 98 |
+
],
|
| 99 |
+
columns=["a", "a.1", "a.3", "a.1.1", "a.2", "a.2.1", "a.3.1"],
|
| 100 |
+
),
|
| 101 |
+
),
|
| 102 |
+
],
|
| 103 |
+
)
|
| 104 |
+
def test_thorough_mangle_names(all_parsers, data, names, expected):
|
| 105 |
+
# see gh-17095
|
| 106 |
+
parser = all_parsers
|
| 107 |
+
|
| 108 |
+
with pytest.raises(ValueError, match="Duplicate names"):
|
| 109 |
+
parser.read_csv(StringIO(data), names=names)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_mangled_unnamed_placeholders(all_parsers):
|
| 113 |
+
# xref gh-13017
|
| 114 |
+
orig_key = "0"
|
| 115 |
+
parser = all_parsers
|
| 116 |
+
|
| 117 |
+
orig_value = [1, 2, 3]
|
| 118 |
+
df = pd.DataFrame({orig_key: orig_value})
|
| 119 |
+
|
| 120 |
+
# This test recursively updates `df`.
|
| 121 |
+
for i in range(3):
|
| 122 |
+
expected = pd.DataFrame(columns=pd.Index([], dtype="str"))
|
| 123 |
+
|
| 124 |
+
for j in range(i + 1):
|
| 125 |
+
col_name = "Unnamed: 0" + f".{1 * j}" * min(j, 1)
|
| 126 |
+
expected.insert(loc=0, column=col_name, value=[0, 1, 2])
|
| 127 |
+
|
| 128 |
+
expected[orig_key] = orig_value
|
| 129 |
+
df = parser.read_csv(StringIO(df.to_csv()))
|
| 130 |
+
|
| 131 |
+
tm.assert_frame_equal(df, expected)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def test_mangle_dupe_cols_already_exists(all_parsers):
|
| 135 |
+
# GH#14704
|
| 136 |
+
parser = all_parsers
|
| 137 |
+
|
| 138 |
+
data = "a,a,a.1,a,a.3,a.1,a.1.1\n1,2,3,4,5,6,7"
|
| 139 |
+
result = parser.read_csv(StringIO(data))
|
| 140 |
+
expected = pd.DataFrame(
|
| 141 |
+
[[1, 2, 3, 4, 5, 6, 7]],
|
| 142 |
+
columns=["a", "a.2", "a.1", "a.4", "a.3", "a.1.2", "a.1.1"],
|
| 143 |
+
)
|
| 144 |
+
tm.assert_frame_equal(result, expected)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_mangle_dupe_cols_already_exists_unnamed_col(all_parsers):
|
| 148 |
+
# GH#14704
|
| 149 |
+
parser = all_parsers
|
| 150 |
+
|
| 151 |
+
data = ",Unnamed: 0,,Unnamed: 2\n1,2,3,4"
|
| 152 |
+
result = parser.read_csv(StringIO(data))
|
| 153 |
+
expected = pd.DataFrame(
|
| 154 |
+
[[1, 2, 3, 4]],
|
| 155 |
+
columns=["Unnamed: 0.1", "Unnamed: 0", "Unnamed: 2.1", "Unnamed: 2"],
|
| 156 |
+
)
|
| 157 |
+
tm.assert_frame_equal(result, expected)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@pytest.mark.parametrize("usecol, engine", [([0, 1, 1], "python"), ([0, 1, 1], "c")])
|
| 161 |
+
def test_mangle_cols_names(all_parsers, usecol, engine):
|
| 162 |
+
# GH 11823
|
| 163 |
+
parser = all_parsers
|
| 164 |
+
data = "1,2,3"
|
| 165 |
+
names = ["A", "A", "B"]
|
| 166 |
+
with pytest.raises(ValueError, match="Duplicate names"):
|
| 167 |
+
parser.read_csv(StringIO(data), names=names, usecols=usecol, engine=engine)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_multi_thread.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests multithreading behaviour for reading and
|
| 3 |
+
parsing files for each parser defined in parsers.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from contextlib import ExitStack
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
from multiprocessing.pool import ThreadPool
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
import pandas as pd
|
| 14 |
+
import pandas._testing as tm
|
| 15 |
+
|
| 16 |
+
# We'll probably always skip these for pyarrow
|
| 17 |
+
# Maybe we'll add our own tests for pyarrow too
|
| 18 |
+
pytestmark = [
|
| 19 |
+
pytest.mark.single_cpu,
|
| 20 |
+
pytest.mark.slow,
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_multi_thread_string_io_read_csv(all_parsers):
|
| 25 |
+
# see gh-11786
|
| 26 |
+
parser = all_parsers
|
| 27 |
+
max_row_range = 100
|
| 28 |
+
num_files = 10
|
| 29 |
+
|
| 30 |
+
bytes_to_df = (
|
| 31 |
+
"\n".join([f"{i:d},{i:d},{i:d}" for i in range(max_row_range)]).encode()
|
| 32 |
+
for _ in range(num_files)
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# Read all files in many threads.
|
| 36 |
+
with ExitStack() as stack:
|
| 37 |
+
files = [stack.enter_context(BytesIO(b)) for b in bytes_to_df]
|
| 38 |
+
|
| 39 |
+
pool = stack.enter_context(ThreadPool(8))
|
| 40 |
+
|
| 41 |
+
results = pool.map(parser.read_csv, files)
|
| 42 |
+
first_result = results[0]
|
| 43 |
+
|
| 44 |
+
for result in results:
|
| 45 |
+
tm.assert_frame_equal(first_result, result)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _generate_multi_thread_dataframe(parser, path, num_rows, num_tasks):
|
| 49 |
+
"""
|
| 50 |
+
Generate a DataFrame via multi-thread.
|
| 51 |
+
|
| 52 |
+
Parameters
|
| 53 |
+
----------
|
| 54 |
+
parser : BaseParser
|
| 55 |
+
The parser object to use for reading the data.
|
| 56 |
+
path : str
|
| 57 |
+
The location of the CSV file to read.
|
| 58 |
+
num_rows : int
|
| 59 |
+
The number of rows to read per task.
|
| 60 |
+
num_tasks : int
|
| 61 |
+
The number of tasks to use for reading this DataFrame.
|
| 62 |
+
|
| 63 |
+
Returns
|
| 64 |
+
-------
|
| 65 |
+
df : DataFrame
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
def reader(arg):
|
| 69 |
+
"""
|
| 70 |
+
Create a reader for part of the CSV.
|
| 71 |
+
|
| 72 |
+
Parameters
|
| 73 |
+
----------
|
| 74 |
+
arg : tuple
|
| 75 |
+
A tuple of the following:
|
| 76 |
+
|
| 77 |
+
* start : int
|
| 78 |
+
The starting row to start for parsing CSV
|
| 79 |
+
* nrows : int
|
| 80 |
+
The number of rows to read.
|
| 81 |
+
|
| 82 |
+
Returns
|
| 83 |
+
-------
|
| 84 |
+
df : DataFrame
|
| 85 |
+
"""
|
| 86 |
+
start, nrows = arg
|
| 87 |
+
|
| 88 |
+
if not start:
|
| 89 |
+
return parser.read_csv(
|
| 90 |
+
path, index_col=0, header=0, nrows=nrows, parse_dates=["date"]
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
return parser.read_csv(
|
| 94 |
+
path,
|
| 95 |
+
index_col=0,
|
| 96 |
+
header=None,
|
| 97 |
+
skiprows=int(start) + 1,
|
| 98 |
+
nrows=nrows,
|
| 99 |
+
parse_dates=[9],
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
tasks = [
|
| 103 |
+
(num_rows * i // num_tasks, num_rows // num_tasks) for i in range(num_tasks)
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
with ThreadPool(processes=num_tasks) as pool:
|
| 107 |
+
results = pool.map(reader, tasks)
|
| 108 |
+
|
| 109 |
+
header = results[0].columns
|
| 110 |
+
|
| 111 |
+
for r in results[1:]:
|
| 112 |
+
r.columns = header
|
| 113 |
+
|
| 114 |
+
final_dataframe = pd.concat(results)
|
| 115 |
+
return final_dataframe
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_multi_thread_path_multipart_read_csv(tmp_path, all_parsers):
|
| 119 |
+
# see gh-11786
|
| 120 |
+
num_tasks = 4
|
| 121 |
+
num_rows = 48
|
| 122 |
+
|
| 123 |
+
parser = all_parsers
|
| 124 |
+
file_name = "__thread_pool_reader__.csv"
|
| 125 |
+
df = pd.DataFrame(
|
| 126 |
+
{
|
| 127 |
+
"a": np.random.default_rng(2).random(num_rows),
|
| 128 |
+
"b": np.random.default_rng(2).random(num_rows),
|
| 129 |
+
"c": np.random.default_rng(2).random(num_rows),
|
| 130 |
+
"d": np.random.default_rng(2).random(num_rows),
|
| 131 |
+
"e": np.random.default_rng(2).random(num_rows),
|
| 132 |
+
"foo": ["foo"] * num_rows,
|
| 133 |
+
"bar": ["bar"] * num_rows,
|
| 134 |
+
"baz": ["baz"] * num_rows,
|
| 135 |
+
"date": pd.date_range("20000101 09:00:00", periods=num_rows, freq="s"),
|
| 136 |
+
"int": np.arange(num_rows, dtype="int64"),
|
| 137 |
+
}
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
path = tmp_path / file_name
|
| 141 |
+
df.to_csv(path)
|
| 142 |
+
|
| 143 |
+
if parser.engine == "pyarrow":
|
| 144 |
+
msg = "The 'nrows' option is not supported with the 'pyarrow' engine"
|
| 145 |
+
with pytest.raises(ValueError, match=msg):
|
| 146 |
+
_generate_multi_thread_dataframe(parser, path, num_rows, num_tasks)
|
| 147 |
+
return
|
| 148 |
+
|
| 149 |
+
result = _generate_multi_thread_dataframe(parser, path, num_rows, num_tasks)
|
| 150 |
+
|
| 151 |
+
expected = df[:]
|
| 152 |
+
expected["date"] = expected["date"].astype("M8[us]")
|
| 153 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_na_values.py
ADDED
|
@@ -0,0 +1,939 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that NA values are properly handled during
|
| 3 |
+
parsing for all of the parsers defined in parsers.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from io import StringIO
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
from pandas._libs.parsers import STR_NA_VALUES
|
| 12 |
+
|
| 13 |
+
import pandas as pd
|
| 14 |
+
import pandas._testing as tm
|
| 15 |
+
|
| 16 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 17 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_string_nas(all_parsers):
|
| 21 |
+
parser = all_parsers
|
| 22 |
+
data = """A,B,C
|
| 23 |
+
a,b,c
|
| 24 |
+
d,,f
|
| 25 |
+
,g,h
|
| 26 |
+
"""
|
| 27 |
+
result = parser.read_csv(StringIO(data))
|
| 28 |
+
expected = pd.DataFrame(
|
| 29 |
+
[["a", "b", "c"], ["d", np.nan, "f"], [np.nan, "g", "h"]],
|
| 30 |
+
columns=["A", "B", "C"],
|
| 31 |
+
)
|
| 32 |
+
if parser.engine == "pyarrow":
|
| 33 |
+
expected.loc[2, "A"] = None
|
| 34 |
+
expected.loc[1, "B"] = None
|
| 35 |
+
tm.assert_frame_equal(result, expected)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_detect_string_na(all_parsers):
|
| 39 |
+
parser = all_parsers
|
| 40 |
+
data = """A,B
|
| 41 |
+
foo,bar
|
| 42 |
+
NA,baz
|
| 43 |
+
NaN,nan
|
| 44 |
+
"""
|
| 45 |
+
expected = pd.DataFrame(
|
| 46 |
+
[["foo", "bar"], [np.nan, "baz"], [np.nan, np.nan]], columns=["A", "B"]
|
| 47 |
+
)
|
| 48 |
+
if parser.engine == "pyarrow":
|
| 49 |
+
expected.loc[[1, 2], "A"] = None
|
| 50 |
+
expected.loc[2, "B"] = None
|
| 51 |
+
result = parser.read_csv(StringIO(data))
|
| 52 |
+
tm.assert_frame_equal(result, expected)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@pytest.mark.parametrize(
|
| 56 |
+
"na_values",
|
| 57 |
+
[
|
| 58 |
+
["-999.0", "-999"],
|
| 59 |
+
[-999, -999.0],
|
| 60 |
+
[-999.0, -999],
|
| 61 |
+
["-999.0"],
|
| 62 |
+
["-999"],
|
| 63 |
+
[-999.0],
|
| 64 |
+
[-999],
|
| 65 |
+
],
|
| 66 |
+
)
|
| 67 |
+
@pytest.mark.parametrize(
|
| 68 |
+
"data",
|
| 69 |
+
[
|
| 70 |
+
"""A,B
|
| 71 |
+
-999,1.2
|
| 72 |
+
2,-999
|
| 73 |
+
3,4.5
|
| 74 |
+
""",
|
| 75 |
+
"""A,B
|
| 76 |
+
-999,1.200
|
| 77 |
+
2,-999.000
|
| 78 |
+
3,4.500
|
| 79 |
+
""",
|
| 80 |
+
],
|
| 81 |
+
)
|
| 82 |
+
def test_non_string_na_values(all_parsers, data, na_values, request):
|
| 83 |
+
# see gh-3611: with an odd float format, we can't match
|
| 84 |
+
# the string "999.0" exactly but still need float matching
|
| 85 |
+
parser = all_parsers
|
| 86 |
+
expected = pd.DataFrame(
|
| 87 |
+
[[np.nan, 1.2], [2.0, np.nan], [3.0, 4.5]], columns=["A", "B"]
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if parser.engine == "pyarrow" and not all(isinstance(x, str) for x in na_values):
|
| 91 |
+
msg = "The 'pyarrow' engine requires all na_values to be strings"
|
| 92 |
+
with pytest.raises(TypeError, match=msg):
|
| 93 |
+
parser.read_csv(StringIO(data), na_values=na_values)
|
| 94 |
+
return
|
| 95 |
+
elif parser.engine == "pyarrow" and "-999.000" in data:
|
| 96 |
+
# bc the pyarrow engine does not include the float-ified version
|
| 97 |
+
# of "-999" -> -999, it does not match the entry with the trailing
|
| 98 |
+
# zeros, so "-999.000" is not treated as null.
|
| 99 |
+
mark = pytest.mark.xfail(
|
| 100 |
+
reason="pyarrow engined does not recognize equivalent floats"
|
| 101 |
+
)
|
| 102 |
+
request.applymarker(mark)
|
| 103 |
+
|
| 104 |
+
result = parser.read_csv(StringIO(data), na_values=na_values)
|
| 105 |
+
tm.assert_frame_equal(result, expected)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_default_na_values(all_parsers):
|
| 109 |
+
_NA_VALUES = {
|
| 110 |
+
"-1.#IND",
|
| 111 |
+
"1.#QNAN",
|
| 112 |
+
"1.#IND",
|
| 113 |
+
"-1.#QNAN",
|
| 114 |
+
"#N/A",
|
| 115 |
+
"N/A",
|
| 116 |
+
"n/a",
|
| 117 |
+
"NA",
|
| 118 |
+
"<NA>",
|
| 119 |
+
"#NA",
|
| 120 |
+
"NULL",
|
| 121 |
+
"null",
|
| 122 |
+
"NaN",
|
| 123 |
+
"nan",
|
| 124 |
+
"-NaN",
|
| 125 |
+
"-nan",
|
| 126 |
+
"#N/A N/A",
|
| 127 |
+
"",
|
| 128 |
+
"None",
|
| 129 |
+
}
|
| 130 |
+
assert _NA_VALUES == STR_NA_VALUES
|
| 131 |
+
|
| 132 |
+
parser = all_parsers
|
| 133 |
+
nv = len(_NA_VALUES)
|
| 134 |
+
|
| 135 |
+
def f(i, v):
|
| 136 |
+
if i == 0:
|
| 137 |
+
buf = ""
|
| 138 |
+
elif i > 0:
|
| 139 |
+
buf = "".join([","] * i)
|
| 140 |
+
|
| 141 |
+
buf = f"{buf}{v}"
|
| 142 |
+
|
| 143 |
+
if i < nv - 1:
|
| 144 |
+
joined = "".join([","] * (nv - i - 1))
|
| 145 |
+
buf = f"{buf}{joined}"
|
| 146 |
+
|
| 147 |
+
return buf
|
| 148 |
+
|
| 149 |
+
data = StringIO("\n".join([f(i, v) for i, v in enumerate(_NA_VALUES)]))
|
| 150 |
+
expected = pd.DataFrame(np.nan, columns=range(nv), index=range(nv))
|
| 151 |
+
|
| 152 |
+
result = parser.read_csv(data, header=None)
|
| 153 |
+
tm.assert_frame_equal(result, expected)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@pytest.mark.parametrize("na_values", ["baz", ["baz"]])
|
| 157 |
+
def test_custom_na_values(all_parsers, na_values):
|
| 158 |
+
parser = all_parsers
|
| 159 |
+
data = """A,B,C
|
| 160 |
+
ignore,this,row
|
| 161 |
+
1,NA,3
|
| 162 |
+
-1.#IND,5,baz
|
| 163 |
+
7,8,NaN
|
| 164 |
+
"""
|
| 165 |
+
expected = pd.DataFrame(
|
| 166 |
+
[[1.0, np.nan, 3], [np.nan, 5, np.nan], [7, 8, np.nan]], columns=["A", "B", "C"]
|
| 167 |
+
)
|
| 168 |
+
if parser.engine == "pyarrow":
|
| 169 |
+
msg = "skiprows argument must be an integer when using engine='pyarrow'"
|
| 170 |
+
with pytest.raises(ValueError, match=msg):
|
| 171 |
+
parser.read_csv(StringIO(data), na_values=na_values, skiprows=[1])
|
| 172 |
+
return
|
| 173 |
+
|
| 174 |
+
result = parser.read_csv(StringIO(data), na_values=na_values, skiprows=[1])
|
| 175 |
+
tm.assert_frame_equal(result, expected)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def test_bool_na_values(all_parsers):
|
| 179 |
+
data = """A,B,C
|
| 180 |
+
True,False,True
|
| 181 |
+
NA,True,False
|
| 182 |
+
False,NA,True"""
|
| 183 |
+
parser = all_parsers
|
| 184 |
+
result = parser.read_csv(StringIO(data))
|
| 185 |
+
expected = pd.DataFrame(
|
| 186 |
+
{
|
| 187 |
+
"A": np.array([True, np.nan, False], dtype=object),
|
| 188 |
+
"B": np.array([False, True, np.nan], dtype=object),
|
| 189 |
+
"C": [True, False, True],
|
| 190 |
+
}
|
| 191 |
+
)
|
| 192 |
+
if parser.engine == "pyarrow":
|
| 193 |
+
expected.loc[1, "A"] = None
|
| 194 |
+
expected.loc[2, "B"] = None
|
| 195 |
+
tm.assert_frame_equal(result, expected)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def test_na_value_dict(all_parsers):
|
| 199 |
+
data = """A,B,C
|
| 200 |
+
foo,bar,NA
|
| 201 |
+
bar,foo,foo
|
| 202 |
+
foo,bar,NA
|
| 203 |
+
bar,foo,foo"""
|
| 204 |
+
parser = all_parsers
|
| 205 |
+
|
| 206 |
+
if parser.engine == "pyarrow":
|
| 207 |
+
msg = "pyarrow engine doesn't support passing a dict for na_values"
|
| 208 |
+
with pytest.raises(ValueError, match=msg):
|
| 209 |
+
parser.read_csv(StringIO(data), na_values={"A": ["foo"], "B": ["bar"]})
|
| 210 |
+
return
|
| 211 |
+
|
| 212 |
+
df = parser.read_csv(StringIO(data), na_values={"A": ["foo"], "B": ["bar"]})
|
| 213 |
+
expected = pd.DataFrame(
|
| 214 |
+
{
|
| 215 |
+
"A": [np.nan, "bar", np.nan, "bar"],
|
| 216 |
+
"B": [np.nan, "foo", np.nan, "foo"],
|
| 217 |
+
"C": [np.nan, "foo", np.nan, "foo"],
|
| 218 |
+
}
|
| 219 |
+
)
|
| 220 |
+
tm.assert_frame_equal(df, expected)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@pytest.mark.parametrize(
|
| 224 |
+
"index_col,expected",
|
| 225 |
+
[
|
| 226 |
+
(
|
| 227 |
+
[0],
|
| 228 |
+
pd.DataFrame(
|
| 229 |
+
{"b": [np.nan], "c": [1], "d": [5]}, index=pd.Index([0], name="a")
|
| 230 |
+
),
|
| 231 |
+
),
|
| 232 |
+
(
|
| 233 |
+
[0, 2],
|
| 234 |
+
pd.DataFrame(
|
| 235 |
+
{"b": [np.nan], "d": [5]},
|
| 236 |
+
index=pd.MultiIndex.from_tuples([(0, 1)], names=["a", "c"]),
|
| 237 |
+
),
|
| 238 |
+
),
|
| 239 |
+
(
|
| 240 |
+
["a", "c"],
|
| 241 |
+
pd.DataFrame(
|
| 242 |
+
{"b": [np.nan], "d": [5]},
|
| 243 |
+
index=pd.MultiIndex.from_tuples([(0, 1)], names=["a", "c"]),
|
| 244 |
+
),
|
| 245 |
+
),
|
| 246 |
+
],
|
| 247 |
+
)
|
| 248 |
+
def test_na_value_dict_multi_index(all_parsers, index_col, expected):
|
| 249 |
+
data = """\
|
| 250 |
+
a,b,c,d
|
| 251 |
+
0,NA,1,5
|
| 252 |
+
"""
|
| 253 |
+
parser = all_parsers
|
| 254 |
+
result = parser.read_csv(StringIO(data), na_values=set(), index_col=index_col)
|
| 255 |
+
tm.assert_frame_equal(result, expected)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@pytest.mark.parametrize(
|
| 259 |
+
"kwargs,expected",
|
| 260 |
+
[
|
| 261 |
+
(
|
| 262 |
+
{},
|
| 263 |
+
{
|
| 264 |
+
"A": ["a", "b", np.nan, "d", "e", np.nan, "g"],
|
| 265 |
+
"B": [1, 2, 3, 4, 5, 6, 7],
|
| 266 |
+
"C": ["one", "two", "three", np.nan, "five", np.nan, "seven"],
|
| 267 |
+
},
|
| 268 |
+
),
|
| 269 |
+
(
|
| 270 |
+
{"na_values": {"A": [], "C": []}, "keep_default_na": False},
|
| 271 |
+
{
|
| 272 |
+
"A": ["a", "b", "", "d", "e", "nan", "g"],
|
| 273 |
+
"B": [1, 2, 3, 4, 5, 6, 7],
|
| 274 |
+
"C": ["one", "two", "three", "nan", "five", "", "seven"],
|
| 275 |
+
},
|
| 276 |
+
),
|
| 277 |
+
(
|
| 278 |
+
{"na_values": ["a"], "keep_default_na": False},
|
| 279 |
+
{
|
| 280 |
+
"A": [np.nan, "b", "", "d", "e", "nan", "g"],
|
| 281 |
+
"B": [1, 2, 3, 4, 5, 6, 7],
|
| 282 |
+
"C": ["one", "two", "three", "nan", "five", "", "seven"],
|
| 283 |
+
},
|
| 284 |
+
),
|
| 285 |
+
(
|
| 286 |
+
{"na_values": {"A": [], "C": []}},
|
| 287 |
+
{
|
| 288 |
+
"A": ["a", "b", np.nan, "d", "e", np.nan, "g"],
|
| 289 |
+
"B": [1, 2, 3, 4, 5, 6, 7],
|
| 290 |
+
"C": ["one", "two", "three", np.nan, "five", np.nan, "seven"],
|
| 291 |
+
},
|
| 292 |
+
),
|
| 293 |
+
],
|
| 294 |
+
)
|
| 295 |
+
def test_na_values_keep_default(
|
| 296 |
+
all_parsers, kwargs, expected, request, using_infer_string
|
| 297 |
+
):
|
| 298 |
+
data = """\
|
| 299 |
+
A,B,C
|
| 300 |
+
a,1,one
|
| 301 |
+
b,2,two
|
| 302 |
+
,3,three
|
| 303 |
+
d,4,nan
|
| 304 |
+
e,5,five
|
| 305 |
+
nan,6,
|
| 306 |
+
g,7,seven
|
| 307 |
+
"""
|
| 308 |
+
parser = all_parsers
|
| 309 |
+
if parser.engine == "pyarrow":
|
| 310 |
+
if "na_values" in kwargs and isinstance(kwargs["na_values"], dict):
|
| 311 |
+
msg = "The pyarrow engine doesn't support passing a dict for na_values"
|
| 312 |
+
with pytest.raises(ValueError, match=msg):
|
| 313 |
+
parser.read_csv(StringIO(data), **kwargs)
|
| 314 |
+
return
|
| 315 |
+
if not using_infer_string or "na_values" in kwargs:
|
| 316 |
+
mark = pytest.mark.xfail()
|
| 317 |
+
request.applymarker(mark)
|
| 318 |
+
|
| 319 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 320 |
+
expected = pd.DataFrame(expected)
|
| 321 |
+
tm.assert_frame_equal(result, expected)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def test_no_na_values_no_keep_default(all_parsers):
|
| 325 |
+
# see gh-4318: passing na_values=None and
|
| 326 |
+
# keep_default_na=False yields 'None" as a na_value
|
| 327 |
+
data = """\
|
| 328 |
+
A,B,C
|
| 329 |
+
a,1,None
|
| 330 |
+
b,2,two
|
| 331 |
+
,3,None
|
| 332 |
+
d,4,nan
|
| 333 |
+
e,5,five
|
| 334 |
+
nan,6,
|
| 335 |
+
g,7,seven
|
| 336 |
+
"""
|
| 337 |
+
parser = all_parsers
|
| 338 |
+
result = parser.read_csv(StringIO(data), keep_default_na=False)
|
| 339 |
+
|
| 340 |
+
expected = pd.DataFrame(
|
| 341 |
+
{
|
| 342 |
+
"A": ["a", "b", "", "d", "e", "nan", "g"],
|
| 343 |
+
"B": [1, 2, 3, 4, 5, 6, 7],
|
| 344 |
+
"C": ["None", "two", "None", "nan", "five", "", "seven"],
|
| 345 |
+
}
|
| 346 |
+
)
|
| 347 |
+
tm.assert_frame_equal(result, expected)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def test_no_keep_default_na_dict_na_values(all_parsers):
|
| 351 |
+
# see gh-19227
|
| 352 |
+
data = "a,b\n,2"
|
| 353 |
+
parser = all_parsers
|
| 354 |
+
|
| 355 |
+
if parser.engine == "pyarrow":
|
| 356 |
+
msg = "The pyarrow engine doesn't support passing a dict for na_values"
|
| 357 |
+
with pytest.raises(ValueError, match=msg):
|
| 358 |
+
parser.read_csv(
|
| 359 |
+
StringIO(data), na_values={"b": ["2"]}, keep_default_na=False
|
| 360 |
+
)
|
| 361 |
+
return
|
| 362 |
+
|
| 363 |
+
result = parser.read_csv(
|
| 364 |
+
StringIO(data), na_values={"b": ["2"]}, keep_default_na=False
|
| 365 |
+
)
|
| 366 |
+
expected = pd.DataFrame({"a": [""], "b": [np.nan]})
|
| 367 |
+
tm.assert_frame_equal(result, expected)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def test_no_keep_default_na_dict_na_scalar_values(all_parsers):
|
| 371 |
+
# see gh-19227
|
| 372 |
+
#
|
| 373 |
+
# Scalar values shouldn't cause the parsing to crash or fail.
|
| 374 |
+
data = "a,b\n1,2"
|
| 375 |
+
parser = all_parsers
|
| 376 |
+
|
| 377 |
+
if parser.engine == "pyarrow":
|
| 378 |
+
msg = "The pyarrow engine doesn't support passing a dict for na_values"
|
| 379 |
+
with pytest.raises(ValueError, match=msg):
|
| 380 |
+
parser.read_csv(StringIO(data), na_values={"b": 2}, keep_default_na=False)
|
| 381 |
+
return
|
| 382 |
+
|
| 383 |
+
df = parser.read_csv(StringIO(data), na_values={"b": 2}, keep_default_na=False)
|
| 384 |
+
expected = pd.DataFrame({"a": [1], "b": [np.nan]})
|
| 385 |
+
tm.assert_frame_equal(df, expected)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
@pytest.mark.parametrize("col_zero_na_values", [113125, "113125"])
|
| 389 |
+
def test_no_keep_default_na_dict_na_values_diff_reprs(all_parsers, col_zero_na_values):
|
| 390 |
+
# see gh-19227
|
| 391 |
+
data = """\
|
| 392 |
+
113125,"blah","/blaha",kjsdkj,412.166,225.874,214.008
|
| 393 |
+
729639,"qwer","",asdfkj,466.681,,252.373
|
| 394 |
+
"""
|
| 395 |
+
parser = all_parsers
|
| 396 |
+
expected = pd.DataFrame(
|
| 397 |
+
{
|
| 398 |
+
0: [np.nan, 729639.0],
|
| 399 |
+
1: [np.nan, "qwer"],
|
| 400 |
+
2: ["/blaha", np.nan],
|
| 401 |
+
3: ["kjsdkj", "asdfkj"],
|
| 402 |
+
4: [412.166, 466.681],
|
| 403 |
+
5: ["225.874", ""],
|
| 404 |
+
6: [np.nan, 252.373],
|
| 405 |
+
}
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
if parser.engine == "pyarrow":
|
| 409 |
+
msg = "The pyarrow engine doesn't support passing a dict for na_values"
|
| 410 |
+
with pytest.raises(ValueError, match=msg):
|
| 411 |
+
parser.read_csv(
|
| 412 |
+
StringIO(data),
|
| 413 |
+
header=None,
|
| 414 |
+
keep_default_na=False,
|
| 415 |
+
na_values={2: "", 6: "214.008", 1: "blah", 0: col_zero_na_values},
|
| 416 |
+
)
|
| 417 |
+
return
|
| 418 |
+
|
| 419 |
+
result = parser.read_csv(
|
| 420 |
+
StringIO(data),
|
| 421 |
+
header=None,
|
| 422 |
+
keep_default_na=False,
|
| 423 |
+
na_values={2: "", 6: "214.008", 1: "blah", 0: col_zero_na_values},
|
| 424 |
+
)
|
| 425 |
+
tm.assert_frame_equal(result, expected)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
@pytest.mark.parametrize(
|
| 429 |
+
"na_filter,row_data",
|
| 430 |
+
[
|
| 431 |
+
(True, [[1, "A"], [np.nan, np.nan], [3, "C"]]),
|
| 432 |
+
(False, [["1", "A"], ["nan", "B"], ["3", "C"]]),
|
| 433 |
+
],
|
| 434 |
+
)
|
| 435 |
+
def test_na_values_na_filter_override(
|
| 436 |
+
request, all_parsers, na_filter, row_data, using_infer_string
|
| 437 |
+
):
|
| 438 |
+
parser = all_parsers
|
| 439 |
+
data = """\
|
| 440 |
+
A,B
|
| 441 |
+
1,A
|
| 442 |
+
nan,B
|
| 443 |
+
3,C
|
| 444 |
+
"""
|
| 445 |
+
if parser.engine == "pyarrow":
|
| 446 |
+
if na_filter is False:
|
| 447 |
+
msg = "The 'na_filter' option is not supported with the 'pyarrow' engine"
|
| 448 |
+
with pytest.raises(ValueError, match=msg):
|
| 449 |
+
parser.read_csv(StringIO(data), na_values=["B"], na_filter=na_filter)
|
| 450 |
+
return
|
| 451 |
+
if not using_infer_string:
|
| 452 |
+
# mismatched dtypes, FutureWarning
|
| 453 |
+
mark = pytest.mark.xfail(reason="pyarrow doesn't support this.")
|
| 454 |
+
request.applymarker(mark)
|
| 455 |
+
|
| 456 |
+
result = parser.read_csv(StringIO(data), na_values=["B"], na_filter=na_filter)
|
| 457 |
+
|
| 458 |
+
expected = pd.DataFrame(row_data, columns=["A", "B"])
|
| 459 |
+
tm.assert_frame_equal(result, expected)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
@skip_pyarrow # CSV parse error: Expected 8 columns, got 5:
|
| 463 |
+
def test_na_trailing_columns(all_parsers):
|
| 464 |
+
parser = all_parsers
|
| 465 |
+
data = """Date,Currency,Symbol,Type,Units,UnitPrice,Cost,Tax
|
| 466 |
+
2012-03-14,USD,AAPL,BUY,1000
|
| 467 |
+
2012-05-12,USD,SBUX,SELL,500"""
|
| 468 |
+
|
| 469 |
+
# Trailing columns should be all NaN.
|
| 470 |
+
result = parser.read_csv(StringIO(data))
|
| 471 |
+
expected = pd.DataFrame(
|
| 472 |
+
[
|
| 473 |
+
["2012-03-14", "USD", "AAPL", "BUY", 1000, np.nan, np.nan, np.nan],
|
| 474 |
+
["2012-05-12", "USD", "SBUX", "SELL", 500, np.nan, np.nan, np.nan],
|
| 475 |
+
],
|
| 476 |
+
columns=[
|
| 477 |
+
"Date",
|
| 478 |
+
"Currency",
|
| 479 |
+
"Symbol",
|
| 480 |
+
"Type",
|
| 481 |
+
"Units",
|
| 482 |
+
"UnitPrice",
|
| 483 |
+
"Cost",
|
| 484 |
+
"Tax",
|
| 485 |
+
],
|
| 486 |
+
)
|
| 487 |
+
tm.assert_frame_equal(result, expected)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
@pytest.mark.parametrize(
|
| 491 |
+
"na_values,row_data",
|
| 492 |
+
[
|
| 493 |
+
(1, [[np.nan, 2.0], [2.0, np.nan]]),
|
| 494 |
+
({"a": 2, "b": 1}, [[1.0, 2.0], [np.nan, np.nan]]),
|
| 495 |
+
],
|
| 496 |
+
)
|
| 497 |
+
def test_na_values_scalar(all_parsers, na_values, row_data):
|
| 498 |
+
# see gh-12224
|
| 499 |
+
parser = all_parsers
|
| 500 |
+
names = ["a", "b"]
|
| 501 |
+
data = "1,2\n2,1"
|
| 502 |
+
|
| 503 |
+
if parser.engine == "pyarrow" and isinstance(na_values, dict):
|
| 504 |
+
msg = "The pyarrow engine doesn't support passing a dict for na_values"
|
| 505 |
+
with pytest.raises(ValueError, match=msg):
|
| 506 |
+
parser.read_csv(StringIO(data), names=names, na_values=na_values)
|
| 507 |
+
return
|
| 508 |
+
elif parser.engine == "pyarrow":
|
| 509 |
+
msg = "The 'pyarrow' engine requires all na_values to be strings"
|
| 510 |
+
with pytest.raises(TypeError, match=msg):
|
| 511 |
+
parser.read_csv(StringIO(data), names=names, na_values=na_values)
|
| 512 |
+
return
|
| 513 |
+
|
| 514 |
+
result = parser.read_csv(StringIO(data), names=names, na_values=na_values)
|
| 515 |
+
expected = pd.DataFrame(row_data, columns=names)
|
| 516 |
+
tm.assert_frame_equal(result, expected)
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def test_na_values_dict_aliasing(all_parsers):
|
| 520 |
+
parser = all_parsers
|
| 521 |
+
na_values = {"a": 2, "b": 1}
|
| 522 |
+
na_values_copy = na_values.copy()
|
| 523 |
+
|
| 524 |
+
names = ["a", "b"]
|
| 525 |
+
data = "1,2\n2,1"
|
| 526 |
+
|
| 527 |
+
expected = pd.DataFrame([[1.0, 2.0], [np.nan, np.nan]], columns=names)
|
| 528 |
+
|
| 529 |
+
if parser.engine == "pyarrow":
|
| 530 |
+
msg = "The pyarrow engine doesn't support passing a dict for na_values"
|
| 531 |
+
with pytest.raises(ValueError, match=msg):
|
| 532 |
+
parser.read_csv(StringIO(data), names=names, na_values=na_values)
|
| 533 |
+
return
|
| 534 |
+
|
| 535 |
+
result = parser.read_csv(StringIO(data), names=names, na_values=na_values)
|
| 536 |
+
|
| 537 |
+
tm.assert_frame_equal(result, expected)
|
| 538 |
+
tm.assert_dict_equal(na_values, na_values_copy)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def test_na_values_dict_null_column_name(all_parsers):
|
| 542 |
+
# see gh-57547
|
| 543 |
+
parser = all_parsers
|
| 544 |
+
data = ",x,y\n\nMA,1,2\nNA,2,1\nOA,,3"
|
| 545 |
+
names = [None, "x", "y"]
|
| 546 |
+
na_values = dict.fromkeys(names, STR_NA_VALUES)
|
| 547 |
+
dtype = {None: "object", "x": "float64", "y": "float64"}
|
| 548 |
+
|
| 549 |
+
if parser.engine == "pyarrow":
|
| 550 |
+
msg = "The pyarrow engine doesn't support passing a dict for na_values"
|
| 551 |
+
with pytest.raises(ValueError, match=msg):
|
| 552 |
+
parser.read_csv(
|
| 553 |
+
StringIO(data),
|
| 554 |
+
index_col=0,
|
| 555 |
+
header=0,
|
| 556 |
+
dtype=dtype,
|
| 557 |
+
names=names,
|
| 558 |
+
na_values=na_values,
|
| 559 |
+
keep_default_na=False,
|
| 560 |
+
)
|
| 561 |
+
return
|
| 562 |
+
|
| 563 |
+
expected = pd.DataFrame(
|
| 564 |
+
{"x": [1.0, 2.0, np.nan], "y": [2.0, 1.0, 3.0]},
|
| 565 |
+
index=pd.Index(["MA", "NA", "OA"], dtype=object),
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
result = parser.read_csv(
|
| 569 |
+
StringIO(data),
|
| 570 |
+
index_col=0,
|
| 571 |
+
header=0,
|
| 572 |
+
dtype=dtype,
|
| 573 |
+
names=names,
|
| 574 |
+
na_values=na_values,
|
| 575 |
+
keep_default_na=False,
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
tm.assert_frame_equal(result, expected)
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def test_na_values_dict_col_index(all_parsers):
|
| 582 |
+
# see gh-14203
|
| 583 |
+
data = "a\nfoo\n1"
|
| 584 |
+
parser = all_parsers
|
| 585 |
+
na_values = {0: "foo"}
|
| 586 |
+
|
| 587 |
+
if parser.engine == "pyarrow":
|
| 588 |
+
msg = "The pyarrow engine doesn't support passing a dict for na_values"
|
| 589 |
+
with pytest.raises(ValueError, match=msg):
|
| 590 |
+
parser.read_csv(StringIO(data), na_values=na_values)
|
| 591 |
+
return
|
| 592 |
+
|
| 593 |
+
result = parser.read_csv(StringIO(data), na_values=na_values)
|
| 594 |
+
expected = pd.DataFrame({"a": [np.nan, 1]})
|
| 595 |
+
tm.assert_frame_equal(result, expected)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
@pytest.mark.parametrize(
|
| 599 |
+
"data,kwargs,expected",
|
| 600 |
+
[
|
| 601 |
+
(
|
| 602 |
+
str(2**63) + "\n" + str(2**63 + 1),
|
| 603 |
+
{"na_values": [2**63]},
|
| 604 |
+
[str(2**63), str(2**63 + 1)],
|
| 605 |
+
),
|
| 606 |
+
(str(2**63) + ",1" + "\n,2", {}, [[str(2**63), 1], ["", 2]]),
|
| 607 |
+
(str(2**63) + "\n1", {"na_values": [2**63]}, [np.nan, 1]),
|
| 608 |
+
],
|
| 609 |
+
)
|
| 610 |
+
def test_na_values_uint64(all_parsers, data, kwargs, expected, request):
|
| 611 |
+
# see gh-14983
|
| 612 |
+
parser = all_parsers
|
| 613 |
+
|
| 614 |
+
if parser.engine == "pyarrow" and "na_values" in kwargs:
|
| 615 |
+
msg = "The 'pyarrow' engine requires all na_values to be strings"
|
| 616 |
+
with pytest.raises(TypeError, match=msg):
|
| 617 |
+
parser.read_csv(StringIO(data), header=None, **kwargs)
|
| 618 |
+
return
|
| 619 |
+
elif parser.engine == "pyarrow":
|
| 620 |
+
mark = pytest.mark.xfail(reason="Returns float64 instead of object")
|
| 621 |
+
request.applymarker(mark)
|
| 622 |
+
|
| 623 |
+
result = parser.read_csv(StringIO(data), header=None, **kwargs)
|
| 624 |
+
expected = pd.DataFrame(expected)
|
| 625 |
+
tm.assert_frame_equal(result, expected)
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def test_empty_na_values_no_default_with_index(all_parsers):
|
| 629 |
+
# see gh-15835
|
| 630 |
+
data = "a,1\nb,2"
|
| 631 |
+
parser = all_parsers
|
| 632 |
+
expected = pd.DataFrame({"1": [2]}, index=pd.Index(["b"], name="a"))
|
| 633 |
+
|
| 634 |
+
result = parser.read_csv(StringIO(data), index_col=0, keep_default_na=False)
|
| 635 |
+
tm.assert_frame_equal(result, expected)
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
@pytest.mark.parametrize(
|
| 639 |
+
"na_filter,index_data", [(False, ["", "5"]), (True, [np.nan, 5.0])]
|
| 640 |
+
)
|
| 641 |
+
def test_no_na_filter_on_index(all_parsers, na_filter, index_data):
|
| 642 |
+
# see gh-5239
|
| 643 |
+
#
|
| 644 |
+
# Don't parse NA-values in index unless na_filter=True
|
| 645 |
+
parser = all_parsers
|
| 646 |
+
data = "a,b,c\n1,,3\n4,5,6"
|
| 647 |
+
|
| 648 |
+
if parser.engine == "pyarrow" and na_filter is False:
|
| 649 |
+
msg = "The 'na_filter' option is not supported with the 'pyarrow' engine"
|
| 650 |
+
with pytest.raises(ValueError, match=msg):
|
| 651 |
+
parser.read_csv(StringIO(data), index_col=[1], na_filter=na_filter)
|
| 652 |
+
return
|
| 653 |
+
|
| 654 |
+
expected = pd.DataFrame(
|
| 655 |
+
{"a": [1, 4], "c": [3, 6]}, index=pd.Index(index_data, name="b")
|
| 656 |
+
)
|
| 657 |
+
result = parser.read_csv(StringIO(data), index_col=[1], na_filter=na_filter)
|
| 658 |
+
tm.assert_frame_equal(result, expected)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def test_inf_na_values_with_int_index(all_parsers):
|
| 662 |
+
# see gh-17128
|
| 663 |
+
parser = all_parsers
|
| 664 |
+
data = "idx,col1,col2\n1,3,4\n2,inf,-inf"
|
| 665 |
+
|
| 666 |
+
# Don't fail with OverflowError with inf's and integer index column.
|
| 667 |
+
out = parser.read_csv(StringIO(data), index_col=[0], na_values=["inf", "-inf"])
|
| 668 |
+
expected = pd.DataFrame(
|
| 669 |
+
{"col1": [3, np.nan], "col2": [4, np.nan]}, index=pd.Index([1, 2], name="idx")
|
| 670 |
+
)
|
| 671 |
+
tm.assert_frame_equal(out, expected)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
@pytest.mark.parametrize("na_filter", [True, False])
|
| 675 |
+
def test_na_values_with_dtype_str_and_na_filter(
|
| 676 |
+
all_parsers, na_filter, using_infer_string, request
|
| 677 |
+
):
|
| 678 |
+
# see gh-20377
|
| 679 |
+
parser = all_parsers
|
| 680 |
+
data = "a,b,c\n1,,3\n4,5,6"
|
| 681 |
+
|
| 682 |
+
if parser.engine == "pyarrow":
|
| 683 |
+
if na_filter is False:
|
| 684 |
+
msg = "The 'na_filter' option is not supported with the 'pyarrow' engine"
|
| 685 |
+
with pytest.raises(ValueError, match=msg):
|
| 686 |
+
parser.read_csv(StringIO(data), na_filter=na_filter, dtype=str)
|
| 687 |
+
return
|
| 688 |
+
if not using_infer_string:
|
| 689 |
+
mark = pytest.mark.xfail(reason="mismatched shape")
|
| 690 |
+
request.applymarker(mark)
|
| 691 |
+
|
| 692 |
+
# na_filter=True --> missing value becomes NaN.
|
| 693 |
+
# na_filter=False --> missing value remains empty string.
|
| 694 |
+
empty = np.nan if na_filter else ""
|
| 695 |
+
expected = pd.DataFrame({"a": ["1", "4"], "b": [empty, "5"], "c": ["3", "6"]})
|
| 696 |
+
|
| 697 |
+
result = parser.read_csv(StringIO(data), na_filter=na_filter, dtype=str)
|
| 698 |
+
tm.assert_frame_equal(result, expected)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
@xfail_pyarrow # mismatched exception message
|
| 702 |
+
@pytest.mark.parametrize(
|
| 703 |
+
"data, na_values",
|
| 704 |
+
[
|
| 705 |
+
("false,1\n,1\ntrue", None),
|
| 706 |
+
("false,1\nnull,1\ntrue", None),
|
| 707 |
+
("false,1\nnan,1\ntrue", None),
|
| 708 |
+
("false,1\nfoo,1\ntrue", "foo"),
|
| 709 |
+
("false,1\nfoo,1\ntrue", ["foo"]),
|
| 710 |
+
("false,1\nfoo,1\ntrue", {"a": "foo"}),
|
| 711 |
+
],
|
| 712 |
+
)
|
| 713 |
+
def test_cast_NA_to_bool_raises_error(all_parsers, data, na_values):
|
| 714 |
+
parser = all_parsers
|
| 715 |
+
msg = "|".join(
|
| 716 |
+
[
|
| 717 |
+
"Bool column has NA values in column [0a]",
|
| 718 |
+
"cannot safely convert passed user dtype of "
|
| 719 |
+
"bool for object dtyped data in column 0",
|
| 720 |
+
]
|
| 721 |
+
)
|
| 722 |
+
|
| 723 |
+
with pytest.raises(ValueError, match=msg):
|
| 724 |
+
parser.read_csv(
|
| 725 |
+
StringIO(data),
|
| 726 |
+
header=None,
|
| 727 |
+
names=["a", "b"],
|
| 728 |
+
dtype={"a": "bool"},
|
| 729 |
+
na_values=na_values,
|
| 730 |
+
)
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
# TODO: this test isn't about the na_values keyword, it is about the empty entries
|
| 734 |
+
# being returned with NaN entries, whereas the pyarrow engine returns "nan"
|
| 735 |
+
@xfail_pyarrow # mismatched shapes
|
| 736 |
+
def test_str_nan_dropped(all_parsers):
|
| 737 |
+
# see gh-21131
|
| 738 |
+
parser = all_parsers
|
| 739 |
+
|
| 740 |
+
data = """File: small.csv,,
|
| 741 |
+
10010010233,0123,654
|
| 742 |
+
foo,,bar
|
| 743 |
+
01001000155,4530,898"""
|
| 744 |
+
|
| 745 |
+
result = parser.read_csv(
|
| 746 |
+
StringIO(data),
|
| 747 |
+
header=None,
|
| 748 |
+
names=["col1", "col2", "col3"],
|
| 749 |
+
dtype={"col1": str, "col2": str, "col3": str},
|
| 750 |
+
).dropna()
|
| 751 |
+
|
| 752 |
+
expected = pd.DataFrame(
|
| 753 |
+
{
|
| 754 |
+
"col1": ["10010010233", "01001000155"],
|
| 755 |
+
"col2": ["0123", "4530"],
|
| 756 |
+
"col3": ["654", "898"],
|
| 757 |
+
},
|
| 758 |
+
index=[1, 3],
|
| 759 |
+
)
|
| 760 |
+
|
| 761 |
+
tm.assert_frame_equal(result, expected)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def test_nan_multi_index(all_parsers):
|
| 765 |
+
# GH 42446
|
| 766 |
+
parser = all_parsers
|
| 767 |
+
data = "A,B,B\nX,Y,Z\n1,2,inf"
|
| 768 |
+
|
| 769 |
+
if parser.engine == "pyarrow":
|
| 770 |
+
msg = "The pyarrow engine doesn't support passing a dict for na_values"
|
| 771 |
+
with pytest.raises(ValueError, match=msg):
|
| 772 |
+
parser.read_csv(
|
| 773 |
+
StringIO(data), header=list(range(2)), na_values={("B", "Z"): "inf"}
|
| 774 |
+
)
|
| 775 |
+
return
|
| 776 |
+
|
| 777 |
+
result = parser.read_csv(
|
| 778 |
+
StringIO(data), header=list(range(2)), na_values={("B", "Z"): "inf"}
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
expected = pd.DataFrame(
|
| 782 |
+
{
|
| 783 |
+
("A", "X"): [1],
|
| 784 |
+
("B", "Y"): [2],
|
| 785 |
+
("B", "Z"): [np.nan],
|
| 786 |
+
}
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
tm.assert_frame_equal(result, expected)
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
@xfail_pyarrow # Failed: DID NOT RAISE <class 'ValueError'>; it casts the NaN to False
|
| 793 |
+
def test_bool_and_nan_to_bool(all_parsers):
|
| 794 |
+
# GH#42808
|
| 795 |
+
parser = all_parsers
|
| 796 |
+
data = """0
|
| 797 |
+
NaN
|
| 798 |
+
True
|
| 799 |
+
False
|
| 800 |
+
"""
|
| 801 |
+
with pytest.raises(ValueError, match="NA values"):
|
| 802 |
+
parser.read_csv(StringIO(data), dtype="bool")
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
def test_bool_and_nan_to_int(all_parsers):
|
| 806 |
+
# GH#42808
|
| 807 |
+
parser = all_parsers
|
| 808 |
+
data = """0
|
| 809 |
+
NaN
|
| 810 |
+
True
|
| 811 |
+
False
|
| 812 |
+
"""
|
| 813 |
+
msg = (
|
| 814 |
+
"cannot safely convert passed user dtype of int(64|32) for "
|
| 815 |
+
"<class 'numpy.bool_?'> dtyped data in column 0 due to NA values"
|
| 816 |
+
)
|
| 817 |
+
if parser.engine == "python":
|
| 818 |
+
msg = "Unable to convert column 0 to type int(64|32)"
|
| 819 |
+
elif parser.engine == "pyarrow":
|
| 820 |
+
msg = (
|
| 821 |
+
r"int\(\) argument must be a string, a bytes-like object or a "
|
| 822 |
+
"real number, not 'NoneType"
|
| 823 |
+
)
|
| 824 |
+
with pytest.raises(ValueError, match=msg):
|
| 825 |
+
parser.read_csv(StringIO(data), dtype="int")
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
def test_bool_and_nan_to_float(all_parsers):
|
| 829 |
+
# GH#42808
|
| 830 |
+
parser = all_parsers
|
| 831 |
+
data = """0
|
| 832 |
+
NaN
|
| 833 |
+
True
|
| 834 |
+
False
|
| 835 |
+
"""
|
| 836 |
+
result = parser.read_csv(StringIO(data), dtype="float")
|
| 837 |
+
expected = pd.DataFrame.from_dict({"0": [np.nan, 1.0, 0.0]})
|
| 838 |
+
tm.assert_frame_equal(result, expected)
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
@pytest.mark.parametrize(
|
| 842 |
+
"na_values",
|
| 843 |
+
[[-99.0, -99], [-99, -99.0]],
|
| 844 |
+
)
|
| 845 |
+
def test_na_values_dict_without_dtype(all_parsers, na_values):
|
| 846 |
+
parser = all_parsers
|
| 847 |
+
data = """A
|
| 848 |
+
-99
|
| 849 |
+
-99
|
| 850 |
+
-99.0
|
| 851 |
+
-99.0"""
|
| 852 |
+
|
| 853 |
+
if parser.engine == "pyarrow":
|
| 854 |
+
msg = "The 'pyarrow' engine requires all na_values to be strings"
|
| 855 |
+
with pytest.raises(TypeError, match=msg):
|
| 856 |
+
parser.read_csv(StringIO(data), na_values=na_values)
|
| 857 |
+
return
|
| 858 |
+
|
| 859 |
+
result = parser.read_csv(StringIO(data), na_values=na_values)
|
| 860 |
+
expected = pd.DataFrame({"A": [np.nan, np.nan, np.nan, np.nan]})
|
| 861 |
+
tm.assert_frame_equal(result, expected)
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
def test_int64_min_with_na_upcasts(all_parsers):
|
| 865 |
+
# GH#66855 a column mixing int64 min with a genuine NA upcasts to float,
|
| 866 |
+
# and only the NA row becomes NaN
|
| 867 |
+
parser = all_parsers
|
| 868 |
+
result = parser.read_csv(
|
| 869 |
+
StringIO("A\n-9223372036854775808\n\n1\n"), skip_blank_lines=False
|
| 870 |
+
)
|
| 871 |
+
expected = pd.DataFrame({"A": [float(-(2**63)), np.nan, 1.0]})
|
| 872 |
+
tm.assert_frame_equal(result, expected)
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
@pytest.mark.parametrize("na_filter", [True, False])
|
| 876 |
+
def test_int64_min_not_read_as_na_nullable(all_parsers, na_filter):
|
| 877 |
+
# GH#66855
|
| 878 |
+
parser = all_parsers
|
| 879 |
+
if parser.engine == "pyarrow" and not na_filter:
|
| 880 |
+
pytest.skip("pyarrow engine does not support na_filter=False")
|
| 881 |
+
result = parser.read_csv(
|
| 882 |
+
StringIO("A\n-9223372036854775808\n1\n"),
|
| 883 |
+
na_filter=na_filter,
|
| 884 |
+
dtype_backend="numpy_nullable",
|
| 885 |
+
)
|
| 886 |
+
expected = pd.DataFrame({"A": [-9223372036854775808, 1]}, dtype="Int64")
|
| 887 |
+
tm.assert_frame_equal(result, expected)
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
@xfail_pyarrow # the pyarrow engine reads uint64 max as a float
|
| 891 |
+
def test_uint64_max_not_read_as_na_nullable(all_parsers):
|
| 892 |
+
# GH#66855 the uint64 NA sentinel is uint64 max
|
| 893 |
+
parser = all_parsers
|
| 894 |
+
result = parser.read_csv(
|
| 895 |
+
StringIO("A\n18446744073709551615\n1\n"), dtype_backend="numpy_nullable"
|
| 896 |
+
)
|
| 897 |
+
expected = pd.DataFrame({"A": [18446744073709551615, 1]}, dtype="UInt64")
|
| 898 |
+
tm.assert_frame_equal(result, expected)
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
def test_int64_min_with_na_explicit_nullable_dtype(all_parsers):
|
| 902 |
+
# GH#66855 an explicitly requested nullable dtype parses through
|
| 903 |
+
# _parse_numeric_natural, which used to rescan the tokens to rebuild the NA
|
| 904 |
+
# mask; the mask now comes from the parse itself
|
| 905 |
+
parser = all_parsers
|
| 906 |
+
result = parser.read_csv(
|
| 907 |
+
StringIO("A\n-9223372036854775808\nNA\n1\n"), dtype="Int64"
|
| 908 |
+
)
|
| 909 |
+
expected = pd.DataFrame({"A": [-9223372036854775808, None, 1]}, dtype="Int64")
|
| 910 |
+
tm.assert_frame_equal(result, expected)
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
@skip_pyarrow # object-dtype NA reads back as None, not NaN
|
| 914 |
+
@pytest.mark.parametrize(
|
| 915 |
+
"na_values, data, expected_values",
|
| 916 |
+
[
|
| 917 |
+
# share the first byte and length with a default NA spelling but not
|
| 918 |
+
# the second byte: "-nan" vs "-1.5", "1.#IND" vs "1.2345"
|
| 919 |
+
(None, "-1.5\n-nan\n1.2345\n1.#IND\n", [-1.5, np.nan, 1.2345, np.nan]),
|
| 920 |
+
# share the first two bytes and the length with an NA spelling
|
| 921 |
+
(["-1.#IND"], "-1.2345\n-1.#IND\n", [-1.2345, np.nan]),
|
| 922 |
+
# single-byte NA spelling
|
| 923 |
+
(["x"], "x\nxx\n1\n", [np.nan, "xx", "1"]),
|
| 924 |
+
# spellings at and beyond the 63-byte length bucket
|
| 925 |
+
(
|
| 926 |
+
["a" * 63, "b" * 70],
|
| 927 |
+
"\n".join(["a" * 63, "a" * 64, "b" * 70, "b" * 63, "c" * 70]) + "\n",
|
| 928 |
+
[np.nan, "a" * 64, np.nan, "b" * 63, "c" * 70],
|
| 929 |
+
),
|
| 930 |
+
],
|
| 931 |
+
)
|
| 932 |
+
def test_na_values_prefilter_edge_cases(all_parsers, na_values, data, expected_values):
|
| 933 |
+
# the C engine screens tokens against na_values by first byte and length,
|
| 934 |
+
# then compares the packed first 8 bytes; each case shares part of that
|
| 935 |
+
# signature with a spelling without being one
|
| 936 |
+
parser = all_parsers
|
| 937 |
+
result = parser.read_csv(StringIO("col\n" + data), na_values=na_values)
|
| 938 |
+
expected = pd.DataFrame({"col": expected_values})
|
| 939 |
+
tm.assert_frame_equal(result, expected)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_network.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests parsers ability to read and parse non-local files
|
| 3 |
+
and hence require a network connection to be read.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
import logging
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
import pandas as pd
|
| 14 |
+
import pandas._testing as tm
|
| 15 |
+
|
| 16 |
+
from pandas.io.feather_format import read_feather
|
| 17 |
+
from pandas.io.parsers import read_csv
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.mark.network
|
| 21 |
+
@pytest.mark.single_cpu
|
| 22 |
+
@pytest.mark.parametrize("mode", ["explicit", "infer"])
|
| 23 |
+
@pytest.mark.parametrize("engine", ["python", "c"])
|
| 24 |
+
def test_compressed_urls(
|
| 25 |
+
httpserver,
|
| 26 |
+
datapath,
|
| 27 |
+
salaries_table,
|
| 28 |
+
mode,
|
| 29 |
+
engine,
|
| 30 |
+
compression_only,
|
| 31 |
+
compression_to_extension,
|
| 32 |
+
):
|
| 33 |
+
# test reading compressed urls with various engines and
|
| 34 |
+
# extension inference
|
| 35 |
+
if compression_only == "tar":
|
| 36 |
+
pytest.skip("TODO: Add tar salaries.csv to pandas/io/parsers/data")
|
| 37 |
+
|
| 38 |
+
extension = compression_to_extension[compression_only]
|
| 39 |
+
with open(datapath("io", "parser", "data", "salaries.csv" + extension), "rb") as f:
|
| 40 |
+
httpserver.serve_content(content=f.read())
|
| 41 |
+
|
| 42 |
+
url = httpserver.url + "/salaries.csv" + extension
|
| 43 |
+
|
| 44 |
+
if mode != "explicit":
|
| 45 |
+
compression_only = mode
|
| 46 |
+
|
| 47 |
+
url_table = read_csv(url, sep="\t", compression=compression_only, engine=engine)
|
| 48 |
+
tm.assert_frame_equal(url_table, salaries_table)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@pytest.mark.network
|
| 52 |
+
@pytest.mark.single_cpu
|
| 53 |
+
def test_url_encoding_csv(httpserver, datapath):
|
| 54 |
+
"""
|
| 55 |
+
read_csv should honor the requested encoding for URLs.
|
| 56 |
+
|
| 57 |
+
GH 10424
|
| 58 |
+
"""
|
| 59 |
+
with open(datapath("io", "parser", "data", "unicode_series.csv"), "rb") as f:
|
| 60 |
+
httpserver.serve_content(content=f.read())
|
| 61 |
+
df = read_csv(httpserver.url, encoding="latin-1", header=None)
|
| 62 |
+
assert df.loc[15, 1] == "Á köldum klaka (Cold Fever) (1994)"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@pytest.fixture
|
| 66 |
+
def tips_df(datapath):
|
| 67 |
+
"""DataFrame with the tips dataset."""
|
| 68 |
+
return read_csv(datapath("io", "data", "csv", "tips.csv"))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@pytest.mark.single_cpu
|
| 72 |
+
@pytest.mark.network
|
| 73 |
+
class TestS3:
|
| 74 |
+
@pytest.mark.parametrize(
|
| 75 |
+
"suffix, compression",
|
| 76 |
+
[
|
| 77 |
+
("", None),
|
| 78 |
+
(".gz", "gzip"),
|
| 79 |
+
(".bz2", "bz2"),
|
| 80 |
+
],
|
| 81 |
+
)
|
| 82 |
+
@pytest.mark.parametrize("nrows", [None, 10])
|
| 83 |
+
@pytest.mark.parametrize("engine", ["c", "python"])
|
| 84 |
+
def test_parse_public_s3_bucket(
|
| 85 |
+
self,
|
| 86 |
+
s3_bucket_public_with_data,
|
| 87 |
+
s3so,
|
| 88 |
+
tips_df,
|
| 89 |
+
suffix,
|
| 90 |
+
compression,
|
| 91 |
+
nrows,
|
| 92 |
+
engine,
|
| 93 |
+
):
|
| 94 |
+
# more of an integration test due to the not-public contents portion
|
| 95 |
+
# can probably mock this though.
|
| 96 |
+
pytest.importorskip("s3fs")
|
| 97 |
+
df = read_csv(
|
| 98 |
+
f"s3://{s3_bucket_public_with_data.name}/tips.csv{suffix}",
|
| 99 |
+
nrows=nrows,
|
| 100 |
+
compression=compression,
|
| 101 |
+
storage_options=s3so,
|
| 102 |
+
engine=engine,
|
| 103 |
+
)
|
| 104 |
+
tm.assert_frame_equal(df, tips_df.iloc[:nrows])
|
| 105 |
+
|
| 106 |
+
def test_parse_private_s3_bucket(self, s3_bucket_private_with_data, s3so, tips_df):
|
| 107 |
+
# Read public file from bucket with not-public contents
|
| 108 |
+
pytest.importorskip("s3fs")
|
| 109 |
+
df = read_csv(
|
| 110 |
+
f"s3://{s3_bucket_private_with_data.name}/tips.csv", storage_options=s3so
|
| 111 |
+
)
|
| 112 |
+
tm.assert_frame_equal(df, tips_df)
|
| 113 |
+
|
| 114 |
+
@pytest.mark.parametrize("scheme", ["s3n", "s3a"])
|
| 115 |
+
def test_parse_public_bucket_s3n_s3a(
|
| 116 |
+
self, s3_bucket_public_with_data, s3so, tips_df, scheme
|
| 117 |
+
):
|
| 118 |
+
nrows = 10
|
| 119 |
+
df = read_csv(
|
| 120 |
+
f"{scheme}://{s3_bucket_public_with_data.name}/tips.csv",
|
| 121 |
+
nrows=nrows,
|
| 122 |
+
storage_options=s3so,
|
| 123 |
+
)
|
| 124 |
+
tm.assert_frame_equal(df, tips_df.iloc[:nrows])
|
| 125 |
+
|
| 126 |
+
@pytest.mark.parametrize(
|
| 127 |
+
"suffix, compression",
|
| 128 |
+
[
|
| 129 |
+
("", None),
|
| 130 |
+
(".gz", "gzip"),
|
| 131 |
+
(".bz2", "bz2"),
|
| 132 |
+
],
|
| 133 |
+
)
|
| 134 |
+
@pytest.mark.parametrize("engine", ["c", "python"])
|
| 135 |
+
def test_parse_public_s3_bucket_chunked(
|
| 136 |
+
self, s3_bucket_public_with_data, s3so, tips_df, suffix, compression, engine
|
| 137 |
+
):
|
| 138 |
+
# Read with a chunksize
|
| 139 |
+
chunksize = 5
|
| 140 |
+
with read_csv(
|
| 141 |
+
f"s3://{s3_bucket_public_with_data.name}/tips.csv{suffix}",
|
| 142 |
+
chunksize=chunksize,
|
| 143 |
+
compression=compression,
|
| 144 |
+
storage_options=s3so,
|
| 145 |
+
engine=engine,
|
| 146 |
+
) as df_reader:
|
| 147 |
+
assert df_reader.chunksize == chunksize
|
| 148 |
+
for i_chunk in [0, 1, 2]:
|
| 149 |
+
# Read a couple of chunks and make sure we see them
|
| 150 |
+
# properly.
|
| 151 |
+
df = df_reader.get_chunk()
|
| 152 |
+
assert isinstance(df, pd.DataFrame)
|
| 153 |
+
assert not df.empty
|
| 154 |
+
true_df = tips_df.iloc[chunksize * i_chunk : chunksize * (i_chunk + 1)]
|
| 155 |
+
tm.assert_frame_equal(true_df, df)
|
| 156 |
+
|
| 157 |
+
@pytest.mark.parametrize("suffix", ["", ".gz", ".bz2"])
|
| 158 |
+
def test_infer_s3_compression(
|
| 159 |
+
self, s3_bucket_public_with_data, s3so, tips_df, suffix
|
| 160 |
+
):
|
| 161 |
+
df = read_csv(
|
| 162 |
+
f"s3://{s3_bucket_public_with_data.name}/tips.csv{suffix}",
|
| 163 |
+
engine="python",
|
| 164 |
+
compression="infer",
|
| 165 |
+
storage_options=s3so,
|
| 166 |
+
)
|
| 167 |
+
tm.assert_frame_equal(df, tips_df)
|
| 168 |
+
|
| 169 |
+
def test_read_s3_fails(self, s3_bucket_public_with_data, s3so):
|
| 170 |
+
msg = "The specified bucket does not exist"
|
| 171 |
+
with pytest.raises(OSError, match=msg):
|
| 172 |
+
read_csv("s3://nyqpug/asdf.csv", storage_options=s3so)
|
| 173 |
+
|
| 174 |
+
def test_read_s3_fails_private(self, s3_bucket_private_with_data, s3so):
|
| 175 |
+
s3_url = f"{s3_bucket_private_with_data.name}/file.csv"
|
| 176 |
+
msg = rf"{s3_url}"
|
| 177 |
+
# Receive a permission error when trying to read a private bucket.
|
| 178 |
+
# It's irrelevant here that this isn't actually a table.
|
| 179 |
+
with pytest.raises(FileNotFoundError, match=msg):
|
| 180 |
+
read_csv(
|
| 181 |
+
f"s3://{s3_url}",
|
| 182 |
+
storage_options=s3so,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
@pytest.mark.single_cpu
|
| 186 |
+
def test_read_csv_handles_boto_s3_object(
|
| 187 |
+
self, s3_bucket_public_with_data, tips_file
|
| 188 |
+
):
|
| 189 |
+
# see gh-16135
|
| 190 |
+
|
| 191 |
+
s3_object = s3_bucket_public_with_data.Object("tips.csv")
|
| 192 |
+
|
| 193 |
+
with BytesIO(s3_object.get()["Body"].read()) as buffer:
|
| 194 |
+
result = read_csv(buffer, encoding="utf8")
|
| 195 |
+
assert isinstance(result, pd.DataFrame)
|
| 196 |
+
assert not result.empty
|
| 197 |
+
|
| 198 |
+
expected = read_csv(tips_file)
|
| 199 |
+
tm.assert_frame_equal(result, expected)
|
| 200 |
+
|
| 201 |
+
@pytest.mark.single_cpu
|
| 202 |
+
def test_read_csv_chunked_download(self, s3_bucket_public, s3so, caplog):
|
| 203 |
+
# 8 MB, S3FS uses 5MB chunks
|
| 204 |
+
df = pd.DataFrame(np.zeros((100000, 4)), columns=list("abcd"))
|
| 205 |
+
with BytesIO(df.to_csv().encode("utf-8")) as buf:
|
| 206 |
+
s3_bucket_public.put_object(Key="large-file.csv", Body=buf)
|
| 207 |
+
uri = f"{s3_bucket_public.name}/large-file.csv"
|
| 208 |
+
match_re = re.compile(rf"^Fetch: {uri}, 0-(?P<stop>\d+)$")
|
| 209 |
+
with caplog.at_level(logging.DEBUG, logger="s3fs"):
|
| 210 |
+
read_csv(
|
| 211 |
+
f"s3://{uri}",
|
| 212 |
+
nrows=5,
|
| 213 |
+
storage_options=s3so,
|
| 214 |
+
)
|
| 215 |
+
for log in caplog.messages:
|
| 216 |
+
if match := re.match(match_re, log):
|
| 217 |
+
# Less than 8 MB
|
| 218 |
+
assert int(match.group("stop")) < 8000000
|
| 219 |
+
|
| 220 |
+
def test_read_s3_with_hash_in_key(self, s3_bucket_public_with_data, s3so, tips_df):
|
| 221 |
+
# GH 25945
|
| 222 |
+
result = read_csv(
|
| 223 |
+
f"s3://{s3_bucket_public_with_data.name}/tips#1.csv", storage_options=s3so
|
| 224 |
+
)
|
| 225 |
+
tm.assert_frame_equal(tips_df, result)
|
| 226 |
+
|
| 227 |
+
def test_read_feather_s3_file_path(
|
| 228 |
+
self, s3_bucket_public_with_data, s3so, feather_file
|
| 229 |
+
):
|
| 230 |
+
# GH 29055
|
| 231 |
+
pytest.importorskip("pyarrow")
|
| 232 |
+
expected = read_feather(feather_file)
|
| 233 |
+
res = read_feather(
|
| 234 |
+
f"s3://{s3_bucket_public_with_data.name}/simple_dataset.feather",
|
| 235 |
+
storage_options=s3so,
|
| 236 |
+
)
|
| 237 |
+
tm.assert_frame_equal(expected, res)
|
.venv/lib/python3.12/site-packages/pandas/tests/io/parser/test_parallel_read.py
ADDED
|
@@ -0,0 +1,2256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
The parallel path is enabled automatically when:
|
| 5 |
+
- reading from a local uncompressed file path
|
| 6 |
+
- using the C engine (the default)
|
| 7 |
+
- not in iterator / chunked mode
|
| 8 |
+
- file size >= _PARALLEL_READ_MIN_BYTES
|
| 9 |
+
|
| 10 |
+
We test correctness (parallel == serial) rather than performance.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import csv
|
| 16 |
+
import io
|
| 17 |
+
import itertools
|
| 18 |
+
import mmap
|
| 19 |
+
import os
|
| 20 |
+
from typing import TYPE_CHECKING
|
| 21 |
+
import warnings
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import pytest
|
| 25 |
+
|
| 26 |
+
from pandas._libs import parsers as _parsers
|
| 27 |
+
from pandas.compat import WASM
|
| 28 |
+
from pandas.errors import (
|
| 29 |
+
EmptyDataError,
|
| 30 |
+
ParserError,
|
| 31 |
+
ParserWarning,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
if TYPE_CHECKING:
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
|
| 37 |
+
import pandas as pd
|
| 38 |
+
import pandas._testing as tm
|
| 39 |
+
|
| 40 |
+
from pandas.io.parsers import readers as _readers
|
| 41 |
+
from pandas.io.parsers.base_parser import ParserBase
|
| 42 |
+
from pandas.io.parsers.readers import (
|
| 43 |
+
_can_parallelize_csv,
|
| 44 |
+
_default_n_workers,
|
| 45 |
+
_find_chunk_byte_offsets,
|
| 46 |
+
_find_data_start_offset,
|
| 47 |
+
_read_csv_parallel,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# ---------------------------------------------------------------------------
|
| 51 |
+
# Helpers
|
| 52 |
+
# ---------------------------------------------------------------------------
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _make_large_csv(path: Path, n_rows: int = 10_000) -> None:
|
| 56 |
+
"""Write a CSV with enough rows to split into multiple parallel chunks."""
|
| 57 |
+
rng = np.random.default_rng(42)
|
| 58 |
+
df = pd.DataFrame(
|
| 59 |
+
{
|
| 60 |
+
"int_col": rng.integers(0, 10_000, size=n_rows),
|
| 61 |
+
"float_col": rng.random(n_rows),
|
| 62 |
+
"str_col": rng.choice(["foo", "bar", "baz", "qux"], size=n_rows),
|
| 63 |
+
}
|
| 64 |
+
)
|
| 65 |
+
df.to_csv(path, index=False)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ---------------------------------------------------------------------------
|
| 69 |
+
# _can_parallelize_csv
|
| 70 |
+
# ---------------------------------------------------------------------------
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class TestCanParallelizeCsv:
|
| 74 |
+
"""Unit tests for the eligibility predicate."""
|
| 75 |
+
|
| 76 |
+
def _kwds(self, **overrides):
|
| 77 |
+
base = {
|
| 78 |
+
"engine": "c",
|
| 79 |
+
"engine_specified": False,
|
| 80 |
+
"iterator": False,
|
| 81 |
+
"chunksize": None,
|
| 82 |
+
"nrows": None,
|
| 83 |
+
"skiprows": None,
|
| 84 |
+
"header": 0,
|
| 85 |
+
"skipfooter": 0,
|
| 86 |
+
"index_col": None,
|
| 87 |
+
"usecols": None,
|
| 88 |
+
"compression": "infer",
|
| 89 |
+
}
|
| 90 |
+
base.update(overrides)
|
| 91 |
+
return base
|
| 92 |
+
|
| 93 |
+
def test_eligible_large_file(self, tmp_path, monkeypatch):
|
| 94 |
+
path = tmp_path / "big.csv"
|
| 95 |
+
_make_large_csv(path)
|
| 96 |
+
# Lower the threshold so the test file qualifies regardless of its size.
|
| 97 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 98 |
+
assert _can_parallelize_csv(path, self._kwds())
|
| 99 |
+
|
| 100 |
+
def test_accepts_default_engine(self, tmp_path, monkeypatch):
|
| 101 |
+
"""engine=None (the default) should be treated the same as engine='c'."""
|
| 102 |
+
path = tmp_path / "data.csv"
|
| 103 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 104 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 105 |
+
assert _can_parallelize_csv(path, self._kwds(engine=None))
|
| 106 |
+
|
| 107 |
+
def test_rejects_file_like_object(self, tmp_path):
|
| 108 |
+
path = tmp_path / "data.csv"
|
| 109 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 110 |
+
with open(path, encoding="utf-8") as f:
|
| 111 |
+
assert not _can_parallelize_csv(f, self._kwds())
|
| 112 |
+
|
| 113 |
+
def test_rejects_url(self):
|
| 114 |
+
assert not _can_parallelize_csv("http://example.com/data.csv", self._kwds())
|
| 115 |
+
assert not _can_parallelize_csv("s3://bucket/key.csv", self._kwds())
|
| 116 |
+
|
| 117 |
+
def test_rejects_compressed(self, tmp_path):
|
| 118 |
+
path = tmp_path / "data.csv.gz"
|
| 119 |
+
path.write_bytes(b"fake")
|
| 120 |
+
assert not _can_parallelize_csv(path, self._kwds(compression="gzip"))
|
| 121 |
+
assert not _can_parallelize_csv(path, self._kwds(compression="infer"))
|
| 122 |
+
|
| 123 |
+
def test_rejects_tar(self, tmp_path):
|
| 124 |
+
# .tar infers as compression="tar" in get_handle; the parallel path
|
| 125 |
+
# must not feed raw archive bytes to the tokenizer.
|
| 126 |
+
path = tmp_path / "data.tar"
|
| 127 |
+
path.write_bytes(b"fake")
|
| 128 |
+
assert not _can_parallelize_csv(path, self._kwds())
|
| 129 |
+
|
| 130 |
+
def test_rejects_dict_compression(self, tmp_path):
|
| 131 |
+
path = tmp_path / "data.csv"
|
| 132 |
+
path.write_bytes(b"fake")
|
| 133 |
+
kwds = self._kwds(compression={"method": "gzip"})
|
| 134 |
+
assert not _can_parallelize_csv(path, kwds)
|
| 135 |
+
|
| 136 |
+
def test_rejects_iterator_mode(self, tmp_path):
|
| 137 |
+
path = tmp_path / "data.csv"
|
| 138 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 139 |
+
assert not _can_parallelize_csv(path, self._kwds(iterator=True))
|
| 140 |
+
|
| 141 |
+
def test_rejects_chunksize(self, tmp_path):
|
| 142 |
+
path = tmp_path / "data.csv"
|
| 143 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 144 |
+
assert not _can_parallelize_csv(path, self._kwds(chunksize=1000))
|
| 145 |
+
|
| 146 |
+
def test_rejects_nrows(self, tmp_path):
|
| 147 |
+
path = tmp_path / "data.csv"
|
| 148 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 149 |
+
assert not _can_parallelize_csv(path, self._kwds(nrows=100))
|
| 150 |
+
|
| 151 |
+
def test_rejects_non_c_engine(self, tmp_path):
|
| 152 |
+
path = tmp_path / "data.csv"
|
| 153 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 154 |
+
assert not _can_parallelize_csv(path, self._kwds(engine="python"))
|
| 155 |
+
assert not _can_parallelize_csv(path, self._kwds(engine="pyarrow"))
|
| 156 |
+
|
| 157 |
+
def test_rejects_custom_lineterminator(self, tmp_path, monkeypatch):
|
| 158 |
+
path = tmp_path / "data.csv"
|
| 159 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 160 |
+
# The chunk splitter always scans for \n; a different lineterminator
|
| 161 |
+
# would misalign chunk boundaries and produce silently wrong output.
|
| 162 |
+
assert not _can_parallelize_csv(path, self._kwds(lineterminator="\r"))
|
| 163 |
+
assert not _can_parallelize_csv(path, self._kwds(lineterminator="|"))
|
| 164 |
+
# \n and None (default) are acceptable.
|
| 165 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 166 |
+
assert _can_parallelize_csv(path, self._kwds(lineterminator="\n"))
|
| 167 |
+
assert _can_parallelize_csv(path, self._kwds(lineterminator=None))
|
| 168 |
+
|
| 169 |
+
@pytest.mark.parametrize(
|
| 170 |
+
"encoding", ["utf-16", "UTF-16", "utf_16_le", "utf-32", "UTF_32_BE"]
|
| 171 |
+
)
|
| 172 |
+
def test_rejects_utf16_32_encoding(self, tmp_path, monkeypatch, encoding):
|
| 173 |
+
# UTF-16/32 encode \n as a multi-byte sequence (e.g. b"\x0a\x00" in
|
| 174 |
+
# UTF-16LE). Splitting on raw \n bytes would misalign chunks and
|
| 175 |
+
# silently corrupt data.
|
| 176 |
+
path = tmp_path / "data.csv"
|
| 177 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 178 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 179 |
+
assert not _can_parallelize_csv(path, self._kwds(encoding=encoding))
|
| 180 |
+
|
| 181 |
+
@pytest.mark.parametrize("encoding", ["latin-1", "cp1252", "shift_jis", "ascii"])
|
| 182 |
+
def test_rejects_non_utf8_encoding(self, tmp_path, monkeypatch, encoding):
|
| 183 |
+
# Chunk workers feed raw file bytes to the C tokenizer, which decodes
|
| 184 |
+
# words as UTF-8; only UTF-8-compatible encodings are byte-safe. "ascii"
|
| 185 |
+
# is excluded too: the workers would decode a non-ASCII byte as UTF-8 and
|
| 186 |
+
# succeed, masking the UnicodeDecodeError serial raises (GH#64347).
|
| 187 |
+
path = tmp_path / "data.csv"
|
| 188 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 189 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 190 |
+
assert not _can_parallelize_csv(path, self._kwds(encoding=encoding))
|
| 191 |
+
assert _can_parallelize_csv(path, self._kwds(encoding="utf-8"))
|
| 192 |
+
assert _can_parallelize_csv(path, self._kwds(encoding="UTF8"))
|
| 193 |
+
assert _can_parallelize_csv(path, self._kwds(encoding="utf-8-sig"))
|
| 194 |
+
|
| 195 |
+
def test_rejects_python_engine_seps(self, tmp_path, monkeypatch):
|
| 196 |
+
# Multi-char/regex seps (other than r"\s+") and sep=None force the
|
| 197 |
+
# python engine inside TextFileReader (GH#64347).
|
| 198 |
+
path = tmp_path / "data.csv"
|
| 199 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 200 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 201 |
+
assert not _can_parallelize_csv(path, self._kwds(delimiter=";;"))
|
| 202 |
+
assert not _can_parallelize_csv(path, self._kwds(delimiter=None))
|
| 203 |
+
assert _can_parallelize_csv(path, self._kwds(delimiter=r"\s+"))
|
| 204 |
+
|
| 205 |
+
def test_rejects_multibyte_sep_and_quotechar(self, tmp_path, monkeypatch):
|
| 206 |
+
# A separator or quotechar wider than one byte forces the python
|
| 207 |
+
# engine too, warning as it does so (GH#66259).
|
| 208 |
+
path = tmp_path / "data.csv"
|
| 209 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 210 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 211 |
+
assert not _can_parallelize_csv(path, self._kwds(delimiter="§"))
|
| 212 |
+
assert not _can_parallelize_csv(path, self._kwds(quotechar="»"))
|
| 213 |
+
assert _can_parallelize_csv(path, self._kwds(quotechar="'"))
|
| 214 |
+
|
| 215 |
+
def test_rejects_comment(self, tmp_path, monkeypatch):
|
| 216 |
+
path = tmp_path / "data.csv"
|
| 217 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 218 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 219 |
+
assert not _can_parallelize_csv(path, self._kwds(comment="#"))
|
| 220 |
+
|
| 221 |
+
def test_rejects_escapechar(self, tmp_path, monkeypatch):
|
| 222 |
+
path = tmp_path / "data.csv"
|
| 223 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 224 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 225 |
+
assert not _can_parallelize_csv(path, self._kwds(escapechar="\\"))
|
| 226 |
+
|
| 227 |
+
def test_rejects_dialect(self, tmp_path, monkeypatch):
|
| 228 |
+
# dialect is merged into the kwds inside TextFileReader, i.e. after
|
| 229 |
+
# this check runs; a dialect-specified escapechar would otherwise
|
| 230 |
+
# bypass the escapechar check above (GH#64347).
|
| 231 |
+
path = tmp_path / "data.csv"
|
| 232 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 233 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 234 |
+
assert not _can_parallelize_csv(path, self._kwds(dialect="excel"))
|
| 235 |
+
|
| 236 |
+
def test_rejects_parse_dates(self, tmp_path, monkeypatch):
|
| 237 |
+
path = tmp_path / "data.csv"
|
| 238 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 239 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 240 |
+
assert not _can_parallelize_csv(path, self._kwds(parse_dates=["a"]))
|
| 241 |
+
assert not _can_parallelize_csv(path, self._kwds(parse_dates=True))
|
| 242 |
+
assert _can_parallelize_csv(path, self._kwds(parse_dates=None))
|
| 243 |
+
assert _can_parallelize_csv(path, self._kwds(parse_dates=False))
|
| 244 |
+
|
| 245 |
+
@pytest.mark.parametrize("low_memory", [False, 0, np.False_])
|
| 246 |
+
def test_rejects_low_memory_false(self, tmp_path, monkeypatch, low_memory):
|
| 247 |
+
# A falsy low_memory guarantees whole-file type inference, which the
|
| 248 |
+
# per-chunk parallel path cannot honour; low_memory=True (and the unset
|
| 249 |
+
# default) document per-chunk divergence, so they stay eligible
|
| 250 |
+
# (GH#64347). low_memory is not coerced to bool, so falsy non-False
|
| 251 |
+
# values must be rejected too (GH#66327).
|
| 252 |
+
path = tmp_path / "data.csv"
|
| 253 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 254 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 255 |
+
assert not _can_parallelize_csv(path, self._kwds(low_memory=low_memory))
|
| 256 |
+
assert _can_parallelize_csv(path, self._kwds(low_memory=True))
|
| 257 |
+
assert _can_parallelize_csv(path, self._kwds())
|
| 258 |
+
|
| 259 |
+
def test_rejects_storage_options(self, tmp_path):
|
| 260 |
+
# storage_options raises for local paths in the serial path; the
|
| 261 |
+
# parallel path strips it and would mask that error (GH#64347).
|
| 262 |
+
path = tmp_path / "data.csv"
|
| 263 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 264 |
+
assert not _can_parallelize_csv(
|
| 265 |
+
path, self._kwds(storage_options={"anon": True})
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
def test_rejects_on_bad_lines_warn(self, tmp_path, monkeypatch):
|
| 269 |
+
# "warn" includes line numbers in its warnings; chunk workers would
|
| 270 |
+
# report chunk-relative (i.e. wrong) ones (GH#64347).
|
| 271 |
+
path = tmp_path / "data.csv"
|
| 272 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 273 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 274 |
+
method = ParserBase.BadLineHandleMethod
|
| 275 |
+
assert not _can_parallelize_csv(path, self._kwds(on_bad_lines=method.BLHM_WARN))
|
| 276 |
+
assert _can_parallelize_csv(path, self._kwds(on_bad_lines=method.BLHM_ERROR))
|
| 277 |
+
assert _can_parallelize_csv(path, self._kwds(on_bad_lines=method.BLHM_SKIP))
|
| 278 |
+
|
| 279 |
+
def test_rejects_blank_line_in_preamble(self, tmp_path, monkeypatch):
|
| 280 |
+
# A blank line before the header shifts where pandas locates the
|
| 281 |
+
# header relative to the physical line count (GH#64347).
|
| 282 |
+
path = tmp_path / "data.csv"
|
| 283 |
+
path.write_text("\na,b\n1,2\n", encoding="utf-8")
|
| 284 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 285 |
+
assert not _can_parallelize_csv(path, self._kwds())
|
| 286 |
+
|
| 287 |
+
def test_rejects_callable_skiprows(self, tmp_path):
|
| 288 |
+
path = tmp_path / "data.csv"
|
| 289 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 290 |
+
assert not _can_parallelize_csv(path, self._kwds(skiprows=lambda x: x == 0))
|
| 291 |
+
|
| 292 |
+
def test_rejects_list_skiprows(self, tmp_path):
|
| 293 |
+
path = tmp_path / "data.csv"
|
| 294 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 295 |
+
assert not _can_parallelize_csv(path, self._kwds(skiprows=[0, 2]))
|
| 296 |
+
|
| 297 |
+
def test_rejects_multi_level_header(self, tmp_path):
|
| 298 |
+
path = tmp_path / "data.csv"
|
| 299 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 300 |
+
assert not _can_parallelize_csv(path, self._kwds(header=[0, 1]))
|
| 301 |
+
|
| 302 |
+
def test_rejects_index_col(self, tmp_path):
|
| 303 |
+
path = tmp_path / "data.csv"
|
| 304 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 305 |
+
assert not _can_parallelize_csv(path, self._kwds(index_col=0))
|
| 306 |
+
assert not _can_parallelize_csv(path, self._kwds(index_col="a"))
|
| 307 |
+
|
| 308 |
+
def test_accepts_index_col_false(self, tmp_path):
|
| 309 |
+
# index_col=False is allowed (suppresses implicit index)
|
| 310 |
+
path = tmp_path / "data.csv"
|
| 311 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 312 |
+
# File is too small → False due to size, not index_col=False
|
| 313 |
+
assert not _can_parallelize_csv(path, self._kwds(index_col=False))
|
| 314 |
+
|
| 315 |
+
def test_rejects_usecols(self, tmp_path):
|
| 316 |
+
path = tmp_path / "data.csv"
|
| 317 |
+
path.write_text("a,b,c\n1,2,3\n", encoding="utf-8")
|
| 318 |
+
assert not _can_parallelize_csv(path, self._kwds(usecols=["a", "b"]))
|
| 319 |
+
|
| 320 |
+
def test_rejects_small_file(self, tmp_path):
|
| 321 |
+
path = tmp_path / "small.csv"
|
| 322 |
+
path.write_text("a,b\n1,2\n", encoding="utf-8")
|
| 323 |
+
assert not _can_parallelize_csv(path, self._kwds())
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# ---------------------------------------------------------------------------
|
| 327 |
+
# _find_data_start_offset
|
| 328 |
+
# ---------------------------------------------------------------------------
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class TestFindDataStartOffset:
|
| 332 |
+
def test_no_skiprows_header_0(self, tmp_path):
|
| 333 |
+
path = tmp_path / "data.csv"
|
| 334 |
+
path.write_bytes(b"a,b,c\n1,2,3\n4,5,6\n")
|
| 335 |
+
offset = _find_data_start_offset(str(path), header=0, skiprows=0)
|
| 336 |
+
assert offset == len(b"a,b,c\n")
|
| 337 |
+
|
| 338 |
+
def test_header_none(self, tmp_path):
|
| 339 |
+
path = tmp_path / "data.csv"
|
| 340 |
+
path.write_bytes(b"1,2,3\n4,5,6\n")
|
| 341 |
+
offset = _find_data_start_offset(str(path), header=None, skiprows=0)
|
| 342 |
+
assert offset == 0
|
| 343 |
+
|
| 344 |
+
def test_skiprows_2_header_0(self, tmp_path):
|
| 345 |
+
path = tmp_path / "data.csv"
|
| 346 |
+
path.write_bytes(b"skip1\nskip2\na,b\n1,2\n")
|
| 347 |
+
offset = _find_data_start_offset(str(path), header=0, skiprows=2)
|
| 348 |
+
# 'skip1\n' + 'skip2\n' + 'a,b\n' = 6 + 6 + 4 = 16
|
| 349 |
+
assert offset == len(b"skip1\nskip2\na,b\n")
|
| 350 |
+
|
| 351 |
+
def test_header_2(self, tmp_path):
|
| 352 |
+
# header=2 means lines 0,1,2 are consumed (lines 0-1 skipped, line 2 is header)
|
| 353 |
+
path = tmp_path / "data.csv"
|
| 354 |
+
path.write_bytes(b"r0\nr1\nr2_header\n1,2\n")
|
| 355 |
+
offset = _find_data_start_offset(str(path), header=2, skiprows=0)
|
| 356 |
+
assert offset == len(b"r0\nr1\nr2_header\n")
|
| 357 |
+
|
| 358 |
+
def test_eof_within_preamble(self, tmp_path):
|
| 359 |
+
# File ends before all preamble lines are consumed → no crash.
|
| 360 |
+
path = tmp_path / "data.csv"
|
| 361 |
+
path.write_bytes(b"only_one_line\n")
|
| 362 |
+
offset = _find_data_start_offset(str(path), header=0, skiprows=5)
|
| 363 |
+
assert offset == len(b"only_one_line\n")
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
# ---------------------------------------------------------------------------
|
| 367 |
+
# _find_chunk_byte_offsets
|
| 368 |
+
# ---------------------------------------------------------------------------
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class TestFindChunkByteOffsets:
|
| 372 |
+
def _write_csv(self, path: Path, n_rows: int = 10) -> None:
|
| 373 |
+
lines = "a,b\n" + "".join(f"{i},{i}\n" for i in range(n_rows))
|
| 374 |
+
path.write_text(lines, encoding="utf-8")
|
| 375 |
+
|
| 376 |
+
def test_single_chunk(self, tmp_path):
|
| 377 |
+
path = tmp_path / "data.csv"
|
| 378 |
+
self._write_csv(path)
|
| 379 |
+
data_start = len(b"a,b\n")
|
| 380 |
+
offsets = _find_chunk_byte_offsets(str(path), 1, data_start)
|
| 381 |
+
assert offsets[0] == data_start
|
| 382 |
+
assert offsets[-1] == os.path.getsize(str(path))
|
| 383 |
+
assert len(offsets) == 2
|
| 384 |
+
|
| 385 |
+
def test_multiple_chunks_cover_full_file(self, tmp_path):
|
| 386 |
+
path = tmp_path / "data.csv"
|
| 387 |
+
self._write_csv(path, n_rows=100)
|
| 388 |
+
data_start = len(b"a,b\n")
|
| 389 |
+
file_size = os.path.getsize(str(path))
|
| 390 |
+
offsets = _find_chunk_byte_offsets(str(path), 4, data_start)
|
| 391 |
+
|
| 392 |
+
assert offsets[0] == data_start
|
| 393 |
+
assert offsets[-1] == file_size
|
| 394 |
+
# All offsets within valid range
|
| 395 |
+
assert all(data_start <= off <= file_size for off in offsets)
|
| 396 |
+
# Strictly increasing
|
| 397 |
+
assert all(offsets[i] < offsets[i + 1] for i in range(len(offsets) - 1))
|
| 398 |
+
|
| 399 |
+
def test_chunks_align_to_newlines(self, tmp_path):
|
| 400 |
+
path = tmp_path / "data.csv"
|
| 401 |
+
self._write_csv(path, n_rows=1000)
|
| 402 |
+
data_start = len(b"a,b\n")
|
| 403 |
+
raw_bytes = path.read_bytes()
|
| 404 |
+
offsets = _find_chunk_byte_offsets(str(path), 4, data_start)
|
| 405 |
+
|
| 406 |
+
for off in offsets[1:-1]:
|
| 407 |
+
# Each interior split point must be at the start of a line.
|
| 408 |
+
assert raw_bytes[off - 1 : off] == b"\n"
|
| 409 |
+
|
| 410 |
+
def test_fewer_chunks_than_requested_when_file_tiny(self, tmp_path):
|
| 411 |
+
path = tmp_path / "data.csv"
|
| 412 |
+
path.write_bytes(b"a,b\n1,2\n")
|
| 413 |
+
offsets = _find_chunk_byte_offsets(str(path), 8, data_start=4)
|
| 414 |
+
# Can't produce 8 distinct split points in 4 bytes.
|
| 415 |
+
assert len(offsets) >= 2
|
| 416 |
+
|
| 417 |
+
def test_one_long_line_does_not_collapse_the_split(self, tmp_path):
|
| 418 |
+
# A line long enough to swallow several split targets must only cost
|
| 419 |
+
# those targets, not every boundary after it.
|
| 420 |
+
path = tmp_path / "data.csv"
|
| 421 |
+
lines = [b"a,b\n"] + [b"1,2\n"] * 20_000
|
| 422 |
+
lines.insert(10, b'1,"' + b"x" * 40_000 + b'"\n')
|
| 423 |
+
path.write_bytes(b"".join(lines))
|
| 424 |
+
|
| 425 |
+
offsets = _find_chunk_byte_offsets(str(path), 32, data_start=4)
|
| 426 |
+
# Skipping only the swallowed targets keeps most of the split; giving
|
| 427 |
+
# up at the first one degenerates to 2 chunks. The long line covers
|
| 428 |
+
# roughly a third of the 32 targets.
|
| 429 |
+
assert len(offsets) - 1 >= 20
|
| 430 |
+
assert all(offsets[i] < offsets[i + 1] for i in range(len(offsets) - 1))
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# ---------------------------------------------------------------------------
|
| 434 |
+
# _read_csv_parallel (correctness: parallel == serial)
|
| 435 |
+
# ---------------------------------------------------------------------------
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
@pytest.mark.slow
|
| 439 |
+
class TestReadCsvParallel:
|
| 440 |
+
"""End-to-end correctness: parallel result must match serial result."""
|
| 441 |
+
|
| 442 |
+
def _serial_read(self, path, **kwargs):
|
| 443 |
+
return pd.read_csv(path, engine="c", **kwargs)
|
| 444 |
+
|
| 445 |
+
def _parallel_read(self, path, kwds, n_workers=4):
|
| 446 |
+
"""Call the internal helper directly so file-size guards don't apply."""
|
| 447 |
+
result = _read_csv_parallel(str(path), kwds, n_workers)
|
| 448 |
+
if result is None:
|
| 449 |
+
pytest.fail("parallel read fell back to serial")
|
| 450 |
+
return result
|
| 451 |
+
|
| 452 |
+
def _base_kwds(self, path, **overrides):
|
| 453 |
+
"""Return kwds as _read() would see them for a default read_csv call."""
|
| 454 |
+
from pandas._libs import lib
|
| 455 |
+
|
| 456 |
+
from pandas.io.parsers.readers import _refine_defaults_read
|
| 457 |
+
|
| 458 |
+
kwds = {
|
| 459 |
+
"header": "infer",
|
| 460 |
+
"names": lib.no_default,
|
| 461 |
+
"index_col": None,
|
| 462 |
+
"usecols": None,
|
| 463 |
+
"dtype": None,
|
| 464 |
+
"converters": None,
|
| 465 |
+
"true_values": None,
|
| 466 |
+
"false_values": None,
|
| 467 |
+
"skipinitialspace": False,
|
| 468 |
+
"skiprows": None,
|
| 469 |
+
"skipfooter": 0,
|
| 470 |
+
"nrows": None,
|
| 471 |
+
"na_values": None,
|
| 472 |
+
"keep_default_na": True,
|
| 473 |
+
"na_filter": True,
|
| 474 |
+
"skip_blank_lines": True,
|
| 475 |
+
"parse_dates": None,
|
| 476 |
+
"date_format": None,
|
| 477 |
+
"dayfirst": False,
|
| 478 |
+
"cache_dates": True,
|
| 479 |
+
"iterator": False,
|
| 480 |
+
"chunksize": None,
|
| 481 |
+
"compression": "infer",
|
| 482 |
+
"thousands": None,
|
| 483 |
+
"decimal": ".",
|
| 484 |
+
"lineterminator": None,
|
| 485 |
+
"quotechar": '"',
|
| 486 |
+
"quoting": 0,
|
| 487 |
+
"doublequote": True,
|
| 488 |
+
"escapechar": None,
|
| 489 |
+
"comment": None,
|
| 490 |
+
"encoding": None,
|
| 491 |
+
"encoding_errors": "strict",
|
| 492 |
+
"dialect": None,
|
| 493 |
+
"on_bad_lines": "error",
|
| 494 |
+
"low_memory": True,
|
| 495 |
+
"memory_map": False,
|
| 496 |
+
"float_precision": None,
|
| 497 |
+
"storage_options": None,
|
| 498 |
+
"dtype_backend": lib.no_default,
|
| 499 |
+
}
|
| 500 |
+
kwds.update(overrides)
|
| 501 |
+
# Apply the same defaulting logic as read_csv → _refine_defaults_read.
|
| 502 |
+
kwds_defaults = _refine_defaults_read(
|
| 503 |
+
dialect=None,
|
| 504 |
+
delimiter=lib.no_default,
|
| 505 |
+
engine=None, # triggers engine="c"
|
| 506 |
+
sep=lib.no_default,
|
| 507 |
+
on_bad_lines=kwds.pop("on_bad_lines"),
|
| 508 |
+
names=kwds.pop("names"),
|
| 509 |
+
defaults={"delimiter": ","},
|
| 510 |
+
dtype_backend=kwds.pop("dtype_backend"),
|
| 511 |
+
lineterminator=kwds["lineterminator"],
|
| 512 |
+
)
|
| 513 |
+
kwds.update(kwds_defaults)
|
| 514 |
+
return kwds
|
| 515 |
+
|
| 516 |
+
# ------------------------------------------------------------------
|
| 517 |
+
# Basic dtypes
|
| 518 |
+
# ------------------------------------------------------------------
|
| 519 |
+
|
| 520 |
+
def test_ints_and_floats(self, tmp_path):
|
| 521 |
+
path = tmp_path / "data.csv"
|
| 522 |
+
n = 5_000
|
| 523 |
+
rng = np.random.default_rng(0)
|
| 524 |
+
df = pd.DataFrame({"a": rng.integers(0, 100, n), "b": rng.random(n)})
|
| 525 |
+
df.to_csv(path, index=False)
|
| 526 |
+
kwds = self._base_kwds(path)
|
| 527 |
+
result = self._parallel_read(path, kwds)
|
| 528 |
+
expected = self._serial_read(path)
|
| 529 |
+
tm.assert_frame_equal(result.reset_index(drop=True), expected)
|
| 530 |
+
|
| 531 |
+
def test_strings(self, tmp_path):
|
| 532 |
+
path = tmp_path / "data.csv"
|
| 533 |
+
n = 5_000
|
| 534 |
+
rng = np.random.default_rng(1)
|
| 535 |
+
df = pd.DataFrame(
|
| 536 |
+
{
|
| 537 |
+
"name": rng.choice(["alice", "bob", "carol"], n),
|
| 538 |
+
"val": rng.integers(0, 10, n),
|
| 539 |
+
}
|
| 540 |
+
)
|
| 541 |
+
df.to_csv(path, index=False)
|
| 542 |
+
kwds = self._base_kwds(path)
|
| 543 |
+
result = self._parallel_read(path, kwds)
|
| 544 |
+
expected = self._serial_read(path)
|
| 545 |
+
tm.assert_frame_equal(result.reset_index(drop=True), expected)
|
| 546 |
+
|
| 547 |
+
def test_with_na_values(self, tmp_path):
|
| 548 |
+
path = tmp_path / "data.csv"
|
| 549 |
+
n = 5_000
|
| 550 |
+
rng = np.random.default_rng(2)
|
| 551 |
+
vals = rng.random(n)
|
| 552 |
+
vals[rng.integers(0, n, 200)] = float("nan")
|
| 553 |
+
df = pd.DataFrame({"a": vals, "b": rng.integers(0, 5, n)})
|
| 554 |
+
df.to_csv(path, index=False)
|
| 555 |
+
kwds = self._base_kwds(path)
|
| 556 |
+
result = self._parallel_read(path, kwds)
|
| 557 |
+
expected = self._serial_read(path)
|
| 558 |
+
tm.assert_frame_equal(result.reset_index(drop=True), expected)
|
| 559 |
+
|
| 560 |
+
def test_header_none(self, tmp_path):
|
| 561 |
+
path = tmp_path / "data.csv"
|
| 562 |
+
n = 5_000
|
| 563 |
+
rng = np.random.default_rng(3)
|
| 564 |
+
df = pd.DataFrame(rng.integers(0, 100, (n, 4)))
|
| 565 |
+
df.to_csv(path, index=False, header=False)
|
| 566 |
+
kwds = self._base_kwds(path, header=None)
|
| 567 |
+
result = self._parallel_read(path, kwds)
|
| 568 |
+
expected = self._serial_read(path, header=None)
|
| 569 |
+
tm.assert_frame_equal(result.reset_index(drop=True), expected)
|
| 570 |
+
|
| 571 |
+
def test_skiprows_int(self, tmp_path):
|
| 572 |
+
path = tmp_path / "data.csv"
|
| 573 |
+
n = 5_000
|
| 574 |
+
lines = ["skip_me\n"] * 3 + ["a,b\n"] + [f"{i},{i}\n" for i in range(n)]
|
| 575 |
+
path.write_text("".join(lines), encoding="utf-8")
|
| 576 |
+
kwds = self._base_kwds(path, skiprows=3)
|
| 577 |
+
result = self._parallel_read(path, kwds)
|
| 578 |
+
expected = self._serial_read(path, skiprows=3)
|
| 579 |
+
tm.assert_frame_equal(result.reset_index(drop=True), expected)
|
| 580 |
+
|
| 581 |
+
def test_implicit_index_returns_none(self, tmp_path):
|
| 582 |
+
# Data rows have one more field than the header (implicit index).
|
| 583 |
+
# concat(ignore_index=True) would silently drop the index, so the
|
| 584 |
+
# helper must bail out up front (GH#64347).
|
| 585 |
+
path = tmp_path / "implicit.csv"
|
| 586 |
+
lines = "a,b\n" + "".join(f"idx{i},{i},{i * 2}\n" for i in range(5_000))
|
| 587 |
+
path.write_text(lines, encoding="utf-8")
|
| 588 |
+
kwds = self._base_kwds(path)
|
| 589 |
+
assert _read_csv_parallel(str(path), kwds, 4) is None
|
| 590 |
+
|
| 591 |
+
def test_long_first_line_keeps_fine_split(self, tmp_path, monkeypatch):
|
| 592 |
+
# The chunk count comes from an estimated row count. The estimate
|
| 593 |
+
# samples several lines across the data section, so one huge first
|
| 594 |
+
# data line must not collapse the split (or worse, force a serial
|
| 595 |
+
# read via the few-rows bailout) (GH#66275).
|
| 596 |
+
path = tmp_path / "data.csv"
|
| 597 |
+
lines = ["a,b\n", f"0,s{'x' * 50_000}\n"]
|
| 598 |
+
lines += [f"{i},s{i}\n" for i in range(30_000)]
|
| 599 |
+
path.write_text("".join(lines), encoding="utf-8")
|
| 600 |
+
|
| 601 |
+
n_targets = []
|
| 602 |
+
|
| 603 |
+
def spy(filepath, n_chunks, data_start, *args):
|
| 604 |
+
n_targets.append(n_chunks)
|
| 605 |
+
return _find_chunk_byte_offsets(filepath, n_chunks, data_start, *args)
|
| 606 |
+
|
| 607 |
+
monkeypatch.setattr("pandas.io.parsers.readers._find_chunk_byte_offsets", spy)
|
| 608 |
+
kwds = self._base_kwds(path)
|
| 609 |
+
result = _read_csv_parallel(str(path), kwds, 4)
|
| 610 |
+
assert result is not None
|
| 611 |
+
expected = self._serial_read(path)
|
| 612 |
+
tm.assert_frame_equal(result.reset_index(drop=True), expected)
|
| 613 |
+
# 30k rows over the 2000-row chunk floor supports the full 4*3
|
| 614 |
+
# split; an estimate from the first line alone would give 2 chunks.
|
| 615 |
+
assert n_targets[0] >= 10
|
| 616 |
+
|
| 617 |
+
def test_few_estimated_rows_returns_none(self, tmp_path):
|
| 618 |
+
# ~300 long rows: even a 2-way split would leave each chunk far
|
| 619 |
+
# below _PARALLEL_MIN_CHUNK_ROWS, and the file is small enough that
|
| 620 |
+
# the per-chunk per-column fixed costs would outweigh the
|
| 621 |
+
# parallelism (GH#66275).
|
| 622 |
+
path = tmp_path / "wide.csv"
|
| 623 |
+
header = ",".join(f"c{i}" for i in range(500)) + "\n"
|
| 624 |
+
row = ",".join(["123456789"] * 500) + "\n"
|
| 625 |
+
path.write_text(header + row * 300, encoding="utf-8")
|
| 626 |
+
kwds = self._base_kwds(path)
|
| 627 |
+
assert _read_csv_parallel(str(path), kwds, 4) is None
|
| 628 |
+
|
| 629 |
+
def test_blank_first_data_line_returns_none(self, tmp_path):
|
| 630 |
+
# header=None with a blank first data line: name inference parses a
|
| 631 |
+
# single blank line and raises EmptyDataError, which must be turned
|
| 632 |
+
# into a serial fallback rather than propagate (GH#66259).
|
| 633 |
+
path = tmp_path / "blank_first.csv"
|
| 634 |
+
path.write_text(
|
| 635 |
+
"\n" + "".join(f"{i},{i * 2}\n" for i in range(5_000)), encoding="utf-8"
|
| 636 |
+
)
|
| 637 |
+
kwds = self._base_kwds(path, header=None)
|
| 638 |
+
assert _read_csv_parallel(str(path), kwds, 4) is None
|
| 639 |
+
|
| 640 |
+
def test_quoted_newline_in_header_returns_none(self, tmp_path):
|
| 641 |
+
# A quoted embedded newline in the header makes the physical line
|
| 642 |
+
# count disagree with the logical row count, so data_start would land
|
| 643 |
+
# mid-header and chunk 0 would inject a garbage row (GH#64347).
|
| 644 |
+
path = tmp_path / "hdr.csv"
|
| 645 |
+
lines = '"col\n1",col2\n' + "".join(f"x{i},y{i}\n" for i in range(5_000))
|
| 646 |
+
path.write_text(lines, encoding="utf-8")
|
| 647 |
+
kwds = self._base_kwds(path)
|
| 648 |
+
assert _read_csv_parallel(str(path), kwds, 4) is None
|
| 649 |
+
|
| 650 |
+
def test_bare_cr_before_data_returns_none(self, tmp_path):
|
| 651 |
+
# The tokenizer ends a line at a bare \r but _find_data_start_offset
|
| 652 |
+
# does not, so data_start may be misplaced. CRLF stays parallel.
|
| 653 |
+
path = tmp_path / "cr.csv"
|
| 654 |
+
body = b"".join(f"x{i},y{i}\n".encode() for i in range(5_000))
|
| 655 |
+
path.write_bytes(b"a,b\rc,d\n\n" + body)
|
| 656 |
+
kwds = self._base_kwds(path)
|
| 657 |
+
assert _read_csv_parallel(str(path), kwds, 4) is None
|
| 658 |
+
path.write_bytes(b"a,b\r\nc,d\r\n\r\n" + body)
|
| 659 |
+
assert _read_csv_parallel(str(path), kwds, 4) is not None
|
| 660 |
+
|
| 661 |
+
def test_dtype_specified(self, tmp_path):
|
| 662 |
+
path = tmp_path / "data.csv"
|
| 663 |
+
n = 5_000
|
| 664 |
+
rng = np.random.default_rng(5)
|
| 665 |
+
df = pd.DataFrame({"a": rng.integers(0, 100, n), "b": rng.integers(0, 100, n)})
|
| 666 |
+
df.to_csv(path, index=False)
|
| 667 |
+
kwds = self._base_kwds(path, dtype={"a": "float64", "b": "float64"})
|
| 668 |
+
result = self._parallel_read(path, kwds)
|
| 669 |
+
expected = self._serial_read(path, dtype={"a": "float64", "b": "float64"})
|
| 670 |
+
tm.assert_frame_equal(result.reset_index(drop=True), expected)
|
| 671 |
+
|
| 672 |
+
def test_dict_dtype_duplicate_names_falls_back(self, tmp_path):
|
| 673 |
+
# A dict dtype keyed on a duplicated header name must return None so the
|
| 674 |
+
# caller re-reads serially; the same dtype on unique names must still
|
| 675 |
+
# parallelize (GH#64347).
|
| 676 |
+
path = tmp_path / "data.csv"
|
| 677 |
+
body = "".join(f"{i},{i + 1}\n" for i in range(5_000))
|
| 678 |
+
|
| 679 |
+
path.write_text("a,a\n" + body, encoding="utf-8")
|
| 680 |
+
kwds = self._base_kwds(path, dtype={"a": str})
|
| 681 |
+
assert _read_csv_parallel(str(path), kwds, 4) is None
|
| 682 |
+
|
| 683 |
+
path.write_text("a,b\n" + body, encoding="utf-8")
|
| 684 |
+
kwds = self._base_kwds(path, dtype={"a": str})
|
| 685 |
+
assert _read_csv_parallel(str(path), kwds, 4) is not None
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
# ---------------------------------------------------------------------------
|
| 689 |
+
# Embedded newlines in quoted fields
|
| 690 |
+
# ---------------------------------------------------------------------------
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
@pytest.mark.parametrize(
|
| 694 |
+
"csv_bytes,expected_rows",
|
| 695 |
+
[
|
| 696 |
+
# Simple embedded newline
|
| 697 |
+
pytest.param(
|
| 698 |
+
b'a,b,c\n1,"hello\nworld",3\n4,normal,6\n',
|
| 699 |
+
2,
|
| 700 |
+
id="simple_embedded_newline",
|
| 701 |
+
),
|
| 702 |
+
# Embedded newline where the text after looks like a complete data row
|
| 703 |
+
# (the most dangerous case for silent corruption)
|
| 704 |
+
pytest.param(
|
| 705 |
+
b'a,b,c\n1,"hello\n2,foo,bar",3\n100,baz,200\n',
|
| 706 |
+
2,
|
| 707 |
+
id="adversarial_after_split_looks_like_full_row",
|
| 708 |
+
),
|
| 709 |
+
# Multiple embedded newlines in the same file
|
| 710 |
+
pytest.param(
|
| 711 |
+
b'a,b\n1,"line1\nline2\nline3"\n2,normal\n3,"also\nembedded"\n',
|
| 712 |
+
3,
|
| 713 |
+
id="multiple_embedded_newlines",
|
| 714 |
+
),
|
| 715 |
+
],
|
| 716 |
+
)
|
| 717 |
+
def test_embedded_newline_falls_back_to_serial(
|
| 718 |
+
tmp_path, monkeypatch, csv_bytes, expected_rows
|
| 719 |
+
):
|
| 720 |
+
"""
|
| 721 |
+
CSV files with newlines inside quoted fields must produce the same result
|
| 722 |
+
as a direct serial read. The parallel path either parses correctly (when
|
| 723 |
+
the split misses the embedded newline) or falls back to serial (when it
|
| 724 |
+
hits it). Silent data corruption must never occur.
|
| 725 |
+
"""
|
| 726 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 727 |
+
path = tmp_path / "embedded.csv"
|
| 728 |
+
path.write_bytes(csv_bytes)
|
| 729 |
+
|
| 730 |
+
serial = pd.read_csv(io.BytesIO(csv_bytes))
|
| 731 |
+
parallel = pd.read_csv(path) # may take parallel path or fall back
|
| 732 |
+
|
| 733 |
+
assert len(parallel) == expected_rows
|
| 734 |
+
tm.assert_frame_equal(
|
| 735 |
+
parallel.reset_index(drop=True), serial.reset_index(drop=True)
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
# ---------------------------------------------------------------------------
|
| 740 |
+
# Integration: automatic activation through read_csv()
|
| 741 |
+
# ---------------------------------------------------------------------------
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
def test_read_csv_auto_parallel(tmp_path, monkeypatch):
|
| 745 |
+
"""
|
| 746 |
+
read_csv() transparently uses the parallel path for large local files.
|
| 747 |
+
Result must match the serial read obtained via engine='python'.
|
| 748 |
+
"""
|
| 749 |
+
path = tmp_path / "big.csv"
|
| 750 |
+
_make_large_csv(path)
|
| 751 |
+
# Lower the threshold so any file triggers the parallel path.
|
| 752 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 753 |
+
|
| 754 |
+
# Force the parallel path regardless of the host's CPU allocation (a
|
| 755 |
+
# single usable CPU defaults to serial) so this exercises parallel ==
|
| 756 |
+
# serial everywhere.
|
| 757 |
+
with pd.option_context("mode.max_threads", 4):
|
| 758 |
+
result = pd.read_csv(path) # auto-selects parallel path for C engine
|
| 759 |
+
expected = pd.read_csv(path, engine="python")
|
| 760 |
+
tm.assert_frame_equal(result, expected)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def test_read_csv_parallel_non_bool_memory_map(tmp_path, monkeypatch):
|
| 764 |
+
# GH#68341 a non-bool must be rejected whatever the file size, i.e. the
|
| 765 |
+
# parallel path must not swallow it
|
| 766 |
+
path = tmp_path / "big.csv"
|
| 767 |
+
_make_large_csv(path)
|
| 768 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 769 |
+
|
| 770 |
+
msg = 'For argument "memory_map" expected type bool'
|
| 771 |
+
with pd.option_context("mode.max_threads", 4):
|
| 772 |
+
with pytest.raises(ValueError, match=msg):
|
| 773 |
+
pd.read_csv(path, memory_map="False")
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so the spy sees no call")
|
| 777 |
+
def test_read_csv_parallel_vs_serial_large_file(tmp_path, monkeypatch):
|
| 778 |
+
"""
|
| 779 |
+
For a file that exceeds the threshold, the parallel result equals the
|
| 780 |
+
result from a direct serial C-engine read (with parallelism forced off).
|
| 781 |
+
"""
|
| 782 |
+
path = tmp_path / "big.csv"
|
| 783 |
+
_make_large_csv(path)
|
| 784 |
+
# Lower the threshold so any file triggers the parallel path.
|
| 785 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 786 |
+
|
| 787 |
+
serial = pd.read_csv(path, engine="python")
|
| 788 |
+
outcomes = _track_parallel(monkeypatch)
|
| 789 |
+
# Force the parallel path so this runs even on a single-CPU allocation.
|
| 790 |
+
with pd.option_context("mode.max_threads", 4):
|
| 791 |
+
parallel = pd.read_csv(path, engine="c")
|
| 792 |
+
tm.assert_frame_equal(parallel, serial)
|
| 793 |
+
assert outcomes == ["used"]
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
@pytest.mark.parametrize("platform_name", ["linux", "darwin", "win32"])
|
| 797 |
+
def test_parallel_on_by_default(tmp_path, monkeypatch, platform_name):
|
| 798 |
+
"""The parallel path is on by default on every threaded platform."""
|
| 799 |
+
path = tmp_path / "big.csv"
|
| 800 |
+
_make_large_csv(path)
|
| 801 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 802 |
+
# Pin the default so the test does not depend on the host's actual core
|
| 803 |
+
# count, or on how many CPUs a container/affinity mask leaves the runner --
|
| 804 |
+
# one usable CPU would make the default serial everywhere.
|
| 805 |
+
monkeypatch.setattr(_readers.os, "cpu_count", lambda: 4)
|
| 806 |
+
monkeypatch.setattr(_readers, "available_cpu_count", lambda: None)
|
| 807 |
+
|
| 808 |
+
# Stub the parallel reader so this exercises only the platform-gating
|
| 809 |
+
# decision. Calling the real one would start threads, which fails on
|
| 810 |
+
# no-thread platforms such as Pyodide/WASM.
|
| 811 |
+
calls = []
|
| 812 |
+
|
| 813 |
+
def stub(*args, **kwargs):
|
| 814 |
+
calls.append(args)
|
| 815 |
+
return pd.DataFrame()
|
| 816 |
+
|
| 817 |
+
monkeypatch.setattr(_readers, "_read_csv_parallel", stub)
|
| 818 |
+
monkeypatch.setattr(_readers.sys, "platform", platform_name)
|
| 819 |
+
|
| 820 |
+
pd.read_csv(path)
|
| 821 |
+
assert len(calls) == 1
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
def test_parallel_default_off_on_wasm(tmp_path, monkeypatch):
|
| 825 |
+
"""Emscripten cannot spawn threads, so it stays serial."""
|
| 826 |
+
path = tmp_path / "big.csv"
|
| 827 |
+
_make_large_csv(path)
|
| 828 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 829 |
+
monkeypatch.setattr(_readers.os, "cpu_count", lambda: 4)
|
| 830 |
+
monkeypatch.setattr(_readers, "available_cpu_count", lambda: None)
|
| 831 |
+
|
| 832 |
+
calls = []
|
| 833 |
+
|
| 834 |
+
def stub(*args, **kwargs):
|
| 835 |
+
calls.append(args)
|
| 836 |
+
return pd.DataFrame()
|
| 837 |
+
|
| 838 |
+
monkeypatch.setattr(_readers, "_read_csv_parallel", stub)
|
| 839 |
+
monkeypatch.setattr(_readers.sys, "platform", "emscripten")
|
| 840 |
+
|
| 841 |
+
pd.read_csv(path)
|
| 842 |
+
assert calls == []
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
def test_parallel_default_thread_cap(tmp_path, monkeypatch):
|
| 846 |
+
"""The default worker count is capped at 6, regardless of core count."""
|
| 847 |
+
path = tmp_path / "big.csv"
|
| 848 |
+
_make_large_csv(path)
|
| 849 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 850 |
+
monkeypatch.setattr(_readers.sys, "platform", "linux")
|
| 851 |
+
# More cores than the cap: the default should clamp down to 6.
|
| 852 |
+
monkeypatch.setattr(_readers.os, "cpu_count", lambda: 16)
|
| 853 |
+
# Otherwise a CI runner with fewer than 6 usable CPUs clamps below the cap
|
| 854 |
+
# and this test measures the runner, not the cap.
|
| 855 |
+
monkeypatch.setattr(_readers, "available_cpu_count", lambda: None)
|
| 856 |
+
|
| 857 |
+
workers = []
|
| 858 |
+
|
| 859 |
+
def stub(_path, _kwds, n_workers):
|
| 860 |
+
workers.append(n_workers)
|
| 861 |
+
return pd.DataFrame()
|
| 862 |
+
|
| 863 |
+
monkeypatch.setattr(_readers, "_read_csv_parallel", stub)
|
| 864 |
+
|
| 865 |
+
pd.read_csv(path)
|
| 866 |
+
assert workers == [6]
|
| 867 |
+
|
| 868 |
+
# An explicit mode.max_threads still overrides the cap.
|
| 869 |
+
workers.clear()
|
| 870 |
+
with pd.option_context("mode.max_threads", 8):
|
| 871 |
+
pd.read_csv(path)
|
| 872 |
+
assert workers == [8]
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ---------------------------------------------------------------------------
|
| 876 |
+
# _default_n_workers
|
| 877 |
+
# ---------------------------------------------------------------------------
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
class TestDefaultNWorkers:
|
| 881 |
+
"""Unit tests for the default worker count."""
|
| 882 |
+
|
| 883 |
+
@pytest.mark.parametrize("platform_name", ["linux", "darwin", "win32"])
|
| 884 |
+
@pytest.mark.parametrize(
|
| 885 |
+
"cpu_count, available, expected",
|
| 886 |
+
[
|
| 887 |
+
(2, None, 2), # unconstrained, below the cap -> logical CPU count
|
| 888 |
+
(16, None, 6), # cap binds
|
| 889 |
+
(16, 1, 1), # single-CPU container
|
| 890 |
+
(16, 2, 2), # cgroup/affinity tighter than the cap
|
| 891 |
+
(16, 8, 6), # allocation looser than the cap -> cap still binds
|
| 892 |
+
(2, 8, 2), # allocation looser than the machine
|
| 893 |
+
],
|
| 894 |
+
)
|
| 895 |
+
def test_combines_cap_and_allocation(
|
| 896 |
+
self, monkeypatch, cpu_count, available, expected, platform_name
|
| 897 |
+
):
|
| 898 |
+
# Default = min(logical CPUs, available CPUs, _MAX_DEFAULT_WORKERS),
|
| 899 |
+
# on every threaded platform.
|
| 900 |
+
assert _readers._MAX_DEFAULT_WORKERS == 6
|
| 901 |
+
monkeypatch.setattr(_readers.sys, "platform", platform_name)
|
| 902 |
+
monkeypatch.setattr(_readers.os, "cpu_count", lambda: cpu_count)
|
| 903 |
+
monkeypatch.setattr(_readers, "available_cpu_count", lambda: available)
|
| 904 |
+
with pd.option_context("mode.max_threads", None):
|
| 905 |
+
assert _default_n_workers() == expected
|
| 906 |
+
|
| 907 |
+
def test_wasm_is_serial(self, monkeypatch):
|
| 908 |
+
monkeypatch.setattr(_readers.sys, "platform", "emscripten")
|
| 909 |
+
# WASM stays serial even if a worker count is requested explicitly.
|
| 910 |
+
with pd.option_context("mode.max_threads", 8):
|
| 911 |
+
assert _default_n_workers() == 1
|
| 912 |
+
|
| 913 |
+
def test_max_threads_exceeds_cap(self, monkeypatch):
|
| 914 |
+
# _MAX_DEFAULT_WORKERS and the availability clamp bound the *default*
|
| 915 |
+
# only. The mode.max_threads docs promise an explicit setting still
|
| 916 |
+
# wins.
|
| 917 |
+
monkeypatch.setattr(_readers.sys, "platform", "linux")
|
| 918 |
+
monkeypatch.setattr(_readers.os, "cpu_count", lambda: 2)
|
| 919 |
+
monkeypatch.setattr(_readers, "available_cpu_count", lambda: 1)
|
| 920 |
+
with pd.option_context("mode.max_threads", 32):
|
| 921 |
+
assert _default_n_workers() == 32
|
| 922 |
+
|
| 923 |
+
@pytest.mark.parametrize("platform_name", ["linux", "win32"])
|
| 924 |
+
def test_max_threads_wins(self, monkeypatch, platform_name):
|
| 925 |
+
monkeypatch.setattr(_readers.sys, "platform", platform_name)
|
| 926 |
+
with pd.option_context("mode.max_threads", 3):
|
| 927 |
+
assert _default_n_workers() == 3
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
# ---------------------------------------------------------------------------
|
| 931 |
+
# Regression tests: inputs the parallel path must hand back to serial
|
| 932 |
+
# (all results must be identical to a serial read of the same bytes)
|
| 933 |
+
# ---------------------------------------------------------------------------
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
def _read_forced_parallel(path, monkeypatch, **kwargs):
|
| 937 |
+
"""read_csv with the parallel path force-enabled on every platform."""
|
| 938 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 939 |
+
with pd.option_context("mode.max_threads", 4):
|
| 940 |
+
return pd.read_csv(path, **kwargs)
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
def test_parallel_latin1_matches_serial(tmp_path, monkeypatch):
|
| 944 |
+
# Non-UTF-8 encodings must take the serial path; the C tokenizer decodes
|
| 945 |
+
# raw chunk bytes as UTF-8 (GH#64347).
|
| 946 |
+
raw = b"col1,col2\n" + b"".join(
|
| 947 |
+
f"se\xf1or{i},{i}\n".encode("latin-1") for i in range(500)
|
| 948 |
+
)
|
| 949 |
+
path = tmp_path / "latin.csv"
|
| 950 |
+
path.write_bytes(raw)
|
| 951 |
+
|
| 952 |
+
result = _read_forced_parallel(path, monkeypatch, encoding="latin-1")
|
| 953 |
+
expected = pd.read_csv(io.BytesIO(raw), encoding="latin-1")
|
| 954 |
+
tm.assert_frame_equal(result, expected)
|
| 955 |
+
assert result.loc[0, "col1"] == "se\xf1or0"
|
| 956 |
+
|
| 957 |
+
|
| 958 |
+
def test_parallel_ascii_non_ascii_byte_matches_serial(tmp_path, monkeypatch):
|
| 959 |
+
# encoding="ascii" with a non-ASCII (but valid UTF-8) byte deep in the
|
| 960 |
+
# file: the serial path raises UnicodeDecodeError, but the workers decode
|
| 961 |
+
# chunk bytes as UTF-8 and would silently succeed, so ascii must take the
|
| 962 |
+
# serial path (GH#64347).
|
| 963 |
+
raw = (
|
| 964 |
+
b"a,b\n"
|
| 965 |
+
+ b"".join(f"{i},x{i}\n".encode() for i in range(500))
|
| 966 |
+
+ b"500,\xc3\xa9\n" # U+00E9 (é): valid UTF-8, not ASCII
|
| 967 |
+
+ b"".join(f"{i},x{i}\n".encode() for i in range(501, 1000))
|
| 968 |
+
)
|
| 969 |
+
path = tmp_path / "ascii.csv"
|
| 970 |
+
path.write_bytes(raw)
|
| 971 |
+
|
| 972 |
+
msg = "'ascii' codec can't decode"
|
| 973 |
+
with pytest.raises(UnicodeDecodeError, match=msg):
|
| 974 |
+
_read_forced_parallel(path, monkeypatch, encoding="ascii")
|
| 975 |
+
with pytest.raises(UnicodeDecodeError, match=msg):
|
| 976 |
+
pd.read_csv(io.BytesIO(raw), encoding="ascii")
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
def test_parallel_dup_names_dict_dtype_matches_serial(tmp_path, monkeypatch):
|
| 980 |
+
# A dict dtype keyed on a duplicated header name is applied by serial to
|
| 981 |
+
# every de-duplicated column ("a" and "a.1"), but the workers receive the
|
| 982 |
+
# already de-duplicated names and would match only "a". The parallel path
|
| 983 |
+
# must recover the raw header names and hand back to serial (GH#64347).
|
| 984 |
+
raw = b"a,a\n" + b"".join(f"{i},{i + 1}\n".encode() for i in range(500))
|
| 985 |
+
path = tmp_path / "dup.csv"
|
| 986 |
+
path.write_bytes(raw)
|
| 987 |
+
|
| 988 |
+
result = _read_forced_parallel(path, monkeypatch, dtype={"a": str})
|
| 989 |
+
expected = pd.read_csv(io.BytesIO(raw), dtype={"a": str})
|
| 990 |
+
tm.assert_frame_equal(result, expected)
|
| 991 |
+
# the dtype reaches BOTH duplicated columns, not just the first
|
| 992 |
+
assert result.dtypes["a"] == result.dtypes["a.1"]
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def test_parallel_comment_before_header_matches_serial(tmp_path, monkeypatch):
|
| 996 |
+
# A full-line comment above the header shifts the preamble byte offset;
|
| 997 |
+
# the header row must not be ingested as data (GH#64347).
|
| 998 |
+
raw = b"# a comment\ncol1,col2\n" + b"".join(
|
| 999 |
+
f"{i},{i * 2}\n".encode() for i in range(500)
|
| 1000 |
+
)
|
| 1001 |
+
path = tmp_path / "comment.csv"
|
| 1002 |
+
path.write_bytes(raw)
|
| 1003 |
+
|
| 1004 |
+
result = _read_forced_parallel(path, monkeypatch, comment="#")
|
| 1005 |
+
expected = pd.read_csv(io.BytesIO(raw), comment="#")
|
| 1006 |
+
tm.assert_frame_equal(result, expected)
|
| 1007 |
+
assert result["col1"].dtype == np.int64
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
def test_parallel_blank_line_before_header_matches_serial(tmp_path, monkeypatch):
|
| 1011 |
+
# Same as the comment case, but triggered by a plain blank line (GH#64347).
|
| 1012 |
+
raw = b"\ncol1,col2\n" + b"".join(f"{i},{i * 2}\n".encode() for i in range(500))
|
| 1013 |
+
path = tmp_path / "blank.csv"
|
| 1014 |
+
path.write_bytes(raw)
|
| 1015 |
+
|
| 1016 |
+
result = _read_forced_parallel(path, monkeypatch)
|
| 1017 |
+
expected = pd.read_csv(io.BytesIO(raw))
|
| 1018 |
+
tm.assert_frame_equal(result, expected)
|
| 1019 |
+
assert result["col1"].dtype == np.int64
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
@pytest.mark.parametrize(
|
| 1023 |
+
"head,kwargs",
|
| 1024 |
+
[
|
| 1025 |
+
(b'a,"line\nbreak",c\rFIRST,ROW,HERE\n', {}),
|
| 1026 |
+
(b"a,b,c\rFIRST,ROW,HERE\n\n", {}),
|
| 1027 |
+
(b"junk\ra,b,c\nFIRST,ROW,HERE\n\n", {"skiprows": 1}),
|
| 1028 |
+
(b"junk\rFIRST,ROW,HERE\n\n", {"skiprows": 1, "header": None}),
|
| 1029 |
+
],
|
| 1030 |
+
)
|
| 1031 |
+
def test_parallel_bare_cr_before_data_matches_serial(
|
| 1032 |
+
tmp_path, monkeypatch, head, kwargs
|
| 1033 |
+
):
|
| 1034 |
+
# A bare \r before the first data row used to misplace the first chunk's
|
| 1035 |
+
# start, silently dropping FIRST,ROW,HERE or adding a junk row.
|
| 1036 |
+
raw = head + b"".join(f"s{i},t{i},u{i}\n".encode() for i in range(500))
|
| 1037 |
+
path = tmp_path / "bare_cr.csv"
|
| 1038 |
+
path.write_bytes(raw)
|
| 1039 |
+
|
| 1040 |
+
result = _read_forced_parallel(path, monkeypatch, **kwargs)
|
| 1041 |
+
expected = pd.read_csv(io.BytesIO(raw), **kwargs)
|
| 1042 |
+
tm.assert_frame_equal(result, expected)
|
| 1043 |
+
assert result.iloc[0].tolist() == ["FIRST", "ROW", "HERE"]
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
@pytest.mark.parametrize(
|
| 1047 |
+
"preamble,skiprows",
|
| 1048 |
+
[
|
| 1049 |
+
(b"\n", 0),
|
| 1050 |
+
(b" \n", 0),
|
| 1051 |
+
(b"junk1\njunk2\n\n", 2),
|
| 1052 |
+
],
|
| 1053 |
+
)
|
| 1054 |
+
def test_parallel_blank_first_data_line_matches_serial(
|
| 1055 |
+
tmp_path, monkeypatch, preamble, skiprows
|
| 1056 |
+
):
|
| 1057 |
+
# header=None puts no header line in the preamble, so a blank first data
|
| 1058 |
+
# line ends up as the single line name inference parses, and that raises
|
| 1059 |
+
# EmptyDataError where the serial path just skips it (GH#66259). A
|
| 1060 |
+
# whitespace-only line must not tokenize as a single field either: that
|
| 1061 |
+
# would infer one column and silently read the rest as an implicit index.
|
| 1062 |
+
raw = preamble + b"".join(f"{i},{i * 2}\n".encode() for i in range(500))
|
| 1063 |
+
path = tmp_path / "blank_first.csv"
|
| 1064 |
+
path.write_bytes(raw)
|
| 1065 |
+
|
| 1066 |
+
result = _read_forced_parallel(path, monkeypatch, header=None, skiprows=skiprows)
|
| 1067 |
+
expected = pd.read_csv(io.BytesIO(raw), header=None, skiprows=skiprows)
|
| 1068 |
+
tm.assert_frame_equal(result, expected)
|
| 1069 |
+
assert result.shape == (500, 2)
|
| 1070 |
+
|
| 1071 |
+
|
| 1072 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so the spy sees no call")
|
| 1073 |
+
def test_parallel_all_blank_lines_raises(tmp_path, monkeypatch):
|
| 1074 |
+
# The fallback for a blank first data line must not mask a file that has
|
| 1075 |
+
# no columns at all: serial raises, so the parallel path must too
|
| 1076 |
+
# (GH#66259).
|
| 1077 |
+
path = tmp_path / "blank_only.csv"
|
| 1078 |
+
path.write_bytes(b"\n" * 500)
|
| 1079 |
+
|
| 1080 |
+
returned = []
|
| 1081 |
+
|
| 1082 |
+
def spy(filepath, kwds, n_workers):
|
| 1083 |
+
result = _read_csv_parallel(filepath, kwds, n_workers)
|
| 1084 |
+
returned.append(result)
|
| 1085 |
+
return result
|
| 1086 |
+
|
| 1087 |
+
monkeypatch.setattr("pandas.io.parsers.readers._read_csv_parallel", spy)
|
| 1088 |
+
|
| 1089 |
+
msg = "No columns to parse from file"
|
| 1090 |
+
with pytest.raises(EmptyDataError, match=msg):
|
| 1091 |
+
_read_forced_parallel(path, monkeypatch, header=None)
|
| 1092 |
+
# The serial read raises the same error, so without this the test would
|
| 1093 |
+
# pass even if the parallel path propagated it directly.
|
| 1094 |
+
assert returned == [None], "the parallel path did not fall back"
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
def test_parallel_single_long_line(tmp_path, monkeypatch):
|
| 1098 |
+
# A data section with no interior newlines cannot be split; this must
|
| 1099 |
+
# fall back to serial instead of raising (GH#64347).
|
| 1100 |
+
raw = b"col1,col2\n" + b"a" * 5_000 + b",b"
|
| 1101 |
+
path = tmp_path / "longline.csv"
|
| 1102 |
+
path.write_bytes(raw)
|
| 1103 |
+
|
| 1104 |
+
result = _read_forced_parallel(path, monkeypatch)
|
| 1105 |
+
expected = pd.read_csv(io.BytesIO(raw))
|
| 1106 |
+
tm.assert_frame_equal(result, expected)
|
| 1107 |
+
|
| 1108 |
+
|
| 1109 |
+
@pytest.mark.skipif(WASM, reason="WASM cannot spawn threads, so no split happens")
|
| 1110 |
+
def test_parallel_long_line_keeps_the_split(tmp_path, monkeypatch):
|
| 1111 |
+
# A line covering the middle of the file swallows the interior split
|
| 1112 |
+
# targets. The boundaries after it must survive: the results are correct
|
| 1113 |
+
# either way, so a collapse is invisible except as lost parallelism, which
|
| 1114 |
+
# is what this asserts (GH#66392).
|
| 1115 |
+
path = tmp_path / "data.csv"
|
| 1116 |
+
blob = "1," + "9" * 39_995 + "\n" # 40 KB, covering 20-60% of the data
|
| 1117 |
+
path.write_text(
|
| 1118 |
+
"a,b\n" + "1,2\n" * 5_000 + blob + "1,2\n" * 10_000, encoding="utf-8"
|
| 1119 |
+
)
|
| 1120 |
+
|
| 1121 |
+
chunk_counts = []
|
| 1122 |
+
|
| 1123 |
+
def spy(filepath, n_chunks, data_start, *args):
|
| 1124 |
+
offsets = _find_chunk_byte_offsets(filepath, n_chunks, data_start, *args)
|
| 1125 |
+
chunk_counts.append(len(offsets) - 1)
|
| 1126 |
+
return offsets
|
| 1127 |
+
|
| 1128 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 1129 |
+
monkeypatch.setattr("pandas.io.parsers.readers._find_chunk_byte_offsets", spy)
|
| 1130 |
+
|
| 1131 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1132 |
+
expected = pd.read_csv(path)
|
| 1133 |
+
with pd.option_context("mode.max_threads", 4):
|
| 1134 |
+
result = pd.read_csv(path)
|
| 1135 |
+
tm.assert_frame_equal(result, expected)
|
| 1136 |
+
# Two of the interior targets land inside the long line; giving up at the
|
| 1137 |
+
# first leaves 2 chunks no matter how many workers were asked for.
|
| 1138 |
+
assert chunk_counts, "the parallel path did not run"
|
| 1139 |
+
assert chunk_counts[0] >= 3
|
| 1140 |
+
|
| 1141 |
+
|
| 1142 |
+
def test_parallel_mixed_dtype_column_matches_serial(tmp_path, monkeypatch):
|
| 1143 |
+
# A numeric column whose only non-numeric row sits in one chunk parses as
|
| 1144 |
+
# int64 in the clean chunks but object in the dirty one; serial gives
|
| 1145 |
+
# strings for the whole column. The parallel path must detect the
|
| 1146 |
+
# disagreement and re-read serially (GH#64347).
|
| 1147 |
+
clean = b"".join(f"{i},{i}\n".encode() for i in range(500))
|
| 1148 |
+
raw = b"col1,col2\n" + clean + b"oops,999\n" + clean
|
| 1149 |
+
path = tmp_path / "mixed.csv"
|
| 1150 |
+
path.write_bytes(raw)
|
| 1151 |
+
|
| 1152 |
+
result = _read_forced_parallel(path, monkeypatch)
|
| 1153 |
+
expected = pd.read_csv(io.BytesIO(raw))
|
| 1154 |
+
tm.assert_frame_equal(result, expected)
|
| 1155 |
+
# serial semantics: the whole column stays as strings
|
| 1156 |
+
assert result.loc[0, "col1"] == "0"
|
| 1157 |
+
|
| 1158 |
+
|
| 1159 |
+
def test_parallel_deferred_strings_pyarrow_backend(tmp_path, monkeypatch):
|
| 1160 |
+
# dtype_backend="pyarrow" builds pa.string() (int32 offset) pending columns
|
| 1161 |
+
# rather than the large_string ones the default string dtype uses; the
|
| 1162 |
+
# gather must reconcile them to ArrowDtype and match a serial read
|
| 1163 |
+
# (GH#66277).
|
| 1164 |
+
pytest.importorskip("pyarrow")
|
| 1165 |
+
path = tmp_path / "data.csv"
|
| 1166 |
+
rows = "\n".join(f"s{i % 13},{i}" for i in range(5000))
|
| 1167 |
+
path.write_text("a,b\n" + rows + "\n", encoding="utf-8")
|
| 1168 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 1169 |
+
|
| 1170 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1171 |
+
serial = pd.read_csv(path, dtype_backend="pyarrow")
|
| 1172 |
+
with pd.option_context("mode.max_threads", 4):
|
| 1173 |
+
parallel = pd.read_csv(path, dtype_backend="pyarrow")
|
| 1174 |
+
tm.assert_frame_equal(parallel, serial)
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
@pytest.mark.filterwarnings(
|
| 1178 |
+
"ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning"
|
| 1179 |
+
)
|
| 1180 |
+
def test_parallel_deferred_strings_token_width_tiers(tmp_path, monkeypatch):
|
| 1181 |
+
# The deferred string path fills each chunk's data buffer with the same
|
| 1182 |
+
# fixed-width token copy the serial path uses, so widths straddling that
|
| 1183 |
+
# copy's 16- and 32-byte tiers have to survive a chunked read too, where
|
| 1184 |
+
# each worker sizes and fills its own chunk's buffer (GH#66756).
|
| 1185 |
+
pytest.importorskip("pyarrow")
|
| 1186 |
+
widths = [1, 2, 15, 16, 17, 31, 32, 33, 64]
|
| 1187 |
+
values = [
|
| 1188 |
+
"".join(chr(ord("a") + pos % 26) for pos in range(width)) for width in widths
|
| 1189 |
+
]
|
| 1190 |
+
path = tmp_path / "tiers.csv"
|
| 1191 |
+
rows = "".join(f"{value},{value.upper()}\n" for value in values * 400)
|
| 1192 |
+
path.write_text("a,b\n" + rows, encoding="utf-8")
|
| 1193 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 1194 |
+
|
| 1195 |
+
# Both options are pinned rather than inherited: the fast path needs
|
| 1196 |
+
# infer_string on *and* pyarrow storage, and under either default flipped
|
| 1197 |
+
# (PANDAS_FUTURE_INFER_STRING=0, mode.string_storage="python") the columns
|
| 1198 |
+
# would come back from the object path instead; the dtype check below
|
| 1199 |
+
# fails loudly if that happens.
|
| 1200 |
+
with pd.option_context(
|
| 1201 |
+
"future.infer_string",
|
| 1202 |
+
True,
|
| 1203 |
+
"mode.string_storage",
|
| 1204 |
+
"pyarrow",
|
| 1205 |
+
"mode.max_threads",
|
| 1206 |
+
1,
|
| 1207 |
+
):
|
| 1208 |
+
serial = pd.read_csv(path)
|
| 1209 |
+
with pd.option_context(
|
| 1210 |
+
"future.infer_string",
|
| 1211 |
+
True,
|
| 1212 |
+
"mode.string_storage",
|
| 1213 |
+
"pyarrow",
|
| 1214 |
+
"mode.max_threads",
|
| 1215 |
+
4,
|
| 1216 |
+
):
|
| 1217 |
+
parallel = pd.read_csv(path)
|
| 1218 |
+
tm.assert_frame_equal(parallel, serial)
|
| 1219 |
+
assert serial["a"].dtype == pd.StringDtype("pyarrow", na_value=np.nan)
|
| 1220 |
+
assert serial["a"].tolist() == values * 400
|
| 1221 |
+
|
| 1222 |
+
|
| 1223 |
+
def test_parallel_deferred_strings_mixed_chunk_dtypes(tmp_path, monkeypatch):
|
| 1224 |
+
# One chunk of a column parses as strings while the rest parse as int64,
|
| 1225 |
+
# so the gather sees pending string columns alongside numeric ones and must
|
| 1226 |
+
# fall back to a serial re-read rather than mixing the two (GH#66277).
|
| 1227 |
+
chunk = "".join(f"{i},{i}\n" for i in range(2000))
|
| 1228 |
+
raw = "col1,col2\n" + chunk + "text,7\n" + chunk
|
| 1229 |
+
path = tmp_path / "mixed_str.csv"
|
| 1230 |
+
path.write_text(raw, encoding="utf-8")
|
| 1231 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 1232 |
+
|
| 1233 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1234 |
+
serial = pd.read_csv(path)
|
| 1235 |
+
with pd.option_context("mode.max_threads", 4):
|
| 1236 |
+
parallel = pd.read_csv(path)
|
| 1237 |
+
tm.assert_frame_equal(parallel, serial)
|
| 1238 |
+
|
| 1239 |
+
|
| 1240 |
+
@pytest.mark.parametrize("low_memory", [False, 0, np.False_])
|
| 1241 |
+
def test_parallel_low_memory_false_matches_serial(tmp_path, monkeypatch, low_memory):
|
| 1242 |
+
# A falsy low_memory promises whole-file type inference. A chunk holding
|
| 1243 |
+
# only NA tokens and a uint64-range int hits the C parser's na_filter=0
|
| 1244 |
+
# uint64-conflict path (gh-14983) and keeps "nan" as a literal string, while
|
| 1245 |
+
# the serial whole-file pass masks it to NaN. Both chunk results are object
|
| 1246 |
+
# dtype, so the per-column dtype-consistency check cannot catch it - the
|
| 1247 |
+
# parallel path must step aside (GH#64347). low_memory is not coerced to
|
| 1248 |
+
# bool and the serial path branches on truthiness, so falsy non-False values
|
| 1249 |
+
# must step aside too (GH#66327).
|
| 1250 |
+
raw = b"col\n" + b"hello\n" * 500 + (b"nan\n" + b"9223372036854775808\n") * 3000
|
| 1251 |
+
path = tmp_path / "uint64.csv"
|
| 1252 |
+
path.write_bytes(raw)
|
| 1253 |
+
|
| 1254 |
+
result = _read_forced_parallel(path, monkeypatch, low_memory=low_memory)
|
| 1255 |
+
expected = pd.read_csv(io.BytesIO(raw), low_memory=low_memory)
|
| 1256 |
+
tm.assert_frame_equal(result, expected)
|
| 1257 |
+
# serial semantics: every "nan" token is masked to NaN, none survive as text
|
| 1258 |
+
assert (result["col"] == "nan").sum() == 0
|
| 1259 |
+
assert result["col"].isna().sum() == 3000
|
| 1260 |
+
|
| 1261 |
+
|
| 1262 |
+
@pytest.mark.parametrize(
|
| 1263 |
+
"kwargs",
|
| 1264 |
+
[
|
| 1265 |
+
{},
|
| 1266 |
+
{"na_values": ["MISSING"]},
|
| 1267 |
+
{"na_values": {"col": ["MISSING"]}},
|
| 1268 |
+
{"dtype_backend": "numpy_nullable"},
|
| 1269 |
+
],
|
| 1270 |
+
)
|
| 1271 |
+
def test_parallel_uint64_na_conflict_matches_serial(tmp_path, monkeypatch, kwargs):
|
| 1272 |
+
# A chunk holding only NA tokens and uint64-range ints converts to no
|
| 1273 |
+
# numeric dtype and is emitted with its NA tokens left as literal strings
|
| 1274 |
+
# (gh-14983). A chunk that also sees ordinary text takes the object branch
|
| 1275 |
+
# and masks them instead, and both results are str dtype, so the gather's
|
| 1276 |
+
# dtype reconciliation cannot tell them apart - the parallel path must step
|
| 1277 |
+
# aside rather than return values a serial read never produces (GH#66259).
|
| 1278 |
+
token = "MISSING" if kwargs.get("na_values") else "nan"
|
| 1279 |
+
body = f"{token}\n9223372036854775808\n" * 3000
|
| 1280 |
+
path = tmp_path / "uint64_default_lm.csv"
|
| 1281 |
+
path.write_text("col\n" + "text\n" * 500 + body, encoding="utf-8")
|
| 1282 |
+
|
| 1283 |
+
result = _read_forced_parallel(path, monkeypatch, **kwargs)
|
| 1284 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1285 |
+
expected = pd.read_csv(path, **kwargs)
|
| 1286 |
+
tm.assert_frame_equal(result, expected)
|
| 1287 |
+
|
| 1288 |
+
|
| 1289 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so the spy sees no call")
|
| 1290 |
+
def test_parallel_uint64_na_conflict_na_filter_false(tmp_path, monkeypatch):
|
| 1291 |
+
# With na_filter=False the literal NA tokens are what a serial read gives
|
| 1292 |
+
# too, so such a file keeps using the parallel path. GH#66259
|
| 1293 |
+
body = "nan\n9223372036854775808\n" * 3000
|
| 1294 |
+
path = tmp_path / "uint64_no_filter.csv"
|
| 1295 |
+
path.write_text("col\n" + "text\n" * 500 + body, encoding="utf-8")
|
| 1296 |
+
|
| 1297 |
+
fell_back = []
|
| 1298 |
+
orig = _readers._read_csv_parallel
|
| 1299 |
+
|
| 1300 |
+
def spy(*args, **kwargs):
|
| 1301 |
+
result = orig(*args, **kwargs)
|
| 1302 |
+
fell_back.append(result is None)
|
| 1303 |
+
return result
|
| 1304 |
+
|
| 1305 |
+
monkeypatch.setattr(_readers, "_read_csv_parallel", spy)
|
| 1306 |
+
|
| 1307 |
+
result = _read_forced_parallel(path, monkeypatch, na_filter=False)
|
| 1308 |
+
assert fell_back == [False]
|
| 1309 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1310 |
+
expected = pd.read_csv(path, na_filter=False)
|
| 1311 |
+
tm.assert_frame_equal(result, expected)
|
| 1312 |
+
|
| 1313 |
+
|
| 1314 |
+
def test_parallel_quoted_newline_in_header_matches_serial(tmp_path, monkeypatch):
|
| 1315 |
+
# A quoted embedded newline in the header shifts data_start mid-header;
|
| 1316 |
+
# without a guard, chunk 0 starts inside the header and silently injects
|
| 1317 |
+
# a garbage row (GH#64347). All-string data so the per-column dtype
|
| 1318 |
+
# consistency check cannot catch it.
|
| 1319 |
+
raw = b'"col\n1",col2\n' + b"".join(f"x{i},y{i}\n".encode() for i in range(500))
|
| 1320 |
+
path = tmp_path / "hdr.csv"
|
| 1321 |
+
path.write_bytes(raw)
|
| 1322 |
+
|
| 1323 |
+
result = _read_forced_parallel(path, monkeypatch)
|
| 1324 |
+
expected = pd.read_csv(io.BytesIO(raw))
|
| 1325 |
+
tm.assert_frame_equal(result, expected)
|
| 1326 |
+
assert len(result) == 500
|
| 1327 |
+
|
| 1328 |
+
|
| 1329 |
+
def test_parallel_storage_options_raises(tmp_path, monkeypatch):
|
| 1330 |
+
# storage_options with a local path raises ValueError in the serial path;
|
| 1331 |
+
# the parallel path strips it and must not mask that error (GH#64347).
|
| 1332 |
+
raw = b"a,b\n" + b"".join(f"{i},{i}\n".encode() for i in range(500))
|
| 1333 |
+
path = tmp_path / "so.csv"
|
| 1334 |
+
path.write_bytes(raw)
|
| 1335 |
+
|
| 1336 |
+
msg = "storage_options passed with file object or non-fsspec file path"
|
| 1337 |
+
with pytest.raises(ValueError, match=msg):
|
| 1338 |
+
_read_forced_parallel(path, monkeypatch, storage_options={"anon": True})
|
| 1339 |
+
|
| 1340 |
+
|
| 1341 |
+
def test_parallel_on_bad_lines_warn_line_numbers(tmp_path, monkeypatch):
|
| 1342 |
+
# on_bad_lines="warn" must report absolute line numbers; chunk workers
|
| 1343 |
+
# would report chunk-relative ones, so the serial path is used (GH#64347).
|
| 1344 |
+
raw = (
|
| 1345 |
+
b"a,b\n"
|
| 1346 |
+
+ b"".join(f"{i},{i}\n".encode() for i in range(300))
|
| 1347 |
+
+ b"1,2,3,4\n"
|
| 1348 |
+
+ b"".join(f"{i},{i}\n".encode() for i in range(300, 600))
|
| 1349 |
+
)
|
| 1350 |
+
path = tmp_path / "bad.csv"
|
| 1351 |
+
path.write_bytes(raw)
|
| 1352 |
+
|
| 1353 |
+
with tm.assert_produces_warning(ParserWarning, match="line 302"):
|
| 1354 |
+
result = _read_forced_parallel(path, monkeypatch, on_bad_lines="warn")
|
| 1355 |
+
with tm.assert_produces_warning(ParserWarning, match="line 302"):
|
| 1356 |
+
expected = pd.read_csv(io.BytesIO(raw), on_bad_lines="warn")
|
| 1357 |
+
tm.assert_frame_equal(result, expected)
|
| 1358 |
+
|
| 1359 |
+
|
| 1360 |
+
def test_parallel_implicit_index_matches_serial(tmp_path, monkeypatch):
|
| 1361 |
+
# Data rows with one more field than the header get an implicit index;
|
| 1362 |
+
# the parallel path must hand back to serial rather than drop it via
|
| 1363 |
+
# concat(ignore_index=True) (GH#64347).
|
| 1364 |
+
raw = b"col1,col2\n" + b"".join(
|
| 1365 |
+
f"idx{i},{i},{i * 2}\n".encode() for i in range(500)
|
| 1366 |
+
)
|
| 1367 |
+
path = tmp_path / "implicit.csv"
|
| 1368 |
+
path.write_bytes(raw)
|
| 1369 |
+
|
| 1370 |
+
result = _read_forced_parallel(path, monkeypatch)
|
| 1371 |
+
expected = pd.read_csv(io.BytesIO(raw))
|
| 1372 |
+
tm.assert_frame_equal(result, expected)
|
| 1373 |
+
assert list(result.index[:2]) == ["idx0", "idx1"]
|
| 1374 |
+
|
| 1375 |
+
|
| 1376 |
+
def test_parallel_dialect_escapechar_matches_serial(tmp_path, monkeypatch):
|
| 1377 |
+
# dialect is merged into the kwds only inside TextFileReader, after the
|
| 1378 |
+
# eligibility check runs; a dialect-specified escapechar must still force
|
| 1379 |
+
# the serial path - an escaped newline split across chunks would
|
| 1380 |
+
# otherwise corrupt data (GH#64347).
|
| 1381 |
+
class EscDialect(csv.Dialect):
|
| 1382 |
+
delimiter = ","
|
| 1383 |
+
quotechar = '"'
|
| 1384 |
+
doublequote = True
|
| 1385 |
+
skipinitialspace = False
|
| 1386 |
+
lineterminator = "\r\n"
|
| 1387 |
+
quoting = csv.QUOTE_NONE
|
| 1388 |
+
escapechar = "\\"
|
| 1389 |
+
|
| 1390 |
+
raw = b"col1,col2\n" + b"".join(
|
| 1391 |
+
f"text\\\nmore{i},{i}\n".encode() for i in range(500)
|
| 1392 |
+
)
|
| 1393 |
+
path = tmp_path / "dialect.csv"
|
| 1394 |
+
path.write_bytes(raw)
|
| 1395 |
+
|
| 1396 |
+
result = _read_forced_parallel(path, monkeypatch, dialect=EscDialect)
|
| 1397 |
+
expected = pd.read_csv(io.BytesIO(raw), dialect=EscDialect)
|
| 1398 |
+
tm.assert_frame_equal(result, expected)
|
| 1399 |
+
assert result.loc[0, "col1"] == "text\nmore0"
|
| 1400 |
+
|
| 1401 |
+
|
| 1402 |
+
def test_parallel_multichar_sep_matches_serial(tmp_path, monkeypatch):
|
| 1403 |
+
# Multi-char seps force the python engine inside TextFileReader; the
|
| 1404 |
+
# parallel path must step aside rather than hit the C-engine assert
|
| 1405 |
+
# (GH#64347).
|
| 1406 |
+
raw = b"col1;;col2\n" + b"".join(f"{i};;{i * 2}\n".encode() for i in range(500))
|
| 1407 |
+
path = tmp_path / "multisep.csv"
|
| 1408 |
+
path.write_bytes(raw)
|
| 1409 |
+
|
| 1410 |
+
warn_msg = "Falling back to the 'python' engine"
|
| 1411 |
+
with tm.assert_produces_warning(ParserWarning, match=warn_msg):
|
| 1412 |
+
result = _read_forced_parallel(path, monkeypatch, sep=";;")
|
| 1413 |
+
with tm.assert_produces_warning(ParserWarning, match=warn_msg):
|
| 1414 |
+
expected = pd.read_csv(io.BytesIO(raw), sep=";;")
|
| 1415 |
+
tm.assert_frame_equal(result, expected)
|
| 1416 |
+
|
| 1417 |
+
|
| 1418 |
+
def _write_with_line_at_chunk_start(path, replacement: bytes, monkeypatch) -> int:
|
| 1419 |
+
"""Write a fixed-width CSV, then overwrite the line at the second chunk
|
| 1420 |
+
boundary with *replacement* (same byte length, so offsets stay valid).
|
| 1421 |
+
|
| 1422 |
+
Returns the boundary, for :func:`_assert_chunk_starts_at` to check against
|
| 1423 |
+
the split the read actually plans - hard-coding a count here that the read
|
| 1424 |
+
does not use would put the line in the middle of a chunk instead.
|
| 1425 |
+
"""
|
| 1426 |
+
rows = [f"{i:06d},{i * 2:06d}" for i in range(4000)]
|
| 1427 |
+
# write bytes so line endings stay "\n" on every platform - the byte-offset
|
| 1428 |
+
# math below assumes single-byte terminators (Windows text mode adds "\r")
|
| 1429 |
+
path.write_bytes(("a,b\n" + "\n".join(rows) + "\n").encode("utf-8"))
|
| 1430 |
+
# 4000 rows is only two chunks' worth at the row floor, and the split has to
|
| 1431 |
+
# be finer than that for a boundary to land mid-file. _read_forced_parallel
|
| 1432 |
+
# uses 4 workers, so this yields the 4 * 3 oversubscription.
|
| 1433 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_MIN_CHUNK_ROWS", 1)
|
| 1434 |
+
data_start = _find_data_start_offset(str(path), 0, 0)
|
| 1435 |
+
# The same four workers the read uses: the chunk sizes taper, so a boundary
|
| 1436 |
+
# computed without them would sit somewhere the read never splits.
|
| 1437 |
+
offsets = _find_chunk_byte_offsets(str(path), 12, data_start, n_workers=4)
|
| 1438 |
+
boundary = offsets[1]
|
| 1439 |
+
raw = path.read_bytes()
|
| 1440 |
+
line_end = raw.index(b"\n", boundary)
|
| 1441 |
+
assert line_end - boundary == len(replacement)
|
| 1442 |
+
with open(path, "r+b") as fd:
|
| 1443 |
+
fd.seek(boundary)
|
| 1444 |
+
fd.write(replacement)
|
| 1445 |
+
return boundary
|
| 1446 |
+
|
| 1447 |
+
|
| 1448 |
+
def _spy_on_chunk_offsets(monkeypatch) -> list:
|
| 1449 |
+
"""Record the byte offsets each planned split actually uses."""
|
| 1450 |
+
seen: list = []
|
| 1451 |
+
real = _find_chunk_byte_offsets
|
| 1452 |
+
|
| 1453 |
+
def spy(filepath, n_chunks, data_start, *args):
|
| 1454 |
+
offsets = real(filepath, n_chunks, data_start, *args)
|
| 1455 |
+
seen.append(offsets)
|
| 1456 |
+
return offsets
|
| 1457 |
+
|
| 1458 |
+
monkeypatch.setattr("pandas.io.parsers.readers._find_chunk_byte_offsets", spy)
|
| 1459 |
+
return seen
|
| 1460 |
+
|
| 1461 |
+
|
| 1462 |
+
def _assert_chunk_starts_at(seen: list, boundary: int) -> None:
|
| 1463 |
+
# Without this the tests below still pass on a coarser split - a ragged line
|
| 1464 |
+
# raises (and a skipped one is skipped) wherever it sits - while no longer
|
| 1465 |
+
# placing it at the chunk start that is the point of the fixture.
|
| 1466 |
+
assert seen, "the parallel path did not run"
|
| 1467 |
+
assert boundary in seen[0], f"{boundary} is not a chunk start in {seen[0]}"
|
| 1468 |
+
|
| 1469 |
+
|
| 1470 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so the spy sees no call")
|
| 1471 |
+
def test_parallel_ragged_line_at_chunk_start_raises(tmp_path, monkeypatch):
|
| 1472 |
+
# A line with extra fields sitting exactly at a chunk boundary: the chunk
|
| 1473 |
+
# worker's first line used to be exempt from the field-count check, so
|
| 1474 |
+
# parallel silently truncated the row while serial raised (GH#64347).
|
| 1475 |
+
path = tmp_path / "ragged.csv"
|
| 1476 |
+
boundary = _write_with_line_at_chunk_start(path, b"11,22,33,4444", monkeypatch)
|
| 1477 |
+
seen = _spy_on_chunk_offsets(monkeypatch)
|
| 1478 |
+
|
| 1479 |
+
with pytest.raises(ParserError, match="Expected 2 fields"):
|
| 1480 |
+
_read_forced_parallel(path, monkeypatch)
|
| 1481 |
+
_assert_chunk_starts_at(seen, boundary)
|
| 1482 |
+
|
| 1483 |
+
|
| 1484 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so the spy sees no call")
|
| 1485 |
+
def test_parallel_ragged_line_at_chunk_start_skip_matches_serial(tmp_path, monkeypatch):
|
| 1486 |
+
# Same layout with on_bad_lines="skip": the chunk worker must skip the
|
| 1487 |
+
# bad line just like serial, not keep a truncated version of it.
|
| 1488 |
+
path = tmp_path / "ragged.csv"
|
| 1489 |
+
boundary = _write_with_line_at_chunk_start(path, b"11,22,33,4444", monkeypatch)
|
| 1490 |
+
seen = _spy_on_chunk_offsets(monkeypatch)
|
| 1491 |
+
outcomes = _track_parallel(monkeypatch)
|
| 1492 |
+
|
| 1493 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1494 |
+
expected = pd.read_csv(path, on_bad_lines="skip")
|
| 1495 |
+
result = _read_forced_parallel(path, monkeypatch, on_bad_lines="skip")
|
| 1496 |
+
tm.assert_frame_equal(result, expected)
|
| 1497 |
+
assert len(result) == 3999
|
| 1498 |
+
_assert_chunk_starts_at(seen, boundary)
|
| 1499 |
+
assert outcomes == ["used"]
|
| 1500 |
+
|
| 1501 |
+
|
| 1502 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so the spy sees no call")
|
| 1503 |
+
@pytest.mark.parametrize(
|
| 1504 |
+
"kwargs", [{"dtype": {"a": "int64"}}, {"converters": {"a": int}}]
|
| 1505 |
+
)
|
| 1506 |
+
def test_parallel_quoted_newline_at_chunk_boundary_converts_like_serial(
|
| 1507 |
+
tmp_path, monkeypatch, kwargs
|
| 1508 |
+
):
|
| 1509 |
+
# A boundary inside a quoted newline: the chunk before it fails to tokenize
|
| 1510 |
+
# and the chunk after fails to convert its misaligned first line, an error
|
| 1511 |
+
# that must not escape.
|
| 1512 |
+
path = tmp_path / "quoted.csv"
|
| 1513 |
+
rows = [f"{i:06d},{i * 2:06d}" for i in range(40_000)]
|
| 1514 |
+
path.write_bytes(("a,b\n" + "\n".join(rows) + "\n").encode("utf-8"))
|
| 1515 |
+
data_start = _find_data_start_offset(str(path), 0, 0)
|
| 1516 |
+
boundary = _find_chunk_byte_offsets(str(path), 6, data_start, n_workers=2)[2]
|
| 1517 |
+
with open(path, "r+b") as fd:
|
| 1518 |
+
# the "b" field of the line before the boundary, then the line after it
|
| 1519 |
+
fd.seek(boundary - 7)
|
| 1520 |
+
fd.write(b'"multi\nmore of note"')
|
| 1521 |
+
seen = _spy_on_chunk_offsets(monkeypatch)
|
| 1522 |
+
|
| 1523 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1524 |
+
expected = pd.read_csv(path, **kwargs)
|
| 1525 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 1526 |
+
with pd.option_context("mode.max_threads", 2):
|
| 1527 |
+
result = pd.read_csv(path, **kwargs)
|
| 1528 |
+
tm.assert_frame_equal(result, expected)
|
| 1529 |
+
assert "multi\nmore of note" in result["b"].values
|
| 1530 |
+
_assert_chunk_starts_at(seen, boundary)
|
| 1531 |
+
|
| 1532 |
+
|
| 1533 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so the spy sees no call")
|
| 1534 |
+
def test_parallel_bom_bytes_mid_file_match_serial(tmp_path, monkeypatch):
|
| 1535 |
+
# Data lines beginning with the UTF-8 BOM byte sequence: each chunk
|
| 1536 |
+
# worker's fresh parser used to strip it from the chunk's first line,
|
| 1537 |
+
# while serial strips only at byte 0 of the file (GH#64347).
|
| 1538 |
+
lines = ["a,b"] + ["\ufeff" + f"x{i},{i}" for i in range(4000)]
|
| 1539 |
+
path = tmp_path / "bom.csv"
|
| 1540 |
+
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
| 1541 |
+
|
| 1542 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1543 |
+
expected = pd.read_csv(path)
|
| 1544 |
+
outcomes = _track_parallel(monkeypatch)
|
| 1545 |
+
result = _read_forced_parallel(path, monkeypatch)
|
| 1546 |
+
tm.assert_frame_equal(result, expected)
|
| 1547 |
+
assert (result["a"].str[0] == "\ufeff").all()
|
| 1548 |
+
assert outcomes == ["used"]
|
| 1549 |
+
|
| 1550 |
+
|
| 1551 |
+
def test_parallel_bom_at_file_start_header_none(tmp_path, monkeypatch):
|
| 1552 |
+
# With header=None and no skiprows the first chunk starts at byte 0 and
|
| 1553 |
+
# must strip a leading BOM exactly like the serial parser does.
|
| 1554 |
+
body = "".join(f"{i},{i * 2}\n" for i in range(4000))
|
| 1555 |
+
path = tmp_path / "bom0.csv"
|
| 1556 |
+
path.write_bytes(b"\xef\xbb\xbf" + body.encode())
|
| 1557 |
+
|
| 1558 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1559 |
+
expected = pd.read_csv(path, header=None, names=["a", "b"])
|
| 1560 |
+
result = _read_forced_parallel(path, monkeypatch, header=None, names=["a", "b"])
|
| 1561 |
+
tm.assert_frame_equal(result, expected)
|
| 1562 |
+
# the stripped BOM means the first cell parses as an integer
|
| 1563 |
+
assert result["a"].iloc[0] == 0
|
| 1564 |
+
|
| 1565 |
+
|
| 1566 |
+
def test_parallel_string_dtype_python_storage(tmp_path, monkeypatch):
|
| 1567 |
+
# Without the pyarrow string fast path, the gathered object column must
|
| 1568 |
+
# get the same string-dtype inference a serial read applies via the
|
| 1569 |
+
# DataFrame constructor (GH#66275).
|
| 1570 |
+
path = tmp_path / "data.csv"
|
| 1571 |
+
rows = "\n".join(f"{i},s{i % 7}" for i in range(5000))
|
| 1572 |
+
path.write_text("a,b\n" + rows + "\n", encoding="utf-8")
|
| 1573 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 1574 |
+
|
| 1575 |
+
with pd.option_context("mode.string_storage", "python"):
|
| 1576 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1577 |
+
serial = pd.read_csv(path)
|
| 1578 |
+
with pd.option_context("mode.max_threads", 4):
|
| 1579 |
+
parallel = pd.read_csv(path)
|
| 1580 |
+
tm.assert_frame_equal(parallel, serial)
|
| 1581 |
+
|
| 1582 |
+
|
| 1583 |
+
def test_parallel_blank_line_run(tmp_path, monkeypatch):
|
| 1584 |
+
# A run of blank lines spanning entire chunks parses those chunks to zero
|
| 1585 |
+
# rows; the reused worker parsers must not leak StopIteration out of
|
| 1586 |
+
# read_csv (GH#66275).
|
| 1587 |
+
path = tmp_path / "data.csv"
|
| 1588 |
+
rows = "\n".join(f"{i},{i * 2}" for i in range(100))
|
| 1589 |
+
path.write_text(
|
| 1590 |
+
"a,b\n" + rows + "\n" + "\n" * 20000 + rows + "\n", encoding="utf-8"
|
| 1591 |
+
)
|
| 1592 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 1593 |
+
|
| 1594 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1595 |
+
expected = pd.read_csv(path)
|
| 1596 |
+
with pd.option_context("mode.max_threads", 4):
|
| 1597 |
+
result = pd.read_csv(path)
|
| 1598 |
+
tm.assert_frame_equal(result, expected)
|
| 1599 |
+
|
| 1600 |
+
|
| 1601 |
+
def test_parallel_bad_line_run_skip(tmp_path, monkeypatch):
|
| 1602 |
+
# Same for chunks whose lines are all skipped via on_bad_lines="skip"
|
| 1603 |
+
# (GH#66275).
|
| 1604 |
+
path = tmp_path / "data.csv"
|
| 1605 |
+
rows = "\n".join(f"{i},{i * 2}" for i in range(100))
|
| 1606 |
+
bad = "\n".join("x,y,z,w,v" for _ in range(5000))
|
| 1607 |
+
path.write_text("a,b\n" + rows + "\n" + bad + "\n" + rows + "\n", encoding="utf-8")
|
| 1608 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 1609 |
+
# The good rows sit at both ends of the file, so at the two chunks the row
|
| 1610 |
+
# floor allows here every chunk has something to parse and the all-skipped
|
| 1611 |
+
# chunk this is about never happens.
|
| 1612 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_MIN_CHUNK_ROWS", 1)
|
| 1613 |
+
|
| 1614 |
+
with pd.option_context("mode.max_threads", 1):
|
| 1615 |
+
expected = pd.read_csv(path, on_bad_lines="skip")
|
| 1616 |
+
with pd.option_context("mode.max_threads", 4):
|
| 1617 |
+
result = pd.read_csv(path, on_bad_lines="skip")
|
| 1618 |
+
tm.assert_frame_equal(result, expected)
|
| 1619 |
+
|
| 1620 |
+
|
| 1621 |
+
def test_parallel_embedded_nul_boolean_column(tmp_path, monkeypatch):
|
| 1622 |
+
# GH#66524: a NUL-bearing field must not match a true/false value on its
|
| 1623 |
+
# pre-NUL prefix in the parallel path either, which feeds the tokenizer
|
| 1624 |
+
# through load_buffer() rather than parser_buffer_bytes().
|
| 1625 |
+
path = tmp_path / "nul_bool.csv"
|
| 1626 |
+
path.write_bytes(b"a\n" + b"True\n" * 200 + b'"True\x00xyz"\n' + b"False\n" * 200)
|
| 1627 |
+
monkeypatch.setattr("pandas.io.parsers.readers._PARALLEL_READ_MIN_BYTES", 1)
|
| 1628 |
+
|
| 1629 |
+
with pd.option_context("mode.max_threads", 4):
|
| 1630 |
+
result = pd.read_csv(path)
|
| 1631 |
+
expected = pd.read_csv(path, engine="python")
|
| 1632 |
+
tm.assert_frame_equal(result, expected)
|
| 1633 |
+
assert result["a"][200] == "True\x00xyz"
|
| 1634 |
+
|
| 1635 |
+
|
| 1636 |
+
def _warnings_from(func, *args, **kwargs):
|
| 1637 |
+
"""Run *func*, returning every warning it raises (no de-duplication)."""
|
| 1638 |
+
with warnings.catch_warnings(record=True) as recorded:
|
| 1639 |
+
warnings.simplefilter("always")
|
| 1640 |
+
result = func(*args, **kwargs)
|
| 1641 |
+
return result, recorded
|
| 1642 |
+
|
| 1643 |
+
|
| 1644 |
+
def _track_parallel(monkeypatch) -> list[str]:
|
| 1645 |
+
"""Record how each parallel attempt ends: used, declined, or raised."""
|
| 1646 |
+
outcomes: list[str] = []
|
| 1647 |
+
original = _readers._read_csv_parallel
|
| 1648 |
+
|
| 1649 |
+
def tracked(*args, **kwargs):
|
| 1650 |
+
try:
|
| 1651 |
+
result = original(*args, **kwargs)
|
| 1652 |
+
except Exception:
|
| 1653 |
+
outcomes.append("raised")
|
| 1654 |
+
raise
|
| 1655 |
+
outcomes.append("used" if result is not None else "declined")
|
| 1656 |
+
return result
|
| 1657 |
+
|
| 1658 |
+
monkeypatch.setattr(_readers, "_read_csv_parallel", tracked)
|
| 1659 |
+
return outcomes
|
| 1660 |
+
|
| 1661 |
+
|
| 1662 |
+
def _converter_dtype_warning(name: str) -> str:
|
| 1663 |
+
return (
|
| 1664 |
+
f"Both a converter and dtype were specified for column {name} - "
|
| 1665 |
+
"only the converter will be used."
|
| 1666 |
+
)
|
| 1667 |
+
|
| 1668 |
+
|
| 1669 |
+
# one column, then two: de-duplicating the collected warnings must not
|
| 1670 |
+
# collapse the distinct ones
|
| 1671 |
+
@pytest.mark.parametrize("names", [["col1"], ["col1", "col2"]])
|
| 1672 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so no chunk repeats the warning")
|
| 1673 |
+
def test_parallel_converter_dtype_warns_once(tmp_path, monkeypatch, names):
|
| 1674 |
+
# The converter+dtype ParserWarning was raised once per chunk, from a pool
|
| 1675 |
+
# thread whose stacklevel walk lands in threading internals (GH#66259).
|
| 1676 |
+
raw = b"col1,col2\n" + b"".join(f"{i},{i * 2}\n".encode() for i in range(500))
|
| 1677 |
+
path = tmp_path / "converter.csv"
|
| 1678 |
+
path.write_bytes(raw)
|
| 1679 |
+
kwargs = {
|
| 1680 |
+
"converters": dict.fromkeys(names, int),
|
| 1681 |
+
"dtype": dict.fromkeys(names, "int64"),
|
| 1682 |
+
}
|
| 1683 |
+
outcomes = _track_parallel(monkeypatch)
|
| 1684 |
+
|
| 1685 |
+
result, recorded = _warnings_from(
|
| 1686 |
+
_read_forced_parallel, path, monkeypatch, **kwargs
|
| 1687 |
+
)
|
| 1688 |
+
|
| 1689 |
+
expected, _ = _warnings_from(pd.read_csv, io.BytesIO(raw), **kwargs)
|
| 1690 |
+
assert outcomes == ["used"]
|
| 1691 |
+
tm.assert_frame_equal(result, expected)
|
| 1692 |
+
assert [str(warning.message) for warning in recorded] == [
|
| 1693 |
+
_converter_dtype_warning(name) for name in names
|
| 1694 |
+
]
|
| 1695 |
+
assert recorded[0].category is ParserWarning
|
| 1696 |
+
# the caller's frame, not a worker thread's
|
| 1697 |
+
assert recorded[0].filename == __file__
|
| 1698 |
+
|
| 1699 |
+
|
| 1700 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so the gather never runs")
|
| 1701 |
+
def test_parallel_gather_exception_still_warns(tmp_path, monkeypatch):
|
| 1702 |
+
# An exception the caller does not answer with a serial read must not carry
|
| 1703 |
+
# the collected warnings off with it - this read is their only chance to be
|
| 1704 |
+
# raised (GH#66259). A chunk's own error falls back to serial, so this
|
| 1705 |
+
# fails the gather instead.
|
| 1706 |
+
raw = b"col1,col2\n" + b"".join(f"{i},{i * 2}\n".encode() for i in range(1000))
|
| 1707 |
+
path = tmp_path / "boom.csv"
|
| 1708 |
+
path.write_bytes(raw)
|
| 1709 |
+
|
| 1710 |
+
def boom(*args, **kwargs):
|
| 1711 |
+
raise RuntimeError("boom")
|
| 1712 |
+
|
| 1713 |
+
monkeypatch.setattr(_readers, "_concatenate_chunks", boom)
|
| 1714 |
+
kwargs = {"converters": {"col1": int}, "dtype": {"col1": "int64"}}
|
| 1715 |
+
outcomes = _track_parallel(monkeypatch)
|
| 1716 |
+
with warnings.catch_warnings(record=True) as recorded:
|
| 1717 |
+
warnings.simplefilter("always")
|
| 1718 |
+
with pytest.raises(RuntimeError, match="boom"):
|
| 1719 |
+
_read_forced_parallel(path, monkeypatch, **kwargs)
|
| 1720 |
+
|
| 1721 |
+
assert outcomes == ["raised"]
|
| 1722 |
+
assert [str(warning.message) for warning in recorded] == [
|
| 1723 |
+
_converter_dtype_warning("col1")
|
| 1724 |
+
]
|
| 1725 |
+
|
| 1726 |
+
|
| 1727 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so no worker raises")
|
| 1728 |
+
def test_parallel_worker_exception_falls_back_to_serial(tmp_path, monkeypatch):
|
| 1729 |
+
# The serial read raises the error, and the collected warning once.
|
| 1730 |
+
raw = b"col1,col2\n" + b"".join(f"{i},{i * 2}\n".encode() for i in range(1000))
|
| 1731 |
+
path = tmp_path / "boom.csv"
|
| 1732 |
+
path.write_bytes(raw)
|
| 1733 |
+
|
| 1734 |
+
def boom(value):
|
| 1735 |
+
if value == "1400":
|
| 1736 |
+
raise RuntimeError("boom")
|
| 1737 |
+
return value
|
| 1738 |
+
|
| 1739 |
+
kwargs = {"converters": {"col1": int, "col2": boom}, "dtype": {"col1": "int64"}}
|
| 1740 |
+
outcomes = _track_parallel(monkeypatch)
|
| 1741 |
+
with warnings.catch_warnings(record=True) as recorded:
|
| 1742 |
+
warnings.simplefilter("always")
|
| 1743 |
+
with pytest.raises(RuntimeError, match="boom"):
|
| 1744 |
+
_read_forced_parallel(path, monkeypatch, **kwargs)
|
| 1745 |
+
|
| 1746 |
+
assert outcomes == ["declined"]
|
| 1747 |
+
assert [str(warning.message) for warning in recorded] == [
|
| 1748 |
+
_converter_dtype_warning("col1")
|
| 1749 |
+
]
|
| 1750 |
+
|
| 1751 |
+
|
| 1752 |
+
def test_parallel_bad_value_raises_like_serial(tmp_path, monkeypatch):
|
| 1753 |
+
# the bad value is in the second chunk, whose own error would report its
|
| 1754 |
+
# position relative to the chunk start
|
| 1755 |
+
rows = [f"{i},{i}" for i in range(4000)]
|
| 1756 |
+
rows[3000] = "x,3000"
|
| 1757 |
+
raw = ("a,b\n" + "\n".join(rows) + "\n").encode()
|
| 1758 |
+
path = tmp_path / "bad.csv"
|
| 1759 |
+
path.write_bytes(raw)
|
| 1760 |
+
|
| 1761 |
+
with pytest.raises(ValueError, match="position 3000") as expected:
|
| 1762 |
+
pd.read_csv(io.BytesIO(raw), dtype={"a": "Int64"})
|
| 1763 |
+
with pytest.raises(ValueError, match=str(expected.value)):
|
| 1764 |
+
_read_forced_parallel(path, monkeypatch, dtype={"a": "Int64"})
|
| 1765 |
+
|
| 1766 |
+
|
| 1767 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so no worker raises")
|
| 1768 |
+
def test_parallel_chunk_failure_unmaps_the_file(tmp_path, monkeypatch):
|
| 1769 |
+
# A failed chunk must not leave the file mapped: the workers hold
|
| 1770 |
+
# memoryview slices of the mapping, so they are closed before it is
|
| 1771 |
+
# (GH#66259).
|
| 1772 |
+
raw = b"col1,col2\n" + b"".join(f"{i},{i * 2}\n".encode() for i in range(1000))
|
| 1773 |
+
path = tmp_path / "boom.csv"
|
| 1774 |
+
path.write_bytes(raw)
|
| 1775 |
+
|
| 1776 |
+
mapped: list[mmap.mmap] = []
|
| 1777 |
+
|
| 1778 |
+
class TrackingMmap(mmap.mmap):
|
| 1779 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 1780 |
+
mapped.append(self)
|
| 1781 |
+
|
| 1782 |
+
monkeypatch.setattr(mmap, "mmap", TrackingMmap)
|
| 1783 |
+
|
| 1784 |
+
def boom(value):
|
| 1785 |
+
if value == "1400":
|
| 1786 |
+
raise RuntimeError("boom")
|
| 1787 |
+
return value
|
| 1788 |
+
|
| 1789 |
+
with pytest.raises(RuntimeError, match="boom"):
|
| 1790 |
+
_read_forced_parallel(path, monkeypatch, converters={"col2": boom})
|
| 1791 |
+
|
| 1792 |
+
assert len(mapped) == 1
|
| 1793 |
+
assert mapped[0].closed
|
| 1794 |
+
|
| 1795 |
+
|
| 1796 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so there is no attempt to decline")
|
| 1797 |
+
def test_parallel_fallback_does_not_repeat_c_layer_warning(tmp_path, monkeypatch):
|
| 1798 |
+
# A parallel attempt that hands back to serial must not leave its own copy
|
| 1799 |
+
# of a warning behind: the name-inference read hits the same converter+dtype
|
| 1800 |
+
# warning the replacing serial read raises (GH#66259).
|
| 1801 |
+
raw = (
|
| 1802 |
+
b"col1,col2\n"
|
| 1803 |
+
+ b"".join(f"{i},{i * 2}\n".encode() for i in range(950))
|
| 1804 |
+
# col2 is str in the last chunk only, so the per-chunk dtypes disagree
|
| 1805 |
+
# and the parallel path declines after inferring the column names
|
| 1806 |
+
+ b"".join(f"{i},x{i}\n".encode() for i in range(50))
|
| 1807 |
+
)
|
| 1808 |
+
path = tmp_path / "fallback.csv"
|
| 1809 |
+
path.write_bytes(raw)
|
| 1810 |
+
kwargs = {"converters": {"col1": int}, "dtype": {"col1": "int64"}}
|
| 1811 |
+
outcomes = _track_parallel(monkeypatch)
|
| 1812 |
+
|
| 1813 |
+
result, recorded = _warnings_from(
|
| 1814 |
+
_read_forced_parallel, path, monkeypatch, **kwargs
|
| 1815 |
+
)
|
| 1816 |
+
|
| 1817 |
+
expected, _ = _warnings_from(pd.read_csv, io.BytesIO(raw), **kwargs)
|
| 1818 |
+
assert outcomes == ["declined"]
|
| 1819 |
+
tm.assert_frame_equal(result, expected)
|
| 1820 |
+
assert [str(warning.message) for warning in recorded] == [
|
| 1821 |
+
_converter_dtype_warning("col1")
|
| 1822 |
+
]
|
| 1823 |
+
|
| 1824 |
+
|
| 1825 |
+
@pytest.mark.skipif(
|
| 1826 |
+
WASM, reason="WASM stays serial, so there is no attempt to fall back"
|
| 1827 |
+
)
|
| 1828 |
+
def test_parallel_fallback_does_not_repeat_python_layer_warning(tmp_path, monkeypatch):
|
| 1829 |
+
# Same for a warning raised by the Python layer rather than the C parser:
|
| 1830 |
+
# index_col=False with more fields than header names warns in the
|
| 1831 |
+
# name-inference read, and again in the serial read that a worker's
|
| 1832 |
+
# failure falls back to (GH#66259).
|
| 1833 |
+
raw = b"col1,col2\n" + b"".join(
|
| 1834 |
+
f"{i},{i * 2},{i * 3}\n".encode() for i in range(500)
|
| 1835 |
+
)
|
| 1836 |
+
path = tmp_path / "mismatch.csv"
|
| 1837 |
+
path.write_bytes(raw)
|
| 1838 |
+
outcomes = _track_parallel(monkeypatch)
|
| 1839 |
+
|
| 1840 |
+
result, recorded = _warnings_from(
|
| 1841 |
+
_read_forced_parallel, path, monkeypatch, index_col=False
|
| 1842 |
+
)
|
| 1843 |
+
|
| 1844 |
+
expected, _ = _warnings_from(pd.read_csv, io.BytesIO(raw), index_col=False)
|
| 1845 |
+
assert outcomes == ["declined"]
|
| 1846 |
+
tm.assert_frame_equal(result, expected)
|
| 1847 |
+
assert [str(warning.message) for warning in recorded] == [
|
| 1848 |
+
"Length of header or names does not match length of data. This leads "
|
| 1849 |
+
"to a loss of data with index_col=False."
|
| 1850 |
+
]
|
| 1851 |
+
|
| 1852 |
+
|
| 1853 |
+
@pytest.mark.parametrize("kwargs", [{"quotechar": "»"}, {"sep": "§"}])
|
| 1854 |
+
def test_multibyte_sep_or_quotechar_warns_once(tmp_path, monkeypatch, kwargs):
|
| 1855 |
+
# Both force TextFileReader onto the python engine, which warns while
|
| 1856 |
+
# falling back. The parallel path has to decline them up front: its
|
| 1857 |
+
# name-inference read would raise that warning before it can notice the
|
| 1858 |
+
# engine it got, and the serial read then raises it again (GH#66259).
|
| 1859 |
+
raw = b"col1,col2\n" + b"".join(f"{i},{i * 2}\n".encode() for i in range(500))
|
| 1860 |
+
path = tmp_path / "multibyte.csv"
|
| 1861 |
+
path.write_bytes(raw)
|
| 1862 |
+
outcomes = _track_parallel(monkeypatch)
|
| 1863 |
+
|
| 1864 |
+
result, recorded = _warnings_from(
|
| 1865 |
+
_read_forced_parallel, path, monkeypatch, **kwargs
|
| 1866 |
+
)
|
| 1867 |
+
|
| 1868 |
+
expected, _ = _warnings_from(pd.read_csv, io.BytesIO(raw), **kwargs)
|
| 1869 |
+
assert outcomes == []
|
| 1870 |
+
tm.assert_frame_equal(result, expected)
|
| 1871 |
+
assert len(recorded) == 1
|
| 1872 |
+
assert recorded[0].category is ParserWarning
|
| 1873 |
+
assert "Falling back to the 'python' engine" in str(recorded[0].message)
|
| 1874 |
+
|
| 1875 |
+
|
| 1876 |
+
# 2**63 - 1 gathers through pyarrow's checked int-to-double cast; 2**64 does not
|
| 1877 |
+
# even fit an integer chunk, so it fails earlier, in a worker's own conversion
|
| 1878 |
+
@pytest.mark.parametrize("big", ["9223372036854775807", "18446744073709551616"])
|
| 1879 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so the chunks never disagree")
|
| 1880 |
+
def test_parallel_pyarrow_huge_int_chunk_matches_serial(tmp_path, monkeypatch, big):
|
| 1881 |
+
# A chunk holding only huge integers converts as an integer column, while
|
| 1882 |
+
# the whole-file serial read sees the trailing float too and infers double
|
| 1883 |
+
# (or leaves the column a string). The parallel path used to propagate the
|
| 1884 |
+
# resulting ArrowInvalid / OverflowError instead of re-reading serially
|
| 1885 |
+
# (GH#66259).
|
| 1886 |
+
pytest.importorskip("pyarrow")
|
| 1887 |
+
raw = b"col1\n" + f"{big}\n".encode() * 500 + b"1.5\n"
|
| 1888 |
+
path = tmp_path / "huge_int.csv"
|
| 1889 |
+
path.write_bytes(raw)
|
| 1890 |
+
outcomes = _track_parallel(monkeypatch)
|
| 1891 |
+
|
| 1892 |
+
result = _read_forced_parallel(path, monkeypatch, dtype_backend="pyarrow")
|
| 1893 |
+
|
| 1894 |
+
expected = pd.read_csv(io.BytesIO(raw), dtype_backend="pyarrow")
|
| 1895 |
+
assert outcomes == ["declined"]
|
| 1896 |
+
tm.assert_frame_equal(result, expected)
|
| 1897 |
+
|
| 1898 |
+
|
| 1899 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so nothing infers per chunk")
|
| 1900 |
+
def test_parallel_pyarrow_huge_int_column_stays_parallel(tmp_path, monkeypatch):
|
| 1901 |
+
# The guard above must not cost the parallel path columns it handles fine:
|
| 1902 |
+
# with no float row every chunk agrees on int64 and nothing falls back
|
| 1903 |
+
# (GH#66259).
|
| 1904 |
+
pytest.importorskip("pyarrow")
|
| 1905 |
+
raw = b"col1\n" + b"9223372036854775807\n" * 500
|
| 1906 |
+
path = tmp_path / "huge_int_only.csv"
|
| 1907 |
+
path.write_bytes(raw)
|
| 1908 |
+
outcomes = _track_parallel(monkeypatch)
|
| 1909 |
+
|
| 1910 |
+
result = _read_forced_parallel(path, monkeypatch, dtype_backend="pyarrow")
|
| 1911 |
+
|
| 1912 |
+
expected = pd.read_csv(io.BytesIO(raw), dtype_backend="pyarrow")
|
| 1913 |
+
assert outcomes == ["used"]
|
| 1914 |
+
tm.assert_frame_equal(result, expected)
|
| 1915 |
+
|
| 1916 |
+
|
| 1917 |
+
@pytest.mark.skipif(WASM, reason="WASM stays serial, so no sample line is parsed")
|
| 1918 |
+
def test_parallel_huge_int_first_line_matches_serial(tmp_path, monkeypatch):
|
| 1919 |
+
# The name-inference read parses one data line only to learn the column
|
| 1920 |
+
# names, so a value that converts on its own but not for the whole column
|
| 1921 |
+
# must not raise there (GH#66259).
|
| 1922 |
+
pytest.importorskip("pyarrow")
|
| 1923 |
+
raw = b"col1\n18446744073709551616\n" + b"".join(
|
| 1924 |
+
f"{i}.5\n".encode() for i in range(500)
|
| 1925 |
+
)
|
| 1926 |
+
path = tmp_path / "huge_first.csv"
|
| 1927 |
+
path.write_bytes(raw)
|
| 1928 |
+
|
| 1929 |
+
result = _read_forced_parallel(path, monkeypatch, dtype_backend="pyarrow")
|
| 1930 |
+
|
| 1931 |
+
tm.assert_frame_equal(result, pd.read_csv(io.BytesIO(raw), dtype_backend="pyarrow"))
|
| 1932 |
+
|
| 1933 |
+
|
| 1934 |
+
# ---------------------------------------------------------------------------
|
| 1935 |
+
# chunk-count planning
|
| 1936 |
+
# ---------------------------------------------------------------------------
|
| 1937 |
+
|
| 1938 |
+
|
| 1939 |
+
def _planned_chunk_count(
|
| 1940 |
+
path, monkeypatch, *, chunk_bytes, n_workers=4, min_chunk_rows=None, **kwargs
|
| 1941 |
+
) -> int:
|
| 1942 |
+
"""Return the chunk count ``read_csv`` actually plans for *path*.
|
| 1943 |
+
|
| 1944 |
+
Reads the split the planner produces rather than recomputing it, so a test
|
| 1945 |
+
cannot agree with a rule the code no longer follows. *chunk_bytes* and
|
| 1946 |
+
*min_chunk_rows* stand in for the module constants so a test-sized fixture
|
| 1947 |
+
can still exercise the one bound it is about.
|
| 1948 |
+
"""
|
| 1949 |
+
seen = []
|
| 1950 |
+
original = _readers._find_chunk_byte_offsets
|
| 1951 |
+
|
| 1952 |
+
def spy(filepath, n_chunks, data_start, *args):
|
| 1953 |
+
offsets = original(filepath, n_chunks, data_start, *args)
|
| 1954 |
+
seen.append(len(offsets) - 1)
|
| 1955 |
+
return offsets
|
| 1956 |
+
|
| 1957 |
+
monkeypatch.setattr(_readers, "_find_chunk_byte_offsets", spy)
|
| 1958 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 1959 |
+
monkeypatch.setattr(_readers, "_PARALLEL_CHUNK_BYTES", chunk_bytes)
|
| 1960 |
+
if min_chunk_rows is not None:
|
| 1961 |
+
monkeypatch.setattr(_readers, "_PARALLEL_MIN_CHUNK_ROWS", min_chunk_rows)
|
| 1962 |
+
with pd.option_context("mode.max_threads", n_workers):
|
| 1963 |
+
pd.read_csv(path, **kwargs)
|
| 1964 |
+
return seen[0] if seen else 0
|
| 1965 |
+
|
| 1966 |
+
|
| 1967 |
+
def _write_grid(path, n_rows, n_cols, field="7") -> None:
|
| 1968 |
+
header = ",".join(f"c{i}" for i in range(n_cols))
|
| 1969 |
+
row = ",".join(field for _ in range(n_cols))
|
| 1970 |
+
# Bytes, not text: text mode writes "\r\n" on Windows, skewing the
|
| 1971 |
+
# byte-budget comparisons below.
|
| 1972 |
+
path.write_bytes((header + "\n" + f"{row}\n" * n_rows).encode())
|
| 1973 |
+
|
| 1974 |
+
|
| 1975 |
+
@pytest.mark.skipif(WASM, reason="WASM cannot spawn threads, so no split happens")
|
| 1976 |
+
def test_parallel_chunk_count_follows_file_size(tmp_path, monkeypatch):
|
| 1977 |
+
# The worker-derived count is blind to file size, splitting a large file
|
| 1978 |
+
# exactly like a small one (GH#66798). Same rows, ~5x the bytes, so only
|
| 1979 |
+
# the byte term can differ.
|
| 1980 |
+
lean = tmp_path / "lean.csv"
|
| 1981 |
+
fat = tmp_path / "fat.csv"
|
| 1982 |
+
_write_grid(lean, 30_000, 4, field="7")
|
| 1983 |
+
_write_grid(fat, 30_000, 4, field="7777777777")
|
| 1984 |
+
assert fat.stat().st_size > 4 * lean.stat().st_size
|
| 1985 |
+
|
| 1986 |
+
# Without the byte term the two files get the identical split ...
|
| 1987 |
+
assert _planned_chunk_count(
|
| 1988 |
+
lean, monkeypatch, chunk_bytes=1 << 60, min_chunk_rows=1
|
| 1989 |
+
) == _planned_chunk_count(fat, monkeypatch, chunk_bytes=1 << 60, min_chunk_rows=1)
|
| 1990 |
+
# ... and with it, the bigger file is split more finely.
|
| 1991 |
+
lean_n = _planned_chunk_count(lean, monkeypatch, chunk_bytes=4096, min_chunk_rows=1)
|
| 1992 |
+
fat_n = _planned_chunk_count(fat, monkeypatch, chunk_bytes=4096, min_chunk_rows=1)
|
| 1993 |
+
|
| 1994 |
+
assert fat_n > lean_n
|
| 1995 |
+
|
| 1996 |
+
|
| 1997 |
+
@pytest.mark.skipif(WASM, reason="WASM cannot spawn threads, so no split happens")
|
| 1998 |
+
def test_parallel_read_many_chunks_per_worker(tmp_path, monkeypatch):
|
| 1999 |
+
# Workers slicing one shared memoryview raised "released memoryview" on
|
| 2000 |
+
# free-threaded builds (GH#71418). The race is narrow, so split a single
|
| 2001 |
+
# column (which gets the whole piece budget) into tiny chunks and repeat.
|
| 2002 |
+
path = tmp_path / "data.csv"
|
| 2003 |
+
_write_grid(path, 20_000, 1)
|
| 2004 |
+
for _ in range(20):
|
| 2005 |
+
n_chunks = _planned_chunk_count(
|
| 2006 |
+
path, monkeypatch, chunk_bytes=16, n_workers=8, min_chunk_rows=1
|
| 2007 |
+
)
|
| 2008 |
+
assert n_chunks >= 1000
|
| 2009 |
+
|
| 2010 |
+
|
| 2011 |
+
@pytest.mark.skipif(WASM, reason="WASM cannot spawn threads, so no split happens")
|
| 2012 |
+
def test_parallel_chunk_count_bounded_by_column_pieces(tmp_path, monkeypatch):
|
| 2013 |
+
# Every chunk repeats a per-column cost, so the byte term stays bounded by
|
| 2014 |
+
# the (column x chunk) piece budget on a wide frame (GH#66798).
|
| 2015 |
+
narrow = tmp_path / "narrow.csv"
|
| 2016 |
+
wide = tmp_path / "wide.csv"
|
| 2017 |
+
_write_grid(narrow, 130_000, 4)
|
| 2018 |
+
_write_grid(wide, 5_300, 100)
|
| 2019 |
+
|
| 2020 |
+
narrow_n = _planned_chunk_count(
|
| 2021 |
+
narrow, monkeypatch, chunk_bytes=4096, min_chunk_rows=1
|
| 2022 |
+
)
|
| 2023 |
+
wide_n = _planned_chunk_count(wide, monkeypatch, chunk_bytes=4096, min_chunk_rows=1)
|
| 2024 |
+
|
| 2025 |
+
assert wide_n < narrow_n
|
| 2026 |
+
# The wide frame has the most bytes, so only the piece budget can have
|
| 2027 |
+
# held its split down.
|
| 2028 |
+
assert wide.stat().st_size > narrow.stat().st_size
|
| 2029 |
+
# The budget itself, rounded up to a whole round of the four workers.
|
| 2030 |
+
budget = _readers._PARALLEL_MAX_COLUMN_PIECES // 100
|
| 2031 |
+
assert wide_n == -(-budget // 4) * 4
|
| 2032 |
+
|
| 2033 |
+
|
| 2034 |
+
def test_parallel_chunk_sizes_taper_towards_the_end_of_the_file(tmp_path):
|
| 2035 |
+
# A read finishes when the last chunk a worker picked up does, so the file
|
| 2036 |
+
# ends in small chunks: a worker that comes free late has something short
|
| 2037 |
+
# left to take (GH#66798).
|
| 2038 |
+
path = tmp_path / "grid.csv"
|
| 2039 |
+
_write_grid(path, 20_000, 4)
|
| 2040 |
+
data_start = _find_data_start_offset(str(path), header=0, skiprows=0)
|
| 2041 |
+
|
| 2042 |
+
offsets = _find_chunk_byte_offsets(str(path), 16, data_start, n_workers=4)
|
| 2043 |
+
sizes = [end - start for start, end in itertools.pairwise(offsets)]
|
| 2044 |
+
|
| 2045 |
+
assert sizes[-1] < sizes[0] / 2
|
| 2046 |
+
assert sum(sizes[-8:]) < sum(sizes[:8])
|
| 2047 |
+
# The chunks still cover the data exactly once, tapered or not.
|
| 2048 |
+
assert offsets[0] == data_start
|
| 2049 |
+
assert offsets[-1] == path.stat().st_size
|
| 2050 |
+
|
| 2051 |
+
# Given no worker count the split is equal, so the taper above is the
|
| 2052 |
+
# argument's doing rather than the fixture's.
|
| 2053 |
+
equal = _find_chunk_byte_offsets(str(path), 16, data_start)
|
| 2054 |
+
equal_sizes = [end - start for start, end in itertools.pairwise(equal)]
|
| 2055 |
+
assert max(equal_sizes) < min(equal_sizes) * 1.05
|
| 2056 |
+
|
| 2057 |
+
|
| 2058 |
+
@pytest.mark.parametrize("n_chunks", [2, 4])
|
| 2059 |
+
def test_parallel_chunk_sizes_do_not_taper_within_one_round(tmp_path, n_chunks):
|
| 2060 |
+
# With no more chunks than workers they all run at once, so the read takes
|
| 2061 |
+
# as long as the largest one and a taper would only inflate it (GH#66798).
|
| 2062 |
+
path = tmp_path / "grid.csv"
|
| 2063 |
+
_write_grid(path, 20_000, 4)
|
| 2064 |
+
data_start = _find_data_start_offset(str(path), header=0, skiprows=0)
|
| 2065 |
+
|
| 2066 |
+
offsets = _find_chunk_byte_offsets(str(path), n_chunks, data_start, n_workers=4)
|
| 2067 |
+
sizes = [end - start for start, end in itertools.pairwise(offsets)]
|
| 2068 |
+
|
| 2069 |
+
assert max(sizes) < min(sizes) * 1.05
|
| 2070 |
+
|
| 2071 |
+
|
| 2072 |
+
@pytest.mark.skipif(WASM, reason="WASM cannot spawn threads, so no split happens")
|
| 2073 |
+
@pytest.mark.parametrize("n_workers", [4, 5, 6, 7])
|
| 2074 |
+
def test_parallel_chunk_count_is_a_whole_number_of_rounds(
|
| 2075 |
+
tmp_path, monkeypatch, n_workers
|
| 2076 |
+
):
|
| 2077 |
+
# A size-driven count that is not a multiple of the worker count leaves the
|
| 2078 |
+
# last round mostly idle: 31 chunks over 6 workers is 5.17 rounds' work
|
| 2079 |
+
# that takes 6 (GH#66798).
|
| 2080 |
+
path = tmp_path / "grid.csv"
|
| 2081 |
+
_write_grid(path, 30_000, 4)
|
| 2082 |
+
|
| 2083 |
+
n_chunks = _planned_chunk_count(
|
| 2084 |
+
path, monkeypatch, chunk_bytes=4096, n_workers=n_workers, min_chunk_rows=1
|
| 2085 |
+
)
|
| 2086 |
+
|
| 2087 |
+
assert n_chunks % n_workers == 0
|
| 2088 |
+
# ... and the byte term set it: the worker-derived floor is a whole number
|
| 2089 |
+
# of rounds anyway, so a count resting on it would pass either way.
|
| 2090 |
+
assert n_chunks > n_workers * 3
|
| 2091 |
+
|
| 2092 |
+
|
| 2093 |
+
@pytest.mark.skipif(WASM, reason="WASM cannot spawn threads, so no split happens")
|
| 2094 |
+
@pytest.mark.parametrize("n_cols", [4, 25])
|
| 2095 |
+
@pytest.mark.parametrize("n_workers", [4, 12])
|
| 2096 |
+
def test_parallel_chunk_count_never_below_the_worker_rule(
|
| 2097 |
+
tmp_path, monkeypatch, n_cols, n_workers
|
| 2098 |
+
):
|
| 2099 |
+
# The byte term only ever *adds* chunks, so no file comes out coarser than
|
| 2100 |
+
# before (GH#66798). Enough rows that the worker count, not the row floor,
|
| 2101 |
+
# sets the floor.
|
| 2102 |
+
path = tmp_path / "grid.csv"
|
| 2103 |
+
_write_grid(path, 30_000, n_cols)
|
| 2104 |
+
|
| 2105 |
+
without = _planned_chunk_count(
|
| 2106 |
+
path, monkeypatch, chunk_bytes=1 << 60, n_workers=n_workers, min_chunk_rows=1
|
| 2107 |
+
)
|
| 2108 |
+
with_term = _planned_chunk_count(
|
| 2109 |
+
path, monkeypatch, chunk_bytes=4096, n_workers=n_workers, min_chunk_rows=1
|
| 2110 |
+
)
|
| 2111 |
+
|
| 2112 |
+
assert without == n_workers * 3
|
| 2113 |
+
# Strictly greater: an equal count would mean the term never fired.
|
| 2114 |
+
assert with_term > without
|
| 2115 |
+
|
| 2116 |
+
|
| 2117 |
+
@pytest.mark.skipif(WASM, reason="WASM cannot spawn threads, so no split happens")
|
| 2118 |
+
def test_parallel_chunk_count_unchanged_below_the_block_size(tmp_path, monkeypatch):
|
| 2119 |
+
# A file smaller than one block adds no chunks, so the small fixtures the
|
| 2120 |
+
# other parallel tests rely on keep the split they had (GH#66798).
|
| 2121 |
+
small = tmp_path / "smallish.csv"
|
| 2122 |
+
_write_grid(small, 4_000, 4)
|
| 2123 |
+
assert small.stat().st_size < _readers._PARALLEL_CHUNK_BYTES
|
| 2124 |
+
|
| 2125 |
+
without = _planned_chunk_count(
|
| 2126 |
+
small, monkeypatch, chunk_bytes=1 << 60, min_chunk_rows=1
|
| 2127 |
+
)
|
| 2128 |
+
with_term = _planned_chunk_count(
|
| 2129 |
+
small,
|
| 2130 |
+
monkeypatch,
|
| 2131 |
+
chunk_bytes=_readers._PARALLEL_CHUNK_BYTES,
|
| 2132 |
+
min_chunk_rows=1,
|
| 2133 |
+
)
|
| 2134 |
+
assert with_term == without
|
| 2135 |
+
|
| 2136 |
+
# Against a block it *does* exceed the file gains chunks, so the equality
|
| 2137 |
+
# above is the block size binding rather than a dead code path.
|
| 2138 |
+
assert (
|
| 2139 |
+
_planned_chunk_count(small, monkeypatch, chunk_bytes=512, min_chunk_rows=1)
|
| 2140 |
+
> without
|
| 2141 |
+
)
|
| 2142 |
+
|
| 2143 |
+
|
| 2144 |
+
@pytest.mark.skipif(WASM, reason="WASM cannot spawn threads, so no split happens")
|
| 2145 |
+
def test_parallel_chunk_count_respects_the_row_floor(tmp_path, monkeypatch):
|
| 2146 |
+
# A file can be byte-rich and row-poor (wide frames, long string fields);
|
| 2147 |
+
# the byte target must not split those past the row floor (GH#66798).
|
| 2148 |
+
path = tmp_path / "row_poor.csv"
|
| 2149 |
+
_write_grid(path, 600, 10, field="x" * 200)
|
| 2150 |
+
|
| 2151 |
+
without = _planned_chunk_count(path, monkeypatch, chunk_bytes=1 << 60)
|
| 2152 |
+
with_term = _planned_chunk_count(path, monkeypatch, chunk_bytes=4096)
|
| 2153 |
+
|
| 2154 |
+
assert with_term == without
|
| 2155 |
+
# The byte target alone would split this an order of magnitude finer.
|
| 2156 |
+
assert path.stat().st_size // 4096 > 10 * with_term
|
| 2157 |
+
|
| 2158 |
+
|
| 2159 |
+
# ---------------------------------------------------------------------------
|
| 2160 |
+
# Row-blocked column conversion (TextReader._convert_batched)
|
| 2161 |
+
# ---------------------------------------------------------------------------
|
| 2162 |
+
|
| 2163 |
+
|
| 2164 |
+
def _blocked_frame(n_rows: int = 30_000) -> pd.DataFrame:
|
| 2165 |
+
# >= 16 columns, so numeric columns qualify for row-blocked conversion at
|
| 2166 |
+
# any worker count; the string columns qualify on their own
|
| 2167 |
+
rng = np.random.default_rng(0)
|
| 2168 |
+
data: dict[str, object] = {
|
| 2169 |
+
f"i{k}": rng.integers(-1000, 1000, size=n_rows) for k in range(6)
|
| 2170 |
+
}
|
| 2171 |
+
data.update({f"f{k}": rng.random(n_rows) for k in range(6)})
|
| 2172 |
+
data.update(
|
| 2173 |
+
{f"s{k}": rng.choice(["id1", "id22", "id333"], size=n_rows) for k in range(6)}
|
| 2174 |
+
)
|
| 2175 |
+
data["b0"] = rng.integers(0, 2, size=n_rows).astype(bool)
|
| 2176 |
+
return pd.DataFrame(data)
|
| 2177 |
+
|
| 2178 |
+
|
| 2179 |
+
@pytest.mark.parametrize("threads", [1, 6])
|
| 2180 |
+
def test_row_blocked_conversion_matches_python_engine(tmp_path, monkeypatch, threads):
|
| 2181 |
+
path = tmp_path / "blocked.csv"
|
| 2182 |
+
_blocked_frame().to_csv(path, index=False)
|
| 2183 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 2184 |
+
# tiny blocks, so every chunk spans many of them
|
| 2185 |
+
monkeypatch.setattr(_parsers, "_BLOCK_BYTES", 2048)
|
| 2186 |
+
|
| 2187 |
+
with pd.option_context("mode.max_threads", threads):
|
| 2188 |
+
result = pd.read_csv(path)
|
| 2189 |
+
expected = pd.read_csv(path, engine="python")
|
| 2190 |
+
tm.assert_frame_equal(result, expected)
|
| 2191 |
+
|
| 2192 |
+
|
| 2193 |
+
@pytest.mark.parametrize("threads", [1, 6])
|
| 2194 |
+
def test_row_blocked_conversion_leading_overflow(tmp_path, monkeypatch, threads):
|
| 2195 |
+
# A leading token that overflows int64 must still reach the uint64 and
|
| 2196 |
+
# object steps of the cascade rather than being inferred as float64.
|
| 2197 |
+
df = _blocked_frame().astype(object)
|
| 2198 |
+
df["u0"] = 2**64 - 1
|
| 2199 |
+
df["o0"] = 10**26
|
| 2200 |
+
path = tmp_path / "overflow.csv"
|
| 2201 |
+
df.to_csv(path, index=False)
|
| 2202 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 2203 |
+
monkeypatch.setattr(_parsers, "_BLOCK_BYTES", 2048)
|
| 2204 |
+
|
| 2205 |
+
with pd.option_context("mode.max_threads", threads):
|
| 2206 |
+
result = pd.read_csv(path)
|
| 2207 |
+
expected = pd.read_csv(path, engine="python")
|
| 2208 |
+
tm.assert_frame_equal(result, expected)
|
| 2209 |
+
assert result["u0"].dtype == np.uint64
|
| 2210 |
+
assert result["o0"].dtype == object
|
| 2211 |
+
|
| 2212 |
+
|
| 2213 |
+
@pytest.mark.parametrize("threads", [1, 6])
|
| 2214 |
+
def test_row_blocked_conversion_string_offset_overflow(tmp_path, monkeypatch, threads):
|
| 2215 |
+
# A string column past the int32-offset target's byte ceiling leaves the
|
| 2216 |
+
# sweep on its own, and the columns sharing its blocks must still convert
|
| 2217 |
+
# from the sweep. "big" needs 400 bytes a row against the 256 KiB ceiling
|
| 2218 |
+
# below, the other string columns under 50 KiB for the whole frame.
|
| 2219 |
+
pytest.importorskip("pyarrow")
|
| 2220 |
+
df = _blocked_frame(n_rows=8_000)
|
| 2221 |
+
df["big"] = ["x" * 400] * len(df)
|
| 2222 |
+
path = tmp_path / "offsets.csv"
|
| 2223 |
+
df.to_csv(path, index=False)
|
| 2224 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 2225 |
+
monkeypatch.setattr(_parsers, "_BLOCK_BYTES", 2048)
|
| 2226 |
+
|
| 2227 |
+
# dtype_backend="pyarrow" is the int32-offset target; the default string
|
| 2228 |
+
# dtype is large_string and has no ceiling.
|
| 2229 |
+
with pd.option_context("mode.max_threads", threads):
|
| 2230 |
+
expected = pd.read_csv(path, dtype_backend="pyarrow")
|
| 2231 |
+
monkeypatch.setattr(_parsers, "_STR_OFFSET_LIMIT", 1 << 18)
|
| 2232 |
+
with pd.option_context("mode.max_threads", threads):
|
| 2233 |
+
result = pd.read_csv(path, dtype_backend="pyarrow")
|
| 2234 |
+
tm.assert_frame_equal(result, expected)
|
| 2235 |
+
|
| 2236 |
+
|
| 2237 |
+
@pytest.mark.parametrize("threads", [1, 6])
|
| 2238 |
+
def test_row_blocked_conversion_late_dtype_miss(tmp_path, monkeypatch, threads):
|
| 2239 |
+
# A column whose leading block infers one kind but whose later rows do
|
| 2240 |
+
# not must fall back to the whole-column inference cascade.
|
| 2241 |
+
df = _blocked_frame().astype(object)
|
| 2242 |
+
df.loc[25_000, "i0"] = 1.5 # int -> float
|
| 2243 |
+
df.loc[25_000, "i1"] = 2**63 + 5 # int -> uint64
|
| 2244 |
+
df.loc[25_000, "i2"] = "abc" # int -> str
|
| 2245 |
+
df.loc[25_000, "f0"] = "oops" # float -> str
|
| 2246 |
+
df.loc[25_000, "s0"] = "h\u00e9llo" # ASCII -> non-ASCII
|
| 2247 |
+
df.loc[25_100, "i3"] = np.nan # NA past the leading block
|
| 2248 |
+
path = tmp_path / "late.csv"
|
| 2249 |
+
df.to_csv(path, index=False)
|
| 2250 |
+
monkeypatch.setattr(_readers, "_PARALLEL_READ_MIN_BYTES", 1)
|
| 2251 |
+
monkeypatch.setattr(_parsers, "_BLOCK_BYTES", 2048)
|
| 2252 |
+
|
| 2253 |
+
with pd.option_context("mode.max_threads", threads):
|
| 2254 |
+
result = pd.read_csv(path)
|
| 2255 |
+
expected = pd.read_csv(path, engine="python")
|
| 2256 |
+
tm.assert_frame_equal(result, expected)
|