title
stringlengths
1
185
diff
stringlengths
0
32.2M
body
stringlengths
0
123k
url
stringlengths
57
58
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
Drop Python 3.6 support
diff --git a/.travis.yml b/.travis.yml index b016cf386098e..2e98cf47aea3e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -45,7 +45,7 @@ matrix: - JOB="3.7, arm64" PYTEST_WORKERS=8 ENV_FILE="ci/deps/travis-37-arm64.yaml" PATTERN="(not slow and not network and not clipboard)" - env: - - JOB="3.6, locale" ENV_FILE="ci/deps/travis-36-locale.yaml" PATTERN="((not slow and not network and not clipboard) or (single and db))" LOCALE_OVERRIDE="zh_CN.UTF-8" SQL="1" + - JOB="3.7, locale" ENV_FILE="ci/deps/travis-37-locale.yaml" PATTERN="((not slow and not network and not clipboard) or (single and db))" LOCALE_OVERRIDE="zh_CN.UTF-8" SQL="1" services: - mysql - postgresql @@ -54,7 +54,7 @@ matrix: # Enabling Deprecations when running tests # PANDAS_TESTING_MODE="deprecate" causes DeprecationWarning messages to be displayed in the logs # See pandas/_testing.py for more details. - - JOB="3.6, coverage" ENV_FILE="ci/deps/travis-36-cov.yaml" PATTERN="((not slow and not network and not clipboard) or (single and db))" PANDAS_TESTING_MODE="deprecate" COVERAGE=true SQL="1" + - JOB="3.7, coverage" ENV_FILE="ci/deps/travis-37-cov.yaml" PATTERN="((not slow and not network and not clipboard) or (single and db))" PANDAS_TESTING_MODE="deprecate" COVERAGE=true SQL="1" services: - mysql - postgresql diff --git a/asv_bench/benchmarks/package.py b/asv_bench/benchmarks/package.py index 8ca33db361fa0..34fe4929a752b 100644 --- a/asv_bench/benchmarks/package.py +++ b/asv_bench/benchmarks/package.py @@ -4,22 +4,16 @@ import subprocess import sys -from pandas.compat import PY37 - class TimeImport: def time_import(self): - if PY37: - # on py37+ we the "-X importtime" usage gives us a more precise - # measurement of the import time we actually care about, - # without the subprocess or interpreter overhead - cmd = [sys.executable, "-X", "importtime", "-c", "import pandas as pd"] - p = subprocess.run(cmd, stderr=subprocess.PIPE) - - line = p.stderr.splitlines()[-1] - field = line.split(b"|")[-2].strip() - total = int(field) # microseconds - return total + # on py37+ we the "-X importtime" usage gives us a more precise + # measurement of the import time we actually care about, + # without the subprocess or interpreter overhead + cmd = [sys.executable, "-X", "importtime", "-c", "import pandas as pd"] + p = subprocess.run(cmd, stderr=subprocess.PIPE) - cmd = [sys.executable, "-c", "import pandas as pd"] - subprocess.run(cmd, stderr=subprocess.PIPE) + line = p.stderr.splitlines()[-1] + field = line.split(b"|")[-2].strip() + total = int(field) # microseconds + return total diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml index f716974f6add1..9f8174b4fa678 100644 --- a/ci/azure/posix.yml +++ b/ci/azure/posix.yml @@ -9,20 +9,20 @@ jobs: strategy: matrix: ${{ if eq(parameters.name, 'macOS') }}: - py36_macos: - ENV_FILE: ci/deps/azure-macos-36.yaml - CONDA_PY: "36" + py37_macos: + ENV_FILE: ci/deps/azure-macos-37.yaml + CONDA_PY: "37" PATTERN: "not slow and not network" ${{ if eq(parameters.name, 'Linux') }}: - py36_minimum_versions: - ENV_FILE: ci/deps/azure-36-minimum_versions.yaml - CONDA_PY: "36" + py37_minimum_versions: + ENV_FILE: ci/deps/azure-37-minimum_versions.yaml + CONDA_PY: "37" PATTERN: "not slow and not network and not clipboard" - py36_locale_slow_old_np: - ENV_FILE: ci/deps/azure-36-locale_slow.yaml - CONDA_PY: "36" + py37_locale_slow: + ENV_FILE: ci/deps/azure-37-locale_slow.yaml + CONDA_PY: "37" PATTERN: "slow" # pandas does not use the language (zh_CN), but should support different encodings (utf8) # we should test with encodings different than utf8, but doesn't seem like Ubuntu supports any @@ -30,36 +30,36 @@ jobs: LC_ALL: "zh_CN.utf8" EXTRA_APT: "language-pack-zh-hans" - py36_slow: - ENV_FILE: ci/deps/azure-36-slow.yaml - CONDA_PY: "36" + py37_slow: + ENV_FILE: ci/deps/azure-37-slow.yaml + CONDA_PY: "37" PATTERN: "slow" - py36_locale: - ENV_FILE: ci/deps/azure-36-locale.yaml - CONDA_PY: "36" + py37_locale: + ENV_FILE: ci/deps/azure-37-locale.yaml + CONDA_PY: "37" PATTERN: "not slow and not network" LANG: "it_IT.utf8" LC_ALL: "it_IT.utf8" EXTRA_APT: "language-pack-it xsel" - #py36_32bit: - # ENV_FILE: ci/deps/azure-36-32bit.yaml - # CONDA_PY: "36" - # PATTERN: "not slow and not network and not clipboard" - # BITS32: "yes" +# py37_32bit: +# ENV_FILE: ci/deps/azure-37-32bit.yaml +# CONDA_PY: "37" +# PATTERN: "not slow and not network and not clipboard" +# BITS32: "yes" - py37_locale: - ENV_FILE: ci/deps/azure-37-locale.yaml - CONDA_PY: "37" + py38_locale: + ENV_FILE: ci/deps/azure-38-locale.yaml + CONDA_PY: "38" PATTERN: "not slow and not network" LANG: "zh_CN.utf8" LC_ALL: "zh_CN.utf8" EXTRA_APT: "language-pack-zh-hans xsel" - py37_np_dev: - ENV_FILE: ci/deps/azure-37-numpydev.yaml - CONDA_PY: "37" + py38_np_dev: + ENV_FILE: ci/deps/azure-38-numpydev.yaml + CONDA_PY: "38" PATTERN: "not slow and not network" TEST_ARGS: "-W error" PANDAS_TESTING_MODE: "deprecate" diff --git a/ci/azure/windows.yml b/ci/azure/windows.yml index 87f1bfd2adb79..5938ba1fd69f5 100644 --- a/ci/azure/windows.yml +++ b/ci/azure/windows.yml @@ -8,16 +8,16 @@ jobs: vmImage: ${{ parameters.vmImage }} strategy: matrix: - py36_np15: - ENV_FILE: ci/deps/azure-windows-36.yaml - CONDA_PY: "36" - PATTERN: "not slow and not network" - - py37_np18: + py37_np16: ENV_FILE: ci/deps/azure-windows-37.yaml CONDA_PY: "37" PATTERN: "not slow and not network" + py38_np18: + ENV_FILE: ci/deps/azure-windows-38.yaml + CONDA_PY: "38" + PATTERN: "not slow and not network" + steps: - powershell: | Write-Host "##vso[task.prependpath]$env:CONDA\Scripts" diff --git a/ci/deps/azure-36-32bit.yaml b/ci/deps/azure-37-32bit.yaml similarity index 76% rename from ci/deps/azure-36-32bit.yaml rename to ci/deps/azure-37-32bit.yaml index 15704cf0d5427..8e0cd73a9536d 100644 --- a/ci/deps/azure-36-32bit.yaml +++ b/ci/deps/azure-37-32bit.yaml @@ -3,10 +3,10 @@ channels: - defaults - conda-forge dependencies: - - python=3.6.* + - python=3.7.* # tools - ### Cython 0.29.13 and pytest 5.0.1 for 32 bits are not available with conda, installing below with pip instead + ### Cython 0.29.16 and pytest 5.0.1 for 32 bits are not available with conda, installing below with pip instead - pytest-xdist>=1.21 - hypothesis>=3.58.0 - pytest-azurepipelines @@ -15,12 +15,12 @@ dependencies: - attrs=19.1.0 - gcc_linux-32 - gxx_linux-32 - - numpy=1.14.* - python-dateutil - - pytz=2017.2 + - pytz=2017.3 # see comment above - pip - pip: - cython>=0.29.16 + - numpy>=1.16.5 - pytest>=5.0.1 diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml index 6f64c81f299d1..a6552aa096a22 100644 --- a/ci/deps/azure-37-locale.yaml +++ b/ci/deps/azure-37-locale.yaml @@ -1,5 +1,6 @@ name: pandas-dev channels: + - defaults - conda-forge dependencies: - python=3.7.* @@ -22,7 +23,7 @@ dependencies: - moto - nomkl - numexpr - - numpy + - numpy=1.16.* - openpyxl - pytables - python-dateutil @@ -32,7 +33,4 @@ dependencies: - xlrd - xlsxwriter - xlwt - - pyarrow>=0.15 - - pip - - pip: - - pyxlsb + - moto diff --git a/ci/deps/azure-36-locale_slow.yaml b/ci/deps/azure-37-locale_slow.yaml similarity index 67% rename from ci/deps/azure-36-locale_slow.yaml rename to ci/deps/azure-37-locale_slow.yaml index c086b3651afc3..3ccb66e09fe7e 100644 --- a/ci/deps/azure-36-locale_slow.yaml +++ b/ci/deps/azure-37-locale_slow.yaml @@ -3,7 +3,7 @@ channels: - defaults - conda-forge dependencies: - - python=3.6.* + - python=3.7.* # tools - cython>=0.29.16 @@ -16,17 +16,15 @@ dependencies: - beautifulsoup4=4.6.0 - bottleneck=1.2.* - lxml - - matplotlib=2.2.2 - - numpy=1.14.* + - matplotlib=3.0.0 + - numpy=1.16.* - openpyxl=2.5.7 - python-dateutil - python-blosc - - pytz=2017.2 + - pytz=2017.3 - scipy - - sqlalchemy=1.1.4 + - sqlalchemy=1.2.8 - xlrd=1.1.0 - - xlsxwriter=0.9.8 - - xlwt=1.2.0 - - pip - - pip: - - html5lib==1.0b2 + - xlsxwriter=1.0.2 + - xlwt=1.3.0 + - html5lib=1.0.1 diff --git a/ci/deps/azure-36-minimum_versions.yaml b/ci/deps/azure-37-minimum_versions.yaml similarity index 70% rename from ci/deps/azure-36-minimum_versions.yaml rename to ci/deps/azure-37-minimum_versions.yaml index f5af7bcf36189..94cc5812bcc10 100644 --- a/ci/deps/azure-36-minimum_versions.yaml +++ b/ci/deps/azure-37-minimum_versions.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - conda-forge dependencies: - - python=3.6.1 + - python=3.7.1 # tools - cython=0.29.16 @@ -15,16 +15,17 @@ dependencies: # pandas dependencies - beautifulsoup4=4.6.0 - bottleneck=1.2.1 - - jinja2=2.8 + - jinja2=2.10 - numba=0.46.0 - - numexpr=2.6.2 - - numpy=1.15.4 + - numexpr=2.6.8 + - numpy=1.16.5 - openpyxl=2.5.7 - - pytables=3.4.3 + - pytables=3.4.4 - python-dateutil=2.7.3 - - pytz=2017.2 + - pytz=2017.3 + - pyarrow=0.15 - scipy=1.2 - xlrd=1.1.0 - - xlsxwriter=0.9.8 - - xlwt=1.2.0 + - xlsxwriter=1.0.2 + - xlwt=1.3.0 - html5lib=1.0.1 diff --git a/ci/deps/azure-36-slow.yaml b/ci/deps/azure-37-slow.yaml similarity index 96% rename from ci/deps/azure-36-slow.yaml rename to ci/deps/azure-37-slow.yaml index 87bad59fa4873..e8ffd3d74ca5e 100644 --- a/ci/deps/azure-36-slow.yaml +++ b/ci/deps/azure-37-slow.yaml @@ -3,7 +3,7 @@ channels: - defaults - conda-forge dependencies: - - python=3.6.* + - python=3.7.* # tools - cython>=0.29.16 diff --git a/ci/deps/azure-36-locale.yaml b/ci/deps/azure-38-locale.yaml similarity index 69% rename from ci/deps/azure-36-locale.yaml rename to ci/deps/azure-38-locale.yaml index 3034ed3dc43af..c466a5929ea29 100644 --- a/ci/deps/azure-36-locale.yaml +++ b/ci/deps/azure-38-locale.yaml @@ -1,9 +1,8 @@ name: pandas-dev channels: - - defaults - conda-forge dependencies: - - python=3.6.* + - python=3.8.* # tools - cython>=0.29.16 @@ -19,14 +18,12 @@ dependencies: - ipython - jinja2 - lxml - - matplotlib=3.0.* + - matplotlib <3.3.0 + - moto - nomkl - numexpr - - numpy=1.15.* + - numpy - openpyxl - # lowest supported version of pyarrow (putting it here instead of in - # azure-36-minimum_versions because it needs numpy >= 1.14) - - pyarrow=0.13 - pytables - python-dateutil - pytz @@ -35,4 +32,7 @@ dependencies: - xlrd - xlsxwriter - xlwt - - moto + - pyarrow>=0.15 + - pip + - pip: + - pyxlsb diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-38-numpydev.yaml similarity index 96% rename from ci/deps/azure-37-numpydev.yaml rename to ci/deps/azure-38-numpydev.yaml index 5cb58756a6ac1..37592086d49e3 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-38-numpydev.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - defaults dependencies: - - python=3.7.* + - python=3.8.* # tools - pytest>=5.0.1 diff --git a/ci/deps/azure-macos-36.yaml b/ci/deps/azure-macos-37.yaml similarity index 89% rename from ci/deps/azure-macos-36.yaml rename to ci/deps/azure-macos-37.yaml index eeea249a19ca1..a5a69b9a59576 100644 --- a/ci/deps/azure-macos-36.yaml +++ b/ci/deps/azure-macos-37.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - defaults dependencies: - - python=3.6.* + - python=3.7.* # tools - pytest>=5.0.1 @@ -19,9 +19,9 @@ dependencies: - matplotlib=2.2.3 - nomkl - numexpr - - numpy=1.15.4 + - numpy=1.16.5 - openpyxl - - pyarrow>=0.13.0 + - pyarrow>=0.15.0 - pytables - python-dateutil==2.7.3 - pytz diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml index 5bbd0e2795d7e..4d745454afcab 100644 --- a/ci/deps/azure-windows-37.yaml +++ b/ci/deps/azure-windows-37.yaml @@ -23,9 +23,9 @@ dependencies: - matplotlib=2.2.* - moto - numexpr - - numpy=1.18.* + - numpy=1.16.* - openpyxl - - pyarrow=0.14 + - pyarrow=0.15 - pytables - python-dateutil - pytz diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-38.yaml similarity index 84% rename from ci/deps/azure-windows-36.yaml rename to ci/deps/azure-windows-38.yaml index 548660cabaa67..f428a6dadfaa2 100644 --- a/ci/deps/azure-windows-36.yaml +++ b/ci/deps/azure-windows-38.yaml @@ -3,7 +3,7 @@ channels: - conda-forge - defaults dependencies: - - python=3.6.* + - python=3.8.* # tools - cython>=0.29.16 @@ -16,13 +16,13 @@ dependencies: - blosc - bottleneck - fastparquet>=0.3.2 - - matplotlib=3.0.2 + - matplotlib=3.1.3 - numba - numexpr - - numpy=1.15.* + - numpy=1.18.* - openpyxl - jinja2 - - pyarrow>=0.13.0 + - pyarrow>=0.15.0 - pytables - python-dateutil - pytz diff --git a/ci/deps/travis-36-cov.yaml b/ci/deps/travis-37-cov.yaml similarity index 93% rename from ci/deps/travis-36-cov.yaml rename to ci/deps/travis-37-cov.yaml index 177e0d3f4c0af..3a0827a16f97a 100644 --- a/ci/deps/travis-36-cov.yaml +++ b/ci/deps/travis-37-cov.yaml @@ -3,7 +3,7 @@ channels: - defaults - conda-forge dependencies: - - python=3.6.* + - python=3.7.* # tools - cython>=0.29.16 @@ -26,12 +26,12 @@ dependencies: - moto - nomkl - numexpr - - numpy=1.15.* + - numpy=1.16.* - odfpy - openpyxl - pandas-gbq - psycopg2 - - pyarrow>=0.13.0 + - pyarrow>=0.15.0 - pymysql - pytables - python-snappy diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-37-locale.yaml similarity index 85% rename from ci/deps/travis-36-locale.yaml rename to ci/deps/travis-37-locale.yaml index 03a1e751b6a86..4427c1d940bf2 100644 --- a/ci/deps/travis-36-locale.yaml +++ b/ci/deps/travis-37-locale.yaml @@ -3,7 +3,7 @@ channels: - defaults - conda-forge dependencies: - - python=3.6.* + - python=3.7.* # tools - cython>=0.29.16 @@ -19,7 +19,7 @@ dependencies: - html5lib - ipython - jinja2 - - lxml=3.8.0 + - lxml=4.3.0 - matplotlib=3.0.* - moto - nomkl @@ -27,14 +27,14 @@ dependencies: - numpy - openpyxl - pandas-gbq=0.12.0 - - psycopg2=2.6.2 + - psycopg2=2.7 - pymysql=0.7.11 - pytables - python-dateutil - pytz - scipy - - sqlalchemy=1.1.4 - - xarray=0.10 + - sqlalchemy=1.3.0 + - xarray=0.12.0 - xlrd - xlsxwriter - xlwt diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index b79a9cd872c47..7ab150394bf51 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -18,7 +18,7 @@ Instructions for installing from source, Python version support ---------------------- -Officially Python 3.6.1 and above, 3.7, and 3.8. +Officially Python 3.7.1 and above, and 3.8. Installing pandas ----------------- @@ -220,9 +220,9 @@ Dependencies Package Minimum supported version ================================================================ ========================== `setuptools <https://setuptools.readthedocs.io/en/latest/>`__ 24.2.0 -`NumPy <https://www.numpy.org>`__ 1.15.4 +`NumPy <https://www.numpy.org>`__ 1.16.5 `python-dateutil <https://dateutil.readthedocs.io/en/stable/>`__ 2.7.3 -`pytz <https://pypi.org/project/pytz/>`__ 2017.2 +`pytz <https://pypi.org/project/pytz/>`__ 2017.3 ================================================================ ========================== .. _install.recommended_dependencies: @@ -232,7 +232,7 @@ Recommended dependencies * `numexpr <https://github.com/pydata/numexpr>`__: for accelerating certain numerical operations. ``numexpr`` uses multiple cores as well as smart chunking and caching to achieve large speedups. - If installed, must be Version 2.6.2 or higher. + If installed, must be Version 2.6.8 or higher. * `bottleneck <https://github.com/pydata/bottleneck>`__: for accelerating certain types of ``nan`` evaluations. ``bottleneck`` uses specialized cython routines to achieve large speedups. If installed, @@ -259,36 +259,36 @@ the method requiring that dependency is called. Dependency Minimum Version Notes ========================= ================== ============================================================= BeautifulSoup4 4.6.0 HTML parser for read_html (see :ref:`note <optional_html>`) -Jinja2 Conditional formatting with DataFrame.style +Jinja2 2.10 Conditional formatting with DataFrame.style PyQt4 Clipboard I/O PyQt5 Clipboard I/O -PyTables 3.4.3 HDF5-based reading / writing -SQLAlchemy 1.1.4 SQL support for databases other than sqlite -SciPy 0.19.0 Miscellaneous statistical functions -XLsxWriter 0.9.8 Excel writing -blosc Compression for HDF5 +PyTables 3.4.4 HDF5-based reading / writing +SQLAlchemy 1.2.8 SQL support for databases other than sqlite +SciPy 1.12.0 Miscellaneous statistical functions +xlsxwriter 1.0.2 Excel writing +blosc 1.14.3 Compression for HDF5 fsspec 0.7.4 Handling files aside from local and HTTP fastparquet 0.3.2 Parquet reading / writing gcsfs 0.6.0 Google Cloud Storage access -html5lib HTML parser for read_html (see :ref:`note <optional_html>`) -lxml 3.8.0 HTML parser for read_html (see :ref:`note <optional_html>`) -matplotlib 2.2.2 Visualization +html5lib 1.0.1 HTML parser for read_html (see :ref:`note <optional_html>`) +lxml 4.3.0 HTML parser for read_html (see :ref:`note <optional_html>`) +matplotlib 2.2.3 Visualization numba 0.46.0 Alternative execution engine for rolling operations openpyxl 2.5.7 Reading / writing for xlsx files pandas-gbq 0.12.0 Google Big Query access -psycopg2 PostgreSQL engine for sqlalchemy -pyarrow 0.12.0 Parquet, ORC (requires 0.13.0), and feather reading / writing +psycopg2 2.7 PostgreSQL engine for sqlalchemy +pyarrow 0.15.0 Parquet, ORC, and feather reading / writing pymysql 0.7.11 MySQL engine for sqlalchemy pyreadstat SPSS files (.sav) reading -pytables 3.4.3 HDF5 reading / writing +pytables 3.4.4 HDF5 reading / writing pyxlsb 1.0.6 Reading for xlsb files qtpy Clipboard I/O s3fs 0.4.0 Amazon S3 access tabulate 0.8.3 Printing in Markdown-friendly format (see `tabulate`_) -xarray 0.8.2 pandas-like API for N-dimensional data +xarray 0.12.0 pandas-like API for N-dimensional data xclip Clipboard I/O on linux xlrd 1.1.0 Excel reading -xlwt 1.2.0 Excel writing +xlwt 1.3.0 Excel writing xsel Clipboard I/O on linux zlib Compression for HDF5 ========================= ================== ============================================================= diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 94bb265c32e4c..184431ea6f2f6 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -54,6 +54,84 @@ Other enhancements - - +.. _whatsnew_120.api_breaking.python: + +Increased minimum version for Python +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Pandas 1.2.0 supports Python 3.7.1 and higher (:issue:`35214`). + +.. _whatsnew_120.api_breaking.deps: + +Increased minimum versions for dependencies +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Some minimum supported versions of dependencies were updated (:issue:`35214`). +If installed, we now require: + ++-----------------+-----------------+----------+---------+ +| Package | Minimum Version | Required | Changed | ++=================+=================+==========+=========+ +| numpy | 1.16.5 | X | X | ++-----------------+-----------------+----------+---------+ +| pytz | 2017.3 | X | X | ++-----------------+-----------------+----------+---------+ +| python-dateutil | 2.7.3 | X | | ++-----------------+-----------------+----------+---------+ +| bottleneck | 1.2.1 | | | ++-----------------+-----------------+----------+---------+ +| numexpr | 2.6.8 | | X | ++-----------------+-----------------+----------+---------+ +| pytest (dev) | 5.0.1 | | X | ++-----------------+-----------------+----------+---------+ + +For `optional libraries <https://dev.pandas.io/docs/install.html#dependencies>`_ the general recommendation is to use the latest version. +The following table lists the lowest version per library that is currently being tested throughout the development of pandas. +Optional libraries below the lowest tested version may still work, but are not considered supported. + ++-----------------+-----------------+---------+ +| Package | Minimum Version | Changed | ++=================+=================+=========+ +| beautifulsoup4 | 4.6.0 | | ++-----------------+-----------------+---------+ +| fastparquet | 0.3.2 | | ++-----------------+-----------------+---------+ +| fsspec | 0.7.4 | | ++-----------------+-----------------+---------+ +| gcsfs | 0.6.0 | | ++-----------------+-----------------+---------+ +| lxml | 4.3.0 | X | ++-----------------+-----------------+---------+ +| matplotlib | 2.2.3 | X | ++-----------------+-----------------+---------+ +| numba | 0.46.0 | | ++-----------------+-----------------+---------+ +| openpyxl | 2.5.7 | | ++-----------------+-----------------+---------+ +| pyarrow | 0.15.0 | X | ++-----------------+-----------------+---------+ +| pymysql | 0.7.11 | X | ++-----------------+-----------------+---------+ +| pytables | 3.4.4 | X | ++-----------------+-----------------+---------+ +| s3fs | 0.4.0 | | ++-----------------+-----------------+---------+ +| scipy | 1.2.0 | | ++-----------------+-----------------+---------+ +| sqlalchemy | 1.2.8 | X | ++-----------------+-----------------+---------+ +| xarray | 0.12.0 | X | ++-----------------+-----------------+---------+ +| xlrd | 1.1.0 | | ++-----------------+-----------------+---------+ +| xlsxwriter | 1.0.2 | X | ++-----------------+-----------------+---------+ +| xlwt | 1.3.0 | X | ++-----------------+-----------------+---------+ +| pandas-gbq | 0.12.0 | | ++-----------------+-----------------+---------+ + +See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more. .. --------------------------------------------------------------------------- diff --git a/environment.yml b/environment.yml index ed9762e5b8893..1e51470d43d36 100644 --- a/environment.yml +++ b/environment.yml @@ -4,7 +4,7 @@ channels: dependencies: # required # Pin numpy<1.19 until MPL 3.3.0 is released. - - numpy>=1.15,<1.19.0 + - numpy>=1.16.5,<1.19.0 - python=3 - python-dateutil>=2.7.3 - pytz @@ -93,11 +93,11 @@ dependencies: - odfpy - fastparquet>=0.3.2 # pandas.read_parquet, DataFrame.to_parquet - - pyarrow>=0.13.1 # pandas.read_parquet, DataFrame.to_parquet, pandas.read_feather, DataFrame.to_feather + - pyarrow>=0.15.0 # pandas.read_parquet, DataFrame.to_parquet, pandas.read_feather, DataFrame.to_feather - python-snappy # required by pyarrow - pyqt>=5.9.2 # pandas.read_clipboard - - pytables>=3.4.3 # pandas.read_hdf, DataFrame.to_hdf + - pytables>=3.4.4 # pandas.read_hdf, DataFrame.to_hdf - s3fs>=0.4.0 # file IO when using 's3://...' path - fsspec>=0.7.4 # for generic remote file operations - gcsfs>=0.6.0 # file IO when using 'gcs://...' path diff --git a/pandas/__init__.py b/pandas/__init__.py index d6584bf4f1c4f..36576da74c75d 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -20,7 +20,6 @@ # numpy compat from pandas.compat.numpy import ( - _np_version_under1p16, _np_version_under1p17, _np_version_under1p18, _is_numpy_dev, @@ -185,181 +184,76 @@ __git_version__ = v.get("full-revisionid") del get_versions, v + # GH 27101 # TODO: remove Panel compat in 1.0 -if pandas.compat.PY37: - - def __getattr__(name): - import warnings - - if name == "Panel": - - warnings.warn( - "The Panel class is removed from pandas. Accessing it " - "from the top-level namespace will also be removed in the next version", - FutureWarning, - stacklevel=2, - ) - - class Panel: - pass - - return Panel - - elif name == "datetime": - warnings.warn( - "The pandas.datetime class is deprecated " - "and will be removed from pandas in a future version. " - "Import from datetime module instead.", - FutureWarning, - stacklevel=2, - ) - - from datetime import datetime as dt - - return dt - - elif name == "np": - - warnings.warn( - "The pandas.np module is deprecated " - "and will be removed from pandas in a future version. " - "Import numpy directly instead", - FutureWarning, - stacklevel=2, - ) - import numpy as np - - return np - - elif name in {"SparseSeries", "SparseDataFrame"}: - warnings.warn( - f"The {name} class is removed from pandas. Accessing it from " - "the top-level namespace will also be removed in the next version", - FutureWarning, - stacklevel=2, - ) - - return type(name, (), {}) - - elif name == "SparseArray": - - warnings.warn( - "The pandas.SparseArray class is deprecated " - "and will be removed from pandas in a future version. " - "Use pandas.arrays.SparseArray instead.", - FutureWarning, - stacklevel=2, - ) - from pandas.core.arrays.sparse import SparseArray as _SparseArray +def __getattr__(name): + import warnings - return _SparseArray + if name == "Panel": - raise AttributeError(f"module 'pandas' has no attribute '{name}'") + warnings.warn( + "The Panel class is removed from pandas. Accessing it " + "from the top-level namespace will also be removed in the next version", + FutureWarning, + stacklevel=2, + ) + class Panel: + pass -else: + return Panel - class Panel: - pass - - class SparseDataFrame: - pass - - class SparseSeries: - pass - - class __numpy: - def __init__(self): - import numpy as np - import warnings - - self.np = np - self.warnings = warnings - - def __getattr__(self, item): - self.warnings.warn( - "The pandas.np module is deprecated " - "and will be removed from pandas in a future version. " - "Import numpy directly instead", - FutureWarning, - stacklevel=2, - ) - - try: - return getattr(self.np, item) - except AttributeError as err: - raise AttributeError(f"module numpy has no attribute {item}") from err - - np = __numpy() - - class __Datetime(type): + elif name == "datetime": + warnings.warn( + "The pandas.datetime class is deprecated " + "and will be removed from pandas in a future version. " + "Import from datetime module instead.", + FutureWarning, + stacklevel=2, + ) from datetime import datetime as dt - datetime = dt - - def __getattr__(cls, item): - cls.emit_warning() - - try: - return getattr(cls.datetime, item) - except AttributeError as err: - raise AttributeError( - f"module datetime has no attribute {item}" - ) from err - - def __instancecheck__(cls, other): - return isinstance(other, cls.datetime) - - class __DatetimeSub(metaclass=__Datetime): - def emit_warning(dummy=0): - import warnings - - warnings.warn( - "The pandas.datetime class is deprecated " - "and will be removed from pandas in a future version. " - "Import from datetime instead.", - FutureWarning, - stacklevel=3, - ) - - def __new__(cls, *args, **kwargs): - cls.emit_warning() - from datetime import datetime as dt - - return dt(*args, **kwargs) - - datetime = __DatetimeSub + return dt - class __SparseArray(type): + elif name == "np": - from pandas.core.arrays.sparse import SparseArray as sa + warnings.warn( + "The pandas.np module is deprecated " + "and will be removed from pandas in a future version. " + "Import numpy directly instead", + FutureWarning, + stacklevel=2, + ) + import numpy as np - SparseArray = sa + return np - def __instancecheck__(cls, other): - return isinstance(other, cls.SparseArray) + elif name in {"SparseSeries", "SparseDataFrame"}: + warnings.warn( + f"The {name} class is removed from pandas. Accessing it from " + "the top-level namespace will also be removed in the next version", + FutureWarning, + stacklevel=2, + ) - class __SparseArraySub(metaclass=__SparseArray): - def emit_warning(dummy=0): - import warnings + return type(name, (), {}) - warnings.warn( - "The pandas.SparseArray class is deprecated " - "and will be removed from pandas in a future version. " - "Use pandas.arrays.SparseArray instead.", - FutureWarning, - stacklevel=3, - ) + elif name == "SparseArray": - def __new__(cls, *args, **kwargs): - cls.emit_warning() - from pandas.core.arrays.sparse import SparseArray as sa + warnings.warn( + "The pandas.SparseArray class is deprecated " + "and will be removed from pandas in a future version. " + "Use pandas.arrays.SparseArray instead.", + FutureWarning, + stacklevel=2, + ) + from pandas.core.arrays.sparse import SparseArray as _SparseArray - return sa(*args, **kwargs) + return _SparseArray - SparseArray = __SparseArraySub + raise AttributeError(f"module 'pandas' has no attribute '{name}'") # module level doc-string diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index b5a1dc2b2fb94..ab2835932c95d 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -14,7 +14,6 @@ from pandas._typing import F -PY37 = sys.version_info >= (3, 7) PY38 = sys.version_info >= (3, 8) PY39 = sys.version_info >= (3, 9) PYPY = platform.python_implementation() == "PyPy" diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py index 789a4668b6fee..08d06da93bb45 100644 --- a/pandas/compat/numpy/__init__.py +++ b/pandas/compat/numpy/__init__.py @@ -8,19 +8,19 @@ # numpy versioning _np_version = np.__version__ _nlv = LooseVersion(_np_version) -_np_version_under1p16 = _nlv < LooseVersion("1.16") _np_version_under1p17 = _nlv < LooseVersion("1.17") _np_version_under1p18 = _nlv < LooseVersion("1.18") _np_version_under1p19 = _nlv < LooseVersion("1.19") _np_version_under1p20 = _nlv < LooseVersion("1.20") _is_numpy_dev = ".dev" in str(_nlv) +_min_numpy_ver = "1.16.5" -if _nlv < "1.15.4": +if _nlv < _min_numpy_ver: raise ImportError( - "this version of pandas is incompatible with numpy < 1.15.4\n" + f"this version of pandas is incompatible with numpy < {_min_numpy_ver}\n" f"your numpy version is {_np_version}.\n" - "Please upgrade numpy to >= 1.15.4 to use this pandas version" + f"Please upgrade numpy to >= {_min_numpy_ver} to use this pandas version" ) @@ -65,7 +65,6 @@ def np_array_datetime64_compat(arr, *args, **kwargs): __all__ = [ "np", "_np_version", - "_np_version_under1p16", "_np_version_under1p17", "_is_numpy_dev", ] diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 9d0751fcce460..547d86f221b5f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -58,7 +58,6 @@ StorageOptions, ValueKeyFunc, ) -from pandas.compat import PY37 from pandas.compat._optional import import_optional_dependency from pandas.compat.numpy import function as nv from pandas.util._decorators import ( @@ -1088,9 +1087,7 @@ def itertuples(self, index=True, name="Pandas"): # use integer indexing because of possible duplicate column names arrays.extend(self.iloc[:, k] for k in range(len(self.columns))) - # Python versions before 3.7 support at most 255 arguments to constructors - can_return_named_tuples = PY37 or len(self.columns) + index < 255 - if name is not None and can_return_named_tuples: + if name is not None: itertuple = collections.namedtuple(name, fields, rename=True) return map(itertuple._make, zip(*arrays)) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index aeb7b3e044794..2abc570a04de3 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -320,6 +320,10 @@ def read_hdf( mode : {'r', 'r+', 'a'}, default 'r' Mode to use when opening the file. Ignored if path_or_buf is a :class:`pandas.HDFStore`. Default is 'r'. + errors : str, default 'strict' + Specifies how encoding and decoding errors are to be handled. + See the errors argument for :func:`open` for a full list + of options. where : list, optional A list of Term (or convertible) objects. start : int, optional @@ -332,10 +336,6 @@ def read_hdf( Return an iterator object. chunksize : int, optional Number of rows to include in an iteration when using an iterator. - errors : str, default 'strict' - Specifies how encoding and decoding errors are to be handled. - See the errors argument for :func:`open` for a full list - of options. **kwargs Additional keyword arguments passed to HDFStore. diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index caa348d3a1fb9..1d25336cd3b70 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -5,7 +5,7 @@ import pytest import pandas as pd -from pandas import api, compat +from pandas import api import pandas._testing as tm @@ -100,11 +100,6 @@ class TestPDApi(Base): # these should be deprecated in the future deprecated_classes_in_future: List[str] = ["SparseArray"] - if not compat.PY37: - classes.extend(["Panel", "SparseSeries", "SparseDataFrame"]) - # deprecated_modules.extend(["np", "datetime"]) - # deprecated_classes_in_future.extend(["SparseArray"]) - # external modules exposed in pandas namespace modules: List[str] = [] @@ -193,7 +188,6 @@ class TestPDApi(Base): "_hashtable", "_lib", "_libs", - "_np_version_under1p16", "_np_version_under1p17", "_np_version_under1p18", "_is_numpy_dev", @@ -217,14 +211,6 @@ def test_api(self): + self.funcs_to + self.private_modules ) - if not compat.PY37: - checkthese.extend( - self.deprecated_modules - + self.deprecated_classes - + self.deprecated_classes_in_future - + self.deprecated_funcs_in_future - + self.deprecated_funcs - ) self.check(pd, checkthese, self.ignored) def test_depr(self): @@ -237,14 +223,7 @@ def test_depr(self): ) for depr in deprecated_list: with tm.assert_produces_warning(FutureWarning): - deprecated = getattr(pd, depr) - if not compat.PY37: - if depr == "datetime": - deprecated.__getattr__(dir(pd.datetime.datetime)[-1]) - elif depr == "SparseArray": - deprecated([]) - else: - deprecated.__getattr__(dir(deprecated)[-1]) + _ = getattr(pd, depr) def test_datetime(): diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index ca942c9288898..89fbfbd5b8324 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -3,8 +3,6 @@ import numpy as np import pytest -from pandas.compat.numpy import _np_version_under1p16 - from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype from pandas.core.dtypes.dtypes import CategoricalDtype @@ -637,7 +635,6 @@ def test_constructor_imaginary(self): tm.assert_index_equal(c1.categories, Index(values)) tm.assert_numpy_array_equal(np.array(c1), np.array(values)) - @pytest.mark.skipif(_np_version_under1p16, reason="Skipping for NumPy <1.16") def test_constructor_string_and_tuples(self): # GH 21416 c = pd.Categorical(np.array(["c", ("a", "b"), ("b", "a"), "c"], dtype=object)) diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py index 7841360e568ed..12426a0c92c55 100644 --- a/pandas/tests/extension/arrow/test_bool.py +++ b/pandas/tests/extension/arrow/test_bool.py @@ -1,8 +1,6 @@ import numpy as np import pytest -from pandas.compat import PY37 - import pandas as pd import pandas._testing as tm from pandas.tests.extension import base @@ -62,13 +60,11 @@ def test_from_dtype(self, data): def test_from_sequence_from_cls(self, data): super().test_from_sequence_from_cls(data) - @pytest.mark.skipif(not PY37, reason="timeout on Linux py36_locale") @pytest.mark.xfail(reason="pa.NULL is not recognised as scalar, GH-33899") def test_series_constructor_no_data_with_index(self, dtype, na_value): # pyarrow.lib.ArrowInvalid: only handle 1-dimensional arrays super().test_series_constructor_no_data_with_index(dtype, na_value) - @pytest.mark.skipif(not PY37, reason="timeout on Linux py36_locale") @pytest.mark.xfail(reason="pa.NULL is not recognised as scalar, GH-33899") def test_series_constructor_scalar_na_with_index(self, dtype, na_value): # pyarrow.lib.ArrowInvalid: only handle 1-dimensional arrays diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 78000c0252375..b9219f9f833de 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -1,8 +1,6 @@ import numpy as np import pytest -from pandas.compat.numpy import _np_version_under1p16 - import pandas as pd import pandas._testing as tm from pandas.core.arrays.numpy_ import PandasArray, PandasDtype @@ -46,11 +44,7 @@ def data(allow_in_pandas, dtype): @pytest.fixture def data_missing(allow_in_pandas, dtype): - # For NumPy <1.16, np.array([np.nan, (1,)]) raises - # ValueError: setting an array element with a sequence. if dtype.numpy_dtype == "object": - if _np_version_under1p16: - raise pytest.skip("Skipping for NumPy <1.16") return PandasArray(np.array([np.nan, (1,)], dtype=object)) return PandasArray(np.array([np.nan, 1.0])) diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index cc57a3970d18b..2fb1f7f911a9c 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -6,7 +6,6 @@ import numpy as np import pytest -from pandas.compat import PY37 from pandas.util._test_decorators import async_mark, skip_if_no import pandas as pd @@ -274,10 +273,7 @@ def test_itertuples(self, float_frame): # will raise SyntaxError if trying to create namedtuple tup3 = next(df3.itertuples()) assert isinstance(tup3, tuple) - if PY37: - assert hasattr(tup3, "_fields") - else: - assert not hasattr(tup3, "_fields") + assert hasattr(tup3, "_fields") # GH 28282 df_254_columns = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(254)}]) @@ -288,12 +284,7 @@ def test_itertuples(self, float_frame): df_255_columns = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(255)}]) result_255_columns = next(df_255_columns.itertuples(index=False)) assert isinstance(result_255_columns, tuple) - - # Dataframes with >=255 columns will fallback to regular tuples on python < 3.7 - if PY37: - assert hasattr(result_255_columns, "_fields") - else: - assert not hasattr(result_255_columns, "_fields") + assert hasattr(result_255_columns, "_fields") def test_sequence_like_with_categorical(self): diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index d0f774344a33d..c8f5b2b0f6364 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -10,7 +10,7 @@ import pytest import pytz -from pandas.compat import PY37, is_platform_little_endian +from pandas.compat import is_platform_little_endian from pandas.compat.numpy import _np_version_under1p19 from pandas.core.dtypes.common import is_integer_dtype @@ -1418,7 +1418,6 @@ def test_constructor_list_of_namedtuples(self): result = DataFrame(tuples, columns=["y", "z"]) tm.assert_frame_equal(result, expected) - @pytest.mark.skipif(not PY37, reason="Requires Python >= 3.7") def test_constructor_list_of_dataclasses(self): # GH21910 from dataclasses import make_dataclass @@ -1430,7 +1429,6 @@ def test_constructor_list_of_dataclasses(self): result = DataFrame(datas) tm.assert_frame_equal(result, expected) - @pytest.mark.skipif(not PY37, reason="Requires Python >= 3.7") def test_constructor_list_of_dataclasses_with_varying_types(self): # GH21910 from dataclasses import make_dataclass @@ -1447,7 +1445,6 @@ def test_constructor_list_of_dataclasses_with_varying_types(self): result = DataFrame(datas) tm.assert_frame_equal(result, expected) - @pytest.mark.skipif(not PY37, reason="Requires Python >= 3.7") def test_constructor_list_of_dataclasses_error_thrown(self): # GH21910 from dataclasses import make_dataclass diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index c74c1529eb537..13a32e285e70a 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -3,8 +3,6 @@ import numpy as np import pytest -from pandas.compat import PY37, is_platform_windows - import pandas as pd from pandas import ( Categorical, @@ -13,7 +11,6 @@ Index, MultiIndex, Series, - _np_version_under1p17, qcut, ) import pandas._testing as tm @@ -244,12 +241,6 @@ def test_level_get_group(observed): tm.assert_frame_equal(result, expected) -# GH#21636 flaky on py37; may be related to older numpy, see discussion -# https://github.com/MacPython/pandas-wheels/pull/64 -@pytest.mark.xfail( - PY37 and _np_version_under1p17 and not is_platform_windows(), - reason="Flaky, GH-27902", -) @pytest.mark.parametrize("ordered", [True, False]) def test_apply(ordered): # GH 10138 diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index 22b4ec189a0f1..8f1ed193b100f 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -256,6 +256,9 @@ def test_read_json_from_to_json_results(self): tm.assert_frame_equal(result1, df) tm.assert_frame_equal(result2, df) + @pytest.mark.filterwarnings( + "ignore:an integer is required (got type float)*:DeprecationWarning" + ) def test_to_json(self): df = self.df.copy() df.index.name = "idx" @@ -432,6 +435,9 @@ def test_to_json_categorical_index(self): assert result == expected + @pytest.mark.filterwarnings( + "ignore:an integer is required (got type float)*:DeprecationWarning" + ) def test_date_format_raises(self): with pytest.raises(ValueError): self.df.to_json(orient="table", date_format="epoch") diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index c4db0170ecc90..1280d0fd434d5 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -35,6 +35,9 @@ def assert_json_roundtrip_equal(result, expected, orient): tm.assert_frame_equal(result, expected) +@pytest.mark.filterwarnings( + "ignore:an integer is required (got type float)*:DeprecationWarning" +) @pytest.mark.filterwarnings("ignore:the 'numpy' keyword is deprecated:FutureWarning") class TestPandasContainer: @pytest.fixture(autouse=True) diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index 5154a9ba6fdf0..c84c0048cc838 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -1138,6 +1138,7 @@ def test_parse_integers_above_fp_precision(all_parsers): tm.assert_frame_equal(result, expected) +@pytest.mark.skip("unreliable test #35214") def test_chunks_have_consistent_numerical_type(all_parsers): parser = all_parsers integers = [str(i) for i in range(499999)] @@ -1151,6 +1152,7 @@ def test_chunks_have_consistent_numerical_type(all_parsers): assert result.a.dtype == float +@pytest.mark.skip("unreliable test #35214") def test_warn_if_chunks_have_mismatched_type(all_parsers): warning_type = None parser = all_parsers diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 03830019affa1..09d5d9c1677d0 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -308,10 +308,6 @@ def test_overlap_public_nat_methods(klass, expected): # In case when Timestamp, Timedelta, and NaT are overlap, the overlap # is considered to be with Timestamp and NaT, not Timedelta. - # "fromisoformat" was introduced in 3.7 - if klass is Timestamp and not compat.PY37: - expected.remove("fromisoformat") - # "fromisocalendar" was introduced in 3.8 if klass is Timestamp and not compat.PY38: expected.remove("fromisocalendar") diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 8c51908c547f4..d1ab797056ece 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -14,7 +14,6 @@ import pandas._libs.tslibs.offsets as liboffsets from pandas._libs.tslibs.offsets import ApplyTypeError, _get_offset, _offset_map from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG -import pandas.compat as compat from pandas.compat.numpy import np_datetime64_compat from pandas.errors import PerformanceWarning @@ -744,10 +743,7 @@ def test_repr(self): assert repr(self.offset) == "<BusinessDay>" assert repr(self.offset2) == "<2 * BusinessDays>" - if compat.PY37: - expected = "<BusinessDay: offset=datetime.timedelta(days=1)>" - else: - expected = "<BusinessDay: offset=datetime.timedelta(1)>" + expected = "<BusinessDay: offset=datetime.timedelta(days=1)>" assert repr(self.offset + timedelta(1)) == expected def test_with_offset(self): @@ -2636,10 +2632,7 @@ def test_repr(self): assert repr(self.offset) == "<CustomBusinessDay>" assert repr(self.offset2) == "<2 * CustomBusinessDays>" - if compat.PY37: - expected = "<BusinessDay: offset=datetime.timedelta(days=1)>" - else: - expected = "<BusinessDay: offset=datetime.timedelta(1)>" + expected = "<BusinessDay: offset=datetime.timedelta(days=1)>" assert repr(self.offset + timedelta(1)) == expected def test_with_offset(self): diff --git a/pandas/util/__init__.py b/pandas/util/__init__.py index b5271dbc0443e..9f2bf156b7e37 100644 --- a/pandas/util/__init__.py +++ b/pandas/util/__init__.py @@ -1,30 +1,12 @@ from pandas.util._decorators import Appender, Substitution, cache_readonly # noqa -from pandas import compat from pandas.core.util.hashing import hash_array, hash_pandas_object # noqa -# compatibility for import pandas; pandas.util.testing -if compat.PY37: +def __getattr__(name): + if name == "testing": + import pandas.util.testing - def __getattr__(name): - if name == "testing": - import pandas.util.testing - - return pandas.util.testing - else: - raise AttributeError(f"module 'pandas.util' has no attribute '{name}'") - - -else: - - class _testing: - def __getattr__(self, item): - import pandas.util.testing - - return getattr(pandas.util.testing, item) - - testing = _testing() - - -del compat + return pandas.util.testing + else: + raise AttributeError(f"module 'pandas.util' has no attribute '{name}'") diff --git a/pyproject.toml b/pyproject.toml index f282f2a085000..f6f8081b6c464 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,16 +5,14 @@ requires = [ "setuptools", "wheel", "Cython>=0.29.16,<3", # Note: sync with setup.py - "numpy==1.15.4; python_version=='3.6' and platform_system!='AIX'", - "numpy==1.15.4; python_version=='3.7' and platform_system!='AIX'", + "numpy==1.16.5; python_version=='3.7' and platform_system!='AIX'", "numpy==1.17.3; python_version>='3.8' and platform_system!='AIX'", - "numpy==1.16.0; python_version=='3.6' and platform_system=='AIX'", - "numpy==1.16.0; python_version=='3.7' and platform_system=='AIX'", + "numpy==1.16.5; python_version=='3.7' and platform_system=='AIX'", "numpy==1.17.3; python_version>='3.8' and platform_system=='AIX'", ] [tool.black] -target-version = ['py36', 'py37', 'py38'] +target-version = ['py37', 'py38'] exclude = ''' ( asv_bench/env diff --git a/requirements-dev.txt b/requirements-dev.txt index 6a87b0a99a4f8..66e72641cd5bb 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,7 +1,7 @@ # This file is auto-generated from environment.yml, do not modify. # See that file for comments about the need/usage of each dependency. -numpy>=1.15,<1.19.0 +numpy>=1.16.5,<1.19.0 python-dateutil>=2.7.3 pytz asv @@ -60,10 +60,10 @@ xlsxwriter xlwt odfpy fastparquet>=0.3.2 -pyarrow>=0.13.1 +pyarrow>=0.15.0 python-snappy pyqt5>=5.9.2 -tables>=3.4.3 +tables>=3.4.4 s3fs>=0.4.0 fsspec>=0.7.4 gcsfs>=0.6.0 diff --git a/setup.py b/setup.py index aebbdbf4d1e96..43d19d525876b 100755 --- a/setup.py +++ b/setup.py @@ -33,7 +33,7 @@ def is_platform_mac(): return sys.platform == "darwin" -min_numpy_ver = "1.15.4" +min_numpy_ver = "1.16.5" min_cython_ver = "0.29.16" # note: sync with pyproject.toml try: @@ -197,7 +197,6 @@ def build_extensions(self): "Intended Audience :: Science/Research", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Cython", @@ -742,7 +741,7 @@ def setup_package(): setuptools_kwargs = { "install_requires": [ "python-dateutil >= 2.7.3", - "pytz >= 2017.2", + "pytz >= 2017.3", f"numpy >= {min_numpy_ver}", ], "setup_requires": [f"numpy >= {min_numpy_ver}"], @@ -766,11 +765,11 @@ def setup_package(): long_description=LONG_DESCRIPTION, classifiers=CLASSIFIERS, platforms="any", - python_requires=">=3.6.1", + python_requires=">=3.7.1", extras_require={ "test": [ # sync with setup.cfg minversion & install.rst - "pytest>=4.0.2", + "pytest>=5.0.1", "pytest-xdist", "hypothesis>=3.58", ]
- [x] closes #34472 - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35214
2020-07-10T15:04:33Z
2020-08-11T01:17:48Z
2020-08-11T01:17:47Z
2020-08-11T16:10:21Z
Add xarray copyright notice to comply with reuse under Apache License
diff --git a/LICENSES/XARRAY_LICENSE b/LICENSES/XARRAY_LICENSE index 37ec93a14fdcd..6bafeb9d3d80e 100644 --- a/LICENSES/XARRAY_LICENSE +++ b/LICENSES/XARRAY_LICENSE @@ -1,3 +1,7 @@ +Copyright 2014-2019, xarray Developers + +-------------------------------------------------------------------------------- + Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
In https://github.com/xarray-contrib/pint-xarray/pull/11, @keewis and I noticed that pandas's (pandas'?...possessive forms are weird) reuse with modification of xarray code added in https://github.com/pandas-dev/pandas/commit/eee83e23ba0c5b32e27db3faca931ddb4c9619aa did not include xarray's copyright notice as required by the Apache License, Version 2.0 (which is not included in the license text itself, unlike MIT or BSD). I'm not sure how big of a deal this is, but given that pint-xarray is going ahead and modeling its code citation practice after that of pandas, I wanted to see what the thoughts are here on it. This PR takes a simple fix and just adds the copyright notice to top of the `LICENSES/XARRAY_LICENSE` file. Also, I'm not sure if this requires a whatsnew entry or not. - ~~closes #xxxx~~ - ~~tests added / passed~~ - ~~passes `black pandas`~~ - ~~passes `git diff upstream/master -u -- "*.py" | flake8 --diff`~~ - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35213
2020-07-10T14:24:58Z
2020-07-10T14:55:39Z
2020-07-10T14:55:39Z
2020-07-10T14:55:40Z
Fix strange behavior when precision display option is zero (#20359)
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5dff6d729479a..bff3e2fcdb267 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1018,6 +1018,7 @@ MultiIndex I/O ^^^ +- Bug in print-out when ``display.precision`` is zero. (:issue:`20359`) - Bug in :meth:`read_json` where integer overflow was occurring when json contains big number strings. (:issue:`30320`) - `read_csv` will now raise a ``ValueError`` when the arguments `header` and `prefix` both are not `None`. (:issue:`27394`) - Bug in :meth:`DataFrame.to_json` was raising ``NotFoundError`` when ``path_or_buf`` was an S3 URI (:issue:`28375`) diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 22cdd8e235e0b..27df014620f56 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1382,9 +1382,9 @@ def format_values_with(float_format): if self.fixed_width: if is_complex: - result = _trim_zeros_complex(values, na_rep) + result = _trim_zeros_complex(values, self.decimal, na_rep) else: - result = _trim_zeros_float(values, na_rep) + result = _trim_zeros_float(values, self.decimal, na_rep) return np.asarray(result, dtype="object") return values @@ -1754,19 +1754,21 @@ def just(x): return result -def _trim_zeros_complex(str_complexes: np.ndarray, na_rep: str = "NaN") -> List[str]: +def _trim_zeros_complex( + str_complexes: np.ndarray, decimal: str = ".", na_rep: str = "NaN" +) -> List[str]: """ Separates the real and imaginary parts from the complex number, and executes the _trim_zeros_float method on each of those. """ return [ - "".join(_trim_zeros_float(re.split(r"([j+-])", x), na_rep)) + "".join(_trim_zeros_float(re.split(r"([j+-])", x), decimal, na_rep)) for x in str_complexes ] def _trim_zeros_float( - str_floats: Union[np.ndarray, List[str]], na_rep: str = "NaN" + str_floats: Union[np.ndarray, List[str]], decimal: str = ".", na_rep: str = "NaN" ) -> List[str]: """ Trims zeros, leaving just one before the decimal points if need be. @@ -1778,8 +1780,11 @@ def _is_number(x): def _cond(values): finite = [x for x in values if _is_number(x)] + has_decimal = [decimal in x for x in finite] + return ( len(finite) > 0 + and all(has_decimal) and all(x.endswith("0") for x in finite) and not (any(("e" in x) or ("E" in x) for x in finite)) ) @@ -1788,7 +1793,7 @@ def _cond(values): trimmed = [x[:-1] if _is_number(x) else x for x in trimmed] # leave one 0 after the decimal points if need be. - return [x + "0" if x.endswith(".") and _is_number(x) else x for x in trimmed] + return [x + "0" if x.endswith(decimal) and _is_number(x) else x for x in trimmed] def _has_names(index: Index) -> bool: diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 3c40a2ae8d6b8..e236b3da73c69 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -2910,6 +2910,15 @@ def test_format(self): assert result[0] == " 12.0" assert result[1] == " 0.0" + def test_output_display_precision_trailing_zeroes(self): + # Issue #20359: trimming zeros while there is no decimal point + + # Happens when display precision is set to zero + with pd.option_context("display.precision", 0): + s = pd.Series([840.0, 4200.0]) + expected_output = "0 840\n1 4200\ndtype: float64" + assert str(s) == expected_output + def test_output_significant_digits(self): # Issue #9764
- [x] closes #20359 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Notes: - [x] I added a unit test for the example given in #20359 - [x] As far as the context of this code is concerned, I replacde '.' with decimal string (passed from self when called) in case of non-standard decimal use
https://api.github.com/repos/pandas-dev/pandas/pulls/35212
2020-07-10T13:15:20Z
2020-07-10T19:33:14Z
2020-07-10T19:33:13Z
2020-07-17T09:29:04Z
Tst return none inplace series
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index 737e21af9242f..3ed25b8bca566 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -736,14 +736,16 @@ def test_append_timedelta_does_not_cast(td): def test_underlying_data_conversion(): # GH 4080 df = DataFrame({c: [1, 2, 3] for c in ["a", "b", "c"]}) - df.set_index(["a", "b", "c"], inplace=True) + return_value = df.set_index(["a", "b", "c"], inplace=True) + assert return_value is None s = Series([1], index=[(2, 2, 2)]) df["val"] = 0 df df["val"].update(s) expected = DataFrame(dict(a=[1, 2, 3], b=[1, 2, 3], c=[1, 2, 3], val=[0, 1, 0])) - expected.set_index(["a", "b", "c"], inplace=True) + return_value = expected.set_index(["a", "b", "c"], inplace=True) + assert return_value is None tm.assert_frame_equal(df, expected) # GH 3970 diff --git a/pandas/tests/series/methods/test_drop_duplicates.py b/pandas/tests/series/methods/test_drop_duplicates.py index a4532ebb3d8c5..40651c4342e8a 100644 --- a/pandas/tests/series/methods/test_drop_duplicates.py +++ b/pandas/tests/series/methods/test_drop_duplicates.py @@ -22,7 +22,8 @@ def test_drop_duplicates(any_numpy_dtype, keep, expected): tm.assert_series_equal(tc.duplicated(keep=keep), expected) tm.assert_series_equal(tc.drop_duplicates(keep=keep), tc[~expected]) sc = tc.copy() - sc.drop_duplicates(keep=keep, inplace=True) + return_value = sc.drop_duplicates(keep=keep, inplace=True) + assert return_value is None tm.assert_series_equal(sc, tc[~expected]) @@ -40,8 +41,9 @@ def test_drop_duplicates_bool(keep, expected): tm.assert_series_equal(tc.duplicated(keep=keep), expected) tm.assert_series_equal(tc.drop_duplicates(keep=keep), tc[~expected]) sc = tc.copy() - sc.drop_duplicates(keep=keep, inplace=True) + return_value = sc.drop_duplicates(keep=keep, inplace=True) tm.assert_series_equal(sc, tc[~expected]) + assert return_value is None @pytest.mark.parametrize("values", [[], list(range(5))]) @@ -84,21 +86,24 @@ def test_drop_duplicates_categorical_non_bool(self, dtype, ordered): tm.assert_series_equal(tc1.duplicated(), expected) tm.assert_series_equal(tc1.drop_duplicates(), tc1[~expected]) sc = tc1.copy() - sc.drop_duplicates(inplace=True) + return_value = sc.drop_duplicates(inplace=True) + assert return_value is None tm.assert_series_equal(sc, tc1[~expected]) expected = Series([False, False, True, False]) tm.assert_series_equal(tc1.duplicated(keep="last"), expected) tm.assert_series_equal(tc1.drop_duplicates(keep="last"), tc1[~expected]) sc = tc1.copy() - sc.drop_duplicates(keep="last", inplace=True) + return_value = sc.drop_duplicates(keep="last", inplace=True) + assert return_value is None tm.assert_series_equal(sc, tc1[~expected]) expected = Series([False, False, True, True]) tm.assert_series_equal(tc1.duplicated(keep=False), expected) tm.assert_series_equal(tc1.drop_duplicates(keep=False), tc1[~expected]) sc = tc1.copy() - sc.drop_duplicates(keep=False, inplace=True) + return_value = sc.drop_duplicates(keep=False, inplace=True) + assert return_value is None tm.assert_series_equal(sc, tc1[~expected]) # Test case 2 @@ -113,21 +118,24 @@ def test_drop_duplicates_categorical_non_bool(self, dtype, ordered): tm.assert_series_equal(tc2.duplicated(), expected) tm.assert_series_equal(tc2.drop_duplicates(), tc2[~expected]) sc = tc2.copy() - sc.drop_duplicates(inplace=True) + return_value = sc.drop_duplicates(inplace=True) + assert return_value is None tm.assert_series_equal(sc, tc2[~expected]) expected = Series([False, True, True, False, False, False, False]) tm.assert_series_equal(tc2.duplicated(keep="last"), expected) tm.assert_series_equal(tc2.drop_duplicates(keep="last"), tc2[~expected]) sc = tc2.copy() - sc.drop_duplicates(keep="last", inplace=True) + return_value = sc.drop_duplicates(keep="last", inplace=True) + assert return_value is None tm.assert_series_equal(sc, tc2[~expected]) expected = Series([False, True, True, False, True, True, False]) tm.assert_series_equal(tc2.duplicated(keep=False), expected) tm.assert_series_equal(tc2.drop_duplicates(keep=False), tc2[~expected]) sc = tc2.copy() - sc.drop_duplicates(keep=False, inplace=True) + return_value = sc.drop_duplicates(keep=False, inplace=True) + assert return_value is None tm.assert_series_equal(sc, tc2[~expected]) def test_drop_duplicates_categorical_bool(self, ordered): @@ -141,19 +149,22 @@ def test_drop_duplicates_categorical_bool(self, ordered): tm.assert_series_equal(tc.duplicated(), expected) tm.assert_series_equal(tc.drop_duplicates(), tc[~expected]) sc = tc.copy() - sc.drop_duplicates(inplace=True) + return_value = sc.drop_duplicates(inplace=True) + assert return_value is None tm.assert_series_equal(sc, tc[~expected]) expected = Series([True, True, False, False]) tm.assert_series_equal(tc.duplicated(keep="last"), expected) tm.assert_series_equal(tc.drop_duplicates(keep="last"), tc[~expected]) sc = tc.copy() - sc.drop_duplicates(keep="last", inplace=True) + return_value = sc.drop_duplicates(keep="last", inplace=True) + assert return_value is None tm.assert_series_equal(sc, tc[~expected]) expected = Series([True, True, True, True]) tm.assert_series_equal(tc.duplicated(keep=False), expected) tm.assert_series_equal(tc.drop_duplicates(keep=False), tc[~expected]) sc = tc.copy() - sc.drop_duplicates(keep=False, inplace=True) + return_value = sc.drop_duplicates(keep=False, inplace=True) + assert return_value is None tm.assert_series_equal(sc, tc[~expected]) diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index c34838be24fc1..80b8271e16e7a 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -67,7 +67,8 @@ def test_fillna_numeric_inplace(self): x = Series([np.nan, 1.0, np.nan, 3.0, np.nan], ["z", "a", "b", "c", "d"]) y = x.copy() - y.fillna(value=0, inplace=True) + return_value = y.fillna(value=0, inplace=True) + assert return_value is None expected = x.fillna(value=0) tm.assert_series_equal(y, expected) diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index 8f57cf3191d5d..11802c59a29da 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -13,7 +13,8 @@ def test_replace(self, datetime_series): ser[6:10] = 0 # replace list with a single value - ser.replace([np.nan], -1, inplace=True) + return_value = ser.replace([np.nan], -1, inplace=True) + assert return_value is None exp = ser.fillna(-1) tm.assert_series_equal(ser, exp) @@ -48,7 +49,8 @@ def test_replace(self, datetime_series): tm.assert_series_equal(rs, rs2) # replace inplace - ser.replace([np.nan, "foo", "bar"], -1, inplace=True) + return_value = ser.replace([np.nan, "foo", "bar"], -1, inplace=True) + assert return_value is None assert (ser[:5] == -1).all() assert (ser[6:10] == -1).all() @@ -124,7 +126,8 @@ def test_replace_with_single_list(self): tm.assert_series_equal(result, pd.Series([0, 0, 0, 0, 4])) s = ser.copy() - s.replace([1, 2, 3], inplace=True) + return_value = s.replace([1, 2, 3], inplace=True) + assert return_value is None tm.assert_series_equal(s, pd.Series([0, 0, 0, 0, 4])) # make sure things don't get corrupted when fillna call fails @@ -134,7 +137,8 @@ def test_replace_with_single_list(self): r"\(bfill\)\. Got crash_cymbal" ) with pytest.raises(ValueError, match=msg): - s.replace([1, 2, 3], inplace=True, method="crash_cymbal") + return_value = s.replace([1, 2, 3], inplace=True, method="crash_cymbal") + assert return_value is None tm.assert_series_equal(s, ser) def test_replace_with_empty_list(self): @@ -156,7 +160,8 @@ def test_replace_mixed_types(self): def check_replace(to_rep, val, expected): sc = s.copy() r = s.replace(to_rep, val) - sc.replace(to_rep, val, inplace=True) + return_value = sc.replace(to_rep, val, inplace=True) + assert return_value is None tm.assert_series_equal(expected, r) tm.assert_series_equal(expected, sc) @@ -242,7 +247,8 @@ def test_replace2(self): tm.assert_series_equal(rs, rs2) # replace inplace - ser.replace([np.nan, "foo", "bar"], -1, inplace=True) + return_value = ser.replace([np.nan, "foo", "bar"], -1, inplace=True) + assert return_value is None assert (ser[:5] == -1).all() assert (ser[6:10] == -1).all() assert (ser[20:30] == -1).all() @@ -325,11 +331,13 @@ def test_replace_categorical_single(self): tm.assert_series_equal(expected, result) assert c[2] != "foo" # ensure non-inplace call does not alter original - c.replace(c[2], "foo", inplace=True) + return_value = c.replace(c[2], "foo", inplace=True) + assert return_value is None tm.assert_series_equal(expected, c) first_value = c[0] - c.replace(c[1], c[0], inplace=True) + return_value = c.replace(c[1], c[0], inplace=True) + assert return_value is None assert c[0] == c[1] == first_value # test replacing with existing value def test_replace_with_no_overflowerror(self): diff --git a/pandas/tests/series/methods/test_reset_index.py b/pandas/tests/series/methods/test_reset_index.py index 597b43a370ef5..1474bb95f4af2 100644 --- a/pandas/tests/series/methods/test_reset_index.py +++ b/pandas/tests/series/methods/test_reset_index.py @@ -22,7 +22,8 @@ def test_reset_index(self): # check inplace s = ser.reset_index(drop=True) s2 = ser - s2.reset_index(drop=True, inplace=True) + return_value = s2.reset_index(drop=True, inplace=True) + assert return_value is None tm.assert_series_equal(s, s2) # level diff --git a/pandas/tests/series/methods/test_sort_values.py b/pandas/tests/series/methods/test_sort_values.py index b32c59b4daa0d..b49e39d4592ea 100644 --- a/pandas/tests/series/methods/test_sort_values.py +++ b/pandas/tests/series/methods/test_sort_values.py @@ -65,7 +65,8 @@ def test_sort_values(self, datetime_series): # inplace=True ts = datetime_series.copy() - ts.sort_values(ascending=False, inplace=True) + return_value = ts.sort_values(ascending=False, inplace=True) + assert return_value is None tm.assert_series_equal(ts, datetime_series.sort_values(ascending=False)) tm.assert_index_equal( ts.index, datetime_series.sort_values(ascending=False).index diff --git a/pandas/tests/series/methods/test_truncate.py b/pandas/tests/series/methods/test_truncate.py index 8a2c62cee7e24..7c82edbaec177 100644 --- a/pandas/tests/series/methods/test_truncate.py +++ b/pandas/tests/series/methods/test_truncate.py @@ -136,7 +136,8 @@ def test_truncate_multiindex(self): df = pd.DataFrame.from_dict( {"L1": [2, 2, 3, 3], "L2": ["A", "B", "A", "B"], "col": [2, 3, 4, 5]} ) - df.set_index(["L1", "L2"], inplace=True) + return_value = df.set_index(["L1", "L2"], inplace=True) + assert return_value is None expected = df.col tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 042841bb4e019..b174eb0e42776 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -179,7 +179,8 @@ def test_constructor_dict_timedelta_index(self): def test_sparse_accessor_updates_on_inplace(self): s = pd.Series([1, 1, 2, 3], dtype="Sparse[int]") - s.drop([0, 1], inplace=True) + return_value = s.drop([0, 1], inplace=True) + assert return_value is None assert s.sparse.density == 1.0 def test_tab_completion(self): @@ -459,7 +460,8 @@ def f(x): def test_str_accessor_updates_on_inplace(self): s = pd.Series(list("abc")) - s.drop([0], inplace=True) + return_value = s.drop([0], inplace=True) + assert return_value is None assert len(s.str.lower()) == 2 def test_str_attribute(self): @@ -548,7 +550,8 @@ def test_cat_accessor(self): assert not s.cat.ordered, False exp = Categorical(["a", "b", np.nan, "a"], categories=["b", "a"]) - s.cat.set_categories(["b", "a"], inplace=True) + return_value = s.cat.set_categories(["b", "a"], inplace=True) + assert return_value is None tm.assert_categorical_equal(s.values, exp) res = s.cat.set_categories(["b", "a"]) @@ -579,8 +582,10 @@ def test_cat_accessor_no_new_attributes(self): def test_cat_accessor_updates_on_inplace(self): s = Series(list("abc")).astype("category") - s.drop(0, inplace=True) - s.cat.remove_unused_categories(inplace=True) + return_value = s.drop(0, inplace=True) + assert return_value is None + return_value = s.cat.remove_unused_categories(inplace=True) + assert return_value is None assert len(s.cat.categories) == 2 def test_categorical_delegations(self): @@ -614,7 +619,8 @@ def test_categorical_delegations(self): assert s.cat.ordered s = s.cat.as_unordered() assert not s.cat.ordered - s.cat.as_ordered(inplace=True) + return_value = s.cat.as_ordered(inplace=True) + assert return_value is None assert s.cat.ordered # reorder diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index 0fd51b8828bc5..d2ad9c8c398ea 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -625,7 +625,8 @@ def test_dt_accessor_invalid(self, ser): def test_dt_accessor_updates_on_inplace(self): s = Series(pd.date_range("2018-01-01", periods=10)) s[2] = None - s.fillna(pd.Timestamp("2018-01-01"), inplace=True) + return_value = s.fillna(pd.Timestamp("2018-01-01"), inplace=True) + assert return_value is None result = s.dt.date assert result[0] == result[2] diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 162778e372426..0144e4257efe0 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -453,7 +453,8 @@ def test_fillna_downcast(self): def test_fillna_int(self): s = Series(np.random.randint(-100, 100, 50)) - s.fillna(method="ffill", inplace=True) + return_value = s.fillna(method="ffill", inplace=True) + assert return_value is None tm.assert_series_equal(s.fillna(method="ffill", inplace=False), s) def test_categorical_nan_equality(self): @@ -680,7 +681,8 @@ def test_dropna_empty(self): s = Series([], dtype=object) assert len(s.dropna()) == 0 - s.dropna(inplace=True) + return_value = s.dropna(inplace=True) + assert return_value is None assert len(s) == 0 # invalid axis @@ -729,7 +731,8 @@ def test_dropna_no_nan(self): assert result is not s s2 = s.copy() - s2.dropna(inplace=True) + return_value = s2.dropna(inplace=True) + assert return_value is None tm.assert_series_equal(s2, s) def test_dropna_intervals(self): @@ -775,7 +778,8 @@ def test_pad_nan(self): [np.nan, 1.0, np.nan, 3.0, np.nan], ["z", "a", "b", "c", "d"], dtype=float ) - x.fillna(method="pad", inplace=True) + return_value = x.fillna(method="pad", inplace=True) + assert return_value is None expected = Series( [np.nan, 1.0, 1.0, 3.0, 3.0], ["z", "a", "b", "c", "d"], dtype=float @@ -799,7 +803,8 @@ def test_dropna_preserve_name(self, datetime_series): assert result.name == datetime_series.name name = datetime_series.name ts = datetime_series.copy() - ts.dropna(inplace=True) + return_value = ts.dropna(inplace=True) + assert return_value is None assert ts.name == name def test_series_fillna_limit(self):
verify we return None for all inplace calls in /series related: https://github.com/pandas-dev/pandas/pull/35181#event-3531612625
https://api.github.com/repos/pandas-dev/pandas/pulls/35210
2020-07-10T10:13:39Z
2020-07-10T19:32:34Z
2020-07-10T19:32:34Z
2020-07-10T19:32:38Z
ROADMAP: add consistent missing values for all dtypes to the roadmap
diff --git a/doc/source/development/roadmap.rst b/doc/source/development/roadmap.rst index d331491d02883..efee21b5889ed 100644 --- a/doc/source/development/roadmap.rst +++ b/doc/source/development/roadmap.rst @@ -53,6 +53,32 @@ need to implement certain operations expected by pandas users (for example the algorithm used in, ``Series.str.upper``). That work may be done outside of pandas. +Consistent missing value handling +--------------------------------- + +Currently, pandas handles missing data differently for different data types. We +use different types to indicate that a value is missing (``np.nan`` for +floating-point data, ``np.nan`` or ``None`` for object-dtype data -- typically +strings or booleans -- with missing values, and ``pd.NaT`` for datetimelike +data). Integer data cannot store missing data or are cast to float. In addition, +pandas 1.0 introduced a new missing value sentinel, ``pd.NA``, which is being +used for the experimental nullable integer, boolean, and string data types. + +These different missing values have different behaviors in user-facing +operations. Specifically, we introduced different semantics for the nullable +data types for certain operations (e.g. propagating in comparison operations +instead of comparing as False). + +Long term, we want to introduce consistent missing data handling for all data +types. This includes consistent behavior in all operations (indexing, arithmetic +operations, comparisons, etc.). We want to eventually make the new semantics the +default. + +This has been discussed at +`github #28095 <https://github.com/pandas-dev/pandas/issues/28095>`__ (and +linked issues), and described in more detail in this +`design doc <https://hackmd.io/@jorisvandenbossche/Sk0wMeAmB>`__. + Apache Arrow interoperability -----------------------------
The more detailed motivation is described in https://hackmd.io/@jorisvandenbossche/Sk0wMeAmB, and many aspects have already been discussed in https://github.com/pandas-dev/pandas/issues/28095 and linked issues. (and there are probably still other details / practical aspects that can be further discussed in dedicated issues) Last year when I made the `pd.NA` proposal (and which resulted in using that for the nullable integer, boolean and string dtypes), which described it as "can be used consistently across all data types", the implicit / aspirational end goal of this proposal for me always was to *actually* have this for all dtypes (and as the default, at some point). I tried to discuss this goal more explicitly on the mailing list earlier this year (in the thread about pandas 2.0: https://mail.python.org/pipermail/pandas-dev/2020-February/001180.html). But we never really "officially" adopted this as a goal / roadmap item, or discussed about doing that. Proposing to add a section about it to the roadmap is an attempt to do this (as that is actually how it's described to do it in our [roadmap](https://pandas.pydata.org/docs/dev/development/roadmap.html#roadmap-evolution)). The aforementioned mailing list thread mostly resulted in a discussion about how to integrate the new semantics in the datetime-like dtypes (pd.NaT vs pd.NA, keep pd.NaT but change its behaviour, etc). This is still a technical discussion we further need to resolve, but note that I kept the text on that in the PR somewhat vague on purpose for this reason: *"..: all data types should support missing values and with the same behaviour"* And the general disclaimer that is also in our roadmap: *An item being on the roadmap does not mean that it will* necessarily *happen, even with unlimited funding. During the implementation period we may discover issues preventing the adoption of the feature.* cc @pandas-dev/pandas-core @pandas-dev/pandas-triage
https://api.github.com/repos/pandas-dev/pandas/pulls/35208
2020-07-10T09:34:16Z
2020-08-20T14:52:53Z
2020-08-20T14:52:53Z
2020-08-20T15:50:22Z
ENH: raise limit for completion number of columns and warn beyond
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 571fcc67f3bb5..69ff4006f34f3 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5175,10 +5175,16 @@ def _dir_additions(self): add the string-like attributes from the info_axis. If info_axis is a MultiIndex, it's first level values are used. """ + unique_entries = self._info_axis.unique(level=0) + if len(unique_entries) > 1000: + unique_entries = unique_entries[:1000] + warnings.warn( + "Completion only considers the first 1000 entries " + "for performance reasons", + UserWarning, + ) additions = { - c - for c in self._info_axis.unique(level=0)[:100] - if isinstance(c, str) and c.isidentifier() + c for c in unique_entries if isinstance(c, str) and c.isidentifier() } return super()._dir_additions().union(additions) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 042841bb4e019..bcf5adf084df3 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -248,7 +248,7 @@ def get_dir(s): tm.makeIntIndex(10), tm.makeFloatIndex(10), Index([True, False]), - Index([f"a{i}" for i in range(101)]), + Index([f"a{i}" for i in range(1001)]), pd.MultiIndex.from_tuples(zip("ABCD", "EFGH")), pd.MultiIndex.from_tuples(zip([0, 1, 2, 3], "EFGH")), ], @@ -256,9 +256,14 @@ def get_dir(s): def test_index_tab_completion(self, index): # dir contains string-like values of the Index. s = pd.Series(index=index, dtype=object) - dir_s = dir(s) + if len(s) < 1000: + dir_s = dir(s) + else: + with tm.assert_produces_warning(UserWarning): + dir_s = dir(s) + for i, x in enumerate(s.index.unique(level=0)): - if i < 100: + if i < 1000: assert not isinstance(x, str) or not x.isidentifier() or x in dir_s else: assert x not in dir_s
Hi, Currently the user-completion (ipython "\<tab\>") on a dataframe with more than 100 columns will silently ignore some columns, letting an unaware user confused on whether data disapeared. This is actually documented, and due to an arbitrary limit set to workaround a performance issue ( See #18587 ) Dataframe with more than 100 columns are quite common, so this can potentially affect and suprise many users. Therefore, I suggest to increase that limit to, say, 1000. In any case, it would probably be good to warn the user hitting that limit. The attached quickfix raises the limit to 1000 and adds a warning beyond. (Note that I didn't experience any completion latency increasing with the axis size, so I'm not sure whether this limit is still relevant in the first place).
https://api.github.com/repos/pandas-dev/pandas/pulls/35207
2020-07-10T07:41:05Z
2020-11-22T04:57:46Z
null
2020-11-22T04:57:46Z
CLN: tighten types to get_rule_month
diff --git a/pandas/_libs/tslibs/parsing.pxd b/pandas/_libs/tslibs/parsing.pxd index 6e826cd4c6602..9c9262beaafad 100644 --- a/pandas/_libs/tslibs/parsing.pxd +++ b/pandas/_libs/tslibs/parsing.pxd @@ -1,2 +1,2 @@ -cpdef str get_rule_month(object source, str default=*) +cpdef str get_rule_month(str source) diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 3a1af9fdb1e8f..92654f3b587e5 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -284,7 +284,7 @@ def parse_time_string(arg: str, freq=None, dayfirst=None, yearfirst=None): cdef parse_datetime_string_with_reso( - str date_string, object freq=None, bint dayfirst=False, bint yearfirst=False, + str date_string, str freq=None, bint dayfirst=False, bint yearfirst=False, ): """ Parse datetime string and try to identify its resolution. @@ -438,6 +438,7 @@ cdef inline object _parse_dateabbr_string(object date_string, datetime default, if freq is not None: # TODO: hack attack, #1228 + freq = getattr(freq, "freqstr", freq) try: mnum = c_MONTH_NUMBERS[get_rule_month(freq)] + 1 except (KeyError, ValueError): @@ -1020,15 +1021,14 @@ def concat_date_cols(tuple date_cols, bint keep_trivial_numbers=True): return result -# TODO: `default` never used? -cpdef str get_rule_month(object source, str default="DEC"): +cpdef str get_rule_month(str source): """ Return starting month of given freq, default is December. Parameters ---------- - source : object - default : str, default "DEC" + source : str + Derived from `freq.rule_code` or `freq.freqstr`. Returns ------- @@ -1042,10 +1042,8 @@ cpdef str get_rule_month(object source, str default="DEC"): >>> get_rule_month('A-JAN') 'JAN' """ - if is_offset_object(source): - source = source.freqstr source = source.upper() if "-" not in source: - return default + return "DEC" else: return source.split("-")[1] diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index e992b20b12db2..20961c6da56bd 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -2440,13 +2440,13 @@ cdef int64_t _ordinal_from_fields(int year, int month, quarter, int day, BaseOffset freq): base = freq_to_dtype_code(freq) if quarter is not None: - year, month = quarter_to_myear(year, quarter, freq) + year, month = quarter_to_myear(year, quarter, freq.freqstr) return period_ordinal(year, month, day, hour, minute, second, 0, 0, base) -def quarter_to_myear(year: int, quarter: int, freq): +def quarter_to_myear(year: int, quarter: int, freqstr: str): """ A quarterly frequency defines a "year" which may not coincide with the calendar-year. Find the calendar-year and calendar-month associated @@ -2456,7 +2456,8 @@ def quarter_to_myear(year: int, quarter: int, freq): ---------- year : int quarter : int - freq : DateOffset + freqstr : str + Equivalent to freq.freqstr Returns ------- @@ -2470,7 +2471,7 @@ def quarter_to_myear(year: int, quarter: int, freq): if quarter <= 0 or quarter > 4: raise ValueError('Quarter must be 1 <= q <= 4') - mnum = c_MONTH_NUMBERS[get_rule_month(freq)] + 1 + mnum = c_MONTH_NUMBERS[get_rule_month(freqstr)] + 1 month = (mnum + (quarter - 1) * 3) % 12 + 1 if month > mnum: year -= 1 diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index b336371655466..8d5cb12d60e4d 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -1034,9 +1034,10 @@ def _range_from_fields( if base != FreqGroup.FR_QTR: raise AssertionError("base must equal FR_QTR") + freqstr = freq.freqstr year, quarter = _make_field_arrays(year, quarter) for y, q in zip(year, quarter): - y, m = libperiod.quarter_to_myear(y, q, freq) + y, m = libperiod.quarter_to_myear(y, q, freqstr) val = libperiod.period_ordinal(y, m, 1, 1, 1, 1, 0, 0, base) ordinals.append(val) else: diff --git a/pandas/tests/tslibs/test_libfrequencies.py b/pandas/tests/tslibs/test_libfrequencies.py index 993f2f4c8ef10..83f28f6b5dc01 100644 --- a/pandas/tests/tslibs/test_libfrequencies.py +++ b/pandas/tests/tslibs/test_libfrequencies.py @@ -9,19 +9,19 @@ "obj,expected", [ ("W", "DEC"), - (offsets.Week(), "DEC"), + (offsets.Week().freqstr, "DEC"), ("D", "DEC"), - (offsets.Day(), "DEC"), + (offsets.Day().freqstr, "DEC"), ("Q", "DEC"), - (offsets.QuarterEnd(startingMonth=12), "DEC"), + (offsets.QuarterEnd(startingMonth=12).freqstr, "DEC"), ("Q-JAN", "JAN"), - (offsets.QuarterEnd(startingMonth=1), "JAN"), + (offsets.QuarterEnd(startingMonth=1).freqstr, "JAN"), ("A-DEC", "DEC"), ("Y-DEC", "DEC"), - (offsets.YearEnd(), "DEC"), + (offsets.YearEnd().freqstr, "DEC"), ("A-MAY", "MAY"), ("Y-MAY", "MAY"), - (offsets.YearEnd(month=5), "MAY"), + (offsets.YearEnd(month=5).freqstr, "MAY"), ], ) def test_get_rule_month(obj, expected):
We're a bit inconsistent about whether we are extracting freq.freqstr vs freq.rule_code; I'd like to get DateOffsets out of libparsing altogether before long.
https://api.github.com/repos/pandas-dev/pandas/pulls/35205
2020-07-10T04:11:10Z
2020-07-10T12:15:22Z
2020-07-10T12:15:22Z
2020-07-10T14:12:09Z
BUG: GroupBy.count() and GroupBy.sum() incorreclty return NaN instead of 0 for missing categories
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 986ee371566cd..eabb02d885762 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1085,6 +1085,8 @@ Groupby/resample/rolling - Bug in :meth:`DataFrame.groupby` lost index, when one of the ``agg`` keys referenced an empty list (:issue:`32580`) - Bug in :meth:`Rolling.apply` where ``center=True`` was ignored when ``engine='numba'`` was specified (:issue:`34784`) - Bug in :meth:`DataFrame.ewm.cov` was throwing ``AssertionError`` for :class:`MultiIndex` inputs (:issue:`34440`) +- Bug in :meth:`DataFrameGroupBy.count` was returning ``NaN`` for missing categories when grouped on multiple ``Categoricals``. Now returning ``0`` (:issue:`35028`) +- Bug in :meth:`DataFrameGroupBy.sum` and :meth:`SeriesGroupBy.sum` was reutrning ``NaN`` for missing categories when grouped on multiple ``Categorials``. Now returning ``0`` (:issue:`31422`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index ebb9d82766c1b..5093bbe8a1711 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -31,7 +31,7 @@ import numpy as np from pandas._libs import lib -from pandas._typing import FrameOrSeries, FrameOrSeriesUnion +from pandas._typing import FrameOrSeries, FrameOrSeriesUnion, Scalar from pandas.util._decorators import Appender, Substitution, doc from pandas.core.dtypes.cast import ( @@ -363,7 +363,9 @@ def _wrap_series_output( return result def _wrap_aggregated_output( - self, output: Mapping[base.OutputKey, Union[Series, np.ndarray]] + self, + output: Mapping[base.OutputKey, Union[Series, np.ndarray]], + fill_value: Scalar = np.NaN, ) -> Union[Series, DataFrame]: """ Wraps the output of a SeriesGroupBy aggregation into the expected result. @@ -385,7 +387,7 @@ def _wrap_aggregated_output( result = self._wrap_series_output( output=output, index=self.grouper.result_index ) - return self._reindex_output(result) + return self._reindex_output(result, fill_value) def _wrap_transformed_output( self, output: Mapping[base.OutputKey, Union[Series, np.ndarray]] @@ -415,7 +417,11 @@ def _wrap_transformed_output( return result def _wrap_applied_output( - self, keys: Index, values: Optional[List[Any]], not_indexed_same: bool = False + self, + keys: Index, + values: Optional[List[Any]], + not_indexed_same: bool = False, + fill_value: Scalar = np.NaN, ) -> FrameOrSeriesUnion: """ Wrap the output of SeriesGroupBy.apply into the expected result. @@ -465,7 +471,7 @@ def _get_index() -> Index: result = self.obj._constructor( data=values, index=_get_index(), name=self._selection_name ) - return self._reindex_output(result) + return self._reindex_output(result, fill_value) def _aggregate_named(self, func, *args, **kwargs): result = {} @@ -1029,7 +1035,10 @@ def _cython_agg_general( agg_blocks, agg_items = self._cython_agg_blocks( how, alt=alt, numeric_only=numeric_only, min_count=min_count ) - return self._wrap_agged_blocks(agg_blocks, items=agg_items) + fill_value = self._cython_func_fill_values.get(alt, np.NaN) + return self._wrap_agged_blocks( + agg_blocks, items=agg_items, fill_value=fill_value + ) def _cython_agg_blocks( self, how: str, alt=None, numeric_only: bool = True, min_count: int = -1 @@ -1219,7 +1228,9 @@ def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame: return self.obj._constructor(result, columns=result_columns) - def _wrap_applied_output(self, keys, values, not_indexed_same=False): + def _wrap_applied_output( + self, keys, values, not_indexed_same=False, fill_value=np.NaN + ): if len(keys) == 0: return self.obj._constructor(index=keys) @@ -1380,7 +1391,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False): if not self.as_index: self._insert_inaxis_grouper_inplace(result) - return self._reindex_output(result) + return self._reindex_output(result, fill_value) # values are not series or array-like but scalars else: @@ -1731,7 +1742,9 @@ def _insert_inaxis_grouper_inplace(self, result): result.insert(0, name, lev) def _wrap_aggregated_output( - self, output: Mapping[base.OutputKey, Union[Series, np.ndarray]] + self, + output: Mapping[base.OutputKey, Union[Series, np.ndarray]], + fill_value: Scalar = np.NaN, ) -> DataFrame: """ Wraps the output of DataFrameGroupBy aggregations into the expected result. @@ -1762,7 +1775,7 @@ def _wrap_aggregated_output( if self.axis == 1: result = result.T - return self._reindex_output(result) + return self._reindex_output(result, fill_value) def _wrap_transformed_output( self, output: Mapping[base.OutputKey, Union[Series, np.ndarray]] @@ -1788,7 +1801,9 @@ def _wrap_transformed_output( return result - def _wrap_agged_blocks(self, blocks: "Sequence[Block]", items: Index) -> DataFrame: + def _wrap_agged_blocks( + self, blocks: "Sequence[Block]", items: Index, fill_value: Scalar = np.NaN + ) -> DataFrame: if not self.as_index: index = np.arange(blocks[0].values.shape[-1]) mgr = BlockManager(blocks, axes=[items, index]) @@ -1804,7 +1819,7 @@ def _wrap_agged_blocks(self, blocks: "Sequence[Block]", items: Index) -> DataFra if self.axis == 1: result = result.T - return self._reindex_output(result)._convert(datetime=True) + return self._reindex_output(result, fill_value)._convert(datetime=True) def _iterate_column_groupbys(self): for i, colname in enumerate(self._selected_obj.columns): @@ -1846,7 +1861,7 @@ def count(self): ) blocks = [make_block(val, placement=loc) for val, loc in zip(counted, locs)] - return self._wrap_agged_blocks(blocks, items=data.items) + return self._wrap_agged_blocks(blocks, items=data.items, fill_value=0) def nunique(self, dropna: bool = True): """ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index d039b715b3c08..afee28a76afc3 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -888,8 +888,12 @@ def _python_apply_general( """ keys, values, mutated = self.grouper.apply(f, data, self.axis) + fill_value = self._cython_func_fill_values.get(f, np.NaN) return self._wrap_applied_output( - keys, values, not_indexed_same=mutated or self.mutated + keys, + values, + not_indexed_same=mutated or self.mutated, + fill_value=fill_value, ) def _iterate_slices(self) -> Iterable[Series]: @@ -970,13 +974,17 @@ def _cython_transform(self, how: str, numeric_only: bool = True, **kwargs): return self._wrap_transformed_output(output) - def _wrap_aggregated_output(self, output: Mapping[base.OutputKey, np.ndarray]): + def _wrap_aggregated_output( + self, output: Mapping[base.OutputKey, np.ndarray], fill_value: Scalar = np.NaN + ): raise AbstractMethodError(self) def _wrap_transformed_output(self, output: Mapping[base.OutputKey, np.ndarray]): raise AbstractMethodError(self) - def _wrap_applied_output(self, keys, values, not_indexed_same: bool = False): + def _wrap_applied_output( + self, keys, values, not_indexed_same: bool = False, fill_value: Scalar = np.NaN + ): raise AbstractMethodError(self) def _agg_general( @@ -1010,6 +1018,8 @@ def _agg_general( result = self.aggregate(lambda x: npfunc(x, axis=self.axis)) return result + _cython_func_fill_values = {np.sum: 0} + def _cython_agg_general( self, how: str, alt=None, numeric_only: bool = True, min_count: int = -1 ): @@ -1045,7 +1055,9 @@ def _cython_agg_general( if len(output) == 0: raise DataError("No numeric types to aggregate") - return self._wrap_aggregated_output(output) + fill_value = self._cython_func_fill_values.get(alt, np.NaN) + + return self._wrap_aggregated_output(output, fill_value) def _python_agg_general( self, func, *args, engine="cython", engine_kwargs=None, **kwargs diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 118d928ac02f4..e64c95063f2cc 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -19,7 +19,7 @@ import pandas._testing as tm -def cartesian_product_for_groupers(result, args, names): +def cartesian_product_for_groupers(result, args, names, fill_value=np.NaN): """ Reindex to a cartesian production for the groupers, preserving the nature (Categorical) of each grouper """ @@ -33,7 +33,7 @@ def f(a): return a index = MultiIndex.from_product(map(f, args), names=names) - return result.reindex(index).sort_index() + return result.reindex(index, fill_value=fill_value).sort_index() _results_for_groupbys_with_missing_categories = dict( @@ -309,7 +309,7 @@ def test_observed(observed): result = gb.sum() if not observed: expected = cartesian_product_for_groupers( - expected, [cat1, cat2, ["foo", "bar"]], list("ABC") + expected, [cat1, cat2, ["foo", "bar"]], list("ABC"), fill_value=0 ) tm.assert_frame_equal(result, expected) @@ -319,7 +319,9 @@ def test_observed(observed): expected = DataFrame({"values": [1, 2, 3, 4]}, index=exp_index) result = gb.sum() if not observed: - expected = cartesian_product_for_groupers(expected, [cat1, cat2], list("AB")) + expected = cartesian_product_for_groupers( + expected, [cat1, cat2], list("AB"), fill_value=0 + ) tm.assert_frame_equal(result, expected) @@ -1188,9 +1190,10 @@ def test_seriesgroupby_observed_false_or_none(df_cat, observed, operation): names=["A", "B"], ).sortlevel() - expected = Series(data=[2, 4, np.nan, 1, np.nan, 3], index=index, name="C") + expected = Series(data=[2, 4, 0, 1, 0, 3], index=index, name="C") grouped = df_cat.groupby(["A", "B"], observed=observed)["C"] result = getattr(grouped, operation)(sum) + tm.assert_series_equal(result, expected) @@ -1340,15 +1343,6 @@ def test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans( ) request.node.add_marker(mark) - if reduction_func == "sum": # GH 31422 - mark = pytest.mark.xfail( - reason=( - "sum should return 0 but currently returns NaN. " - "This is a known bug. See GH 31422." - ) - ) - request.node.add_marker(mark) - df = pd.DataFrame( { "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")), @@ -1369,8 +1363,11 @@ def test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans( val = result.loc[idx] assert (pd.isna(zero_or_nan) and pd.isna(val)) or (val == zero_or_nan) - # If we expect unobserved values to be zero, we also expect the dtype to be int - if zero_or_nan == 0: + # If we expect unobserved values to be zero, we also expect the dtype to be int. + # Except for .sum(). If the observed categories sum to dtype=float (i.e. their + # sums have decimals), then the zeros for the missing categories should also be + # floats. + if zero_or_nan == 0 and reduction_func != "sum": assert np.issubdtype(result.dtype, np.integer) @@ -1412,24 +1409,6 @@ def test_dataframe_groupby_on_2_categoricals_when_observed_is_false( if reduction_func == "ngroup": pytest.skip("ngroup does not return the Categories on the index") - if reduction_func == "count": # GH 35028 - mark = pytest.mark.xfail( - reason=( - "DataFrameGroupBy.count returns np.NaN for missing " - "categories, when it should return 0. See GH 35028" - ) - ) - request.node.add_marker(mark) - - if reduction_func == "sum": # GH 31422 - mark = pytest.mark.xfail( - reason=( - "sum should return 0 but currently returns NaN. " - "This is a known bug. See GH 31422." - ) - ) - request.node.add_marker(mark) - df = pd.DataFrame( { "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")), diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index c07a5673fe503..67b3151b0ff9c 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -1817,7 +1817,7 @@ def test_categorical_aggfunc(self, observed): ["A", "B", "C"], categories=["A", "B", "C"], ordered=False, name="C1" ) expected_columns = pd.Index(["a", "b"], name="C2") - expected_data = np.array([[1.0, np.nan], [1.0, np.nan], [np.nan, 2.0]]) + expected_data = np.array([[1, 0], [1, 0], [0, 2]], dtype=np.int64) expected = pd.DataFrame( expected_data, index=expected_index, columns=expected_columns ) @@ -1851,18 +1851,19 @@ def test_categorical_pivot_index_ordering(self, observed): values="Sales", index="Month", columns="Year", - dropna=observed, + observed=observed, aggfunc="sum", ) expected_columns = pd.Int64Index([2013, 2014], name="Year") expected_index = pd.CategoricalIndex( - ["January"], categories=months, ordered=False, name="Month" + months, categories=months, ordered=False, name="Month" ) + expected_data = [[320, 120]] + [[0, 0]] * 11 expected = pd.DataFrame( - [[320, 120]], index=expected_index, columns=expected_columns + expected_data, index=expected_index, columns=expected_columns ) - if not observed: - result = result.dropna().astype(np.int64) + if observed: + expected = expected.loc[["January"]] tm.assert_frame_equal(result, expected)
- [x] closes #31422 - [x] closes #35028 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry *Behavioural Changes* Fixing two related bugs: when grouping on multiple categoricals, `.sum()` and `.count()` would return `NaN` for the missing categories, but they are expected to return `0` for the missing categories. Both these bugs are fixed. *Tests* Tests were added in PR #35022 when these bugs were discovered and the tests were marked with an `xfail`. For this PR the `xfails` are removed and the tests are passing normally. As well, a few other existing tests were expecting `sum()` to return `NaN`; these have been updated so that the tests now expect to get `0` (which is the desired behaviour). *Pivot* The change to `.sum()` also impacts the `df.pivot_table()` if it is called with `aggfunc=sum` and is pivoted on a Categorical column with `observed=False`. This is not explicitly mentioned in either of the bugs, but it does make the behaviour consistent (i.e. the sum of a missing category is zero, not `NaN`). One test on test_pivot.py was updated to reflect this change. *Default Behaviour* Because `df.groupby()` and `df.pivot_table()` have `observed=False` as the default, the default behaviour will change for a user calling `df.groupby().sum()` or `df.pivot_table(..., aggfunc='sum')` if they are grouping/pivoting on a categorical with missing categories. Previously the default would give them `NaN` for the missing categories, now the default will give them `0`. What is the appropriate to highlight/document this change to the default behaviour?
https://api.github.com/repos/pandas-dev/pandas/pulls/35201
2020-07-09T23:23:32Z
2020-07-15T01:33:41Z
null
2020-07-15T01:33:42Z
REF: re-use get_firstbday, get_lastbday in fields.pyx
diff --git a/pandas/_libs/tslibs/ccalendar.pxd b/pandas/_libs/tslibs/ccalendar.pxd index 41cc477413607..4eb5188b8a04b 100644 --- a/pandas/_libs/tslibs/ccalendar.pxd +++ b/pandas/_libs/tslibs/ccalendar.pxd @@ -10,6 +10,8 @@ cpdef int32_t get_days_in_month(int year, Py_ssize_t month) nogil cpdef int32_t get_week_of_year(int year, int month, int day) nogil cpdef iso_calendar_t get_iso_calendar(int year, int month, int day) nogil cpdef int32_t get_day_of_year(int year, int month, int day) nogil +cpdef int get_lastbday(int year, int month) nogil +cpdef int get_firstbday(int year, int month) nogil cdef int64_t DAY_NANOS cdef int64_t HOUR_NANOS diff --git a/pandas/_libs/tslibs/ccalendar.pyx b/pandas/_libs/tslibs/ccalendar.pyx index de8fd3911e946..00cecd25e5225 100644 --- a/pandas/_libs/tslibs/ccalendar.pyx +++ b/pandas/_libs/tslibs/ccalendar.pyx @@ -241,3 +241,52 @@ cpdef int32_t get_day_of_year(int year, int month, int day) nogil: day_of_year = mo_off + day return day_of_year + + +# --------------------------------------------------------------------- +# Business Helpers + +cpdef int get_lastbday(int year, int month) nogil: + """ + Find the last day of the month that is a business day. + + Parameters + ---------- + year : int + month : int + + Returns + ------- + last_bday : int + """ + cdef: + int wkday, days_in_month + + wkday = dayofweek(year, month, 1) + days_in_month = get_days_in_month(year, month) + return days_in_month - max(((wkday + days_in_month - 1) % 7) - 4, 0) + + +cpdef int get_firstbday(int year, int month) nogil: + """ + Find the first day of the month that is a business day. + + Parameters + ---------- + year : int + month : int + + Returns + ------- + first_bday : int + """ + cdef: + int first, wkday + + wkday = dayofweek(year, month, 1) + first = 1 + if wkday == 5: # on Saturday + first = 3 + elif wkday == 6: # on Sunday + first = 2 + return first diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index 5ea7c0b6c5d02..03e4188fd06ef 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -19,6 +19,8 @@ from pandas._libs.tslibs.ccalendar cimport ( get_days_in_month, is_leapyear, dayofweek, get_week_of_year, get_day_of_year, get_iso_calendar, iso_calendar_t, month_offset, + get_firstbday, + get_lastbday, ) from pandas._libs.tslibs.np_datetime cimport ( npy_datetimestruct, pandas_timedeltastruct, dt64_to_dtstruct, @@ -137,9 +139,7 @@ def get_start_end_field(const int64_t[:] dtindex, str field, int end_month = 12 int start_month = 1 ndarray[int8_t] out - bint isleap npy_datetimestruct dts - int mo_off, dom, doy, dow, ldom out = np.zeros(count, dtype='int8') @@ -172,10 +172,8 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - dom = dts.day - dow = dayofweek(dts.year, dts.month, dts.day) - if (dom == 1 and dow < 5) or (dom <= 3 and dow == 0): + if dts.day == get_firstbday(dts.year, dts.month): out[i] = 1 else: @@ -185,9 +183,8 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - dom = dts.day - if dom == 1: + if dts.day == 1: out[i] = 1 elif field == 'is_month_end': @@ -198,15 +195,8 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - isleap = is_leapyear(dts.year) - mo_off = month_offset[isleap * 13 + dts.month - 1] - dom = dts.day - doy = mo_off + dom - ldom = month_offset[isleap * 13 + dts.month] - dow = dayofweek(dts.year, dts.month, dts.day) - - if (ldom == doy and dow < 5) or ( - dow == 4 and (ldom - doy <= 2)): + + if dts.day == get_lastbday(dts.year, dts.month): out[i] = 1 else: @@ -216,13 +206,8 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - isleap = is_leapyear(dts.year) - mo_off = month_offset[isleap * 13 + dts.month - 1] - dom = dts.day - doy = mo_off + dom - ldom = month_offset[isleap * 13 + dts.month] - if ldom == doy: + if dts.day == get_days_in_month(dts.year, dts.month): out[i] = 1 elif field == 'is_quarter_start': @@ -233,11 +218,9 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - dom = dts.day - dow = dayofweek(dts.year, dts.month, dts.day) if ((dts.month - start_month) % 3 == 0) and ( - (dom == 1 and dow < 5) or (dom <= 3 and dow == 0)): + dts.day == get_firstbday(dts.year, dts.month)): out[i] = 1 else: @@ -247,9 +230,8 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - dom = dts.day - if ((dts.month - start_month) % 3 == 0) and dom == 1: + if ((dts.month - start_month) % 3 == 0) and dts.day == 1: out[i] = 1 elif field == 'is_quarter_end': @@ -260,16 +242,9 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - isleap = is_leapyear(dts.year) - mo_off = month_offset[isleap * 13 + dts.month - 1] - dom = dts.day - doy = mo_off + dom - ldom = month_offset[isleap * 13 + dts.month] - dow = dayofweek(dts.year, dts.month, dts.day) if ((dts.month - end_month) % 3 == 0) and ( - (ldom == doy and dow < 5) or ( - dow == 4 and (ldom - doy <= 2))): + dts.day == get_lastbday(dts.year, dts.month)): out[i] = 1 else: @@ -279,13 +254,9 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - isleap = is_leapyear(dts.year) - mo_off = month_offset[isleap * 13 + dts.month - 1] - dom = dts.day - doy = mo_off + dom - ldom = month_offset[isleap * 13 + dts.month] - if ((dts.month - end_month) % 3 == 0) and (ldom == doy): + if ((dts.month - end_month) % 3 == 0) and ( + dts.day == get_days_in_month(dts.year, dts.month)): out[i] = 1 elif field == 'is_year_start': @@ -296,11 +267,9 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - dom = dts.day - dow = dayofweek(dts.year, dts.month, dts.day) if (dts.month == start_month) and ( - (dom == 1 and dow < 5) or (dom <= 3 and dow == 0)): + dts.day == get_firstbday(dts.year, dts.month)): out[i] = 1 else: @@ -310,9 +279,8 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - dom = dts.day - if (dts.month == start_month) and dom == 1: + if (dts.month == start_month) and dts.day == 1: out[i] = 1 elif field == 'is_year_end': @@ -323,16 +291,9 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - isleap = is_leapyear(dts.year) - dom = dts.day - mo_off = month_offset[isleap * 13 + dts.month - 1] - doy = mo_off + dom - dow = dayofweek(dts.year, dts.month, dts.day) - ldom = month_offset[isleap * 13 + dts.month] if (dts.month == end_month) and ( - (ldom == doy and dow < 5) or ( - dow == 4 and (ldom - doy <= 2))): + dts.day == get_lastbday(dts.year, dts.month)): out[i] = 1 else: @@ -342,13 +303,9 @@ def get_start_end_field(const int64_t[:] dtindex, str field, continue dt64_to_dtstruct(dtindex[i], &dts) - isleap = is_leapyear(dts.year) - mo_off = month_offset[isleap * 13 + dts.month - 1] - dom = dts.day - doy = mo_off + dom - ldom = month_offset[isleap * 13 + dts.month] - if (dts.month == end_month) and (ldom == doy): + if (dts.month == end_month) and ( + dts.day == get_days_in_month(dts.year, dts.month)): out[i] = 1 else: diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 0f9280ae92d39..4429ff083f350 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -34,7 +34,13 @@ from pandas._libs.tslibs.util cimport ( from pandas._libs.tslibs.ccalendar import ( MONTH_ALIASES, MONTH_TO_CAL_NUM, weekday_to_int, int_to_weekday, ) -from pandas._libs.tslibs.ccalendar cimport DAY_NANOS, get_days_in_month, dayofweek +from pandas._libs.tslibs.ccalendar cimport ( + DAY_NANOS, + dayofweek, + get_days_in_month, + get_firstbday, + get_lastbday, +) from pandas._libs.tslibs.conversion cimport ( convert_datetime_to_tsobject, localize_pydatetime, @@ -177,51 +183,6 @@ cdef _wrap_timedelta_result(result): # --------------------------------------------------------------------- # Business Helpers -cpdef int get_lastbday(int year, int month) nogil: - """ - Find the last day of the month that is a business day. - - Parameters - ---------- - year : int - month : int - - Returns - ------- - last_bday : int - """ - cdef: - int wkday, days_in_month - - wkday = dayofweek(year, month, 1) - days_in_month = get_days_in_month(year, month) - return days_in_month - max(((wkday + days_in_month - 1) % 7) - 4, 0) - - -cpdef int get_firstbday(int year, int month) nogil: - """ - Find the first day of the month that is a business day. - - Parameters - ---------- - year : int - month : int - - Returns - ------- - first_bday : int - """ - cdef: - int first, wkday - - wkday = dayofweek(year, month, 1) - first = 1 - if wkday == 5: # on Saturday - first = 3 - elif wkday == 6: # on Sunday - first = 2 - return first - cdef _get_calendar(weekmask, holidays, calendar): """Generate busdaycalendar""" diff --git a/pandas/tests/tslibs/test_liboffsets.py b/pandas/tests/tslibs/test_liboffsets.py index 206a604788c7e..6a514d2cc8713 100644 --- a/pandas/tests/tslibs/test_liboffsets.py +++ b/pandas/tests/tslibs/test_liboffsets.py @@ -5,6 +5,7 @@ import pytest +from pandas._libs.tslibs.ccalendar import get_firstbday, get_lastbday import pandas._libs.tslibs.offsets as liboffsets from pandas._libs.tslibs.offsets import roll_qtrday @@ -25,7 +26,7 @@ def day_opt(request): ) def test_get_last_bday(dt, exp_week_day, exp_last_day): assert dt.weekday() == exp_week_day - assert liboffsets.get_lastbday(dt.year, dt.month) == exp_last_day + assert get_lastbday(dt.year, dt.month) == exp_last_day @pytest.mark.parametrize( @@ -37,7 +38,7 @@ def test_get_last_bday(dt, exp_week_day, exp_last_day): ) def test_get_first_bday(dt, exp_week_day, exp_first_day): assert dt.weekday() == exp_week_day - assert liboffsets.get_firstbday(dt.year, dt.month) == exp_first_day + assert get_firstbday(dt.year, dt.month) == exp_first_day @pytest.mark.parametrize(
https://api.github.com/repos/pandas-dev/pandas/pulls/35199
2020-07-09T22:27:50Z
2020-07-09T23:40:15Z
2020-07-09T23:40:15Z
2020-07-09T23:46:48Z
REF: remove libresolution
diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py index 6fe6fa0a13c34..0ae4cc97d07e3 100644 --- a/pandas/_libs/tslibs/__init__.py +++ b/pandas/_libs/tslibs/__init__.py @@ -27,11 +27,11 @@ from . import dtypes from .conversion import localize_pydatetime +from .dtypes import Resolution from .nattype import NaT, NaTType, iNaT, is_null_datetimelike, nat_strings from .np_datetime import OutOfBoundsDatetime from .offsets import BaseOffset, Tick, to_offset from .period import IncompatibleFrequency, Period -from .resolution import Resolution from .timedeltas import Timedelta, delta_to_nanoseconds, ints_to_pytimedelta from .timestamps import Timestamp from .tzconversion import tz_convert_from_utc_single diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index 03e4188fd06ef..1d1f900bc18b3 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -73,6 +73,46 @@ def build_field_sarray(const int64_t[:] dtindex): return out +def month_position_check(fields, weekdays): + cdef: + int32_t daysinmonth, y, m, d + bint calendar_end = True + bint business_end = True + bint calendar_start = True + bint business_start = True + bint cal + int32_t[:] years = fields["Y"] + int32_t[:] months = fields["M"] + int32_t[:] days = fields["D"] + + for y, m, d, wd in zip(years, months, days, weekdays): + if calendar_start: + calendar_start &= d == 1 + if business_start: + business_start &= d == 1 or (d <= 3 and wd == 0) + + if calendar_end or business_end: + daysinmonth = get_days_in_month(y, m) + cal = d == daysinmonth + if calendar_end: + calendar_end &= cal + if business_end: + business_end &= cal or (daysinmonth - d < 3 and wd == 4) + elif not calendar_start and not business_start: + break + + if calendar_end: + return "ce" + elif business_end: + return "be" + elif calendar_start: + return "cs" + elif business_start: + return "bs" + else: + return None + + @cython.wraparound(False) @cython.boundscheck(False) def get_date_name_field(const int64_t[:] dtindex, str field, object locale=None): diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx deleted file mode 100644 index d2861d8e9fe8d..0000000000000 --- a/pandas/_libs/tslibs/resolution.pyx +++ /dev/null @@ -1,53 +0,0 @@ - -import numpy as np -from numpy cimport int32_t - -from pandas._libs.tslibs.dtypes import Resolution -from pandas._libs.tslibs.ccalendar cimport get_days_in_month - - -# ---------------------------------------------------------------------- -# Frequency Inference - -def month_position_check(fields, weekdays): - cdef: - int32_t daysinmonth, y, m, d - bint calendar_end = True - bint business_end = True - bint calendar_start = True - bint business_start = True - bint cal - int32_t[:] years - int32_t[:] months - int32_t[:] days - - years = fields['Y'] - months = fields['M'] - days = fields['D'] - - for y, m, d, wd in zip(years, months, days, weekdays): - if calendar_start: - calendar_start &= d == 1 - if business_start: - business_start &= d == 1 or (d <= 3 and wd == 0) - - if calendar_end or business_end: - daysinmonth = get_days_in_month(y, m) - cal = d == daysinmonth - if calendar_end: - calendar_end &= cal - if business_end: - business_end &= cal or (daysinmonth - d < 3 and wd == 4) - elif not calendar_start and not business_start: - break - - if calendar_end: - return 'ce' - elif business_end: - return 'be' - elif calendar_start: - return 'cs' - elif business_start: - return 'bs' - else: - return None diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 5038df85c9160..7058ed3682d59 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -7,6 +7,7 @@ from pandas._libs import lib, tslib from pandas._libs.tslibs import ( NaT, + Resolution, Timestamp, conversion, fields, @@ -15,7 +16,6 @@ ints_to_pydatetime, is_date_array_normalized, normalize_i8_timestamps, - resolution as libresolution, timezones, to_offset, tzconversion, @@ -533,7 +533,7 @@ def is_normalized(self): return is_date_array_normalized(self.asi8, self.tz) @property # NB: override with cache_readonly in immutable subclasses - def _resolution_obj(self) -> libresolution.Resolution: + def _resolution_obj(self) -> Resolution: return get_resolution(self.asi8, self.tz) # ---------------------------------------------------------------- diff --git a/pandas/tests/tslibs/test_api.py b/pandas/tests/tslibs/test_api.py index ccaceb7e6f906..036037032031a 100644 --- a/pandas/tests/tslibs/test_api.py +++ b/pandas/tests/tslibs/test_api.py @@ -16,7 +16,6 @@ def test_namespace(): "offsets", "parsing", "period", - "resolution", "strptime", "vectorized", "timedeltas", diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 23e08c7550646..f80ff1a53cd69 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -12,7 +12,7 @@ MONTHS, int_to_weekday, ) -from pandas._libs.tslibs.fields import build_field_sarray +from pandas._libs.tslibs.fields import build_field_sarray, month_position_check from pandas._libs.tslibs.offsets import ( # noqa:F401 DateOffset, Day, @@ -20,7 +20,6 @@ to_offset, ) from pandas._libs.tslibs.parsing import get_rule_month -from pandas._libs.tslibs.resolution import month_position_check from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import ( diff --git a/setup.py b/setup.py index 1885546e001fe..aebbdbf4d1e96 100755 --- a/setup.py +++ b/setup.py @@ -319,7 +319,6 @@ class CheckSDist(sdist_class): "pandas/_libs/tslibs/conversion.pyx", "pandas/_libs/tslibs/fields.pyx", "pandas/_libs/tslibs/offsets.pyx", - "pandas/_libs/tslibs/resolution.pyx", "pandas/_libs/tslibs/parsing.pyx", "pandas/_libs/tslibs/tzconversion.pyx", "pandas/_libs/tslibs/vectorized.pyx", @@ -639,10 +638,6 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "depends": tseries_depends, "sources": ["pandas/_libs/tslibs/src/datetime/np_datetime.c"], }, - "_libs.tslibs.resolution": { - "pyxfile": "_libs/tslibs/resolution", - "depends": tseries_depends, - }, "_libs.tslibs.strptime": { "pyxfile": "_libs/tslibs/strptime", "depends": tseries_depends,
It only has one function left, and that fits fine in fields.pyx
https://api.github.com/repos/pandas-dev/pandas/pulls/35198
2020-07-09T22:25:16Z
2020-07-10T12:16:28Z
2020-07-10T12:16:28Z
2020-07-10T14:15:20Z
PERF: lookups on Timestamp attributes
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index a2dacd9d36b14..f1051d0210f96 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -25,6 +25,13 @@ from cpython.datetime cimport ( PyDelta_Check, PyTZInfo_Check, PyDateTime_IMPORT, + PyDateTime_DATE_GET_HOUR, + PyDateTime_DATE_GET_MICROSECOND, + PyDateTime_DATE_GET_MINUTE, + PyDateTime_DATE_GET_SECOND, + PyDateTime_GET_DAY, + PyDateTime_GET_MONTH, + PyDateTime_GET_YEAR, ) PyDateTime_IMPORT @@ -417,7 +424,7 @@ cdef class _Timestamp(ABCTimestamp): """ if self.freq is None: # fast-path for non-business frequencies - return self.day == 1 + return PyDateTime_GET_DAY(self) == 1 return self._get_start_end_field("is_month_start") @property @@ -427,7 +434,7 @@ cdef class _Timestamp(ABCTimestamp): """ if self.freq is None: # fast-path for non-business frequencies - return self.day == self.days_in_month + return PyDateTime_GET_DAY(self) == self.days_in_month return self._get_start_end_field("is_month_end") @property @@ -437,7 +444,8 @@ cdef class _Timestamp(ABCTimestamp): """ if self.freq is None: # fast-path for non-business frequencies - return self.day == 1 and self.month % 3 == 1 + return (PyDateTime_GET_DAY(self) == 1 + and PyDateTime_GET_MONTH(self) % 3 == 1) return self._get_start_end_field("is_quarter_start") @property @@ -447,7 +455,8 @@ cdef class _Timestamp(ABCTimestamp): """ if self.freq is None: # fast-path for non-business frequencies - return (self.month % 3) == 0 and self.day == self.days_in_month + return ((PyDateTime_GET_MONTH(self) % 3) == 0 + and PyDateTime_GET_DAY(self) == self.days_in_month) return self._get_start_end_field("is_quarter_end") @property @@ -457,7 +466,7 @@ cdef class _Timestamp(ABCTimestamp): """ if self.freq is None: # fast-path for non-business frequencies - return self.day == self.month == 1 + return PyDateTime_GET_DAY(self) == PyDateTime_GET_MONTH(self) == 1 return self._get_start_end_field("is_year_start") @property @@ -467,7 +476,8 @@ cdef class _Timestamp(ABCTimestamp): """ if self.freq is None: # fast-path for non-business frequencies - return self.month == 12 and self.day == 31 + return (PyDateTime_GET_MONTH(self) == 12 + and PyDateTime_GET_DAY(self) == 31) return self._get_start_end_field("is_year_end") cdef _get_date_name_field(self, str field, object locale): @@ -519,7 +529,7 @@ cdef class _Timestamp(ABCTimestamp): """ Return True if year is a leap year. """ - return bool(ccalendar.is_leapyear(self.year)) + return bool(ccalendar.is_leapyear(PyDateTime_GET_YEAR(self))) @property def dayofweek(self) -> int: @@ -533,28 +543,38 @@ cdef class _Timestamp(ABCTimestamp): """ Return the day of the year. """ - return ccalendar.get_day_of_year(self.year, self.month, self.day) + return ccalendar.get_day_of_year( + PyDateTime_GET_YEAR(self), + PyDateTime_GET_MONTH(self), + PyDateTime_GET_DAY(self), + ) @property def quarter(self) -> int: """ Return the quarter of the year. """ - return ((self.month - 1) // 3) + 1 + return ((PyDateTime_GET_MONTH(self) - 1) // 3) + 1 @property def week(self) -> int: """ Return the week number of the year. """ - return ccalendar.get_week_of_year(self.year, self.month, self.day) + return ccalendar.get_week_of_year( + PyDateTime_GET_YEAR(self), + PyDateTime_GET_MONTH(self), + PyDateTime_GET_DAY(self), + ) @property def days_in_month(self) -> int: """ Return the number of days in the month. """ - return ccalendar.get_days_in_month(self.year, self.month) + return ccalendar.get_days_in_month( + PyDateTime_GET_YEAR(self), PyDateTime_GET_MONTH(self), + ) # ----------------------------------------------------------------- # Transformation Methods @@ -658,10 +678,10 @@ cdef class _Timestamp(ABCTimestamp): def _short_repr(self) -> str: # format a Timestamp with only _date_repr if possible # otherwise _repr_base - if (self.hour == 0 and - self.minute == 0 and - self.second == 0 and - self.microsecond == 0 and + if (PyDateTime_DATE_GET_HOUR(self) == 0 and + PyDateTime_DATE_GET_MINUTE(self) == 0 and + PyDateTime_DATE_GET_SECOND(self) == 0 and + PyDateTime_DATE_GET_MICROSECOND(self) == 0 and self.nanosecond == 0): return self._date_repr return self._repr_base @@ -692,9 +712,16 @@ cdef class _Timestamp(ABCTimestamp): warnings.warn("Discarding nonzero nanoseconds in conversion", UserWarning, stacklevel=2) - return datetime(self.year, self.month, self.day, - self.hour, self.minute, self.second, - self.microsecond, self.tzinfo) + return datetime( + PyDateTime_GET_YEAR(self), + PyDateTime_GET_MONTH(self), + PyDateTime_GET_DAY(self), + PyDateTime_DATE_GET_HOUR(self), + PyDateTime_DATE_GET_MINUTE(self), + PyDateTime_DATE_GET_SECOND(self), + PyDateTime_DATE_GET_MICROSECOND(self), + self.tzinfo, + ) cpdef to_datetime64(self): """ @@ -1453,9 +1480,9 @@ default 'raise' Convert TimeStamp to a Julian Date. 0 Julian date is noon January 1, 4713 BC. """ - year = self.year - month = self.month - day = self.day + year = PyDateTime_GET_YEAR(self) + month = PyDateTime_GET_MONTH(self) + day = PyDateTime_GET_DAY(self) if month <= 2: year -= 1 month += 12
This is pretty ugly, but it avoids python-space attribute lookups e.g. `__Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_microsecond)` cc @scoder is there a way to make this unnecessary? I'm imagining a cdef property that aliased these attributes appropriately.
https://api.github.com/repos/pandas-dev/pandas/pulls/35196
2020-07-09T20:23:12Z
2020-07-09T21:35:29Z
null
2020-07-09T21:37:32Z
PERF: MonthOffset.apply_index
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index fb07e3fe7547e..fa5ef0e7adf59 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -598,7 +598,7 @@ cdef class BaseOffset: def _get_offset_day(self, other: datetime) -> int: # subclass must implement `_day_opt`; calling from the base class - # will raise NotImplementedError. + # will implicitly assume day_opt = "business_end", see get_day_of_month. cdef: npy_datetimestruct dts pydate_to_dtstruct(other, &dts) @@ -3651,7 +3651,6 @@ def shift_months(const int64_t[:] dtindex, int months, object day_opt=None): out[i] = dtstruct_to_dt64(&dts) elif day_opt in ["start", "end", "business_start", "business_end"]: _shift_months(dtindex, out, count, months, day_opt) - else: raise ValueError("day must be None, 'start', 'end', " "'business_start', or 'business_end'") @@ -3841,7 +3840,7 @@ def shift_month(stamp: datetime, months: int, day_opt: object=None) -> datetime: return stamp.replace(year=year, month=month, day=day) -cdef inline int get_day_of_month(npy_datetimestruct* dts, day_opt) nogil except? -1: +cdef inline int get_day_of_month(npy_datetimestruct* dts, str day_opt) nogil: """ Find the day in `other`'s month that satisfies a DateOffset's is_on_offset policy, as described by the `day_opt` argument. @@ -3867,27 +3866,23 @@ cdef inline int get_day_of_month(npy_datetimestruct* dts, day_opt) nogil except? >>> get_day_of_month(other, 'end') 30 + Notes + ----- + Caller is responsible for ensuring one of the four accepted day_opt values + is passed. """ - cdef: - int days_in_month if day_opt == "start": return 1 elif day_opt == "end": - days_in_month = get_days_in_month(dts.year, dts.month) - return days_in_month + return get_days_in_month(dts.year, dts.month) elif day_opt == "business_start": # first business day of month return get_firstbday(dts.year, dts.month) - elif day_opt == "business_end": + else: + # i.e. day_opt == "business_end": # last business day of month return get_lastbday(dts.year, dts.month) - elif day_opt is not None: - raise ValueError(day_opt) - elif day_opt is None: - # Note: unlike `shift_month`, get_day_of_month does not - # allow day_opt = None - raise NotImplementedError cpdef int roll_convention(int other, int n, int compare) nogil: @@ -3941,6 +3936,10 @@ def roll_qtrday(other: datetime, n: int, month: int, cdef: int months_since npy_datetimestruct dts + + if day_opt not in ["start", "end", "business_start", "business_end"]: + raise ValueError(day_opt) + pydate_to_dtstruct(other, &dts) if modby == 12: diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 784c04f225630..cffaa7b43d0cf 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -4310,12 +4310,6 @@ def test_all_offset_classes(self, tup): # --------------------------------------------------------------------- -def test_get_offset_day_error(): - # subclass of _BaseOffset must override _day_opt attribute, or we should - # get a NotImplementedError - - with pytest.raises(NotImplementedError): - DateOffset()._get_offset_day(datetime.now()) def test_valid_default_arguments(offset_types):
- [x] closes #35048 - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry ``` import pandas as pd import numpy as np N = 10000 rng = pd.date_range(start="1/1/2000", periods=N, freq="T") offset = pd.offsets.MonthBegin() In [6]: %timeit offset + rng 463 µs ± 19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # <-- PR 508 µs ± 18.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # <-- 1.0.4 736 µs ± 15 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # <-- master ```
https://api.github.com/repos/pandas-dev/pandas/pulls/35195
2020-07-09T20:10:39Z
2020-07-10T12:13:21Z
2020-07-10T12:13:20Z
2020-07-10T14:12:55Z
Create sayan2
diff --git a/sayan2 b/sayan2 new file mode 100644 index 0000000000000..63e1645b576f9 --- /dev/null +++ b/sayan2 @@ -0,0 +1,15 @@ +def row_replace(array,x,y): + for i in range(len(array)): + if array[i] == x: + array[i] = y + return array + +def rows(DataFrame,row, x ='0', y='0'): + df = [] + for i in DataFrame: + df.append(DataFrame[i][row]) + row_replace(df,x,y) + return df + + +
code to extract row from database and replace values within row - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35192
2020-07-09T14:05:02Z
2020-07-09T22:03:11Z
null
2020-07-09T22:03:18Z
Be specific about more indexes or values
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5f93e08d51baa..d721897da540f 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1169,6 +1169,7 @@ Other - Bug in :class:`Tick` comparisons raising ``TypeError`` when comparing against timedelta-like objects (:issue:`34088`) - Bug in :class:`Tick` multiplication raising ``TypeError`` when multiplying by a float (:issue:`34486`) - Passing a `set` as `names` argument to :func:`pandas.read_csv`, :func:`pandas.read_table`, or :func:`pandas.read_fwf` will raise ``ValueError: Names should be an ordered collection.`` (:issue:`34946`) +- Improved error message for invalid construction of list when creating a new index (:issue:`35190`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 4b9db810dead0..2d4163e0dee89 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -744,7 +744,12 @@ def sanitize_index(data, index: Index): through a non-Index. """ if len(data) != len(index): - raise ValueError("Length of values does not match length of index") + raise ValueError( + "Length of values " + f"({len(data)}) " + "does not match length of index " + f"({len(index)})" + ) if isinstance(data, np.ndarray): diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py index bfa53ad02525b..a4e6fc0f78cbb 100644 --- a/pandas/tests/extension/base/setitem.py +++ b/pandas/tests/extension/base/setitem.py @@ -244,7 +244,10 @@ def test_setitem_expand_with_extension(self, data): def test_setitem_frame_invalid_length(self, data): df = pd.DataFrame({"A": [1] * len(data)}) - xpr = "Length of values does not match length of index" + xpr = ( + rf"Length of values \({len(data[:5])}\) " + rf"does not match length of index \({len(df)}\)" + ) with pytest.raises(ValueError, match=xpr): df["B"] = data[:5] diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 3fa3c9303806f..d27487dfb8aaa 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -160,10 +160,13 @@ def test_setitem_list(self, float_frame): msg = "Columns must be same length as key" with pytest.raises(ValueError, match=msg): data[["A"]] = float_frame[["A", "B"]] - - msg = "Length of values does not match length of index" + newcolumndata = range(len(data.index) - 1) + msg = ( + rf"Length of values \({len(newcolumndata)}\) " + rf"does not match length of index \({len(data)}\)" + ) with pytest.raises(ValueError, match=msg): - data["A"] = range(len(data.index) - 1) + data["A"] = newcolumndata df = DataFrame(0, index=range(3), columns=["tt1", "tt2"], dtype=np.int_) df.loc[1, ["tt1", "tt2"]] = [1, 2] diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 9bb5338f1e07f..c5945edfd3127 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -117,7 +117,10 @@ def test_setitem_wrong_length_categorical_dtype_raises(self): cat = Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"]) df = DataFrame(range(10), columns=["bar"]) - msg = "Length of values does not match length of index" + msg = ( + rf"Length of values \({len(cat)}\) " + rf"does not match length of index \({len(df)}\)" + ) with pytest.raises(ValueError, match=msg): df["foo"] = cat
The generic "are not equal" really frustrated me just now when someone was conveying their issue. This specific two errors lets me know which way around, although I believe having more indexes than data shows a place in the api for a default value (possibly per-index) which would allow this to later be reduced to the case I feel I fully understand of more data than indexes, which I think probably is unsolvable generally. I can see that both have problems, but I still think it's more important to be specific about which side is mismatched. - [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35190
2020-07-09T10:04:56Z
2020-07-14T17:05:59Z
2020-07-14T17:05:59Z
2020-07-14T17:21:47Z
Add date overflow message to tz_localize (#32967)
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index ce0668917f800..49b23e3c78a33 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -897,6 +897,7 @@ Datetimelike resolution which converted to object dtype instead of coercing to ``datetime64[ns]`` dtype when within the timestamp bounds (:issue:`34843`). - The ``freq`` keyword in :class:`Period`, :func:`date_range`, :func:`period_range`, :func:`pd.tseries.frequencies.to_offset` no longer allows tuples, pass as string instead (:issue:`34703`) +- ``OutOfBoundsDatetime`` issues an improved error message when timestamp is out of implementation bounds. (:issue:`32967`) Timedelta ^^^^^^^^^ diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 31d2d0e9572f5..7e0627df7f58a 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -607,11 +607,20 @@ cdef inline check_overflows(_TSObject obj): # GH#12677 if obj.dts.year == 1677: if not (obj.value < 0): - raise OutOfBoundsDatetime + from pandas._libs.tslibs.timestamps import Timestamp + fmt = (f"{obj.dts.year}-{obj.dts.month:02d}-{obj.dts.day:02d} " + f"{obj.dts.hour:02d}:{obj.dts.min:02d}:{obj.dts.sec:02d}") + raise OutOfBoundsDatetime( + f"Converting {fmt} underflows past {Timestamp.min}" + ) elif obj.dts.year == 2262: if not (obj.value > 0): - raise OutOfBoundsDatetime - + from pandas._libs.tslibs.timestamps import Timestamp + fmt = (f"{obj.dts.year}-{obj.dts.month:02d}-{obj.dts.day:02d} " + f"{obj.dts.hour:02d}:{obj.dts.min:02d}:{obj.dts.sec:02d}") + raise OutOfBoundsDatetime( + f"Converting {fmt} overflows past {Timestamp.max}" + ) # ---------------------------------------------------------------------- # Localization diff --git a/pandas/tests/scalar/timestamp/test_timezones.py b/pandas/tests/scalar/timestamp/test_timezones.py index 9611c827be6fe..f29a72d0b8dd0 100644 --- a/pandas/tests/scalar/timestamp/test_timezones.py +++ b/pandas/tests/scalar/timestamp/test_timezones.py @@ -21,9 +21,12 @@ class TestTimestampTZOperations: # Timestamp.tz_localize def test_tz_localize_pushes_out_of_bounds(self): - msg = "^$" # GH#12677 # tz_localize that pushes away from the boundary is OK + msg = ( + f"Converting {Timestamp.min.strftime('%Y-%m-%d %H:%M:%S')} " + f"underflows past {Timestamp.min}" + ) pac = Timestamp.min.tz_localize("US/Pacific") assert pac.value > Timestamp.min.value pac.tz_convert("Asia/Tokyo") # tz_convert doesn't change value @@ -31,6 +34,10 @@ def test_tz_localize_pushes_out_of_bounds(self): Timestamp.min.tz_localize("Asia/Tokyo") # tz_localize that pushes away from the boundary is OK + msg = ( + f"Converting {Timestamp.max.strftime('%Y-%m-%d %H:%M:%S')} " + f"overflows past {Timestamp.max}" + ) tokyo = Timestamp.max.tz_localize("Asia/Tokyo") assert tokyo.value < Timestamp.max.value tokyo.tz_convert("US/Pacific") # tz_convert doesn't change value
- [x] closes #32967 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Added an error message to tz_localize when the timestamp overflows. I got a little confused by the history in #32979 as some changes were lost on the force pushes, but I tried to handle all review comments.
https://api.github.com/repos/pandas-dev/pandas/pulls/35187
2020-07-09T02:25:32Z
2020-07-16T01:51:19Z
2020-07-16T01:51:19Z
2020-07-16T01:51:29Z
Performance regression in stat_ops.FrameMultiIndexOps.time_op
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index d039b715b3c08..93ee65b6ddd57 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1434,16 +1434,18 @@ def std(self, ddof: int = 1): Series or DataFrame Standard deviation of values within each group. """ - return self._get_cythonized_result( - "group_var_float64", - aggregate=True, - needs_counts=True, - needs_values=True, - needs_2d=True, - cython_dtype=np.dtype(np.float64), - post_processing=lambda vals, inference: np.sqrt(vals), - ddof=ddof, - ) + result = self.var(ddof=ddof) + if result.ndim == 1: + result = np.sqrt(result) + else: + cols = result.columns.get_indexer_for( + result.columns.difference(self.exclusions).unique() + ) + # TODO(GH-22046) - setting with iloc broken if labels are not unique + # .values to remove labels + result.iloc[:, cols] = np.sqrt(result.iloc[:, cols]).values + + return result @Substitution(name="groupby") @Appender(_common_see_also)
- [ ] closes #35050 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry ``` import pandas as pd import numpy as np levels = [np.arange(10), np.arange(100), np.arange(100)] codes = [ np.arange(10).repeat(10000), np.tile(np.arange(100).repeat(100), 10), np.tile(np.tile(np.arange(100), 100), 10), ] index = pd.MultiIndex(levels=levels, codes=codes) df = pd.DataFrame(np.random.randn(len(index), 4), index=index) %timeit df.std(level=1) # 9.09 ms ± 59.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) -> master # 7.39 ms ± 71.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) -> 0.25.3 # 7.21 ms ± 113 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) -> PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/35186
2020-07-08T19:15:05Z
2020-07-09T09:26:01Z
null
2020-07-25T15:02:04Z
CI: MacPython failing TestPandasContainer.test_to_json_large_numbers
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 10f49b9b81528..97b53a6e66575 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -1250,23 +1250,32 @@ def test_to_json_large_numbers(self, bigNum): json = series.to_json() expected = '{"articleId":' + str(bigNum) + "}" assert json == expected - # GH 20599 + + df = DataFrame(bigNum, dtype=object, index=["articleId"], columns=[0]) + json = df.to_json() + expected = '{"0":{"articleId":' + str(bigNum) + "}}" + assert json == expected + + @pytest.mark.parametrize("bigNum", [sys.maxsize + 1, -(sys.maxsize + 2)]) + @pytest.mark.skipif(sys.maxsize <= 2 ** 32, reason="GH-35279") + def test_read_json_large_numbers(self, bigNum): + # GH20599 + + series = Series(bigNum, dtype=object, index=["articleId"]) + json = '{"articleId":' + str(bigNum) + "}" with pytest.raises(ValueError): json = StringIO(json) result = read_json(json) tm.assert_series_equal(series, result) df = DataFrame(bigNum, dtype=object, index=["articleId"], columns=[0]) - json = df.to_json() - expected = '{"0":{"articleId":' + str(bigNum) + "}}" - assert json == expected - # GH 20599 + json = '{"0":{"articleId":' + str(bigNum) + "}}" with pytest.raises(ValueError): json = StringIO(json) result = read_json(json) tm.assert_frame_equal(df, result) - def test_read_json_large_numbers(self): + def test_read_json_large_numbers2(self): # GH18842 json = '{"articleId": "1404366058080022500245"}' json = StringIO(json)
- [x] closes #35147 - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/35184
2020-07-08T17:59:53Z
2020-07-15T13:43:45Z
2020-07-15T13:43:45Z
2020-07-16T18:55:14Z
Json Visual Clutter cleanup
diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c index e841f00489887..59298522d86d1 100644 --- a/pandas/_libs/src/ujson/python/objToJSON.c +++ b/pandas/_libs/src/ujson/python/objToJSON.c @@ -143,8 +143,6 @@ typedef struct __PyObjectEncoder { enum PANDAS_FORMAT { SPLIT, RECORDS, INDEX, COLUMNS, VALUES }; -#define PRINTMARK() - int PdBlock_iterNext(JSOBJ, JSONTypeContext *); void *initObjToJSON(void) { @@ -219,13 +217,11 @@ static TypeContext *createTypeContext(void) { static PyObject *get_values(PyObject *obj) { PyObject *values = NULL; - PRINTMARK(); - - if (PyObject_TypeCheck(obj, cls_index) || PyObject_TypeCheck(obj, cls_series)) { + if (PyObject_TypeCheck(obj, cls_index) || + PyObject_TypeCheck(obj, cls_series)) { // The special cases to worry about are dt64tz and category[dt64tz]. // In both cases we want the UTC-localized datetime64 ndarray, // without going through and object array of Timestamps. - PRINTMARK(); values = PyObject_GetAttrString(obj, "values"); if (values == NULL) { @@ -236,7 +232,6 @@ static PyObject *get_values(PyObject *obj) { values = PyObject_CallMethod(values, "__array__", NULL); } else if (!PyArray_CheckExact(values)) { // Didn't get a numpy array, so keep trying - PRINTMARK(); Py_DECREF(values); values = NULL; } @@ -245,7 +240,6 @@ static PyObject *get_values(PyObject *obj) { if (values == NULL) { PyObject *typeRepr = PyObject_Repr((PyObject *)Py_TYPE(obj)); PyObject *repr; - PRINTMARK(); if (PyObject_HasAttrString(obj, "dtype")) { PyObject *dtype = PyObject_GetAttrString(obj, "dtype"); repr = PyObject_Repr(dtype); @@ -369,7 +363,6 @@ static char *PyTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, size_t *outLen) { str = PyObject_CallMethod(obj, "isoformat", NULL); if (str == NULL) { - PRINTMARK(); *outLen = 0; if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ValueError, "Failed to convert time"); @@ -397,7 +390,6 @@ static char *PyTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, size_t *outLen) { static void NpyArr_freeItemValue(JSOBJ Py_UNUSED(_obj), JSONTypeContext *tc) { if (GET_TC(tc)->npyarr && GET_TC(tc)->itemValue != GET_TC(tc)->npyarr->array) { - PRINTMARK(); Py_XDECREF(GET_TC(tc)->itemValue); GET_TC(tc)->itemValue = NULL; } @@ -417,7 +409,6 @@ void NpyArr_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { obj = (PyArrayObject *)_obj; } - PRINTMARK(); npyarr = PyObject_Malloc(sizeof(NpyArrContext)); GET_TC(tc)->npyarr = npyarr; @@ -454,7 +445,6 @@ void NpyArr_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { void NpyArr_iterEnd(JSOBJ obj, JSONTypeContext *tc) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; - PRINTMARK(); if (npyarr) { NpyArr_freeItemValue(obj, tc); @@ -463,13 +453,10 @@ void NpyArr_iterEnd(JSOBJ obj, JSONTypeContext *tc) { } void NpyArrPassThru_iterBegin(JSOBJ Py_UNUSED(obj), - JSONTypeContext *Py_UNUSED(tc)) { - PRINTMARK(); -} + JSONTypeContext *Py_UNUSED(tc)) {} void NpyArrPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; - PRINTMARK(); // finished this dimension, reset the data pointer npyarr->curdim--; npyarr->dataptr -= npyarr->stride * npyarr->index[npyarr->stridedim]; @@ -483,28 +470,24 @@ void NpyArrPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { int NpyArr_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; - PRINTMARK(); if (PyErr_Occurred()) { return 0; } if (npyarr->index[npyarr->stridedim] >= npyarr->dim) { - PRINTMARK(); return 0; } NpyArr_freeItemValue(obj, tc); if (PyArray_ISDATETIME(npyarr->array)) { - PRINTMARK(); GET_TC(tc)->itemValue = obj; Py_INCREF(obj); ((PyObjectEncoder *)tc->encoder)->npyType = PyArray_TYPE(npyarr->array); ((PyObjectEncoder *)tc->encoder)->npyValue = npyarr->dataptr; ((PyObjectEncoder *)tc->encoder)->npyCtxtPassthru = npyarr; } else { - PRINTMARK(); GET_TC(tc)->itemValue = npyarr->getitem(npyarr->dataptr, npyarr->array); } @@ -515,16 +498,13 @@ int NpyArr_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { int NpyArr_iterNext(JSOBJ _obj, JSONTypeContext *tc) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; - PRINTMARK(); if (PyErr_Occurred()) { - PRINTMARK(); return 0; } if (npyarr->curdim >= npyarr->ndim || npyarr->index[npyarr->stridedim] >= npyarr->dim) { - PRINTMARK(); // innermost dimension, start retrieving item values GET_TC(tc)->iterNext = NpyArr_iterNextItem; return NpyArr_iterNextItem(_obj, tc); @@ -545,7 +525,6 @@ int NpyArr_iterNext(JSOBJ _obj, JSONTypeContext *tc) { } JSOBJ NpyArr_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { - PRINTMARK(); return GET_TC(tc)->itemValue; } @@ -553,7 +532,6 @@ char *NpyArr_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, size_t *outLen) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; npy_intp idx; - PRINTMARK(); char *cStr; if (GET_TC(tc)->iterNext == NpyArr_iterNextItem) { @@ -580,7 +558,6 @@ char *NpyArr_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, void PdBlockPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; - PRINTMARK(); if (blkCtxt->transpose) { blkCtxt->colIdx++; @@ -593,7 +570,6 @@ void PdBlockPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { int PdBlock_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; - PRINTMARK(); if (blkCtxt->colIdx >= blkCtxt->ncols) { return 0; @@ -610,7 +586,6 @@ char *PdBlock_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, NpyArrContext *npyarr = blkCtxt->npyCtxts[0]; npy_intp idx; char *cStr; - PRINTMARK(); if (GET_TC(tc)->iterNext == PdBlock_iterNextItem) { idx = blkCtxt->colIdx - 1; @@ -633,7 +608,6 @@ char *PdBlock_iterGetName_Transpose(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, NpyArrContext *npyarr = blkCtxt->npyCtxts[blkCtxt->colIdx]; npy_intp idx; char *cStr; - PRINTMARK(); if (GET_TC(tc)->iterNext == NpyArr_iterNextItem) { idx = npyarr->index[npyarr->stridedim] - 1; @@ -650,7 +624,6 @@ char *PdBlock_iterGetName_Transpose(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, int PdBlock_iterNext(JSOBJ obj, JSONTypeContext *tc) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; NpyArrContext *npyarr; - PRINTMARK(); if (PyErr_Occurred() || ((JSONObjectEncoder *)tc->encoder)->errorMsg) { return 0; @@ -675,7 +648,6 @@ int PdBlock_iterNext(JSOBJ obj, JSONTypeContext *tc) { void PdBlockPassThru_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; - PRINTMARK(); if (blkCtxt->transpose) { // if transposed we exhaust each column before moving to the next @@ -697,7 +669,6 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { npy_int64 colIdx; npy_intp idx; - PRINTMARK(); obj = (PyObject *)_obj; GET_TC(tc)->iterGetName = GET_TC(tc)->transpose @@ -744,8 +715,8 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { GET_TC(tc)->iterNext = NpyArr_iterNextNone; return; } else if (!PyTuple_Check(blocks)) { - PyErr_SetString(PyExc_TypeError, "blocks must be a tuple!"); - goto BLKRET; + PyErr_SetString(PyExc_TypeError, "blocks must be a tuple!"); + goto BLKRET; } // force transpose so each NpyArrContext strides down its column @@ -836,7 +807,6 @@ void PdBlock_iterEnd(JSOBJ obj, JSONTypeContext *tc) { PdBlockContext *blkCtxt; NpyArrContext *npyarr; int i; - PRINTMARK(); GET_TC(tc)->itemValue = NULL; npyarr = GET_TC(tc)->npyarr; @@ -948,7 +918,7 @@ JSOBJ Set_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { } char *Set_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc), - size_t *Py_UNUSED(outLen)) { + size_t *Py_UNUSED(outLen)) { return NULL; } @@ -961,7 +931,6 @@ void Dir_iterBegin(JSOBJ obj, JSONTypeContext *tc) { GET_TC(tc)->attrList = PyObject_Dir(obj); GET_TC(tc)->index = 0; GET_TC(tc)->size = PyList_GET_SIZE(GET_TC(tc)->attrList); - PRINTMARK(); } void Dir_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { @@ -976,7 +945,6 @@ void Dir_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { } Py_DECREF((PyObject *)GET_TC(tc)->attrList); - PRINTMARK(); } int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc) { @@ -1007,7 +975,6 @@ int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc) { attrStr = PyBytes_AS_STRING(attr); if (attrStr[0] == '_') { - PRINTMARK(); Py_DECREF(attr); continue; } @@ -1016,14 +983,12 @@ int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc) { if (itemValue == NULL) { PyErr_Clear(); Py_DECREF(attr); - PRINTMARK(); continue; } if (PyCallable_Check(itemValue)) { Py_DECREF(itemValue); Py_DECREF(attr); - PRINTMARK(); continue; } @@ -1031,7 +996,6 @@ int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc) { GET_TC(tc)->itemValue = itemValue; GET_TC(tc)->index++; - PRINTMARK(); itemName = attr; break; } @@ -1046,18 +1010,15 @@ int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc) { GET_TC(tc)->itemValue = itemValue; GET_TC(tc)->index++; - PRINTMARK(); return 1; } JSOBJ Dir_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { - PRINTMARK(); return GET_TC(tc)->itemValue; } char *Dir_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, size_t *outLen) { - PRINTMARK(); *outLen = PyBytes_GET_SIZE(GET_TC(tc)->itemName); return PyBytes_AS_STRING(GET_TC(tc)->itemName); } @@ -1073,7 +1034,6 @@ void List_iterBegin(JSOBJ obj, JSONTypeContext *tc) { int List_iterNext(JSOBJ obj, JSONTypeContext *tc) { if (GET_TC(tc)->index >= GET_TC(tc)->size) { - PRINTMARK(); return 0; } @@ -1102,7 +1062,6 @@ void Index_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { if (!GET_TC(tc)->cStr) { PyErr_NoMemory(); } - PRINTMARK(); } int Index_iterNext(JSOBJ obj, JSONTypeContext *tc) { @@ -1123,18 +1082,14 @@ int Index_iterNext(JSOBJ obj, JSONTypeContext *tc) { return 0; } } else { - PRINTMARK(); return 0; } GET_TC(tc)->index++; - PRINTMARK(); return 1; } -void Index_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc)) { - PRINTMARK(); -} +void Index_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc)) {} JSOBJ Index_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->itemValue; @@ -1157,7 +1112,6 @@ void Series_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { if (!GET_TC(tc)->cStr) { PyErr_NoMemory(); } - PRINTMARK(); } int Series_iterNext(JSOBJ obj, JSONTypeContext *tc) { @@ -1181,19 +1135,16 @@ int Series_iterNext(JSOBJ obj, JSONTypeContext *tc) { return 0; } } else { - PRINTMARK(); return 0; } GET_TC(tc)->index++; - PRINTMARK(); return 1; } void Series_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { PyObjectEncoder *enc = (PyObjectEncoder *)tc->encoder; enc->outputFormat = enc->originalOutputFormat; - PRINTMARK(); } JSOBJ Series_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { @@ -1217,7 +1168,6 @@ void DataFrame_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { if (!GET_TC(tc)->cStr) { PyErr_NoMemory(); } - PRINTMARK(); } int DataFrame_iterNext(JSOBJ obj, JSONTypeContext *tc) { @@ -1246,19 +1196,16 @@ int DataFrame_iterNext(JSOBJ obj, JSONTypeContext *tc) { GET_TC(tc)->itemValue = obj; } } else { - PRINTMARK(); return 0; } GET_TC(tc)->index++; - PRINTMARK(); return 1; } void DataFrame_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { PyObjectEncoder *enc = (PyObjectEncoder *)tc->encoder; enc->outputFormat = enc->originalOutputFormat; - PRINTMARK(); } JSOBJ DataFrame_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { @@ -1278,7 +1225,6 @@ char *DataFrame_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, //============================================================================= void Dict_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { GET_TC(tc)->index = 0; - PRINTMARK(); } int Dict_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { @@ -1291,7 +1237,6 @@ int Dict_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { if (!PyDict_Next((PyObject *)GET_TC(tc)->dictObj, &GET_TC(tc)->index, &GET_TC(tc)->itemName, &GET_TC(tc)->itemValue)) { - PRINTMARK(); return 0; } @@ -1305,7 +1250,6 @@ int Dict_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { } else { Py_INCREF(GET_TC(tc)->itemName); } - PRINTMARK(); return 1; } @@ -1315,7 +1259,6 @@ void Dict_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { GET_TC(tc)->itemName = NULL; } Py_DECREF(GET_TC(tc)->dictObj); - PRINTMARK(); } JSOBJ Dict_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { @@ -1366,7 +1309,6 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc, char *dataptr, *cLabel; int type_num; NPY_DATETIMEUNIT base = enc->datetimeUnit; - PRINTMARK(); if (!labels) { return 0; @@ -1425,8 +1367,7 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc, 1000000000LL; // nanoseconds per second } else { // datetime.* objects don't follow above rules - nanosecVal = - PyDateTimeToEpoch(item, NPY_FR_ns); + nanosecVal = PyDateTimeToEpoch(item, NPY_FR_ns); } } } @@ -1503,7 +1444,6 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc, void Object_invokeDefaultHandler(PyObject *obj, PyObjectEncoder *enc) { PyObject *tmpObj = NULL; - PRINTMARK(); tmpObj = PyObject_CallFunctionObjArgs(enc->defaultHandler, obj, NULL); if (!PyErr_Occurred()) { if (tmpObj == NULL) { @@ -1524,7 +1464,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { double val; npy_int64 value; int unit; - PRINTMARK(); tc->prv = NULL; @@ -1537,11 +1476,9 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { enc = (PyObjectEncoder *)tc->encoder; if (PyBool_Check(obj)) { - PRINTMARK(); tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE; return; } else if (obj == Py_None) { - PRINTMARK(); tc->type = JT_NULL; return; } @@ -1554,7 +1491,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { tc->prv = pc; if (PyTypeNum_ISDATETIME(enc->npyType)) { - PRINTMARK(); int64_t longVal; PyArray_VectorUnaryFunc *castfunc = PyArray_GetCastFunc(PyArray_DescrFromType(enc->npyType), NPY_INT64); @@ -1564,12 +1500,10 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } castfunc(enc->npyValue, &longVal, 1, NULL, NULL); if (longVal == get_nat()) { - PRINTMARK(); tc->type = JT_NULL; } else { if (enc->datetimeIso) { - PRINTMARK(); if (enc->npyType == NPY_TIMEDELTA) { pc->PyTypeToUTF8 = NpyTimeDeltaToIsoCallback; } else { @@ -1580,7 +1514,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { GET_TC(tc)->longValue = longVal; tc->type = JT_UTF8; } else { - PRINTMARK(); NPY_DATETIMEUNIT base = ((PyObjectEncoder *)tc->encoder)->datetimeUnit; GET_TC(tc)->longValue = NpyDateTimeToEpoch(longVal, base); @@ -1597,30 +1530,24 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { if (PyIter_Check(obj) || (PyArray_Check(obj) && !PyArray_CheckScalar(obj))) { - PRINTMARK(); goto ISITERABLE; } if (PyLong_Check(obj)) { - PRINTMARK(); tc->type = JT_LONG; int overflow = 0; GET_TC(tc)->longValue = PyLong_AsLongLongAndOverflow(obj, &overflow); int err; err = (GET_TC(tc)->longValue == -1) && PyErr_Occurred(); - if (overflow){ - PRINTMARK(); + if (overflow) { tc->type = JT_BIGNUM; - } - else if (err) { - PRINTMARK(); + } else if (err) { goto INVALID; } - + return; } else if (PyFloat_Check(obj)) { - PRINTMARK(); val = PyFloat_AS_DOUBLE(obj); if (npy_isnan(val) || npy_isinf(val)) { tc->type = JT_NULL; @@ -1630,80 +1557,61 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } return; } else if (PyBytes_Check(obj)) { - PRINTMARK(); pc->PyTypeToUTF8 = PyBytesToUTF8; tc->type = JT_UTF8; return; } else if (PyUnicode_Check(obj)) { - PRINTMARK(); pc->PyTypeToUTF8 = PyUnicodeToUTF8; tc->type = JT_UTF8; return; } else if (PyObject_TypeCheck(obj, type_decimal)) { - PRINTMARK(); GET_TC(tc)->doubleValue = PyFloat_AsDouble(obj); tc->type = JT_DOUBLE; return; } else if (PyDateTime_Check(obj) || PyDate_Check(obj)) { if (PyObject_TypeCheck(obj, cls_nat)) { - PRINTMARK(); tc->type = JT_NULL; return; } - PRINTMARK(); if (enc->datetimeIso) { - PRINTMARK(); pc->PyTypeToUTF8 = PyDateTimeToIsoCallback; tc->type = JT_UTF8; } else { - PRINTMARK(); NPY_DATETIMEUNIT base = ((PyObjectEncoder *)tc->encoder)->datetimeUnit; - GET_TC(tc)->longValue = - PyDateTimeToEpoch(obj, base); + GET_TC(tc)->longValue = PyDateTimeToEpoch(obj, base); tc->type = JT_LONG; } return; } else if (PyTime_Check(obj)) { - PRINTMARK(); pc->PyTypeToUTF8 = PyTimeToJSON; tc->type = JT_UTF8; return; } else if (PyArray_IsScalar(obj, Datetime)) { - PRINTMARK(); if (((PyDatetimeScalarObject *)obj)->obval == get_nat()) { - PRINTMARK(); tc->type = JT_NULL; return; } - PRINTMARK(); if (enc->datetimeIso) { - PRINTMARK(); pc->PyTypeToUTF8 = PyDateTimeToIsoCallback; tc->type = JT_UTF8; } else { - PRINTMARK(); NPY_DATETIMEUNIT base = ((PyObjectEncoder *)tc->encoder)->datetimeUnit; - GET_TC(tc)->longValue = - PyDateTimeToEpoch(obj, base); + GET_TC(tc)->longValue = PyDateTimeToEpoch(obj, base); tc->type = JT_LONG; } return; } else if (PyDelta_Check(obj)) { if (PyObject_HasAttrString(obj, "value")) { - PRINTMARK(); value = get_long_attr(obj, "value"); } else { - PRINTMARK(); value = total_seconds(obj) * 1000000000LL; // nanoseconds per second } - PRINTMARK(); if (value == get_nat()) { - PRINTMARK(); tc->type = JT_NULL; return; } else if (enc->datetimeIso) { @@ -1718,7 +1626,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { exc = PyErr_Occurred(); if (exc && PyErr_ExceptionMatches(PyExc_OverflowError)) { - PRINTMARK(); goto INVALID; } @@ -1727,7 +1634,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { GET_TC(tc)->longValue = value; return; } else if (PyArray_IsScalar(obj, Integer)) { - PRINTMARK(); tc->type = JT_LONG; PyArray_CastScalarToCtype(obj, &(GET_TC(tc)->longValue), PyArray_DescrFromType(NPY_INT64)); @@ -1735,19 +1641,16 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { exc = PyErr_Occurred(); if (exc && PyErr_ExceptionMatches(PyExc_OverflowError)) { - PRINTMARK(); goto INVALID; } return; } else if (PyArray_IsScalar(obj, Bool)) { - PRINTMARK(); PyArray_CastScalarToCtype(obj, &(GET_TC(tc)->longValue), PyArray_DescrFromType(NPY_BOOL)); tc->type = (GET_TC(tc)->longValue) ? JT_TRUE : JT_FALSE; return; } else if (PyArray_IsScalar(obj, Float) || PyArray_IsScalar(obj, Double)) { - PRINTMARK(); PyArray_CastScalarToCtype(obj, &(GET_TC(tc)->doubleValue), PyArray_DescrFromType(NPY_DOUBLE)); tc->type = JT_DOUBLE; @@ -1758,7 +1661,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { obj); goto INVALID; } else if (PyObject_TypeCheck(obj, cls_na)) { - PRINTMARK(); tc->type = JT_NULL; return; } @@ -1767,7 +1669,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { if (PyObject_TypeCheck(obj, cls_index)) { if (enc->outputFormat == SPLIT) { - PRINTMARK(); tc->type = JT_OBJECT; pc->iterBegin = Index_iterBegin; pc->iterEnd = Index_iterEnd; @@ -1779,7 +1680,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { pc->newObj = get_values(obj); if (pc->newObj) { - PRINTMARK(); tc->type = JT_ARRAY; pc->iterBegin = NpyArr_iterBegin; pc->iterEnd = NpyArr_iterEnd; @@ -1793,7 +1693,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } else if (PyObject_TypeCheck(obj, cls_series)) { if (enc->outputFormat == SPLIT) { - PRINTMARK(); tc->type = JT_OBJECT; pc->iterBegin = Series_iterBegin; pc->iterEnd = Series_iterEnd; @@ -1809,7 +1708,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } if (enc->outputFormat == INDEX || enc->outputFormat == COLUMNS) { - PRINTMARK(); tc->type = JT_OBJECT; tmpObj = PyObject_GetAttrString(obj, "index"); if (!tmpObj) { @@ -1827,7 +1725,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { goto INVALID; } } else { - PRINTMARK(); tc->type = JT_ARRAY; } pc->iterBegin = NpyArr_iterBegin; @@ -1838,7 +1735,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } else if (PyArray_Check(obj)) { if (enc->npyCtxtPassthru) { - PRINTMARK(); pc->npyarr = enc->npyCtxtPassthru; tc->type = (pc->npyarr->columnLabels ? JT_OBJECT : JT_ARRAY); @@ -1852,7 +1748,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } - PRINTMARK(); tc->type = JT_ARRAY; pc->iterBegin = NpyArr_iterBegin; pc->iterEnd = NpyArr_iterEnd; @@ -1862,7 +1757,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } else if (PyObject_TypeCheck(obj, cls_dataframe)) { if (enc->blkCtxtPassthru) { - PRINTMARK(); pc->pdblock = enc->blkCtxtPassthru; tc->type = (pc->pdblock->npyCtxts[0]->columnLabels ? JT_OBJECT : JT_ARRAY); @@ -1878,7 +1772,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } if (enc->outputFormat == SPLIT) { - PRINTMARK(); tc->type = JT_OBJECT; pc->iterBegin = DataFrame_iterBegin; pc->iterEnd = DataFrame_iterEnd; @@ -1888,7 +1781,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } - PRINTMARK(); if (is_simple_frame(obj)) { pc->iterBegin = NpyArr_iterBegin; pc->iterEnd = NpyArr_iterEnd; @@ -1908,10 +1800,8 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { pc->iterGetValue = NpyArr_iterGetValue; if (enc->outputFormat == VALUES) { - PRINTMARK(); tc->type = JT_ARRAY; } else if (enc->outputFormat == RECORDS) { - PRINTMARK(); tc->type = JT_ARRAY; tmpObj = PyObject_GetAttrString(obj, "columns"); if (!tmpObj) { @@ -1930,7 +1820,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { goto INVALID; } } else if (enc->outputFormat == INDEX || enc->outputFormat == COLUMNS) { - PRINTMARK(); tc->type = JT_OBJECT; tmpObj = (enc->outputFormat == INDEX ? PyObject_GetAttrString(obj, "index") @@ -1973,7 +1862,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } if (enc->outputFormat == COLUMNS) { - PRINTMARK(); pc->transpose = 1; } } else { @@ -1981,7 +1869,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } return; } else if (PyDict_Check(obj)) { - PRINTMARK(); tc->type = JT_OBJECT; pc->iterBegin = Dict_iterBegin; pc->iterEnd = Dict_iterEnd; @@ -1993,7 +1880,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } else if (PyList_Check(obj)) { - PRINTMARK(); tc->type = JT_ARRAY; pc->iterBegin = List_iterBegin; pc->iterEnd = List_iterEnd; @@ -2002,7 +1888,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { pc->iterGetName = List_iterGetName; return; } else if (PyTuple_Check(obj)) { - PRINTMARK(); tc->type = JT_ARRAY; pc->iterBegin = Tuple_iterBegin; pc->iterEnd = Tuple_iterEnd; @@ -2011,7 +1896,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { pc->iterGetName = Tuple_iterGetName; return; } else if (PyAnySet_Check(obj)) { - PRINTMARK(); tc->type = JT_ARRAY; pc->iterBegin = Set_iterBegin; pc->iterEnd = Set_iterEnd; @@ -2041,7 +1925,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } - PRINTMARK(); tc->type = JT_OBJECT; pc->iterBegin = Dict_iterBegin; pc->iterEnd = Dict_iterEnd; @@ -2059,7 +1942,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { goto INVALID; } - PRINTMARK(); tc->type = JT_OBJECT; pc->iterBegin = Dir_iterBegin; pc->iterEnd = Dir_iterEnd; @@ -2076,7 +1958,6 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } void Object_endTypeContext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { - PRINTMARK(); if (tc->prv) { Py_XDECREF(GET_TC(tc)->newObj); GET_TC(tc)->newObj = NULL; @@ -2105,16 +1986,16 @@ double Object_getDoubleValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->doubleValue; } -const char *Object_getBigNumStringValue(JSOBJ obj, JSONTypeContext *tc, - size_t *_outLen) { - PyObject* repr = PyObject_Str(obj); - const char *str = PyUnicode_AsUTF8AndSize(repr, (Py_ssize_t *) _outLen); - char* bytes = PyObject_Malloc(*_outLen + 1); +const char *Object_getBigNumStringValue(JSOBJ obj, JSONTypeContext *tc, + size_t *_outLen) { + PyObject *repr = PyObject_Str(obj); + const char *str = PyUnicode_AsUTF8AndSize(repr, (Py_ssize_t *)_outLen); + char *bytes = PyObject_Malloc(*_outLen + 1); memcpy(bytes, str, *_outLen + 1); GET_TC(tc)->cStr = bytes; Py_DECREF(repr); - + return GET_TC(tc)->cStr; } @@ -2200,8 +2081,6 @@ PyObject *objToJSON(PyObject *Py_UNUSED(self), PyObject *args, pyEncoder.outputFormat = COLUMNS; pyEncoder.defaultHandler = 0; - PRINTMARK(); - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OiOssOOi", kwlist, &oinput, &oensureAscii, &idoublePrecision, &oencodeHTMLChars, &sOrient, &sdateFormat, @@ -2274,16 +2153,12 @@ PyObject *objToJSON(PyObject *Py_UNUSED(self), PyObject *args, encoder->indent = indent; pyEncoder.originalOutputFormat = pyEncoder.outputFormat; - PRINTMARK(); ret = JSON_EncodeObject(oinput, encoder, buffer, sizeof(buffer)); - PRINTMARK(); if (PyErr_Occurred()) { - PRINTMARK(); return NULL; } if (encoder->errorMsg) { - PRINTMARK(); if (ret != buffer) { encoder->free(ret); } @@ -2297,7 +2172,5 @@ PyObject *objToJSON(PyObject *Py_UNUSED(self), PyObject *args, encoder->free(ret); } - PRINTMARK(); - return newobj; }
Removed PRINTMARK symbols and ran `clang-format -sort-includes=0 -i -style="{IndentWidth: 4}" pandas/_libs/src/ujson/python/objToJSON.c`
https://api.github.com/repos/pandas-dev/pandas/pulls/35183
2020-07-08T17:50:58Z
2020-07-09T21:57:05Z
2020-07-09T21:57:05Z
2020-07-22T18:56:47Z
ENH: Add compute.use_numba configuration for automatically using numba
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 85b29a58a1f15..9dd6dceac6da3 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -333,6 +333,7 @@ Other enhancements - :meth:`read_csv` now accepts string values like "0", "0.0", "1", "1.0" as convertible to the nullable boolean dtype (:issue:`34859`) - :class:`pandas.core.window.ExponentialMovingWindow` now supports a ``times`` argument that allows ``mean`` to be calculated with observations spaced by the timestamps in ``times`` (:issue:`34839`) - :meth:`DataFrame.agg` and :meth:`Series.agg` now accept named aggregation for renaming the output columns/indexes. (:issue:`26513`) +- ``compute.use_numba`` now exists as a configuration option that utilizes the numba engine when available (:issue:`33966`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 54d23fe8829e6..86f6be77bc505 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -52,6 +52,20 @@ def use_numexpr_cb(key): expressions.set_use_numexpr(cf.get_option(key)) +use_numba_doc = """ +: bool + Use the numba engine option for select operations if it is installed, + the default is False + Valid values: False,True +""" + + +def use_numba_cb(key): + from pandas.core.util import numba_ + + numba_.set_use_numba(cf.get_option(key)) + + with cf.config_prefix("compute"): cf.register_option( "use_bottleneck", @@ -63,6 +77,9 @@ def use_numexpr_cb(key): cf.register_option( "use_numexpr", True, use_numexpr_doc, validator=is_bool, cb=use_numexpr_cb ) + cf.register_option( + "use_numba", False, use_numba_doc, validator=is_bool, cb=use_numba_cb + ) # # options from the "display" namespace diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 093e1d4ab3942..f04b930c15c4f 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -80,6 +80,7 @@ from pandas.core.util.numba_ import ( NUMBA_FUNC_CACHE, generate_numba_func, + maybe_use_numba, split_for_numba, ) @@ -227,9 +228,7 @@ def apply(self, func, *args, **kwargs): @doc( _agg_template, examples=_agg_examples_doc, klass="Series", ) - def aggregate( - self, func=None, *args, engine="cython", engine_kwargs=None, **kwargs - ): + def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): relabeling = func is None columns = None @@ -480,7 +479,7 @@ def _aggregate_named(self, func, *args, **kwargs): @Substitution(klass="Series") @Appender(_transform_template) - def transform(self, func, *args, engine="cython", engine_kwargs=None, **kwargs): + def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): func = self._get_cython_func(func) or func if not isinstance(func, str): @@ -512,7 +511,7 @@ def _transform_general( Transform with a non-str `func`. """ - if engine == "numba": + if maybe_use_numba(engine): numba_func, cache_key = generate_numba_func( func, engine_kwargs, kwargs, "groupby_transform" ) @@ -522,7 +521,7 @@ def _transform_general( results = [] for name, group in self: object.__setattr__(group, "name", name) - if engine == "numba": + if maybe_use_numba(engine): values, index = split_for_numba(group) res = numba_func(values, index, *args) if cache_key not in NUMBA_FUNC_CACHE: @@ -931,13 +930,11 @@ class DataFrameGroupBy(GroupBy[DataFrame]): @doc( _agg_template, examples=_agg_examples_doc, klass="DataFrame", ) - def aggregate( - self, func=None, *args, engine="cython", engine_kwargs=None, **kwargs - ): + def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): relabeling, func, columns, order = reconstruct_func(func, **kwargs) - if engine == "numba": + if maybe_use_numba(engine): return self._python_agg_general( func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) @@ -1382,7 +1379,7 @@ def _transform_general( applied = [] obj = self._obj_with_exclusions gen = self.grouper.get_iterator(obj, axis=self.axis) - if engine == "numba": + if maybe_use_numba(engine): numba_func, cache_key = generate_numba_func( func, engine_kwargs, kwargs, "groupby_transform" ) @@ -1392,7 +1389,7 @@ def _transform_general( for name, group in gen: object.__setattr__(group, "name", name) - if engine == "numba": + if maybe_use_numba(engine): values, index = split_for_numba(group) res = numba_func(values, index, *args) if cache_key not in NUMBA_FUNC_CACHE: @@ -1443,7 +1440,7 @@ def _transform_general( @Substitution(klass="DataFrame") @Appender(_transform_template) - def transform(self, func, *args, engine="cython", engine_kwargs=None, **kwargs): + def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): # optimized transforms func = self._get_cython_func(func) or func diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index d039b715b3c08..65483abbd2a6e 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -65,6 +65,7 @@ class providing the base-class of operations. from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex from pandas.core.series import Series from pandas.core.sorting import get_group_index_sorter +from pandas.core.util.numba_ import maybe_use_numba _common_see_also = """ See Also @@ -286,9 +287,10 @@ class providing the base-class of operations. .. versionchanged:: 1.1.0 *args Positional arguments to pass to func -engine : str, default 'cython' +engine : str, default None * ``'cython'`` : Runs the function through C-extensions from cython. * ``'numba'`` : Runs the function through JIT compiled code from numba. + * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` .. versionadded:: 1.1.0 engine_kwargs : dict, default None @@ -393,9 +395,10 @@ class providing the base-class of operations. .. versionchanged:: 1.1.0 *args Positional arguments to pass to func -engine : str, default 'cython' +engine : str, default None * ``'cython'`` : Runs the function through C-extensions from cython. * ``'numba'`` : Runs the function through JIT compiled code from numba. + * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` .. versionadded:: 1.1.0 engine_kwargs : dict, default None @@ -1063,7 +1066,7 @@ def _python_agg_general( # agg_series below assumes ngroups > 0 continue - if engine == "numba": + if maybe_use_numba(engine): result, counts = self.grouper.agg_series( obj, func, diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 74db87f46c5e2..3aaeef3b63760 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -58,6 +58,7 @@ from pandas.core.util.numba_ import ( NUMBA_FUNC_CACHE, generate_numba_func, + maybe_use_numba, split_for_numba, ) @@ -620,7 +621,7 @@ def agg_series( # Caller is responsible for checking ngroups != 0 assert self.ngroups != 0 - if engine == "numba": + if maybe_use_numba(engine): return self._aggregate_series_pure_python( obj, func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) @@ -678,7 +679,7 @@ def _aggregate_series_pure_python( **kwargs, ): - if engine == "numba": + if maybe_use_numba(engine): numba_func, cache_key = generate_numba_func( func, engine_kwargs, kwargs, "groupby_agg" ) @@ -691,7 +692,7 @@ def _aggregate_series_pure_python( splitter = get_splitter(obj, group_index, ngroups, axis=0) for label, group in splitter: - if engine == "numba": + if maybe_use_numba(engine): values, index = split_for_numba(group) res = numba_func(values, index, *args) if cache_key not in NUMBA_FUNC_CACHE: diff --git a/pandas/core/util/numba_.py b/pandas/core/util/numba_.py index c3f60ea7cc217..c9b7943478cdd 100644 --- a/pandas/core/util/numba_.py +++ b/pandas/core/util/numba_.py @@ -10,9 +10,22 @@ from pandas.compat._optional import import_optional_dependency from pandas.errors import NumbaUtilError +GLOBAL_USE_NUMBA: bool = False NUMBA_FUNC_CACHE: Dict[Tuple[Callable, str], Callable] = dict() +def maybe_use_numba(engine: Optional[str]) -> bool: + """Signal whether to use numba routines.""" + return engine == "numba" or (engine is None and GLOBAL_USE_NUMBA) + + +def set_use_numba(enable: bool = False) -> None: + global GLOBAL_USE_NUMBA + if enable: + import_optional_dependency("numba") + GLOBAL_USE_NUMBA = enable + + def check_kwargs_and_nopython( kwargs: Optional[Dict] = None, nopython: Optional[bool] = None ) -> None: diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 8cb53ebd92214..48953f6a75487 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -39,7 +39,7 @@ import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexes.api import Index, MultiIndex, ensure_index -from pandas.core.util.numba_ import NUMBA_FUNC_CACHE +from pandas.core.util.numba_ import NUMBA_FUNC_CACHE, maybe_use_numba from pandas.core.window.common import ( WindowGroupByMixin, _doc_template, @@ -1298,10 +1298,11 @@ def count(self): objects instead. If you are just applying a NumPy reduction function this will achieve much better performance. - engine : str, default 'cython' + engine : str, default None * ``'cython'`` : Runs rolling apply through C-extensions from cython. * ``'numba'`` : Runs rolling apply through JIT compiled code from numba. Only available when ``raw`` is set to ``True``. + * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` .. versionadded:: 1.0.0 @@ -1357,18 +1358,7 @@ def apply( if not is_bool(raw): raise ValueError("raw parameter must be `True` or `False`") - if engine == "cython": - if engine_kwargs is not None: - raise ValueError("cython engine does not accept engine_kwargs") - # Cython apply functions handle center, so don't need to use - # _apply's center handling - window = self._get_window() - offset = calculate_center_offset(window) if self.center else 0 - apply_func = self._generate_cython_apply_func( - args, kwargs, raw, offset, func - ) - center = False - elif engine == "numba": + if maybe_use_numba(engine): if raw is False: raise ValueError("raw must be `True` when using the numba engine") cache_key = (func, "rolling_apply") @@ -1380,6 +1370,17 @@ def apply( args, kwargs, func, engine_kwargs ) center = self.center + elif engine in ("cython", None): + if engine_kwargs is not None: + raise ValueError("cython engine does not accept engine_kwargs") + # Cython apply functions handle center, so don't need to use + # _apply's center handling + window = self._get_window() + offset = calculate_center_offset(window) if self.center else 0 + apply_func = self._generate_cython_apply_func( + args, kwargs, raw, offset, func + ) + center = False else: raise ValueError("engine must be either 'numba' or 'cython'") @@ -2053,13 +2054,7 @@ def count(self): @Substitution(name="rolling") @Appender(_shared_docs["apply"]) def apply( - self, - func, - raw=False, - engine="cython", - engine_kwargs=None, - args=None, - kwargs=None, + self, func, raw=False, engine=None, engine_kwargs=None, args=None, kwargs=None, ): return super().apply( func, diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py index 726d79535184a..690694b0e66f5 100644 --- a/pandas/tests/groupby/aggregate/test_numba.py +++ b/pandas/tests/groupby/aggregate/test_numba.py @@ -4,7 +4,7 @@ from pandas.errors import NumbaUtilError import pandas.util._test_decorators as td -from pandas import DataFrame +from pandas import DataFrame, option_context import pandas._testing as tm from pandas.core.util.numba_ import NUMBA_FUNC_CACHE @@ -113,3 +113,18 @@ def func_2(values, index): result = grouped.agg(func_1, engine="numba", engine_kwargs=engine_kwargs) expected = grouped.agg(lambda x: np.mean(x) - 3.4, engine="cython") tm.assert_equal(result, expected) + + +@td.skip_if_no("numba", "0.46.0") +def test_use_global_config(): + def func_1(values, index): + return np.mean(values) - 3.4 + + data = DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + ) + grouped = data.groupby(0) + expected = grouped.agg(func_1, engine="numba") + with option_context("compute.use_numba", True): + result = grouped.agg(func_1, engine=None) + tm.assert_frame_equal(expected, result) diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py index 9a4015ac983c5..ee482571e644d 100644 --- a/pandas/tests/groupby/transform/test_numba.py +++ b/pandas/tests/groupby/transform/test_numba.py @@ -3,7 +3,7 @@ from pandas.errors import NumbaUtilError import pandas.util._test_decorators as td -from pandas import DataFrame +from pandas import DataFrame, option_context import pandas._testing as tm from pandas.core.util.numba_ import NUMBA_FUNC_CACHE @@ -112,3 +112,18 @@ def func_2(values, index): result = grouped.transform(func_1, engine="numba", engine_kwargs=engine_kwargs) expected = grouped.transform(lambda x: x + 1, engine="cython") tm.assert_equal(result, expected) + + +@td.skip_if_no("numba", "0.46.0") +def test_use_global_config(): + def func_1(values, index): + return values + 1 + + data = DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + ) + grouped = data.groupby(0) + expected = grouped.transform(func_1, engine="numba") + with option_context("compute.use_numba", True): + result = grouped.transform(func_1, engine=None) + tm.assert_frame_equal(expected, result) diff --git a/pandas/tests/util/test_numba.py b/pandas/tests/util/test_numba.py new file mode 100644 index 0000000000000..27b68ff0f6044 --- /dev/null +++ b/pandas/tests/util/test_numba.py @@ -0,0 +1,12 @@ +import pytest + +import pandas.util._test_decorators as td + +from pandas import option_context + + +@td.skip_if_installed("numba") +def test_numba_not_installed_option_context(): + with pytest.raises(ImportError, match="Missing optional"): + with option_context("compute.use_numba", True): + pass diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py index 7e049af0ca1f8..35bdb972a7bc0 100644 --- a/pandas/tests/window/test_numba.py +++ b/pandas/tests/window/test_numba.py @@ -3,7 +3,7 @@ import pandas.util._test_decorators as td -from pandas import Series +from pandas import Series, option_context import pandas._testing as tm from pandas.core.util.numba_ import NUMBA_FUNC_CACHE @@ -75,3 +75,15 @@ def func_2(x): ) expected = roll.apply(func_1, engine="cython", raw=True) tm.assert_series_equal(result, expected) + + +@td.skip_if_no("numba", "0.46.0") +def test_use_global_config(): + def f(x): + return np.mean(x) + 2 + + s = Series(range(10)) + with option_context("compute.use_numba", True): + result = s.rolling(2).apply(f, engine=None, raw=True) + expected = s.rolling(2).apply(f, engine="numba", raw=True) + tm.assert_series_equal(expected, result)
- [x] closes #33966 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35182
2020-07-08T17:25:12Z
2020-07-15T12:28:04Z
2020-07-15T12:28:04Z
2020-07-15T16:32:26Z
TST Verifiy that dropna returns none when called inplace (#35179)
diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index 7cb7115276f71..9bf5d24085697 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -24,14 +24,16 @@ def test_dropEmptyRows(self, float_frame): smaller_frame = frame.dropna(how="all") # check that original was preserved tm.assert_series_equal(frame["foo"], original) - inplace_frame1.dropna(how="all", inplace=True) + return_value = inplace_frame1.dropna(how="all", inplace=True) tm.assert_series_equal(smaller_frame["foo"], expected) tm.assert_series_equal(inplace_frame1["foo"], expected) + assert return_value is None smaller_frame = frame.dropna(how="all", subset=["foo"]) - inplace_frame2.dropna(how="all", subset=["foo"], inplace=True) + return_value = inplace_frame2.dropna(how="all", subset=["foo"], inplace=True) tm.assert_series_equal(smaller_frame["foo"], expected) tm.assert_series_equal(inplace_frame2["foo"], expected) + assert return_value is None def test_dropIncompleteRows(self, float_frame): N = len(float_frame.index) @@ -45,18 +47,20 @@ def test_dropIncompleteRows(self, float_frame): smaller_frame = frame.dropna() tm.assert_series_equal(frame["foo"], original) - inp_frame1.dropna(inplace=True) + return_value = inp_frame1.dropna(inplace=True) exp = Series(mat[5:], index=float_frame.index[5:], name="foo") tm.assert_series_equal(smaller_frame["foo"], exp) tm.assert_series_equal(inp_frame1["foo"], exp) + assert return_value is None samesize_frame = frame.dropna(subset=["bar"]) tm.assert_series_equal(frame["foo"], original) assert (frame["bar"] == 5).all() - inp_frame2.dropna(subset=["bar"], inplace=True) + return_value = inp_frame2.dropna(subset=["bar"], inplace=True) tm.assert_index_equal(samesize_frame.index, float_frame.index) tm.assert_index_equal(inp_frame2.index, float_frame.index) + assert return_value is None def test_dropna(self): df = DataFrame(np.random.randn(6, 4)) @@ -65,31 +69,35 @@ def test_dropna(self): dropped = df.dropna(axis=1) expected = df.loc[:, [0, 1, 3]] inp = df.copy() - inp.dropna(axis=1, inplace=True) + return_value = inp.dropna(axis=1, inplace=True) tm.assert_frame_equal(dropped, expected) tm.assert_frame_equal(inp, expected) + assert return_value is None dropped = df.dropna(axis=0) expected = df.loc[list(range(2, 6))] inp = df.copy() - inp.dropna(axis=0, inplace=True) + return_value = inp.dropna(axis=0, inplace=True) tm.assert_frame_equal(dropped, expected) tm.assert_frame_equal(inp, expected) + assert return_value is None # threshold dropped = df.dropna(axis=1, thresh=5) expected = df.loc[:, [0, 1, 3]] inp = df.copy() - inp.dropna(axis=1, thresh=5, inplace=True) + return_value = inp.dropna(axis=1, thresh=5, inplace=True) tm.assert_frame_equal(dropped, expected) tm.assert_frame_equal(inp, expected) + assert return_value is None dropped = df.dropna(axis=0, thresh=4) expected = df.loc[range(2, 6)] inp = df.copy() - inp.dropna(axis=0, thresh=4, inplace=True) + return_value = inp.dropna(axis=0, thresh=4, inplace=True) tm.assert_frame_equal(dropped, expected) tm.assert_frame_equal(inp, expected) + assert return_value is None dropped = df.dropna(axis=1, thresh=4) tm.assert_frame_equal(dropped, df) @@ -100,9 +108,10 @@ def test_dropna(self): # subset dropped = df.dropna(axis=0, subset=[0, 1, 3]) inp = df.copy() - inp.dropna(axis=0, subset=[0, 1, 3], inplace=True) + return_value = inp.dropna(axis=0, subset=[0, 1, 3], inplace=True) tm.assert_frame_equal(dropped, df) tm.assert_frame_equal(inp, df) + assert return_value is None # all dropped = df.dropna(axis=1, how="all") @@ -126,12 +135,14 @@ def test_drop_and_dropna_caching(self): df2 = df.copy() df["A"].dropna() tm.assert_series_equal(df["A"], original) - df["A"].dropna(inplace=True) + return_value = df["A"].dropna(inplace=True) tm.assert_series_equal(df["A"], expected) + assert return_value is None df2["A"].drop([1]) tm.assert_series_equal(df2["A"], original) - df2["A"].drop([1], inplace=True) + return_value = df2["A"].drop([1], inplace=True) tm.assert_series_equal(df2["A"], original.drop([1])) + assert return_value is None def test_dropna_corner(self, float_frame): # bad input @@ -251,8 +262,9 @@ def test_fillna_different_dtype(self): ) tm.assert_frame_equal(result, expected) - df.fillna({2: "foo"}, inplace=True) + return_value = df.fillna({2: "foo"}, inplace=True) tm.assert_frame_equal(df, expected) + assert return_value is None def test_fillna_limit_and_value(self): # limit and value
Closes https://github.com/pandas-dev/pandas/issues/35179
https://api.github.com/repos/pandas-dev/pandas/pulls/35181
2020-07-08T17:09:01Z
2020-07-09T22:05:35Z
2020-07-09T22:05:34Z
2020-07-10T10:20:35Z
Tst verify dropna returns None inplace (#35179)
diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index 7cb7115276f71..9bf5d24085697 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -24,14 +24,16 @@ def test_dropEmptyRows(self, float_frame): smaller_frame = frame.dropna(how="all") # check that original was preserved tm.assert_series_equal(frame["foo"], original) - inplace_frame1.dropna(how="all", inplace=True) + return_value = inplace_frame1.dropna(how="all", inplace=True) tm.assert_series_equal(smaller_frame["foo"], expected) tm.assert_series_equal(inplace_frame1["foo"], expected) + assert return_value is None smaller_frame = frame.dropna(how="all", subset=["foo"]) - inplace_frame2.dropna(how="all", subset=["foo"], inplace=True) + return_value = inplace_frame2.dropna(how="all", subset=["foo"], inplace=True) tm.assert_series_equal(smaller_frame["foo"], expected) tm.assert_series_equal(inplace_frame2["foo"], expected) + assert return_value is None def test_dropIncompleteRows(self, float_frame): N = len(float_frame.index) @@ -45,18 +47,20 @@ def test_dropIncompleteRows(self, float_frame): smaller_frame = frame.dropna() tm.assert_series_equal(frame["foo"], original) - inp_frame1.dropna(inplace=True) + return_value = inp_frame1.dropna(inplace=True) exp = Series(mat[5:], index=float_frame.index[5:], name="foo") tm.assert_series_equal(smaller_frame["foo"], exp) tm.assert_series_equal(inp_frame1["foo"], exp) + assert return_value is None samesize_frame = frame.dropna(subset=["bar"]) tm.assert_series_equal(frame["foo"], original) assert (frame["bar"] == 5).all() - inp_frame2.dropna(subset=["bar"], inplace=True) + return_value = inp_frame2.dropna(subset=["bar"], inplace=True) tm.assert_index_equal(samesize_frame.index, float_frame.index) tm.assert_index_equal(inp_frame2.index, float_frame.index) + assert return_value is None def test_dropna(self): df = DataFrame(np.random.randn(6, 4)) @@ -65,31 +69,35 @@ def test_dropna(self): dropped = df.dropna(axis=1) expected = df.loc[:, [0, 1, 3]] inp = df.copy() - inp.dropna(axis=1, inplace=True) + return_value = inp.dropna(axis=1, inplace=True) tm.assert_frame_equal(dropped, expected) tm.assert_frame_equal(inp, expected) + assert return_value is None dropped = df.dropna(axis=0) expected = df.loc[list(range(2, 6))] inp = df.copy() - inp.dropna(axis=0, inplace=True) + return_value = inp.dropna(axis=0, inplace=True) tm.assert_frame_equal(dropped, expected) tm.assert_frame_equal(inp, expected) + assert return_value is None # threshold dropped = df.dropna(axis=1, thresh=5) expected = df.loc[:, [0, 1, 3]] inp = df.copy() - inp.dropna(axis=1, thresh=5, inplace=True) + return_value = inp.dropna(axis=1, thresh=5, inplace=True) tm.assert_frame_equal(dropped, expected) tm.assert_frame_equal(inp, expected) + assert return_value is None dropped = df.dropna(axis=0, thresh=4) expected = df.loc[range(2, 6)] inp = df.copy() - inp.dropna(axis=0, thresh=4, inplace=True) + return_value = inp.dropna(axis=0, thresh=4, inplace=True) tm.assert_frame_equal(dropped, expected) tm.assert_frame_equal(inp, expected) + assert return_value is None dropped = df.dropna(axis=1, thresh=4) tm.assert_frame_equal(dropped, df) @@ -100,9 +108,10 @@ def test_dropna(self): # subset dropped = df.dropna(axis=0, subset=[0, 1, 3]) inp = df.copy() - inp.dropna(axis=0, subset=[0, 1, 3], inplace=True) + return_value = inp.dropna(axis=0, subset=[0, 1, 3], inplace=True) tm.assert_frame_equal(dropped, df) tm.assert_frame_equal(inp, df) + assert return_value is None # all dropped = df.dropna(axis=1, how="all") @@ -126,12 +135,14 @@ def test_drop_and_dropna_caching(self): df2 = df.copy() df["A"].dropna() tm.assert_series_equal(df["A"], original) - df["A"].dropna(inplace=True) + return_value = df["A"].dropna(inplace=True) tm.assert_series_equal(df["A"], expected) + assert return_value is None df2["A"].drop([1]) tm.assert_series_equal(df2["A"], original) - df2["A"].drop([1], inplace=True) + return_value = df2["A"].drop([1], inplace=True) tm.assert_series_equal(df2["A"], original.drop([1])) + assert return_value is None def test_dropna_corner(self, float_frame): # bad input @@ -251,8 +262,9 @@ def test_fillna_different_dtype(self): ) tm.assert_frame_equal(result, expected) - df.fillna({2: "foo"}, inplace=True) + return_value = df.fillna({2: "foo"}, inplace=True) tm.assert_frame_equal(df, expected) + assert return_value is None def test_fillna_limit_and_value(self): # limit and value
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35180
2020-07-08T15:37:01Z
2020-07-08T16:44:21Z
null
2020-07-08T16:44:21Z
DOC: fix code snippets for generic indexing
diff --git a/doc/source/user_guide/cookbook.rst b/doc/source/user_guide/cookbook.rst index 50b946999092a..49487ac327e73 100644 --- a/doc/source/user_guide/cookbook.rst +++ b/doc/source/user_guide/cookbook.rst @@ -219,8 +219,8 @@ There are 2 explicit slicing methods, with a third general case df.loc['bar':'kar'] # Label # Generic - df.iloc[0:3] - df.loc['bar':'kar'] + df[0:3] + df['bar':'kar'] Ambiguity arises when an index consists of integers with a non-zero start or non-unit increment.
The code example for generic indexing is the same as positional/label indexing above. I think generic indexing here intended to be referred to something like `df[0:3]` and `df['bar':'kar']`
https://api.github.com/repos/pandas-dev/pandas/pulls/35175
2020-07-08T09:24:03Z
2020-07-09T22:06:36Z
2020-07-09T22:06:36Z
2020-07-09T22:06:43Z
PERF: periodarr_to_dt64arr
diff --git a/asv_bench/benchmarks/tslibs/period.py b/asv_bench/benchmarks/tslibs/period.py index 9156c4aa90ea0..1a2c89b48c665 100644 --- a/asv_bench/benchmarks/tslibs/period.py +++ b/asv_bench/benchmarks/tslibs/period.py @@ -2,10 +2,15 @@ Period benchmarks that rely only on tslibs. See benchmarks.period for Period benchmarks that rely on other parts fo pandas. """ -from pandas import Period + +import numpy as np + +from pandas._libs.tslibs.period import Period, periodarr_to_dt64arr from pandas.tseries.frequencies import to_offset +from .tslib import _sizes + class PeriodProperties: @@ -68,3 +73,34 @@ def setup(self, freq, is_offset): def time_period_constructor(self, freq, is_offset): Period("2012-06-01", freq=freq) + + +class TimePeriodArrToDT64Arr: + params = [ + _sizes, + [ + 1000, + 1011, # Annual - November End + 2000, + 2011, # Quarterly - November End + 3000, + 4000, + 4006, # Weekly - Saturday End + 5000, + 6000, + 7000, + 8000, + 9000, + 10000, + 11000, + 12000, + ], + ] + param_names = ["size", "freq"] + + def setup(self, size, freq): + arr = np.arange(10, dtype="i8").repeat(size // 10) + self.i8values = arr + + def time_periodarray_to_dt64arr(self, size, freq): + periodarr_to_dt64arr(self.i8values, freq) diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index c0641297c4b8a..dbfb26784be63 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -56,6 +56,7 @@ from pandas._libs.tslibs.ccalendar cimport ( get_days_in_month, ) from pandas._libs.tslibs.ccalendar cimport c_MONTH_NUMBERS +from pandas._libs.tslibs.conversion import ensure_datetime64ns from pandas._libs.tslibs.dtypes cimport ( PeriodDtypeBase, @@ -946,14 +947,34 @@ def periodarr_to_dt64arr(const int64_t[:] periodarr, int freq): int64_t[:] out Py_ssize_t i, l - l = len(periodarr) + if freq < 6000: # i.e. FR_DAY, hard-code to avoid need to cast + l = len(periodarr) + out = np.empty(l, dtype="i8") - out = np.empty(l, dtype='i8') + # We get here with freqs that do not correspond to a datetime64 unit + for i in range(l): + out[i] = period_ordinal_to_dt64(periodarr[i], freq) - for i in range(l): - out[i] = period_ordinal_to_dt64(periodarr[i], freq) + return out.base # .base to access underlying np.ndarray - return out.base # .base to access underlying np.ndarray + else: + # Short-circuit for performance + if freq == FR_NS: + return periodarr.base + + if freq == FR_US: + dta = periodarr.base.view("M8[us]") + elif freq == FR_MS: + dta = periodarr.base.view("M8[ms]") + elif freq == FR_SEC: + dta = periodarr.base.view("M8[s]") + elif freq == FR_MIN: + dta = periodarr.base.view("M8[m]") + elif freq == FR_HR: + dta = periodarr.base.view("M8[h]") + elif freq == FR_DAY: + dta = periodarr.base.view("M8[D]") + return ensure_datetime64ns(dta) cpdef int64_t period_asfreq(int64_t ordinal, int freq1, int freq2, bint end):
- [x] closes #33919 - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Re-use `ensure_datetime64ns` for the subset of cases where that is applicable. I'm at a loss for why we get such a slowdown for the other cases. ``` before after ratio [42a6d445] [a0ece778] <master> <perf-periodarr_to_dt64arr> + 48.7±0.8ms 133±6ms 2.72 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 4000) + 48.0±1ms 131±0.8ms 2.72 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 5000) + 493±10μs 1.33±0.05ms 2.70 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 4000) + 47.8±0.4ms 125±3ms 2.62 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 4006) + 599±20μs 1.47±0.07ms 2.46 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 2000) + 60.6±0.9ms 149±7ms 2.45 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 3000) + 524±40μs 1.27±0.04ms 2.42 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 4006) + 587±10μs 1.42±0.04ms 2.41 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 1000) + 59.9±0.8ms 144±0.9ms 2.40 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 1000) + 526±40μs 1.26±0.05ms 2.39 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 5000) + 61.0±1ms 144±2ms 2.35 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 2011) + 60.8±0.5ms 143±0.9ms 2.35 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 2000) + 7.72±0.3μs 17.7±3μs 2.30 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(100, 4000) + 63.7±0.6ms 145±3ms 2.28 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 1011) + 3.04±0.06μs 6.94±1μs 2.28 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 6000) + 611±10μs 1.38±0.06ms 2.27 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 2011) + 653±20μs 1.44±0.03ms 2.20 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 1011) + 2.82±0.07μs 6.12±0.2μs 2.17 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 6000) + 2.81±0.06μs 6.06±0.2μs 2.16 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 9000) + 2.99±0.06μs 6.16±0.2μs 2.06 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 8000) + 2.80±0.06μs 5.75±0.2μs 2.05 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 11000) + 2.95±0.09μs 6.02±0.4μs 2.04 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 9000) + 2.94±0.06μs 5.97±0.2μs 2.03 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 7000) + 701±50μs 1.41±0.01ms 2.01 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 3000) + 3.09±0.1μs 6.18±0.1μs 2.00 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 7000) + 3.02±0.2μs 6.02±0.3μs 1.99 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 8000) + 3.05±0.1μs 5.95±0.2μs 1.95 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 10000) + 7.98±0.3μs 15.4±0.3μs 1.93 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(100, 4006) + 9.01±0.4μs 17.3±0.8μs 1.92 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(100, 2011) + 2.99±0.1μs 5.66±0.2μs 1.89 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 11000) + 3.09±0.09μs 5.82±0.1μs 1.88 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 10000) + 8.20±0.4μs 15.3±0.5μs 1.87 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(100, 5000) + 9.37±0.6μs 17.4±0.5μs 1.86 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(100, 2000) + 9.28±0.6μs 17.2±0.7μs 1.85 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(100, 3000) + 9.61±0.3μs 17.6±0.6μs 1.83 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(100, 1011) + 10.1±0.7μs 17.5±0.7μs 1.73 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(100, 1000) - 2.93±0.1μs 2.48±0.1μs 0.85 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 4000) - 2.90±0.04μs 2.44±0.08μs 0.84 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 2011) - 2.92±0.06μs 2.44±0.1μs 0.84 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 1011) - 3.08±0.1μs 2.56±0.1μs 0.83 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 2011) - 3.03±0.2μs 2.52±0.09μs 0.83 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 4006) - 9.41±0.4μs 7.79±0.2μs 0.83 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(100, 8000) - 2.97±0.1μs 2.42±0.1μs 0.81 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 2000) - 2.99±0.1μs 2.40±0.07μs 0.80 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 4006) - 3.18±0.1μs 2.55±0.1μs 0.80 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 1000) - 3.21±0.2μs 2.48±0.03μs 0.77 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 5000) - 3.07±0.2μs 2.34±0.05μs 0.76 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 3000) - 3.08±0.1μs 2.34±0.04μs 0.76 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 5000) - 3.23±0.1μs 2.43±0.1μs 0.75 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 1000) - 3.16±0.1μs 2.37±0.05μs 0.75 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 2000) - 3.28±0.3μs 2.33±0.08μs 0.71 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 4000) - 3.44±0.3μs 2.36±0.1μs 0.69 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 1011) - 398±20μs 242±7μs 0.61 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 6000) - 39.0±1ms 23.7±0.4ms 0.61 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 6000) - 62.4±0.5ms 28.9±0.5ms 0.46 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 11000) - 64.4±0.2ms 28.6±0.4ms 0.44 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 10000) - 657±20μs 290±10μs 0.44 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 11000) - 64.7±0.4ms 27.9±0.4ms 0.43 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 9000) - 659±20μs 279±8μs 0.42 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 7000) - 64.1±0.6ms 27.1±0.4ms 0.42 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 8000) - 64.6±0.9ms 26.7±0.3ms 0.41 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 7000) - 661±20μs 272±8μs 0.41 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 8000) - 661±10μs 269±10μs 0.41 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 9000) - 698±50μs 282±7μs 0.40 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 10000) - 3.02±0.1μs 344±10ns 0.11 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(0, 12000) - 3.21±0.2μs 342±10ns 0.11 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1, 12000) - 10.6±0.5μs 339±10ns 0.03 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(100, 12000) - 661±20μs 346±5ns 0.00 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(10000, 12000) - 62.3±0.6ms 368±10ns 0.00 tslibs.period.TimePeriodArrToDT64Arr.time_periodarray_to_dt64arr(1000000, 12000) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/35171
2020-07-08T02:17:05Z
2020-07-09T22:08:17Z
2020-07-09T22:08:17Z
2020-07-09T23:21:34Z
DOC: Add pint pandas ecosystem docs
diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index 72e24e34bc5c1..b02d4abd3ddf8 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -421,6 +421,14 @@ found in NumPy or pandas, which work well with pandas' data containers. Cyberpandas provides an extension type for storing arrays of IP Addresses. These arrays can be stored inside pandas' Series and DataFrame. +`Pint-Pandas`_ +~~~~~~~~~~~~~~ + +`Pint-Pandas <https://github.com/hgrecco/pint-pandas>` provides an extension type for +storing numeric arrays with units. These arrays can be stored inside pandas' +Series and DataFrame. Operations between Series and DataFrame columns which +use pint's extension array are then units aware. + .. _ecosystem.accessors: Accessors @@ -436,6 +444,7 @@ Library Accessor Classes Description `cyberpandas`_ ``ip`` ``Series`` Provides common operations for working with IP addresses. `pdvega`_ ``vgplot`` ``Series``, ``DataFrame`` Provides plotting functions from the Altair_ library. `pandas_path`_ ``path`` ``Index``, ``Series`` Provides `pathlib.Path`_ functions for Series. +`pint-pandas`_ ``pint`` ``Series``, ``DataFrame`` Provides units support for numeric Series and DataFrames. =============== ========== ========================= =============================================================== .. _cyberpandas: https://cyberpandas.readthedocs.io/en/latest @@ -443,3 +452,4 @@ Library Accessor Classes Description .. _Altair: https://altair-viz.github.io/ .. _pandas_path: https://github.com/drivendataorg/pandas-path/ .. _pathlib.Path: https://docs.python.org/3/library/pathlib.html +.. _pint-pandas: https://github.com/hgrecco/pint-pandas diff --git a/web/pandas/community/ecosystem.md b/web/pandas/community/ecosystem.md index 715a84c1babc6..be109ea53eb7d 100644 --- a/web/pandas/community/ecosystem.md +++ b/web/pandas/community/ecosystem.md @@ -353,13 +353,22 @@ Cyberpandas provides an extension type for storing arrays of IP Addresses. These arrays can be stored inside pandas' Series and DataFrame. +### [Pint-Pandas](https://github.com/hgrecco/pint-pandas) + +Pint-Pandas provides an extension type for storing numeric arrays with units. +These arrays can be stored inside pandas' Series and DataFrame. Operations +between Series and DataFrame columns which use pint's extension array are then +units aware. + ## Accessors A directory of projects providing `extension accessors <extending.register-accessors>`. This is for users to discover new accessors and for library authors to coordinate on the namespace. - | Library | Accessor | Classes | - | ------------------------------------------------------------|----------|-----------------------| - | [cyberpandas](https://cyberpandas.readthedocs.io/en/latest) | `ip` | `Series` | - | [pdvega](https://altair-viz.github.io/pdvega/) | `vgplot` | `Series`, `DataFrame` | + | Library | Accessor | Classes | + | --------------------------------------------------------------|----------|-----------------------| + | [cyberpandas](https://cyberpandas.readthedocs.io/en/latest) | `ip` | `Series` | + | [pdvega](https://altair-viz.github.io/pdvega/) | `vgplot` | `Series`, `DataFrame` | + | [pandas_path](https://github.com/drivendataorg/pandas-path/) | `path` | `Index`, `Series` | + | [pint-pandas](https://github.com/hgrecco/pint-pandas) | `pint` | `Series`, `DataFrame` |
- [ ] closes #xxxx (N/A) - [ ] tests added / passed (N/A) - [ ] passes `black pandas` (N/A) - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` (N/A) - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35170
2020-07-07T22:41:48Z
2020-07-10T20:33:18Z
2020-07-10T20:33:18Z
2020-07-10T20:33:25Z
REF: collect get_dst_info-using functions in tslibs.vectorized
diff --git a/asv_bench/benchmarks/tslibs/resolution.py b/asv_bench/benchmarks/tslibs/resolution.py index 274aa1ad6d4a9..280be7932d4db 100644 --- a/asv_bench/benchmarks/tslibs/resolution.py +++ b/asv_bench/benchmarks/tslibs/resolution.py @@ -23,7 +23,10 @@ import numpy as np import pytz -from pandas._libs.tslibs.resolution import get_resolution +try: + from pandas._libs.tslibs import get_resolution +except ImportError: + from pandas._libs.tslibs.resolution import get_resolution class TimeResolution: diff --git a/asv_bench/benchmarks/tslibs/tslib.py b/asv_bench/benchmarks/tslibs/tslib.py index eacf5a5731dc2..5952a402bf89a 100644 --- a/asv_bench/benchmarks/tslibs/tslib.py +++ b/asv_bench/benchmarks/tslibs/tslib.py @@ -21,7 +21,10 @@ import numpy as np import pytz -from pandas._libs.tslib import ints_to_pydatetime +try: + from pandas._libs.tslibs import ints_to_pydatetime +except ImportError: + from pandas._libs.tslib import ints_to_pydatetime _tzs = [ None, diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 3472dbf161b8e..d70d0378a2621 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -4,18 +4,14 @@ from cpython.datetime cimport ( PyDate_Check, PyDateTime_Check, PyDateTime_IMPORT, - date, datetime, - time, - timedelta, - tzinfo, ) # import datetime C API PyDateTime_IMPORT cimport numpy as cnp -from numpy cimport float64_t, int64_t, ndarray, uint8_t, intp_t +from numpy cimport float64_t, int64_t, ndarray import numpy as np cnp.import_array() @@ -42,11 +38,6 @@ from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime from pandas._libs.tslibs.parsing import parse_datetime_string -from pandas._libs.tslibs.timezones cimport ( - get_dst_info, - is_utc, - is_tzlocal, -) from pandas._libs.tslibs.conversion cimport ( _TSObject, cast_from_unit, @@ -60,13 +51,10 @@ from pandas._libs.tslibs.nattype cimport ( c_nat_strings as nat_strings, ) -from pandas._libs.tslibs.offsets cimport to_offset - -from pandas._libs.tslibs.timestamps cimport create_timestamp_from_ts, _Timestamp +from pandas._libs.tslibs.timestamps cimport _Timestamp from pandas._libs.tslibs.timestamps import Timestamp from pandas._libs.tslibs.tzconversion cimport ( - tz_convert_utc_to_tzlocal, tz_localize_to_utc_single, ) @@ -74,160 +62,6 @@ from pandas._libs.tslibs.tzconversion cimport ( from pandas._libs.missing cimport checknull_with_nat_and_na -cdef inline object create_datetime_from_ts( - int64_t value, - npy_datetimestruct dts, - tzinfo tz, - object freq, - bint fold, -): - """ - Convenience routine to construct a datetime.datetime from its parts. - """ - return datetime( - dts.year, dts.month, dts.day, dts.hour, dts.min, dts.sec, dts.us, tz, fold=fold - ) - - -cdef inline object create_date_from_ts( - int64_t value, - npy_datetimestruct dts, - tzinfo tz, - object freq, - bint fold -): - """ - Convenience routine to construct a datetime.date from its parts. - """ - # GH 25057 add fold argument to match other func_create signatures - return date(dts.year, dts.month, dts.day) - - -cdef inline object create_time_from_ts( - int64_t value, - npy_datetimestruct dts, - tzinfo tz, - object freq, - bint fold -): - """ - Convenience routine to construct a datetime.time from its parts. - """ - return time(dts.hour, dts.min, dts.sec, dts.us, tz, fold=fold) - - -@cython.wraparound(False) -@cython.boundscheck(False) -def ints_to_pydatetime( - const int64_t[:] arr, - tzinfo tz=None, - object freq=None, - bint fold=False, - str box="datetime" -): - """ - Convert an i8 repr to an ndarray of datetimes, date, time or Timestamp. - - Parameters - ---------- - arr : array of i8 - tz : str, optional - convert to this timezone - freq : str/Offset, optional - freq to convert - fold : bint, default is 0 - Due to daylight saving time, one wall clock time can occur twice - when shifting from summer to winter time; fold describes whether the - datetime-like corresponds to the first (0) or the second time (1) - the wall clock hits the ambiguous time - - .. versionadded:: 1.1.0 - box : {'datetime', 'timestamp', 'date', 'time'}, default 'datetime' - * If datetime, convert to datetime.datetime - * If date, convert to datetime.date - * If time, convert to datetime.time - * If Timestamp, convert to pandas.Timestamp - - Returns - ------- - ndarray of dtype specified by box - """ - cdef: - Py_ssize_t i, n = len(arr) - ndarray[int64_t] trans - int64_t[:] deltas - intp_t[:] pos - npy_datetimestruct dts - object dt, new_tz - str typ - int64_t value, local_value, delta = NPY_NAT # dummy for delta - ndarray[object] result = np.empty(n, dtype=object) - object (*func_create)(int64_t, npy_datetimestruct, tzinfo, object, bint) - bint use_utc = False, use_tzlocal = False, use_fixed = False - bint use_pytz = False - - if box == "date": - assert (tz is None), "tz should be None when converting to date" - - func_create = create_date_from_ts - elif box == "timestamp": - func_create = create_timestamp_from_ts - - if isinstance(freq, str): - freq = to_offset(freq) - elif box == "time": - func_create = create_time_from_ts - elif box == "datetime": - func_create = create_datetime_from_ts - else: - raise ValueError( - "box must be one of 'datetime', 'date', 'time' or 'timestamp'" - ) - - if is_utc(tz) or tz is None: - use_utc = True - elif is_tzlocal(tz): - use_tzlocal = True - else: - trans, deltas, typ = get_dst_info(tz) - if typ not in ["pytz", "dateutil"]: - # static/fixed; in this case we know that len(delta) == 1 - use_fixed = True - delta = deltas[0] - else: - pos = trans.searchsorted(arr, side="right") - 1 - use_pytz = typ == "pytz" - - for i in range(n): - new_tz = tz - value = arr[i] - - if value == NPY_NAT: - result[i] = <object>NaT - else: - if use_utc: - local_value = value - elif use_tzlocal: - local_value = tz_convert_utc_to_tzlocal(value, tz) - elif use_fixed: - local_value = value + delta - elif not use_pytz: - # i.e. dateutil - # no zone-name change for dateutil tzs - dst etc - # represented in single object. - local_value = value + deltas[pos[i]] - else: - # pytz - # find right representation of dst etc in pytz timezone - new_tz = tz._tzinfos[tz._transition_info[pos[i]]] - local_value = value + deltas[pos[i]] - - dt64_to_dtstruct(local_value, &dts) - result[i] = func_create(value, dts, new_tz, freq, fold) - - return result - - def _test_parse_iso8601(ts: str): """ TESTING ONLY: Parse string into Timestamp using iso8601 parser. Used diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py index 76e356370de70..c2f3478a50ab4 100644 --- a/pandas/_libs/tslibs/__init__.py +++ b/pandas/_libs/tslibs/__init__.py @@ -11,8 +11,13 @@ "Period", "Resolution", "Timedelta", + "normalize_i8_timestamps", + "is_date_array_normalized", + "dt64arr_to_periodarr", "delta_to_nanoseconds", + "ints_to_pydatetime", "ints_to_pytimedelta", + "get_resolution", "Timestamp", "tz_convert_single", "to_offset", @@ -30,3 +35,10 @@ from .timedeltas import Timedelta, delta_to_nanoseconds, ints_to_pytimedelta from .timestamps import Timestamp from .tzconversion import tz_convert_single +from .vectorized import ( + dt64arr_to_periodarr, + get_resolution, + ints_to_pydatetime, + is_date_array_normalized, + normalize_i8_timestamps, +) diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index 0eb94fecf7d6b..73772e5ab4577 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -25,5 +25,4 @@ cdef int64_t get_datetime64_nanos(object val) except? -1 cpdef datetime localize_pydatetime(datetime dt, object tz) cdef int64_t cast_from_unit(object ts, str unit) except? -1 -cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo tz) cdef int64_t normalize_i8_stamp(int64_t local_val) nogil diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 36a4a1f60d8b9..31d2d0e9572f5 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -765,73 +765,6 @@ cpdef inline datetime localize_pydatetime(datetime dt, object tz): # ---------------------------------------------------------------------- # Normalization - -@cython.wraparound(False) -@cython.boundscheck(False) -cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo tz): - """ - Normalize each of the (nanosecond) timezone aware timestamps in the given - array by rounding down to the beginning of the day (i.e. midnight). - This is midnight for timezone, `tz`. - - Parameters - ---------- - stamps : int64 ndarray - tz : tzinfo or None - - Returns - ------- - result : int64 ndarray of converted of normalized nanosecond timestamps - """ - cdef: - Py_ssize_t i, n = len(stamps) - int64_t[:] result = np.empty(n, dtype=np.int64) - ndarray[int64_t] trans - int64_t[:] deltas - str typ - Py_ssize_t[:] pos - int64_t delta, local_val - - if tz is None or is_utc(tz): - with nogil: - for i in range(n): - if stamps[i] == NPY_NAT: - result[i] = NPY_NAT - continue - local_val = stamps[i] - result[i] = normalize_i8_stamp(local_val) - elif is_tzlocal(tz): - for i in range(n): - if stamps[i] == NPY_NAT: - result[i] = NPY_NAT - continue - local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) - result[i] = normalize_i8_stamp(local_val) - else: - # Adjust datetime64 timestamp, recompute datetimestruct - trans, deltas, typ = get_dst_info(tz) - - if typ not in ['pytz', 'dateutil']: - # static/fixed; in this case we know that len(delta) == 1 - delta = deltas[0] - for i in range(n): - if stamps[i] == NPY_NAT: - result[i] = NPY_NAT - continue - local_val = stamps[i] + delta - result[i] = normalize_i8_stamp(local_val) - else: - pos = trans.searchsorted(stamps, side='right') - 1 - for i in range(n): - if stamps[i] == NPY_NAT: - result[i] = NPY_NAT - continue - local_val = stamps[i] + deltas[pos[i]] - result[i] = normalize_i8_stamp(local_val) - - return result.base # `.base` to access underlying ndarray - - @cython.cdivision cdef inline int64_t normalize_i8_stamp(int64_t local_val) nogil: """ @@ -848,63 +781,3 @@ cdef inline int64_t normalize_i8_stamp(int64_t local_val) nogil: cdef: int64_t day_nanos = 24 * 3600 * 1_000_000_000 return local_val - (local_val % day_nanos) - - -@cython.wraparound(False) -@cython.boundscheck(False) -def is_date_array_normalized(const int64_t[:] stamps, tzinfo tz=None): - """ - Check if all of the given (nanosecond) timestamps are normalized to - midnight, i.e. hour == minute == second == 0. If the optional timezone - `tz` is not None, then this is midnight for this timezone. - - Parameters - ---------- - stamps : int64 ndarray - tz : tzinfo or None - - Returns - ------- - is_normalized : bool True if all stamps are normalized - """ - cdef: - Py_ssize_t i, n = len(stamps) - ndarray[int64_t] trans - int64_t[:] deltas - intp_t[:] pos - int64_t local_val, delta - str typ - int64_t day_nanos = 24 * 3600 * 1_000_000_000 - - if tz is None or is_utc(tz): - for i in range(n): - local_val = stamps[i] - if local_val % day_nanos != 0: - return False - - elif is_tzlocal(tz): - for i in range(n): - local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) - if local_val % day_nanos != 0: - return False - else: - trans, deltas, typ = get_dst_info(tz) - - if typ not in ['pytz', 'dateutil']: - # static/fixed; in this case we know that len(delta) == 1 - delta = deltas[0] - for i in range(n): - # Adjust datetime64 timestamp, recompute datetimestruct - local_val = stamps[i] + delta - if local_val % day_nanos != 0: - return False - - else: - pos = trans.searchsorted(stamps) - 1 - for i in range(n): - # Adjust datetime64 timestamp, recompute datetimestruct - local_val = stamps[i] + deltas[pos[i]] - if local_val % day_nanos != 0: - return False - - return True diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index e4d05e0d70e2f..fb07e3fe7547e 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -38,7 +38,6 @@ from pandas._libs.tslibs.ccalendar cimport DAY_NANOS, get_days_in_month, dayofwe from pandas._libs.tslibs.conversion cimport ( convert_datetime_to_tsobject, localize_pydatetime, - normalize_i8_timestamps, ) from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT from pandas._libs.tslibs.np_datetime cimport ( @@ -92,6 +91,8 @@ def apply_index_wraps(func): result = np.asarray(result) if self.normalize: + # TODO: Avoid circular/runtime import + from .vectorized import normalize_i8_timestamps result = normalize_i8_timestamps(result.view("i8"), None) return result diff --git a/pandas/_libs/tslibs/period.pxd b/pandas/_libs/tslibs/period.pxd index eb11a4a572e85..9c0342e239a89 100644 --- a/pandas/_libs/tslibs/period.pxd +++ b/pandas/_libs/tslibs/period.pxd @@ -1 +1,6 @@ +from numpy cimport int64_t + +from .np_datetime cimport npy_datetimestruct + cdef bint is_period_object(object obj) +cdef int64_t get_period_ordinal(npy_datetimestruct *dts, int freq) nogil diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index c0641297c4b8a..e6ba1968797ed 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -14,7 +14,6 @@ import cython from cpython.datetime cimport ( datetime, - tzinfo, PyDate_Check, PyDateTime_Check, PyDateTime_IMPORT, @@ -41,7 +40,6 @@ cdef extern from "src/datetime/np_datetime.h": cimport pandas._libs.tslibs.util as util from pandas._libs.tslibs.timestamps import Timestamp -from pandas._libs.tslibs.timezones cimport is_utc, is_tzlocal, get_dst_info from pandas._libs.tslibs.timedeltas import Timedelta from pandas._libs.tslibs.timedeltas cimport ( delta_to_nanoseconds, @@ -91,7 +89,6 @@ from pandas._libs.tslibs.offsets cimport ( is_offset_object, ) from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG -from pandas._libs.tslibs.tzconversion cimport tz_convert_utc_to_tzlocal cdef: @@ -1416,60 +1413,6 @@ def extract_freq(ndarray[object] values): # period helpers -@cython.wraparound(False) -@cython.boundscheck(False) -def dt64arr_to_periodarr(const int64_t[:] stamps, int freq, tzinfo tz): - cdef: - Py_ssize_t n = len(stamps) - int64_t[:] result = np.empty(n, dtype=np.int64) - ndarray[int64_t] trans - int64_t[:] deltas - Py_ssize_t[:] pos - npy_datetimestruct dts - int64_t local_val - - if is_utc(tz) or tz is None: - with nogil: - for i in range(n): - if stamps[i] == NPY_NAT: - result[i] = NPY_NAT - continue - dt64_to_dtstruct(stamps[i], &dts) - result[i] = get_period_ordinal(&dts, freq) - - elif is_tzlocal(tz): - for i in range(n): - if stamps[i] == NPY_NAT: - result[i] = NPY_NAT - continue - local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) - dt64_to_dtstruct(local_val, &dts) - result[i] = get_period_ordinal(&dts, freq) - else: - # Adjust datetime64 timestamp, recompute datetimestruct - trans, deltas, typ = get_dst_info(tz) - - if typ not in ['pytz', 'dateutil']: - # static/fixed; in this case we know that len(delta) == 1 - for i in range(n): - if stamps[i] == NPY_NAT: - result[i] = NPY_NAT - continue - dt64_to_dtstruct(stamps[i] + deltas[0], &dts) - result[i] = get_period_ordinal(&dts, freq) - else: - pos = trans.searchsorted(stamps, side='right') - 1 - - for i in range(n): - if stamps[i] == NPY_NAT: - result[i] = NPY_NAT - continue - dt64_to_dtstruct(stamps[i] + deltas[pos[i]], &dts) - result[i] = get_period_ordinal(&dts, freq) - - return result.base # .base to get underlying ndarray - - DIFFERENT_FREQ = ("Input has different freq={other_freq} " "from {cls}(freq={own_freq})") diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index d5f10374d2860..d2861d8e9fe8d 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -1,105 +1,9 @@ -from cpython.datetime cimport tzinfo import numpy as np -from numpy cimport ndarray, int64_t, int32_t - -from pandas._libs.tslibs.util cimport get_nat +from numpy cimport int32_t from pandas._libs.tslibs.dtypes import Resolution -from pandas._libs.tslibs.np_datetime cimport ( - npy_datetimestruct, dt64_to_dtstruct) -from pandas._libs.tslibs.timezones cimport ( - is_utc, is_tzlocal, get_dst_info) from pandas._libs.tslibs.ccalendar cimport get_days_in_month -from pandas._libs.tslibs.tzconversion cimport tz_convert_utc_to_tzlocal - -# ---------------------------------------------------------------------- -# Constants - -cdef: - int64_t NPY_NAT = get_nat() - - int RESO_NS = 0 - int RESO_US = 1 - int RESO_MS = 2 - int RESO_SEC = 3 - int RESO_MIN = 4 - int RESO_HR = 5 - int RESO_DAY = 6 - int RESO_MTH = 7 - int RESO_QTR = 8 - int RESO_YR = 9 - - -# ---------------------------------------------------------------------- - - -def get_resolution(const int64_t[:] stamps, tzinfo tz=None): - cdef: - Py_ssize_t i, n = len(stamps) - npy_datetimestruct dts - int reso = RESO_DAY, curr_reso - ndarray[int64_t] trans - int64_t[:] deltas - Py_ssize_t[:] pos - int64_t local_val, delta - - if is_utc(tz) or tz is None: - for i in range(n): - if stamps[i] == NPY_NAT: - continue - dt64_to_dtstruct(stamps[i], &dts) - curr_reso = _reso_stamp(&dts) - if curr_reso < reso: - reso = curr_reso - elif is_tzlocal(tz): - for i in range(n): - if stamps[i] == NPY_NAT: - continue - local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) - dt64_to_dtstruct(local_val, &dts) - curr_reso = _reso_stamp(&dts) - if curr_reso < reso: - reso = curr_reso - else: - # Adjust datetime64 timestamp, recompute datetimestruct - trans, deltas, typ = get_dst_info(tz) - - if typ not in ['pytz', 'dateutil']: - # static/fixed; in this case we know that len(delta) == 1 - delta = deltas[0] - for i in range(n): - if stamps[i] == NPY_NAT: - continue - dt64_to_dtstruct(stamps[i] + delta, &dts) - curr_reso = _reso_stamp(&dts) - if curr_reso < reso: - reso = curr_reso - else: - pos = trans.searchsorted(stamps, side='right') - 1 - for i in range(n): - if stamps[i] == NPY_NAT: - continue - dt64_to_dtstruct(stamps[i] + deltas[pos[i]], &dts) - curr_reso = _reso_stamp(&dts) - if curr_reso < reso: - reso = curr_reso - - return Resolution(reso) - - -cdef inline int _reso_stamp(npy_datetimestruct *dts): - if dts.us != 0: - if dts.us % 1000 == 0: - return RESO_MS - return RESO_US - elif dts.sec != 0: - return RESO_SEC - elif dts.min != 0: - return RESO_MIN - elif dts.hour != 0: - return RESO_HR - return RESO_DAY # ---------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/vectorized.pyx b/pandas/_libs/tslibs/vectorized.pyx new file mode 100644 index 0000000000000..c8f8daf6724c2 --- /dev/null +++ b/pandas/_libs/tslibs/vectorized.pyx @@ -0,0 +1,440 @@ +import cython + +from cpython.datetime cimport datetime, date, time, tzinfo + +import numpy as np +from numpy cimport int64_t, intp_t, ndarray + +from .conversion cimport normalize_i8_stamp +from .dtypes import Resolution +from .nattype cimport NPY_NAT, c_NaT as NaT +from .np_datetime cimport npy_datetimestruct, dt64_to_dtstruct +from .offsets cimport to_offset +from .period cimport get_period_ordinal +from .timestamps cimport create_timestamp_from_ts +from .timezones cimport is_utc, is_tzlocal, get_dst_info +from .tzconversion cimport tz_convert_utc_to_tzlocal + +# ------------------------------------------------------------------------- + +cdef inline object create_datetime_from_ts( + int64_t value, + npy_datetimestruct dts, + tzinfo tz, + object freq, + bint fold, +): + """ + Convenience routine to construct a datetime.datetime from its parts. + """ + return datetime( + dts.year, dts.month, dts.day, dts.hour, dts.min, dts.sec, dts.us, + tz, fold=fold, + ) + + +cdef inline object create_date_from_ts( + int64_t value, + npy_datetimestruct dts, + tzinfo tz, + object freq, + bint fold +): + """ + Convenience routine to construct a datetime.date from its parts. + """ + # GH#25057 add fold argument to match other func_create signatures + return date(dts.year, dts.month, dts.day) + + +cdef inline object create_time_from_ts( + int64_t value, + npy_datetimestruct dts, + tzinfo tz, + object freq, + bint fold +): + """ + Convenience routine to construct a datetime.time from its parts. + """ + return time(dts.hour, dts.min, dts.sec, dts.us, tz, fold=fold) + + +@cython.wraparound(False) +@cython.boundscheck(False) +def ints_to_pydatetime( + const int64_t[:] arr, + tzinfo tz=None, + object freq=None, + bint fold=False, + str box="datetime" +): + """ + Convert an i8 repr to an ndarray of datetimes, date, time or Timestamp. + + Parameters + ---------- + arr : array of i8 + tz : str, optional + convert to this timezone + freq : str/Offset, optional + freq to convert + fold : bint, default is 0 + Due to daylight saving time, one wall clock time can occur twice + when shifting from summer to winter time; fold describes whether the + datetime-like corresponds to the first (0) or the second time (1) + the wall clock hits the ambiguous time + + .. versionadded:: 1.1.0 + box : {'datetime', 'timestamp', 'date', 'time'}, default 'datetime' + * If datetime, convert to datetime.datetime + * If date, convert to datetime.date + * If time, convert to datetime.time + * If Timestamp, convert to pandas.Timestamp + + Returns + ------- + ndarray of dtype specified by box + """ + cdef: + Py_ssize_t i, n = len(arr) + ndarray[int64_t] trans + int64_t[:] deltas + intp_t[:] pos + npy_datetimestruct dts + object dt, new_tz + str typ + int64_t value, local_value, delta = NPY_NAT # dummy for delta + ndarray[object] result = np.empty(n, dtype=object) + object (*func_create)(int64_t, npy_datetimestruct, tzinfo, object, bint) + bint use_utc = False, use_tzlocal = False, use_fixed = False + bint use_pytz = False + + if box == "date": + assert (tz is None), "tz should be None when converting to date" + + func_create = create_date_from_ts + elif box == "timestamp": + func_create = create_timestamp_from_ts + + if isinstance(freq, str): + freq = to_offset(freq) + elif box == "time": + func_create = create_time_from_ts + elif box == "datetime": + func_create = create_datetime_from_ts + else: + raise ValueError( + "box must be one of 'datetime', 'date', 'time' or 'timestamp'" + ) + + if is_utc(tz) or tz is None: + use_utc = True + elif is_tzlocal(tz): + use_tzlocal = True + else: + trans, deltas, typ = get_dst_info(tz) + if typ not in ["pytz", "dateutil"]: + # static/fixed; in this case we know that len(delta) == 1 + use_fixed = True + delta = deltas[0] + else: + pos = trans.searchsorted(arr, side="right") - 1 + use_pytz = typ == "pytz" + + for i in range(n): + new_tz = tz + value = arr[i] + + if value == NPY_NAT: + result[i] = <object>NaT + else: + if use_utc: + local_value = value + elif use_tzlocal: + local_value = tz_convert_utc_to_tzlocal(value, tz) + elif use_fixed: + local_value = value + delta + elif not use_pytz: + # i.e. dateutil + # no zone-name change for dateutil tzs - dst etc + # represented in single object. + local_value = value + deltas[pos[i]] + else: + # pytz + # find right representation of dst etc in pytz timezone + new_tz = tz._tzinfos[tz._transition_info[pos[i]]] + local_value = value + deltas[pos[i]] + + dt64_to_dtstruct(local_value, &dts) + result[i] = func_create(value, dts, new_tz, freq, fold) + + return result + + +# ------------------------------------------------------------------------- + +cdef: + int RESO_NS = 0 + int RESO_US = 1 + int RESO_MS = 2 + int RESO_SEC = 3 + int RESO_MIN = 4 + int RESO_HR = 5 + int RESO_DAY = 6 + int RESO_MTH = 7 + int RESO_QTR = 8 + int RESO_YR = 9 + + +cdef inline int _reso_stamp(npy_datetimestruct *dts): + if dts.us != 0: + if dts.us % 1000 == 0: + return RESO_MS + return RESO_US + elif dts.sec != 0: + return RESO_SEC + elif dts.min != 0: + return RESO_MIN + elif dts.hour != 0: + return RESO_HR + return RESO_DAY + + +def get_resolution(const int64_t[:] stamps, tzinfo tz=None): + cdef: + Py_ssize_t i, n = len(stamps) + npy_datetimestruct dts + int reso = RESO_DAY, curr_reso + ndarray[int64_t] trans + int64_t[:] deltas + Py_ssize_t[:] pos + int64_t local_val, delta + + if is_utc(tz) or tz is None: + for i in range(n): + if stamps[i] == NPY_NAT: + continue + dt64_to_dtstruct(stamps[i], &dts) + curr_reso = _reso_stamp(&dts) + if curr_reso < reso: + reso = curr_reso + elif is_tzlocal(tz): + for i in range(n): + if stamps[i] == NPY_NAT: + continue + local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) + dt64_to_dtstruct(local_val, &dts) + curr_reso = _reso_stamp(&dts) + if curr_reso < reso: + reso = curr_reso + else: + # Adjust datetime64 timestamp, recompute datetimestruct + trans, deltas, typ = get_dst_info(tz) + + if typ not in ["pytz", "dateutil"]: + # static/fixed; in this case we know that len(delta) == 1 + delta = deltas[0] + for i in range(n): + if stamps[i] == NPY_NAT: + continue + dt64_to_dtstruct(stamps[i] + delta, &dts) + curr_reso = _reso_stamp(&dts) + if curr_reso < reso: + reso = curr_reso + else: + pos = trans.searchsorted(stamps, side="right") - 1 + for i in range(n): + if stamps[i] == NPY_NAT: + continue + dt64_to_dtstruct(stamps[i] + deltas[pos[i]], &dts) + curr_reso = _reso_stamp(&dts) + if curr_reso < reso: + reso = curr_reso + + return Resolution(reso) + + +# ------------------------------------------------------------------------- + +@cython.wraparound(False) +@cython.boundscheck(False) +cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo tz): + """ + Normalize each of the (nanosecond) timezone aware timestamps in the given + array by rounding down to the beginning of the day (i.e. midnight). + This is midnight for timezone, `tz`. + + Parameters + ---------- + stamps : int64 ndarray + tz : tzinfo or None + + Returns + ------- + result : int64 ndarray of converted of normalized nanosecond timestamps + """ + cdef: + Py_ssize_t i, n = len(stamps) + int64_t[:] result = np.empty(n, dtype=np.int64) + ndarray[int64_t] trans + int64_t[:] deltas + str typ + Py_ssize_t[:] pos + int64_t delta, local_val + + if tz is None or is_utc(tz): + with nogil: + for i in range(n): + if stamps[i] == NPY_NAT: + result[i] = NPY_NAT + continue + local_val = stamps[i] + result[i] = normalize_i8_stamp(local_val) + elif is_tzlocal(tz): + for i in range(n): + if stamps[i] == NPY_NAT: + result[i] = NPY_NAT + continue + local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) + result[i] = normalize_i8_stamp(local_val) + else: + # Adjust datetime64 timestamp, recompute datetimestruct + trans, deltas, typ = get_dst_info(tz) + + if typ not in ["pytz", "dateutil"]: + # static/fixed; in this case we know that len(delta) == 1 + delta = deltas[0] + for i in range(n): + if stamps[i] == NPY_NAT: + result[i] = NPY_NAT + continue + local_val = stamps[i] + delta + result[i] = normalize_i8_stamp(local_val) + else: + pos = trans.searchsorted(stamps, side="right") - 1 + for i in range(n): + if stamps[i] == NPY_NAT: + result[i] = NPY_NAT + continue + local_val = stamps[i] + deltas[pos[i]] + result[i] = normalize_i8_stamp(local_val) + + return result.base # `.base` to access underlying ndarray + + +@cython.wraparound(False) +@cython.boundscheck(False) +def is_date_array_normalized(const int64_t[:] stamps, tzinfo tz=None): + """ + Check if all of the given (nanosecond) timestamps are normalized to + midnight, i.e. hour == minute == second == 0. If the optional timezone + `tz` is not None, then this is midnight for this timezone. + + Parameters + ---------- + stamps : int64 ndarray + tz : tzinfo or None + + Returns + ------- + is_normalized : bool True if all stamps are normalized + """ + cdef: + Py_ssize_t i, n = len(stamps) + ndarray[int64_t] trans + int64_t[:] deltas + intp_t[:] pos + int64_t local_val, delta + str typ + int64_t day_nanos = 24 * 3600 * 1_000_000_000 + + if tz is None or is_utc(tz): + for i in range(n): + local_val = stamps[i] + if local_val % day_nanos != 0: + return False + + elif is_tzlocal(tz): + for i in range(n): + local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) + if local_val % day_nanos != 0: + return False + else: + trans, deltas, typ = get_dst_info(tz) + + if typ not in ["pytz", "dateutil"]: + # static/fixed; in this case we know that len(delta) == 1 + delta = deltas[0] + for i in range(n): + # Adjust datetime64 timestamp, recompute datetimestruct + local_val = stamps[i] + delta + if local_val % day_nanos != 0: + return False + + else: + pos = trans.searchsorted(stamps) - 1 + for i in range(n): + # Adjust datetime64 timestamp, recompute datetimestruct + local_val = stamps[i] + deltas[pos[i]] + if local_val % day_nanos != 0: + return False + + return True + + +# ------------------------------------------------------------------------- + + +@cython.wraparound(False) +@cython.boundscheck(False) +def dt64arr_to_periodarr(const int64_t[:] stamps, int freq, tzinfo tz): + cdef: + Py_ssize_t n = len(stamps) + int64_t[:] result = np.empty(n, dtype=np.int64) + ndarray[int64_t] trans + int64_t[:] deltas + Py_ssize_t[:] pos + npy_datetimestruct dts + int64_t local_val + + if is_utc(tz) or tz is None: + with nogil: + for i in range(n): + if stamps[i] == NPY_NAT: + result[i] = NPY_NAT + continue + dt64_to_dtstruct(stamps[i], &dts) + result[i] = get_period_ordinal(&dts, freq) + + elif is_tzlocal(tz): + for i in range(n): + if stamps[i] == NPY_NAT: + result[i] = NPY_NAT + continue + local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) + dt64_to_dtstruct(local_val, &dts) + result[i] = get_period_ordinal(&dts, freq) + else: + # Adjust datetime64 timestamp, recompute datetimestruct + trans, deltas, typ = get_dst_info(tz) + + if typ not in ["pytz", "dateutil"]: + # static/fixed; in this case we know that len(delta) == 1 + for i in range(n): + if stamps[i] == NPY_NAT: + result[i] = NPY_NAT + continue + dt64_to_dtstruct(stamps[i] + deltas[0], &dts) + result[i] = get_period_ordinal(&dts, freq) + else: + pos = trans.searchsorted(stamps, side="right") - 1 + + for i in range(n): + if stamps[i] == NPY_NAT: + result[i] = NPY_NAT + continue + dt64_to_dtstruct(stamps[i] + deltas[pos[i]], &dts) + result[i] = get_period_ordinal(&dts, freq) + + return result.base # .base to get underlying ndarray diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index fcfbaa4ac2a1c..8eac45cdedaec 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -10,7 +10,11 @@ Timestamp, conversion, fields, + get_resolution, iNaT, + ints_to_pydatetime, + is_date_array_normalized, + normalize_i8_timestamps, resolution as libresolution, timezones, to_offset, @@ -526,11 +530,11 @@ def is_normalized(self): """ Returns True if all of the dates are at midnight ("no time") """ - return conversion.is_date_array_normalized(self.asi8, self.tz) + return is_date_array_normalized(self.asi8, self.tz) @property # NB: override with cache_readonly in immutable subclasses def _resolution_obj(self) -> libresolution.Resolution: - return libresolution.get_resolution(self.asi8, self.tz) + return get_resolution(self.asi8, self.tz) # ---------------------------------------------------------------- # Array-Like / EA-Interface Methods @@ -559,7 +563,7 @@ def __iter__(self): for i in range(chunks): start_i = i * chunksize end_i = min((i + 1) * chunksize, length) - converted = tslib.ints_to_pydatetime( + converted = ints_to_pydatetime( data[start_i:end_i], tz=self.tz, freq=self.freq, box="timestamp" ) for v in converted: @@ -991,7 +995,7 @@ def to_pydatetime(self) -> np.ndarray: ------- datetimes : ndarray """ - return tslib.ints_to_pydatetime(self.asi8, tz=self.tz) + return ints_to_pydatetime(self.asi8, tz=self.tz) def normalize(self): """ @@ -1031,7 +1035,7 @@ def normalize(self): '2014-08-01 00:00:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq=None) """ - new_values = conversion.normalize_i8_timestamps(self.asi8, self.tz) + new_values = normalize_i8_timestamps(self.asi8, self.tz) return type(self)(new_values)._with_freq("infer").tz_localize(self.tz) def to_period(self, freq=None): @@ -1219,7 +1223,7 @@ def time(self): else: timestamps = self.asi8 - return tslib.ints_to_pydatetime(timestamps, box="time") + return ints_to_pydatetime(timestamps, box="time") @property def timetz(self): @@ -1227,7 +1231,7 @@ def timetz(self): Returns numpy array of datetime.time also containing timezone information. The time part of the Timestamps. """ - return tslib.ints_to_pydatetime(self.asi8, self.tz, box="time") + return ints_to_pydatetime(self.asi8, self.tz, box="time") @property def date(self): @@ -1243,7 +1247,7 @@ def date(self): else: timestamps = self.asi8 - return tslib.ints_to_pydatetime(timestamps, box="date") + return ints_to_pydatetime(timestamps, box="date") def isocalendar(self): """ diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 4b4df3445be4e..b336371655466 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -10,6 +10,7 @@ NaTType, Timedelta, delta_to_nanoseconds, + dt64arr_to_periodarr as c_dt64arr_to_periodarr, iNaT, period as libperiod, to_offset, @@ -951,7 +952,7 @@ def dt64arr_to_periodarr(data, freq, tz=None): data = data._values base = freq._period_dtype_code - return libperiod.dt64arr_to_periodarr(data.view("i8"), base, tz), freq + return c_dt64arr_to_periodarr(data.view("i8"), base, tz), freq def _get_ordinal_range(start, end, periods, freq, mult=1): diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index d0417d51da497..6b84f0e81f48b 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -15,6 +15,7 @@ Timedelta, Timestamp, iNaT, + ints_to_pydatetime, ) from pandas._libs.tslibs.timezones import tz_compare from pandas._typing import ArrayLike, Dtype, DtypeObj @@ -919,7 +920,7 @@ def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False): elif is_datetime64_dtype(arr): if is_object_dtype(dtype): - return tslib.ints_to_pydatetime(arr.view(np.int64)) + return ints_to_pydatetime(arr.view(np.int64)) elif dtype == np.int64: if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") @@ -1399,7 +1400,7 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"): if value.dtype != DT64NS_DTYPE: value = value.astype(DT64NS_DTYPE) ints = np.asarray(value).view("i8") - return tslib.ints_to_pydatetime(ints) + return ints_to_pydatetime(ints) # we have a non-castable dtype that was passed raise TypeError(f"Cannot cast datetime64 to {dtype}") diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 0317d0b93859b..6d2e592f024ed 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -5,8 +5,14 @@ import numpy as np -from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib -from pandas._libs.tslibs import Resolution, parsing, timezones, to_offset +from pandas._libs import NaT, Period, Timestamp, index as libindex, lib +from pandas._libs.tslibs import ( + Resolution, + ints_to_pydatetime, + parsing, + timezones, + to_offset, +) from pandas._libs.tslibs.offsets import prefix_mapping from pandas._typing import DtypeObj, Label from pandas.errors import InvalidIndexError @@ -339,7 +345,7 @@ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: def _mpl_repr(self): # how to represent ourselves to matplotlib - return tslib.ints_to_pydatetime(self.asi8, self.tz) + return ints_to_pydatetime(self.asi8, self.tz) @property def _formatter_func(self): diff --git a/pandas/tests/tslibs/test_api.py b/pandas/tests/tslibs/test_api.py index 840a8c2fb68b1..957706fcb460e 100644 --- a/pandas/tests/tslibs/test_api.py +++ b/pandas/tests/tslibs/test_api.py @@ -18,6 +18,7 @@ def test_namespace(): "period", "resolution", "strptime", + "vectorized", "timedeltas", "timestamps", "timezones", @@ -37,7 +38,12 @@ def test_namespace(): "Resolution", "Tick", "Timedelta", + "dt64arr_to_periodarr", "Timestamp", + "is_date_array_normalized", + "ints_to_pydatetime", + "normalize_i8_timestamps", + "get_resolution", "delta_to_nanoseconds", "ints_to_pytimedelta", "localize_pydatetime", diff --git a/setup.py b/setup.py index e9d305d831653..1885546e001fe 100755 --- a/setup.py +++ b/setup.py @@ -322,6 +322,7 @@ class CheckSDist(sdist_class): "pandas/_libs/tslibs/resolution.pyx", "pandas/_libs/tslibs/parsing.pyx", "pandas/_libs/tslibs/tzconversion.pyx", + "pandas/_libs/tslibs/vectorized.pyx", "pandas/_libs/window/indexers.pyx", "pandas/_libs/writers.pyx", "pandas/io/sas/sas.pyx", @@ -659,6 +660,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "pyxfile": "_libs/tslibs/tzconversion", "depends": tseries_depends, }, + "_libs.tslibs.vectorized": {"pyxfile": "_libs/tslibs/vectorized"}, "_libs.testing": {"pyxfile": "_libs/testing"}, "_libs.window.aggregations": { "pyxfile": "_libs/window/aggregations",
I'm open to better names for the new module. With these all in the same place, we can separate out helper functions and de-duplicate a whole bunch of verbose code.
https://api.github.com/repos/pandas-dev/pandas/pulls/35168
2020-07-07T20:22:31Z
2020-07-08T21:50:17Z
2020-07-08T21:50:17Z
2020-07-08T22:06:58Z
CLN: remove unused freq kwarg in libparsing
diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 92654f3b587e5..c4f369d0d3b3f 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -197,7 +197,6 @@ cdef inline bint does_string_look_like_time(str parse_string): def parse_datetime_string( str date_string, - object freq=None, bint dayfirst=False, bint yearfirst=False, **kwargs, @@ -228,7 +227,7 @@ def parse_datetime_string( return dt try: - dt, _ = _parse_dateabbr_string(date_string, _DEFAULT_DATETIME, freq) + dt, _ = _parse_dateabbr_string(date_string, _DEFAULT_DATETIME, freq=None) return dt except DateParseError: raise @@ -265,9 +264,6 @@ def parse_time_string(arg: str, freq=None, dayfirst=None, yearfirst=None): ------- datetime, datetime/dateutil.parser._result, str """ - if not isinstance(arg, str): - raise TypeError("parse_time_string argument must be str") - if is_offset_object(freq): freq = freq.rule_code
https://api.github.com/repos/pandas-dev/pandas/pulls/35167
2020-07-07T20:02:15Z
2020-07-10T22:20:52Z
2020-07-10T22:20:52Z
2020-07-10T23:37:58Z
Fixed Series.apply performance regression
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 9c223d66b727b..d4be660939773 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -291,16 +291,14 @@ def apply_series_generator(self, partial_result=None) -> Tuple[ResType, "Index"] res_index = res_index.take(successes) else: - for i, v in series_gen_enumeration: - - with option_context("mode.chained_assignment", None): + with option_context("mode.chained_assignment", None): + for i, v in series_gen_enumeration: # ignore SettingWithCopy here in case the user mutates results[i] = self.f(v) - - if isinstance(results[i], ABCSeries): - # If we have a view on v, we need to make a copy because - # series_generator will swap out the underlying data - results[i] = results[i].copy(deep=False) + if isinstance(results[i], ABCSeries): + # If we have a view on v, we need to make a copy because + # series_generator will swap out the underlying data + results[i] = results[i].copy(deep=False) return results, res_index
Set the option once, rather than in the loop. Closes https://github.com/pandas-dev/pandas/issues/35047 ```python import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(1000, 3), columns=list("ABC")) %timeit df.apply(lambda x: x["A"] + x["B"], axis=1) ``` ``` # 1.0.4 22.5 ms ± 4.73 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) # PR 10.4 ms ± 714 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/35166
2020-07-07T19:38:58Z
2020-07-08T12:40:46Z
2020-07-08T12:40:46Z
2020-07-08T12:40:56Z
Fixed apply_index
diff --git a/doc/source/reference/offset_frequency.rst b/doc/source/reference/offset_frequency.rst index 1b63253cde2c5..e6271a7806706 100644 --- a/doc/source/reference/offset_frequency.rst +++ b/doc/source/reference/offset_frequency.rst @@ -33,6 +33,7 @@ Methods :toctree: api/ DateOffset.apply + DateOffset.apply_index DateOffset.copy DateOffset.isAnchored DateOffset.onOffset @@ -117,6 +118,7 @@ Methods :toctree: api/ BusinessHour.apply + BusinessHour.apply_index BusinessHour.copy BusinessHour.isAnchored BusinessHour.onOffset @@ -201,6 +203,7 @@ Methods :toctree: api/ CustomBusinessHour.apply + CustomBusinessHour.apply_index CustomBusinessHour.copy CustomBusinessHour.isAnchored CustomBusinessHour.onOffset @@ -401,6 +404,7 @@ Methods :toctree: api/ CustomBusinessMonthEnd.apply + CustomBusinessMonthEnd.apply_index CustomBusinessMonthEnd.copy CustomBusinessMonthEnd.isAnchored CustomBusinessMonthEnd.onOffset @@ -447,6 +451,7 @@ Methods :toctree: api/ CustomBusinessMonthBegin.apply + CustomBusinessMonthBegin.apply_index CustomBusinessMonthBegin.copy CustomBusinessMonthBegin.isAnchored CustomBusinessMonthBegin.onOffset @@ -586,6 +591,7 @@ Methods :toctree: api/ WeekOfMonth.apply + WeekOfMonth.apply_index WeekOfMonth.copy WeekOfMonth.isAnchored WeekOfMonth.onOffset @@ -622,6 +628,7 @@ Methods :toctree: api/ LastWeekOfMonth.apply + LastWeekOfMonth.apply_index LastWeekOfMonth.copy LastWeekOfMonth.isAnchored LastWeekOfMonth.onOffset @@ -938,6 +945,7 @@ Methods :toctree: api/ FY5253.apply + FY5253.apply_index FY5253.copy FY5253.get_rule_code_suffix FY5253.get_year_end @@ -977,6 +985,7 @@ Methods :toctree: api/ FY5253Quarter.apply + FY5253Quarter.apply_index FY5253Quarter.copy FY5253Quarter.get_rule_code_suffix FY5253Quarter.get_weeks @@ -1013,6 +1022,7 @@ Methods :toctree: api/ Easter.apply + Easter.apply_index Easter.copy Easter.isAnchored Easter.onOffset @@ -1053,6 +1063,7 @@ Methods Tick.is_on_offset Tick.__call__ Tick.apply + Tick.apply_index Day --- @@ -1087,6 +1098,7 @@ Methods Day.is_on_offset Day.__call__ Day.apply + Day.apply_index Hour ---- @@ -1121,6 +1133,7 @@ Methods Hour.is_on_offset Hour.__call__ Hour.apply + Hour.apply_index Minute ------ @@ -1155,6 +1168,7 @@ Methods Minute.is_on_offset Minute.__call__ Minute.apply + Minute.apply_index Second ------ @@ -1189,6 +1203,7 @@ Methods Second.is_on_offset Second.__call__ Second.apply + Second.apply_index Milli ----- @@ -1223,6 +1238,7 @@ Methods Milli.is_on_offset Milli.__call__ Milli.apply + Milli.apply_index Micro ----- @@ -1257,6 +1273,7 @@ Methods Micro.is_on_offset Micro.__call__ Micro.apply + Micro.apply_index Nano ---- @@ -1291,6 +1308,7 @@ Methods Nano.is_on_offset Nano.__call__ Nano.apply + Nano.apply_index .. _api.frequencies: diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 088f1d1946fa9..895c38e718859 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -795,6 +795,7 @@ Deprecations - :meth:`DatetimeIndex.week` and `DatetimeIndex.weekofyear` are deprecated and will be removed in a future version, use :meth:`DatetimeIndex.isocalendar().week` instead (:issue:`33595`) - :meth:`DatetimeArray.week` and `DatetimeArray.weekofyear` are deprecated and will be removed in a future version, use :meth:`DatetimeArray.isocalendar().week` instead (:issue:`33595`) - :meth:`DateOffset.__call__` is deprecated and will be removed in a future version, use ``offset + other`` instead (:issue:`34171`) +- :meth:`~BusinessDay.apply_index` is deprecated and will be removed in a future version. Use ``offset + other`` instead (:issue:`34580`) - :meth:`DataFrame.tshift` and :meth:`Series.tshift` are deprecated and will be removed in a future version, use :meth:`DataFrame.shift` and :meth:`Series.shift` instead (:issue:`11631`) - Indexing an :class:`Index` object with a float key is deprecated, and will raise an ``IndexError`` in the future. You can manually convert to an integer key diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index b0c6648514e99..9a7ca15a2a1c2 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -86,19 +86,38 @@ cdef bint _is_normalized(datetime dt): return True +def apply_wrapper_core(func, self, other) -> ndarray: + result = func(self, other) + result = np.asarray(result) + + if self.normalize: + # TODO: Avoid circular/runtime import + from .vectorized import normalize_i8_timestamps + result = normalize_i8_timestamps(result.view("i8"), None) + + return result + + def apply_index_wraps(func): # Note: normally we would use `@functools.wraps(func)`, but this does # not play nicely with cython class methods - def wrapper(self, other) -> np.ndarray: + def wrapper(self, other): # other is a DatetimeArray + result = apply_wrapper_core(func, self, other) + result = type(other)(result) + warnings.warn("'Offset.apply_index(other)' is deprecated. " + "Use 'offset + other' instead.", FutureWarning) + return result - result = func(self, other) - result = np.asarray(result) + return wrapper - if self.normalize: - # TODO: Avoid circular/runtime import - from .vectorized import normalize_i8_timestamps - result = normalize_i8_timestamps(result.view("i8"), None) + +def apply_array_wraps(func): + # Note: normally we would use `@functools.wraps(func)`, but this does + # not play nicely with cython class methods + def wrapper(self, other) -> np.ndarray: + # other is a DatetimeArray + result = apply_wrapper_core(func, self, other) return result # do @functools.wraps(func) manually since it doesn't work on cdef funcs @@ -515,6 +534,10 @@ cdef class BaseOffset: raises NotImplementedError for offsets without a vectorized implementation. + .. deprecated:: 1.1.0 + + Use ``offset + dtindex`` instead. + Parameters ---------- index : DatetimeIndex @@ -522,12 +545,25 @@ cdef class BaseOffset: Returns ------- DatetimeIndex + + Raises + ------ + NotImplementedError + When the specific offset subclass does not have a vectorized + implementation. """ raise NotImplementedError( f"DateOffset subclass {type(self).__name__} " "does not have a vectorized implementation" ) + @apply_array_wraps + def _apply_array(self, dtarr): + raise NotImplementedError( + f"DateOffset subclass {type(self).__name__} " + "does not have a vectorized implementation" + ) + def rollback(self, dt) -> datetime: """ Roll provided date backward to next offset only if not on offset. @@ -992,7 +1028,11 @@ cdef class RelativeDeltaOffset(BaseOffset): ------- ndarray[datetime64[ns]] """ - dt64other = np.asarray(dtindex) + return self._apply_array(dtindex) + + @apply_array_wraps + def _apply_array(self, dtarr): + dt64other = np.asarray(dtarr) kwds = self.kwds relativedelta_fast = { "years", @@ -1321,7 +1361,11 @@ cdef class BusinessDay(BusinessMixin): @apply_index_wraps def apply_index(self, dtindex): - i8other = dtindex.view("i8") + return self._apply_array(dtindex) + + @apply_array_wraps + def _apply_array(self, dtarr): + i8other = dtarr.view("i8") return shift_bdays(i8other, self.n) def is_on_offset(self, dt: datetime) -> bool: @@ -1804,8 +1848,12 @@ cdef class YearOffset(SingleConstructorOffset): @apply_index_wraps def apply_index(self, dtindex): + return self._apply_array(dtindex) + + @apply_array_wraps + def _apply_array(self, dtarr): shifted = shift_quarters( - dtindex.view("i8"), self.n, self.month, self._day_opt, modby=12 + dtarr.view("i8"), self.n, self.month, self._day_opt, modby=12 ) return shifted @@ -1957,8 +2005,12 @@ cdef class QuarterOffset(SingleConstructorOffset): @apply_index_wraps def apply_index(self, dtindex): + return self._apply_array(dtindex) + + @apply_array_wraps + def _apply_array(self, dtarr): shifted = shift_quarters( - dtindex.view("i8"), self.n, self.startingMonth, self._day_opt + dtarr.view("i8"), self.n, self.startingMonth, self._day_opt ) return shifted @@ -2072,7 +2124,11 @@ cdef class MonthOffset(SingleConstructorOffset): @apply_index_wraps def apply_index(self, dtindex): - shifted = shift_months(dtindex.view("i8"), self.n, self._day_opt) + return self._apply_array(dtindex) + + @apply_array_wraps + def _apply_array(self, dtarr): + shifted = shift_months(dtarr.view("i8"), self.n, self._day_opt) return shifted cpdef __setstate__(self, state): @@ -2209,8 +2265,14 @@ cdef class SemiMonthOffset(SingleConstructorOffset): @cython.wraparound(False) @cython.boundscheck(False) def apply_index(self, dtindex): + return self._apply_array(dtindex) + + @apply_array_wraps + @cython.wraparound(False) + @cython.boundscheck(False) + def _apply_array(self, dtarr): cdef: - int64_t[:] i8other = dtindex.view("i8") + int64_t[:] i8other = dtarr.view("i8") Py_ssize_t i, count = len(i8other) int64_t val int64_t[:] out = np.empty(count, dtype="i8") @@ -2368,12 +2430,16 @@ cdef class Week(SingleConstructorOffset): @apply_index_wraps def apply_index(self, dtindex): + return self._apply_array(dtindex) + + @apply_array_wraps + def _apply_array(self, dtarr): if self.weekday is None: td = timedelta(days=7 * self.n) td64 = np.timedelta64(td, "ns") - return dtindex + td64 + return dtarr + td64 else: - i8other = dtindex.view("i8") + i8other = dtarr.view("i8") return self._end_apply_index(i8other) @cython.wraparound(False) @@ -3146,6 +3212,9 @@ cdef class CustomBusinessDay(BusinessDay): def apply_index(self, dtindex): raise NotImplementedError + def _apply_array(self, dtarr): + raise NotImplementedError + def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_normalized(dt): return False diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 7058ed3682d59..d674b1c476d2c 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -683,7 +683,7 @@ def _add_offset(self, offset): values = self.tz_localize(None) else: values = self - result = offset.apply_index(values) + result = offset._apply_array(values) result = DatetimeArray._simple_new(result) result = result.tz_localize(self.tz) diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index cffaa7b43d0cf..8c51908c547f4 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -3663,14 +3663,19 @@ def test_offset(self, case): @pytest.mark.parametrize("case", offset_cases) def test_apply_index(self, case): + # https://github.com/pandas-dev/pandas/issues/34580 offset, cases = case s = DatetimeIndex(cases.keys()) + exp = DatetimeIndex(cases.values()) + with tm.assert_produces_warning(None): # GH#22535 check that we don't get a FutureWarning from adding # an integer array to PeriodIndex result = offset + s + tm.assert_index_equal(result, exp) - exp = DatetimeIndex(cases.values()) + with tm.assert_produces_warning(FutureWarning): + result = offset.apply_index(s) tm.assert_index_equal(result, exp) on_offset_cases = [
Closes https://github.com/pandas-dev/pandas/issues/34580
https://api.github.com/repos/pandas-dev/pandas/pulls/35165
2020-07-07T19:00:14Z
2020-07-15T12:25:34Z
2020-07-15T12:25:34Z
2020-07-15T12:25:37Z
Infer compression if file extension is uppercase
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 798a3d838ef7e..3976696ecdd06 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1053,6 +1053,7 @@ I/O - Bug in :meth:`~HDFStore.create_table` now raises an error when `column` argument was not specified in `data_columns` on input (:issue:`28156`) - :meth:`read_json` now could read line-delimited json file from a file url while `lines` and `chunksize` are set. - Bug in :meth:`DataFrame.to_sql` when reading DataFrames with ``-np.inf`` entries with MySQL now has a more explicit ``ValueError`` (:issue:`34431`) +- Bug where capitalised files extensions were not decompressed by read_* functions (:issue:`35164`) - Bug in :meth:`read_excel` that was raising a ``TypeError`` when ``header=None`` and ``index_col`` given as list (:issue:`31783`) - Bug in "meth"`read_excel` where datetime values are used in the header in a `MultiIndex` (:issue:`34748`) diff --git a/pandas/io/common.py b/pandas/io/common.py index 51323c5ff3ef5..4e6395fc67b2a 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -311,7 +311,7 @@ def infer_compression( # Infer compression from the filename/URL extension for compression, extension in _compression_to_extension.items(): - if filepath_or_buffer.endswith(extension): + if filepath_or_buffer.lower().endswith(extension): return compression return None diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index e2f4ae04c1f9f..dde38eb55ea7f 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -87,7 +87,17 @@ def test_stringify_path_fspath(self): @pytest.mark.parametrize( "extension,expected", - [("", None), (".gz", "gzip"), (".bz2", "bz2"), (".zip", "zip"), (".xz", "xz")], + [ + ("", None), + (".gz", "gzip"), + (".bz2", "bz2"), + (".zip", "zip"), + (".xz", "xz"), + (".GZ", "gzip"), + (".BZ2", "bz2"), + (".ZIP", "zip"), + (".XZ", "xz"), + ], ) @pytest.mark.parametrize("path_type", path_types) def test_infer_compression_from_path(self, extension, expected, path_type):
Inferring compression fails for files with uppercase extensions (e.g. `x.zip` works but `y.ZIP` does not) - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35164
2020-07-07T18:06:02Z
2020-07-17T10:58:30Z
2020-07-17T10:58:30Z
2020-07-17T10:58:39Z
CI: update to isort 5 (#35134)
diff --git a/asv_bench/benchmarks/arithmetic.py b/asv_bench/benchmarks/arithmetic.py index 3ef6ab6209ea7..708f9be5846b4 100644 --- a/asv_bench/benchmarks/arithmetic.py +++ b/asv_bench/benchmarks/arithmetic.py @@ -4,16 +4,22 @@ import numpy as np import pandas as pd -from pandas import DataFrame, Series, Timestamp, date_range, to_timedelta -import pandas._testing as tm +from pandas import ( + DataFrame, + Series, + Timestamp, + _testing as tm, + date_range, + to_timedelta, +) from pandas.core.algorithms import checked_add_with_arr from .pandas_vb_common import numeric_dtypes try: - import pandas.core.computation.expressions as expr + from pandas.core.computation import expressions as expr except ImportError: - import pandas.computation.expressions as expr + from pandas.computation import expressions as expr try: import pandas.tseries.holiday except ImportError: diff --git a/asv_bench/benchmarks/eval.py b/asv_bench/benchmarks/eval.py index cbab9fdc9c0ba..07ecfabb3b453 100644 --- a/asv_bench/benchmarks/eval.py +++ b/asv_bench/benchmarks/eval.py @@ -3,9 +3,9 @@ import pandas as pd try: - import pandas.core.computation.expressions as expr + from pandas.core.computation import expressions as expr except ImportError: - import pandas.computation.expressions as expr + from pandas.computation import expressions as expr class Eval: diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py index dc6f45f810f3d..e0a2257b0ca1f 100644 --- a/asv_bench/benchmarks/frame_ctor.py +++ b/asv_bench/benchmarks/frame_ctor.py @@ -6,7 +6,7 @@ from .pandas_vb_common import tm try: - from pandas.tseries.offsets import Nano, Hour + from pandas.tseries.offsets import Hour, Nano except ImportError: # For compatibility with older versions from pandas.core.datetools import * # noqa diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py index e266d871f5bc6..5d9070de92ec7 100644 --- a/asv_bench/benchmarks/gil.py +++ b/asv_bench/benchmarks/gil.py @@ -7,14 +7,14 @@ try: from pandas import ( - rolling_median, + rolling_kurt, + rolling_max, rolling_mean, + rolling_median, rolling_min, - rolling_max, - rolling_var, rolling_skew, - rolling_kurt, rolling_std, + rolling_var, ) have_rolling_methods = True diff --git a/asv_bench/benchmarks/io/parsers.py b/asv_bench/benchmarks/io/parsers.py index ec3eddfff7184..5390056ba36f2 100644 --- a/asv_bench/benchmarks/io/parsers.py +++ b/asv_bench/benchmarks/io/parsers.py @@ -2,8 +2,8 @@ try: from pandas._libs.tslibs.parsing import ( - concat_date_cols, _does_string_look_like_datetime, + concat_date_cols, ) except ImportError: # Avoid whole benchmark suite import failure on asv (currently 0.4) diff --git a/asv_bench/benchmarks/pandas_vb_common.py b/asv_bench/benchmarks/pandas_vb_common.py index 23286343d7367..5ee3fdcdbb34b 100644 --- a/asv_bench/benchmarks/pandas_vb_common.py +++ b/asv_bench/benchmarks/pandas_vb_common.py @@ -15,9 +15,9 @@ # Compatibility import for the testing module try: - import pandas._testing as tm # noqa + from pandas import _testing as tm # noqa except ImportError: - import pandas.util.testing as tm # noqa + from pandas.util import testing as tm # noqa numeric_dtypes = [ diff --git a/asv_bench/benchmarks/tslibs/normalize.py b/asv_bench/benchmarks/tslibs/normalize.py index 7d4e0556f4d96..9a206410d8775 100644 --- a/asv_bench/benchmarks/tslibs/normalize.py +++ b/asv_bench/benchmarks/tslibs/normalize.py @@ -1,5 +1,5 @@ try: - from pandas._libs.tslibs import normalize_i8_timestamps, is_date_array_normalized + from pandas._libs.tslibs import is_date_array_normalized, normalize_i8_timestamps except ImportError: from pandas._libs.tslibs.conversion import ( normalize_i8_timestamps, diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 7b12de387d648..69ce0f1adce22 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -121,7 +121,7 @@ if [[ -z "$CHECK" || "$CHECK" == "lint" ]]; then # Imports - Check formatting using isort see setup.cfg for settings MSG='Check import format using isort' ; echo $MSG - ISORT_CMD="isort --quiet --recursive --check-only pandas asv_bench scripts" + ISORT_CMD="isort --quiet --check-only pandas asv_bench scripts" if [[ "$GITHUB_ACTIONS" == "true" ]]; then eval $ISORT_CMD | awk '{print "##[error]" $0}'; RET=$(($RET + ${PIPESTATUS[0]})) else diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index b85e9403038ab..3eed25cfdfb7f 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -751,7 +751,7 @@ Imports are alphabetically sorted within these sections. As part of :ref:`Continuous Integration <contributing.ci>` checks we run:: - isort --recursive --check-only pandas + isort --check-only pandas to check that imports are correctly formatted as per the `setup.cfg`. diff --git a/environment.yml b/environment.yml index 53106906a52cb..5149ff28e60d9 100644 --- a/environment.yml +++ b/environment.yml @@ -21,7 +21,7 @@ dependencies: - flake8<3.8.0 # temporary pin, GH#34150 - flake8-comprehensions>=3.1.0 # used by flake8, linting of unnecessary comprehensions - flake8-rst>=0.6.0,<=0.7.0 # linting of code blocks in rst files - - isort=4.3.21 # check that imports are in the right order + - isort=5.1.1 # check that imports are in the right order - mypy=0.730 - pycodestyle # used by flake8 diff --git a/pandas/_config/config.py b/pandas/_config/config.py index f5e16cddeb04c..b476a518790c9 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -47,7 +47,6 @@ which can save developers some typing, see the docstring. """ - from collections import namedtuple from contextlib import ContextDecorator, contextmanager import re @@ -442,8 +441,8 @@ def register_option( ValueError if `validator` is specified and `defval` is not a valid value. """ - import tokenize import keyword + import tokenize key = key.lower() @@ -660,8 +659,8 @@ def _build_option_description(k: str) -> str: def pp_options_list(keys: Iterable[str], width=80, _print: bool = False): """ Builds a concise listing of available options, grouped by prefix """ - from textwrap import wrap from itertools import groupby + from textwrap import wrap def pp(name: str, ks: Iterable[str]) -> List[str]: pfx = "- " + name + ".[" if name else "" diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index 6b6ead795584f..4db14114c716d 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -1,11 +1,12 @@ import cython from cython import Py_ssize_t -from libc.stdlib cimport malloc, free -from libc.string cimport memmove from libc.math cimport fabs, sqrt +from libc.stdlib cimport free, malloc +from libc.string cimport memmove import numpy as np + cimport numpy as cnp from numpy cimport ( NPY_FLOAT32, @@ -31,12 +32,11 @@ from numpy cimport ( uint32_t, uint64_t, ) -cnp.import_array() +cnp.import_array() -cimport pandas._libs.util as util -from pandas._libs.util cimport numeric, get_nat +from pandas._libs cimport util as util from pandas._libs.khash cimport ( kh_destroy_int64, kh_get_int64, @@ -46,9 +46,9 @@ from pandas._libs.khash cimport ( kh_resize_int64, khiter_t, ) +from pandas._libs.util cimport get_nat, numeric - -import pandas._libs.missing as missing +from pandas._libs import missing as missing cdef: float64_t FP_ERR = 1e-13 diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 7c57e6ee9dbfd..38cb973d6dde9 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -1,27 +1,51 @@ import cython from cython import Py_ssize_t -from cython cimport floating -from libc.stdlib cimport malloc, free +from cython cimport floating +from libc.stdlib cimport free, malloc import numpy as np + cimport numpy as cnp -from numpy cimport (ndarray, - int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, - uint32_t, uint64_t, float32_t, float64_t, complex64_t, complex128_t) +from numpy cimport ( + complex64_t, + complex128_t, + float32_t, + float64_t, + int8_t, + int16_t, + int32_t, + int64_t, + ndarray, + uint8_t, + uint16_t, + uint32_t, + uint64_t, +) from numpy.math cimport NAN -cnp.import_array() -from pandas._libs.util cimport numeric, get_nat +cnp.import_array() -from pandas._libs.algos cimport (swap, TiebreakEnumType, TIEBREAK_AVERAGE, - TIEBREAK_MIN, TIEBREAK_MAX, TIEBREAK_FIRST, - TIEBREAK_DENSE) -from pandas._libs.algos import (take_2d_axis1_float64_float64, - groupsort_indexer, tiebreakers) +from pandas._libs.algos cimport ( + TIEBREAK_AVERAGE, + TIEBREAK_DENSE, + TIEBREAK_FIRST, + TIEBREAK_MAX, + TIEBREAK_MIN, + TiebreakEnumType, + swap, +) +from pandas._libs.util cimport get_nat, numeric + +from pandas._libs.algos import ( + groupsort_indexer, + take_2d_axis1_float64_float64, + tiebreakers, +) from pandas._libs.missing cimport checknull + cdef int64_t NPY_NAT = get_nat() _int64_max = np.iinfo(np.int64).max diff --git a/pandas/_libs/hashing.pyx b/pandas/_libs/hashing.pyx index a98820ca57895..614a8da787b2a 100644 --- a/pandas/_libs/hashing.pyx +++ b/pandas/_libs/hashing.pyx @@ -1,11 +1,13 @@ # Translated from the reference implementation # at https://github.com/veorq/SipHash - import cython -from libc.stdlib cimport malloc, free + +from libc.stdlib cimport free, malloc import numpy as np -from numpy cimport ndarray, uint8_t, uint32_t, uint64_t, import_array + +from numpy cimport import_array, ndarray, uint8_t, uint32_t, uint64_t + import_array() from pandas._libs.util cimport is_nan diff --git a/pandas/_libs/hashtable.pyx b/pandas/_libs/hashtable.pyx index c3dcbb942d7fe..ffaf6d6505955 100644 --- a/pandas/_libs/hashtable.pyx +++ b/pandas/_libs/hashtable.pyx @@ -1,60 +1,57 @@ cimport cython - -from cpython.ref cimport PyObject, Py_INCREF -from cpython.mem cimport PyMem_Malloc, PyMem_Free - -from libc.stdlib cimport malloc, free +from cpython.mem cimport PyMem_Free, PyMem_Malloc +from cpython.ref cimport Py_INCREF, PyObject +from libc.stdlib cimport free, malloc import numpy as np + cimport numpy as cnp -from numpy cimport ndarray, uint8_t, uint32_t, float64_t +from numpy cimport float64_t, ndarray, uint8_t, uint32_t from numpy.math cimport NAN + cnp.import_array() +from pandas._libs cimport util from pandas._libs.khash cimport ( - khiter_t, - kh_str_t, - kh_init_str, - kh_put_str, - kh_exist_str, - kh_get_str, - kh_destroy_str, - kh_resize_str, - kh_put_strbox, - kh_get_strbox, - kh_init_strbox, - kh_int64_t, - kh_init_int64, - kh_resize_int64, + kh_destroy_float64, kh_destroy_int64, - kh_get_int64, + kh_destroy_pymap, + kh_destroy_str, + kh_destroy_uint64, + kh_exist_float64, kh_exist_int64, - kh_put_int64, + kh_exist_pymap, + kh_exist_str, + kh_exist_uint64, kh_float64_t, - kh_exist_float64, - kh_put_float64, - kh_init_float64, kh_get_float64, - kh_destroy_float64, - kh_resize_float64, - kh_resize_uint64, - kh_exist_uint64, - kh_destroy_uint64, - kh_put_uint64, + kh_get_int64, + kh_get_pymap, + kh_get_str, + kh_get_strbox, kh_get_uint64, - kh_init_uint64, - kh_destroy_pymap, - kh_exist_pymap, + kh_init_float64, + kh_init_int64, kh_init_pymap, - kh_get_pymap, + kh_init_str, + kh_init_strbox, + kh_init_uint64, + kh_int64_t, + kh_put_float64, + kh_put_int64, kh_put_pymap, + kh_put_str, + kh_put_strbox, + kh_put_uint64, + kh_resize_float64, + kh_resize_int64, kh_resize_pymap, + kh_resize_str, + kh_resize_uint64, + kh_str_t, + khiter_t, ) - - -from pandas._libs cimport util - from pandas._libs.missing cimport checknull diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 35c4b73b47695..d6659cc1895b1 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -1,6 +1,7 @@ import warnings import numpy as np + cimport numpy as cnp from numpy cimport ( float32_t, @@ -16,17 +17,16 @@ from numpy cimport ( uint32_t, uint64_t, ) + cnp.import_array() from pandas._libs cimport util - +from pandas._libs.hashtable cimport HashTable from pandas._libs.tslibs.nattype cimport c_NaT as NaT from pandas._libs.tslibs.period cimport is_period_object -from pandas._libs.tslibs.timestamps cimport _Timestamp from pandas._libs.tslibs.timedeltas cimport _Timedelta - -from pandas._libs.hashtable cimport HashTable +from pandas._libs.tslibs.timestamps cimport _Timestamp from pandas._libs import algos, hashtable as _hash from pandas._libs.missing import checknull diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx index 8b4b490f49b12..4f27fde52414a 100644 --- a/pandas/_libs/internals.pyx +++ b/pandas/_libs/internals.pyx @@ -5,12 +5,15 @@ from cython import Py_ssize_t from cpython.slice cimport PySlice_GetIndicesEx + cdef extern from "Python.h": Py_ssize_t PY_SSIZE_T_MAX import numpy as np + cimport numpy as cnp from numpy cimport NPY_INT64, int64_t + cnp.import_array() from pandas._libs.algos import ensure_int64 diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index 95881ebf1385c..6867e8aba7411 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -1,7 +1,8 @@ import numbers from operator import le, lt -from cpython.datetime cimport PyDelta_Check, PyDateTime_IMPORT +from cpython.datetime cimport PyDateTime_IMPORT, PyDelta_Check + PyDateTime_IMPORT from cpython.object cimport ( @@ -16,8 +17,8 @@ from cpython.object cimport ( import cython from cython import Py_ssize_t - import numpy as np + cimport numpy as cnp from numpy cimport ( NPY_QUICKSORT, @@ -30,22 +31,21 @@ from numpy cimport ( ndarray, uint64_t, ) + cnp.import_array() from pandas._libs cimport util - from pandas._libs.hashtable cimport Int64Vector +from pandas._libs.tslibs.timedeltas cimport _Timedelta +from pandas._libs.tslibs.timestamps cimport _Timestamp +from pandas._libs.tslibs.timezones cimport tz_compare from pandas._libs.tslibs.util cimport ( - is_integer_object, is_float_object, + is_integer_object, is_timedelta64_object, ) -from pandas._libs.tslibs.timezones cimport tz_compare -from pandas._libs.tslibs.timestamps cimport _Timestamp -from pandas._libs.tslibs.timedeltas cimport _Timedelta - _VALID_CLOSED = frozenset(['left', 'right', 'both', 'neither']) diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx index 54892a7e4bc77..13c7187923473 100644 --- a/pandas/_libs/join.pyx +++ b/pandas/_libs/join.pyx @@ -1,7 +1,7 @@ import cython from cython import Py_ssize_t - import numpy as np + cimport numpy as cnp from numpy cimport ( float32_t, @@ -16,6 +16,7 @@ from numpy cimport ( uint32_t, uint64_t, ) + cnp.import_array() from pandas._libs.algos import ( @@ -640,7 +641,11 @@ def outer_join_indexer(ndarray[join_t] left, ndarray[join_t] right): # ---------------------------------------------------------------------- from pandas._libs.hashtable cimport ( - HashTable, PyObjectHashTable, UInt64HashTable, Int64HashTable) + HashTable, + Int64HashTable, + PyObjectHashTable, + UInt64HashTable, +) ctypedef fused asof_t: uint8_t diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 5ecbb2c3ffd35..5fa91ffee8ea8 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -5,23 +5,24 @@ import warnings import cython from cython import Py_ssize_t -from cpython.object cimport PyObject_RichCompareBool, Py_EQ -from cpython.ref cimport Py_INCREF -from cpython.tuple cimport PyTuple_SET_ITEM, PyTuple_New -from cpython.iterator cimport PyIter_Check -from cpython.sequence cimport PySequence_Check -from cpython.number cimport PyNumber_Check - from cpython.datetime cimport ( - PyDateTime_Check, PyDate_Check, - PyTime_Check, - PyDelta_Check, + PyDateTime_Check, PyDateTime_IMPORT, + PyDelta_Check, + PyTime_Check, ) +from cpython.iterator cimport PyIter_Check +from cpython.number cimport PyNumber_Check +from cpython.object cimport Py_EQ, PyObject_RichCompareBool +from cpython.ref cimport Py_INCREF +from cpython.sequence cimport PySequence_Check +from cpython.tuple cimport PyTuple_New, PyTuple_SET_ITEM + PyDateTime_IMPORT import numpy as np + cimport numpy as cnp from numpy cimport ( NPY_OBJECT, @@ -39,6 +40,7 @@ from numpy cimport ( uint8_t, uint64_t, ) + cnp.import_array() cdef extern from "numpy/arrayobject.h": @@ -63,28 +65,23 @@ cdef extern from "src/parse_helper.h": int floatify(object, float64_t *result, int *maybe_int) except -1 from pandas._libs cimport util -from pandas._libs.util cimport is_nan, UINT64_MAX, INT64_MAX, INT64_MIN +from pandas._libs.util cimport INT64_MAX, INT64_MIN, UINT64_MAX, is_nan from pandas._libs.tslib import array_to_datetime -from pandas._libs.tslibs.nattype cimport ( - NPY_NAT, - c_NaT as NaT, - checknull_with_nat, -) -from pandas._libs.tslibs.conversion cimport convert_to_tsobject -from pandas._libs.tslibs.timedeltas cimport convert_to_timedelta64 -from pandas._libs.tslibs.timezones cimport tz_compare -from pandas._libs.tslibs.period cimport is_period_object -from pandas._libs.tslibs.offsets cimport is_offset_object from pandas._libs.missing cimport ( + C_NA, checknull, - isnaobj, is_null_datetime64, is_null_timedelta64, - C_NA, + isnaobj, ) - +from pandas._libs.tslibs.conversion cimport convert_to_tsobject +from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT, checknull_with_nat +from pandas._libs.tslibs.offsets cimport is_offset_object +from pandas._libs.tslibs.period cimport is_period_object +from pandas._libs.tslibs.timedeltas cimport convert_to_timedelta64 +from pandas._libs.tslibs.timezones cimport tz_compare # constants that will be compared to potentially arbitrarily large # python int @@ -1317,8 +1314,7 @@ def infer_dtype(value: object, skipna: bool = True) -> str: if not isinstance(value, list): value = list(value) - from pandas.core.dtypes.cast import ( - construct_1d_object_array_from_listlike) + from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike values = construct_1d_object_array_from_listlike(value) # make contiguous diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index fdd06fe631b97..760fab3781fd4 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -1,27 +1,25 @@ -import cython -from cython import Py_ssize_t - import numbers +import cython +from cython import Py_ssize_t import numpy as np + cimport numpy as cnp -from numpy cimport ndarray, int64_t, uint8_t, float64_t +from numpy cimport float64_t, int64_t, ndarray, uint8_t + cnp.import_array() from pandas._libs cimport util - - -from pandas._libs.tslibs.np_datetime cimport get_datetime64_value, get_timedelta64_value from pandas._libs.tslibs.nattype cimport ( c_NaT as NaT, checknull_with_nat, is_null_datetimelike, ) -from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op +from pandas._libs.tslibs.np_datetime cimport get_datetime64_value, get_timedelta64_value +from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op from pandas.compat import is_platform_32bit - cdef: float64_t INF = <float64_t>np.inf float64_t NEGINF = -INF diff --git a/pandas/_libs/ops.pyx b/pandas/_libs/ops.pyx index 658600cdfbe6c..d1f897d237c1b 100644 --- a/pandas/_libs/ops.pyx +++ b/pandas/_libs/ops.pyx @@ -10,18 +10,17 @@ from cpython.object cimport ( PyObject_RichCompareBool, ) - import cython from cython import Py_ssize_t - import numpy as np -from numpy cimport ndarray, uint8_t, import_array -import_array() +from numpy cimport import_array, ndarray, uint8_t + +import_array() -from pandas._libs.util cimport UINT8_MAX, is_nan from pandas._libs.missing cimport checknull +from pandas._libs.util cimport UINT8_MAX, is_nan @cython.wraparound(False) diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 6ffb036e01595..01c85c95ac6bc 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -1,6 +1,8 @@ # Copyright (c) 2012, Lambda Foundry, Inc. # See LICENSE for the license import bz2 +from csv import QUOTE_MINIMAL, QUOTE_NONE, QUOTE_NONNUMERIC +from errno import ENOENT import gzip import io import os @@ -9,17 +11,14 @@ import time import warnings import zipfile -from csv import QUOTE_MINIMAL, QUOTE_NONNUMERIC, QUOTE_NONE -from errno import ENOENT - from libc.stdlib cimport free -from libc.string cimport strncpy, strlen, strcasecmp +from libc.string cimport strcasecmp, strlen, strncpy import cython from cython import Py_ssize_t from cpython.bytes cimport PyBytes_AsString, PyBytes_FromString -from cpython.exc cimport PyErr_Occurred, PyErr_Fetch +from cpython.exc cimport PyErr_Fetch, PyErr_Occurred from cpython.object cimport PyObject from cpython.ref cimport Py_XDECREF from cpython.unicode cimport PyUnicode_AsUTF8String, PyUnicode_Decode @@ -28,39 +27,60 @@ from cpython.unicode cimport PyUnicode_AsUTF8String, PyUnicode_Decode cdef extern from "Python.h": object PyUnicode_FromString(char *v) - import numpy as np + cimport numpy as cnp -from numpy cimport ndarray, uint8_t, uint64_t, int64_t, float64_t +from numpy cimport float64_t, int64_t, ndarray, uint8_t, uint64_t + cnp.import_array() from pandas._libs cimport util -from pandas._libs.util cimport UINT64_MAX, INT64_MAX, INT64_MIN -import pandas._libs.lib as lib +from pandas._libs.util cimport INT64_MAX, INT64_MIN, UINT64_MAX + +from pandas._libs import lib as lib from pandas._libs.khash cimport ( - khiter_t, - kh_str_t, kh_init_str, kh_put_str, kh_exist_str, - kh_get_str, kh_destroy_str, - kh_float64_t, kh_get_float64, kh_destroy_float64, - kh_put_float64, kh_init_float64, kh_resize_float64, - kh_strbox_t, kh_put_strbox, kh_get_strbox, kh_init_strbox, + kh_destroy_float64, + kh_destroy_str, + kh_destroy_str_starts, kh_destroy_strbox, - kh_str_starts_t, kh_put_str_starts_item, kh_init_str_starts, - kh_get_str_starts_item, kh_destroy_str_starts, kh_resize_str_starts) + kh_exist_str, + kh_float64_t, + kh_get_float64, + kh_get_str, + kh_get_str_starts_item, + kh_get_strbox, + kh_init_float64, + kh_init_str, + kh_init_str_starts, + kh_init_strbox, + kh_put_float64, + kh_put_str, + kh_put_str_starts_item, + kh_put_strbox, + kh_resize_float64, + kh_resize_str_starts, + kh_str_starts_t, + kh_str_t, + kh_strbox_t, + khiter_t, +) + +from pandas.compat import _get_lzma_file, _import_lzma +from pandas.errors import DtypeWarning, EmptyDataError, ParserError, ParserWarning from pandas.core.dtypes.common import ( + is_bool_dtype, is_categorical_dtype, - is_integer_dtype, is_float_dtype, - is_bool_dtype, is_object_dtype, is_datetime64_dtype, - pandas_dtype, is_extension_array_dtype) + is_extension_array_dtype, + is_float_dtype, + is_integer_dtype, + is_object_dtype, + pandas_dtype, +) from pandas.core.dtypes.concat import union_categoricals -from pandas.compat import _import_lzma, _get_lzma_file -from pandas.errors import (ParserError, DtypeWarning, - EmptyDataError, ParserWarning) - lzma = _import_lzma() cdef: diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx index a01e0c5705dcf..7b36bc8baf891 100644 --- a/pandas/_libs/reduction.pyx +++ b/pandas/_libs/reduction.pyx @@ -2,15 +2,18 @@ from copy import copy from cython import Py_ssize_t -from libc.stdlib cimport malloc, free +from libc.stdlib cimport free, malloc import numpy as np + cimport numpy as cnp -from numpy cimport ndarray, int64_t +from numpy cimport int64_t, ndarray + cnp.import_array() from pandas._libs cimport util -from pandas._libs.lib import maybe_convert_objects, is_scalar + +from pandas._libs.lib import is_scalar, maybe_convert_objects cdef _check_result_array(object obj, Py_ssize_t cnt): diff --git a/pandas/_libs/reshape.pyx b/pandas/_libs/reshape.pyx index da4dd00027395..5c6c15fb50fed 100644 --- a/pandas/_libs/reshape.pyx +++ b/pandas/_libs/reshape.pyx @@ -16,7 +16,9 @@ from numpy cimport ( ) import numpy as np + cimport numpy as cnp + cnp.import_array() from pandas._libs.lib cimport c_is_list_like diff --git a/pandas/_libs/sparse.pyx b/pandas/_libs/sparse.pyx index 7c9575d921dc9..321d7c374d8ec 100644 --- a/pandas/_libs/sparse.pyx +++ b/pandas/_libs/sparse.pyx @@ -1,9 +1,18 @@ import cython - import numpy as np + cimport numpy as cnp -from numpy cimport (ndarray, uint8_t, int64_t, int32_t, int16_t, int8_t, - float64_t, float32_t) +from numpy cimport ( + float32_t, + float64_t, + int8_t, + int16_t, + int32_t, + int64_t, + ndarray, + uint8_t, +) + cnp.import_array() diff --git a/pandas/_libs/testing.pyx b/pandas/_libs/testing.pyx index 785a4d1f8b923..64fc8d615ea9c 100644 --- a/pandas/_libs/testing.pyx +++ b/pandas/_libs/testing.pyx @@ -1,13 +1,16 @@ import math import numpy as np + from numpy cimport import_array + import_array() from pandas._libs.util cimport is_array -from pandas.core.dtypes.missing import isna, array_equivalent from pandas.core.dtypes.common import is_dtype_equal +from pandas.core.dtypes.missing import array_equivalent, isna + cdef NUMERIC_TYPES = ( bool, @@ -129,6 +132,7 @@ cpdef assert_almost_equal(a, b, if not isiterable(b): from pandas._testing import assert_class_equal + # classes can't be the same, to raise error assert_class_equal(a, b, obj=obj) @@ -181,6 +185,7 @@ cpdef assert_almost_equal(a, b, elif isiterable(b): from pandas._testing import assert_class_equal + # classes can't be the same, to raise error assert_class_equal(a, b, obj=obj) diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 35d5cd8f1e275..56cca99cba598 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -7,23 +7,20 @@ from cpython.datetime cimport ( datetime, tzinfo, ) + # import datetime C API PyDateTime_IMPORT cimport numpy as cnp from numpy cimport float64_t, int64_t, ndarray + import numpy as np + cnp.import_array() import pytz -from pandas._libs.util cimport ( - is_datetime64_object, - is_float_object, - is_integer_object, -) - from pandas._libs.tslibs.np_datetime cimport ( _string_to_dts, check_dts_bounds, @@ -34,9 +31,9 @@ from pandas._libs.tslibs.np_datetime cimport ( pydate_to_dt64, pydatetime_to_dt64, ) +from pandas._libs.util cimport is_datetime64_object, is_float_object, is_integer_object from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime - from pandas._libs.tslibs.parsing import parse_datetime_string from pandas._libs.tslibs.conversion cimport ( @@ -45,22 +42,19 @@ from pandas._libs.tslibs.conversion cimport ( convert_datetime_to_tsobject, get_datetime64_nanos, ) - from pandas._libs.tslibs.nattype cimport ( NPY_NAT, c_NaT as NaT, c_nat_strings as nat_strings, ) - from pandas._libs.tslibs.timestamps cimport _Timestamp -from pandas._libs.tslibs.timestamps import Timestamp -from pandas._libs.tslibs.tzconversion cimport ( - tz_localize_to_utc_single, -) +from pandas._libs.tslibs.timestamps import Timestamp # Note: this is the only non-tslibs intra-pandas dependency here + from pandas._libs.missing cimport checknull_with_nat_and_na +from pandas._libs.tslibs.tzconversion cimport tz_localize_to_utc_single def _test_parse_iso8601(ts: str): diff --git a/pandas/_libs/tslibs/ccalendar.pyx b/pandas/_libs/tslibs/ccalendar.pyx index 00cecd25e5225..02829d361912a 100644 --- a/pandas/_libs/tslibs/ccalendar.pyx +++ b/pandas/_libs/tslibs/ccalendar.pyx @@ -2,10 +2,9 @@ """ Cython implementations of functions resembling the stdlib calendar module """ - import cython -from numpy cimport int64_t, int32_t +from numpy cimport int32_t, int64_t # ---------------------------------------------------------------------- # Constants diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 8cc3d25e86340..adf1dfbc1ac72 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -1,44 +1,68 @@ import cython - import numpy as np + cimport numpy as cnp -from numpy cimport int64_t, int32_t, intp_t, ndarray +from numpy cimport int32_t, int64_t, intp_t, ndarray + cnp.import_array() import pytz # stdlib datetime imports -from cpython.datetime cimport (datetime, time, tzinfo, - PyDateTime_Check, PyDate_Check, - PyDateTime_IMPORT) + +from cpython.datetime cimport ( + PyDate_Check, + PyDateTime_Check, + PyDateTime_IMPORT, + datetime, + time, + tzinfo, +) + PyDateTime_IMPORT from pandas._libs.tslibs.base cimport ABCTimestamp - from pandas._libs.tslibs.np_datetime cimport ( - check_dts_bounds, npy_datetimestruct, pandas_datetime_to_datetimestruct, - _string_to_dts, npy_datetime, dt64_to_dtstruct, dtstruct_to_dt64, - get_datetime64_unit, get_datetime64_value, pydatetime_to_dt64, - NPY_DATETIMEUNIT, NPY_FR_ns) -from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime + NPY_DATETIMEUNIT, + NPY_FR_ns, + _string_to_dts, + check_dts_bounds, + dt64_to_dtstruct, + dtstruct_to_dt64, + get_datetime64_unit, + get_datetime64_value, + npy_datetime, + npy_datetimestruct, + pandas_datetime_to_datetimestruct, + pydatetime_to_dt64, +) -from pandas._libs.tslibs.util cimport ( - is_datetime64_object, is_integer_object, is_float_object) +from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime from pandas._libs.tslibs.timezones cimport ( - is_utc, is_tzlocal, is_fixed_offset, get_utcoffset, get_dst_info, - maybe_get_tz, tz_compare, + get_dst_info, + get_utcoffset, + is_fixed_offset, + is_tzlocal, + is_utc, + maybe_get_tz, + tz_compare, utc_pytz as UTC, ) +from pandas._libs.tslibs.util cimport ( + is_datetime64_object, + is_float_object, + is_integer_object, +) + from pandas._libs.tslibs.parsing import parse_datetime_string from pandas._libs.tslibs.nattype cimport ( NPY_NAT, - checknull_with_nat, c_NaT as NaT, c_nat_strings as nat_strings, + checknull_with_nat, ) - from pandas._libs.tslibs.tzconversion cimport ( tz_convert_utc_to_tzlocal, tz_localize_to_utc_single, diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index 1d1f900bc18b3..16fa05c3801c6 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -6,26 +6,37 @@ from locale import LC_TIME import cython from cython import Py_ssize_t - import numpy as np + cimport numpy as cnp -from numpy cimport ndarray, int64_t, int32_t, int8_t, uint32_t +from numpy cimport int8_t, int32_t, int64_t, ndarray, uint32_t + cnp.import_array() from pandas._config.localization import set_locale -from pandas._libs.tslibs.ccalendar import MONTHS_FULL, DAYS_FULL +from pandas._libs.tslibs.ccalendar import DAYS_FULL, MONTHS_FULL + from pandas._libs.tslibs.ccalendar cimport ( - get_days_in_month, is_leapyear, dayofweek, get_week_of_year, - get_day_of_year, get_iso_calendar, iso_calendar_t, - month_offset, + dayofweek, + get_day_of_year, + get_days_in_month, get_firstbday, + get_iso_calendar, get_lastbday, + get_week_of_year, + is_leapyear, + iso_calendar_t, + month_offset, ) -from pandas._libs.tslibs.np_datetime cimport ( - npy_datetimestruct, pandas_timedeltastruct, dt64_to_dtstruct, - td64_to_tdstruct) from pandas._libs.tslibs.nattype cimport NPY_NAT +from pandas._libs.tslibs.np_datetime cimport ( + dt64_to_dtstruct, + npy_datetimestruct, + pandas_timedeltastruct, + td64_to_tdstruct, +) + from pandas._libs.tslibs.strptime import LocaleTime diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 264013f928d22..8e943d5ca975e 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -1,3 +1,10 @@ +from cpython.datetime cimport ( + PyDateTime_Check, + PyDateTime_IMPORT, + PyDelta_Check, + datetime, + timedelta, +) from cpython.object cimport ( Py_EQ, Py_GE, @@ -8,28 +15,19 @@ from cpython.object cimport ( PyObject_RichCompare, ) -from cpython.datetime cimport ( - PyDateTime_Check, - PyDateTime_IMPORT, - PyDelta_Check, - datetime, - timedelta, -) PyDateTime_IMPORT from cpython.version cimport PY_MINOR_VERSION import numpy as np + cimport numpy as cnp from numpy cimport int64_t -cnp.import_array() -from pandas._libs.tslibs.np_datetime cimport ( - get_datetime64_value, - get_timedelta64_value, -) -cimport pandas._libs.tslibs.util as util +cnp.import_array() +from pandas._libs.tslibs cimport util as util +from pandas._libs.tslibs.np_datetime cimport get_datetime64_value, get_timedelta64_value # ---------------------------------------------------------------------- # Constants diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index 31cc55ad981bb..12aaaf4ce3977 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -1,5 +1,3 @@ -from cpython.object cimport Py_EQ, Py_NE, Py_GE, Py_GT, Py_LT, Py_LE - from cpython.datetime cimport ( PyDateTime_DATE_GET_HOUR, PyDateTime_DATE_GET_MICROSECOND, @@ -10,11 +8,15 @@ from cpython.datetime cimport ( PyDateTime_GET_YEAR, PyDateTime_IMPORT, ) +from cpython.object cimport Py_EQ, Py_GE, Py_GT, Py_LE, Py_LT, Py_NE + PyDateTime_IMPORT from numpy cimport int64_t + from pandas._libs.tslibs.util cimport get_c_string_buf_and_size + cdef extern from "src/datetime/np_datetime.h": int cmp_npy_datetimestruct(npy_datetimestruct *a, npy_datetimestruct *b) diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 9a7ca15a2a1c2..37e36523b2c3a 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1,38 +1,49 @@ -import cython - import operator import re import time from typing import Any import warnings -from cpython.datetime cimport (PyDateTime_IMPORT, - PyDateTime_Check, - PyDate_Check, - PyDelta_Check, - datetime, timedelta, date, - time as dt_time) + +import cython + +from cpython.datetime cimport ( + PyDate_Check, + PyDateTime_Check, + PyDateTime_IMPORT, + PyDelta_Check, + date, + datetime, + time as dt_time, + timedelta, +) + PyDateTime_IMPORT -from dateutil.relativedelta import relativedelta from dateutil.easter import easter - +from dateutil.relativedelta import relativedelta import numpy as np + cimport numpy as cnp from numpy cimport int64_t, ndarray + cnp.import_array() # TODO: formalize having _libs.properties "above" tslibs in the dependency structure + from pandas._libs.properties import cache_readonly from pandas._libs.tslibs cimport util from pandas._libs.tslibs.util cimport ( - is_integer_object, is_datetime64_object, is_float_object, + is_integer_object, ) from pandas._libs.tslibs.ccalendar import ( - MONTH_ALIASES, MONTH_TO_CAL_NUM, weekday_to_int, int_to_weekday, + MONTH_ALIASES, + MONTH_TO_CAL_NUM, + int_to_weekday, + weekday_to_int, ) from pandas._libs.tslibs.ccalendar cimport ( DAY_NANOS, @@ -47,17 +58,20 @@ from pandas._libs.tslibs.conversion cimport ( ) from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT from pandas._libs.tslibs.np_datetime cimport ( - npy_datetimestruct, - dtstruct_to_dt64, dt64_to_dtstruct, + dtstruct_to_dt64, + npy_datetimestruct, pydate_to_dtstruct, ) from pandas._libs.tslibs.tzconversion cimport tz_convert_from_utc_single from .dtypes cimport PeriodDtypeCode from .timedeltas cimport delta_to_nanoseconds + from .timedeltas import Timedelta + from .timestamps cimport _Timestamp + from .timestamps import Timestamp # --------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index c4f369d0d3b3f..8429aebbd85b8 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -9,39 +9,44 @@ from libc.string cimport strchr import cython from cython import Py_ssize_t -from cpython.object cimport PyObject_Str - from cpython.datetime cimport datetime, datetime_new, import_datetime, tzinfo +from cpython.object cimport PyObject_Str from cpython.version cimport PY_VERSION_HEX + import_datetime() import numpy as np + cimport numpy as cnp -from numpy cimport (PyArray_GETITEM, PyArray_ITER_DATA, PyArray_ITER_NEXT, - PyArray_IterNew, flatiter, float64_t) +from numpy cimport ( + PyArray_GETITEM, + PyArray_ITER_DATA, + PyArray_ITER_NEXT, + PyArray_IterNew, + flatiter, + float64_t, +) + cnp.import_array() # dateutil compat -from dateutil.tz import (tzoffset, - tzlocal as _dateutil_tzlocal, - tzutc as _dateutil_tzutc, - tzstr as _dateutil_tzstr) + +from dateutil.parser import DEFAULTPARSER, parse as du_parse from dateutil.relativedelta import relativedelta -from dateutil.parser import DEFAULTPARSER -from dateutil.parser import parse as du_parse +from dateutil.tz import ( + tzlocal as _dateutil_tzlocal, + tzoffset, + tzstr as _dateutil_tzstr, + tzutc as _dateutil_tzutc, +) from pandas._config import get_option from pandas._libs.tslibs.ccalendar cimport c_MONTH_NUMBERS -from pandas._libs.tslibs.nattype cimport ( - c_nat_strings as nat_strings, - c_NaT as NaT, -) -from pandas._libs.tslibs.util cimport ( - is_array, - get_c_string_buf_and_size, -) +from pandas._libs.tslibs.nattype cimport c_NaT as NaT, c_nat_strings as nat_strings from pandas._libs.tslibs.offsets cimport is_offset_object +from pandas._libs.tslibs.util cimport get_c_string_buf_and_size, is_array + cdef extern from "../src/headers/portable.h": int getdigit_ascii(char c, int default) nogil diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 20961c6da56bd..29cee4d4aab59 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1,96 +1,101 @@ import warnings -from cpython.object cimport PyObject_RichCompareBool, Py_EQ, Py_NE +from cpython.object cimport Py_EQ, Py_NE, PyObject_RichCompareBool +from numpy cimport import_array, int64_t, ndarray -from numpy cimport int64_t, import_array, ndarray import numpy as np + import_array() from libc.stdlib cimport free, malloc +from libc.string cimport memset, strlen from libc.time cimport strftime, tm -from libc.string cimport strlen, memset import cython from cpython.datetime cimport ( - datetime, PyDate_Check, PyDateTime_Check, PyDateTime_IMPORT, PyDelta_Check, + datetime, + tzinfo, ) + # import datetime C API PyDateTime_IMPORT from pandas._libs.tslibs.np_datetime cimport ( - npy_datetimestruct, - dtstruct_to_dt64, - dt64_to_dtstruct, - pandas_datetime_to_datetimestruct, - check_dts_bounds, NPY_DATETIMEUNIT, NPY_FR_D, NPY_FR_us, + check_dts_bounds, + dt64_to_dtstruct, + dtstruct_to_dt64, + npy_datetimestruct, + pandas_datetime_to_datetimestruct, ) + cdef extern from "src/datetime/np_datetime.h": int64_t npy_datetimestruct_to_datetime(NPY_DATETIMEUNIT fr, npy_datetimestruct *d) nogil -cimport pandas._libs.tslibs.util as util +from pandas._libs.tslibs cimport util as util -from pandas._libs.tslibs.timestamps import Timestamp from pandas._libs.tslibs.timedeltas import Timedelta -from pandas._libs.tslibs.timedeltas cimport ( - delta_to_nanoseconds, - is_any_td_scalar, -) +from pandas._libs.tslibs.timestamps import Timestamp from pandas._libs.tslibs.ccalendar cimport ( + c_MONTH_NUMBERS, dayofweek, get_day_of_year, - is_leapyear, - get_week_of_year, get_days_in_month, + get_week_of_year, + is_leapyear, ) -from pandas._libs.tslibs.ccalendar cimport c_MONTH_NUMBERS + from pandas._libs.tslibs.conversion import ensure_datetime64ns from pandas._libs.tslibs.dtypes cimport ( - PeriodDtypeBase, - FR_UND, FR_ANN, - FR_QTR, - FR_MTH, - FR_WK, FR_BUS, FR_DAY, FR_HR, FR_MIN, - FR_SEC, FR_MS, - FR_US, + FR_MTH, FR_NS, + FR_QTR, + FR_SEC, + FR_UND, + FR_US, + FR_WK, + PeriodDtypeBase, attrname_to_abbrevs, ) - from pandas._libs.tslibs.parsing cimport get_rule_month +from pandas._libs.tslibs.timedeltas cimport delta_to_nanoseconds, is_any_td_scalar + from pandas._libs.tslibs.parsing import parse_time_string + from pandas._libs.tslibs.nattype cimport ( - _nat_scalar_rules, NPY_NAT, - is_null_datetimelike, + _nat_scalar_rules, c_NaT as NaT, c_nat_strings as nat_strings, + is_null_datetimelike, ) from pandas._libs.tslibs.offsets cimport ( BaseOffset, - to_offset, - is_tick_object, is_offset_object, + is_tick_object, + to_offset, ) + from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG +from pandas._libs.tslibs.tzconversion cimport tz_convert_utc_to_tzlocal cdef: enum: diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx new file mode 100644 index 0000000000000..ec1bd1d7b398e --- /dev/null +++ b/pandas/_libs/tslibs/resolution.pyx @@ -0,0 +1,149 @@ +from cpython.datetime cimport tzinfo + +import numpy as np + +from numpy cimport int32_t, int64_t, ndarray + +from pandas._libs.tslibs.util cimport get_nat + +from pandas._libs.tslibs.dtypes import Resolution + +from pandas._libs.tslibs.ccalendar cimport get_days_in_month +from pandas._libs.tslibs.np_datetime cimport dt64_to_dtstruct, npy_datetimestruct +from pandas._libs.tslibs.timezones cimport get_dst_info, is_tzlocal, is_utc +from pandas._libs.tslibs.tzconversion cimport tz_convert_utc_to_tzlocal + +# ---------------------------------------------------------------------- +# Constants + +cdef: + int64_t NPY_NAT = get_nat() + + int RESO_NS = 0 + int RESO_US = 1 + int RESO_MS = 2 + int RESO_SEC = 3 + int RESO_MIN = 4 + int RESO_HR = 5 + int RESO_DAY = 6 + int RESO_MTH = 7 + int RESO_QTR = 8 + int RESO_YR = 9 + + +# ---------------------------------------------------------------------- + + +def get_resolution(const int64_t[:] stamps, tzinfo tz=None): + cdef: + Py_ssize_t i, n = len(stamps) + npy_datetimestruct dts + int reso = RESO_DAY, curr_reso + ndarray[int64_t] trans + int64_t[:] deltas + Py_ssize_t[:] pos + int64_t local_val, delta + + if is_utc(tz) or tz is None: + for i in range(n): + if stamps[i] == NPY_NAT: + continue + dt64_to_dtstruct(stamps[i], &dts) + curr_reso = _reso_stamp(&dts) + if curr_reso < reso: + reso = curr_reso + elif is_tzlocal(tz): + for i in range(n): + if stamps[i] == NPY_NAT: + continue + local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) + dt64_to_dtstruct(local_val, &dts) + curr_reso = _reso_stamp(&dts) + if curr_reso < reso: + reso = curr_reso + else: + # Adjust datetime64 timestamp, recompute datetimestruct + trans, deltas, typ = get_dst_info(tz) + + if typ not in ['pytz', 'dateutil']: + # static/fixed; in this case we know that len(delta) == 1 + delta = deltas[0] + for i in range(n): + if stamps[i] == NPY_NAT: + continue + dt64_to_dtstruct(stamps[i] + delta, &dts) + curr_reso = _reso_stamp(&dts) + if curr_reso < reso: + reso = curr_reso + else: + pos = trans.searchsorted(stamps, side='right') - 1 + for i in range(n): + if stamps[i] == NPY_NAT: + continue + dt64_to_dtstruct(stamps[i] + deltas[pos[i]], &dts) + curr_reso = _reso_stamp(&dts) + if curr_reso < reso: + reso = curr_reso + + return Resolution(reso) + + +cdef inline int _reso_stamp(npy_datetimestruct *dts): + if dts.us != 0: + if dts.us % 1000 == 0: + return RESO_MS + return RESO_US + elif dts.sec != 0: + return RESO_SEC + elif dts.min != 0: + return RESO_MIN + elif dts.hour != 0: + return RESO_HR + return RESO_DAY + + +# ---------------------------------------------------------------------- +# Frequency Inference + +def month_position_check(fields, weekdays): + cdef: + int32_t daysinmonth, y, m, d + bint calendar_end = True + bint business_end = True + bint calendar_start = True + bint business_start = True + bint cal + int32_t[:] years + int32_t[:] months + int32_t[:] days + + years = fields['Y'] + months = fields['M'] + days = fields['D'] + + for y, m, d, wd in zip(years, months, days, weekdays): + if calendar_start: + calendar_start &= d == 1 + if business_start: + business_start &= d == 1 or (d <= 3 and wd == 0) + + if calendar_end or business_end: + daysinmonth = get_days_in_month(y, m) + cal = d == daysinmonth + if calendar_end: + calendar_end &= cal + if business_end: + business_end &= cal or (daysinmonth - d < 3 and wd == 4) + elif not calendar_start and not business_start: + break + + if calendar_end: + return 'ce' + elif business_end: + return 'be' + elif calendar_start: + return 'cs' + elif business_start: + return 'bs' + else: + return None diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index 660b582f73e6e..d2690be905a68 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -1,27 +1,30 @@ """Strptime-related classes and functions. """ -import time -import locale import calendar +import locale import re +import time from cpython.datetime cimport date, tzinfo from _thread import allocate_lock as _thread_allocate_lock +import numpy as np import pytz -import numpy as np from numpy cimport int64_t -from pandas._libs.tslibs.np_datetime cimport ( - check_dts_bounds, dtstruct_to_dt64, npy_datetimestruct) - from pandas._libs.tslibs.nattype cimport ( - checknull_with_nat, NPY_NAT, c_nat_strings as nat_strings, + checknull_with_nat, ) +from pandas._libs.tslibs.np_datetime cimport ( + check_dts_bounds, + dtstruct_to_dt64, + npy_datetimestruct, +) + cdef dict _parse_code_table = {'y': 0, 'Y': 1, diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 8f3a599bf107c..7b730eb7570a8 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -2,39 +2,47 @@ import collections import cython -from cpython.object cimport Py_NE, Py_EQ, PyObject_RichCompare +from cpython.object cimport Py_EQ, Py_NE, PyObject_RichCompare import numpy as np + cimport numpy as cnp from numpy cimport int64_t, ndarray + cnp.import_array() -from cpython.datetime cimport (timedelta, - PyDateTime_Check, PyDelta_Check, - PyDateTime_IMPORT) +from cpython.datetime cimport ( + PyDateTime_Check, + PyDateTime_IMPORT, + PyDelta_Check, + timedelta, +) + PyDateTime_IMPORT -cimport pandas._libs.tslibs.util as util -from pandas._libs.tslibs.util cimport ( - is_timedelta64_object, is_datetime64_object, is_integer_object, - is_float_object, is_array -) - +from pandas._libs.tslibs cimport util as util from pandas._libs.tslibs.base cimport ABCTimestamp - from pandas._libs.tslibs.conversion cimport cast_from_unit - -from pandas._libs.tslibs.np_datetime cimport ( - cmp_scalar, td64_to_tdstruct, pandas_timedeltastruct) - from pandas._libs.tslibs.nattype cimport ( - checknull_with_nat, NPY_NAT, c_NaT as NaT, c_nat_strings as nat_strings, + checknull_with_nat, +) +from pandas._libs.tslibs.np_datetime cimport ( + cmp_scalar, + pandas_timedeltastruct, + td64_to_tdstruct, ) from pandas._libs.tslibs.offsets cimport is_tick_object +from pandas._libs.tslibs.util cimport ( + is_array, + is_datetime64_object, + is_float_object, + is_integer_object, + is_timedelta64_object, +) # ---------------------------------------------------------------------- # Constants diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 8cef685933863..bddfc30d86a53 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -9,54 +9,66 @@ shadows the python class, where we do any heavy lifting. import warnings import numpy as np + cimport numpy as cnp -from numpy cimport int64_t, int8_t, uint8_t, ndarray -cnp.import_array() +from numpy cimport int8_t, int64_t, ndarray, uint8_t -from cpython.object cimport (PyObject_RichCompareBool, PyObject_RichCompare, - Py_EQ, Py_NE) +cnp.import_array() -from cpython.datetime cimport ( - datetime, - time, - tzinfo, - tzinfo as tzinfo_type, # alias bc `tzinfo` is a kwarg below +from cpython.datetime cimport ( # alias bc `tzinfo` is a kwarg below PyDateTime_Check, + PyDateTime_IMPORT, PyDelta_Check, PyTZInfo_Check, - PyDateTime_IMPORT, -) -PyDateTime_IMPORT - -from pandas._libs.tslibs.util cimport ( - is_datetime64_object, is_float_object, is_integer_object, - is_timedelta64_object, is_array, + datetime, + time, + tzinfo as tzinfo_type, ) +from cpython.object cimport Py_EQ, Py_NE, PyObject_RichCompare, PyObject_RichCompareBool -from pandas._libs.tslibs.base cimport ABCTimestamp +PyDateTime_IMPORT from pandas._libs.tslibs cimport ccalendar - +from pandas._libs.tslibs.base cimport ABCTimestamp from pandas._libs.tslibs.conversion cimport ( _TSObject, - convert_to_tsobject, convert_datetime_to_tsobject, + convert_to_tsobject, normalize_i8_stamp, ) -from pandas._libs.tslibs.fields import get_start_end_field, get_date_name_field +from pandas._libs.tslibs.util cimport ( + is_array, + is_datetime64_object, + is_float_object, + is_integer_object, + is_timedelta64_object, +) + +from pandas._libs.tslibs.fields import get_date_name_field, get_start_end_field + from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT from pandas._libs.tslibs.np_datetime cimport ( - check_dts_bounds, npy_datetimestruct, dt64_to_dtstruct, + check_dts_bounds, cmp_scalar, + dt64_to_dtstruct, + npy_datetimestruct, pydatetime_to_dt64, ) + from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime -from pandas._libs.tslibs.offsets cimport to_offset, is_offset_object -from pandas._libs.tslibs.timedeltas cimport is_any_td_scalar, delta_to_nanoseconds + +from pandas._libs.tslibs.offsets cimport is_offset_object, to_offset +from pandas._libs.tslibs.timedeltas cimport delta_to_nanoseconds, is_any_td_scalar + from pandas._libs.tslibs.timedeltas import Timedelta + from pandas._libs.tslibs.timezones cimport ( - is_utc, maybe_get_tz, treat_tz_as_pytz, utc_pytz as UTC, - get_timezone, tz_compare, + get_timezone, + is_utc, + maybe_get_tz, + treat_tz_as_pytz, + tz_compare, + utc_pytz as UTC, ) from pandas._libs.tslibs.tzconversion cimport ( tz_convert_from_utc_single, diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index a8c785704d8e8..b82291a71057e 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -1,27 +1,31 @@ from datetime import timezone + from cpython.datetime cimport datetime, timedelta, tzinfo # dateutil compat + from dateutil.tz import ( gettz as dateutil_gettz, tzfile as _dateutil_tzfile, tzlocal as _dateutil_tzlocal, tzutc as _dateutil_tzutc, ) - - -from pytz.tzinfo import BaseTzInfo as _pytz_BaseTzInfo import pytz +from pytz.tzinfo import BaseTzInfo as _pytz_BaseTzInfo + UTC = pytz.utc import numpy as np + cimport numpy as cnp from numpy cimport int64_t + cnp.import_array() # ---------------------------------------------------------------------- -from pandas._libs.tslibs.util cimport is_integer_object, get_nat +from pandas._libs.tslibs.util cimport get_nat, is_integer_object + cdef int64_t NPY_NAT = get_nat() cdef tzinfo utc_stdlib = timezone.utc diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index 606639af16a18..2b148cd8849f1 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -5,21 +5,27 @@ import cython from cython import Py_ssize_t from cpython.datetime cimport ( - PyDateTime_IMPORT, PyDelta_Check, datetime, timedelta, tzinfo) + PyDateTime_IMPORT, + PyDelta_Check, + datetime, + timedelta, + tzinfo, +) + PyDateTime_IMPORT -import pytz from dateutil.tz import tzutc - import numpy as np +import pytz + cimport numpy as cnp -from numpy cimport ndarray, int64_t, uint8_t, intp_t +from numpy cimport int64_t, intp_t, ndarray, uint8_t + cnp.import_array() from pandas._libs.tslibs.ccalendar cimport DAY_NANOS, HOUR_NANOS from pandas._libs.tslibs.nattype cimport NPY_NAT -from pandas._libs.tslibs.np_datetime cimport ( - npy_datetimestruct, dt64_to_dtstruct) +from pandas._libs.tslibs.np_datetime cimport dt64_to_dtstruct, npy_datetimestruct from pandas._libs.tslibs.timezones cimport ( get_dst_info, get_utcoffset, diff --git a/pandas/_libs/tslibs/vectorized.pyx b/pandas/_libs/tslibs/vectorized.pyx index c8f8daf6724c2..bdc00f6c6e21a 100644 --- a/pandas/_libs/tslibs/vectorized.pyx +++ b/pandas/_libs/tslibs/vectorized.pyx @@ -1,18 +1,21 @@ import cython -from cpython.datetime cimport datetime, date, time, tzinfo +from cpython.datetime cimport date, datetime, time, tzinfo import numpy as np + from numpy cimport int64_t, intp_t, ndarray from .conversion cimport normalize_i8_stamp + from .dtypes import Resolution + from .nattype cimport NPY_NAT, c_NaT as NaT -from .np_datetime cimport npy_datetimestruct, dt64_to_dtstruct +from .np_datetime cimport dt64_to_dtstruct, npy_datetimestruct from .offsets cimport to_offset from .period cimport get_period_ordinal from .timestamps cimport create_timestamp_from_ts -from .timezones cimport is_utc, is_tzlocal, get_dst_info +from .timezones cimport get_dst_info, is_tzlocal, is_utc from .tzconversion cimport tz_convert_utc_to_tzlocal # ------------------------------------------------------------------------- diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx index 362d0e6263697..b7955c8972dd8 100644 --- a/pandas/_libs/window/aggregations.pyx +++ b/pandas/_libs/window/aggregations.pyx @@ -1,14 +1,15 @@ # cython: boundscheck=False, wraparound=False, cdivision=True - import cython from cython import Py_ssize_t -from libcpp.deque cimport deque -from libc.stdlib cimport malloc, free +from libc.stdlib cimport free, malloc +from libcpp.deque cimport deque import numpy as np + cimport numpy as cnp -from numpy cimport ndarray, int64_t, float64_t, float32_t, uint8_t +from numpy cimport float32_t, float64_t, int64_t, ndarray, uint8_t + cnp.import_array() @@ -22,6 +23,7 @@ from pandas._libs.algos import is_monotonic from pandas._libs.util cimport numeric + cdef extern from "../src/skiplist.h": ctypedef struct node_t: node_t **next diff --git a/pandas/_libs/window/indexers.pyx b/pandas/_libs/window/indexers.pyx index 8a1e7feb57ace..ca3dc8fafe198 100644 --- a/pandas/_libs/window/indexers.pyx +++ b/pandas/_libs/window/indexers.pyx @@ -1,7 +1,7 @@ # cython: boundscheck=False, wraparound=False, cdivision=True - import numpy as np -from numpy cimport ndarray, int64_t + +from numpy cimport int64_t, ndarray # Cython routines for window indexers diff --git a/pandas/_libs/writers.pyx b/pandas/_libs/writers.pyx index 2d5b31d7ccbcf..40c39aabb7a7a 100644 --- a/pandas/_libs/writers.pyx +++ b/pandas/_libs/writers.pyx @@ -5,8 +5,8 @@ from cpython.bytes cimport PyBytes_GET_SIZE from cpython.unicode cimport PyUnicode_GET_SIZE import numpy as np -from numpy cimport ndarray, uint8_t +from numpy cimport ndarray, uint8_t ctypedef fused pandas_string: str diff --git a/pandas/_testing.py b/pandas/_testing.py index fc6df7a95e348..79261ca3a9f8c 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -23,7 +23,10 @@ ) from pandas._libs.lib import no_default -import pandas._libs.testing as _testing +from pandas._libs.testing import ( + assert_almost_equal as _assert_almost_equal, + assert_dict_equal as _assert_dict_equal, +) from pandas._typing import Dtype, FilePathOrBuffer, FrameOrSeries from pandas.compat import _get_lzma_file, _import_lzma @@ -450,7 +453,7 @@ def assert_almost_equal( else: obj = "Input" assert_class_equal(left, right, obj=obj) - _testing.assert_almost_equal( + _assert_almost_equal( left, right, check_dtype=check_dtype, rtol=rtol, atol=atol, **kwargs ) @@ -486,7 +489,7 @@ def _check_isinstance(left, right, cls): def assert_dict_equal(left, right, compare_keys: bool = True): _check_isinstance(left, right, dict) - _testing.assert_dict_equal(left, right, compare_keys=compare_keys) + _assert_dict_equal(left, right, compare_keys=compare_keys) def randbool(size=(), p: float = 0.5): @@ -535,7 +538,7 @@ def rands(nchars): def close(fignum=None): - from matplotlib.pyplot import get_fignums, close as _close + from matplotlib.pyplot import close as _close, get_fignums if fignum is None: for fignum in get_fignums(): @@ -791,7 +794,7 @@ def _get_ilevel_values(index, level): msg = f"{obj} values are different ({np.round(diff, 5)} %)" raise_assert_detail(obj, msg, left, right) else: - _testing.assert_almost_equal( + _assert_almost_equal( left.values, right.values, rtol=rtol, @@ -887,7 +890,7 @@ def assert_attr_equal(attr: str, left, right, obj: str = "Attributes"): def assert_is_valid_plot_return_object(objs): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt if isinstance(objs, (pd.Series, np.ndarray)): for el in objs.ravel(): @@ -1202,7 +1205,7 @@ def assert_extension_array_equal( left_valid, right_valid, obj="ExtensionArray", index_values=index_values ) else: - _testing.assert_almost_equal( + _assert_almost_equal( left_valid, right_valid, check_dtype=check_dtype, @@ -1368,7 +1371,7 @@ def assert_series_equal( elif is_interval_dtype(left.dtype) and is_interval_dtype(right.dtype): assert_interval_array_equal(left.array, right.array) elif is_categorical_dtype(left.dtype) or is_categorical_dtype(right.dtype): - _testing.assert_almost_equal( + _assert_almost_equal( left._values, right._values, rtol=rtol, @@ -1387,7 +1390,7 @@ def assert_series_equal( left._values, right._values, index_values=np.asarray(left.index) ) else: - _testing.assert_almost_equal( + _assert_almost_equal( left._values, right._values, rtol=rtol, diff --git a/pandas/_typing.py b/pandas/_typing.py index 8e98833ad37f7..76ec527e6e258 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -24,13 +24,15 @@ # https://mypy.readthedocs.io/en/latest/common_issues.html#import-cycles if TYPE_CHECKING: from pandas._libs import Period, Timedelta, Timestamp # noqa: F401 - from pandas.core.arrays.base import ExtensionArray # noqa: F401 + from pandas.core.dtypes.dtypes import ExtensionDtype # noqa: F401 - from pandas.core.indexes.base import Index # noqa: F401 - from pandas.core.generic import NDFrame # noqa: F401 + from pandas import Interval # noqa: F401 - from pandas.core.series import Series # noqa: F401 + from pandas.core.arrays.base import ExtensionArray # noqa: F401 from pandas.core.frame import DataFrame # noqa: F401 + from pandas.core.generic import NDFrame # noqa: F401 + from pandas.core.indexes.base import Index # noqa: F401 + from pandas.core.series import Series # noqa: F401 # array-like diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py index 0484de3fa165d..f4f32e6ee2285 100644 --- a/pandas/compat/pickle_compat.py +++ b/pandas/compat/pickle_compat.py @@ -1,7 +1,6 @@ """ Support pre-0.12 series pickle compatibility. """ - import contextlib import copy import io @@ -14,7 +13,7 @@ from pandas import Index if TYPE_CHECKING: - from pandas import Series, DataFrame + from pandas import DataFrame, Series def load_reduce(self): diff --git a/pandas/conftest.py b/pandas/conftest.py index e0adb37e7d2f5..8b1ab86278d2d 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -17,7 +17,6 @@ - Dtypes - Misc """ - from collections import abc from datetime import date, time, timedelta, timezone from decimal import Decimal @@ -31,13 +30,11 @@ import pytest from pytz import FixedOffset, utc -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm from pandas.core import ops from pandas.core.indexes.api import Index, MultiIndex +from pandas.util import _test_decorators as td # ---------------------------------------------------------------- diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index 891048ae82dfd..14d844e41c758 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -2,7 +2,6 @@ aggregation.py contains utility functions to handle multiple named and lambda kwarg aggregations in groupby and DataFrame/Series aggregation """ - from collections import defaultdict from functools import partial from typing import ( diff --git a/pandas/core/apply.py b/pandas/core/apply.py index d4be660939773..883783effcd51 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -15,7 +15,7 @@ from pandas.core.construction import create_series_with_explicit_dtype if TYPE_CHECKING: - from pandas import DataFrame, Series, Index + from pandas import DataFrame, Index, Series ResType = Dict[int, Any] diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index db9cfd9d7fc59..07f05aed49df8 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -40,9 +40,8 @@ from pandas.core.dtypes.inference import is_hashable from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna -from pandas.core import ops +from pandas.core import algorithms as algorithms, common as com, ops from pandas.core.accessor import PandasDelegate, delegate_names -import pandas.core.algorithms as algorithms from pandas.core.algorithms import _get_data_algo, factorize, take_1d, unique1d from pandas.core.array_algos.transforms import shift from pandas.core.arrays._mixins import _T, NDArrayBackedExtensionArray @@ -52,7 +51,6 @@ PandasObject, _shared_docs, ) -import pandas.core.common as com from pandas.core.construction import array, extract_array, sanitize_array from pandas.core.indexers import check_array_indexer, deprecate_ndim_indexing from pandas.core.missing import interpolate_2d @@ -520,7 +518,7 @@ def _from_inferred_categories( ------- Categorical """ - from pandas import Index, to_numeric, to_datetime, to_timedelta + from pandas import Index, to_datetime, to_numeric, to_timedelta cats = Index(inferred_categories) known_categories = ( @@ -1403,7 +1401,7 @@ def value_counts(self, dropna=True): -------- Series.value_counts """ - from pandas import Series, CategoricalIndex + from pandas import CategoricalIndex, Series code, cat = self._codes, self.categories ncat, mask = len(cat), 0 <= code diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index ee4d43fdb3bc2..53b0d1b6ae375 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -52,12 +52,11 @@ from pandas.core.dtypes.inference import is_array_like from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna -from pandas.core import missing, nanops, ops +from pandas.core import common as com, missing, nanops, ops from pandas.core.algorithms import checked_add_with_arr, unique1d, value_counts from pandas.core.array_algos.transforms import shift from pandas.core.arrays._mixins import _T, NDArrayBackedExtensionArray from pandas.core.arrays.base import ExtensionArray, ExtensionOpsMixin -import pandas.core.common as com from pandas.core.construction import array, extract_array from pandas.core.indexers import check_array_indexer from pandas.core.ops.common import unpack_zerodim_and_defer @@ -959,7 +958,7 @@ def value_counts(self, dropna=False): ------- Series """ - from pandas import Series, Index + from pandas import Index, Series if dropna: values = self[~self.isna()]._data diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index d674b1c476d2c..51851f0c9c41a 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -44,10 +44,10 @@ from pandas.core.dtypes.generic import ABCIndexClass, ABCPandasArray, ABCSeries from pandas.core.dtypes.missing import isna +from pandas.core import common as com from pandas.core.algorithms import checked_add_with_arr from pandas.core.arrays import datetimelike as dtl from pandas.core.arrays._ranges import generate_regular_range -import pandas.core.common as com from pandas.tseries.frequencies import get_period_alias from pandas.tseries.offsets import BDay, Day, Tick diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index b0958af41158c..57df067c7b16e 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -116,6 +116,7 @@ def __from_arrow__( Construct IntegerArray from pyarrow Array/ChunkedArray. """ import pyarrow # noqa: F811 + from pandas.core.arrays._arrow_utils import pyarrow_array_to_numpy_and_mask pyarrow_type = pyarrow.from_numpy_dtype(self.type) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index c861d25afd13f..75ad636352600 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -34,10 +34,10 @@ ) from pandas.core.dtypes.missing import isna, notna +from pandas.core import common as com from pandas.core.algorithms import take, value_counts from pandas.core.arrays.base import ExtensionArray, _extension_array_shared_docs from pandas.core.arrays.categorical import Categorical -import pandas.core.common as com from pandas.core.construction import array from pandas.core.indexers import check_array_indexer from pandas.core.indexes.base import ensure_index @@ -1105,6 +1105,7 @@ def __arrow_array__(self, type=None): Convert myself into a pyarrow Array. """ import pyarrow + from pandas.core.arrays._arrow_utils import ArrowIntervalType try: diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 8d5cb12d60e4d..06c430e6b129b 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -46,9 +46,8 @@ ) from pandas.core.dtypes.missing import isna, notna -import pandas.core.algorithms as algos +from pandas.core import algorithms as algos, common as com from pandas.core.arrays import datetimelike as dtl -import pandas.core.common as com def _field_accessor(name: str, docstring=None): @@ -300,6 +299,7 @@ def __arrow_array__(self, type=None): Convert myself into a pyarrow Array. """ import pyarrow + from pandas.core.arrays._arrow_utils import ArrowPeriodType if type is not None: diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py index 8a30d2b954b55..9bbeecd50ad8d 100644 --- a/pandas/core/arrays/sparse/accessor.py +++ b/pandas/core/arrays/sparse/accessor.py @@ -1,5 +1,4 @@ """Sparse accessor""" - import numpy as np from pandas.compat._optional import import_optional_dependency @@ -87,8 +86,8 @@ def from_coo(cls, A, dense_index=False): 1 0 3.0 dtype: Sparse[float64, nan] """ - from pandas.core.arrays.sparse.scipy_sparse import _coo_to_sparse_series from pandas import Series + from pandas.core.arrays.sparse.scipy_sparse import _coo_to_sparse_series result = _coo_to_sparse_series(A, dense_index=dense_index) result = Series(result.array, index=result.index, copy=False) @@ -253,9 +252,10 @@ def from_spmatrix(cls, data, index=None, columns=None): 1 0.0 1.0 0.0 2 0.0 0.0 1.0 """ - from pandas import DataFrame from pandas._libs.sparse import IntIndex + from pandas import DataFrame + data = data.tocsc() index, columns = cls._prep_index(data, index, columns) n_rows, n_columns = data.shape @@ -354,7 +354,7 @@ def density(self) -> float: @staticmethod def _prep_index(data, index, columns): - import pandas.core.indexes.base as ibase + from pandas.core.indexes import base as ibase from pandas.core.indexes.api import ensure_index N, K = data.shape diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index d8db196e4b92f..e6379e1f8f092 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -9,12 +9,10 @@ import numpy as np -from pandas._libs import lib -import pandas._libs.sparse as splib +from pandas._libs import lib, sparse as splib from pandas._libs.sparse import BlockIndex, IntIndex, SparseIndex from pandas._libs.tslibs import NaT from pandas._typing import Scalar -import pandas.compat as compat from pandas.compat.numpy import function as nv from pandas.errors import PerformanceWarning @@ -39,19 +37,18 @@ from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries from pandas.core.dtypes.missing import isna, na_value_for_dtype, notna -import pandas.core.algorithms as algos +from pandas import compat as compat +from pandas.core import algorithms as algos, common as com, ops as ops from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin from pandas.core.arrays.sparse.dtype import SparseDtype from pandas.core.base import PandasObject -import pandas.core.common as com from pandas.core.construction import extract_array, sanitize_array from pandas.core.indexers import check_array_indexer from pandas.core.missing import interpolate_2d from pandas.core.nanops import check_below_min_count -import pandas.core.ops as ops from pandas.core.ops.common import unpack_zerodim_and_defer -import pandas.io.formats.printing as printing +from pandas.io.formats import printing as printing # ---------------------------------------------------------------------------- # Array diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index a378423df788b..7a756ce5c45c6 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -27,11 +27,10 @@ from pandas.core.dtypes.generic import ABCSeries, ABCTimedeltaIndex from pandas.core.dtypes.missing import isna -from pandas.core import nanops +from pandas.core import common as com, nanops from pandas.core.algorithms import checked_add_with_arr from pandas.core.arrays import datetimelike as dtl from pandas.core.arrays._ranges import generate_regular_range -import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.ops.common import unpack_zerodim_and_defer diff --git a/pandas/core/base.py b/pandas/core/base.py index b62ef668df5e1..930f93ec5b587 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1,14 +1,13 @@ """ Base and utility classes for pandas objects. """ - import builtins import textwrap from typing import Any, Dict, FrozenSet, List, Optional, Union import numpy as np -import pandas._libs.lib as lib +from pandas._libs import lib as lib from pandas.compat import PYPY from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError @@ -26,12 +25,11 @@ from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries from pandas.core.dtypes.missing import isna -from pandas.core import algorithms, common as com +from pandas.core import algorithms, common as com, nanops as nanops from pandas.core.accessor import DirNamesMixin from pandas.core.algorithms import duplicated, unique1d, value_counts from pandas.core.arrays import ExtensionArray from pandas.core.construction import create_series_with_explicit_dtype -import pandas.core.nanops as nanops _shared_docs: Dict[str, str] = dict() _indexops_doc_kwargs = dict( diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py index 82867cf9dcd29..c100fec1cbfab 100644 --- a/pandas/core/computation/align.py +++ b/pandas/core/computation/align.py @@ -1,7 +1,6 @@ """ Core eval alignment algorithms. """ - from functools import partial, wraps from typing import Dict, Optional, Sequence, Tuple, Type, Union import warnings @@ -13,8 +12,8 @@ from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries +from pandas.core import common as com from pandas.core.base import PandasObject -import pandas.core.common as com from pandas.core.computation.common import result_type_many diff --git a/pandas/core/computation/engines.py b/pandas/core/computation/engines.py index 9c5388faae1bd..e2edafa4cc1bc 100644 --- a/pandas/core/computation/engines.py +++ b/pandas/core/computation/engines.py @@ -1,14 +1,13 @@ """ Engine classes for :func:`~pandas.eval` """ - import abc from typing import Dict, Type from pandas.core.computation.align import align_terms, reconstruct_object from pandas.core.computation.ops import _mathops, _reductions -import pandas.io.formats.printing as printing +from pandas.io.formats import printing as printing _ne_builtins = frozenset(_mathops + _reductions) diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index fcccc24ed7615..848ffc3b3cd14 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -1,7 +1,6 @@ """ :func:`~pandas.eval` parsers. """ - import ast from functools import partial, reduce from keyword import iskeyword @@ -10,7 +9,7 @@ import numpy as np -import pandas.core.common as com +from pandas.core import common as com from pandas.core.computation.ops import ( _LOCAL_TAG, BinOp, @@ -32,7 +31,7 @@ from pandas.core.computation.parsing import clean_backtick_quoted_toks, tokenize_string from pandas.core.computation.scope import Scope -import pandas.io.formats.printing as printing +from pandas.io.formats import printing as printing def _rewrite_assign(tok: Tuple[int, str]) -> Tuple[int, str]: diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index bc9ff7c44b689..c6ccb3a5bc8a9 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -1,7 +1,6 @@ """ Operator classes for eval. """ - from datetime import datetime from distutils.version import LooseVersion from functools import partial @@ -14,7 +13,7 @@ from pandas.core.dtypes.common import is_list_like, is_scalar -import pandas.core.common as com +from pandas.core import common as com from pandas.core.computation.common import _ensure_decoded, result_type_many from pandas.core.computation.scope import _DEFAULT_GLOBALS diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index 001eb1789007f..74dcd1932c39c 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -1,5 +1,4 @@ """ manage PyTables query interface via Expressions """ - import ast from functools import partial from typing import Any, Dict, Optional, Tuple @@ -12,7 +11,7 @@ from pandas.core.dtypes.common import is_list_like import pandas as pd -import pandas.core.common as com +from pandas.core import common as com from pandas.core.computation import expr, ops, scope as _scope from pandas.core.computation.common import _ensure_decoded from pandas.core.computation.expr import BaseExprVisitor diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 86f6be77bc505..9c943967b80d0 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -11,7 +11,7 @@ """ import warnings -import pandas._config.config as cf +from pandas._config import config as cf from pandas._config.config import ( is_bool, is_callable, @@ -662,8 +662,10 @@ def register_plotting_backend_cb(key): def register_converter_cb(key): - from pandas.plotting import register_matplotlib_converters - from pandas.plotting import deregister_matplotlib_converters + from pandas.plotting import ( + deregister_matplotlib_converters, + register_matplotlib_converters, + ) if cf.get_option(key): register_matplotlib_converters() diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 6c58698989e96..db22040b288ba 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -4,12 +4,11 @@ These should not depend on core.internals. """ - from collections import abc from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast import numpy as np -import numpy.ma as ma +from numpy import ma as ma from pandas._libs import lib from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime @@ -45,12 +44,12 @@ ) from pandas.core.dtypes.missing import isna -import pandas.core.common as com +from pandas.core import common as com if TYPE_CHECKING: - from pandas.core.series import Series # noqa: F401 - from pandas.core.indexes.api import Index # noqa: F401 from pandas.core.arrays import ExtensionArray # noqa: F401 + from pandas.core.indexes.api import Index # noqa: F401 + from pandas.core.series import Series # noqa: F401 def array( @@ -255,14 +254,14 @@ def array( ValueError: Cannot pass scalar '1' to 'pandas.array'. """ from pandas.core.arrays import ( - period_array, BooleanArray, + DatetimeArray, IntegerArray, IntervalArray, PandasArray, - DatetimeArray, - TimedeltaArray, StringArray, + TimedeltaArray, + period_array, ) if lib.is_scalar(data): diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 6b84f0e81f48b..b287e9e14d5e8 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1,7 +1,6 @@ """ Routines for casting. """ - from datetime import date, datetime, timedelta from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type @@ -1244,6 +1243,7 @@ def try_datetime(v): # if so coerce to a DatetimeIndex; if they are not the same, # then these stay as object dtype, xref GH19671 from pandas._libs.tslibs import conversion + from pandas import DatetimeIndex try: @@ -1303,8 +1303,8 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"): try to cast the array/value to a datetimelike dtype, converting float nan to iNaT """ - from pandas.core.tools.timedeltas import to_timedelta from pandas.core.tools.datetimes import to_datetime + from pandas.core.tools.timedeltas import to_timedelta if dtype is not None: if isinstance(dtype, str): diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 22480fbc47508..1362b4df268ca 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -1,7 +1,6 @@ """ Define extension dtypes. """ - import re from typing import ( TYPE_CHECKING, @@ -30,12 +29,13 @@ if TYPE_CHECKING: import pyarrow # noqa: F401 + + from pandas import Categorical # noqa: F401 from pandas.core.arrays import ( # noqa: F401 + DatetimeArray, IntervalArray, PeriodArray, - DatetimeArray, ) - from pandas import Categorical # noqa: F401 str_type = str @@ -391,12 +391,13 @@ def __repr__(self) -> str_type: @staticmethod def _hash_categories(categories, ordered: Ordered = True) -> int: + from pandas.core.dtypes.common import DT64NS_DTYPE, is_datetime64tz_dtype + from pandas.core.util.hashing import ( - hash_array, _combine_hash_arrays, + hash_array, hash_tuples, ) - from pandas.core.dtypes.common import is_datetime64tz_dtype, DT64NS_DTYPE if len(categories) and isinstance(categories[0], tuple): # assumes if any individual category is a tuple, then all our. ATM @@ -939,6 +940,7 @@ def __from_arrow__( Construct PeriodArray from pyarrow Array/ChunkedArray. """ import pyarrow # noqa: F811 + from pandas.core.arrays import PeriodArray from pandas.core.arrays._arrow_utils import pyarrow_array_to_numpy_and_mask @@ -1136,6 +1138,7 @@ def __from_arrow__( Construct IntervalArray from pyarrow Array/ChunkedArray. """ import pyarrow # noqa: F811 + from pandas.core.arrays import IntervalArray if isinstance(array, pyarrow.Array): diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 8551ce9f14e6c..a81b88fef0433 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -7,8 +7,7 @@ from pandas._config import get_option -from pandas._libs import lib -import pandas._libs.missing as libmissing +from pandas._libs import lib, missing as libmissing from pandas._libs.tslibs import NaT, iNaT from pandas._typing import DtypeObj diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f52341ed782d8..ae7a1c9f6e4e1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8,7 +8,6 @@ alignment and a host of useful data manipulation methods having to do with the labeling information """ - import collections from collections import abc import datetime @@ -38,7 +37,7 @@ import warnings import numpy as np -import numpy.ma as ma +from numpy import ma as ma from pandas._config import get_option @@ -150,6 +149,7 @@ if TYPE_CHECKING: from pandas.core.groupby.generic import DataFrameGroupBy + from pandas.io.formats.style import Styler # --------------------------------------------------------------------- @@ -466,7 +466,7 @@ def __init__( elif isinstance(data, dict): mgr = init_dict(data, index, columns, dtype=dtype) elif isinstance(data, ma.MaskedArray): - import numpy.ma.mrecords as mrecords + from numpy.ma import mrecords as mrecords # masked recarray if isinstance(data, mrecords.MaskedRecords): @@ -5204,8 +5204,9 @@ def duplicated( 4 True dtype: bool """ + from pandas._libs.hashtable import _SIZE_HINT_LIMIT, duplicated_int64 + from pandas.core.sorting import get_group_index - from pandas._libs.hashtable import duplicated_int64, _SIZE_HINT_LIMIT if self.empty: return self._constructor_sliced(dtype=bool) @@ -6199,7 +6200,7 @@ def combine_first(self, other: "DataFrame") -> "DataFrame": 1 0.0 3.0 1.0 2 NaN 3.0 1.0 """ - import pandas.core.computation.expressions as expressions + from pandas.core.computation import expressions as expressions def extract_values(arr): # Does two things: @@ -6348,7 +6349,7 @@ def update( 1 2 500.0 2 3 6.0 """ - import pandas.core.computation.expressions as expressions + from pandas.core.computation import expressions as expressions # TODO: Support other joins if join != "left": # pragma: no cover @@ -7867,8 +7868,8 @@ def join( def _join_compat( self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False ): - from pandas.core.reshape.merge import merge from pandas.core.reshape.concat import concat + from pandas.core.reshape.merge import merge if isinstance(other, Series): if other.name is None: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index e46fde1f59f16..22b5f83afbca2 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -85,15 +85,18 @@ from pandas.core.dtypes.missing import isna, notna import pandas as pd -from pandas.core import missing, nanops -import pandas.core.algorithms as algos +from pandas.core import ( + algorithms as algos, + common as com, + indexing as indexing, + missing, + nanops, +) from pandas.core.base import PandasObject, SelectionMixin -import pandas.core.common as com from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.indexes.api import Index, MultiIndex, RangeIndex, ensure_index from pandas.core.indexes.datetimes import DatetimeIndex from pandas.core.indexes.period import Period, PeriodIndex -import pandas.core.indexing as indexing from pandas.core.internals import BlockManager from pandas.core.missing import find_valid_index from pandas.core.ops import _align_method_FRAME diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index ec7b14f27c5a1..f0ecca84acc15 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -54,14 +54,13 @@ ) from pandas.core.dtypes.missing import isna, notna +from pandas.core import algorithms as algorithms, common as com from pandas.core.aggregation import ( maybe_mangle_lambdas, reconstruct_func, validate_func_kwargs, ) -import pandas.core.algorithms as algorithms from pandas.core.base import DataError, SpecificationError -import pandas.core.common as com from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.frame import DataFrame from pandas.core.generic import ABCDataFrame, ABCSeries, NDFrame @@ -73,8 +72,8 @@ _transform_template, get_groupby, ) +from pandas.core.indexes import base as ibase from pandas.core.indexes.api import Index, MultiIndex, all_indexes_same -import pandas.core.indexes.base as ibase from pandas.core.internals import BlockManager, make_block from pandas.core.series import Series from pandas.core.util.numba_ import ( @@ -681,8 +680,8 @@ def value_counts( self, normalize=False, sort=True, ascending=False, bins=None, dropna=True ): - from pandas.core.reshape.tile import cut from pandas.core.reshape.merge import _get_join_indexers + from pandas.core.reshape.tile import cut if bins is not None and not np.iterable(bins): # scalar bins cannot be done at top level diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index ac45222625569..8b32c171da05e 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -6,7 +6,6 @@ class providing the base-class of operations. (defined in pandas.core.groupby.generic) expose these user-facing objects to provide specific functionality. """ - from contextlib import contextmanager import datetime from functools import partial, wraps @@ -34,8 +33,7 @@ class providing the base-class of operations. from pandas._config.config import option_context -from pandas._libs import Timestamp -import pandas._libs.groupby as libgroupby +from pandas._libs import Timestamp, groupby as libgroupby from pandas._typing import F, FrameOrSeries, FrameOrSeriesUnion, Scalar from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError @@ -54,11 +52,9 @@ class providing the base-class of operations. ) from pandas.core.dtypes.missing import isna, notna -from pandas.core import nanops -import pandas.core.algorithms as algorithms +from pandas.core import algorithms as algorithms, common as com, nanops from pandas.core.arrays import Categorical, DatetimeArray from pandas.core.base import DataError, PandasObject, SelectionMixin -import pandas.core.common as com from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame from pandas.core.groupby import base, ops diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 67003dffb90bb..6417c1c6c2434 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -20,9 +20,8 @@ ) from pandas.core.dtypes.generic import ABCSeries -import pandas.core.algorithms as algorithms +from pandas.core import algorithms as algorithms, common as com from pandas.core.arrays import Categorical, ExtensionArray -import pandas.core.common as com from pandas.core.frame import DataFrame from pandas.core.groupby import ops from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 3aaeef3b63760..777d0620603dd 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -5,15 +5,18 @@ operations, primarily in cython. These classes (BaseGrouper and BinGrouper) are contained *in* the SeriesGroupBy and DataFrameGroupBy objects. """ - import collections from typing import List, Optional, Sequence, Tuple, Type import numpy as np -from pandas._libs import NaT, iNaT, lib -import pandas._libs.groupby as libgroupby -import pandas._libs.reduction as libreduction +from pandas._libs import ( + NaT, + groupby as libgroupby, + iNaT, + lib, + reduction as libreduction, +) from pandas._typing import F, FrameOrSeries, Label from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly @@ -39,9 +42,8 @@ ) from pandas.core.dtypes.missing import _maybe_fill, isna -import pandas.core.algorithms as algorithms +from pandas.core import algorithms as algorithms, common as com from pandas.core.base import SelectionMixin -import pandas.core.common as com from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame from pandas.core.groupby import base, grouper diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index 4c5a70f4088ee..57e1f3ce30dca 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -4,7 +4,7 @@ from pandas._libs import NaT, lib from pandas.errors import InvalidIndexError -import pandas.core.common as com +from pandas.core import common as com from pandas.core.indexes.base import ( Index, _new_Index, diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 3dbee7d0929cb..5a48ef447b199 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -17,7 +17,12 @@ import numpy as np from pandas._libs import algos as libalgos, index as libindex, lib -import pandas._libs.join as libjoin +from pandas._libs.join import ( + inner_join_indexer, + left_join_indexer, + left_join_indexer_unique, + outer_join_indexer, +) from pandas._libs.lib import is_datetime_array, no_default from pandas._libs.tslibs import OutOfBoundsDatetime, Timestamp from pandas._libs.tslibs.period import IncompatibleFrequency @@ -73,16 +78,13 @@ ) from pandas.core.dtypes.missing import array_equivalent, isna -from pandas.core import ops +from pandas.core import algorithms as algos, common as com, missing as missing, ops from pandas.core.accessor import CachedAccessor -import pandas.core.algorithms as algos from pandas.core.arrays import Categorical, ExtensionArray from pandas.core.arrays.datetimes import tz_to_dtype, validate_tz_from_dtype from pandas.core.base import IndexOpsMixin, PandasObject -import pandas.core.common as com from pandas.core.indexers import deprecate_ndim_indexing from pandas.core.indexes.frozen import FrozenList -import pandas.core.missing as missing from pandas.core.ops import get_op_result_name from pandas.core.ops.invalid import make_invalid_op from pandas.core.sorting import ensure_key_mapped @@ -247,16 +249,16 @@ class Index(IndexOpsMixin, PandasObject): # Moreover, cython will choose the appropriate-dtyped sub-function # given the dtypes of the passed arguments def _left_indexer_unique(self, left, right): - return libjoin.left_join_indexer_unique(left, right) + return left_join_indexer_unique(left, right) def _left_indexer(self, left, right): - return libjoin.left_join_indexer(left, right) + return left_join_indexer(left, right) def _inner_indexer(self, left, right): - return libjoin.inner_join_indexer(left, right) + return inner_join_indexer(left, right) def _outer_indexer(self, left, right): - return libjoin.outer_join_indexer(left, right) + return outer_join_indexer(left, right) _typ = "index" _data: Union[ExtensionArray, np.ndarray] @@ -5728,9 +5730,9 @@ def _maybe_cast_data_without_dtype(subarr): """ # Runtime import needed bc IntervalArray imports Index from pandas.core.arrays import ( + DatetimeArray, IntervalArray, PeriodArray, - DatetimeArray, TimedeltaArray, ) diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index b0b008de69a94..91288b6e7a7c1 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -22,15 +22,13 @@ from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna -from pandas.core import accessor +from pandas.core import accessor, common as com, missing as missing from pandas.core.algorithms import take_1d from pandas.core.arrays.categorical import Categorical, contains, recode_for_categories -import pandas.core.common as com from pandas.core.construction import extract_array -import pandas.core.indexes.base as ibase +from pandas.core.indexes import base as ibase from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name from pandas.core.indexes.extension import ExtensionIndex, inherit_names -import pandas.core.missing as missing from pandas.core.ops import get_op_result_name _index_doc_kwargs = dict(ibase._index_doc_kwargs) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 15a7e25238983..f7174a1dfd0fd 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -26,13 +26,12 @@ from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries -from pandas.core import algorithms +from pandas.core import algorithms, common as com from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin from pandas.core.base import IndexOpsMixin -import pandas.core.common as com from pandas.core.construction import array as pd_array, extract_array -import pandas.core.indexes.base as ibase +from pandas.core.indexes import base as ibase from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.extension import ( ExtensionIndex, diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 6d2e592f024ed..922772c6feebb 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -29,8 +29,8 @@ ) from pandas.core.dtypes.missing import is_valid_nat_for_dtype +from pandas.core import common as com from pandas.core.arrays.datetimes import DatetimeArray, tz_to_dtype -import pandas.core.common as com from pandas.core.indexes.base import Index, maybe_extract_name from pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin from pandas.core.indexes.extension import inherit_names diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 9548ebbd9c3b2..fc61aea544ac3 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -38,11 +38,11 @@ ) from pandas.core.dtypes.missing import isna +from pandas.core import common as com from pandas.core.algorithms import take_1d from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs -import pandas.core.common as com from pandas.core.indexers import is_valid_positional_slice -import pandas.core.indexes.base as ibase +from pandas.core.indexes import base as ibase from pandas.core.indexes.base import ( Index, _index_shared_docs, diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 235da89083d0a..9b9e2a40f3d36 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -41,15 +41,13 @@ from pandas.core.dtypes.generic import ABCDataFrame, ABCDatetimeIndex, ABCTimedeltaIndex from pandas.core.dtypes.missing import array_equivalent, isna -import pandas.core.algorithms as algos +from pandas.core import algorithms as algos, common as com, missing as missing from pandas.core.arrays import Categorical from pandas.core.arrays.categorical import factorize_from_iterables -import pandas.core.common as com -import pandas.core.indexes.base as ibase +from pandas.core.indexes import base as ibase from pandas.core.indexes.base import Index, _index_shared_docs, ensure_index from pandas.core.indexes.frozen import FrozenList from pandas.core.indexes.numeric import Int64Index -import pandas.core.missing as missing from pandas.core.sorting import ( get_group_index, indexer_from_factorized, diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 731907993d08f..95aee75622c88 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -30,8 +30,7 @@ ) from pandas.core.dtypes.missing import isna -from pandas.core import algorithms -import pandas.core.common as com +from pandas.core import algorithms, common as com from pandas.core.indexes.base import Index, maybe_extract_name from pandas.core.ops import get_op_result_name diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 03e11b652477f..48b35aa6a8f1e 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -24,14 +24,14 @@ ) from pandas.core.dtypes.dtypes import PeriodDtype +from pandas.core import common as com from pandas.core.arrays.period import ( PeriodArray, period_array, raise_on_incompatible, validate_dtype_freq, ) -import pandas.core.common as com -import pandas.core.indexes.base as ibase +from pandas.core.indexes import base as ibase from pandas.core.indexes.base import ( _index_shared_docs, ensure_index, diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index e5e98039ff77b..2cb45f67a37d9 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -9,7 +9,6 @@ from pandas._libs import index as libindex from pandas._libs.lib import no_default from pandas._typing import Label -import pandas.compat as compat from pandas.compat.numpy import function as nv from pandas.util._decorators import Appender, cache_readonly, doc @@ -25,10 +24,10 @@ ) from pandas.core.dtypes.generic import ABCTimedeltaIndex -from pandas.core import ops -import pandas.core.common as com +from pandas import compat as compat +from pandas.core import common as com, ops from pandas.core.construction import extract_array -import pandas.core.indexes.base as ibase +from pandas.core.indexes import base as ibase from pandas.core.indexes.base import _index_shared_docs, maybe_extract_name from pandas.core.indexes.numeric import Int64Index from pandas.core.ops.common import unpack_zerodim_and_defer diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index dccc8369c5366..5c36d07e19e8c 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -1,5 +1,4 @@ """ implement the TimedeltaIndex """ - from pandas._libs import index as libindex, lib from pandas._libs.tslibs import Timedelta, to_offset from pandas._typing import DtypeObj, Label @@ -16,9 +15,9 @@ pandas_dtype, ) +from pandas.core import common as com from pandas.core.arrays import datetimelike as dtl from pandas.core.arrays.timedeltas import TimedeltaArray -import pandas.core.common as com from pandas.core.indexes.base import Index, maybe_extract_name from pandas.core.indexes.datetimelike import ( DatetimeIndexOpsMixin, diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 04d1dbceb3342..cb843dc29f022 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -24,7 +24,7 @@ from pandas.core.dtypes.generic import ABCDataFrame, ABCMultiIndex, ABCSeries from pandas.core.dtypes.missing import _infer_fill_value, isna -import pandas.core.common as com +from pandas.core import common as com from pandas.core.construction import array as pd_array from pandas.core.indexers import ( check_array_indexer, diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index cc0f09ced7399..d1b52f9be355f 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -6,8 +6,7 @@ import numpy as np -from pandas._libs import NaT, algos as libalgos, lib, writers -import pandas._libs.internals as libinternals +from pandas._libs import NaT, algos as libalgos, internals as libinternals, lib, writers from pandas._libs.internals import BlockPlacement from pandas._libs.tslibs import conversion from pandas._libs.tslibs.timezones import tz_compare @@ -58,7 +57,7 @@ ) from pandas.core.dtypes.missing import _isna_compat, is_valid_nat_for_dtype, isna -import pandas.core.algorithms as algos +from pandas.core import algorithms as algos, common as com, missing as missing from pandas.core.array_algos.transforms import shift from pandas.core.arrays import ( Categorical, @@ -69,14 +68,12 @@ TimedeltaArray, ) from pandas.core.base import PandasObject -import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexers import ( check_setitem_lengths, is_empty_indexer, is_scalar_indexer, ) -import pandas.core.missing as missing from pandas.core.nanops import nanpercentile if TYPE_CHECKING: @@ -1296,7 +1293,7 @@ def where( ------- List[Block] """ - import pandas.core.computation.expressions as expressions + from pandas.core.computation import expressions as expressions cond = _extract_bool_array(cond) assert not isinstance(other, (ABCIndexClass, ABCSeries, ABCDataFrame)) diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 2c0d4931a7bf2..990357e3d3743 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -22,7 +22,7 @@ from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.missing import isna -import pandas.core.algorithms as algos +from pandas.core import algorithms as algos from pandas.core.arrays import ExtensionArray from pandas.core.internals.blocks import make_block from pandas.core.internals.managers import BlockManager diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 2d4163e0dee89..0823c7916a4c1 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union import numpy as np -import numpy.ma as ma +from numpy import ma as ma from pandas._libs import lib from pandas._typing import Axis, DtypeObj, Scalar diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 895385b170c91..f83a2a82e8989 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -30,11 +30,10 @@ from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries from pandas.core.dtypes.missing import array_equivalent, isna -import pandas.core.algorithms as algos +from pandas.core import algorithms as algos, common as com from pandas.core.arrays import ExtensionArray from pandas.core.arrays.sparse import SparseDtype from pandas.core.base import PandasObject -import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexers import maybe_convert_indices from pandas.core.indexes.api import Index, ensure_index diff --git a/pandas/core/internals/ops.py b/pandas/core/internals/ops.py index fd9a9a5ef6c93..6eedf72726acb 100644 --- a/pandas/core/internals/ops.py +++ b/pandas/core/internals/ops.py @@ -5,8 +5,8 @@ from pandas._typing import ArrayLike if TYPE_CHECKING: - from pandas.core.internals.managers import BlockManager # noqa:F401 from pandas.core.internals.blocks import Block # noqa:F401 + from pandas.core.internals.managers import BlockManager # noqa:F401 def operate_blockwise( diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py index 3379ee56b6ad0..46213b51a188b 100644 --- a/pandas/core/ops/array_ops.py +++ b/pandas/core/ops/array_ops.py @@ -10,7 +10,9 @@ import numpy as np -from pandas._libs import Timedelta, Timestamp, lib, ops as libops +from pandas._libs import Timedelta, Timestamp +from pandas._libs.lib import is_integer, is_scalar as lib_is_scalar, item_from_zerodim +from pandas._libs.ops import scalar_binop, scalar_compare, vec_binop, vec_compare from pandas._typing import ArrayLike from pandas.core.dtypes.cast import ( @@ -50,9 +52,9 @@ def comp_method_OBJECT_ARRAY(op, x, y): if x.shape != y.shape: raise ValueError("Shapes must match", x.shape, y.shape) - result = libops.vec_compare(x.ravel(), y.ravel(), op) + result = vec_compare(x.ravel(), y.ravel(), op) else: - result = libops.scalar_compare(x.ravel(), y, op) + result = scalar_compare(x.ravel(), y, op) return result.reshape(x.shape) @@ -136,7 +138,7 @@ def na_arithmetic_op(left, right, op, is_cmp: bool = False): ------ TypeError : invalid operation """ - import pandas.core.computation.expressions as expressions + from pandas.core.computation import expressions as expressions try: result = expressions.evaluate(op, left, right) @@ -210,7 +212,7 @@ def comparison_op(left: ArrayLike, right: Any, op) -> ArrayLike: lvalues = maybe_upcast_datetimelike_array(left) rvalues = right - rvalues = lib.item_from_zerodim(rvalues) + rvalues = item_from_zerodim(rvalues) if isinstance(rvalues, list): # TODO: same for tuples? rvalues = np.asarray(rvalues) @@ -265,14 +267,14 @@ def na_logical_op(x: np.ndarray, y, op): assert not (is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype)) x = ensure_object(x) y = ensure_object(y) - result = libops.vec_binop(x.ravel(), y.ravel(), op) + result = vec_binop(x.ravel(), y.ravel(), op) else: # let null fall thru - assert lib.is_scalar(y) + assert lib_is_scalar(y) if not isna(y): y = bool(y) try: - result = libops.scalar_binop(x, y, op) + result = scalar_binop(x, y, op) except ( TypeError, ValueError, @@ -322,7 +324,7 @@ def fill_bool(x, left=None): is_self_int_dtype = is_integer_dtype(left.dtype) - right = lib.item_from_zerodim(right) + right = item_from_zerodim(right) if is_list_like(right) and not hasattr(right, "dtype"): # e.g. list, tuple right = construct_1d_object_array_from_listlike(right) @@ -342,7 +344,7 @@ def fill_bool(x, left=None): else: # i.e. scalar - is_other_int_dtype = lib.is_integer(rvalues) + is_other_int_dtype = is_integer(rvalues) # For int vs int `^`, `|`, `&` are bitwise operators and return # integer dtypes. Otherwise these are boolean ops diff --git a/pandas/core/resample.py b/pandas/core/resample.py index bfdfc65723433..b526069ef23ba 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -21,7 +21,7 @@ from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries -import pandas.core.algorithms as algos +from pandas.core import algorithms as algos from pandas.core.base import DataError, ShallowMixin from pandas.core.generic import NDFrame, _shared_docs from pandas.core.groupby.base import GroupByMixin diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 9e8fb643791f2..4e0ec7810b071 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -1,7 +1,6 @@ """ Concat routines. """ - from collections import abc from typing import TYPE_CHECKING, Iterable, List, Mapping, Union, overload @@ -12,11 +11,12 @@ from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries +from pandas.core import common as com from pandas.core.arrays.categorical import ( factorize_from_iterable, factorize_from_iterables, ) -import pandas.core.common as com +from pandas.core.indexes import base as ibase from pandas.core.indexes.api import ( Index, MultiIndex, @@ -25,7 +25,6 @@ get_consensus_names, get_objs_combined_axis, ) -import pandas.core.indexes.base as ibase from pandas.core.internals import concatenate_block_managers if TYPE_CHECKING: diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 1ba6854a79265..1758062c53e22 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -10,8 +10,8 @@ from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.missing import notna +from pandas.core import common as com from pandas.core.arrays import Categorical -import pandas.core.common as com from pandas.core.indexes.api import Index, MultiIndex from pandas.core.reshape.concat import concat from pandas.core.reshape.util import _tile_compat diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 27b331babe692..bf67d2894854e 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1,7 +1,6 @@ """ SQL-style merge routines """ - import copy import datetime from functools import partial @@ -11,8 +10,7 @@ import numpy as np -from pandas._libs import Timedelta, hashtable as libhashtable, lib -import pandas._libs.join as libjoin +from pandas._libs import Timedelta, hashtable as libhashtable, join as libjoin, lib from pandas._typing import ArrayLike, FrameOrSeries from pandas.errors import MergeError from pandas.util._decorators import Appender, Substitution @@ -41,10 +39,8 @@ from pandas.core.dtypes.missing import isna, na_value_for_dtype from pandas import Categorical, Index, MultiIndex -from pandas.core import groupby -import pandas.core.algorithms as algos +from pandas.core import algorithms as algos, common as com, groupby from pandas.core.arrays.categorical import recode_for_categories -import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.frame import _merge_doc from pandas.core.internals import concatenate_block_managers diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index ea5916eff3afa..0eb9a29bf00c6 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -19,7 +19,7 @@ from pandas.core.dtypes.common import is_integer_dtype, is_list_like, is_scalar from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries -import pandas.core.common as com +from pandas.core import common as com from pandas.core.frame import _shared_docs from pandas.core.groupby import Grouper from pandas.core.indexes.api import Index, MultiIndex, get_objs_combined_axis diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 391313fbb5283..b067dfea4287c 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -3,8 +3,7 @@ import numpy as np -import pandas._libs.algos as libalgos -import pandas._libs.reshape as libreshape +from pandas._libs import algos as libalgos, reshape as libreshape from pandas._libs.sparse import IntIndex from pandas.util._decorators import cache_readonly @@ -21,7 +20,7 @@ ) from pandas.core.dtypes.missing import notna -import pandas.core.algorithms as algos +from pandas.core import algorithms as algos from pandas.core.arrays import SparseArray from pandas.core.arrays.categorical import factorize_from_iterable from pandas.core.frame import DataFrame diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index f7723bee532ff..7e73153671ba8 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -25,8 +25,7 @@ from pandas.core.dtypes.missing import isna from pandas import Categorical, Index, IntervalIndex, to_datetime, to_timedelta -import pandas.core.algorithms as algos -import pandas.core.nanops as nanops +from pandas.core import algorithms as algos, nanops as nanops def cut( diff --git a/pandas/core/series.py b/pandas/core/series.py index ef3be854bc3bb..9602f5a15d24a 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -22,8 +22,9 @@ from pandas._config import get_option -from pandas._libs import lib, properties, reshape, tslibs +from pandas._libs import lib, properties, tslibs from pandas._libs.lib import no_default +from pandas._libs.reshape import explode from pandas._typing import ( ArrayLike, Axis, @@ -65,12 +66,11 @@ ) import pandas as pd -from pandas.core import algorithms, base, generic, nanops, ops +from pandas.core import algorithms, base, common as com, generic, nanops, ops from pandas.core.accessor import CachedAccessor from pandas.core.arrays import ExtensionArray from pandas.core.arrays.categorical import CategoricalAccessor from pandas.core.arrays.sparse import SparseAccessor -import pandas.core.common as com from pandas.core.construction import ( create_series_with_explicit_dtype, extract_array, @@ -79,9 +79,9 @@ ) from pandas.core.generic import NDFrame from pandas.core.indexers import deprecate_ndim_indexing, unpack_1tuple +from pandas.core.indexes import base as ibase from pandas.core.indexes.accessors import CombinedDatetimelikeProperties from pandas.core.indexes.api import Float64Index, Index, MultiIndex, ensure_index -import pandas.core.indexes.base as ibase from pandas.core.indexes.datetimes import DatetimeIndex from pandas.core.indexes.period import PeriodIndex from pandas.core.indexes.timedeltas import TimedeltaIndex @@ -91,7 +91,7 @@ from pandas.core.strings import StringMethods from pandas.core.tools.datetimes import to_datetime -import pandas.io.formats.format as fmt +from pandas.io.formats import format as fmt import pandas.plotting if TYPE_CHECKING: @@ -3836,7 +3836,7 @@ def explode(self, ignore_index: bool = False) -> "Series": if not len(self) or not is_object_dtype(self): return self.copy() - values, counts = reshape.explode(np.asarray(self.array)) + values, counts = explode(np.asarray(self.array)) if ignore_index: index = ibase.default_index(len(values)) diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index ee73aa42701b0..7bb6e79c73e4d 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -15,7 +15,7 @@ from pandas.core.dtypes.generic import ABCMultiIndex from pandas.core.dtypes.missing import isna -import pandas.core.algorithms as algorithms +from pandas.core import algorithms as algorithms from pandas.core.construction import extract_array _INT64_MAX = np.iinfo(np.int64).max diff --git a/pandas/core/strings.py b/pandas/core/strings.py index a1db7742916de..c435b0caa47d7 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -7,9 +7,7 @@ import numpy as np -import pandas._libs.lib as lib -import pandas._libs.missing as libmissing -import pandas._libs.ops as libops +from pandas._libs import lib as lib, missing as libmissing, ops as libops from pandas._typing import ArrayLike, Dtype, Scalar from pandas.util._decorators import Appender @@ -155,7 +153,7 @@ def _map_stringarray( an ndarray. """ - from pandas.arrays import IntegerArray, StringArray, BooleanArray + from pandas.arrays import BooleanArray, IntegerArray, StringArray mask = isna(arr) @@ -2186,7 +2184,7 @@ def _wrap_result( returns_string=True, ): - from pandas import Index, Series, MultiIndex + from pandas import Index, MultiIndex, Series # for category, we do the stuff on the categories, so blow it up # to the full series again @@ -2292,7 +2290,7 @@ def _get_series_list(self, others): list of Series Others transformed into list of Series. """ - from pandas import Series, DataFrame + from pandas import DataFrame, Series # self._orig is either Series or Index idx = self._orig if isinstance(self._orig, ABCIndexClass) else self._orig.index diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 0adab143f6052..7aac2f793f61a 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -53,9 +53,10 @@ from pandas.core.indexes.datetimes import DatetimeIndex if TYPE_CHECKING: - from pandas import Series # noqa:F401 from pandas._libs.tslibs.nattype import NaTType # noqa:F401 + from pandas import Series # noqa:F401 + # --------------------------------------------------------------------- # types used in annotations @@ -876,7 +877,7 @@ def _assemble_from_unit_mappings(arg, errors, tz): ------- Series """ - from pandas import to_timedelta, to_numeric, DataFrame + from pandas import DataFrame, to_numeric, to_timedelta arg = DataFrame(arg) if not arg.columns.is_unique: diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index 1b56b6d5a46fa..6684166d3b9de 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -6,7 +6,7 @@ import numpy as np -import pandas._libs.hashing as hashing +from pandas._libs.hashing import hash_object_array from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -275,17 +275,17 @@ def hash_array( # then hash and rename categories. We allow skipping the categorization # when the values are known/likely to be unique. if categorize: - from pandas import factorize, Categorical, Index + from pandas import Categorical, Index, factorize codes, categories = factorize(vals, sort=False) cat = Categorical(codes, Index(categories), ordered=False, fastpath=True) return _hash_categorical(cat, encoding, hash_key) try: - vals = hashing.hash_object_array(vals, hash_key, encoding) + vals = hash_object_array(vals, hash_key, encoding) except TypeError: # we have mixed types - vals = hashing.hash_object_array( + vals = hash_object_array( vals.astype(str).astype(object), hash_key, encoding ) diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 7a2d8e84bec76..c9c23681e5fdf 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -6,7 +6,7 @@ import numpy as np from pandas._libs.tslibs import Timedelta -import pandas._libs.window.aggregations as window_aggregations +from pandas._libs.window.aggregations import ewmcov from pandas._typing import FrameOrSeries, TimedeltaConvertibleTypes from pandas.compat.numpy import function as nv from pandas.util._decorators import Appender, Substitution, doc @@ -14,8 +14,8 @@ from pandas.core.dtypes.common import is_datetime64_ns_dtype from pandas.core.dtypes.generic import ABCDataFrame +from pandas.core import common as common from pandas.core.base import DataError -import pandas.core.common as common from pandas.core.window.common import _doc_template, _shared_docs, zsqrt from pandas.core.window.rolling import _flex_binary_moment, _Rolling @@ -380,7 +380,7 @@ def var(self, bias: bool = False, *args, **kwargs): nv.validate_window_func("var", args, kwargs) def f(arg): - return window_aggregations.ewmcov( + return ewmcov( arg, arg, self.com, self.adjust, self.ignore_na, self.min_periods, bias, ) @@ -424,7 +424,7 @@ def cov( def _get_cov(X, Y): X = self._shallow_copy(X) Y = self._shallow_copy(Y) - cov = window_aggregations.ewmcov( + cov = ewmcov( X._prep_values(), Y._prep_values(), self.com, @@ -476,7 +476,7 @@ def _get_corr(X, Y): Y = self._shallow_copy(Y) def _cov(x, y): - return window_aggregations.ewmcov( + return ewmcov( x, y, self.com, self.adjust, self.ignore_na, self.min_periods, 1, ) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 48953f6a75487..352f78b8a6873 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -11,7 +11,7 @@ import numpy as np from pandas._libs.tslibs import BaseOffset, to_offset -import pandas._libs.window.aggregations as window_aggregations +from pandas._libs.window import aggregations as window_aggregations from pandas._typing import Axis, FrameOrSeries, Scalar from pandas.compat._optional import import_optional_dependency from pandas.compat.numpy import function as nv @@ -35,8 +35,8 @@ ABCTimedeltaIndex, ) +from pandas.core import common as com from pandas.core.base import DataError, PandasObject, SelectionMixin, ShallowMixin -import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexes.api import Index, MultiIndex, ensure_index from pandas.core.util.numba_ import NUMBA_FUNC_CACHE, maybe_use_numba @@ -1044,7 +1044,7 @@ def validate(self): import_optional_dependency( "scipy", extra="Scipy is required to generate window weight." ) - import scipy.signal as sig + from scipy import signal as sig if not isinstance(self.win_type, str): raise ValueError(f"Invalid win_type {self.win_type}") @@ -1119,7 +1119,7 @@ def _get_window( if isinstance(window, (list, tuple, np.ndarray)): return com.asarray_tuplesafe(window).astype(float) elif is_integer(window): - import scipy.signal as sig + from scipy import signal as sig # GH #15662. `False` makes symmetric window, rather than periodic. return sig.get_window(win_type, window, False).astype(float) diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py index 40bff5a75709b..3454c5a38374b 100644 --- a/pandas/io/clipboard/__init__.py +++ b/pandas/io/clipboard/__init__.py @@ -41,7 +41,6 @@ """ __version__ = "1.7.0" - import contextlib import ctypes from ctypes import c_size_t, c_wchar, c_wchar_p, get_errno, sizeof @@ -311,17 +310,17 @@ def init_windows_clipboard(): global HGLOBAL, LPVOID, DWORD, LPCSTR, INT global HWND, HINSTANCE, HMENU, BOOL, UINT, HANDLE from ctypes.wintypes import ( - HGLOBAL, - LPVOID, + BOOL, DWORD, - LPCSTR, - INT, - HWND, + HANDLE, + HGLOBAL, HINSTANCE, HMENU, - BOOL, + HWND, + INT, + LPCSTR, + LPVOID, UINT, - HANDLE, ) windll = ctypes.windll @@ -528,8 +527,8 @@ def determine_clipboard(): # Setup for the MAC OS X platform: if os.name == "mac" or platform.system() == "Darwin": try: - import Foundation # check if pyobjc is installed import AppKit + import Foundation # check if pyobjc is installed except ImportError: return init_osx_pbcopy_clipboard() else: diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 2a12f779230b2..b1bbda4a4b7e0 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -834,8 +834,8 @@ class ExcelFile: from pandas.io.excel._odfreader import _ODFReader from pandas.io.excel._openpyxl import _OpenpyxlReader - from pandas.io.excel._xlrd import _XlrdReader from pandas.io.excel._pyxlsb import _PyxlsbReader + from pandas.io.excel._xlrd import _XlrdReader _engines = { "xlrd": _XlrdReader, diff --git a/pandas/io/excel/_odfreader.py b/pandas/io/excel/_odfreader.py index 85ec9afaaec25..44abaf5d3b3c9 100644 --- a/pandas/io/excel/_odfreader.py +++ b/pandas/io/excel/_odfreader.py @@ -191,9 +191,9 @@ def _get_cell_string_value(self, cell) -> str: Find and decode OpenDocument text:s tags that represent a run length encoded sequence of space characters. """ - from odf.element import Text, Element - from odf.text import S, P + from odf.element import Element, Text from odf.namespaces import TEXTNS + from odf.text import P, S text_p = P().qname text_s = S().qname diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py index 0131240f99cf6..0c397e2cae724 100644 --- a/pandas/io/excel/_odswriter.py +++ b/pandas/io/excel/_odswriter.py @@ -2,7 +2,7 @@ import datetime from typing import Any, DefaultDict, Dict, List, Optional, Tuple, Union -import pandas._libs.json as json +from pandas._libs import json as json from pandas.io.excel._base import ExcelWriter from pandas.io.excel._util import _validate_freeze_panes diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index 0696d82e51f34..03a30cbd62f9a 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -225,7 +225,7 @@ def _convert_to_fill(cls, fill_dict): ------- fill : openpyxl.styles.Fill """ - from openpyxl.styles import PatternFill, GradientFill + from openpyxl.styles import GradientFill, PatternFill _pattern_fill_key_map = { "patternType": "fill_type", diff --git a/pandas/io/excel/_xlrd.py b/pandas/io/excel/_xlrd.py index 8f7d3b1368fc7..af82c15fd6b66 100644 --- a/pandas/io/excel/_xlrd.py +++ b/pandas/io/excel/_xlrd.py @@ -48,11 +48,11 @@ def get_sheet_by_index(self, index): def get_sheet_data(self, sheet, convert_float): from xlrd import ( - xldate, + XL_CELL_BOOLEAN, XL_CELL_DATE, XL_CELL_ERROR, - XL_CELL_BOOLEAN, XL_CELL_NUMBER, + xldate, ) epoch1904 = self.book.datemode diff --git a/pandas/io/excel/_xlsxwriter.py b/pandas/io/excel/_xlsxwriter.py index 85a1bb031f457..876e24bdc315e 100644 --- a/pandas/io/excel/_xlsxwriter.py +++ b/pandas/io/excel/_xlsxwriter.py @@ -1,4 +1,4 @@ -import pandas._libs.json as json +from pandas._libs.json import dumps from pandas.io.excel._base import ExcelWriter from pandas.io.excel._util import _validate_freeze_panes @@ -212,7 +212,7 @@ def write_cells( for cell in cells: val, fmt = self._value_with_fmt(cell.val) - stylekey = json.dumps(cell.style) + stylekey = dumps(cell.style) if fmt: stylekey += fmt diff --git a/pandas/io/excel/_xlwt.py b/pandas/io/excel/_xlwt.py index 78efe77e9fe2d..305fd77814cee 100644 --- a/pandas/io/excel/_xlwt.py +++ b/pandas/io/excel/_xlwt.py @@ -1,4 +1,4 @@ -import pandas._libs.json as json +from pandas._libs.json import dumps from pandas.io.excel._base import ExcelWriter from pandas.io.excel._util import _validate_freeze_panes @@ -54,7 +54,7 @@ def write_cells( for cell in cells: val, fmt = self._value_with_fmt(cell.val) - stylekey = json.dumps(cell.style) + stylekey = dumps(cell.style) if fmt: stylekey += fmt diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index bf4586a4b5b96..914bf0dd23672 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -1,7 +1,6 @@ """ Utilities for conversion to writer-agnostic Excel representation. """ - from functools import reduce import itertools import re @@ -17,7 +16,7 @@ from pandas.core.dtypes.generic import ABCIndex from pandas import DataFrame, Index, MultiIndex, PeriodIndex -import pandas.core.common as com +from pandas.core import common as com from pandas.io.common import stringify_path from pandas.io.formats.css import CSSResolver, CSSWarning diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index fe85eab4bfbf5..8cb34bccbd750 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -2,7 +2,6 @@ Internal module for formatting output data in csv, html, and latex files. This module also applies to display formatting. """ - from contextlib import contextmanager from csv import QUOTE_NONE, QUOTE_NONNUMERIC from datetime import tzinfo @@ -59,10 +58,10 @@ ) from pandas.core.dtypes.missing import isna, notna +from pandas.core import common as com from pandas.core.arrays.datetimes import DatetimeArray from pandas.core.arrays.timedeltas import TimedeltaArray from pandas.core.base import PandasObject -import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexes.api import Index, MultiIndex, PeriodIndex, ensure_index from pandas.core.indexes.datetimes import DatetimeIndex @@ -72,7 +71,7 @@ from pandas.io.formats.printing import adjoin, justify, pprint_thing if TYPE_CHECKING: - from pandas import Series, DataFrame, Categorical + from pandas import Categorical, DataFrame, Series FormattersType = Union[ List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable] diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index d11144938eb26..8352c3cfe1418 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1,7 +1,6 @@ """ Module for applying conditional formatting to DataFrames and Series. """ - from collections import defaultdict from contextlib import contextmanager import copy @@ -33,7 +32,7 @@ import pandas as pd from pandas.api.types import is_dict_like, is_list_like -import pandas.core.common as com +from pandas.core import common as com from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame from pandas.core.indexing import _maybe_numeric_slice, _non_reducing_slice @@ -42,8 +41,7 @@ try: - import matplotlib.pyplot as plt - from matplotlib import colors + from matplotlib import colors, pyplot as plt has_mpl = True except ImportError: diff --git a/pandas/io/html.py b/pandas/io/html.py index 3193f52d239f1..4a2e261da86e1 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -3,7 +3,6 @@ HTML IO. """ - from collections import abc import numbers import os @@ -707,8 +706,8 @@ def _build_doc(self): -------- pandas.io.html._HtmlFrameParser._build_doc """ - from lxml.html import parse, fromstring, HTMLParser from lxml.etree import XMLSyntaxError + from lxml.html import HTMLParser, fromstring, parse parser = HTMLParser(recover=True, encoding=self.encoding) diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index ff37c36962aec..003cbda052286 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -7,7 +7,7 @@ import numpy as np -import pandas._libs.json as json +from pandas._libs.json import dumps, loads from pandas._libs.tslibs import iNaT from pandas._typing import JSONSerializable from pandas.errors import AbstractMethodError @@ -24,9 +24,6 @@ from pandas.io.json._table_schema import build_table_schema, parse_table_schema from pandas.io.parsers import _validate_integer -loads = json.loads -dumps = json.dumps - TABLE_SCHEMA_VERSION = "0.20.0" diff --git a/pandas/io/json/_table_schema.py b/pandas/io/json/_table_schema.py index 84146a5d732e1..7d0fc56bd0aab 100644 --- a/pandas/io/json/_table_schema.py +++ b/pandas/io/json/_table_schema.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optional, cast import warnings -import pandas._libs.json as json +from pandas._libs.json import loads from pandas._typing import DtypeObj, FrameOrSeries, JSONSerializable from pandas.core.dtypes.common import ( @@ -23,13 +23,11 @@ from pandas.core.dtypes.dtypes import CategoricalDtype from pandas import DataFrame -import pandas.core.common as com +from pandas.core import common as com if TYPE_CHECKING: from pandas.core.indexes.multi import MultiIndex # noqa: F401 -loads = json.loads - def as_json_table_type(x: DtypeObj) -> str: """ diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index d4f346f8c1087..74c401aa1359a 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1,7 +1,6 @@ """ Module contains tools for processing files into DataFrames or other objects """ - from collections import abc, defaultdict import csv import datetime @@ -15,9 +14,7 @@ import numpy as np -import pandas._libs.lib as lib -import pandas._libs.ops as libops -import pandas._libs.parsers as parsers +from pandas._libs import lib as lib, ops as libops, parsers as parsers from pandas._libs.parsers import STR_NA_VALUES from pandas._libs.tslibs import parsing from pandas._typing import FilePathOrBuffer, Union diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index b67a1c5781d91..602689636007e 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -48,8 +48,8 @@ concat, isna, ) +from pandas.core import common as com from pandas.core.arrays import Categorical, DatetimeArray, PeriodArray -import pandas.core.common as com from pandas.core.computation.pytables import PyTablesExpr, maybe_expression from pandas.core.indexes.api import ensure_index @@ -57,7 +57,7 @@ from pandas.io.formats.printing import adjoin, pprint_thing if TYPE_CHECKING: - from tables import File, Node, Col # noqa:F401 + from tables import Col, File, Node # noqa:F401 # versioning attribute diff --git a/pandas/io/sas/sas.pyx b/pandas/io/sas/sas.pyx index 0038e39e2ffcc..2c349611725fb 100644 --- a/pandas/io/sas/sas.pyx +++ b/pandas/io/sas/sas.pyx @@ -1,9 +1,9 @@ # cython: profile=False # cython: boundscheck=False, initializedcheck=False from cython import Py_ssize_t - import numpy as np -import pandas.io.sas.sas_constants as const + +from pandas.io.sas import sas_constants as const ctypedef signed long long int64_t ctypedef unsigned char uint8_t diff --git a/pandas/io/sas/sas7bdat.py b/pandas/io/sas/sas7bdat.py index 3d9be7c15726b..8ae1b31e692d8 100644 --- a/pandas/io/sas/sas7bdat.py +++ b/pandas/io/sas/sas7bdat.py @@ -24,8 +24,8 @@ import pandas as pd from pandas.io.common import get_filepath_or_buffer +from pandas.io.sas import sas_constants as const from pandas.io.sas._sas import Parser -import pandas.io.sas.sas_constants as const from pandas.io.sas.sasreader import ReaderBase diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 9177696ca13d6..ada8e8c6cbf6e 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -2,7 +2,6 @@ Collection of query wrappers / abstractions to both facilitate data retrieval and to reduce dependency on DB-specific API. """ - from contextlib import contextmanager from datetime import date, datetime, time from functools import partial @@ -12,7 +11,7 @@ import numpy as np -import pandas._libs.lib as lib +from pandas._libs import lib as lib from pandas.core.dtypes.common import is_datetime64tz_dtype, is_dict_like, is_list_like from pandas.core.dtypes.dtypes import DatetimeTZDtype @@ -937,7 +936,7 @@ def _get_column_names_and_types(self, dtype_mapper): return column_names_and_types def _create_table_setup(self): - from sqlalchemy import Table, Column, PrimaryKeyConstraint + from sqlalchemy import Column, PrimaryKeyConstraint, Table column_names_and_types = self._get_column_names_and_types(self._sqlalchemy_type) @@ -1026,15 +1025,15 @@ def _sqlalchemy_type(self, col): col_type = lib.infer_dtype(col, skipna=True) from sqlalchemy.types import ( + TIMESTAMP, BigInteger, - Integer, - Float, - Text, Boolean, - DateTime, Date, + DateTime, + Float, + Integer, + Text, Time, - TIMESTAMP, ) if col_type == "datetime64" or col_type == "datetime": @@ -1079,7 +1078,7 @@ def _sqlalchemy_type(self, col): return Text def _get_dtype(self, sqltype): - from sqlalchemy.types import Integer, Float, Boolean, DateTime, Date, TIMESTAMP + from sqlalchemy.types import TIMESTAMP, Boolean, Date, DateTime, Float, Integer if isinstance(sqltype, Float): return float @@ -1374,7 +1373,7 @@ def to_sql( dtype = {col_name: dtype for col_name in frame} if dtype is not None: - from sqlalchemy.types import to_instance, TypeEngine + from sqlalchemy.types import TypeEngine, to_instance for col, my_type in dtype.items(): if not isinstance(to_instance(my_type), TypeEngine): diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 45a3818492b44..5e3ca708284ec 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -1775,7 +1775,7 @@ def _get_plot_backend(backend=None): # Because matplotlib is an optional dependency and first-party backend, # we need to attempt an import here to raise an ImportError if needed. try: - import pandas.plotting._matplotlib as module + from pandas.plotting import _matplotlib as module except ImportError: raise ImportError( "matplotlib is required for plotting when the " diff --git a/pandas/plotting/_matplotlib/__init__.py b/pandas/plotting/_matplotlib/__init__.py index 27b1d55fe1bd6..fd9da13d0c102 100644 --- a/pandas/plotting/_matplotlib/__init__.py +++ b/pandas/plotting/_matplotlib/__init__.py @@ -49,7 +49,7 @@ def plot(data, kind, **kwargs): # Importing pyplot at the top of the file (before the converters are # registered) causes problems in matplotlib 2 (converters seem to not # work) - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt if kwargs.pop("reuse_plot", False): ax = kwargs.get("ax") diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index 4b79bef41d025..131349e32a2e5 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -241,7 +241,7 @@ def boxplot( **kwds, ): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt # validate return_type: if return_type not in BoxPlot._valid_return_types: @@ -370,7 +370,7 @@ def boxplot_frame( return_type=None, **kwds, ): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt ax = boxplot( self, diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index 05377e0c240b9..7cca1989462c7 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -4,10 +4,9 @@ import functools from dateutil.relativedelta import relativedelta -import matplotlib.dates as dates +from matplotlib import dates as dates, units as units from matplotlib.ticker import AutoLocator, Formatter, Locator from matplotlib.transforms import nonsingular -import matplotlib.units as units import numpy as np from pandas._libs import lib @@ -25,10 +24,10 @@ ) from pandas import Index, Series, get_option -import pandas.core.common as com +from pandas.core import common as com from pandas.core.indexes.datetimes import date_range from pandas.core.indexes.period import Period, PeriodIndex, period_range -import pandas.core.tools.datetimes as tools +from pandas.core.tools import datetimes as tools # constants HOURS_PER_DAY = 24.0 diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 353bc8a8936a5..5025520fbc626 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -27,7 +27,7 @@ ) from pandas.core.dtypes.missing import isna, notna -import pandas.core.common as com +from pandas.core import common as com from pandas.io.formats.printing import pprint_thing from pandas.plotting._matplotlib.compat import _mpl_ge_3_0_0 @@ -111,7 +111,7 @@ def __init__( **kwds, ): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt self.data = data self.by = by @@ -607,7 +607,7 @@ def _get_ax_legend_handle(self, ax): @cache_readonly def plt(self): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt return plt @@ -708,7 +708,7 @@ def _get_ax(self, i): @classmethod def get_default_ax(cls, ax): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt if ax is None and len(plt.get_fignums()) > 0: with plt.rc_context(): @@ -1149,8 +1149,8 @@ def _plot(cls, ax, x, y, style=None, column_num=None, stacking_id=None, **kwds): @classmethod def _ts_plot(cls, ax, x, data, style=None, **kwds): from pandas.plotting._matplotlib.timeseries import ( - _maybe_resample, _decorate_axes, + _maybe_resample, format_dateaxis, ) diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index ee41479b3c7c9..aaee2b437021b 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -305,7 +305,7 @@ def hist_series( legend: bool = False, **kwds, ): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt if legend and "label" in kwds: raise ValueError("Cannot use both legend and label") diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index bb6530b0f6412..392171a0dabb5 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -1,7 +1,6 @@ import random -import matplotlib.lines as mlines -import matplotlib.patches as patches +from matplotlib import lines as mlines, patches as patches import numpy as np from pandas.core.dtypes.missing import notna @@ -115,7 +114,7 @@ def _get_marker_compat(marker): def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt def normalize(series): a = min(series) @@ -199,7 +198,7 @@ def normalize(series): def andrews_curves( frame, class_column, ax=None, samples=200, color=None, colormap=None, **kwds ): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt def function(amplitudes): def f(t): @@ -258,7 +257,7 @@ def f(t): def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt # TODO: is the failure mentioned below still relevant? # random.sample(ndarray, int) fails on python 3.3, sigh @@ -319,7 +318,7 @@ def parallel_coordinates( sort_labels=False, **kwds, ): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt if axvlines_kwds is None: axvlines_kwds = {"linewidth": 1, "color": "black"} @@ -387,7 +386,7 @@ def parallel_coordinates( def lag_plot(series, lag=1, ax=None, **kwds): # workaround because `c='b'` is hardcoded in matplotlib's scatter method - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt kwds.setdefault("c", plt.rcParams["patch.facecolor"]) @@ -403,7 +402,7 @@ def lag_plot(series, lag=1, ax=None, **kwds): def autocorrelation_plot(series, ax=None, **kwds): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt n = len(series) data = np.asarray(series) diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index 7990bff4f517c..b875557623065 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -1,19 +1,19 @@ # being a bit too dynamic import warnings -import matplotlib.cm as cm +from matplotlib import cm as cm import matplotlib.colors import numpy as np from pandas.core.dtypes.common import is_list_like -import pandas.core.common as com +from pandas.core import common as com def _get_standard_colors( num_colors=None, colormap=None, color_type="default", color=None ): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt if color is None and colormap is not None: if isinstance(colormap, str): diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 8f3571cf13cbc..e390d2b93f25f 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -1,5 +1,4 @@ # TODO: Use the fact that axis can have units to simplify the process - import functools from typing import TYPE_CHECKING, Optional @@ -24,7 +23,7 @@ from pandas.tseries.frequencies import get_period_alias, is_subperiod, is_superperiod if TYPE_CHECKING: - from pandas import Series, Index # noqa:F401 + from pandas import Index, Series # noqa:F401 # --------------------------------------------------------------------- diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index caf2f27de9276..5b9d15c31d8cc 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -2,8 +2,8 @@ from math import ceil import warnings +from matplotlib import ticker as ticker import matplotlib.table -import matplotlib.ticker as ticker import numpy as np from pandas.core.dtypes.common import is_list_like @@ -176,7 +176,7 @@ def _subplots( # Four polar axes plt.subplots(2, 2, subplot_kw=dict(polar=True)) """ - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt if subplot_kw is None: subplot_kw = {} @@ -343,7 +343,7 @@ def _flatten(axes): def _set_ticks_props(axes, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt for ax in _flatten(axes): if xlabelsize is not None: diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index ecd20796b6f21..7ac01e5b10a88 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import api, compat -import pandas._testing as tm +from pandas import _testing as tm, api, compat class Base: @@ -267,9 +266,10 @@ def test_sparsearray(): def test_np(): - import numpy as np import warnings + import numpy as np + with warnings.catch_warnings(): warnings.simplefilter("ignore", FutureWarning) assert (pd.np.arange(0, 10) == np.arange(0, 10)).all() diff --git a/pandas/tests/api/test_types.py b/pandas/tests/api/test_types.py index 31423c03dee34..1ecbb9dfd9b1d 100644 --- a/pandas/tests/api/test_types.py +++ b/pandas/tests/api/test_types.py @@ -1,4 +1,4 @@ -import pandas._testing as tm +from pandas import _testing as tm from pandas.api import types from .test_api import Base diff --git a/pandas/tests/arithmetic/common.py b/pandas/tests/arithmetic/common.py index 755fbd0d9036c..5e45829c2d609 100644 --- a/pandas/tests/arithmetic/common.py +++ b/pandas/tests/arithmetic/common.py @@ -4,8 +4,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, Series -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm def assert_invalid_addsub_type(left, right, msg=None): diff --git a/pandas/tests/arithmetic/conftest.py b/pandas/tests/arithmetic/conftest.py index 8b9e5cd371a90..718ffd680d386 100644 --- a/pandas/tests/arithmetic/conftest.py +++ b/pandas/tests/arithmetic/conftest.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm # ------------------------------------------------------------------ # Helper Functions diff --git a/pandas/tests/arithmetic/test_array_ops.py b/pandas/tests/arithmetic/test_array_ops.py index 53cb10ba9fc5e..99b2604c78ecf 100644 --- a/pandas/tests/arithmetic/test_array_ops.py +++ b/pandas/tests/arithmetic/test_array_ops.py @@ -3,7 +3,7 @@ import numpy as np import pytest -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.ops.array_ops import comparison_op, na_logical_op diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 5dfaea7c77420..c1454e255b1b9 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -24,9 +24,9 @@ Timedelta, TimedeltaIndex, Timestamp, + _testing as tm, date_range, ) -import pandas._testing as tm from pandas.core.arrays import DatetimeArray, TimedeltaArray from pandas.core.ops import roperator from pandas.tests.arithmetic.common import ( diff --git a/pandas/tests/arithmetic/test_interval.py b/pandas/tests/arithmetic/test_interval.py index 50b5fe8e6f6b9..5b416beaf40e3 100644 --- a/pandas/tests/arithmetic/test_interval.py +++ b/pandas/tests/arithmetic/test_interval.py @@ -15,11 +15,11 @@ Series, Timedelta, Timestamp, + _testing as tm, date_range, period_range, timedelta_range, ) -import pandas._testing as tm from pandas.core.arrays import IntervalArray diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index 2155846b271fc..8c35774ca4d46 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -11,8 +11,7 @@ import pytest import pandas as pd -from pandas import Index, Series, Timedelta, TimedeltaIndex -import pandas._testing as tm +from pandas import Index, Series, Timedelta, TimedeltaIndex, _testing as tm from pandas.core import ops diff --git a/pandas/tests/arithmetic/test_object.py b/pandas/tests/arithmetic/test_object.py index c0cb522b516ab..b621511a57f74 100644 --- a/pandas/tests/arithmetic/test_object.py +++ b/pandas/tests/arithmetic/test_object.py @@ -9,8 +9,7 @@ import pytest import pandas as pd -from pandas import Series, Timestamp -import pandas._testing as tm +from pandas import Series, Timestamp, _testing as tm from pandas.core import ops # ------------------------------------------------------------------ diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index 930435074efc1..7602ba7abfcea 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -10,8 +10,7 @@ from pandas.errors import PerformanceWarning import pandas as pd -from pandas import PeriodIndex, Series, TimedeltaIndex, period_range -import pandas._testing as tm +from pandas import PeriodIndex, Series, TimedeltaIndex, _testing as tm, period_range from pandas.core import ops from pandas.core.arrays import TimedeltaArray diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index f94408d657ae5..c6b1f65c318c2 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -16,9 +16,9 @@ Timedelta, TimedeltaIndex, Timestamp, + _testing as tm, timedelta_range, ) -import pandas._testing as tm from pandas.tests.arithmetic.common import ( assert_invalid_addsub_type, assert_invalid_comparison, diff --git a/pandas/tests/arrays/boolean/test_arithmetic.py b/pandas/tests/arrays/boolean/test_arithmetic.py index 1a4ab9799e8e5..00e43be08fe0a 100644 --- a/pandas/tests/arrays/boolean/test_arithmetic.py +++ b/pandas/tests/arrays/boolean/test_arithmetic.py @@ -4,7 +4,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.fixture diff --git a/pandas/tests/arrays/boolean/test_astype.py b/pandas/tests/arrays/boolean/test_astype.py index 57cec70262526..3d74cc2c766ea 100644 --- a/pandas/tests/arrays/boolean/test_astype.py +++ b/pandas/tests/arrays/boolean/test_astype.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_astype(): diff --git a/pandas/tests/arrays/boolean/test_comparison.py b/pandas/tests/arrays/boolean/test_comparison.py index 726b78fbd43bd..9df32972f4ed8 100644 --- a/pandas/tests/arrays/boolean/test_comparison.py +++ b/pandas/tests/arrays/boolean/test_comparison.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.arrays import BooleanArray from pandas.tests.extension.base import BaseOpsUtil diff --git a/pandas/tests/arrays/boolean/test_construction.py b/pandas/tests/arrays/boolean/test_construction.py index 2f5c61304d415..3fd1c985eeead 100644 --- a/pandas/tests/arrays/boolean/test_construction.py +++ b/pandas/tests/arrays/boolean/test_construction.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.arrays import BooleanArray from pandas.core.arrays.boolean import coerce_to_array diff --git a/pandas/tests/arrays/boolean/test_function.py b/pandas/tests/arrays/boolean/test_function.py index 49a832f8dda20..cc3910518edf4 100644 --- a/pandas/tests/arrays/boolean/test_function.py +++ b/pandas/tests/arrays/boolean/test_function.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.fixture diff --git a/pandas/tests/arrays/boolean/test_indexing.py b/pandas/tests/arrays/boolean/test_indexing.py index 6a7daea16963c..cf9f06a948868 100644 --- a/pandas/tests/arrays/boolean/test_indexing.py +++ b/pandas/tests/arrays/boolean/test_indexing.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.mark.parametrize("na", [None, np.nan, pd.NA]) diff --git a/pandas/tests/arrays/boolean/test_logical.py b/pandas/tests/arrays/boolean/test_logical.py index e79262e1b7934..a53e20329585b 100644 --- a/pandas/tests/arrays/boolean/test_logical.py +++ b/pandas/tests/arrays/boolean/test_logical.py @@ -4,7 +4,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.arrays import BooleanArray from pandas.tests.extension.base import BaseOpsUtil diff --git a/pandas/tests/arrays/boolean/test_ops.py b/pandas/tests/arrays/boolean/test_ops.py index 52f602258a049..ec8cc5e1002ed 100644 --- a/pandas/tests/arrays/boolean/test_ops.py +++ b/pandas/tests/arrays/boolean/test_ops.py @@ -1,5 +1,5 @@ import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestUnaryOps: diff --git a/pandas/tests/arrays/categorical/test_algos.py b/pandas/tests/arrays/categorical/test_algos.py index 45e0d503f30e7..647c174a6a016 100644 --- a/pandas/tests/arrays/categorical/test_algos.py +++ b/pandas/tests/arrays/categorical/test_algos.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.mark.parametrize("ordered", [True, False]) diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py index 4bf9b4b40d0b6..36d74e43ccf64 100644 --- a/pandas/tests/arrays/categorical/test_analytics.py +++ b/pandas/tests/arrays/categorical/test_analytics.py @@ -6,8 +6,7 @@ from pandas.compat import PYPY -from pandas import Categorical, Index, NaT, Series, date_range -import pandas._testing as tm +from pandas import Categorical, Index, NaT, Series, _testing as tm, date_range from pandas.api.types import is_scalar diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py index 6fce4b4145ff2..4507bef3c3c5c 100644 --- a/pandas/tests/arrays/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -3,8 +3,14 @@ import numpy as np import pytest -from pandas import Categorical, CategoricalIndex, DataFrame, Index, Series -import pandas._testing as tm +from pandas import ( + Categorical, + CategoricalIndex, + DataFrame, + Index, + Series, + _testing as tm, +) from pandas.core.arrays.categorical import recode_for_categories from pandas.tests.arrays.categorical.common import TestCategorical diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index ca942c9288898..9743143753cf6 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -20,11 +20,11 @@ NaT, Series, Timestamp, + _testing as tm, date_range, period_range, timedelta_range, ) -import pandas._testing as tm class TestCategoricalConstructors: diff --git a/pandas/tests/arrays/categorical/test_dtypes.py b/pandas/tests/arrays/categorical/test_dtypes.py index 47ce9cb4089f9..c69dd474dca46 100644 --- a/pandas/tests/arrays/categorical/test_dtypes.py +++ b/pandas/tests/arrays/categorical/test_dtypes.py @@ -3,8 +3,14 @@ from pandas.core.dtypes.dtypes import CategoricalDtype -from pandas import Categorical, CategoricalIndex, Index, Series, Timestamp -import pandas._testing as tm +from pandas import ( + Categorical, + CategoricalIndex, + Index, + Series, + Timestamp, + _testing as tm, +) class TestCategoricalDtypes: diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index abfae189bb4d7..8eb451a6edba0 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -2,9 +2,15 @@ import pytest import pandas as pd -from pandas import Categorical, CategoricalIndex, Index, PeriodIndex, Series -import pandas._testing as tm -import pandas.core.common as com +from pandas import ( + Categorical, + CategoricalIndex, + Index, + PeriodIndex, + Series, + _testing as tm, +) +from pandas.core import common as com from pandas.tests.arrays.categorical.common import TestCategorical diff --git a/pandas/tests/arrays/categorical/test_missing.py b/pandas/tests/arrays/categorical/test_missing.py index 5309b8827e3f0..0443b8d87a071 100644 --- a/pandas/tests/arrays/categorical/test_missing.py +++ b/pandas/tests/arrays/categorical/test_missing.py @@ -6,8 +6,7 @@ from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd -from pandas import Categorical, DataFrame, Index, Series, isna -import pandas._testing as tm +from pandas import Categorical, DataFrame, Index, Series, _testing as tm, isna class TestCategoricalMissing: diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index 6ea003c122eea..0e2a6d40f7df7 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import Categorical, DataFrame, Series, date_range -import pandas._testing as tm +from pandas import Categorical, DataFrame, Series, _testing as tm, date_range from pandas.tests.arrays.categorical.common import TestCategorical diff --git a/pandas/tests/arrays/categorical/test_replace.py b/pandas/tests/arrays/categorical/test_replace.py index b9ac3ce9a37ae..81494a1ed974b 100644 --- a/pandas/tests/arrays/categorical/test_replace.py +++ b/pandas/tests/arrays/categorical/test_replace.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/arrays/categorical/test_sorting.py b/pandas/tests/arrays/categorical/test_sorting.py index 2a0ef043bf9a9..55abe26e2f743 100644 --- a/pandas/tests/arrays/categorical/test_sorting.py +++ b/pandas/tests/arrays/categorical/test_sorting.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Categorical, Index -import pandas._testing as tm +from pandas import Categorical, Index, _testing as tm class TestCategoricalSort: diff --git a/pandas/tests/arrays/categorical/test_subclass.py b/pandas/tests/arrays/categorical/test_subclass.py index b80d0ff41aba6..d15f4157c27fb 100644 --- a/pandas/tests/arrays/categorical/test_subclass.py +++ b/pandas/tests/arrays/categorical/test_subclass.py @@ -1,5 +1,4 @@ -from pandas import Categorical -import pandas._testing as tm +from pandas import Categorical, _testing as tm class TestCategoricalSubclassing: diff --git a/pandas/tests/arrays/categorical/test_warnings.py b/pandas/tests/arrays/categorical/test_warnings.py index 9e164a250cdb1..e396037974be4 100644 --- a/pandas/tests/arrays/categorical/test_warnings.py +++ b/pandas/tests/arrays/categorical/test_warnings.py @@ -2,7 +2,7 @@ from pandas.util._test_decorators import async_mark -import pandas._testing as tm +from pandas import _testing as tm class TestCategoricalWarnings: diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py index d309f6423e0c1..0a5d2dad0e7a6 100644 --- a/pandas/tests/arrays/integer/test_arithmetic.py +++ b/pandas/tests/arrays/integer/test_arithmetic.py @@ -4,9 +4,9 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm +from pandas.core import ops as ops from pandas.core.arrays import integer_array -import pandas.core.ops as ops # Basic test for the arithmetic array ops # ----------------------------------------------------------------------------- diff --git a/pandas/tests/arrays/integer/test_comparison.py b/pandas/tests/arrays/integer/test_comparison.py index 1767250af09b0..d0583f0ff6a00 100644 --- a/pandas/tests/arrays/integer/test_comparison.py +++ b/pandas/tests/arrays/integer/test_comparison.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.tests.extension.base import BaseOpsUtil diff --git a/pandas/tests/arrays/integer/test_concat.py b/pandas/tests/arrays/integer/test_concat.py index fc24709deb82c..0f1f31859482c 100644 --- a/pandas/tests/arrays/integer/test_concat.py +++ b/pandas/tests/arrays/integer/test_concat.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/arrays/integer/test_construction.py b/pandas/tests/arrays/integer/test_construction.py index 1893c4554bfbf..b80d1d6ad25c6 100644 --- a/pandas/tests/arrays/integer/test_construction.py +++ b/pandas/tests/arrays/integer/test_construction.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.api.types import is_integer from pandas.core.arrays import IntegerArray, integer_array from pandas.core.arrays.integer import Int8Dtype, Int32Dtype, Int64Dtype diff --git a/pandas/tests/arrays/integer/test_dtypes.py b/pandas/tests/arrays/integer/test_dtypes.py index 67efa4cb2ce4a..6a2825c762ec7 100644 --- a/pandas/tests/arrays/integer/test_dtypes.py +++ b/pandas/tests/arrays/integer/test_dtypes.py @@ -4,7 +4,7 @@ from pandas.core.dtypes.generic import ABCIndexClass import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays import integer_array from pandas.core.arrays.integer import Int8Dtype, UInt32Dtype diff --git a/pandas/tests/arrays/integer/test_function.py b/pandas/tests/arrays/integer/test_function.py index a81434339fdae..ac1690493ea99 100644 --- a/pandas/tests/arrays/integer/test_function.py +++ b/pandas/tests/arrays/integer/test_function.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays import integer_array diff --git a/pandas/tests/arrays/integer/test_indexing.py b/pandas/tests/arrays/integer/test_indexing.py index 4b953d699108b..7baf118bf58a0 100644 --- a/pandas/tests/arrays/integer/test_indexing.py +++ b/pandas/tests/arrays/integer/test_indexing.py @@ -1,5 +1,5 @@ import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_array_setitem_nullable_boolean_mask(): diff --git a/pandas/tests/arrays/interval/test_interval.py b/pandas/tests/arrays/interval/test_interval.py index d517eaaec68d2..69c0e038d225b 100644 --- a/pandas/tests/arrays/interval/test_interval.py +++ b/pandas/tests/arrays/interval/test_interval.py @@ -1,8 +1,6 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd from pandas import ( Index, @@ -10,11 +8,12 @@ IntervalIndex, Timedelta, Timestamp, + _testing as tm, date_range, timedelta_range, ) -import pandas._testing as tm from pandas.core.arrays import IntervalArray +from pandas.util import _test_decorators as td @pytest.fixture( @@ -142,6 +141,7 @@ def test_repr(): @pyarrow_skip def test_arrow_extension_type(): import pyarrow as pa + from pandas.core.arrays._arrow_utils import ArrowIntervalType p1 = ArrowIntervalType(pa.int64(), "left") @@ -158,6 +158,7 @@ def test_arrow_extension_type(): @pyarrow_skip def test_arrow_array(): import pyarrow as pa + from pandas.core.arrays._arrow_utils import ArrowIntervalType intervals = pd.interval_range(1, 5, freq=1).array @@ -187,6 +188,7 @@ def test_arrow_array(): @pyarrow_skip def test_arrow_array_missing(): import pyarrow as pa + from pandas.core.arrays._arrow_utils import ArrowIntervalType arr = IntervalArray.from_breaks([0.0, 1.0, 2.0, 3.0]) @@ -221,6 +223,7 @@ def test_arrow_array_missing(): ) def test_arrow_table_roundtrip(breaks): import pyarrow as pa + from pandas.core.arrays._arrow_utils import ArrowIntervalType arr = IntervalArray.from_breaks(breaks) diff --git a/pandas/tests/arrays/interval/test_ops.py b/pandas/tests/arrays/interval/test_ops.py index 9c78c2a48b9ff..31f6c31219efa 100644 --- a/pandas/tests/arrays/interval/test_ops.py +++ b/pandas/tests/arrays/interval/test_ops.py @@ -2,8 +2,7 @@ import numpy as np import pytest -from pandas import Interval, IntervalIndex, Timedelta, Timestamp -import pandas._testing as tm +from pandas import Interval, IntervalIndex, Timedelta, Timestamp, _testing as tm from pandas.core.arrays import IntervalArray diff --git a/pandas/tests/arrays/masked/test_arithmetic.py b/pandas/tests/arrays/masked/test_arithmetic.py index db938c36fe7ae..4612b0d9778a8 100644 --- a/pandas/tests/arrays/masked/test_arithmetic.py +++ b/pandas/tests/arrays/masked/test_arithmetic.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays import ExtensionArray arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_EA_INT_DTYPES] diff --git a/pandas/tests/arrays/masked/test_arrow_compat.py b/pandas/tests/arrays/masked/test_arrow_compat.py index b63bb0fbd9a3b..8c6243c970f18 100644 --- a/pandas/tests/arrays/masked/test_arrow_compat.py +++ b/pandas/tests/arrays/masked/test_arrow_compat.py @@ -1,9 +1,8 @@ import pytest -import pandas.util._test_decorators as td - import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_EA_INT_DTYPES] arrays += [pd.array([True, False, True, None], dtype="boolean")] diff --git a/pandas/tests/arrays/sparse/test_accessor.py b/pandas/tests/arrays/sparse/test_accessor.py index 2a81b94ce779c..40c38be73356b 100644 --- a/pandas/tests/arrays/sparse/test_accessor.py +++ b/pandas/tests/arrays/sparse/test_accessor.py @@ -3,11 +3,10 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays.sparse import SparseArray, SparseDtype +from pandas.util import _test_decorators as td class TestSeriesAccessor: diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py index c9f1dd7f589fc..c7eebbd425e30 100644 --- a/pandas/tests/arrays/sparse/test_arithmetics.py +++ b/pandas/tests/arrays/sparse/test_arithmetics.py @@ -4,7 +4,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core import ops from pandas.core.arrays.sparse import SparseArray, SparseDtype diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 04215bfe1bedb..918186fd18f04 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -6,12 +6,11 @@ import pytest from pandas._libs.sparse import IntIndex -import pandas.util._test_decorators as td import pandas as pd -from pandas import isna -import pandas._testing as tm +from pandas import _testing as tm, isna from pandas.core.arrays.sparse import SparseArray, SparseDtype +from pandas.util import _test_decorators as td @pytest.fixture(params=["integer", "block"]) diff --git a/pandas/tests/arrays/sparse/test_combine_concat.py b/pandas/tests/arrays/sparse/test_combine_concat.py index 0f09af269148b..bd0070256d0e5 100644 --- a/pandas/tests/arrays/sparse/test_combine_concat.py +++ b/pandas/tests/arrays/sparse/test_combine_concat.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays.sparse import SparseArray diff --git a/pandas/tests/arrays/sparse/test_libsparse.py b/pandas/tests/arrays/sparse/test_libsparse.py index a2f861d378e67..d7100f14341a4 100644 --- a/pandas/tests/arrays/sparse/test_libsparse.py +++ b/pandas/tests/arrays/sparse/test_libsparse.py @@ -3,12 +3,11 @@ import numpy as np import pytest -import pandas._libs.sparse as splib -import pandas.util._test_decorators as td +from pandas._libs import sparse as splib -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm from pandas.core.arrays.sparse import BlockIndex, IntIndex, _make_index +from pandas.util import _test_decorators as td TEST_LENGTH = 20 diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index 6f9a1a5be4c43..db010958a2845 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -3,10 +3,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td def test_repr(): diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py index a0525aa511ee2..eddf2f47f0663 100644 --- a/pandas/tests/arrays/test_array.py +++ b/pandas/tests/arrays/test_array.py @@ -8,7 +8,7 @@ from pandas.core.dtypes.base import registry import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.api.extensions import register_extension_dtype from pandas.api.types import is_scalar from pandas.arrays import ( diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index b1ab700427c28..8559d11e1ab31 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -7,7 +7,7 @@ from pandas.compat.numpy import _np_version_under1p18 import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.indexes.datetimes import DatetimeIndex from pandas.core.indexes.period import Period, PeriodIndex diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index 804654451a6d9..10f95bd7d237d 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -9,7 +9,7 @@ from pandas.core.dtypes.dtypes import DatetimeTZDtype import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays import DatetimeArray from pandas.core.arrays.datetimes import sequence_to_dt64ns diff --git a/pandas/tests/arrays/test_numpy.py b/pandas/tests/arrays/test_numpy.py index 86793c4ec50dd..fb81972c3557b 100644 --- a/pandas/tests/arrays/test_numpy.py +++ b/pandas/tests/arrays/test_numpy.py @@ -6,7 +6,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.arrays import PandasArray from pandas.core.arrays.numpy_ import PandasDtype diff --git a/pandas/tests/arrays/test_period.py b/pandas/tests/arrays/test_period.py index 8887dd0278afe..7f1ed92957e7d 100644 --- a/pandas/tests/arrays/test_period.py +++ b/pandas/tests/arrays/test_period.py @@ -3,14 +3,14 @@ from pandas._libs.tslibs import iNaT from pandas._libs.tslibs.period import IncompatibleFrequency -import pandas.util._test_decorators as td from pandas.core.dtypes.base import registry from pandas.core.dtypes.dtypes import PeriodDtype import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays import PeriodArray, period_array +from pandas.util import _test_decorators as td # ---------------------------------------------------------------------------- # Dtype @@ -359,6 +359,7 @@ def test_arrow_extension_type(): ) def test_arrow_array(data, freq): import pyarrow as pa + from pandas.core.arrays._arrow_utils import ArrowPeriodType periods = period_array(data, freq=freq) @@ -384,6 +385,7 @@ def test_arrow_array(data, freq): @pyarrow_skip def test_arrow_array_missing(): import pyarrow as pa + from pandas.core.arrays._arrow_utils import ArrowPeriodType arr = PeriodArray([1, 2, 3], freq="D") @@ -399,6 +401,7 @@ def test_arrow_array_missing(): @pyarrow_skip def test_arrow_table_roundtrip(): import pyarrow as pa + from pandas.core.arrays._arrow_utils import ArrowPeriodType arr = PeriodArray([1, 2, 3], freq="D") diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py index c86b4f71ee592..6a3d8f25f3499 100644 --- a/pandas/tests/arrays/test_timedeltas.py +++ b/pandas/tests/arrays/test_timedeltas.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays import TimedeltaArray diff --git a/pandas/tests/base/test_constructors.py b/pandas/tests/base/test_constructors.py index 697364fc87175..e6dcb90ccbc21 100644 --- a/pandas/tests/base/test_constructors.py +++ b/pandas/tests/base/test_constructors.py @@ -7,8 +7,7 @@ from pandas.compat import PYPY import pandas as pd -from pandas import DataFrame, Index, Series -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm from pandas.core.accessor import PandasDelegate from pandas.core.base import NoNewAttributesMixin, PandasObject diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py index b688a048cbe8e..a3c06f2dafe69 100644 --- a/pandas/tests/base/test_conversion.py +++ b/pandas/tests/base/test_conversion.py @@ -5,8 +5,7 @@ from pandas.core.dtypes.dtypes import DatetimeTZDtype import pandas as pd -from pandas import CategoricalIndex, Series, Timedelta, Timestamp -import pandas._testing as tm +from pandas import CategoricalIndex, Series, Timedelta, Timestamp, _testing as tm from pandas.core.arrays import ( DatetimeArray, IntervalArray, diff --git a/pandas/tests/base/test_drop_duplicates.py b/pandas/tests/base/test_drop_duplicates.py index 4032890b4db18..ace39bec637cd 100644 --- a/pandas/tests/base/test_drop_duplicates.py +++ b/pandas/tests/base/test_drop_duplicates.py @@ -3,7 +3,7 @@ import numpy as np import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_drop_duplicates_series_vs_dataframe(): diff --git a/pandas/tests/base/test_factorize.py b/pandas/tests/base/test_factorize.py index 415a8b7e4362f..2be2bb1b893af 100644 --- a/pandas/tests/base/test_factorize.py +++ b/pandas/tests/base/test_factorize.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.mark.parametrize("sort", [True, False]) diff --git a/pandas/tests/base/test_fillna.py b/pandas/tests/base/test_fillna.py index c6f58af4c5c3a..641944cd18641 100644 --- a/pandas/tests/base/test_fillna.py +++ b/pandas/tests/base/test_fillna.py @@ -2,7 +2,6 @@ Though Index.fillna and Series.fillna has separate impl, test here to confirm these works as the same """ - import numpy as np import pytest @@ -11,8 +10,7 @@ from pandas.core.dtypes.common import needs_i8_conversion from pandas.core.dtypes.generic import ABCMultiIndex -from pandas import Index -import pandas._testing as tm +from pandas import Index, _testing as tm from pandas.tests.base.common import allow_na_ops diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py index 78a830c7f43d8..7f506c5985d93 100644 --- a/pandas/tests/base/test_misc.py +++ b/pandas/tests/base/test_misc.py @@ -13,8 +13,7 @@ ) import pandas as pd -from pandas import DataFrame, Index, IntervalIndex, Series -import pandas._testing as tm +from pandas import DataFrame, Index, IntervalIndex, Series, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/base/test_transpose.py b/pandas/tests/base/test_transpose.py index 5ba278368834c..ddbfad3ccf5a1 100644 --- a/pandas/tests/base/test_transpose.py +++ b/pandas/tests/base/test_transpose.py @@ -1,7 +1,7 @@ import numpy as np import pytest -import pandas._testing as tm +from pandas import _testing as tm def test_transpose(index_or_series_obj): diff --git a/pandas/tests/base/test_unique.py b/pandas/tests/base/test_unique.py index e5592cef59592..1970fc3782196 100644 --- a/pandas/tests/base/test_unique.py +++ b/pandas/tests/base/test_unique.py @@ -6,7 +6,7 @@ from pandas.core.dtypes.common import is_datetime64tz_dtype, needs_i8_conversion import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.tests.base.common import allow_na_ops diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py index de04c30432e6f..16df47e203b2d 100644 --- a/pandas/tests/base/test_value_counts.py +++ b/pandas/tests/base/test_value_counts.py @@ -19,8 +19,8 @@ Series, Timedelta, TimedeltaIndex, + _testing as tm, ) -import pandas._testing as tm from pandas.tests.base.common import allow_na_ops diff --git a/pandas/tests/computation/test_compat.py b/pandas/tests/computation/test_compat.py index b3fbd8c17d8bf..1fae055ffe666 100644 --- a/pandas/tests/computation/test_compat.py +++ b/pandas/tests/computation/test_compat.py @@ -5,8 +5,8 @@ from pandas.compat._optional import VERSIONS import pandas as pd +from pandas.core.computation import expr as expr from pandas.core.computation.engines import _engines -import pandas.core.computation.expr as expr def test_compat(): diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 08d8d5ca342b7..f9cd0cea8753a 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -10,17 +10,14 @@ import pytest from pandas.errors import PerformanceWarning -import pandas.util._test_decorators as td from pandas.core.dtypes.common import is_bool, is_list_like, is_scalar import pandas as pd -from pandas import DataFrame, Series, compat, date_range -import pandas._testing as tm -from pandas.core.computation import pytables +from pandas import DataFrame, Series, _testing as tm, compat, date_range +from pandas.core.computation import expr as expr, pytables from pandas.core.computation.check import _NUMEXPR_VERSION from pandas.core.computation.engines import NumExprClobberingError, _engines -import pandas.core.computation.expr as expr from pandas.core.computation.expr import ( BaseExprVisitor, PandasExprVisitor, @@ -34,6 +31,7 @@ _special_case_arith_ops_syms, _unary_math_ops, ) +from pandas.util import _test_decorators as td @pytest.fixture( diff --git a/pandas/tests/dtypes/cast/test_construct_from_scalar.py b/pandas/tests/dtypes/cast/test_construct_from_scalar.py index ed272cef3e7ba..b7360de38d631 100644 --- a/pandas/tests/dtypes/cast/test_construct_from_scalar.py +++ b/pandas/tests/dtypes/cast/test_construct_from_scalar.py @@ -1,8 +1,7 @@ from pandas.core.dtypes.cast import construct_1d_arraylike_from_scalar from pandas.core.dtypes.dtypes import CategoricalDtype -from pandas import Categorical -import pandas._testing as tm +from pandas import Categorical, _testing as tm def test_cast_1d_array_like_from_scalar_categorical(): diff --git a/pandas/tests/dtypes/cast/test_construct_ndarray.py b/pandas/tests/dtypes/cast/test_construct_ndarray.py index fe271392122a2..fcd50c0f53242 100644 --- a/pandas/tests/dtypes/cast/test_construct_ndarray.py +++ b/pandas/tests/dtypes/cast/test_construct_ndarray.py @@ -3,7 +3,7 @@ from pandas.core.dtypes.cast import construct_1d_ndarray_preserving_na -import pandas._testing as tm +from pandas import _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/dtypes/cast/test_downcast.py b/pandas/tests/dtypes/cast/test_downcast.py index d6e6ed3022b75..7ab1498c09f5b 100644 --- a/pandas/tests/dtypes/cast/test_downcast.py +++ b/pandas/tests/dtypes/cast/test_downcast.py @@ -5,8 +5,7 @@ from pandas.core.dtypes.cast import maybe_downcast_to_dtype -from pandas import DatetimeIndex, Series, Timestamp -import pandas._testing as tm +from pandas import DatetimeIndex, Series, Timestamp, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/dtypes/cast/test_infer_dtype.py b/pandas/tests/dtypes/cast/test_infer_dtype.py index 70d38aad951cc..fc1a99bd478f2 100644 --- a/pandas/tests/dtypes/cast/test_infer_dtype.py +++ b/pandas/tests/dtypes/cast/test_infer_dtype.py @@ -17,9 +17,9 @@ Series, Timedelta, Timestamp, + _testing as tm, date_range, ) -import pandas._testing as tm @pytest.fixture(params=[True, False]) diff --git a/pandas/tests/dtypes/cast/test_upcast.py b/pandas/tests/dtypes/cast/test_upcast.py index f9227a4e78a79..353caa4fefb47 100644 --- a/pandas/tests/dtypes/cast/test_upcast.py +++ b/pandas/tests/dtypes/cast/test_upcast.py @@ -3,8 +3,7 @@ from pandas.core.dtypes.cast import maybe_upcast_putmask -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm @pytest.mark.parametrize("result", [Series([10, 11, 12]), [10, 11, 12], (10, 11, 12)]) diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index ce12718e48d0d..d2526a4c7a01e 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -4,10 +4,8 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - +from pandas.core.dtypes import common as com from pandas.core.dtypes.cast import astype_nansafe -import pandas.core.dtypes.common as com from pandas.core.dtypes.dtypes import ( CategoricalDtype, CategoricalDtypeType, @@ -18,8 +16,9 @@ from pandas.core.dtypes.missing import isna import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.arrays import SparseArray +from pandas.util import _test_decorators as td # EA & Actual Dtypes diff --git a/pandas/tests/dtypes/test_concat.py b/pandas/tests/dtypes/test_concat.py index 5a9ad732792ea..e4804928e7e1d 100644 --- a/pandas/tests/dtypes/test_concat.py +++ b/pandas/tests/dtypes/test_concat.py @@ -1,10 +1,16 @@ import pytest -import pandas.core.dtypes.concat as _concat +from pandas.core.dtypes import concat as _concat import pandas as pd -from pandas import DatetimeIndex, Period, PeriodIndex, Series, TimedeltaIndex -import pandas._testing as tm +from pandas import ( + DatetimeIndex, + Period, + PeriodIndex, + Series, + TimedeltaIndex, + _testing as tm, +) @pytest.mark.parametrize( diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index a58dc5e5ec74a..de0b0dd6a68a1 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -32,9 +32,9 @@ DatetimeIndex, IntervalIndex, Series, + _testing as tm, date_range, ) -import pandas._testing as tm from pandas.core.arrays.sparse import SparseArray, SparseDtype diff --git a/pandas/tests/dtypes/test_generic.py b/pandas/tests/dtypes/test_generic.py index e51b0546b0cee..09524b94291e3 100644 --- a/pandas/tests/dtypes/test_generic.py +++ b/pandas/tests/dtypes/test_generic.py @@ -5,7 +5,7 @@ from pandas.core.dtypes import generic as gt import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestABCClasses: diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index e40a12f7bc8d1..2aa3a625a3122 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -17,7 +17,6 @@ import pytz from pandas._libs import lib, missing as libmissing -import pandas.util._test_decorators as td from pandas.core.dtypes import inference from pandas.core.dtypes.common import ( @@ -49,9 +48,10 @@ Timedelta, TimedeltaIndex, Timestamp, + _testing as tm, ) -import pandas._testing as tm from pandas.core.arrays import IntegerArray +from pandas.util import _test_decorators as td @pytest.fixture(params=[True, False], ids=str) diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index 04dde08de082d..c539f7fb7b511 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -21,8 +21,15 @@ ) import pandas as pd -from pandas import DatetimeIndex, Float64Index, NaT, Series, TimedeltaIndex, date_range -import pandas._testing as tm +from pandas import ( + DatetimeIndex, + Float64Index, + NaT, + Series, + TimedeltaIndex, + _testing as tm, + date_range, +) now = pd.Timestamp.now() utcnow = pd.Timestamp.now("UTC") diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py index 7841360e568ed..263cf0d8b1a44 100644 --- a/pandas/tests/extension/arrow/test_bool.py +++ b/pandas/tests/extension/arrow/test_bool.py @@ -4,7 +4,7 @@ from pandas.compat import PY37 import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.tests.extension import base pytest.importorskip("pyarrow", minversion="0.13.0") diff --git a/pandas/tests/extension/base/base.py b/pandas/tests/extension/base/base.py index 97d8e7c66dbdb..511d352be46a5 100644 --- a/pandas/tests/extension/base/base.py +++ b/pandas/tests/extension/base/base.py @@ -1,4 +1,4 @@ -import pandas._testing as tm +from pandas import _testing as tm class BaseExtensionTests: diff --git a/pandas/tests/extension/base/groupby.py b/pandas/tests/extension/base/groupby.py index 94d0ef7bbea84..78cebd85713a3 100644 --- a/pandas/tests/extension/base/groupby.py +++ b/pandas/tests/extension/base/groupby.py @@ -1,7 +1,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from .base import BaseExtensionTests diff --git a/pandas/tests/extension/base/interface.py b/pandas/tests/extension/base/interface.py index 9ae4b01508d79..6bfb168247d63 100644 --- a/pandas/tests/extension/base/interface.py +++ b/pandas/tests/extension/base/interface.py @@ -4,7 +4,7 @@ from pandas.core.dtypes.dtypes import ExtensionDtype import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from .base import BaseExtensionTests diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index 5e1cf30efd534..d8d535d7d3603 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -6,7 +6,7 @@ from pandas.core.dtypes.common import is_bool_dtype import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.sorting import nargsort from .base import BaseExtensionTests diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py index a5969ef961bab..ba315a5c72cfe 100644 --- a/pandas/tests/extension/base/missing.py +++ b/pandas/tests/extension/base/missing.py @@ -1,7 +1,7 @@ import numpy as np import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from .base import BaseExtensionTests diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py index 359acf230ce14..84eddff69c450 100644 --- a/pandas/tests/extension/base/ops.py +++ b/pandas/tests/extension/base/ops.py @@ -3,7 +3,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core import ops from .base import BaseExtensionTests diff --git a/pandas/tests/extension/base/reduce.py b/pandas/tests/extension/base/reduce.py index 6f433d659575a..303bf07c5b76a 100644 --- a/pandas/tests/extension/base/reduce.py +++ b/pandas/tests/extension/base/reduce.py @@ -3,7 +3,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from .base import BaseExtensionTests diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py index a4e6fc0f78cbb..7ce45707f4e25 100644 --- a/pandas/tests/extension/base/setitem.py +++ b/pandas/tests/extension/base/setitem.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from .base import BaseExtensionTests diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 233b658d29782..4195be7c1453b 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -6,7 +6,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.tests.extension import base from .array import DecimalArray, DecimalDtype, make_data, to_decimal diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 74ca341e27bf8..6a47a76fa78ac 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -4,7 +4,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.tests.extension import base from .array import JSONArray, JSONDtype, make_data diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py index 8acbeaf0b8170..dccb3593780c3 100644 --- a/pandas/tests/extension/test_boolean.py +++ b/pandas/tests/extension/test_boolean.py @@ -17,7 +17,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays.boolean import BooleanDtype from pandas.tests.extension import base diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index f7b572a70073a..0715bce62ea6e 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -19,8 +19,7 @@ import pytest import pandas as pd -from pandas import Categorical, CategoricalIndex, Timestamp -import pandas._testing as tm +from pandas import Categorical, CategoricalIndex, Timestamp, _testing as tm from pandas.api.types import CategoricalDtype from pandas.tests.extension import base diff --git a/pandas/tests/extension/test_common.py b/pandas/tests/extension/test_common.py index e43650c291200..c7d138675edc8 100644 --- a/pandas/tests/extension/test_common.py +++ b/pandas/tests/extension/test_common.py @@ -5,7 +5,7 @@ from pandas.core.dtypes.common import is_extension_array_dtype import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays import ExtensionArray diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py index 725533765ca2c..16aa2c6eb9382 100644 --- a/pandas/tests/extension/test_integer.py +++ b/pandas/tests/extension/test_integer.py @@ -19,7 +19,7 @@ from pandas.core.dtypes.common import is_extension_array_dtype import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays import integer_array from pandas.core.arrays.integer import ( Int8Dtype, diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 78000c0252375..31a712299cb41 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -4,7 +4,7 @@ from pandas.compat.numpy import _np_version_under1p16 import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays.numpy_ import PandasArray, PandasDtype from . import base diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index b411ca1c482a4..635f1a4b4abe9 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -6,8 +6,7 @@ from pandas.core.dtypes.common import is_object_dtype import pandas as pd -from pandas import SparseDtype -import pandas._testing as tm +from pandas import SparseDtype, _testing as tm from pandas.arrays import SparseArray from pandas.tests.extension import base diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py index 3a32278e2a4b1..c5c3e2e44753c 100644 --- a/pandas/tests/frame/apply/test_frame_apply.py +++ b/pandas/tests/frame/apply/test_frame_apply.py @@ -10,8 +10,15 @@ from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd -from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range, notna -import pandas._testing as tm +from pandas import ( + DataFrame, + MultiIndex, + Series, + Timestamp, + _testing as tm, + date_range, + notna, +) from pandas.core.apply import frame_apply from pandas.core.base import SpecificationError diff --git a/pandas/tests/frame/conftest.py b/pandas/tests/frame/conftest.py index 486d140849159..188d81ddfb957 100644 --- a/pandas/tests/frame/conftest.py +++ b/pandas/tests/frame/conftest.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import DataFrame, NaT, date_range -import pandas._testing as tm +from pandas import DataFrame, NaT, _testing as tm, date_range @pytest.fixture(params=product([True, False], [True, False])) diff --git a/pandas/tests/frame/indexing/test_at.py b/pandas/tests/frame/indexing/test_at.py index 9c2d88f1589c2..415e927e87abe 100644 --- a/pandas/tests/frame/indexing/test_at.py +++ b/pandas/tests/frame/indexing/test_at.py @@ -1,7 +1,7 @@ from datetime import datetime, timezone import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_at_timezone(): diff --git a/pandas/tests/frame/indexing/test_categorical.py b/pandas/tests/frame/indexing/test_categorical.py index 314de5bdd8146..af102b6e8ebb9 100644 --- a/pandas/tests/frame/indexing/test_categorical.py +++ b/pandas/tests/frame/indexing/test_categorical.py @@ -4,8 +4,7 @@ from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd -from pandas import Categorical, DataFrame, Index, Series -import pandas._testing as tm +from pandas import Categorical, DataFrame, Index, Series, _testing as tm class TestDataFrameIndexingCategorical: diff --git a/pandas/tests/frame/indexing/test_datetime.py b/pandas/tests/frame/indexing/test_datetime.py index 1937a4c380dc9..61264a5ec59c4 100644 --- a/pandas/tests/frame/indexing/test_datetime.py +++ b/pandas/tests/frame/indexing/test_datetime.py @@ -1,6 +1,5 @@ import pandas as pd -from pandas import DataFrame, Index, Series, date_range, notna -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm, date_range, notna class TestDataFrameIndexingDatetimeWithTZ: diff --git a/pandas/tests/frame/indexing/test_get.py b/pandas/tests/frame/indexing/test_get.py index 5f2651eec683c..b6076b8a62af7 100644 --- a/pandas/tests/frame/indexing/test_get.py +++ b/pandas/tests/frame/indexing/test_get.py @@ -1,7 +1,6 @@ import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm class TestGet: diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index d27487dfb8aaa..4679841c4f249 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -16,11 +16,11 @@ MultiIndex, Series, Timestamp, + _testing as tm, date_range, isna, notna, ) -import pandas._testing as tm import pandas.core.common as com from pandas.core.indexing import IndexingError diff --git a/pandas/tests/frame/indexing/test_insert.py b/pandas/tests/frame/indexing/test_insert.py index 622c93d1c2fdc..18856011505b4 100644 --- a/pandas/tests/frame/indexing/test_insert.py +++ b/pandas/tests/frame/indexing/test_insert.py @@ -6,8 +6,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index -import pandas._testing as tm +from pandas import DataFrame, Index, _testing as tm class TestDataFrameInsert: diff --git a/pandas/tests/frame/indexing/test_mask.py b/pandas/tests/frame/indexing/test_mask.py index 23f3a18881782..a2e7b0982d89d 100644 --- a/pandas/tests/frame/indexing/test_mask.py +++ b/pandas/tests/frame/indexing/test_mask.py @@ -1,11 +1,9 @@ """ Tests for DataFrame.mask; tests DataFrame.where as a side-effect. """ - import numpy as np -from pandas import DataFrame, isna -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, isna class TestDataFrameMask: diff --git a/pandas/tests/frame/indexing/test_take.py b/pandas/tests/frame/indexing/test_take.py index 3b59d3cf10658..e6b8ac1d7ff87 100644 --- a/pandas/tests/frame/indexing/test_take.py +++ b/pandas/tests/frame/indexing/test_take.py @@ -1,6 +1,6 @@ import pytest -import pandas._testing as tm +from pandas import _testing as tm class TestDataFrameTake: diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index d114a3178b686..e9cbca10a7be2 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -6,8 +6,15 @@ from pandas.core.dtypes.common import is_scalar import pandas as pd -from pandas import DataFrame, DatetimeIndex, Series, Timestamp, date_range, isna -import pandas._testing as tm +from pandas import ( + DataFrame, + DatetimeIndex, + Series, + Timestamp, + _testing as tm, + date_range, + isna, +) @pytest.fixture(params=["default", "float_string", "mixed_float", "mixed_int"]) diff --git a/pandas/tests/frame/indexing/test_xs.py b/pandas/tests/frame/indexing/test_xs.py index 71b40585f0c2f..01be0f4530f2b 100644 --- a/pandas/tests/frame/indexing/test_xs.py +++ b/pandas/tests/frame/indexing/test_xs.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.tseries.offsets import BDay diff --git a/pandas/tests/frame/methods/test_align.py b/pandas/tests/frame/methods/test_align.py index d19b59debfdea..498b9107cb0f7 100644 --- a/pandas/tests/frame/methods/test_align.py +++ b/pandas/tests/frame/methods/test_align.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, Series -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm class TestDataFrameAlign: diff --git a/pandas/tests/frame/methods/test_append.py b/pandas/tests/frame/methods/test_append.py index 9fc3629e794e2..2cebb2a319b56 100644 --- a/pandas/tests/frame/methods/test_append.py +++ b/pandas/tests/frame/methods/test_append.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series, Timestamp -import pandas._testing as tm +from pandas import DataFrame, Series, Timestamp, _testing as tm class TestDataFrameAppend: diff --git a/pandas/tests/frame/methods/test_asfreq.py b/pandas/tests/frame/methods/test_asfreq.py index 40b0ec0c0d811..ba011ad9d4420 100644 --- a/pandas/tests/frame/methods/test_asfreq.py +++ b/pandas/tests/frame/methods/test_asfreq.py @@ -2,8 +2,7 @@ import numpy as np -from pandas import DataFrame, DatetimeIndex, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, DatetimeIndex, Series, _testing as tm, date_range from pandas.tseries import offsets diff --git a/pandas/tests/frame/methods/test_asof.py b/pandas/tests/frame/methods/test_asof.py index 70b42976c95a7..7d56fc7f2907a 100644 --- a/pandas/tests/frame/methods/test_asof.py +++ b/pandas/tests/frame/methods/test_asof.py @@ -8,11 +8,11 @@ Period, Series, Timestamp, + _testing as tm, date_range, period_range, to_datetime, ) -import pandas._testing as tm @pytest.fixture diff --git a/pandas/tests/frame/methods/test_assign.py b/pandas/tests/frame/methods/test_assign.py index 0ae501d43e742..8cc33198dc80f 100644 --- a/pandas/tests/frame/methods/test_assign.py +++ b/pandas/tests/frame/methods/test_assign.py @@ -1,7 +1,6 @@ import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm class TestAssign: diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index b0fd0496ea81e..b664919f11210 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -14,11 +14,11 @@ Timedelta, Timestamp, UInt64Index, + _testing as tm, concat, date_range, option_context, ) -import pandas._testing as tm from pandas.core.arrays import integer_array diff --git a/pandas/tests/frame/methods/test_at_time.py b/pandas/tests/frame/methods/test_at_time.py index ac98d632c5dcd..5d710ca0a45a6 100644 --- a/pandas/tests/frame/methods/test_at_time.py +++ b/pandas/tests/frame/methods/test_at_time.py @@ -4,8 +4,7 @@ import pytest import pytz -from pandas import DataFrame, date_range -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, date_range class TestAtTime: diff --git a/pandas/tests/frame/methods/test_between_time.py b/pandas/tests/frame/methods/test_between_time.py index 19e802d0fa663..52e7b18bb3803 100644 --- a/pandas/tests/frame/methods/test_between_time.py +++ b/pandas/tests/frame/methods/test_between_time.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import DataFrame, date_range -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, date_range class TestBetweenTime: diff --git a/pandas/tests/frame/methods/test_clip.py b/pandas/tests/frame/methods/test_clip.py index ca62b56664518..9903ecc981a2e 100644 --- a/pandas/tests/frame/methods/test_clip.py +++ b/pandas/tests/frame/methods/test_clip.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm class TestDataFrameClip: diff --git a/pandas/tests/frame/methods/test_combine.py b/pandas/tests/frame/methods/test_combine.py index bc6a67e4e1f32..66aa8a1bd8a9a 100644 --- a/pandas/tests/frame/methods/test_combine.py +++ b/pandas/tests/frame/methods/test_combine.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestCombine: diff --git a/pandas/tests/frame/methods/test_combine_first.py b/pandas/tests/frame/methods/test_combine_first.py index 78f265d32f8df..fd1d477ad5e5c 100644 --- a/pandas/tests/frame/methods/test_combine_first.py +++ b/pandas/tests/frame/methods/test_combine_first.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, Series -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm class TestDataFrameCombineFirst: diff --git a/pandas/tests/frame/methods/test_compare.py b/pandas/tests/frame/methods/test_compare.py index 468811eba0d39..c90cec390e657 100644 --- a/pandas/tests/frame/methods/test_compare.py +++ b/pandas/tests/frame/methods/test_compare.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.mark.parametrize("align_axis", [0, 1, "index", "columns"]) diff --git a/pandas/tests/frame/methods/test_count.py b/pandas/tests/frame/methods/test_count.py index 13a93e3efc48c..a3129231b7c65 100644 --- a/pandas/tests/frame/methods/test_count.py +++ b/pandas/tests/frame/methods/test_count.py @@ -1,5 +1,4 @@ -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm class TestDataFrameCount: diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py index d3548b639572d..838b1ddd1954e 100644 --- a/pandas/tests/frame/methods/test_cov_corr.py +++ b/pandas/tests/frame/methods/test_cov_corr.py @@ -3,11 +3,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Series, isna -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, isna +from pandas.util import _test_decorators as td class TestDataFrameCov: diff --git a/pandas/tests/frame/methods/test_describe.py b/pandas/tests/frame/methods/test_describe.py index 0b70bead375da..81e088feec7f9 100644 --- a/pandas/tests/frame/methods/test_describe.py +++ b/pandas/tests/frame/methods/test_describe.py @@ -1,8 +1,7 @@ import numpy as np import pandas as pd -from pandas import Categorical, DataFrame, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import Categorical, DataFrame, Series, Timestamp, _testing as tm, date_range class TestDataFrameDescribe: diff --git a/pandas/tests/frame/methods/test_diff.py b/pandas/tests/frame/methods/test_diff.py index 45f134a93a23a..8cf73257cca63 100644 --- a/pandas/tests/frame/methods/test_diff.py +++ b/pandas/tests/frame/methods/test_diff.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, Timestamp, _testing as tm, date_range class TestDataFrameDiff: diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index aa44a2427dc8f..1a2fe57430920 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -6,8 +6,7 @@ from pandas.errors import PerformanceWarning import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, Timestamp -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/frame/methods/test_drop_duplicates.py b/pandas/tests/frame/methods/test_drop_duplicates.py index cebec215a0d9d..0e8334d30cf9b 100644 --- a/pandas/tests/frame/methods/test_drop_duplicates.py +++ b/pandas/tests/frame/methods/test_drop_duplicates.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm @pytest.mark.parametrize("subset", ["a", ["a"], ["a", "B"]]) diff --git a/pandas/tests/frame/methods/test_droplevel.py b/pandas/tests/frame/methods/test_droplevel.py index 517905cf23259..6ef1cdec474bf 100644 --- a/pandas/tests/frame/methods/test_droplevel.py +++ b/pandas/tests/frame/methods/test_droplevel.py @@ -1,5 +1,4 @@ -from pandas import DataFrame, Index, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, _testing as tm class TestDropLevel: diff --git a/pandas/tests/frame/methods/test_duplicated.py b/pandas/tests/frame/methods/test_duplicated.py index 7a1c16adc2a09..59b6cf5b93178 100644 --- a/pandas/tests/frame/methods/test_duplicated.py +++ b/pandas/tests/frame/methods/test_duplicated.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import DataFrame, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, date_range @pytest.mark.parametrize("subset", ["a", ["a"], ["a", "B"]]) diff --git a/pandas/tests/frame/methods/test_explode.py b/pandas/tests/frame/methods/test_explode.py index 2bbe8ac2d5b81..3db9e6cd91a88 100644 --- a/pandas/tests/frame/methods/test_explode.py +++ b/pandas/tests/frame/methods/test_explode.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_error(): diff --git a/pandas/tests/frame/methods/test_filter.py b/pandas/tests/frame/methods/test_filter.py index 569b2fe21d1c2..66780efaad74c 100644 --- a/pandas/tests/frame/methods/test_filter.py +++ b/pandas/tests/frame/methods/test_filter.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm class TestDataFrameFilter: diff --git a/pandas/tests/frame/methods/test_first_and_last.py b/pandas/tests/frame/methods/test_first_and_last.py index 2b3756969acca..4ce1b93f11df1 100644 --- a/pandas/tests/frame/methods/test_first_and_last.py +++ b/pandas/tests/frame/methods/test_first_and_last.py @@ -3,8 +3,7 @@ """ import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm class TestFirst: diff --git a/pandas/tests/frame/methods/test_head_tail.py b/pandas/tests/frame/methods/test_head_tail.py index 93763bc12ce0d..2df3974b38578 100644 --- a/pandas/tests/frame/methods/test_head_tail.py +++ b/pandas/tests/frame/methods/test_head_tail.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm def test_head_tail(float_frame): diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py index ddb5723e7bd3e..8d17f3c79bed7 100644 --- a/pandas/tests/frame/methods/test_interpolate.py +++ b/pandas/tests/frame/methods/test_interpolate.py @@ -1,10 +1,8 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - -from pandas import DataFrame, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, date_range +from pandas.util import _test_decorators as td class TestDataFrameInterpolate: diff --git a/pandas/tests/frame/methods/test_isin.py b/pandas/tests/frame/methods/test_isin.py index 35d45bd00131b..0e7052ea071bc 100644 --- a/pandas/tests/frame/methods/test_isin.py +++ b/pandas/tests/frame/methods/test_isin.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, Series, _testing as tm class TestDataFrameIsIn: diff --git a/pandas/tests/frame/methods/test_nlargest.py b/pandas/tests/frame/methods/test_nlargest.py index 4ce474230b686..d9b3979e82462 100644 --- a/pandas/tests/frame/methods/test_nlargest.py +++ b/pandas/tests/frame/methods/test_nlargest.py @@ -8,7 +8,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.fixture diff --git a/pandas/tests/frame/methods/test_pct_change.py b/pandas/tests/frame/methods/test_pct_change.py index 8f3f37fb9fff7..6b99799251ccb 100644 --- a/pandas/tests/frame/methods/test_pct_change.py +++ b/pandas/tests/frame/methods/test_pct_change.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm class TestDataFramePctChange: diff --git a/pandas/tests/frame/methods/test_pop.py b/pandas/tests/frame/methods/test_pop.py index fccb3f10dde45..9c38448ad8ce6 100644 --- a/pandas/tests/frame/methods/test_pop.py +++ b/pandas/tests/frame/methods/test_pop.py @@ -1,5 +1,4 @@ -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm class TestDataFramePop: diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index 0b8f1e0495155..ba95f484ae1e5 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series, Timestamp -import pandas._testing as tm +from pandas import DataFrame, Series, Timestamp, _testing as tm class TestDataFrameQuantile: diff --git a/pandas/tests/frame/methods/test_rank.py b/pandas/tests/frame/methods/test_rank.py index bab2db3192b4a..95236de3be07d 100644 --- a/pandas/tests/frame/methods/test_rank.py +++ b/pandas/tests/frame/methods/test_rank.py @@ -3,10 +3,8 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm +from pandas.util import _test_decorators as td class TestRank: diff --git a/pandas/tests/frame/methods/test_reindex_like.py b/pandas/tests/frame/methods/test_reindex_like.py index ce68ec28eec3d..e53d155a41f73 100644 --- a/pandas/tests/frame/methods/test_reindex_like.py +++ b/pandas/tests/frame/methods/test_reindex_like.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm class TestDataFrameReindexLike: diff --git a/pandas/tests/frame/methods/test_rename.py b/pandas/tests/frame/methods/test_rename.py index eb908e9472fe2..9fa202eeb6014 100644 --- a/pandas/tests/frame/methods/test_rename.py +++ b/pandas/tests/frame/methods/test_rename.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, _testing as tm class TestRename: diff --git a/pandas/tests/frame/methods/test_rename_axis.py b/pandas/tests/frame/methods/test_rename_axis.py index 3339119841813..1067d304da696 100644 --- a/pandas/tests/frame/methods/test_rename_axis.py +++ b/pandas/tests/frame/methods/test_rename_axis.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, _testing as tm class TestDataFrameRenameAxis: diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index a3f056dbf9648..2690da878e055 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -7,8 +7,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import DataFrame, Index, Series, Timestamp, _testing as tm, date_range @pytest.fixture diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index da4bfa9be4881..fb88f58baa497 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -12,9 +12,9 @@ RangeIndex, Series, Timestamp, + _testing as tm, date_range, ) -import pandas._testing as tm class TestResetIndex: diff --git a/pandas/tests/frame/methods/test_round.py b/pandas/tests/frame/methods/test_round.py index 3051f27882fb8..60cc33956e888 100644 --- a/pandas/tests/frame/methods/test_round.py +++ b/pandas/tests/frame/methods/test_round.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, date_range class TestDataFrameRound: diff --git a/pandas/tests/frame/methods/test_select_dtypes.py b/pandas/tests/frame/methods/test_select_dtypes.py index fe7baebcf0cf7..b925042963bdd 100644 --- a/pandas/tests/frame/methods/test_select_dtypes.py +++ b/pandas/tests/frame/methods/test_select_dtypes.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Timestamp -import pandas._testing as tm +from pandas import DataFrame, Timestamp, _testing as tm class TestSelectDtypes: diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py index ebe7eabd53b46..1bcc42c2acdc1 100644 --- a/pandas/tests/frame/methods/test_set_index.py +++ b/pandas/tests/frame/methods/test_set_index.py @@ -3,8 +3,15 @@ import numpy as np import pytest -from pandas import DataFrame, DatetimeIndex, Index, MultiIndex, Series, date_range -import pandas._testing as tm +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + MultiIndex, + Series, + _testing as tm, + date_range, +) class TestSetIndex: diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py index 9ec029a6c4304..bdb7feb2fff70 100644 --- a/pandas/tests/frame/methods/test_shift.py +++ b/pandas/tests/frame/methods/test_shift.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, Series, date_range, offsets -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm, date_range, offsets class TestDataFrameShift: diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index 5216c3be116e0..e5a633bfd357c 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -2,8 +2,15 @@ import pytest import pandas as pd -from pandas import CategoricalDtype, DataFrame, Index, IntervalIndex, MultiIndex, Series -import pandas._testing as tm +from pandas import ( + CategoricalDtype, + DataFrame, + Index, + IntervalIndex, + MultiIndex, + Series, + _testing as tm, +) class TestDataFrameSortIndex: diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index c60e7e3b1bdb6..48fcb4809693f 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import Categorical, DataFrame, NaT, Timestamp, date_range -import pandas._testing as tm +from pandas import Categorical, DataFrame, NaT, Timestamp, _testing as tm, date_range class TestDataFrameSortValues: diff --git a/pandas/tests/frame/methods/test_to_dict.py b/pandas/tests/frame/methods/test_to_dict.py index f1656b46cf356..bae57b8793b7a 100644 --- a/pandas/tests/frame/methods/test_to_dict.py +++ b/pandas/tests/frame/methods/test_to_dict.py @@ -5,8 +5,7 @@ import pytest import pytz -from pandas import DataFrame, Series, Timestamp -import pandas._testing as tm +from pandas import DataFrame, Series, Timestamp, _testing as tm class TestDataFrameToDict: diff --git a/pandas/tests/frame/methods/test_to_period.py b/pandas/tests/frame/methods/test_to_period.py index 051461b6c554d..ae814f3cb9bc7 100644 --- a/pandas/tests/frame/methods/test_to_period.py +++ b/pandas/tests/frame/methods/test_to_period.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, date_range, period_range -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, date_range, period_range class TestToPeriod: diff --git a/pandas/tests/frame/methods/test_to_records.py b/pandas/tests/frame/methods/test_to_records.py index d9c999c9119f4..cb5bf7bd891fe 100644 --- a/pandas/tests/frame/methods/test_to_records.py +++ b/pandas/tests/frame/methods/test_to_records.py @@ -9,9 +9,9 @@ MultiIndex, Series, Timestamp, + _testing as tm, date_range, ) -import pandas._testing as tm class TestDataFrameToRecords: diff --git a/pandas/tests/frame/methods/test_to_timestamp.py b/pandas/tests/frame/methods/test_to_timestamp.py index ae7d2827e05a6..13964cd62a1f0 100644 --- a/pandas/tests/frame/methods/test_to_timestamp.py +++ b/pandas/tests/frame/methods/test_to_timestamp.py @@ -7,11 +7,11 @@ DataFrame, DatetimeIndex, Timedelta, + _testing as tm, date_range, period_range, to_datetime, ) -import pandas._testing as tm class TestToTimestamp: diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py index a5fe5f3a6d5e4..418de30a5d426 100644 --- a/pandas/tests/frame/methods/test_transpose.py +++ b/pandas/tests/frame/methods/test_transpose.py @@ -1,7 +1,7 @@ import numpy as np import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestTranspose: diff --git a/pandas/tests/frame/methods/test_truncate.py b/pandas/tests/frame/methods/test_truncate.py index 674f482c478a0..5f0d44de35e5d 100644 --- a/pandas/tests/frame/methods/test_truncate.py +++ b/pandas/tests/frame/methods/test_truncate.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestDataFrameTruncate: diff --git a/pandas/tests/frame/methods/test_tz_convert.py b/pandas/tests/frame/methods/test_tz_convert.py index d2ab7a386a92d..a36a02f3c4c54 100644 --- a/pandas/tests/frame/methods/test_tz_convert.py +++ b/pandas/tests/frame/methods/test_tz_convert.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, MultiIndex, date_range -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, _testing as tm, date_range class TestTZConvert: diff --git a/pandas/tests/frame/methods/test_tz_localize.py b/pandas/tests/frame/methods/test_tz_localize.py index 1d4e26a6999b7..64d2879225cdc 100644 --- a/pandas/tests/frame/methods/test_tz_localize.py +++ b/pandas/tests/frame/methods/test_tz_localize.py @@ -1,5 +1,4 @@ -from pandas import DataFrame, date_range -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, date_range class TestTZLocalize: diff --git a/pandas/tests/frame/methods/test_update.py b/pandas/tests/frame/methods/test_update.py index d9de026dbf4e9..6027c604ab51f 100644 --- a/pandas/tests/frame/methods/test_update.py +++ b/pandas/tests/frame/methods/test_update.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, date_range class TestDataFrameUpdate: diff --git a/pandas/tests/frame/methods/test_value_counts.py b/pandas/tests/frame/methods/test_value_counts.py index c409b0bbe6fa9..be47345b2a30b 100644 --- a/pandas/tests/frame/methods/test_value_counts.py +++ b/pandas/tests/frame/methods/test_value_counts.py @@ -1,7 +1,7 @@ import numpy as np import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_data_frame_value_counts_unsorted(): diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 486855f5c37cd..82621c08f82c6 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -18,11 +18,11 @@ IntervalIndex, Series, Timestamp, + _testing as tm, cut, date_range, to_datetime, ) -import pandas._testing as tm class TestDataFrameAlterAxes: diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 9d6b9f39a0578..d75e2dea8d351 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -5,8 +5,6 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd from pandas import ( Categorical, @@ -14,15 +12,15 @@ MultiIndex, Series, Timestamp, + _testing as tm, date_range, isna, notna, to_datetime, to_timedelta, ) -import pandas._testing as tm -import pandas.core.algorithms as algorithms -import pandas.core.nanops as nanops +from pandas.core import algorithms as algorithms, nanops as nanops +from pandas.util import _test_decorators as td def assert_stat_op_calc( @@ -287,7 +285,7 @@ def test_stat_op_api(self, float_frame, float_string_frame): assert_stat_op_api("median", float_frame, float_string_frame) try: - from scipy.stats import skew, kurtosis # noqa:F401 + from scipy.stats import kurtosis, skew # noqa:F401 assert_stat_op_api("skew", float_frame, float_string_frame) assert_stat_op_api("kurt", float_frame, float_string_frame) @@ -370,7 +368,7 @@ def kurt(x): ) try: - from scipy import skew, kurtosis # noqa:F401 + from scipy import kurtosis, skew # noqa:F401 assert_stat_op_calc("skew", skewness, float_frame_with_na) assert_stat_op_calc("kurt", kurt, float_frame_with_na) diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 2b79fc8cd3406..2b34f7c431490 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -10,8 +10,15 @@ from pandas.util._test_decorators import async_mark, skip_if_no import pandas as pd -from pandas import Categorical, DataFrame, Series, compat, date_range, timedelta_range -import pandas._testing as tm +from pandas import ( + Categorical, + DataFrame, + Series, + _testing as tm, + compat, + date_range, + timedelta_range, +) class TestDataFrameMisc: diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index e17357e9845b5..06aadb410d6a9 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -8,9 +8,8 @@ import pytz import pandas as pd -from pandas import DataFrame, MultiIndex, Series -import pandas._testing as tm -import pandas.core.common as com +from pandas import DataFrame, MultiIndex, Series, _testing as tm +from pandas.core import common as com from pandas.core.computation.expressions import _MIN_ELEMENTS, _NUMEXPR_INSTALLED from pandas.tests.frame.common import _check_mixed_float, _check_mixed_int diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index b68e20bee63fc..5a19023640e09 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -4,8 +4,16 @@ import pytest import pandas as pd -from pandas import Categorical, DataFrame, Index, MultiIndex, Series, date_range, isna -import pandas._testing as tm +from pandas import ( + Categorical, + DataFrame, + Index, + MultiIndex, + Series, + _testing as tm, + date_range, + isna, +) class TestDataFrameSelectReindex: diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index c9fec3215d57f..5a76b5ed248c1 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -11,11 +11,11 @@ DataFrame, Series, Timestamp, + _testing as tm, compat, date_range, option_context, ) -import pandas._testing as tm from pandas.core.arrays import IntervalArray, integer_array from pandas.core.internals import ObjectBlock from pandas.core.internals.blocks import IntBlock diff --git a/pandas/tests/frame/test_combine_concat.py b/pandas/tests/frame/test_combine_concat.py index 7eba2b873c4f4..73a3103bed854 100644 --- a/pandas/tests/frame/test_combine_concat.py +++ b/pandas/tests/frame/test_combine_concat.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import DataFrame, Index, Series, Timestamp, _testing as tm, date_range class TestDataFrameConcat: diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index a4ed548264d39..328444272d4ae 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -5,8 +5,8 @@ import re import numpy as np -import numpy.ma as ma -import numpy.ma.mrecords as mrecords +from numpy import ma as ma +from numpy.ma import mrecords as mrecords import pytest import pytz @@ -29,10 +29,10 @@ Series, Timedelta, Timestamp, + _testing as tm, date_range, isna, ) -import pandas._testing as tm from pandas.arrays import IntervalArray, PeriodArray, SparseArray from pandas.core.construction import create_series_with_explicit_dtype diff --git a/pandas/tests/frame/test_cumulative.py b/pandas/tests/frame/test_cumulative.py index 248f3500c41df..655d982b022c2 100644 --- a/pandas/tests/frame/test_cumulative.py +++ b/pandas/tests/frame/test_cumulative.py @@ -5,11 +5,9 @@ -------- tests.series.test_cumulative """ - import numpy as np -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm class TestDataFrameCumulativeOps: diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index f3e3ef9bae5c6..05021d3a0f9b9 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -7,8 +7,14 @@ from pandas.core.dtypes.dtypes import DatetimeTZDtype import pandas as pd -from pandas import DataFrame, Series, Timestamp, date_range, option_context -import pandas._testing as tm +from pandas import ( + DataFrame, + Series, + Timestamp, + _testing as tm, + date_range, + option_context, +) def _check_cast(df, v): diff --git a/pandas/tests/frame/test_join.py b/pandas/tests/frame/test_join.py index 4d6e675c6765f..7ef8f965fef48 100644 --- a/pandas/tests/frame/test_join.py +++ b/pandas/tests/frame/test_join.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, period_range -import pandas._testing as tm +from pandas import DataFrame, Index, _testing as tm, period_range @pytest.fixture diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index 9bf5d24085697..6d929e076a99d 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import Categorical, DataFrame, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import Categorical, DataFrame, Series, Timestamp, _testing as tm, date_range from pandas.tests.frame.common import _check_mixed_float diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index a8b76f4d85f49..840731a307778 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, MultiIndex, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, Series, _testing as tm, date_range class TestDataFrameNonuniqueIndexes: diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index fede1ca23a8ce..68b654bca2bab 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -6,8 +6,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm class TestDataFrameUnaryOperators: diff --git a/pandas/tests/frame/test_period.py b/pandas/tests/frame/test_period.py index c378194b9e2b2..60946330993ad 100644 --- a/pandas/tests/frame/test_period.py +++ b/pandas/tests/frame/test_period.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import DataFrame, Index, PeriodIndex, period_range -import pandas._testing as tm +from pandas import DataFrame, Index, PeriodIndex, _testing as tm, period_range class TestPeriodIndex: diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index 628b955a1de92..e252320a1eecc 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -4,12 +4,10 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm, date_range from pandas.core.computation.check import _NUMEXPR_INSTALLED +from pandas.util import _test_decorators as td PARSERS = "python", "pandas" ENGINES = "python", pytest.param("numexpr", marks=td.skip_if_no_ne) diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py index 6d786d9580542..d32a05a1397b4 100644 --- a/pandas/tests/frame/test_repr_info.py +++ b/pandas/tests/frame/test_repr_info.py @@ -9,13 +9,13 @@ Categorical, DataFrame, Series, + _testing as tm, date_range, option_context, period_range, ) -import pandas._testing as tm -import pandas.io.formats.format as fmt +from pandas.io.formats import format as fmt class TestDataFrameReprInfoEtc: diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index 6a8f1e7c1aca2..2821a90698af4 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -5,8 +5,16 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Period, Series, Timedelta, date_range -import pandas._testing as tm +from pandas import ( + DataFrame, + Index, + MultiIndex, + Period, + Series, + Timedelta, + _testing as tm, + date_range, +) class TestDataFrameReshape: diff --git a/pandas/tests/frame/test_sort_values_level_as_str.py b/pandas/tests/frame/test_sort_values_level_as_str.py index 40526ab27ac9a..34625c0c8ea02 100644 --- a/pandas/tests/frame/test_sort_values_level_as_str.py +++ b/pandas/tests/frame/test_sort_values_level_as_str.py @@ -3,8 +3,7 @@ from pandas.errors import PerformanceWarning -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm @pytest.fixture diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py index 2b462d5a10c51..39e429c3d25b9 100644 --- a/pandas/tests/frame/test_subclass.py +++ b/pandas/tests/frame/test_subclass.py @@ -1,11 +1,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm +from pandas.util import _test_decorators as td class TestDataFrameSubclassing: diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index 63361789b8e50..e16321f7437ea 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -1,8 +1,7 @@ import numpy as np import pandas as pd -from pandas import DataFrame, date_range, to_datetime -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, date_range, to_datetime class TestDataFrameTimeSeriesMethods: diff --git a/pandas/tests/frame/test_timezones.py b/pandas/tests/frame/test_timezones.py index dfd4fb1855383..51e190fe8834d 100644 --- a/pandas/tests/frame/test_timezones.py +++ b/pandas/tests/frame/test_timezones.py @@ -8,8 +8,7 @@ from pandas.core.dtypes.dtypes import DatetimeTZDtype import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.core.indexes.datetimes import date_range diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index db7347bb863a5..6c62ba7e23d3b 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -14,12 +14,12 @@ MultiIndex, Series, Timestamp, + _testing as tm, date_range, read_csv, to_datetime, ) -import pandas._testing as tm -import pandas.core.common as com +from pandas.core import common as com from pandas.io.common import get_handle diff --git a/pandas/tests/generic/methods/test_dot.py b/pandas/tests/generic/methods/test_dot.py index ecbec6b06e923..2cbc5a9fe0006 100644 --- a/pandas/tests/generic/methods/test_dot.py +++ b/pandas/tests/generic/methods/test_dot.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm class DotSharedTests: diff --git a/pandas/tests/generic/methods/test_first_valid_index.py b/pandas/tests/generic/methods/test_first_valid_index.py index bca3452c3c458..2c099432494a1 100644 --- a/pandas/tests/generic/methods/test_first_valid_index.py +++ b/pandas/tests/generic/methods/test_first_valid_index.py @@ -4,8 +4,7 @@ import numpy as np import pytest -from pandas import DataFrame, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, date_range class TestFirstValidIndex: diff --git a/pandas/tests/generic/methods/test_reorder_levels.py b/pandas/tests/generic/methods/test_reorder_levels.py index 8bb6417e56659..4d36bee328fe5 100644 --- a/pandas/tests/generic/methods/test_reorder_levels.py +++ b/pandas/tests/generic/methods/test_reorder_levels.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, Series, _testing as tm class TestReorderLevels: diff --git a/pandas/tests/generic/methods/test_set_axis.py b/pandas/tests/generic/methods/test_set_axis.py index 278d43ef93d2f..bab2b32c79788 100644 --- a/pandas/tests/generic/methods/test_set_axis.py +++ b/pandas/tests/generic/methods/test_set_axis.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm class SharedSetAxisTests: diff --git a/pandas/tests/generic/test_frame.py b/pandas/tests/generic/test_frame.py index 31501f20db453..9ae7dd1327cef 100644 --- a/pandas/tests/generic/test_frame.py +++ b/pandas/tests/generic/test_frame.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import DataFrame, MultiIndex, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, Series, _testing as tm, date_range from .test_generic import Generic diff --git a/pandas/tests/generic/test_series.py b/pandas/tests/generic/test_series.py index 07c02330d85ce..17b93eb372f3a 100644 --- a/pandas/tests/generic/test_series.py +++ b/pandas/tests/generic/test_series.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import MultiIndex, Series, date_range -import pandas._testing as tm +from pandas import MultiIndex, Series, _testing as tm, date_range from .test_generic import Generic diff --git a/pandas/tests/generic/test_to_xarray.py b/pandas/tests/generic/test_to_xarray.py index ab56a752f7e90..7f0f2fba12b76 100644 --- a/pandas/tests/generic/test_to_xarray.py +++ b/pandas/tests/generic/test_to_xarray.py @@ -1,11 +1,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm +from pandas.util import _test_decorators as td class TestDataFrameToXArray: diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 40a20c8210052..8683d71936317 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -12,8 +12,7 @@ from pandas.core.dtypes.common import is_integer_dtype import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, concat -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm, concat from pandas.core.base import SpecificationError from pandas.core.groupby.grouper import Grouping diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index 5ddda264642de..ff9081c44c975 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -1,13 +1,20 @@ """ test cython .agg behavior """ - import numpy as np import pytest import pandas as pd -from pandas import DataFrame, Index, NaT, Series, Timedelta, Timestamp, bdate_range -import pandas._testing as tm +from pandas import ( + DataFrame, + Index, + NaT, + Series, + Timedelta, + Timestamp, + _testing as tm, + bdate_range, +) from pandas.core.groupby.groupby import DataError diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py index 690694b0e66f5..629fea2e67b11 100644 --- a/pandas/tests/groupby/aggregate/test_numba.py +++ b/pandas/tests/groupby/aggregate/test_numba.py @@ -2,11 +2,11 @@ import pytest from pandas.errors import NumbaUtilError -import pandas.util._test_decorators as td from pandas import DataFrame, option_context import pandas._testing as tm from pandas.core.util.numba_ import NUMBA_FUNC_CACHE +from pandas.util import _test_decorators as td @td.skip_if_no("numba", "0.46.0") diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py index 264cf40dc6984..f1158fb5d3058 100644 --- a/pandas/tests/groupby/aggregate/test_other.py +++ b/pandas/tests/groupby/aggregate/test_other.py @@ -1,7 +1,6 @@ """ test all other .agg behavior """ - import datetime as dt from functools import partial @@ -15,10 +14,10 @@ MultiIndex, PeriodIndex, Series, + _testing as tm, date_range, period_range, ) -import pandas._testing as tm from pandas.core.base import SpecificationError from pandas.io.formats.printing import pprint_thing diff --git a/pandas/tests/groupby/conftest.py b/pandas/tests/groupby/conftest.py index 0b9721968a881..3446a93e1eb13 100644 --- a/pandas/tests/groupby/conftest.py +++ b/pandas/tests/groupby/conftest.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, _testing as tm from pandas.core.groupby.base import reduction_kernels, transformation_kernels diff --git a/pandas/tests/groupby/test_allowlist.py b/pandas/tests/groupby/test_allowlist.py index 0fd66cc047017..21e36c73cfa41 100644 --- a/pandas/tests/groupby/test_allowlist.py +++ b/pandas/tests/groupby/test_allowlist.py @@ -2,14 +2,12 @@ test methods relating to generic function evaluation the so-called white/black lists """ - from string import ascii_lowercase import numpy as np import pytest -from pandas import DataFrame, Index, MultiIndex, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm, date_range from pandas.core.groupby.base import ( groupby_other_methods, reduction_kernels, diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index 5a1268bfb03db..df7893a9e2680 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, bdate_range -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm, bdate_range def test_apply_issues(): diff --git a/pandas/tests/groupby/test_apply_mutate.py b/pandas/tests/groupby/test_apply_mutate.py index 529f76bf692ce..71d5399838be0 100644 --- a/pandas/tests/groupby/test_apply_mutate.py +++ b/pandas/tests/groupby/test_apply_mutate.py @@ -1,7 +1,7 @@ import numpy as np import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_mutate_groups(): diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py index f20eed4575e91..34afc5e897208 100644 --- a/pandas/tests/groupby/test_bin_groupby.py +++ b/pandas/tests/groupby/test_bin_groupby.py @@ -1,13 +1,13 @@ import numpy as np import pytest -from pandas._libs import groupby, lib, reduction as libreduction +from pandas._libs import groupby, lib +from pandas._libs.reduction import SeriesBinGrouper, SeriesGrouper from pandas.core.dtypes.common import ensure_int64 import pandas as pd -from pandas import Series, isna -import pandas._testing as tm +from pandas import Series, _testing as tm, isna def test_series_grouper(): @@ -16,7 +16,7 @@ def test_series_grouper(): labels = np.array([-1, -1, -1, 0, 0, 0, 1, 1, 1, 1], dtype=np.int64) - grouper = libreduction.SeriesGrouper(obj, np.mean, labels, 2, dummy) + grouper = SeriesGrouper(obj, np.mean, labels, 2, dummy) result, counts = grouper.get_result() expected = np.array([obj[3:6].mean(), obj[6:].mean()]) @@ -33,7 +33,7 @@ def test_series_grouper_requires_nonempty_raises(): labels = np.array([-1, -1, -1, 0, 0, 0, 1, 1, 1, 1], dtype=np.int64) with pytest.raises(ValueError, match="SeriesGrouper requires non-empty `series`"): - libreduction.SeriesGrouper(dummy, np.mean, labels, 2, dummy) + SeriesGrouper(dummy, np.mean, labels, 2, dummy) def test_series_bin_grouper(): @@ -42,7 +42,7 @@ def test_series_bin_grouper(): bins = np.array([3, 6]) - grouper = libreduction.SeriesBinGrouper(obj, np.mean, bins, dummy) + grouper = SeriesBinGrouper(obj, np.mean, bins, dummy) result, counts = grouper.get_result() expected = np.array([obj[:3].mean(), obj[3:6].mean(), obj[6:].mean()]) diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 7e4513da37dc9..072bdafee4bad 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -14,9 +14,9 @@ MultiIndex, Series, _np_version_under1p17, + _testing as tm, qcut, ) -import pandas._testing as tm def cartesian_product_for_groupers(result, args, names): diff --git a/pandas/tests/groupby/test_counting.py b/pandas/tests/groupby/test_counting.py index 997d9b006c802..c239551fc49d2 100644 --- a/pandas/tests/groupby/test_counting.py +++ b/pandas/tests/groupby/test_counting.py @@ -13,9 +13,9 @@ Series, Timedelta, Timestamp, + _testing as tm, date_range, ) -import pandas._testing as tm class TestCounting: diff --git a/pandas/tests/groupby/test_filters.py b/pandas/tests/groupby/test_filters.py index c16ad812eb634..410cbcf6f27df 100644 --- a/pandas/tests/groupby/test_filters.py +++ b/pandas/tests/groupby/test_filters.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series, Timestamp -import pandas._testing as tm +from pandas import DataFrame, Series, Timestamp, _testing as tm def test_filter_series(): diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index e693962e57ac3..2f54628d9f9da 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -7,9 +7,17 @@ from pandas.errors import UnsupportedFunctionCall import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range, isna -import pandas._testing as tm -import pandas.core.nanops as nanops +from pandas import ( + DataFrame, + Index, + MultiIndex, + Series, + Timestamp, + _testing as tm, + date_range, + isna, +) +from pandas.core import nanops as nanops from pandas.util import _test_decorators as td diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index ebce5b0ef0a66..24ec46aee88c7 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -8,10 +8,18 @@ from pandas.errors import PerformanceWarning import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range, read_csv -import pandas._testing as tm +from pandas import ( + DataFrame, + Index, + MultiIndex, + Series, + Timestamp, + _testing as tm, + date_range, + read_csv, +) +from pandas.core import common as com from pandas.core.base import SpecificationError -import pandas.core.common as com def test_repr(): diff --git a/pandas/tests/groupby/test_groupby_dropna.py b/pandas/tests/groupby/test_groupby_dropna.py index 1a525d306e9f5..b25c7bfcaf84d 100644 --- a/pandas/tests/groupby/test_groupby_dropna.py +++ b/pandas/tests/groupby/test_groupby_dropna.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas.testing as tm +from pandas import testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/groupby/test_groupby_subclass.py b/pandas/tests/groupby/test_groupby_subclass.py index 7271911c5f80f..4acfc0a8fcab0 100644 --- a/pandas/tests/groupby/test_groupby_subclass.py +++ b/pandas/tests/groupby/test_groupby_subclass.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index efcd22f9c0c82..350fc7dbea375 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -1,5 +1,4 @@ """ test where we are determining what we are grouping, or getting groups """ - import numpy as np import pytest @@ -11,9 +10,9 @@ MultiIndex, Series, Timestamp, + _testing as tm, date_range, ) -import pandas._testing as tm from pandas.core.groupby.grouper import Grouping # selection diff --git a/pandas/tests/groupby/test_index_as_string.py b/pandas/tests/groupby/test_index_as_string.py index 971a447b84cae..54183ac036861 100644 --- a/pandas/tests/groupby/test_index_as_string.py +++ b/pandas/tests/groupby/test_index_as_string.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.fixture(params=[["inner"], ["inner", "outer"]]) diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py index 0cbfbad85a8b6..f951b373fb5ec 100644 --- a/pandas/tests/groupby/test_nth.py +++ b/pandas/tests/groupby/test_nth.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, isna -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, _testing as tm, isna def test_first_last_nth(df): diff --git a/pandas/tests/groupby/test_nunique.py b/pandas/tests/groupby/test_nunique.py index c3347b7ae52f3..50a4e0880e79f 100644 --- a/pandas/tests/groupby/test_nunique.py +++ b/pandas/tests/groupby/test_nunique.py @@ -5,8 +5,15 @@ import pytest import pandas as pd -from pandas import DataFrame, MultiIndex, NaT, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import ( + DataFrame, + MultiIndex, + NaT, + Series, + Timestamp, + _testing as tm, + date_range, +) @pytest.mark.slow diff --git a/pandas/tests/groupby/test_pipe.py b/pandas/tests/groupby/test_pipe.py index d2ab016f608fa..ed0c8746cf3a6 100644 --- a/pandas/tests/groupby/test_pipe.py +++ b/pandas/tests/groupby/test_pipe.py @@ -1,8 +1,7 @@ import numpy as np import pandas as pd -from pandas import DataFrame, Index -import pandas._testing as tm +from pandas import DataFrame, Index, _testing as tm def test_pipe(): diff --git a/pandas/tests/groupby/test_quantile.py b/pandas/tests/groupby/test_quantile.py index 9338742195bfe..e751c00d63b2c 100644 --- a/pandas/tests/groupby/test_quantile.py +++ b/pandas/tests/groupby/test_quantile.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index -import pandas._testing as tm +from pandas import DataFrame, Index, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/groupby/test_rank.py b/pandas/tests/groupby/test_rank.py index 3461bf6e10662..2a3197b74f8b6 100644 --- a/pandas/tests/groupby/test_rank.py +++ b/pandas/tests/groupby/test_rank.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series, concat -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, concat from pandas.core.base import DataError diff --git a/pandas/tests/groupby/test_sample.py b/pandas/tests/groupby/test_sample.py index 412e3e8f732de..af30d583ec9ea 100644 --- a/pandas/tests/groupby/test_sample.py +++ b/pandas/tests/groupby/test_sample.py @@ -1,7 +1,6 @@ import pytest -from pandas import DataFrame, Index, Series -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm @pytest.mark.parametrize("n, frac", [(2, None), (None, 0.2)]) diff --git a/pandas/tests/groupby/test_size.py b/pandas/tests/groupby/test_size.py index 9cff8b966dad0..ebeab910fb45e 100644 --- a/pandas/tests/groupby/test_size.py +++ b/pandas/tests/groupby/test_size.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, PeriodIndex, Series -import pandas._testing as tm +from pandas import DataFrame, Index, PeriodIndex, Series, _testing as tm @pytest.mark.parametrize("by", ["A", "B", ["A", "B"]]) diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index 84fd7a1bdfb05..1e5aff2c38974 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -1,5 +1,4 @@ """ test with the TimeGrouper / grouping with datetimes """ - from datetime import datetime from io import StringIO @@ -15,10 +14,10 @@ MultiIndex, Series, Timestamp, + _testing as tm, date_range, offsets, ) -import pandas._testing as tm from pandas.core.groupby.grouper import Grouper from pandas.core.groupby.ops import BinGrouper diff --git a/pandas/tests/groupby/test_value_counts.py b/pandas/tests/groupby/test_value_counts.py index c86cb4532bc26..c2f3d2ad05076 100644 --- a/pandas/tests/groupby/test_value_counts.py +++ b/pandas/tests/groupby/test_value_counts.py @@ -3,14 +3,20 @@ with different size combinations. This is to ensure stability of the sorting and proper parameter handling """ - from itertools import product import numpy as np import pytest -from pandas import DataFrame, Grouper, MultiIndex, Series, date_range, to_datetime -import pandas._testing as tm +from pandas import ( + DataFrame, + Grouper, + MultiIndex, + Series, + _testing as tm, + date_range, + to_datetime, +) # our starting frame diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py index ee482571e644d..bdb0f602efe34 100644 --- a/pandas/tests/groupby/transform/test_numba.py +++ b/pandas/tests/groupby/transform/test_numba.py @@ -1,11 +1,11 @@ import pytest from pandas.errors import NumbaUtilError -import pandas.util._test_decorators as td from pandas import DataFrame, option_context import pandas._testing as tm from pandas.core.util.numba_ import NUMBA_FUNC_CACHE +from pandas.util import _test_decorators as td @td.skip_if_no("numba", "0.46.0") diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index cdaf27e214d80..d028775a22144 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -15,10 +15,10 @@ MultiIndex, Series, Timestamp, + _testing as tm, concat, date_range, ) -import pandas._testing as tm from pandas.core.groupby.groupby import DataError diff --git a/pandas/tests/indexes/base_class/test_reshape.py b/pandas/tests/indexes/base_class/test_reshape.py index 61826f2403a4b..aaba26686cd85 100644 --- a/pandas/tests/indexes/base_class/test_reshape.py +++ b/pandas/tests/indexes/base_class/test_reshape.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import Index -import pandas._testing as tm +from pandas import Index, _testing as tm class TestReshape: diff --git a/pandas/tests/indexes/base_class/test_setops.py b/pandas/tests/indexes/base_class/test_setops.py index 77b5e2780464d..682b1571378cc 100644 --- a/pandas/tests/indexes/base_class/test_setops.py +++ b/pandas/tests/indexes/base_class/test_setops.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Index, Series -import pandas._testing as tm +from pandas import Index, Series, _testing as tm from pandas.core.algorithms import safe_sort diff --git a/pandas/tests/indexes/categorical/test_astype.py b/pandas/tests/indexes/categorical/test_astype.py index a4a0cb1978325..b85194631a0e1 100644 --- a/pandas/tests/indexes/categorical/test_astype.py +++ b/pandas/tests/indexes/categorical/test_astype.py @@ -1,8 +1,14 @@ import numpy as np import pytest -from pandas import Categorical, CategoricalDtype, CategoricalIndex, Index, IntervalIndex -import pandas._testing as tm +from pandas import ( + Categorical, + CategoricalDtype, + CategoricalIndex, + Index, + IntervalIndex, + _testing as tm, +) class TestAstype: diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 7f30a77872bc1..13ede2e47127a 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -4,8 +4,7 @@ from pandas._libs import index as libindex import pandas as pd -from pandas import Categorical -import pandas._testing as tm +from pandas import Categorical, _testing as tm from pandas.core.indexes.api import CategoricalIndex, Index from ..common import Base diff --git a/pandas/tests/indexes/categorical/test_constructors.py b/pandas/tests/indexes/categorical/test_constructors.py index ee3f85da22781..81e24ba075047 100644 --- a/pandas/tests/indexes/categorical/test_constructors.py +++ b/pandas/tests/indexes/categorical/test_constructors.py @@ -1,8 +1,13 @@ import numpy as np import pytest -from pandas import Categorical, CategoricalDtype, CategoricalIndex, Index -import pandas._testing as tm +from pandas import ( + Categorical, + CategoricalDtype, + CategoricalIndex, + Index, + _testing as tm, +) class TestCategoricalIndexConstructors: diff --git a/pandas/tests/indexes/categorical/test_fillna.py b/pandas/tests/indexes/categorical/test_fillna.py index 0d878249d3800..29d6d2ae63375 100644 --- a/pandas/tests/indexes/categorical/test_fillna.py +++ b/pandas/tests/indexes/categorical/test_fillna.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import CategoricalIndex -import pandas._testing as tm +from pandas import CategoricalIndex, _testing as tm class TestFillNA: diff --git a/pandas/tests/indexes/categorical/test_formats.py b/pandas/tests/indexes/categorical/test_formats.py index a5607224f6448..4929eaeb60f93 100644 --- a/pandas/tests/indexes/categorical/test_formats.py +++ b/pandas/tests/indexes/categorical/test_formats.py @@ -1,7 +1,7 @@ """ Tests for CategoricalIndex.__repr__ and related methods. """ -import pandas._config.config as cf +from pandas._config import config as cf import pandas as pd diff --git a/pandas/tests/indexes/categorical/test_indexing.py b/pandas/tests/indexes/categorical/test_indexing.py index 9cf901c0797d8..236a2caff8bbd 100644 --- a/pandas/tests/indexes/categorical/test_indexing.py +++ b/pandas/tests/indexes/categorical/test_indexing.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import CategoricalIndex, Index, IntervalIndex -import pandas._testing as tm +from pandas import CategoricalIndex, Index, IntervalIndex, _testing as tm class TestTake: diff --git a/pandas/tests/indexes/categorical/test_map.py b/pandas/tests/indexes/categorical/test_map.py index 6cef555275444..7993a08f02ded 100644 --- a/pandas/tests/indexes/categorical/test_map.py +++ b/pandas/tests/indexes/categorical/test_map.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import CategoricalIndex, Index -import pandas._testing as tm +from pandas import CategoricalIndex, Index, _testing as tm class TestMap: diff --git a/pandas/tests/indexes/categorical/test_reindex.py b/pandas/tests/indexes/categorical/test_reindex.py index f59ddc42ce4e4..f6ff124564877 100644 --- a/pandas/tests/indexes/categorical/test_reindex.py +++ b/pandas/tests/indexes/categorical/test_reindex.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import Categorical, CategoricalIndex, Index -import pandas._testing as tm +from pandas import Categorical, CategoricalIndex, Index, _testing as tm class TestReindex: diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index c8b780455f862..451d84c05e917 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -23,9 +23,9 @@ Series, TimedeltaIndex, UInt64Index, + _testing as tm, isna, ) -import pandas._testing as tm from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin diff --git a/pandas/tests/indexes/datetimelike.py b/pandas/tests/indexes/datetimelike.py index ac3320c6f9fa0..fc36e4b5ba85c 100644 --- a/pandas/tests/indexes/datetimelike.py +++ b/pandas/tests/indexes/datetimelike.py @@ -3,7 +3,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from .common import Base diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py index 3e7e76bba0dde..a2869df907500 100644 --- a/pandas/tests/indexes/datetimes/test_astype.py +++ b/pandas/tests/indexes/datetimes/test_astype.py @@ -13,9 +13,9 @@ NaT, PeriodIndex, Timestamp, + _testing as tm, date_range, ) -import pandas._testing as tm class TestDatetimeIndex: diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index c150e7901c86a..91aa8d8edd671 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -10,8 +10,15 @@ from pandas._libs.tslibs import OutOfBoundsDatetime, conversion import pandas as pd -from pandas import DatetimeIndex, Index, Timestamp, date_range, offsets, to_datetime -import pandas._testing as tm +from pandas import ( + DatetimeIndex, + Index, + Timestamp, + _testing as tm, + date_range, + offsets, + to_datetime, +) from pandas.core.arrays import DatetimeArray, period_array diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 9d867df147096..2020157604039 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -1,7 +1,6 @@ """ test date_range, bdate_range construction from the convenience range functions """ - from datetime import datetime, time, timedelta import numpy as np @@ -12,12 +11,18 @@ from pandas._libs.tslibs import timezones from pandas._libs.tslibs.offsets import BDay, CDay, DateOffset, MonthEnd, prefix_mapping from pandas.errors import OutOfBoundsDatetime -import pandas.util._test_decorators as td import pandas as pd -from pandas import DatetimeIndex, Timestamp, bdate_range, date_range, offsets -import pandas._testing as tm +from pandas import ( + DatetimeIndex, + Timestamp, + _testing as tm, + bdate_range, + date_range, + offsets, +) from pandas.core.arrays.datetimes import generate_range +from pandas.util import _test_decorators as td START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index ec4162f87010f..13678eb9ff62f 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -5,8 +5,15 @@ import pytest import pandas as pd -from pandas import DataFrame, DatetimeIndex, Index, Timestamp, date_range, offsets -import pandas._testing as tm +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + Timestamp, + _testing as tm, + date_range, + offsets, +) randn = np.random.randn @@ -59,6 +66,7 @@ def test_reindex_with_same_tz(self): def test_time_loc(self): # GH8667 from datetime import time + from pandas._libs.index import _SIZE_CUTOFF ns = _SIZE_CUTOFF + np.array([-100, 100], dtype=np.int64) diff --git a/pandas/tests/indexes/datetimes/test_datetimelike.py b/pandas/tests/indexes/datetimes/test_datetimelike.py index 7345ae3032463..e472d355c3440 100644 --- a/pandas/tests/indexes/datetimes/test_datetimelike.py +++ b/pandas/tests/indexes/datetimes/test_datetimelike.py @@ -1,8 +1,7 @@ """ generic tests from the Datetimelike class """ import pytest -from pandas import DatetimeIndex, date_range -import pandas._testing as tm +from pandas import DatetimeIndex, _testing as tm, date_range from ..datetimelike import DatetimeLike diff --git a/pandas/tests/indexes/datetimes/test_delete.py b/pandas/tests/indexes/datetimes/test_delete.py index 4fbb440bc89e5..a5ba08ae9eb99 100644 --- a/pandas/tests/indexes/datetimes/test_delete.py +++ b/pandas/tests/indexes/datetimes/test_delete.py @@ -1,7 +1,6 @@ import pytest -from pandas import DatetimeIndex, Series, date_range -import pandas._testing as tm +from pandas import DatetimeIndex, Series, _testing as tm, date_range class TestDelete: diff --git a/pandas/tests/indexes/datetimes/test_fillna.py b/pandas/tests/indexes/datetimes/test_fillna.py index 5fbe60bb0c50f..d2d572c72a119 100644 --- a/pandas/tests/indexes/datetimes/test_fillna.py +++ b/pandas/tests/indexes/datetimes/test_fillna.py @@ -1,7 +1,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestDatetimeIndexFillNA: diff --git a/pandas/tests/indexes/datetimes/test_formats.py b/pandas/tests/indexes/datetimes/test_formats.py index f34019e06fd5f..53c8423541594 100644 --- a/pandas/tests/indexes/datetimes/test_formats.py +++ b/pandas/tests/indexes/datetimes/test_formats.py @@ -6,8 +6,7 @@ import pytz import pandas as pd -from pandas import DatetimeIndex, Series -import pandas._testing as tm +from pandas import DatetimeIndex, Series, _testing as tm def test_to_native_types(): diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 5d2c6daba3f57..c6fa64168ea79 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -6,8 +6,7 @@ from pandas.errors import InvalidIndexError import pandas as pd -from pandas import DatetimeIndex, Index, Timestamp, date_range, notna -import pandas._testing as tm +from pandas import DatetimeIndex, Index, Timestamp, _testing as tm, date_range, notna from pandas.tseries.offsets import BDay, CDay diff --git a/pandas/tests/indexes/datetimes/test_insert.py b/pandas/tests/indexes/datetimes/test_insert.py index b4f6cc3798f4f..c460e684a12bc 100644 --- a/pandas/tests/indexes/datetimes/test_insert.py +++ b/pandas/tests/indexes/datetimes/test_insert.py @@ -4,8 +4,7 @@ import pytest import pytz -from pandas import NA, DatetimeIndex, Index, NaT, Timestamp, date_range -import pandas._testing as tm +from pandas import NA, DatetimeIndex, Index, NaT, Timestamp, _testing as tm, date_range class TestInsert: diff --git a/pandas/tests/indexes/datetimes/test_join.py b/pandas/tests/indexes/datetimes/test_join.py index 9a9c94fa19e6d..cb138dcdcb642 100644 --- a/pandas/tests/indexes/datetimes/test_join.py +++ b/pandas/tests/indexes/datetimes/test_join.py @@ -3,8 +3,14 @@ import numpy as np import pytest -from pandas import DatetimeIndex, Index, Timestamp, date_range, to_datetime -import pandas._testing as tm +from pandas import ( + DatetimeIndex, + Index, + Timestamp, + _testing as tm, + date_range, + to_datetime, +) from pandas.tseries.offsets import BDay, BMonthEnd diff --git a/pandas/tests/indexes/datetimes/test_map.py b/pandas/tests/indexes/datetimes/test_map.py index 2644ad7616b51..25dfb90d99ba7 100644 --- a/pandas/tests/indexes/datetimes/test_map.py +++ b/pandas/tests/indexes/datetimes/test_map.py @@ -1,7 +1,6 @@ import pytest -from pandas import DatetimeIndex, Index, MultiIndex, Period, date_range -import pandas._testing as tm +from pandas import DatetimeIndex, Index, MultiIndex, Period, _testing as tm, date_range class TestMap: diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py index 51841727d510b..e0f61dfadb415 100644 --- a/pandas/tests/indexes/datetimes/test_misc.py +++ b/pandas/tests/indexes/datetimes/test_misc.py @@ -7,8 +7,7 @@ import pytest import pandas as pd -from pandas import DatetimeIndex, Index, Timestamp, date_range, offsets -import pandas._testing as tm +from pandas import DatetimeIndex, Index, Timestamp, _testing as tm, date_range, offsets class TestTimeSeries: diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index ea6381547009c..96180096b6362 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -10,10 +10,10 @@ Index, Series, Timestamp, + _testing as tm, bdate_range, date_range, ) -import pandas._testing as tm from pandas.tseries.offsets import BDay, Day, Hour diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index 635470b930252..db7ad158d963d 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -1,5 +1,4 @@ """ test partial slicing on Series/Frame """ - from datetime import datetime import operator @@ -13,9 +12,9 @@ Series, Timedelta, Timestamp, + _testing as tm, date_range, ) -import pandas._testing as tm from pandas.core.indexing import IndexingError diff --git a/pandas/tests/indexes/datetimes/test_pickle.py b/pandas/tests/indexes/datetimes/test_pickle.py index bb08d4c66cb3c..6d2fb1dfbaf2c 100644 --- a/pandas/tests/indexes/datetimes/test_pickle.py +++ b/pandas/tests/indexes/datetimes/test_pickle.py @@ -1,7 +1,6 @@ import pytest -from pandas import NaT, date_range, to_datetime -import pandas._testing as tm +from pandas import NaT, _testing as tm, date_range, to_datetime class TestPickle: diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py index 0d39e034905d2..8aab471e58460 100644 --- a/pandas/tests/indexes/datetimes/test_scalar_compat.py +++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py @@ -10,8 +10,7 @@ from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG import pandas as pd -from pandas import DatetimeIndex, Timestamp, date_range -import pandas._testing as tm +from pandas import DatetimeIndex, Timestamp, _testing as tm, date_range class TestDatetimeIndexOps: diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index 6670b079ddd29..5af9e6583b3a7 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -3,8 +3,6 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd from pandas import ( DataFrame, @@ -12,10 +10,11 @@ Index, Int64Index, Series, + _testing as tm, bdate_range, date_range, ) -import pandas._testing as tm +from pandas.util import _test_decorators as td from pandas.tseries.offsets import BMonthEnd, Minute, MonthEnd diff --git a/pandas/tests/indexes/datetimes/test_shift.py b/pandas/tests/indexes/datetimes/test_shift.py index 8724bfeb05c4d..5ca039d2a98d8 100644 --- a/pandas/tests/indexes/datetimes/test_shift.py +++ b/pandas/tests/indexes/datetimes/test_shift.py @@ -6,8 +6,7 @@ from pandas.errors import NullFrequencyError import pandas as pd -from pandas import DatetimeIndex, Series, date_range -import pandas._testing as tm +from pandas import DatetimeIndex, Series, _testing as tm, date_range START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) diff --git a/pandas/tests/indexes/datetimes/test_snap.py b/pandas/tests/indexes/datetimes/test_snap.py index 8baea9fe8341f..957b800450aa9 100644 --- a/pandas/tests/indexes/datetimes/test_snap.py +++ b/pandas/tests/indexes/datetimes/test_snap.py @@ -1,7 +1,6 @@ import pytest -from pandas import DatetimeIndex, date_range -import pandas._testing as tm +from pandas import DatetimeIndex, _testing as tm, date_range @pytest.mark.filterwarnings("ignore::DeprecationWarning") diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index ea68e8759c123..ac5508d9270f8 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -10,19 +10,19 @@ import pytz from pandas._libs.tslibs import conversion, timezones -import pandas.util._test_decorators as td import pandas as pd from pandas import ( DatetimeIndex, Index, Timestamp, + _testing as tm, bdate_range, date_range, isna, to_datetime, ) -import pandas._testing as tm +from pandas.util import _test_decorators as td class FixedOffset(tzinfo): diff --git a/pandas/tests/indexes/datetimes/test_to_period.py b/pandas/tests/indexes/datetimes/test_to_period.py index 51cc6af2eed08..3fe305e08646c 100644 --- a/pandas/tests/indexes/datetimes/test_to_period.py +++ b/pandas/tests/indexes/datetimes/test_to_period.py @@ -13,10 +13,10 @@ Period, PeriodIndex, Timestamp, + _testing as tm, date_range, period_range, ) -import pandas._testing as tm class TestToPeriod: diff --git a/pandas/tests/indexes/interval/test_astype.py b/pandas/tests/indexes/interval/test_astype.py index c94af6c0d533e..67526570bf583 100644 --- a/pandas/tests/indexes/interval/test_astype.py +++ b/pandas/tests/indexes/interval/test_astype.py @@ -10,9 +10,9 @@ NaT, Timedelta, Timestamp, + _testing as tm, interval_range, ) -import pandas._testing as tm class Base: diff --git a/pandas/tests/indexes/interval/test_base.py b/pandas/tests/indexes/interval/test_base.py index c316655fbda8a..f8a78ba016d29 100644 --- a/pandas/tests/indexes/interval/test_base.py +++ b/pandas/tests/indexes/interval/test_base.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import IntervalIndex, Series, date_range -import pandas._testing as tm +from pandas import IntervalIndex, Series, _testing as tm, date_range from pandas.tests.indexes.common import Base diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py index fa881df8139c6..7b201deb52347 100644 --- a/pandas/tests/indexes/interval/test_constructors.py +++ b/pandas/tests/indexes/interval/test_constructors.py @@ -14,14 +14,14 @@ Int64Index, Interval, IntervalIndex, + _testing as tm, date_range, notna, period_range, timedelta_range, ) -import pandas._testing as tm +from pandas.core import common as com from pandas.core.arrays import IntervalArray -import pandas.core.common as com @pytest.fixture(params=[None, "foo"]) diff --git a/pandas/tests/indexes/interval/test_formats.py b/pandas/tests/indexes/interval/test_formats.py index 7acf5c1e0906c..e57a3c1a08be7 100644 --- a/pandas/tests/indexes/interval/test_formats.py +++ b/pandas/tests/indexes/interval/test_formats.py @@ -1,8 +1,14 @@ import numpy as np import pytest -from pandas import DataFrame, IntervalIndex, Series, Timedelta, Timestamp -import pandas._testing as tm +from pandas import ( + DataFrame, + IntervalIndex, + Series, + Timedelta, + Timestamp, + _testing as tm, +) class TestIntervalIndexRendering: diff --git a/pandas/tests/indexes/interval/test_indexing.py b/pandas/tests/indexes/interval/test_indexing.py index 3abc6e348748a..b37a339cc7312 100644 --- a/pandas/tests/indexes/interval/test_indexing.py +++ b/pandas/tests/indexes/interval/test_indexing.py @@ -10,10 +10,10 @@ Interval, IntervalIndex, Timedelta, + _testing as tm, date_range, timedelta_range, ) -import pandas._testing as tm class TestGetLoc: diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index 2755b186f3eae..f4361b417f81b 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -13,14 +13,14 @@ IntervalIndex, Timedelta, Timestamp, + _testing as tm, date_range, interval_range, isna, notna, timedelta_range, ) -import pandas._testing as tm -import pandas.core.common as com +from pandas.core import common as com @pytest.fixture(scope="class", params=[None, "foo"]) diff --git a/pandas/tests/indexes/interval/test_interval_range.py b/pandas/tests/indexes/interval/test_interval_range.py index 2f28c33a3bbc6..7d60b3c3c6cdd 100644 --- a/pandas/tests/indexes/interval/test_interval_range.py +++ b/pandas/tests/indexes/interval/test_interval_range.py @@ -11,11 +11,11 @@ IntervalIndex, Timedelta, Timestamp, + _testing as tm, date_range, interval_range, timedelta_range, ) -import pandas._testing as tm from pandas.tseries.offsets import Day diff --git a/pandas/tests/indexes/interval/test_interval_tree.py b/pandas/tests/indexes/interval/test_interval_tree.py index 476ec1dd10b4b..8200cf57a627e 100644 --- a/pandas/tests/indexes/interval/test_interval_tree.py +++ b/pandas/tests/indexes/interval/test_interval_tree.py @@ -5,8 +5,7 @@ from pandas._libs.interval import IntervalTree -from pandas import compat -import pandas._testing as tm +from pandas import _testing as tm, compat def skipif_32bit(param): diff --git a/pandas/tests/indexes/interval/test_setops.py b/pandas/tests/indexes/interval/test_setops.py index e3e5070064aff..1bee43720b239 100644 --- a/pandas/tests/indexes/interval/test_setops.py +++ b/pandas/tests/indexes/interval/test_setops.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Index, IntervalIndex, Timestamp, interval_range -import pandas._testing as tm +from pandas import Index, IntervalIndex, Timestamp, _testing as tm, interval_range @pytest.fixture(scope="class", params=[None, "foo"]) diff --git a/pandas/tests/indexes/multi/test_analytics.py b/pandas/tests/indexes/multi/test_analytics.py index 9e4e73e793bac..b46d5684faf36 100644 --- a/pandas/tests/indexes/multi/test_analytics.py +++ b/pandas/tests/indexes/multi/test_analytics.py @@ -4,8 +4,7 @@ from pandas.compat.numpy import _np_version_under1p17 import pandas as pd -from pandas import Index, MultiIndex, date_range, period_range -import pandas._testing as tm +from pandas import Index, MultiIndex, _testing as tm, date_range, period_range def test_shift(idx): diff --git a/pandas/tests/indexes/multi/test_astype.py b/pandas/tests/indexes/multi/test_astype.py index 29908537fbe59..17986a9100fac 100644 --- a/pandas/tests/indexes/multi/test_astype.py +++ b/pandas/tests/indexes/multi/test_astype.py @@ -3,7 +3,7 @@ from pandas.core.dtypes.dtypes import CategoricalDtype -import pandas._testing as tm +from pandas import _testing as tm def test_astype(idx): diff --git a/pandas/tests/indexes/multi/test_compat.py b/pandas/tests/indexes/multi/test_compat.py index d1f66af4a8e83..9c18b25b7e71f 100644 --- a/pandas/tests/indexes/multi/test_compat.py +++ b/pandas/tests/indexes/multi/test_compat.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import MultiIndex -import pandas._testing as tm +from pandas import MultiIndex, _testing as tm def test_numeric_compat(idx): diff --git a/pandas/tests/indexes/multi/test_constructors.py b/pandas/tests/indexes/multi/test_constructors.py index 1157c7f8bb962..17d3211ef25c8 100644 --- a/pandas/tests/indexes/multi/test_constructors.py +++ b/pandas/tests/indexes/multi/test_constructors.py @@ -9,8 +9,7 @@ from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike import pandas as pd -from pandas import Index, MultiIndex, Series, date_range -import pandas._testing as tm +from pandas import Index, MultiIndex, Series, _testing as tm, date_range def test_constructor_single_level(): diff --git a/pandas/tests/indexes/multi/test_conversion.py b/pandas/tests/indexes/multi/test_conversion.py index 3519c5d0d5a9a..ae27ab1e4c428 100644 --- a/pandas/tests/indexes/multi/test_conversion.py +++ b/pandas/tests/indexes/multi/test_conversion.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, _testing as tm def test_to_numpy(idx): diff --git a/pandas/tests/indexes/multi/test_copy.py b/pandas/tests/indexes/multi/test_copy.py index 67b815ecba3b8..c9cca09ebc883 100644 --- a/pandas/tests/indexes/multi/test_copy.py +++ b/pandas/tests/indexes/multi/test_copy.py @@ -2,8 +2,7 @@ import pytest -from pandas import MultiIndex -import pandas._testing as tm +from pandas import MultiIndex, _testing as tm def assert_multiindex_copied(copy, original): diff --git a/pandas/tests/indexes/multi/test_drop.py b/pandas/tests/indexes/multi/test_drop.py index 6ba565f0406ab..3f925a3076f24 100644 --- a/pandas/tests/indexes/multi/test_drop.py +++ b/pandas/tests/indexes/multi/test_drop.py @@ -4,8 +4,7 @@ from pandas.errors import PerformanceWarning import pandas as pd -from pandas import Index, MultiIndex -import pandas._testing as tm +from pandas import Index, MultiIndex, _testing as tm def test_drop(idx): diff --git a/pandas/tests/indexes/multi/test_duplicates.py b/pandas/tests/indexes/multi/test_duplicates.py index e48731b9c8099..ec80ebcf77987 100644 --- a/pandas/tests/indexes/multi/test_duplicates.py +++ b/pandas/tests/indexes/multi/test_duplicates.py @@ -5,8 +5,7 @@ from pandas._libs import hashtable -from pandas import DatetimeIndex, MultiIndex -import pandas._testing as tm +from pandas import DatetimeIndex, MultiIndex, _testing as tm @pytest.mark.parametrize("names", [None, ["first", "second"]]) diff --git a/pandas/tests/indexes/multi/test_equivalence.py b/pandas/tests/indexes/multi/test_equivalence.py index 063ede028add7..f4e57e51a33bb 100644 --- a/pandas/tests/indexes/multi/test_equivalence.py +++ b/pandas/tests/indexes/multi/test_equivalence.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Index, MultiIndex, Series -import pandas._testing as tm +from pandas import Index, MultiIndex, Series, _testing as tm def test_equals(idx): diff --git a/pandas/tests/indexes/multi/test_formats.py b/pandas/tests/indexes/multi/test_formats.py index 792dcf4c535e3..aa5c691c52da8 100644 --- a/pandas/tests/indexes/multi/test_formats.py +++ b/pandas/tests/indexes/multi/test_formats.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import Index, MultiIndex -import pandas._testing as tm +from pandas import Index, MultiIndex, _testing as tm def test_format(idx): diff --git a/pandas/tests/indexes/multi/test_get_level_values.py b/pandas/tests/indexes/multi/test_get_level_values.py index 985fe5773ceed..ab321c85b9cac 100644 --- a/pandas/tests/indexes/multi/test_get_level_values.py +++ b/pandas/tests/indexes/multi/test_get_level_values.py @@ -1,8 +1,14 @@ import numpy as np import pandas as pd -from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range -import pandas._testing as tm +from pandas import ( + CategoricalIndex, + Index, + MultiIndex, + Timestamp, + _testing as tm, + date_range, +) class TestGetLevelValues: diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py index 8a3deca0236e4..a41babceb1d96 100644 --- a/pandas/tests/indexes/multi/test_get_set.py +++ b/pandas/tests/indexes/multi/test_get_set.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import CategoricalIndex, MultiIndex -import pandas._testing as tm +from pandas import CategoricalIndex, MultiIndex, _testing as tm def assert_matching(actual, expected, check_dtype=False): diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index 6b27682ed5674..1dd8a64c957a7 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -6,8 +6,7 @@ from pandas.errors import InvalidIndexError import pandas as pd -from pandas import Categorical, Index, MultiIndex, date_range -import pandas._testing as tm +from pandas import Categorical, Index, MultiIndex, _testing as tm, date_range class TestSliceLocs: diff --git a/pandas/tests/indexes/multi/test_integrity.py b/pandas/tests/indexes/multi/test_integrity.py index fd150bb4d57a2..6091d2d0edcd3 100644 --- a/pandas/tests/indexes/multi/test_integrity.py +++ b/pandas/tests/indexes/multi/test_integrity.py @@ -6,8 +6,7 @@ from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike import pandas as pd -from pandas import IntervalIndex, MultiIndex, RangeIndex -import pandas._testing as tm +from pandas import IntervalIndex, MultiIndex, RangeIndex, _testing as tm def test_labels_dtypes(): diff --git a/pandas/tests/indexes/multi/test_isin.py b/pandas/tests/indexes/multi/test_isin.py index 122263e6ec198..57543b878c9b9 100644 --- a/pandas/tests/indexes/multi/test_isin.py +++ b/pandas/tests/indexes/multi/test_isin.py @@ -3,8 +3,7 @@ from pandas.compat import PYPY -from pandas import MultiIndex -import pandas._testing as tm +from pandas import MultiIndex, _testing as tm @pytest.mark.skipif(not PYPY, reason="tuples cmp recursively on PyPy") diff --git a/pandas/tests/indexes/multi/test_join.py b/pandas/tests/indexes/multi/test_join.py index 6be9ec463ce36..61d5222d00ebc 100644 --- a/pandas/tests/indexes/multi/test_join.py +++ b/pandas/tests/indexes/multi/test_join.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Index, MultiIndex -import pandas._testing as tm +from pandas import Index, MultiIndex, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/indexes/multi/test_missing.py b/pandas/tests/indexes/multi/test_missing.py index 4c9d518778ceb..126493323d1d6 100644 --- a/pandas/tests/indexes/multi/test_missing.py +++ b/pandas/tests/indexes/multi/test_missing.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import MultiIndex -import pandas._testing as tm +from pandas import MultiIndex, _testing as tm def test_fillna(idx): diff --git a/pandas/tests/indexes/multi/test_names.py b/pandas/tests/indexes/multi/test_names.py index 479b5ef0211a0..bcf1161577b67 100644 --- a/pandas/tests/indexes/multi/test_names.py +++ b/pandas/tests/indexes/multi/test_names.py @@ -1,8 +1,7 @@ import pytest import pandas as pd -from pandas import MultiIndex -import pandas._testing as tm +from pandas import MultiIndex, _testing as tm def check_level_names(index, names): diff --git a/pandas/tests/indexes/multi/test_partial_indexing.py b/pandas/tests/indexes/multi/test_partial_indexing.py index 7dfe0b20a7478..f61a0edbeecc6 100644 --- a/pandas/tests/indexes/multi/test_partial_indexing.py +++ b/pandas/tests/indexes/multi/test_partial_indexing.py @@ -1,7 +1,6 @@ import pytest -from pandas import DataFrame, IndexSlice, MultiIndex, date_range -import pandas._testing as tm +from pandas import DataFrame, IndexSlice, MultiIndex, _testing as tm, date_range @pytest.fixture diff --git a/pandas/tests/indexes/multi/test_reindex.py b/pandas/tests/indexes/multi/test_reindex.py index ceb14aa82a76c..9b6745d188b5b 100644 --- a/pandas/tests/indexes/multi/test_reindex.py +++ b/pandas/tests/indexes/multi/test_reindex.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Index, MultiIndex -import pandas._testing as tm +from pandas import Index, MultiIndex, _testing as tm def test_reindex(idx): diff --git a/pandas/tests/indexes/multi/test_reshape.py b/pandas/tests/indexes/multi/test_reshape.py index 6d8a396119ef3..42bb6e9cf7516 100644 --- a/pandas/tests/indexes/multi/test_reshape.py +++ b/pandas/tests/indexes/multi/test_reshape.py @@ -5,8 +5,7 @@ import pytz import pandas as pd -from pandas import Index, MultiIndex -import pandas._testing as tm +from pandas import Index, MultiIndex, _testing as tm def test_insert(idx): diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py index d7427ee622977..a27c5e607f347 100644 --- a/pandas/tests/indexes/multi/test_setops.py +++ b/pandas/tests/indexes/multi/test_setops.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import MultiIndex, Series -import pandas._testing as tm +from pandas import MultiIndex, Series, _testing as tm @pytest.mark.parametrize("case", [0.5, "xxx"]) diff --git a/pandas/tests/indexes/multi/test_sorting.py b/pandas/tests/indexes/multi/test_sorting.py index 423bbed831b87..0869be187a410 100644 --- a/pandas/tests/indexes/multi/test_sorting.py +++ b/pandas/tests/indexes/multi/test_sorting.py @@ -6,8 +6,14 @@ from pandas.errors import PerformanceWarning, UnsortedIndexError import pandas as pd -from pandas import CategoricalIndex, DataFrame, Index, MultiIndex, RangeIndex -import pandas._testing as tm +from pandas import ( + CategoricalIndex, + DataFrame, + Index, + MultiIndex, + RangeIndex, + _testing as tm, +) def test_sortlevel(idx): diff --git a/pandas/tests/indexes/multi/test_take.py b/pandas/tests/indexes/multi/test_take.py index f8e7632c91ab2..57a57e1c0c2c2 100644 --- a/pandas/tests/indexes/multi/test_take.py +++ b/pandas/tests/indexes/multi/test_take.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_take(idx): diff --git a/pandas/tests/indexes/numeric/test_astype.py b/pandas/tests/indexes/numeric/test_astype.py index 1771f4336df67..7357fb4bbe92d 100644 --- a/pandas/tests/indexes/numeric/test_astype.py +++ b/pandas/tests/indexes/numeric/test_astype.py @@ -5,8 +5,7 @@ from pandas.core.dtypes.common import pandas_dtype -from pandas import Float64Index, Index, Int64Index -import pandas._testing as tm +from pandas import Float64Index, Index, Int64Index, _testing as tm class TestAstype: diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py index 473e370c76f8b..7b14a76641552 100644 --- a/pandas/tests/indexes/numeric/test_indexing.py +++ b/pandas/tests/indexes/numeric/test_indexing.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Float64Index, Int64Index, Series, UInt64Index -import pandas._testing as tm +from pandas import Float64Index, Int64Index, Series, UInt64Index, _testing as tm @pytest.fixture diff --git a/pandas/tests/indexes/numeric/test_join.py b/pandas/tests/indexes/numeric/test_join.py index c8dffa411e5fd..5a7cdec71e67e 100644 --- a/pandas/tests/indexes/numeric/test_join.py +++ b/pandas/tests/indexes/numeric/test_join.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Index, Int64Index, UInt64Index -import pandas._testing as tm +from pandas import Index, Int64Index, UInt64Index, _testing as tm class TestJoinInt64Index: diff --git a/pandas/tests/indexes/period/test_asfreq.py b/pandas/tests/indexes/period/test_asfreq.py index 8c04ac1177676..5e473adf85f78 100644 --- a/pandas/tests/indexes/period/test_asfreq.py +++ b/pandas/tests/indexes/period/test_asfreq.py @@ -1,7 +1,6 @@ import pytest -from pandas import PeriodIndex, period_range -import pandas._testing as tm +from pandas import PeriodIndex, _testing as tm, period_range class TestPeriodIndex: diff --git a/pandas/tests/indexes/period/test_astype.py b/pandas/tests/indexes/period/test_astype.py index fa1617bdfaa52..f06131edd5c7f 100644 --- a/pandas/tests/indexes/period/test_astype.py +++ b/pandas/tests/indexes/period/test_astype.py @@ -11,9 +11,9 @@ PeriodIndex, Timedelta, UInt64Index, + _testing as tm, period_range, ) -import pandas._testing as tm class TestPeriodIndexAsType: diff --git a/pandas/tests/indexes/period/test_constructors.py b/pandas/tests/indexes/period/test_constructors.py index f85f37e4127c3..b19f306ac52c7 100644 --- a/pandas/tests/indexes/period/test_constructors.py +++ b/pandas/tests/indexes/period/test_constructors.py @@ -12,11 +12,11 @@ Period, PeriodIndex, Series, + _testing as tm, date_range, offsets, period_range, ) -import pandas._testing as tm from pandas.core.arrays import PeriodArray diff --git a/pandas/tests/indexes/period/test_factorize.py b/pandas/tests/indexes/period/test_factorize.py index 7c9367a1011a2..e945c8384e386 100644 --- a/pandas/tests/indexes/period/test_factorize.py +++ b/pandas/tests/indexes/period/test_factorize.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import PeriodIndex -import pandas._testing as tm +from pandas import PeriodIndex, _testing as tm class TestFactorize: diff --git a/pandas/tests/indexes/period/test_fillna.py b/pandas/tests/indexes/period/test_fillna.py index 602e87333a6c1..9e726a0488f74 100644 --- a/pandas/tests/indexes/period/test_fillna.py +++ b/pandas/tests/indexes/period/test_fillna.py @@ -1,5 +1,4 @@ -from pandas import Index, NaT, Period, PeriodIndex -import pandas._testing as tm +from pandas import Index, NaT, Period, PeriodIndex, _testing as tm class TestFillNA: diff --git a/pandas/tests/indexes/period/test_formats.py b/pandas/tests/indexes/period/test_formats.py index 5db373a9f07ae..590972f96c793 100644 --- a/pandas/tests/indexes/period/test_formats.py +++ b/pandas/tests/indexes/period/test_formats.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import PeriodIndex -import pandas._testing as tm +from pandas import PeriodIndex, _testing as tm def test_to_native_types(): diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index b61d1d903f89a..d2354af3bf65f 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -15,11 +15,11 @@ PeriodIndex, Series, Timedelta, + _testing as tm, date_range, notna, period_range, ) -import pandas._testing as tm class TestGetItem: diff --git a/pandas/tests/indexes/period/test_join.py b/pandas/tests/indexes/period/test_join.py index 8a68561dd5819..f5acd475ba5c1 100644 --- a/pandas/tests/indexes/period/test_join.py +++ b/pandas/tests/indexes/period/test_join.py @@ -3,8 +3,7 @@ from pandas._libs.tslibs import IncompatibleFrequency -from pandas import Index, PeriodIndex, period_range -import pandas._testing as tm +from pandas import Index, PeriodIndex, _testing as tm, period_range class TestJoin: diff --git a/pandas/tests/indexes/period/test_ops.py b/pandas/tests/indexes/period/test_ops.py index e7dd76584d780..9e86b138f5a88 100644 --- a/pandas/tests/indexes/period/test_ops.py +++ b/pandas/tests/indexes/period/test_ops.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Index, NaT, PeriodIndex, Series -import pandas._testing as tm +from pandas import Index, NaT, PeriodIndex, Series, _testing as tm class TestPeriodIndexOps: diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py index 660c32d44a7aa..4a0280c06a321 100644 --- a/pandas/tests/indexes/period/test_partial_slicing.py +++ b/pandas/tests/indexes/period/test_partial_slicing.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Series, date_range, period_range -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, date_range, period_range class TestPeriodIndex: diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 15a88ab3819ce..35f1d0dd0f164 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -2,7 +2,6 @@ import pytest from pandas._libs.tslibs.period import IncompatibleFrequency -import pandas.util._test_decorators as td import pandas as pd from pandas import ( @@ -13,11 +12,12 @@ Period, PeriodIndex, Series, + _testing as tm, date_range, offsets, period_range, ) -import pandas._testing as tm +from pandas.util import _test_decorators as td from ..datetimelike import DatetimeLike diff --git a/pandas/tests/indexes/period/test_period_range.py b/pandas/tests/indexes/period/test_period_range.py index 68b48a55957ff..743ad249f14c6 100644 --- a/pandas/tests/indexes/period/test_period_range.py +++ b/pandas/tests/indexes/period/test_period_range.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import NaT, Period, PeriodIndex, date_range, period_range -import pandas._testing as tm +from pandas import NaT, Period, PeriodIndex, _testing as tm, date_range, period_range class TestPeriodRange: diff --git a/pandas/tests/indexes/period/test_scalar_compat.py b/pandas/tests/indexes/period/test_scalar_compat.py index e9d17e7e20778..1e69c83f049ca 100644 --- a/pandas/tests/indexes/period/test_scalar_compat.py +++ b/pandas/tests/indexes/period/test_scalar_compat.py @@ -1,7 +1,5 @@ """Tests for PeriodIndex behaving like a vectorized Period scalar""" - -from pandas import Timedelta, date_range, period_range -import pandas._testing as tm +from pandas import Timedelta, _testing as tm, date_range, period_range class TestPeriodIndexOps: diff --git a/pandas/tests/indexes/period/test_searchsorted.py b/pandas/tests/indexes/period/test_searchsorted.py index f5a2583bf2e10..7b51da718e664 100644 --- a/pandas/tests/indexes/period/test_searchsorted.py +++ b/pandas/tests/indexes/period/test_searchsorted.py @@ -3,8 +3,7 @@ from pandas._libs.tslibs import IncompatibleFrequency -from pandas import NaT, Period, PeriodIndex, Series, array -import pandas._testing as tm +from pandas import NaT, Period, PeriodIndex, Series, _testing as tm, array class TestSearchsorted: diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py index 71b827d83b836..3815fc97f2b8b 100644 --- a/pandas/tests/indexes/period/test_setops.py +++ b/pandas/tests/indexes/period/test_setops.py @@ -4,8 +4,7 @@ from pandas._libs.tslibs import IncompatibleFrequency import pandas as pd -from pandas import PeriodIndex, date_range, period_range -import pandas._testing as tm +from pandas import PeriodIndex, _testing as tm, date_range, period_range def _permute(obj): diff --git a/pandas/tests/indexes/period/test_shift.py b/pandas/tests/indexes/period/test_shift.py index 278bb7f07c679..a04c01e5471ad 100644 --- a/pandas/tests/indexes/period/test_shift.py +++ b/pandas/tests/indexes/period/test_shift.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import PeriodIndex, period_range -import pandas._testing as tm +from pandas import PeriodIndex, _testing as tm, period_range class TestPeriodIndexShift: diff --git a/pandas/tests/indexes/period/test_to_timestamp.py b/pandas/tests/indexes/period/test_to_timestamp.py index c2328872aee1b..bf00fe713effc 100644 --- a/pandas/tests/indexes/period/test_to_timestamp.py +++ b/pandas/tests/indexes/period/test_to_timestamp.py @@ -9,10 +9,10 @@ PeriodIndex, Timedelta, Timestamp, + _testing as tm, date_range, period_range, ) -import pandas._testing as tm class TestToTimestamp: diff --git a/pandas/tests/indexes/period/test_tools.py b/pandas/tests/indexes/period/test_tools.py index 82c13240c6bf2..354a13536afce 100644 --- a/pandas/tests/indexes/period/test_tools.py +++ b/pandas/tests/indexes/period/test_tools.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Period, PeriodIndex, period_range -import pandas._testing as tm +from pandas import Period, PeriodIndex, _testing as tm, period_range class TestPeriodRepresentation: diff --git a/pandas/tests/indexes/ranges/test_constructors.py b/pandas/tests/indexes/ranges/test_constructors.py index f573da44e99b3..1aa254c14a7e9 100644 --- a/pandas/tests/indexes/ranges/test_constructors.py +++ b/pandas/tests/indexes/ranges/test_constructors.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import Index, RangeIndex, Series -import pandas._testing as tm +from pandas import Index, RangeIndex, Series, _testing as tm class TestRangeIndexConstructors: diff --git a/pandas/tests/indexes/ranges/test_indexing.py b/pandas/tests/indexes/ranges/test_indexing.py index 238c33c3db6d7..b123fdf5ffbe5 100644 --- a/pandas/tests/indexes/ranges/test_indexing.py +++ b/pandas/tests/indexes/ranges/test_indexing.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import RangeIndex -import pandas._testing as tm +from pandas import RangeIndex, _testing as tm class TestGetIndexer: diff --git a/pandas/tests/indexes/ranges/test_join.py b/pandas/tests/indexes/ranges/test_join.py index 76013d2b7a387..d209180ed2e7b 100644 --- a/pandas/tests/indexes/ranges/test_join.py +++ b/pandas/tests/indexes/ranges/test_join.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import Index, Int64Index, RangeIndex -import pandas._testing as tm +from pandas import Index, Int64Index, RangeIndex, _testing as tm class TestJoin: diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index 5b6f9cb358b7d..af8506a8f7204 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -4,8 +4,7 @@ from pandas.core.dtypes.common import ensure_platform_int import pandas as pd -from pandas import Float64Index, Index, Int64Index, RangeIndex -import pandas._testing as tm +from pandas import Float64Index, Index, Int64Index, RangeIndex, _testing as tm from ..test_numeric import Numeric diff --git a/pandas/tests/indexes/ranges/test_setops.py b/pandas/tests/indexes/ranges/test_setops.py index 5b565310cfb9c..f8ab1673a391d 100644 --- a/pandas/tests/indexes/ranges/test_setops.py +++ b/pandas/tests/indexes/ranges/test_setops.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import Index, Int64Index, RangeIndex -import pandas._testing as tm +from pandas import Index, Int64Index, RangeIndex, _testing as tm class TestRangeIndexSetOps: diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py index 5e7065f785309..d84fc08a1ca19 100644 --- a/pandas/tests/indexes/test_any_index.py +++ b/pandas/tests/indexes/test_any_index.py @@ -5,7 +5,7 @@ """ import pytest -import pandas._testing as tm +from pandas import _testing as tm def test_boolean_context_compat(index): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index eaf48421dc071..6d19baf4ef8c7 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -8,7 +8,7 @@ import numpy as np import pytest -import pandas._config.config as cf +from pandas._config import config as cf from pandas._libs.tslib import Timestamp from pandas.compat.numpy import np_datetime64_compat @@ -28,11 +28,11 @@ Series, TimedeltaIndex, UInt64Index, + _testing as tm, date_range, isna, period_range, ) -import pandas._testing as tm from pandas.core.indexes.api import ( Index, MultiIndex, diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py index 02a173eb4958d..163ad5c07b1ac 100644 --- a/pandas/tests/indexes/test_common.py +++ b/pandas/tests/indexes/test_common.py @@ -13,8 +13,7 @@ from pandas.core.dtypes.common import is_period_dtype, needs_i8_conversion import pandas as pd -from pandas import CategoricalIndex, MultiIndex, RangeIndex -import pandas._testing as tm +from pandas import CategoricalIndex, MultiIndex, RangeIndex, _testing as tm class TestCommon: diff --git a/pandas/tests/indexes/test_engines.py b/pandas/tests/indexes/test_engines.py index 9ea70a457e516..77fa65cb6024a 100644 --- a/pandas/tests/indexes/test_engines.py +++ b/pandas/tests/indexes/test_engines.py @@ -6,7 +6,7 @@ from pandas._libs import algos as libalgos, index as libindex import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.fixture( diff --git a/pandas/tests/indexes/test_index_new.py b/pandas/tests/indexes/test_index_new.py index 9248c185bccd7..7dfa85b600896 100644 --- a/pandas/tests/indexes/test_index_new.py +++ b/pandas/tests/indexes/test_index_new.py @@ -19,9 +19,9 @@ TimedeltaIndex, Timestamp, UInt64Index, + _testing as tm, period_range, ) -import pandas._testing as tm class TestIndexConstructorInference: diff --git a/pandas/tests/indexes/test_indexing.py b/pandas/tests/indexes/test_indexing.py index 8910a3731cf8a..b132ca316e160 100644 --- a/pandas/tests/indexes/test_indexing.py +++ b/pandas/tests/indexes/test_indexing.py @@ -16,8 +16,7 @@ import numpy as np import pytest -from pandas import Float64Index, Index, Int64Index, UInt64Index -import pandas._testing as tm +from pandas import Float64Index, Index, Int64Index, UInt64Index, _testing as tm class TestContains: diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index a7c5734ef9b02..eafcd977ca83d 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -6,8 +6,7 @@ from pandas._libs.tslibs import Timestamp import pandas as pd -from pandas import Float64Index, Index, Int64Index, Series, UInt64Index -import pandas._testing as tm +from pandas import Float64Index, Index, Int64Index, Series, UInt64Index, _testing as tm from pandas.tests.indexes.common import Base diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py index 043539c173427..eda5104880c42 100644 --- a/pandas/tests/indexes/test_numpy_compat.py +++ b/pandas/tests/indexes/test_numpy_compat.py @@ -11,8 +11,8 @@ UInt64Index, _np_version_under1p17, _np_version_under1p18, + _testing as tm, ) -import pandas._testing as tm from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index 1a40fe550be61..3aac77e891657 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -8,8 +8,7 @@ from pandas.core.dtypes.common import is_dtype_equal import pandas as pd -from pandas import Float64Index, Int64Index, RangeIndex, UInt64Index -import pandas._testing as tm +from pandas import Float64Index, Int64Index, RangeIndex, UInt64Index, _testing as tm from pandas.api.types import pandas_dtype COMPATIBLE_INCONSISTENT_PAIRS = { diff --git a/pandas/tests/indexes/timedeltas/test_astype.py b/pandas/tests/indexes/timedeltas/test_astype.py index d9f24b4a35520..561c6c99a9fa9 100644 --- a/pandas/tests/indexes/timedeltas/test_astype.py +++ b/pandas/tests/indexes/timedeltas/test_astype.py @@ -11,9 +11,9 @@ NaT, Timedelta, TimedeltaIndex, + _testing as tm, timedelta_range, ) -import pandas._testing as tm class TestTimedeltaIndex: diff --git a/pandas/tests/indexes/timedeltas/test_constructors.py b/pandas/tests/indexes/timedeltas/test_constructors.py index 41e4e220c999c..18b7bdbdcbeb8 100644 --- a/pandas/tests/indexes/timedeltas/test_constructors.py +++ b/pandas/tests/indexes/timedeltas/test_constructors.py @@ -4,8 +4,13 @@ import pytest import pandas as pd -from pandas import Timedelta, TimedeltaIndex, timedelta_range, to_timedelta -import pandas._testing as tm +from pandas import ( + Timedelta, + TimedeltaIndex, + _testing as tm, + timedelta_range, + to_timedelta, +) from pandas.core.arrays import TimedeltaArray diff --git a/pandas/tests/indexes/timedeltas/test_delete.py b/pandas/tests/indexes/timedeltas/test_delete.py index 63f2b450aa818..292e280d5014b 100644 --- a/pandas/tests/indexes/timedeltas/test_delete.py +++ b/pandas/tests/indexes/timedeltas/test_delete.py @@ -1,5 +1,4 @@ -from pandas import TimedeltaIndex, timedelta_range -import pandas._testing as tm +from pandas import TimedeltaIndex, _testing as tm, timedelta_range class TestTimedeltaIndexDelete: diff --git a/pandas/tests/indexes/timedeltas/test_fillna.py b/pandas/tests/indexes/timedeltas/test_fillna.py index 47b2f2ff597f4..d72f55ff20163 100644 --- a/pandas/tests/indexes/timedeltas/test_fillna.py +++ b/pandas/tests/indexes/timedeltas/test_fillna.py @@ -1,5 +1,4 @@ -from pandas import Index, NaT, Timedelta, TimedeltaIndex -import pandas._testing as tm +from pandas import Index, NaT, Timedelta, TimedeltaIndex, _testing as tm class TestFillNA: diff --git a/pandas/tests/indexes/timedeltas/test_indexing.py b/pandas/tests/indexes/timedeltas/test_indexing.py index 396a676b97a1b..721870bcf4aae 100644 --- a/pandas/tests/indexes/timedeltas/test_indexing.py +++ b/pandas/tests/indexes/timedeltas/test_indexing.py @@ -5,8 +5,14 @@ import pytest import pandas as pd -from pandas import Index, Timedelta, TimedeltaIndex, notna, timedelta_range -import pandas._testing as tm +from pandas import ( + Index, + Timedelta, + TimedeltaIndex, + _testing as tm, + notna, + timedelta_range, +) class TestGetItem: diff --git a/pandas/tests/indexes/timedeltas/test_insert.py b/pandas/tests/indexes/timedeltas/test_insert.py index 1ebc0a4b1eca0..36271b3c7dbea 100644 --- a/pandas/tests/indexes/timedeltas/test_insert.py +++ b/pandas/tests/indexes/timedeltas/test_insert.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import Index, Timedelta, TimedeltaIndex, timedelta_range -import pandas._testing as tm +from pandas import Index, Timedelta, TimedeltaIndex, _testing as tm, timedelta_range class TestTimedeltaIndexInsert: diff --git a/pandas/tests/indexes/timedeltas/test_join.py b/pandas/tests/indexes/timedeltas/test_join.py index aaf4ef29e162b..008a154a0dcf5 100644 --- a/pandas/tests/indexes/timedeltas/test_join.py +++ b/pandas/tests/indexes/timedeltas/test_join.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import Index, Timedelta, timedelta_range -import pandas._testing as tm +from pandas import Index, Timedelta, _testing as tm, timedelta_range class TestJoin: diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index 3e452e7e2841d..876dd6ac454b0 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import Series, TimedeltaIndex, timedelta_range -import pandas._testing as tm +from pandas import Series, TimedeltaIndex, _testing as tm, timedelta_range from pandas.tseries.offsets import DateOffset, Day, Hour diff --git a/pandas/tests/indexes/timedeltas/test_partial_slicing.py b/pandas/tests/indexes/timedeltas/test_partial_slicing.py index e5f509acf4734..9a3e7e9865d85 100644 --- a/pandas/tests/indexes/timedeltas/test_partial_slicing.py +++ b/pandas/tests/indexes/timedeltas/test_partial_slicing.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Series, timedelta_range -import pandas._testing as tm +from pandas import Series, _testing as tm, timedelta_range class TestSlicing: diff --git a/pandas/tests/indexes/timedeltas/test_scalar_compat.py b/pandas/tests/indexes/timedeltas/test_scalar_compat.py index 16c19b8d00380..1e416f7f09994 100644 --- a/pandas/tests/indexes/timedeltas/test_scalar_compat.py +++ b/pandas/tests/indexes/timedeltas/test_scalar_compat.py @@ -1,15 +1,20 @@ """ Tests for TimedeltaIndex methods behaving like their Timedelta counterparts """ - import numpy as np import pytest from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG import pandas as pd -from pandas import Index, Series, Timedelta, TimedeltaIndex, timedelta_range -import pandas._testing as tm +from pandas import ( + Index, + Series, + Timedelta, + TimedeltaIndex, + _testing as tm, + timedelta_range, +) class TestVectorizedTimedelta: diff --git a/pandas/tests/indexes/timedeltas/test_searchsorted.py b/pandas/tests/indexes/timedeltas/test_searchsorted.py index 4806a9acff96f..0ddb377dfe293 100644 --- a/pandas/tests/indexes/timedeltas/test_searchsorted.py +++ b/pandas/tests/indexes/timedeltas/test_searchsorted.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Series, TimedeltaIndex, Timestamp, array -import pandas._testing as tm +from pandas import Series, TimedeltaIndex, Timestamp, _testing as tm, array class TestSearchSorted: diff --git a/pandas/tests/indexes/timedeltas/test_setops.py b/pandas/tests/indexes/timedeltas/test_setops.py index 6a2f66cade733..c00699ea2c1eb 100644 --- a/pandas/tests/indexes/timedeltas/test_setops.py +++ b/pandas/tests/indexes/timedeltas/test_setops.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Int64Index, TimedeltaIndex, timedelta_range -import pandas._testing as tm +from pandas import Int64Index, TimedeltaIndex, _testing as tm, timedelta_range from pandas.tseries.offsets import Hour diff --git a/pandas/tests/indexes/timedeltas/test_shift.py b/pandas/tests/indexes/timedeltas/test_shift.py index 1282bd510ec17..1ad2d7c55b753 100644 --- a/pandas/tests/indexes/timedeltas/test_shift.py +++ b/pandas/tests/indexes/timedeltas/test_shift.py @@ -3,8 +3,7 @@ from pandas.errors import NullFrequencyError import pandas as pd -from pandas import TimedeltaIndex -import pandas._testing as tm +from pandas import TimedeltaIndex, _testing as tm class TestTimedeltaIndexShift: diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 4a1749ff734c1..69c17e0c22f39 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -11,10 +11,10 @@ Series, Timedelta, TimedeltaIndex, + _testing as tm, date_range, timedelta_range, ) -import pandas._testing as tm from ..datetimelike import DatetimeLike diff --git a/pandas/tests/indexes/timedeltas/test_timedelta_range.py b/pandas/tests/indexes/timedeltas/test_timedelta_range.py index 7d78fbf9ff190..5d0cb608b3dcb 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta_range.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta_range.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Timedelta, timedelta_range, to_timedelta -import pandas._testing as tm +from pandas import Timedelta, _testing as tm, timedelta_range, to_timedelta from pandas.tseries.offsets import Day, Second diff --git a/pandas/tests/indexing/common.py b/pandas/tests/indexing/common.py index 9cc031001f81c..67d40bcacbfc3 100644 --- a/pandas/tests/indexing/common.py +++ b/pandas/tests/indexing/common.py @@ -3,8 +3,15 @@ import numpy as np -from pandas import DataFrame, Float64Index, MultiIndex, Series, UInt64Index, date_range -import pandas._testing as tm +from pandas import ( + DataFrame, + Float64Index, + MultiIndex, + Series, + UInt64Index, + _testing as tm, + date_range, +) def _mklbl(prefix, n): diff --git a/pandas/tests/indexing/interval/test_interval.py b/pandas/tests/indexing/interval/test_interval.py index 634020982b1c2..ab4413030d1cd 100644 --- a/pandas/tests/indexing/interval/test_interval.py +++ b/pandas/tests/indexing/interval/test_interval.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, IntervalIndex, Series -import pandas._testing as tm +from pandas import DataFrame, IntervalIndex, Series, _testing as tm class TestIntervalIndex: diff --git a/pandas/tests/indexing/interval/test_interval_new.py b/pandas/tests/indexing/interval/test_interval_new.py index 03c3034772bc6..ecbd498e1b04d 100644 --- a/pandas/tests/indexing/interval/test_interval_new.py +++ b/pandas/tests/indexing/interval/test_interval_new.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import Interval, IntervalIndex, Series -import pandas._testing as tm +from pandas import Interval, IntervalIndex, Series, _testing as tm class TestIntervalIndex: diff --git a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py index d3b13336e2a44..b4217fcad748b 100644 --- a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py +++ b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py @@ -1,9 +1,8 @@ import numpy as np import pytest -from pandas import DataFrame, MultiIndex, Series -import pandas._testing as tm -import pandas.core.common as com +from pandas import DataFrame, MultiIndex, Series, _testing as tm +from pandas.core import common as com def test_detect_chained_assignment(): diff --git a/pandas/tests/indexing/multiindex/test_getitem.py b/pandas/tests/indexing/multiindex/test_getitem.py index 54b22dbc53466..4ff876d38f38e 100644 --- a/pandas/tests/indexing/multiindex/test_getitem.py +++ b/pandas/tests/indexing/multiindex/test_getitem.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm from pandas.core.indexing import IndexingError # ---------------------------------------------------------------------------- diff --git a/pandas/tests/indexing/multiindex/test_iloc.py b/pandas/tests/indexing/multiindex/test_iloc.py index 9859c7235c380..7ad7455cedcc5 100644 --- a/pandas/tests/indexing/multiindex/test_iloc.py +++ b/pandas/tests/indexing/multiindex/test_iloc.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, Series, _testing as tm @pytest.fixture diff --git a/pandas/tests/indexing/multiindex/test_indexing_slow.py b/pandas/tests/indexing/multiindex/test_indexing_slow.py index be193e0854d8d..e3198edb2fb6a 100644 --- a/pandas/tests/indexing/multiindex/test_indexing_slow.py +++ b/pandas/tests/indexing/multiindex/test_indexing_slow.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm @pytest.mark.slow @@ -15,7 +14,7 @@ def test_multiindex_get_loc(): # GH7724, GH2646 with warnings.catch_warnings(record=True): # test indexing into a multi-index before & past the lexsort depth - from numpy.random import randint, choice, randn + from numpy.random import choice, randint, randn cols = ["jim", "joe", "jolie", "joline", "jolia"] diff --git a/pandas/tests/indexing/multiindex/test_insert.py b/pandas/tests/indexing/multiindex/test_insert.py index 42922c3deeee4..abc4e969d9015 100644 --- a/pandas/tests/indexing/multiindex/test_insert.py +++ b/pandas/tests/indexing/multiindex/test_insert.py @@ -1,7 +1,6 @@ from numpy.random import randn -from pandas import DataFrame, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, Series, _testing as tm class TestMultiIndexInsertion: diff --git a/pandas/tests/indexing/multiindex/test_ix.py b/pandas/tests/indexing/multiindex/test_ix.py index abf989324e4a5..28d917358b9b0 100644 --- a/pandas/tests/indexing/multiindex/test_ix.py +++ b/pandas/tests/indexing/multiindex/test_ix.py @@ -3,8 +3,7 @@ from pandas.errors import PerformanceWarning -from pandas import DataFrame, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, _testing as tm class TestMultiIndex: diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index f0cbdbe8d0564..939fcc5f6c983 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm from pandas.core.indexing import IndexingError diff --git a/pandas/tests/indexing/multiindex/test_multiindex.py b/pandas/tests/indexing/multiindex/test_multiindex.py index 5e5fcd3db88d8..fdf839b5503e1 100644 --- a/pandas/tests/indexing/multiindex/test_multiindex.py +++ b/pandas/tests/indexing/multiindex/test_multiindex.py @@ -1,11 +1,10 @@ import numpy as np -import pandas._libs.index as _index +from pandas._libs import index as _index from pandas.errors import PerformanceWarning import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm class TestMultiIndexBasic: diff --git a/pandas/tests/indexing/multiindex/test_partial.py b/pandas/tests/indexing/multiindex/test_partial.py index 538aa1d3a1164..1b7c6d0482587 100644 --- a/pandas/tests/indexing/multiindex/test_partial.py +++ b/pandas/tests/indexing/multiindex/test_partial.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Float64Index, Int64Index, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, Float64Index, Int64Index, MultiIndex, _testing as tm class TestMultiIndexPartial: diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index 853b92ea91274..c25f6a8535324 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -3,9 +3,17 @@ import pytest import pandas as pd -from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range, isna, notna -import pandas._testing as tm -import pandas.core.common as com +from pandas import ( + DataFrame, + MultiIndex, + Series, + Timestamp, + _testing as tm, + date_range, + isna, + notna, +) +from pandas.core import common as com class TestMultiIndexSetItem: diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py index 532bb4f2e6dac..50a4ea62b9b75 100644 --- a/pandas/tests/indexing/multiindex/test_slice.py +++ b/pandas/tests/indexing/multiindex/test_slice.py @@ -4,8 +4,7 @@ from pandas.errors import UnsortedIndexError import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, Timestamp -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, _testing as tm from pandas.core.indexing import _non_reducing_slice from pandas.tests.indexing.common import _mklbl diff --git a/pandas/tests/indexing/multiindex/test_sorted.py b/pandas/tests/indexing/multiindex/test_sorted.py index 572cb9da405d1..4fd8f1ece1e6b 100644 --- a/pandas/tests/indexing/multiindex/test_sorted.py +++ b/pandas/tests/indexing/multiindex/test_sorted.py @@ -2,8 +2,7 @@ from numpy.random import randn import pytest -from pandas import DataFrame, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, Series, _testing as tm class TestMultiIndexSorted: diff --git a/pandas/tests/indexing/multiindex/test_xs.py b/pandas/tests/indexing/multiindex/test_xs.py index b807795b9c309..15c0dca11adab 100644 --- a/pandas/tests/indexing/multiindex/test_xs.py +++ b/pandas/tests/indexing/multiindex/test_xs.py @@ -1,9 +1,16 @@ import numpy as np import pytest -from pandas import DataFrame, Index, MultiIndex, Series, concat, date_range -import pandas._testing as tm -import pandas.core.common as com +from pandas import ( + DataFrame, + Index, + MultiIndex, + Series, + _testing as tm, + concat, + date_range, +) +from pandas.core import common as com @pytest.fixture diff --git a/pandas/tests/indexing/test_callable.py b/pandas/tests/indexing/test_callable.py index 621417eb38d94..d168122fe155d 100644 --- a/pandas/tests/indexing/test_callable.py +++ b/pandas/tests/indexing/test_callable.py @@ -1,7 +1,7 @@ import numpy as np import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestIndexingCallable: diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index 98edb56260b01..9327e9e62194c 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -14,8 +14,8 @@ Series, Timedelta, Timestamp, + _testing as tm, ) -import pandas._testing as tm from pandas.api.types import CategoricalDtype as CDT diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index fa5fe5ba5c384..e66fd96daf51f 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -2,9 +2,15 @@ import pytest import pandas as pd -from pandas import DataFrame, Series, Timestamp, date_range, option_context -import pandas._testing as tm -import pandas.core.common as com +from pandas import ( + DataFrame, + Series, + Timestamp, + _testing as tm, + date_range, + option_context, +) +from pandas.core import common as com class TestCaching: diff --git a/pandas/tests/indexing/test_check_indexer.py b/pandas/tests/indexing/test_check_indexer.py index 69d4065234d93..2125994781325 100644 --- a/pandas/tests/indexing/test_check_indexer.py +++ b/pandas/tests/indexing/test_check_indexer.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.api.indexers import check_array_indexer diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 1512c88a68778..316dcc88ebf7b 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -5,10 +5,8 @@ import numpy as np import pytest -import pandas.compat as compat - import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm, compat as compat ############################################################### # Index / Series common tests which may trigger dtype coercions diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index ad71b6b72df33..d93ac2d51e400 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import DataFrame, Index, Series, Timestamp, _testing as tm, date_range class TestDatetimeIndex: diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index 18b9898e7d800..2e243a34ec8d1 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -3,8 +3,15 @@ import numpy as np import pytest -from pandas import DataFrame, Float64Index, Index, Int64Index, RangeIndex, Series -import pandas._testing as tm +from pandas import ( + DataFrame, + Float64Index, + Index, + Int64Index, + RangeIndex, + Series, + _testing as tm, +) # We pass through the error message from numpy _slice_iloc_msg = re.escape( diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index c5f40102874dd..afa0333fab3a4 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -1,5 +1,4 @@ """ test positional based indexing with iloc """ - from datetime import datetime from warnings import catch_warnings, simplefilter @@ -7,8 +6,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series, concat, date_range, isna -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, concat, date_range, isna from pandas.api.types import is_scalar from pandas.core.indexing import IndexingError from pandas.tests.indexing.common import Base diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index ced70069dd955..737d3df90b94a 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -1,5 +1,4 @@ """ test fancy indexing & misc """ - from datetime import datetime import re import weakref @@ -10,8 +9,7 @@ from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype import pandas as pd -from pandas import DataFrame, Index, NaT, Series -import pandas._testing as tm +from pandas import DataFrame, Index, NaT, Series, _testing as tm from pandas.core.indexing import _maybe_numeric_slice, _non_reducing_slice from pandas.tests.indexing.common import _mklbl diff --git a/pandas/tests/indexing/test_indexing_slow.py b/pandas/tests/indexing/test_indexing_slow.py index 2ffa44bec14a6..2e348b77e6ed5 100644 --- a/pandas/tests/indexing/test_indexing_slow.py +++ b/pandas/tests/indexing/test_indexing_slow.py @@ -1,7 +1,6 @@ import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm class TestIndexingSlow: diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 30b13b6ea9fce..8d05c52ffab7f 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -6,8 +6,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, Timestamp, _testing as tm, date_range from pandas.api.types import is_scalar from pandas.tests.indexing.common import Base diff --git a/pandas/tests/indexing/test_na_indexing.py b/pandas/tests/indexing/test_na_indexing.py index 9e8ef6e6e1c22..7d7cc0a85581a 100644 --- a/pandas/tests/indexing/test_na_indexing.py +++ b/pandas/tests/indexing/test_na_indexing.py @@ -1,7 +1,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 350f86b4e9fd0..c8cd591c7d561 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -3,13 +3,20 @@ TODO: these should be split among the indexer tests """ - import numpy as np import pytest import pandas as pd -from pandas import DataFrame, Index, Period, Series, Timestamp, date_range, period_range -import pandas._testing as tm +from pandas import ( + DataFrame, + Index, + Period, + Series, + Timestamp, + _testing as tm, + date_range, + period_range, +) class TestPartialSetting: diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index 4337f01ea33e0..40cb02e93cc07 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -4,8 +4,15 @@ import numpy as np import pytest -from pandas import DataFrame, Series, Timedelta, Timestamp, date_range, period_range -import pandas._testing as tm +from pandas import ( + DataFrame, + Series, + Timedelta, + Timestamp, + _testing as tm, + date_range, + period_range, +) from pandas.tests.indexing.common import Base diff --git a/pandas/tests/indexing/test_timedelta.py b/pandas/tests/indexing/test_timedelta.py index 7da368e4bb321..08591b55f6ff1 100644 --- a/pandas/tests/indexing/test_timedelta.py +++ b/pandas/tests/indexing/test_timedelta.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestTimedeltaIndexing: diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 06ccdd2484a2a..802c7cf42a4c4 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -10,9 +10,16 @@ from pandas._libs.internals import BlockPlacement import pandas as pd -from pandas import Categorical, DataFrame, DatetimeIndex, Index, MultiIndex, Series -import pandas._testing as tm -import pandas.core.algorithms as algos +from pandas import ( + Categorical, + DataFrame, + DatetimeIndex, + Index, + MultiIndex, + Series, + _testing as tm, +) +from pandas.core import algorithms as algos from pandas.core.arrays import DatetimeArray, SparseArray, TimedeltaArray from pandas.core.internals import BlockManager, SingleBlockManager, make_block diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py index fcee25c258efa..bbad0647314a6 100644 --- a/pandas/tests/io/conftest.py +++ b/pandas/tests/io/conftest.py @@ -2,7 +2,7 @@ import pytest -import pandas._testing as tm +from pandas import _testing as tm from pandas.io.parsers import read_csv diff --git a/pandas/tests/io/excel/conftest.py b/pandas/tests/io/excel/conftest.py index 0455e0d61ad97..d57fc7fe8e9ae 100644 --- a/pandas/tests/io/excel/conftest.py +++ b/pandas/tests/io/excel/conftest.py @@ -1,8 +1,7 @@ import pytest -import pandas.util._test_decorators as td - -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td from pandas.io.parsers import read_csv diff --git a/pandas/tests/io/excel/test_odf.py b/pandas/tests/io/excel/test_odf.py index d6c6399f082c6..2587cba2671ce 100644 --- a/pandas/tests/io/excel/test_odf.py +++ b/pandas/tests/io/excel/test_odf.py @@ -4,7 +4,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm pytest.importorskip("odf") diff --git a/pandas/tests/io/excel/test_odswriter.py b/pandas/tests/io/excel/test_odswriter.py index b50c641ebf0c0..381c58d8a274f 100644 --- a/pandas/tests/io/excel/test_odswriter.py +++ b/pandas/tests/io/excel/test_odswriter.py @@ -1,6 +1,6 @@ import pytest -import pandas._testing as tm +from pandas import _testing as tm from pandas.io.excel import ExcelWriter diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index 5f8d58ea1f105..8242efd6be435 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm from pandas.io.excel import ExcelWriter, _OpenpyxlWriter diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index b610c5ec3a838..6240925755118 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -8,11 +8,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm +from pandas.util import _test_decorators as td @contextlib.contextmanager diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py index 936fc175a493b..95c3779c29b15 100644 --- a/pandas/tests/io/excel/test_style.py +++ b/pandas/tests/io/excel/test_style.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm from pandas.io.excel import ExcelWriter from pandas.io.formats.excel import ExcelFormatter diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index e3ee53b63e102..9cd7a6c36acbf 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -6,11 +6,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Index, MultiIndex, get_option, set_option -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, _testing as tm, get_option, set_option +from pandas.util import _test_decorators as td from pandas.io.excel import ( ExcelFile, diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py index 1c9c514b20f46..2efcf0a9fa587 100644 --- a/pandas/tests/io/excel/test_xlrd.py +++ b/pandas/tests/io/excel/test_xlrd.py @@ -1,7 +1,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.io.excel import ExcelFile diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py index b6f791434a92b..5be8aeb9f9200 100644 --- a/pandas/tests/io/excel/test_xlsxwriter.py +++ b/pandas/tests/io/excel/test_xlsxwriter.py @@ -2,8 +2,7 @@ import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm from pandas.io.excel import ExcelWriter diff --git a/pandas/tests/io/excel/test_xlwt.py b/pandas/tests/io/excel/test_xlwt.py index a2d8b9fce9767..e1656011d467d 100644 --- a/pandas/tests/io/excel/test_xlwt.py +++ b/pandas/tests/io/excel/test_xlwt.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, _testing as tm from pandas.io.excel import ExcelWriter, _XlwtWriter diff --git a/pandas/tests/io/formats/test_css.py b/pandas/tests/io/formats/test_css.py index 9383f86e335fa..b4442c39c6127 100644 --- a/pandas/tests/io/formats/test_css.py +++ b/pandas/tests/io/formats/test_css.py @@ -1,6 +1,6 @@ import pytest -import pandas._testing as tm +from pandas import _testing as tm from pandas.io.formats.css import CSSResolver, CSSWarning diff --git a/pandas/tests/io/formats/test_eng_formatting.py b/pandas/tests/io/formats/test_eng_formatting.py index 6801316ada8a3..2038a7f6e2e7b 100644 --- a/pandas/tests/io/formats/test_eng_formatting.py +++ b/pandas/tests/io/formats/test_eng_formatting.py @@ -1,10 +1,9 @@ import numpy as np import pandas as pd -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm -import pandas.io.formats.format as fmt +from pandas.io.formats import format as fmt class TestEngFormatter: diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index e236b3da73c69..d14e34b67efd2 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1,7 +1,6 @@ """ Test output formatting for Series/DataFrame, including to_string & reprs """ - from datetime import datetime from io import StringIO import itertools @@ -28,6 +27,7 @@ NaT, Series, Timestamp, + _testing as tm, date_range, get_option, option_context, @@ -35,10 +35,8 @@ reset_option, set_option, ) -import pandas._testing as tm -import pandas.io.formats.format as fmt -import pandas.io.formats.printing as printing +from pandas.io.formats import format as fmt, printing as printing use_32bit_repr = is_platform_windows() or is_platform_32bit() diff --git a/pandas/tests/io/formats/test_info.py b/pandas/tests/io/formats/test_info.py index 877bd1650ae60..67ea393ab0113 100644 --- a/pandas/tests/io/formats/test_info.py +++ b/pandas/tests/io/formats/test_info.py @@ -14,12 +14,12 @@ DataFrame, MultiIndex, Series, + _testing as tm, date_range, option_context, reset_option, set_option, ) -import pandas._testing as tm @pytest.fixture diff --git a/pandas/tests/io/formats/test_printing.py b/pandas/tests/io/formats/test_printing.py index f0d5ef19c4468..8fa12a0834f6d 100644 --- a/pandas/tests/io/formats/test_printing.py +++ b/pandas/tests/io/formats/test_printing.py @@ -1,12 +1,11 @@ import numpy as np import pytest -import pandas._config.config as cf +from pandas._config import config as cf import pandas as pd -import pandas.io.formats.format as fmt -import pandas.io.formats.printing as printing +from pandas.io.formats import format as fmt, printing as printing def test_adjoin(): diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 9c6910637fa7e..0c0e07582d72e 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -5,11 +5,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm +from pandas.util import _test_decorators as td jinja2 = pytest.importorskip("jinja2") from pandas.io.formats.style import Styler, _get_level_lengths # noqa # isort:skip diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index 4c86e3a16b135..650a150cdd919 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -6,8 +6,7 @@ import pytest import pandas as pd -from pandas import DataFrame, compat -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, compat class TestToCSV: diff --git a/pandas/tests/io/formats/test_to_excel.py b/pandas/tests/io/formats/test_to_excel.py index 8529a0fb33b67..9b3b44c99d270 100644 --- a/pandas/tests/io/formats/test_to_excel.py +++ b/pandas/tests/io/formats/test_to_excel.py @@ -2,10 +2,9 @@ ExcelFormatter is tested implicitly in pandas/tests/io/excel """ - import pytest -import pandas._testing as tm +from pandas import _testing as tm from pandas.io.formats.css import CSSWarning from pandas.io.formats.excel import CSSToExcelConverter diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py index e85fd398964d0..f7b970433e28e 100644 --- a/pandas/tests/io/formats/test_to_html.py +++ b/pandas/tests/io/formats/test_to_html.py @@ -6,10 +6,9 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, MultiIndex, option_context -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, _testing as tm, option_context -import pandas.io.formats.format as fmt +from pandas.io.formats import format as fmt lorem_ipsum = ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index 509e5bcb33304..d4b4fac2e52d5 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm class TestToLatex: diff --git a/pandas/tests/io/json/test_compression.py b/pandas/tests/io/json/test_compression.py index 182c21ed1d416..9c44ada185e42 100644 --- a/pandas/tests/io/json/test_compression.py +++ b/pandas/tests/io/json/test_compression.py @@ -1,9 +1,8 @@ import pytest -import pandas.util._test_decorators as td - import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td def test_compression_roundtrip(compression): diff --git a/pandas/tests/io/json/test_deprecated_kwargs.py b/pandas/tests/io/json/test_deprecated_kwargs.py index 79245bc9d34a8..4bfba86d6d4db 100644 --- a/pandas/tests/io/json/test_deprecated_kwargs.py +++ b/pandas/tests/io/json/test_deprecated_kwargs.py @@ -1,9 +1,8 @@ """ Tests for the deprecated keyword arguments for `read_json`. """ - import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.io.json import read_json diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index 22b4ec189a0f1..e386e9703e758 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -9,8 +9,7 @@ from pandas.core.dtypes.dtypes import CategoricalDtype, DatetimeTZDtype, PeriodDtype import pandas as pd -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm from pandas.io.json._table_schema import ( as_json_table_type, diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index 8d93fbcc063f4..b95f74ee0d280 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, Series, json_normalize -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm, json_normalize from pandas.io.json._normalize import nested_to_record diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index c4db0170ecc90..966cfeda55fc6 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -10,7 +10,7 @@ import pytest from pandas.compat import is_platform_32bit, is_platform_windows -import pandas.util._test_decorators as td +from pandas.util._test_decorators import skip_if_not_us_locale import pandas as pd from pandas import DataFrame, DatetimeIndex, Series, Timestamp, compat, read_json @@ -1209,7 +1209,7 @@ def test_read_inline_jsonl(self): expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) tm.assert_frame_equal(result, expected) - @td.skip_if_not_us_locale + @skip_if_not_us_locale def test_read_s3_jsonl(self, s3_resource): # GH17200 diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py index b475fa2c514ff..9c56f8527f436 100644 --- a/pandas/tests/io/json/test_readlines.py +++ b/pandas/tests/io/json/test_readlines.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, read_json -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, read_json from pandas.io.json._json import JsonReader diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index f969cbca9f427..f97bf999a4c31 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -13,12 +13,20 @@ import pytest import pytz -import pandas._libs.json as ujson +from pandas._libs import json as ujson from pandas._libs.tslib import Timestamp -import pandas.compat as compat -from pandas import DataFrame, DatetimeIndex, Index, NaT, Series, Timedelta, date_range -import pandas._testing as tm +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + NaT, + Series, + Timedelta, + _testing as tm, + compat as compat, + date_range, +) def _clean_dict(d): diff --git a/pandas/tests/io/parser/test_c_parser_only.py b/pandas/tests/io/parser/test_c_parser_only.py index d76d01904731a..f06ab740de7e3 100644 --- a/pandas/tests/io/parser/test_c_parser_only.py +++ b/pandas/tests/io/parser/test_c_parser_only.py @@ -4,7 +4,6 @@ these tests out of this module as soon as the Python parser can accept further arguments when parsing. """ - from io import BytesIO, StringIO, TextIOWrapper import mmap import os @@ -14,10 +13,9 @@ import pytest from pandas.errors import ParserError -import pandas.util._test_decorators as td -from pandas import DataFrame, concat -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, concat +from pandas.util import _test_decorators as td @pytest.mark.parametrize( diff --git a/pandas/tests/io/parser/test_comment.py b/pandas/tests/io/parser/test_comment.py index 60e32d7c27200..7bed3e46e24ae 100644 --- a/pandas/tests/io/parser/test_comment.py +++ b/pandas/tests/io/parser/test_comment.py @@ -7,8 +7,7 @@ import numpy as np import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm @pytest.mark.parametrize("na_values", [None, ["NaN"]]) diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index 12e73bae40eac..cc5305b21f58b 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -16,10 +16,9 @@ from pandas._libs.tslib import Timestamp from pandas.errors import DtypeWarning, EmptyDataError, ParserError -import pandas.util._test_decorators as td -from pandas import DataFrame, Index, MultiIndex, Series, compat, concat -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm, compat, concat +from pandas.util import _test_decorators as td from pandas.io.parsers import CParserWrapper, TextFileReader, TextParser diff --git a/pandas/tests/io/parser/test_compression.py b/pandas/tests/io/parser/test_compression.py index b773664adda72..d1c9bc8556db1 100644 --- a/pandas/tests/io/parser/test_compression.py +++ b/pandas/tests/io/parser/test_compression.py @@ -2,14 +2,13 @@ Tests compressed data parsing functionality for all of the parsers defined in parsers.py """ - import os import zipfile import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.fixture(params=[True, False]) diff --git a/pandas/tests/io/parser/test_converters.py b/pandas/tests/io/parser/test_converters.py index 88b400d9a11df..a037af4888e54 100644 --- a/pandas/tests/io/parser/test_converters.py +++ b/pandas/tests/io/parser/test_converters.py @@ -9,8 +9,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index -import pandas._testing as tm +from pandas import DataFrame, Index, _testing as tm def test_converters_type_must_be_dict(all_parsers): diff --git a/pandas/tests/io/parser/test_dialect.py b/pandas/tests/io/parser/test_dialect.py index cc65def0fd096..aed5203d81999 100644 --- a/pandas/tests/io/parser/test_dialect.py +++ b/pandas/tests/io/parser/test_dialect.py @@ -2,7 +2,6 @@ Tests that dialects are properly handled during parsing for all of the parsers defined in parsers.py """ - import csv from io import StringIO @@ -10,8 +9,7 @@ from pandas.errors import ParserWarning -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm @pytest.fixture diff --git a/pandas/tests/io/parser/test_dtypes.py b/pandas/tests/io/parser/test_dtypes.py index 6ac310e3b2227..d1f2938d83fe3 100644 --- a/pandas/tests/io/parser/test_dtypes.py +++ b/pandas/tests/io/parser/test_dtypes.py @@ -13,8 +13,16 @@ from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd -from pandas import Categorical, DataFrame, Index, MultiIndex, Series, Timestamp, concat -import pandas._testing as tm +from pandas import ( + Categorical, + DataFrame, + Index, + MultiIndex, + Series, + Timestamp, + _testing as tm, + concat, +) @pytest.mark.parametrize("dtype", [str, object]) diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py index de7b3bed034c7..413e425e50fe4 100644 --- a/pandas/tests/io/parser/test_encoding.py +++ b/pandas/tests/io/parser/test_encoding.py @@ -2,7 +2,6 @@ Tests encoding functionality during parsing for all of the parsers defined in parsers.py """ - from io import BytesIO import os import tempfile @@ -10,8 +9,7 @@ import numpy as np import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm def test_bytes_io_input(all_parsers): diff --git a/pandas/tests/io/parser/test_header.py b/pandas/tests/io/parser/test_header.py index 4cd110136d7b0..b2f85bc7afeb0 100644 --- a/pandas/tests/io/parser/test_header.py +++ b/pandas/tests/io/parser/test_header.py @@ -2,7 +2,6 @@ Tests that the file header is properly handled or inferred during parsing for all of the parsers defined in parsers.py """ - from collections import namedtuple from io import StringIO @@ -11,8 +10,7 @@ from pandas.errors import ParserError -from pandas import DataFrame, Index, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, _testing as tm def test_read_with_bad_header(all_parsers): diff --git a/pandas/tests/io/parser/test_index_col.py b/pandas/tests/io/parser/test_index_col.py index 9f425168540ba..dd0717250ef82 100644 --- a/pandas/tests/io/parser/test_index_col.py +++ b/pandas/tests/io/parser/test_index_col.py @@ -8,8 +8,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, _testing as tm @pytest.mark.parametrize("with_header", [True, False]) diff --git a/pandas/tests/io/parser/test_mangle_dupes.py b/pandas/tests/io/parser/test_mangle_dupes.py index 5c4e642115798..08fbbf8122e1f 100644 --- a/pandas/tests/io/parser/test_mangle_dupes.py +++ b/pandas/tests/io/parser/test_mangle_dupes.py @@ -7,8 +7,7 @@ import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm @pytest.mark.parametrize("kwargs", [dict(), dict(mangle_dupe_cols=True)]) diff --git a/pandas/tests/io/parser/test_multi_thread.py b/pandas/tests/io/parser/test_multi_thread.py index d50560c684084..c8953de13fe42 100644 --- a/pandas/tests/io/parser/test_multi_thread.py +++ b/pandas/tests/io/parser/test_multi_thread.py @@ -9,8 +9,7 @@ import pytest import pandas as pd -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm def _construct_dataframe(num_rows): diff --git a/pandas/tests/io/parser/test_na_values.py b/pandas/tests/io/parser/test_na_values.py index 9f86bbd65640e..253819aa66caf 100644 --- a/pandas/tests/io/parser/test_na_values.py +++ b/pandas/tests/io/parser/test_na_values.py @@ -9,8 +9,7 @@ from pandas._libs.parsers import STR_NA_VALUES -from pandas import DataFrame, Index, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, _testing as tm def test_string_nas(all_parsers): diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index 509ae89909699..89d372089b478 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -8,10 +8,8 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm +from pandas.util import _test_decorators as td from pandas.io.feather_format import read_feather from pandas.io.parsers import read_csv diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index ed947755e3419..0d93d6ec3c743 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -2,7 +2,6 @@ Tests date parsing functionality for all of the parsers defined in parsers.py """ - from datetime import date, datetime from io import StringIO @@ -19,11 +18,10 @@ from pandas.compat.numpy import np_array_datetime64_compat import pandas as pd -from pandas import DataFrame, DatetimeIndex, Index, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, DatetimeIndex, Index, MultiIndex, Series, _testing as tm from pandas.core.indexes.datetimes import date_range -import pandas.io.date_converters as conv +from pandas.io import date_converters as conv # constant _DEFAULT_DATETIME = datetime(1, 1, 1) diff --git a/pandas/tests/io/parser/test_python_parser_only.py b/pandas/tests/io/parser/test_python_parser_only.py index 4d933fa02d36f..71d9e9d65b04e 100644 --- a/pandas/tests/io/parser/test_python_parser_only.py +++ b/pandas/tests/io/parser/test_python_parser_only.py @@ -4,7 +4,6 @@ these tests out of this module as soon as the C parser can accept further arguments when parsing. """ - import csv from io import BytesIO, StringIO @@ -12,8 +11,7 @@ from pandas.errors import ParserError -from pandas import DataFrame, Index, MultiIndex -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, _testing as tm def test_default_separator(python_parser_only): diff --git a/pandas/tests/io/parser/test_quoting.py b/pandas/tests/io/parser/test_quoting.py index 14773dfbea20e..a4bfb79078b75 100644 --- a/pandas/tests/io/parser/test_quoting.py +++ b/pandas/tests/io/parser/test_quoting.py @@ -2,7 +2,6 @@ Tests that quoting specifications are properly handled during parsing for all of the parsers defined in parsers.py """ - import csv from io import StringIO @@ -10,8 +9,7 @@ from pandas.errors import ParserError -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py index e982667f06f31..2511967c94653 100644 --- a/pandas/tests/io/parser/test_read_fwf.py +++ b/pandas/tests/io/parser/test_read_fwf.py @@ -3,7 +3,6 @@ test suite is independent of the others because the engine is set to 'python-fwf' internally. """ - from datetime import datetime from io import BytesIO, StringIO @@ -11,8 +10,7 @@ import pytest import pandas as pd -from pandas import DataFrame, DatetimeIndex -import pandas._testing as tm +from pandas import DataFrame, DatetimeIndex, _testing as tm from pandas.io.parsers import EmptyDataError, read_csv, read_fwf diff --git a/pandas/tests/io/parser/test_skiprows.py b/pandas/tests/io/parser/test_skiprows.py index fdccef1127c7e..4388146d3e661 100644 --- a/pandas/tests/io/parser/test_skiprows.py +++ b/pandas/tests/io/parser/test_skiprows.py @@ -2,7 +2,6 @@ Tests that skipped rows are properly handled during parsing for all of the parsers defined in parsers.py """ - from datetime import datetime from io import StringIO @@ -11,8 +10,7 @@ from pandas.errors import EmptyDataError -from pandas import DataFrame, Index -import pandas._testing as tm +from pandas import DataFrame, Index, _testing as tm @pytest.mark.parametrize("skiprows", [list(range(6)), 6]) diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py index 1c2518646bb29..a829da46e7602 100644 --- a/pandas/tests/io/parser/test_textreader.py +++ b/pandas/tests/io/parser/test_textreader.py @@ -8,11 +8,10 @@ import numpy as np import pytest -import pandas._libs.parsers as parser +from pandas._libs import parsers as parser from pandas._libs.parsers import TextReader -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm from pandas.io.parsers import TextFileReader, read_csv diff --git a/pandas/tests/io/parser/test_unsupported.py b/pandas/tests/io/parser/test_unsupported.py index 267fae760398a..30176b374b1f2 100644 --- a/pandas/tests/io/parser/test_unsupported.py +++ b/pandas/tests/io/parser/test_unsupported.py @@ -12,9 +12,9 @@ from pandas.errors import ParserError -import pandas._testing as tm +from pandas import _testing as tm -import pandas.io.parsers as parsers +from pandas.io import parsers as parsers from pandas.io.parsers import read_csv diff --git a/pandas/tests/io/parser/test_usecols.py b/pandas/tests/io/parser/test_usecols.py index d4e049cc3fcc2..5208c15e37606 100644 --- a/pandas/tests/io/parser/test_usecols.py +++ b/pandas/tests/io/parser/test_usecols.py @@ -9,8 +9,7 @@ from pandas._libs.tslib import Timestamp -from pandas import DataFrame, Index -import pandas._testing as tm +from pandas import DataFrame, Index, _testing as tm _msg_validate_usecols_arg = ( "'usecols' must either be list-like " diff --git a/pandas/tests/io/pytables/conftest.py b/pandas/tests/io/pytables/conftest.py index 38ffcb3b0e8ec..390ddb2c20257 100644 --- a/pandas/tests/io/pytables/conftest.py +++ b/pandas/tests/io/pytables/conftest.py @@ -1,6 +1,6 @@ import pytest -import pandas._testing as tm +from pandas import _testing as tm @pytest.fixture diff --git a/pandas/tests/io/pytables/test_compat.py b/pandas/tests/io/pytables/test_compat.py index c7200385aa998..a11e88e3b4575 100644 --- a/pandas/tests/io/pytables/test_compat.py +++ b/pandas/tests/io/pytables/test_compat.py @@ -1,7 +1,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.tests.io.pytables.common import ensure_clean_path tables = pytest.importorskip("tables") diff --git a/pandas/tests/io/pytables/test_complex.py b/pandas/tests/io/pytables/test_complex.py index 543940e674dba..a56073f254774 100644 --- a/pandas/tests/io/pytables/test_complex.py +++ b/pandas/tests/io/pytables/test_complex.py @@ -3,12 +3,10 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.tests.io.pytables.common import ensure_clean_path, ensure_clean_store +from pandas.util import _test_decorators as td from pandas.io.pytables import read_hdf diff --git a/pandas/tests/io/pytables/test_pytables_missing.py b/pandas/tests/io/pytables/test_pytables_missing.py index 9adb0a6d227da..53694ba98e543 100644 --- a/pandas/tests/io/pytables/test_pytables_missing.py +++ b/pandas/tests/io/pytables/test_pytables_missing.py @@ -1,9 +1,8 @@ import pytest -import pandas.util._test_decorators as td - import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td @td.skip_if_installed("tables") diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index df014171be817..f3ce2055ab6af 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -13,7 +13,6 @@ import pytest from pandas.compat import is_platform_little_endian, is_platform_windows -import pandas.util._test_decorators as td import pandas as pd from pandas import ( @@ -27,13 +26,13 @@ RangeIndex, Series, Timestamp, + _testing as tm, bdate_range, concat, date_range, isna, timedelta_range, ) -import pandas._testing as tm from pandas.tests.io.pytables.common import ( _maybe_remove, create_tempfile, @@ -43,6 +42,7 @@ safe_remove, tables, ) +from pandas.util import _test_decorators as td from pandas.io.pytables import ( ClosedFileError, diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index 38d32b0bdc8a3..063fc4e3efee2 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -3,16 +3,21 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, DatetimeIndex, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import ( + DataFrame, + DatetimeIndex, + Series, + Timestamp, + _testing as tm, + date_range, +) from pandas.tests.io.pytables.common import ( _maybe_remove, ensure_clean_path, ensure_clean_store, ) +from pandas.util import _test_decorators as td def _compare_with_tz(a, b): diff --git a/pandas/tests/io/sas/test_sas.py b/pandas/tests/io/sas/test_sas.py index 5d2643c20ceb2..c3ea613d0f3cf 100644 --- a/pandas/tests/io/sas/test_sas.py +++ b/pandas/tests/io/sas/test_sas.py @@ -2,8 +2,7 @@ import pytest -from pandas import read_sas -import pandas._testing as tm +from pandas import _testing as tm, read_sas class TestSas: diff --git a/pandas/tests/io/sas/test_sas7bdat.py b/pandas/tests/io/sas/test_sas7bdat.py index 8c14f9de9f61c..69b92f8b5c324 100644 --- a/pandas/tests/io/sas/test_sas7bdat.py +++ b/pandas/tests/io/sas/test_sas7bdat.py @@ -8,10 +8,10 @@ import pytest from pandas.errors import EmptyDataError -import pandas.util._test_decorators as td import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td # https://github.com/cython/cython/issues/1720 diff --git a/pandas/tests/io/sas/test_xport.py b/pandas/tests/io/sas/test_xport.py index 2682bafedb8f1..212115c33066e 100644 --- a/pandas/tests/io/sas/test_xport.py +++ b/pandas/tests/io/sas/test_xport.py @@ -4,7 +4,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.io.sas.sasreader import read_sas diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py index b627e0e1cad54..05d5a1eec33b1 100644 --- a/pandas/tests/io/test_clipboard.py +++ b/pandas/tests/io/test_clipboard.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import DataFrame, get_option, read_clipboard -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, get_option, read_clipboard from pandas.io.clipboard import clipboard_get, clipboard_set diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index dde38eb55ea7f..9babe854a6793 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -9,12 +9,12 @@ import pytest from pandas.compat import is_platform_windows -import pandas.util._test_decorators as td import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td -import pandas.io.common as icom +from pandas.io import common as icom class CustomFSPath: diff --git a/pandas/tests/io/test_compression.py b/pandas/tests/io/test_compression.py index 59c9bd0a36d3d..57fce79d9387d 100644 --- a/pandas/tests/io/test_compression.py +++ b/pandas/tests/io/test_compression.py @@ -6,9 +6,9 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm -import pandas.io.common as icom +from pandas.io import common as icom @pytest.mark.parametrize( diff --git a/pandas/tests/io/test_date_converters.py b/pandas/tests/io/test_date_converters.py index cdb8eca02a3e5..6fc867e05b04d 100644 --- a/pandas/tests/io/test_date_converters.py +++ b/pandas/tests/io/test_date_converters.py @@ -2,9 +2,9 @@ import numpy as np -import pandas._testing as tm +from pandas import _testing as tm -import pandas.io.date_converters as conv +from pandas.io import date_converters as conv def test_parse_date_time(): diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index a8a5c8f00e6bf..1b3615d0425cb 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -4,10 +4,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td from pandas.io.feather_format import read_feather, to_feather # noqa: E402 isort:skip diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py index c397a61616c1c..85e1b156620ff 100644 --- a/pandas/tests/io/test_fsspec.py +++ b/pandas/tests/io/test_fsspec.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, date_range, read_csv, read_parquet -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, date_range, read_csv, read_parquet from pandas.util import _test_decorators as td df1 = DataFrame( @@ -37,8 +36,8 @@ def test_read_csv(cleared_fs): def test_reasonable_error(monkeypatch, cleared_fs): - from fsspec.registry import known_implementations from fsspec import registry + from fsspec.registry import known_implementations registry.target.clear() with pytest.raises(ValueError) as e: diff --git a/pandas/tests/io/test_gcs.py b/pandas/tests/io/test_gcs.py index 4d93119ffa3f5..128454d8c0f12 100644 --- a/pandas/tests/io/test_gcs.py +++ b/pandas/tests/io/test_gcs.py @@ -4,15 +4,13 @@ import numpy as np import pytest -from pandas import DataFrame, date_range, read_csv -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, date_range, read_csv from pandas.util import _test_decorators as td @td.skip_if_no("gcsfs") def test_read_csv_gcs(monkeypatch): - from fsspec import AbstractFileSystem - from fsspec import registry + from fsspec import AbstractFileSystem, registry registry.target.clear() # noqa # remove state @@ -37,8 +35,7 @@ def open(*args, **kwargs): @td.skip_if_no("gcsfs") def test_to_csv_gcs(monkeypatch): - from fsspec import AbstractFileSystem - from fsspec import registry + from fsspec import AbstractFileSystem, registry registry.target.clear() # noqa # remove state df1 = DataFrame( @@ -76,8 +73,7 @@ def mock_get_filepath_or_buffer(*args, **kwargs): @td.skip_if_no("gcsfs") def test_to_parquet_gcs_new_file(monkeypatch, tmpdir): """Regression test for writing to a not-yet-existent GCS Parquet file.""" - from fsspec import AbstractFileSystem - from fsspec import registry + from fsspec import AbstractFileSystem, registry registry.target.clear() # noqa # remove state df1 = DataFrame( diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index 2c93dbb5b6b83..178634fdcba92 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -12,10 +12,17 @@ from pandas.compat import is_platform_windows from pandas.errors import ParserError -import pandas.util._test_decorators as td -from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range, read_csv -import pandas._testing as tm +from pandas import ( + DataFrame, + MultiIndex, + Series, + Timestamp, + _testing as tm, + date_range, + read_csv, +) +from pandas.util import _test_decorators as td from pandas.io.common import file_path_to_url import pandas.io.html diff --git a/pandas/tests/io/test_orc.py b/pandas/tests/io/test_orc.py index a1f9c6f6af51a..1e0b7281f0058 100644 --- a/pandas/tests/io/test_orc.py +++ b/pandas/tests/io/test_orc.py @@ -6,8 +6,7 @@ import pytest import pandas as pd -from pandas import read_orc -import pandas._testing as tm +from pandas import _testing as tm, read_orc pytest.importorskip("pyarrow", minversion="0.13.0") pytest.importorskip("pyarrow.orc") diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 82157f3d722a9..7e56cf1ac09ef 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -8,10 +8,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td from pandas.io.parquet import ( FastParquetImpl, @@ -606,7 +605,7 @@ def test_partition_cols_supported(self, pa, df_full): df = df_full with tm.ensure_clean_dir() as path: df.to_parquet(path, partition_cols=partition_cols, compression=None) - import pyarrow.parquet as pq + from pyarrow import parquet as pq dataset = pq.ParquetDataset(path, validate_schema=False) assert len(dataset.partitions.partition_names) == 2 @@ -619,7 +618,7 @@ def test_partition_cols_string(self, pa, df_full): df = df_full with tm.ensure_clean_dir() as path: df.to_parquet(path, partition_cols=partition_cols, compression=None) - import pyarrow.parquet as pq + from pyarrow import parquet as pq dataset = pq.ParquetDataset(path, validate_schema=False) assert len(dataset.partitions.partition_names) == 1 diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index e4d43db7834e3..6110a888c9454 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -23,11 +23,10 @@ import pytest from pandas.compat import _get_lzma_file, _import_lzma, is_platform_little_endian -import pandas.util._test_decorators as td import pandas as pd -from pandas import Index -import pandas._testing as tm +from pandas import Index, _testing as tm +from pandas.util import _test_decorators as td from pandas.tseries.offsets import Day, MonthEnd diff --git a/pandas/tests/io/test_spss.py b/pandas/tests/io/test_spss.py index 013f56f83c5ec..9915e20a8ed88 100644 --- a/pandas/tests/io/test_spss.py +++ b/pandas/tests/io/test_spss.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm pyreadstat = pytest.importorskip("pyreadstat") diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 0991fae39138e..6038f5fac1adc 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -16,7 +16,6 @@ - Tests for the fallback mode (`TestSQLiteFallback`) """ - import csv from datetime import date, datetime, time from io import StringIO @@ -35,23 +34,23 @@ MultiIndex, Series, Timestamp, + _testing as tm, concat, date_range, isna, to_datetime, to_timedelta, ) -import pandas._testing as tm -import pandas.io.sql as sql +from pandas.io import sql as sql from pandas.io.sql import read_sql_query, read_sql_table try: import sqlalchemy - import sqlalchemy.schema - import sqlalchemy.sql.sqltypes as sqltypes from sqlalchemy.ext import declarative from sqlalchemy.orm import session as sa_session + import sqlalchemy.schema + from sqlalchemy.sql import sqltypes as sqltypes SQLALCHEMY_INSTALLED = True except ImportError: diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 6d7fec803a8e0..db62b07c9278c 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -15,7 +15,7 @@ from pandas.core.dtypes.common import is_categorical_dtype import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.frame import DataFrame, Series from pandas.io.parsers import read_csv diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index 896d3278cdde1..1827567277b6b 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -5,14 +5,12 @@ from numpy import random from pandas.util._decorators import cache_readonly -import pandas.util._test_decorators as td from pandas.core.dtypes.api import is_list_like import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm - +from pandas import DataFrame, Series, _testing as tm +from pandas.util import _test_decorators as td """ This is a common base class used for various plotting tests @@ -24,6 +22,7 @@ class TestPlotBase: def setup_method(self, method): import matplotlib as mpl + from pandas.plotting._matplotlib import compat mpl.rcdefaults() @@ -67,13 +66,13 @@ def teardown_method(self, method): @cache_readonly def plt(self): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt return plt @cache_readonly def colorconverter(self): - import matplotlib.colors as colors + from matplotlib import colors as colors return colors.colorConverter @@ -187,8 +186,8 @@ def _check_colors( Series used for color grouping key used for andrew_curves, parallel_coordinates, radviz test """ + from matplotlib.collections import Collection, LineCollection, PolyCollection from matplotlib.lines import Line2D - from matplotlib.collections import Collection, PolyCollection, LineCollection conv = self.colorconverter if linecolors is not None: @@ -519,7 +518,7 @@ def _unpack_cycler(self, rcParams, field="color"): def _check_plot_works(f, filterwarnings="always", **kwargs): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt ret = None with warnings.catch_warnings(): diff --git a/pandas/tests/plotting/test_backend.py b/pandas/tests/plotting/test_backend.py index 9025f8c361a82..943ab83bad096 100644 --- a/pandas/tests/plotting/test_backend.py +++ b/pandas/tests/plotting/test_backend.py @@ -4,9 +4,8 @@ import pkg_resources import pytest -import pandas.util._test_decorators as td - import pandas +from pandas.util import _test_decorators as td dummy_backend = types.ModuleType("pandas_dummy_backend") setattr(dummy_backend, "plot", lambda *args, **kwargs: "used_dummy") diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 0a096acc9fa6d..5d6f045e8c21a 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -5,13 +5,17 @@ from numpy import random import pytest -import pandas.util._test_decorators as td - -from pandas import DataFrame, MultiIndex, Series, date_range, timedelta_range -import pandas._testing as tm +from pandas import ( + DataFrame, + MultiIndex, + Series, + _testing as tm, + date_range, + plotting as plotting, + timedelta_range, +) from pandas.tests.plotting.common import TestPlotBase, _check_plot_works - -import pandas.plotting as plotting +from pandas.util import _test_decorators as td """ Test cases for .boxplot method """ diff --git a/pandas/tests/plotting/test_common.py b/pandas/tests/plotting/test_common.py index af67ed7ec215b..0f9ea94aa648e 100644 --- a/pandas/tests/plotting/test_common.py +++ b/pandas/tests/plotting/test_common.py @@ -1,9 +1,8 @@ import pytest -import pandas.util._test_decorators as td - from pandas import DataFrame from pandas.tests.plotting.common import TestPlotBase, _check_plot_works +from pandas.util import _test_decorators as td @td.skip_if_no_mpl diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py index df2c9ecbd7a0a..ec76e18efbb71 100644 --- a/pandas/tests/plotting/test_converter.py +++ b/pandas/tests/plotting/test_converter.py @@ -5,13 +5,12 @@ import numpy as np import pytest -import pandas._config.config as cf +from pandas._config import config as cf from pandas.compat.numpy import np_datetime64_compat -import pandas.util._test_decorators as td -from pandas import Index, Period, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import Index, Period, Series, Timestamp, _testing as tm, date_range +from pandas.util import _test_decorators as td from pandas.plotting import ( deregister_matplotlib_converters, diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 201856669103a..4827ab1daab37 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -7,14 +7,13 @@ import pytest from pandas._libs.tslibs import BaseOffset, to_offset -import pandas.util._test_decorators as td -from pandas import DataFrame, Index, NaT, Series, isna -import pandas._testing as tm +from pandas import DataFrame, Index, NaT, Series, _testing as tm, isna from pandas.core.indexes.datetimes import DatetimeIndex, bdate_range, date_range from pandas.core.indexes.period import Period, PeriodIndex, period_range from pandas.core.indexes.timedeltas import timedelta_range from pandas.tests.plotting.common import TestPlotBase +from pandas.util import _test_decorators as td from pandas.tseries.offsets import WeekOfMonth @@ -258,7 +257,7 @@ def test_plot_multiple_inferred_freq(self): @pytest.mark.slow def test_uhf(self): - import pandas.plotting._matplotlib.converter as conv + from pandas.plotting._matplotlib import converter as conv idx = date_range("2012-6-22 21:59:51.960928", freq="L", periods=500) df = DataFrame(np.random.randn(len(idx), 2), index=idx) @@ -395,7 +394,7 @@ def _test(ax): _test(ax) def test_get_finder(self): - import pandas.plotting._matplotlib.converter as conv + from pandas.plotting._matplotlib import converter as conv assert conv.get_finder(to_offset("B")) == conv._daily_finder assert conv.get_finder(to_offset("D")) == conv._daily_finder @@ -1492,7 +1491,7 @@ def test_matplotlib_scatter_datetime64(self): def _check_plot_works(f, freq=None, series=None, *args, **kwargs): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt fig = plt.gcf() diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 3d85e79b15c4c..b95fc7e920f21 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -1,5 +1,4 @@ """ Test cases for DataFrame.plot """ - from datetime import date, datetime import itertools import string @@ -9,18 +8,24 @@ from numpy.random import rand, randn import pytest -import pandas.util._test_decorators as td - from pandas.core.dtypes.api import is_list_like import pandas as pd -from pandas import DataFrame, MultiIndex, PeriodIndex, Series, bdate_range, date_range -import pandas._testing as tm +from pandas import ( + DataFrame, + MultiIndex, + PeriodIndex, + Series, + _testing as tm, + bdate_range, + date_range, + plotting as plotting, +) from pandas.core.arrays import integer_array from pandas.tests.plotting.common import TestPlotBase, _check_plot_works +from pandas.util import _test_decorators as td from pandas.io.formats.printing import pprint_thing -import pandas.plotting as plotting @td.skip_if_no_mpl @@ -916,7 +921,7 @@ def test_area_lim(self): @pytest.mark.slow def test_bar_colors(self): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt default_colors = self._unpack_cycler(plt.rcParams) @@ -1230,7 +1235,7 @@ def test_if_hexbin_xaxis_label_is_visible(self): @pytest.mark.slow def test_if_scatterplot_colorbars_are_next_to_parent_axes(self): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt random_array = np.random.random((1000, 3)) df = pd.DataFrame(random_array, columns=["A label", "B label", "C label"]) @@ -1347,7 +1352,7 @@ def test_scatter_colors(self): def test_scatter_colorbar_different_cmap(self): # GH 33389 - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt df = pd.DataFrame({"x": [1, 2, 3], "y": [1, 3, 2], "c": [1, 2, 3]}) df["x2"] = df["x"] + 1 @@ -2016,7 +2021,7 @@ def test_no_legend(self): @pytest.mark.slow def test_style_by_column(self): - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt fig = plt.gcf() @@ -2407,8 +2412,8 @@ def test_specified_props_kwd_plot_box(self, props, expected): assert result[expected][0].get_color() == "C1" def test_default_color_cycle(self): - import matplotlib.pyplot as plt import cycler + from matplotlib import pyplot as plt colors = list("rgbk") plt.rcParams["axes.prop_cycle"] = cycler.cycler("color", colors) @@ -2845,7 +2850,7 @@ def test_sharex_and_ax(self): # https://github.com/pandas-dev/pandas/issues/9737 using gridspec, # the axis in fig.get_axis() are sorted differently than pandas # expected them, so make sure that only the right ones are removed - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt plt.close("all") gs, axes = _generate_4_axes_via_gridspec() @@ -2900,7 +2905,7 @@ def test_sharey_and_ax(self): # https://github.com/pandas-dev/pandas/issues/9737 using gridspec, # the axis in fig.get_axis() are sorted differently than pandas # expected them, so make sure that only the right ones are removed - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt gs, axes = _generate_4_axes_via_gridspec() @@ -2952,8 +2957,8 @@ def _check(axes): @td.skip_if_no_scipy def test_memory_leak(self): """ Check that every plot type gets properly collected. """ - import weakref import gc + import weakref results = {} for kind in plotting.PlotAccessor._all_kinds: @@ -2984,7 +2989,7 @@ def test_memory_leak(self): @pytest.mark.slow def test_df_subplots_patterns_minorticks(self): # GH 10657 - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt df = DataFrame( np.random.randn(10, 2), @@ -3031,8 +3036,7 @@ def test_df_subplots_patterns_minorticks(self): @pytest.mark.slow def test_df_gridspec_patterns(self): # GH 10819 - import matplotlib.pyplot as plt - import matplotlib.gridspec as gridspec + from matplotlib import gridspec as gridspec, pyplot as plt ts = Series(np.random.randn(10), index=date_range("1/1/2000", periods=10)) @@ -3421,8 +3425,8 @@ def test_xlabel_ylabel_dataframe_subplots( def _generate_4_axes_via_gridspec(): - import matplotlib.pyplot as plt import matplotlib as mpl + from matplotlib import pyplot as plt import matplotlib.gridspec # noqa gs = mpl.gridspec.GridSpec(2, 2) diff --git a/pandas/tests/plotting/test_groupby.py b/pandas/tests/plotting/test_groupby.py index 4ac23c2cffa15..cdfd4022c5774 100644 --- a/pandas/tests/plotting/test_groupby.py +++ b/pandas/tests/plotting/test_groupby.py @@ -1,14 +1,10 @@ """ Test cases for GroupBy.plot """ - - import numpy as np import pytest -import pandas.util._test_decorators as td - -from pandas import DataFrame, Index, Series -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm from pandas.tests.plotting.common import TestPlotBase +from pandas.util import _test_decorators as td @td.skip_if_no_mpl diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index b6a6c326c3df3..0dd4057200cd8 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -1,14 +1,11 @@ """ Test cases for .hist method """ - import numpy as np from numpy.random import randn import pytest -import pandas.util._test_decorators as td - -from pandas import DataFrame, Index, Series -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm from pandas.tests.plotting.common import TestPlotBase, _check_plot_works +from pandas.util import _test_decorators as td @td.skip_if_no_mpl @@ -101,7 +98,7 @@ def test_hist_layout_with_by(self): @pytest.mark.slow def test_hist_no_overlap(self): - from matplotlib.pyplot import subplot, gcf + from matplotlib.pyplot import gcf, subplot x = Series(randn(2)) y = Series(randn(2)) @@ -352,6 +349,7 @@ class TestDataFrameGroupByPlots(TestPlotBase): @pytest.mark.slow def test_grouped_hist_legacy(self): from matplotlib.patches import Rectangle + from pandas.plotting._matplotlib.hist import _grouped_hist df = DataFrame(randn(500, 2), columns=["A", "B"]) diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 75eeede472fe9..c218c3f5c7881 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -1,17 +1,12 @@ """ Test cases for misc plot functions """ - import numpy as np from numpy import random from numpy.random import randn import pytest -import pandas.util._test_decorators as td - -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, plotting as plotting from pandas.tests.plotting.common import TestPlotBase, _check_plot_works - -import pandas.plotting as plotting +from pandas.util import _test_decorators as td @td.skip_if_mpl @@ -131,9 +126,10 @@ def test_scatter_matrix_axis(self): @pytest.mark.slow def test_andrews_curves(self, iris): - from pandas.plotting import andrews_curves from matplotlib import cm + from pandas.plotting import andrews_curves + df = iris _check_plot_works(andrews_curves, frame=df, class_column="Name") @@ -206,9 +202,10 @@ def test_andrews_curves(self, iris): @pytest.mark.slow def test_parallel_coordinates(self, iris): - from pandas.plotting import parallel_coordinates from matplotlib import cm + from pandas.plotting import parallel_coordinates + df = iris ax = _check_plot_works(parallel_coordinates, frame=df, class_column="Name") @@ -279,9 +276,10 @@ def test_parallel_coordinates_with_sorted_labels(self): @pytest.mark.slow def test_radviz(self, iris): - from pandas.plotting import radviz from matplotlib import cm + from pandas.plotting import radviz + df = iris _check_plot_works(radviz, frame=df, class_column="Name") @@ -397,6 +395,7 @@ def test_get_standard_colors_no_appending(self): # Make sure not to add more colors so that matplotlib can cycle # correctly. from matplotlib import cm + from pandas.plotting._matplotlib.style import _get_standard_colors color_before = cm.gnuplot(range(5)) diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 316ca6ce91af7..63283bc27dbf6 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -1,6 +1,4 @@ """ Test cases for Series.plot """ - - from datetime import datetime from itertools import chain @@ -8,14 +6,10 @@ from numpy.random import randn import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, date_range, plotting as plotting from pandas.tests.plotting.common import TestPlotBase, _check_plot_works - -import pandas.plotting as plotting +from pandas.util import _test_decorators as td @td.skip_if_no_mpl @@ -450,7 +444,7 @@ def test_hist_layout_with_by(self): @pytest.mark.slow def test_hist_no_overlap(self): - from matplotlib.pyplot import subplot, gcf + from matplotlib.pyplot import gcf, subplot x = Series(randn(2)) y = Series(randn(2)) @@ -822,7 +816,8 @@ def test_standard_colors(self): @pytest.mark.slow def test_standard_colors_all(self): - import matplotlib.colors as colors + from matplotlib import colors as colors + from pandas.plotting._matplotlib.style import _get_standard_colors # multiple colors like mediumaquamarine diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index a112bc80b60b0..b6b6b44862313 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -17,11 +17,11 @@ Timedelta, TimedeltaIndex, Timestamp, + _testing as tm, isna, timedelta_range, to_timedelta, ) -import pandas._testing as tm from pandas.core import nanops diff --git a/pandas/tests/reductions/test_stat_reductions.py b/pandas/tests/reductions/test_stat_reductions.py index 59dbcb9ab9fa0..37bc937aaaff5 100644 --- a/pandas/tests/reductions/test_stat_reductions.py +++ b/pandas/tests/reductions/test_stat_reductions.py @@ -6,12 +6,10 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray +from pandas.util import _test_decorators as td class TestDatetimeLikeStatReductions: diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py index 28d33ebb23c20..a368c9737b052 100644 --- a/pandas/tests/resample/test_base.py +++ b/pandas/tests/resample/test_base.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.core.groupby.groupby import DataError from pandas.core.groupby.grouper import Grouper from pandas.core.indexes.datetimes import date_range diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index e7637a598403f..f4ebc025f5914 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -10,14 +10,13 @@ from pandas.errors import UnsupportedFunctionCall import pandas as pd -from pandas import DataFrame, Series, Timedelta, Timestamp, isna, notna -import pandas._testing as tm +from pandas import DataFrame, Series, Timedelta, Timestamp, _testing as tm, isna, notna from pandas.core.groupby.grouper import Grouper from pandas.core.indexes.datetimes import date_range from pandas.core.indexes.period import Period, period_range from pandas.core.resample import DatetimeIndex, _get_timestamp_range_edges -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets as offsets from pandas.tseries.offsets import Minute diff --git a/pandas/tests/resample/test_deprecated.py b/pandas/tests/resample/test_deprecated.py index 8b3adbf08d157..d1fa4f74b61b2 100644 --- a/pandas/tests/resample/test_deprecated.py +++ b/pandas/tests/resample/test_deprecated.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.core.indexes.datetimes import date_range from pandas.core.indexes.period import PeriodIndex, period_range from pandas.core.indexes.timedeltas import timedelta_range diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index fe02eaef8ba82..bde2729bde394 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -10,13 +10,12 @@ from pandas.errors import InvalidIndexError import pandas as pd -from pandas import DataFrame, Series, Timestamp -import pandas._testing as tm +from pandas import DataFrame, Series, Timestamp, _testing as tm from pandas.core.indexes.datetimes import date_range from pandas.core.indexes.period import Period, PeriodIndex, period_range from pandas.core.resample import _get_period_range_edges -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets as offsets @pytest.fixture() diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index 73aa01cff84fa..6f5dbb261721a 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.core.indexes.datetimes import date_range dti = date_range(start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq="Min") diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py index 26e429c47b494..66dd628971442 100644 --- a/pandas/tests/resample/test_time_grouper.py +++ b/pandas/tests/resample/test_time_grouper.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.core.groupby.grouper import Grouper from pandas.core.indexes.datetimes import date_range diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py index 0fbb60c176b30..af2535c1fa8ae 100644 --- a/pandas/tests/resample/test_timedelta.py +++ b/pandas/tests/resample/test_timedelta.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.core.indexes.timedeltas import timedelta_range diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index c33443e24b268..e737c00eb7ec0 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -5,8 +5,7 @@ from pandas._libs import join as libjoin import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, concat, merge -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm, concat, merge from pandas.tests.reshape.merge.test_merge import NGROUPS, N, get_test_data a_ = np.array diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 4fd3c688b8771..13c29bf229bca 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -24,8 +24,8 @@ Series, TimedeltaIndex, UInt64Index, + _testing as tm, ) -import pandas._testing as tm from pandas.api.types import CategoricalDtype as CDT from pandas.core.reshape.concat import concat from pandas.core.reshape.merge import MergeError, merge diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py index 9b09f0033715d..c15207a0ae4ae 100644 --- a/pandas/tests/reshape/merge/test_merge_asof.py +++ b/pandas/tests/reshape/merge/test_merge_asof.py @@ -5,8 +5,7 @@ import pytz import pandas as pd -from pandas import Timedelta, merge_asof, read_csv, to_datetime -import pandas._testing as tm +from pandas import Timedelta, _testing as tm, merge_asof, read_csv, to_datetime from pandas.core.reshape.merge import MergeError diff --git a/pandas/tests/reshape/merge/test_merge_index_as_string.py b/pandas/tests/reshape/merge/test_merge_index_as_string.py index 08614d04caf4b..27cfded8f3266 100644 --- a/pandas/tests/reshape/merge/test_merge_index_as_string.py +++ b/pandas/tests/reshape/merge/test_merge_index_as_string.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm @pytest.fixture diff --git a/pandas/tests/reshape/merge/test_merge_ordered.py b/pandas/tests/reshape/merge/test_merge_ordered.py index e0063925a03e1..6a57242d683a7 100644 --- a/pandas/tests/reshape/merge/test_merge_ordered.py +++ b/pandas/tests/reshape/merge/test_merge_ordered.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, merge_ordered -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, merge_ordered class TestMergeOrdered: diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py index 61fdafa0c6db2..777a53cd5dfc4 100644 --- a/pandas/tests/reshape/merge/test_multi.py +++ b/pandas/tests/reshape/merge/test_multi.py @@ -3,8 +3,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm from pandas.core.reshape.concat import concat from pandas.core.reshape.merge import merge diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 0159fabd04d59..1aee40dd24de8 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -22,12 +22,12 @@ MultiIndex, Series, Timestamp, + _testing as tm, concat, date_range, isna, read_csv, ) -import pandas._testing as tm from pandas.core.arrays import SparseArray from pandas.core.construction import create_series_with_explicit_dtype from pandas.tests.extension.decimal import to_decimal diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py index 8795af2e11122..3d12fca69225d 100644 --- a/pandas/tests/reshape/test_crosstab.py +++ b/pandas/tests/reshape/test_crosstab.py @@ -1,8 +1,15 @@ import numpy as np import pytest -from pandas import CategoricalIndex, DataFrame, Index, MultiIndex, Series, crosstab -import pandas._testing as tm +from pandas import ( + CategoricalIndex, + DataFrame, + Index, + MultiIndex, + Series, + _testing as tm, + crosstab, +) class TestCrosstab: diff --git a/pandas/tests/reshape/test_cut.py b/pandas/tests/reshape/test_cut.py index 60c80a8abdba6..39bd1b7208f5d 100644 --- a/pandas/tests/reshape/test_cut.py +++ b/pandas/tests/reshape/test_cut.py @@ -12,6 +12,7 @@ Series, TimedeltaIndex, Timestamp, + _testing as tm, cut, date_range, isna, @@ -19,9 +20,8 @@ timedelta_range, to_datetime, ) -import pandas._testing as tm from pandas.api.types import CategoricalDtype as CDT -import pandas.core.reshape.tile as tmod +from pandas.core.reshape import tile as tmod def test_simple(): diff --git a/pandas/tests/reshape/test_get_dummies.py b/pandas/tests/reshape/test_get_dummies.py index c003bfa6a239a..687470dd0f4ca 100644 --- a/pandas/tests/reshape/test_get_dummies.py +++ b/pandas/tests/reshape/test_get_dummies.py @@ -6,8 +6,14 @@ from pandas.core.dtypes.common import is_integer_dtype import pandas as pd -from pandas import Categorical, CategoricalIndex, DataFrame, Series, get_dummies -import pandas._testing as tm +from pandas import ( + Categorical, + CategoricalIndex, + DataFrame, + Series, + _testing as tm, + get_dummies, +) from pandas.core.arrays.sparse import SparseArray, SparseDtype diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index 2b75a1ec6ca6e..858a14185e559 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, lreshape, melt, wide_to_long -import pandas._testing as tm +from pandas import DataFrame, _testing as tm, lreshape, melt, wide_to_long class TestMelt: diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index c07a5673fe503..0456b5a1ec9f1 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -12,10 +12,10 @@ Index, MultiIndex, Series, + _testing as tm, concat, date_range, ) -import pandas._testing as tm from pandas.api.types import CategoricalDtype as CDT from pandas.core.reshape.pivot import pivot_table diff --git a/pandas/tests/reshape/test_pivot_multilevel.py b/pandas/tests/reshape/test_pivot_multilevel.py index 8374e829e6a28..0e23f9609d5f8 100644 --- a/pandas/tests/reshape/test_pivot_multilevel.py +++ b/pandas/tests/reshape/test_pivot_multilevel.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Index, MultiIndex -import pandas._testing as tm +from pandas import Index, MultiIndex, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/reshape/test_qcut.py b/pandas/tests/reshape/test_qcut.py index c436ab5d90578..1a7a3d6eba0e3 100644 --- a/pandas/tests/reshape/test_qcut.py +++ b/pandas/tests/reshape/test_qcut.py @@ -13,13 +13,13 @@ Series, TimedeltaIndex, Timestamp, + _testing as tm, cut, date_range, isna, qcut, timedelta_range, ) -import pandas._testing as tm from pandas.api.types import CategoricalDtype as CDT from pandas.core.algorithms import quantile diff --git a/pandas/tests/reshape/test_union_categoricals.py b/pandas/tests/reshape/test_union_categoricals.py index 8918d19e4ba7b..d1b5c4c68554a 100644 --- a/pandas/tests/reshape/test_union_categoricals.py +++ b/pandas/tests/reshape/test_union_categoricals.py @@ -4,8 +4,7 @@ from pandas.core.dtypes.concat import union_categoricals import pandas as pd -from pandas import Categorical, CategoricalIndex, Series -import pandas._testing as tm +from pandas import Categorical, CategoricalIndex, Series, _testing as tm class TestUnionCategoricals: diff --git a/pandas/tests/reshape/test_util.py b/pandas/tests/reshape/test_util.py index 9d074b5ade425..c70713c3b0a4c 100644 --- a/pandas/tests/reshape/test_util.py +++ b/pandas/tests/reshape/test_util.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Index, date_range -import pandas._testing as tm +from pandas import Index, _testing as tm, date_range from pandas.core.reshape.util import cartesian_product diff --git a/pandas/tests/scalar/interval/test_interval.py b/pandas/tests/scalar/interval/test_interval.py index a0151bb9ac7bf..3727ab4bc0dff 100644 --- a/pandas/tests/scalar/interval/test_interval.py +++ b/pandas/tests/scalar/interval/test_interval.py @@ -2,7 +2,7 @@ import pytest from pandas import Interval, Period, Timedelta, Timestamp -import pandas.core.common as com +from pandas.core import common as com @pytest.fixture diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index dcef0615121c1..654374cdfcdf3 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -12,8 +12,7 @@ from pandas.compat.numpy import np_datetime64_compat import pandas as pd -from pandas import NaT, Period, Timedelta, Timestamp, offsets -import pandas._testing as tm +from pandas import NaT, Period, Timedelta, Timestamp, _testing as tm, offsets class TestPeriodConstruction: diff --git a/pandas/tests/scalar/test_na_scalar.py b/pandas/tests/scalar/test_na_scalar.py index dc5eb15348c1b..6885bca3653bb 100644 --- a/pandas/tests/scalar/test_na_scalar.py +++ b/pandas/tests/scalar/test_na_scalar.py @@ -8,7 +8,7 @@ from pandas.core.dtypes.common import is_scalar import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_singleton(): diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index e1e2ea1a5cec8..2a0fe32d4e290 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -6,7 +6,6 @@ import pytz from pandas._libs.tslibs import iNaT -import pandas.compat as compat from pandas.core.dtypes.common import is_datetime64_any_dtype @@ -19,10 +18,11 @@ Timedelta, TimedeltaIndex, Timestamp, + _testing as tm, + compat as compat, isna, offsets, ) -import pandas._testing as tm from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.ops import roperator diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index cb33f99d9bd91..bdc8b4bb81320 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -8,8 +8,15 @@ import pytest import pandas as pd -from pandas import NaT, Timedelta, Timestamp, _is_numpy_dev, compat, offsets -import pandas._testing as tm +from pandas import ( + NaT, + Timedelta, + Timestamp, + _is_numpy_dev, + _testing as tm, + compat, + offsets, +) from pandas.core import ops diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index a01921bd6c4c2..a29561b14fa48 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -7,8 +7,7 @@ from pandas._libs.tslibs import NaT, iNaT import pandas as pd -from pandas import Timedelta, TimedeltaIndex, offsets, to_timedelta -import pandas._testing as tm +from pandas import Timedelta, TimedeltaIndex, _testing as tm, offsets, to_timedelta class TestTimedeltaUnaryOps: diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py index 954301b979074..32528030b0847 100644 --- a/pandas/tests/scalar/timestamp/test_arithmetic.py +++ b/pandas/tests/scalar/timestamp/test_arithmetic.py @@ -11,7 +11,7 @@ to_offset, ) -import pandas._testing as tm +from pandas import _testing as tm class TestTimestampArithmetic: diff --git a/pandas/tests/scalar/timestamp/test_comparisons.py b/pandas/tests/scalar/timestamp/test_comparisons.py index 71693a9ca61ce..74c17918b549c 100644 --- a/pandas/tests/scalar/timestamp/test_comparisons.py +++ b/pandas/tests/scalar/timestamp/test_comparisons.py @@ -4,8 +4,7 @@ import numpy as np import pytest -from pandas import Timestamp -import pandas._testing as tm +from pandas import Timestamp, _testing as tm class TestTimestampComparison: diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index cee7ac450e411..b0eb0c8b37d34 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -1,5 +1,4 @@ """ test the scalar Timestamp """ - import calendar from datetime import datetime, timedelta import locale @@ -13,10 +12,9 @@ from pandas._libs.tslibs.timezones import dateutil_gettz as gettz, get_timezone from pandas.compat.numpy import np_datetime64_compat -import pandas.util._test_decorators as td -from pandas import NaT, Timedelta, Timestamp -import pandas._testing as tm +from pandas import NaT, Timedelta, Timestamp, _testing as tm +from pandas.util import _test_decorators as td from pandas.tseries import offsets diff --git a/pandas/tests/scalar/timestamp/test_timezones.py b/pandas/tests/scalar/timestamp/test_timezones.py index f05f2054b2483..efa48fc0f3607 100644 --- a/pandas/tests/scalar/timestamp/test_timezones.py +++ b/pandas/tests/scalar/timestamp/test_timezones.py @@ -11,9 +11,9 @@ from pandas._libs.tslibs import timezones from pandas.errors import OutOfBoundsDatetime -import pandas.util._test_decorators as td from pandas import NaT, Timestamp +from pandas.util import _test_decorators as td class TestTimestampTZOperations: diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py index 8641bbd0a66f2..1f71f4be5459e 100644 --- a/pandas/tests/scalar/timestamp/test_unary_ops.py +++ b/pandas/tests/scalar/timestamp/test_unary_ops.py @@ -7,9 +7,9 @@ from pandas._libs.tslibs import NaT, Timestamp, conversion, to_offset from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG -import pandas.util._test_decorators as td -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td class TestTimestampUnaryOps: diff --git a/pandas/tests/series/apply/test_series_apply.py b/pandas/tests/series/apply/test_series_apply.py index 308398642895c..a50cb93e7ed58 100644 --- a/pandas/tests/series/apply/test_series_apply.py +++ b/pandas/tests/series/apply/test_series_apply.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, isna -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm, isna from pandas.core.base import SpecificationError diff --git a/pandas/tests/series/conftest.py b/pandas/tests/series/conftest.py index 87aefec559311..91b09b1d1bbc1 100644 --- a/pandas/tests/series/conftest.py +++ b/pandas/tests/series/conftest.py @@ -1,6 +1,6 @@ import pytest -import pandas._testing as tm +from pandas import _testing as tm @pytest.fixture diff --git a/pandas/tests/series/indexing/test_alter_index.py b/pandas/tests/series/indexing/test_alter_index.py index 0415434f01fcf..ae77d81111724 100644 --- a/pandas/tests/series/indexing/test_alter_index.py +++ b/pandas/tests/series/indexing/test_alter_index.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Categorical, Series, date_range, isna -import pandas._testing as tm +from pandas import Categorical, Series, _testing as tm, date_range, isna def test_reindex(datetime_series, string_series): diff --git a/pandas/tests/series/indexing/test_boolean.py b/pandas/tests/series/indexing/test_boolean.py index e2b71b1f2f412..f85ee757c76c8 100644 --- a/pandas/tests/series/indexing/test_boolean.py +++ b/pandas/tests/series/indexing/test_boolean.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Index, Series -import pandas._testing as tm +from pandas import Index, Series, _testing as tm from pandas.core.indexing import IndexingError from pandas.tseries.offsets import BDay diff --git a/pandas/tests/series/indexing/test_callable.py b/pandas/tests/series/indexing/test_callable.py index fe575cf146641..f469095e60ed6 100644 --- a/pandas/tests/series/indexing/test_callable.py +++ b/pandas/tests/series/indexing/test_callable.py @@ -1,5 +1,5 @@ import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_getitem_callable(): diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py index 0b34fab7b80b1..a8b2626b6612b 100644 --- a/pandas/tests/series/indexing/test_datetime.py +++ b/pandas/tests/series/indexing/test_datetime.py @@ -4,13 +4,18 @@ import numpy as np import pytest -from pandas._libs import iNaT -import pandas._libs.index as _index +from pandas._libs import iNaT, index as _index import pandas as pd -from pandas import DataFrame, DatetimeIndex, NaT, Series, Timestamp, date_range -import pandas._testing as tm - +from pandas import ( + DataFrame, + DatetimeIndex, + NaT, + Series, + Timestamp, + _testing as tm, + date_range, +) """ Also test support for datetime64[ns] in Series / DataFrame @@ -166,6 +171,7 @@ def test_getitem_setitem_datetime_tz_pytz(): def test_getitem_setitem_datetime_tz_dateutil(): from dateutil.tz import tzutc + from pandas._libs.tslibs.timezones import dateutil_gettz as gettz tz = ( diff --git a/pandas/tests/series/indexing/test_delitem.py b/pandas/tests/series/indexing/test_delitem.py index 6c7e3f2b06983..e55a4cef5ce46 100644 --- a/pandas/tests/series/indexing/test_delitem.py +++ b/pandas/tests/series/indexing/test_delitem.py @@ -1,7 +1,6 @@ import pytest -from pandas import Index, Series -import pandas._testing as tm +from pandas import Index, Series, _testing as tm class TestSeriesDelItem: diff --git a/pandas/tests/series/indexing/test_get.py b/pandas/tests/series/indexing/test_get.py index 3371c47fa1b0a..9cb695a87b708 100644 --- a/pandas/tests/series/indexing/test_get.py +++ b/pandas/tests/series/indexing/test_get.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm def test_get(): diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index 6b7cda89a4714..65ef83ca13574 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -9,8 +9,7 @@ from pandas._libs.tslibs import conversion, timezones import pandas as pd -from pandas import Series, Timestamp, date_range, period_range -import pandas._testing as tm +from pandas import Series, Timestamp, _testing as tm, date_range, period_range class TestSeriesGetitemScalars: diff --git a/pandas/tests/series/indexing/test_iloc.py b/pandas/tests/series/indexing/test_iloc.py index f276eb5b0b23d..6e6b5391fb4c2 100644 --- a/pandas/tests/series/indexing/test_iloc.py +++ b/pandas/tests/series/indexing/test_iloc.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm def test_iloc(): diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index 3ed25b8bca566..7ba0827f22ac6 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -1,5 +1,4 @@ """ test get/set & misc """ - from datetime import timedelta import numpy as np @@ -16,11 +15,11 @@ Series, Timedelta, Timestamp, + _testing as tm, date_range, period_range, timedelta_range, ) -import pandas._testing as tm from pandas.tseries.offsets import BDay diff --git a/pandas/tests/series/indexing/test_loc.py b/pandas/tests/series/indexing/test_loc.py index 368adcfb32215..66317c874ea2d 100644 --- a/pandas/tests/series/indexing/test_loc.py +++ b/pandas/tests/series/indexing/test_loc.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Series, Timestamp -import pandas._testing as tm +from pandas import Series, Timestamp, _testing as tm @pytest.mark.parametrize("val,expected", [(2 ** 63 - 1, 3), (2 ** 63, 4)]) diff --git a/pandas/tests/series/indexing/test_mask.py b/pandas/tests/series/indexing/test_mask.py index dc4fb530dbb52..9eecdd1557724 100644 --- a/pandas/tests/series/indexing/test_mask.py +++ b/pandas/tests/series/indexing/test_mask.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm def test_mask(): diff --git a/pandas/tests/series/indexing/test_numeric.py b/pandas/tests/series/indexing/test_numeric.py index b5bef46e95ec2..74d421e8574d2 100644 --- a/pandas/tests/series/indexing/test_numeric.py +++ b/pandas/tests/series/indexing/test_numeric.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, Series -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm def test_slice_float64(): diff --git a/pandas/tests/series/indexing/test_take.py b/pandas/tests/series/indexing/test_take.py index dc161b6be5d66..ee81286c44859 100644 --- a/pandas/tests/series/indexing/test_take.py +++ b/pandas/tests/series/indexing/test_take.py @@ -1,8 +1,7 @@ import pytest import pandas as pd -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm def test_take(): diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py index c4a2cb90f7090..bcd199ad2e6af 100644 --- a/pandas/tests/series/indexing/test_where.py +++ b/pandas/tests/series/indexing/test_where.py @@ -4,8 +4,7 @@ from pandas.core.dtypes.common import is_integer import pandas as pd -from pandas import Series, Timestamp, date_range, isna -import pandas._testing as tm +from pandas import Series, Timestamp, _testing as tm, date_range, isna def test_where_unsafe_int(sint_dtype): diff --git a/pandas/tests/series/methods/test_align.py b/pandas/tests/series/methods/test_align.py index 974ba5d1e35a7..3f7cdcf2b77ef 100644 --- a/pandas/tests/series/methods/test_align.py +++ b/pandas/tests/series/methods/test_align.py @@ -3,8 +3,7 @@ import pytz import pandas as pd -from pandas import Series, date_range, period_range -import pandas._testing as tm +from pandas import Series, _testing as tm, date_range, period_range @pytest.mark.parametrize( diff --git a/pandas/tests/series/methods/test_append.py b/pandas/tests/series/methods/test_append.py index 82bde7c233626..7b81934361d12 100644 --- a/pandas/tests/series/methods/test_append.py +++ b/pandas/tests/series/methods/test_append.py @@ -2,8 +2,15 @@ import pytest import pandas as pd -from pandas import DataFrame, DatetimeIndex, Index, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + Series, + Timestamp, + _testing as tm, + date_range, +) class TestSeriesAppend: diff --git a/pandas/tests/series/methods/test_argsort.py b/pandas/tests/series/methods/test_argsort.py index 4353eb4c8cd64..5b3cfdea814f6 100644 --- a/pandas/tests/series/methods/test_argsort.py +++ b/pandas/tests/series/methods/test_argsort.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Series, Timestamp, isna -import pandas._testing as tm +from pandas import Series, Timestamp, _testing as tm, isna class TestSeriesArgsort: diff --git a/pandas/tests/series/methods/test_asfreq.py b/pandas/tests/series/methods/test_asfreq.py index cd61c510c75f5..e2eabea1ac48d 100644 --- a/pandas/tests/series/methods/test_asfreq.py +++ b/pandas/tests/series/methods/test_asfreq.py @@ -3,8 +3,14 @@ import numpy as np import pytest -from pandas import DataFrame, DatetimeIndex, Series, date_range, period_range -import pandas._testing as tm +from pandas import ( + DataFrame, + DatetimeIndex, + Series, + _testing as tm, + date_range, + period_range, +) from pandas.tseries.offsets import BDay, BMonthEnd diff --git a/pandas/tests/series/methods/test_asof.py b/pandas/tests/series/methods/test_asof.py index 19caf4eccf748..2ac8225b12f37 100644 --- a/pandas/tests/series/methods/test_asof.py +++ b/pandas/tests/series/methods/test_asof.py @@ -3,8 +3,7 @@ from pandas._libs.tslibs import IncompatibleFrequency -from pandas import Series, Timestamp, date_range, isna, notna, offsets -import pandas._testing as tm +from pandas import Series, Timestamp, _testing as tm, date_range, isna, notna, offsets class TestSeriesAsof: @@ -90,7 +89,7 @@ def test_with_nan(self): tm.assert_series_equal(result, expected) def test_periodindex(self): - from pandas import period_range, PeriodIndex + from pandas import PeriodIndex, period_range # array or list or dates N = 50 diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index 9fdc4179de2e1..efe09bfb651d1 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -1,5 +1,4 @@ -from pandas import Series, date_range -import pandas._testing as tm +from pandas import Series, _testing as tm, date_range class TestAstype: diff --git a/pandas/tests/series/methods/test_at_time.py b/pandas/tests/series/methods/test_at_time.py index 810e4c1446708..433e05e0e5a72 100644 --- a/pandas/tests/series/methods/test_at_time.py +++ b/pandas/tests/series/methods/test_at_time.py @@ -5,8 +5,7 @@ from pandas._libs.tslibs import timezones -from pandas import DataFrame, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, date_range class TestAtTime: diff --git a/pandas/tests/series/methods/test_between.py b/pandas/tests/series/methods/test_between.py index 350a3fe6ff009..957895a2844e6 100644 --- a/pandas/tests/series/methods/test_between.py +++ b/pandas/tests/series/methods/test_between.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import Series, bdate_range, date_range, period_range -import pandas._testing as tm +from pandas import Series, _testing as tm, bdate_range, date_range, period_range class TestBetween: diff --git a/pandas/tests/series/methods/test_between_time.py b/pandas/tests/series/methods/test_between_time.py index e9d2f8e6f1637..73826d519fcff 100644 --- a/pandas/tests/series/methods/test_between_time.py +++ b/pandas/tests/series/methods/test_between_time.py @@ -5,10 +5,9 @@ import pytest from pandas._libs.tslibs import timezones -import pandas.util._test_decorators as td -from pandas import DataFrame, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, date_range +from pandas.util import _test_decorators as td class TestBetweenTime: diff --git a/pandas/tests/series/methods/test_clip.py b/pandas/tests/series/methods/test_clip.py index 37764d3b82c2d..e20856d7da165 100644 --- a/pandas/tests/series/methods/test_clip.py +++ b/pandas/tests/series/methods/test_clip.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Series, Timestamp, isna, notna -import pandas._testing as tm +from pandas import Series, Timestamp, _testing as tm, isna, notna class TestSeriesClip: diff --git a/pandas/tests/series/methods/test_combine.py b/pandas/tests/series/methods/test_combine.py index 75d47e3daa103..2cde1a669eba6 100644 --- a/pandas/tests/series/methods/test_combine.py +++ b/pandas/tests/series/methods/test_combine.py @@ -1,5 +1,4 @@ -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm class TestCombine: diff --git a/pandas/tests/series/methods/test_combine_first.py b/pandas/tests/series/methods/test_combine_first.py index 1ee55fbe39513..6e3c4edb94212 100644 --- a/pandas/tests/series/methods/test_combine_first.py +++ b/pandas/tests/series/methods/test_combine_first.py @@ -3,8 +3,7 @@ import numpy as np import pandas as pd -from pandas import Period, Series, date_range, period_range, to_datetime -import pandas._testing as tm +from pandas import Period, Series, _testing as tm, date_range, period_range, to_datetime class TestCombineFirst: diff --git a/pandas/tests/series/methods/test_compare.py b/pandas/tests/series/methods/test_compare.py index 8570800048898..908db844634ec 100644 --- a/pandas/tests/series/methods/test_compare.py +++ b/pandas/tests/series/methods/test_compare.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @pytest.mark.parametrize("align_axis", [0, 1, "index", "columns"]) diff --git a/pandas/tests/series/methods/test_convert_dtypes.py b/pandas/tests/series/methods/test_convert_dtypes.py index dd4bf642e68e8..52e9dd43742a2 100644 --- a/pandas/tests/series/methods/test_convert_dtypes.py +++ b/pandas/tests/series/methods/test_convert_dtypes.py @@ -6,7 +6,7 @@ from pandas.core.dtypes.common import is_interval_dtype import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestSeriesConvertDtypes: diff --git a/pandas/tests/series/methods/test_count.py b/pandas/tests/series/methods/test_count.py index 1ca48eeb7c441..299d32da4a1b8 100644 --- a/pandas/tests/series/methods/test_count.py +++ b/pandas/tests/series/methods/test_count.py @@ -1,8 +1,7 @@ import numpy as np import pandas as pd -from pandas import Categorical, MultiIndex, Series -import pandas._testing as tm +from pandas import Categorical, MultiIndex, Series, _testing as tm class TestSeriesCount: diff --git a/pandas/tests/series/methods/test_cov_corr.py b/pandas/tests/series/methods/test_cov_corr.py index 282f499506aae..0e769d24646f2 100644 --- a/pandas/tests/series/methods/test_cov_corr.py +++ b/pandas/tests/series/methods/test_cov_corr.py @@ -3,11 +3,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import Series, isna -import pandas._testing as tm +from pandas import Series, _testing as tm, isna +from pandas.util import _test_decorators as td class TestSeriesCov: @@ -55,7 +53,7 @@ def test_cov_ddof(self, test_ddof): class TestSeriesCorr: @td.skip_if_no_scipy def test_corr(self, datetime_series): - import scipy.stats as stats + from scipy import stats as stats # full overlap tm.assert_almost_equal(datetime_series.corr(datetime_series), 1) @@ -85,7 +83,7 @@ def test_corr(self, datetime_series): @td.skip_if_no_scipy def test_corr_rank(self): - import scipy.stats as stats + from scipy import stats as stats # kendall and spearman A = tm.makeTimeSeries() diff --git a/pandas/tests/series/methods/test_describe.py b/pandas/tests/series/methods/test_describe.py index a15dc0751aa7d..2311a7097d4c5 100644 --- a/pandas/tests/series/methods/test_describe.py +++ b/pandas/tests/series/methods/test_describe.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import Period, Series, Timedelta, Timestamp, date_range -import pandas._testing as tm +from pandas import Period, Series, Timedelta, Timestamp, _testing as tm, date_range class TestSeriesDescribe: diff --git a/pandas/tests/series/methods/test_diff.py b/pandas/tests/series/methods/test_diff.py index 033f75e95f11b..757c687feb212 100644 --- a/pandas/tests/series/methods/test_diff.py +++ b/pandas/tests/series/methods/test_diff.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Series, TimedeltaIndex, date_range -import pandas._testing as tm +from pandas import Series, TimedeltaIndex, _testing as tm, date_range class TestSeriesDiff: diff --git a/pandas/tests/series/methods/test_drop.py b/pandas/tests/series/methods/test_drop.py index 197fe9ff68df2..738c5d7280f61 100644 --- a/pandas/tests/series/methods/test_drop.py +++ b/pandas/tests/series/methods/test_drop.py @@ -1,8 +1,7 @@ import pytest import pandas as pd -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/series/methods/test_drop_duplicates.py b/pandas/tests/series/methods/test_drop_duplicates.py index 40651c4342e8a..a10e3908dde4e 100644 --- a/pandas/tests/series/methods/test_drop_duplicates.py +++ b/pandas/tests/series/methods/test_drop_duplicates.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Categorical, Series -import pandas._testing as tm +from pandas import Categorical, Series, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/series/methods/test_droplevel.py b/pandas/tests/series/methods/test_droplevel.py index 449ddd1cd0e49..4e4d38b560630 100644 --- a/pandas/tests/series/methods/test_droplevel.py +++ b/pandas/tests/series/methods/test_droplevel.py @@ -1,7 +1,6 @@ import pytest -from pandas import MultiIndex, Series -import pandas._testing as tm +from pandas import MultiIndex, Series, _testing as tm class TestDropLevel: diff --git a/pandas/tests/series/methods/test_duplicated.py b/pandas/tests/series/methods/test_duplicated.py index 5cc297913e851..13d428a4c0b0e 100644 --- a/pandas/tests/series/methods/test_duplicated.py +++ b/pandas/tests/series/methods/test_duplicated.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/series/methods/test_explode.py b/pandas/tests/series/methods/test_explode.py index 4b65e042f7b02..d24ccef7fa9fa 100644 --- a/pandas/tests/series/methods/test_explode.py +++ b/pandas/tests/series/methods/test_explode.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def test_basic(): diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index 80b8271e16e7a..3ade42f032f03 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -3,8 +3,16 @@ import numpy as np import pytest -from pandas import Categorical, DataFrame, NaT, Period, Series, Timedelta, Timestamp -import pandas._testing as tm +from pandas import ( + Categorical, + DataFrame, + NaT, + Period, + Series, + Timedelta, + Timestamp, + _testing as tm, +) class TestSeriesFillNA: diff --git a/pandas/tests/series/methods/test_first_and_last.py b/pandas/tests/series/methods/test_first_and_last.py index 7629dc8cda30b..b4590d33c1f00 100644 --- a/pandas/tests/series/methods/test_first_and_last.py +++ b/pandas/tests/series/methods/test_first_and_last.py @@ -1,12 +1,10 @@ """ Note: includes tests for `last` """ - import numpy as np import pytest -from pandas import Series, date_range -import pandas._testing as tm +from pandas import Series, _testing as tm, date_range class TestFirst: diff --git a/pandas/tests/series/methods/test_head_tail.py b/pandas/tests/series/methods/test_head_tail.py index d9f8d85eda350..2db04a88a8efa 100644 --- a/pandas/tests/series/methods/test_head_tail.py +++ b/pandas/tests/series/methods/test_head_tail.py @@ -1,4 +1,4 @@ -import pandas._testing as tm +from pandas import _testing as tm def test_head_tail(string_series): diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py index c4b10e0ccdc3e..af457452b32a5 100644 --- a/pandas/tests/series/methods/test_interpolate.py +++ b/pandas/tests/series/methods/test_interpolate.py @@ -1,11 +1,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import Index, MultiIndex, Series, date_range, isna -import pandas._testing as tm +from pandas import Index, MultiIndex, Series, _testing as tm, date_range, isna +from pandas.util import _test_decorators as td @pytest.fixture( diff --git a/pandas/tests/series/methods/test_isin.py b/pandas/tests/series/methods/test_isin.py index 3836c1d56bf87..414e95616e537 100644 --- a/pandas/tests/series/methods/test_isin.py +++ b/pandas/tests/series/methods/test_isin.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Series, date_range -import pandas._testing as tm +from pandas import Series, _testing as tm, date_range class TestSeriesIsIn: diff --git a/pandas/tests/series/methods/test_nlargest.py b/pandas/tests/series/methods/test_nlargest.py index b1aa09f387a13..4ebd94d12b7e0 100644 --- a/pandas/tests/series/methods/test_nlargest.py +++ b/pandas/tests/series/methods/test_nlargest.py @@ -8,8 +8,7 @@ import pytest import pandas as pd -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm main_dtypes = [ "datetime", diff --git a/pandas/tests/series/methods/test_pct_change.py b/pandas/tests/series/methods/test_pct_change.py index 1efb57894f986..8af7d3f4028eb 100644 --- a/pandas/tests/series/methods/test_pct_change.py +++ b/pandas/tests/series/methods/test_pct_change.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Series, date_range -import pandas._testing as tm +from pandas import Series, _testing as tm, date_range class TestSeriesPctChange: diff --git a/pandas/tests/series/methods/test_quantile.py b/pandas/tests/series/methods/test_quantile.py index 79f50afca658f..115449d988d43 100644 --- a/pandas/tests/series/methods/test_quantile.py +++ b/pandas/tests/series/methods/test_quantile.py @@ -4,8 +4,7 @@ from pandas.core.dtypes.common import is_integer import pandas as pd -from pandas import Index, Series -import pandas._testing as tm +from pandas import Index, Series, _testing as tm from pandas.core.indexes.datetimes import Timestamp diff --git a/pandas/tests/series/methods/test_rank.py b/pandas/tests/series/methods/test_rank.py index 6d3c37659f5c4..bef93fd61d73d 100644 --- a/pandas/tests/series/methods/test_rank.py +++ b/pandas/tests/series/methods/test_rank.py @@ -5,11 +5,10 @@ from pandas._libs import iNaT from pandas._libs.algos import Infinity, NegInfinity -import pandas.util._test_decorators as td -from pandas import NaT, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import NaT, Series, Timestamp, _testing as tm, date_range from pandas.api.types import CategoricalDtype +from pandas.util import _test_decorators as td class TestSeriesRank: diff --git a/pandas/tests/series/methods/test_reindex_like.py b/pandas/tests/series/methods/test_reindex_like.py index 7f24c778feb1b..a5b450d2284b7 100644 --- a/pandas/tests/series/methods/test_reindex_like.py +++ b/pandas/tests/series/methods/test_reindex_like.py @@ -2,8 +2,7 @@ import numpy as np -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm def test_reindex_like(datetime_series): diff --git a/pandas/tests/series/methods/test_rename.py b/pandas/tests/series/methods/test_rename.py index ac07fed7c951a..52543a6a50df9 100644 --- a/pandas/tests/series/methods/test_rename.py +++ b/pandas/tests/series/methods/test_rename.py @@ -2,8 +2,7 @@ import numpy as np -from pandas import Index, Series -import pandas._testing as tm +from pandas import Index, Series, _testing as tm class TestRename: diff --git a/pandas/tests/series/methods/test_rename_axis.py b/pandas/tests/series/methods/test_rename_axis.py index b519dd1144493..bcae7a0f237d3 100644 --- a/pandas/tests/series/methods/test_rename_axis.py +++ b/pandas/tests/series/methods/test_rename_axis.py @@ -1,7 +1,6 @@ import pytest -from pandas import Index, MultiIndex, Series -import pandas._testing as tm +from pandas import Index, MultiIndex, Series, _testing as tm class TestSeriesRenameAxis: diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index 11802c59a29da..dba3eb2e39045 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestSeriesReplace: diff --git a/pandas/tests/series/methods/test_reset_index.py b/pandas/tests/series/methods/test_reset_index.py index 1474bb95f4af2..0fc7de72bdc09 100644 --- a/pandas/tests/series/methods/test_reset_index.py +++ b/pandas/tests/series/methods/test_reset_index.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, MultiIndex, RangeIndex, Series -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, RangeIndex, Series, _testing as tm class TestResetIndex: diff --git a/pandas/tests/series/methods/test_round.py b/pandas/tests/series/methods/test_round.py index 88d5c428712dc..67495ddadbb11 100644 --- a/pandas/tests/series/methods/test_round.py +++ b/pandas/tests/series/methods/test_round.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm class TestSeriesRound: diff --git a/pandas/tests/series/methods/test_searchsorted.py b/pandas/tests/series/methods/test_searchsorted.py index 5a6ec0039c7cd..87e14a50e17f9 100644 --- a/pandas/tests/series/methods/test_searchsorted.py +++ b/pandas/tests/series/methods/test_searchsorted.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import Series, Timestamp, date_range -import pandas._testing as tm +from pandas import Series, Timestamp, _testing as tm, date_range from pandas.api.types import is_scalar diff --git a/pandas/tests/series/methods/test_shift.py b/pandas/tests/series/methods/test_shift.py index da6407c73104c..c1c67a44b6a9d 100644 --- a/pandas/tests/series/methods/test_shift.py +++ b/pandas/tests/series/methods/test_shift.py @@ -10,10 +10,10 @@ NaT, Series, TimedeltaIndex, + _testing as tm, date_range, offsets, ) -import pandas._testing as tm from pandas.tseries.offsets import BDay diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py index 6c6be1506255a..fcaba2997c14d 100644 --- a/pandas/tests/series/methods/test_sort_index.py +++ b/pandas/tests/series/methods/test_sort_index.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import DatetimeIndex, IntervalIndex, MultiIndex, Series -import pandas._testing as tm +from pandas import DatetimeIndex, IntervalIndex, MultiIndex, Series, _testing as tm class TestSeriesSortIndex: diff --git a/pandas/tests/series/methods/test_sort_values.py b/pandas/tests/series/methods/test_sort_values.py index b49e39d4592ea..007fbc3d1692c 100644 --- a/pandas/tests/series/methods/test_sort_values.py +++ b/pandas/tests/series/methods/test_sort_values.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Categorical, DataFrame, Series -import pandas._testing as tm +from pandas import Categorical, DataFrame, Series, _testing as tm class TestSeriesSortValues: diff --git a/pandas/tests/series/methods/test_to_dict.py b/pandas/tests/series/methods/test_to_dict.py index 47badb0a1bb52..6d1f7057a8082 100644 --- a/pandas/tests/series/methods/test_to_dict.py +++ b/pandas/tests/series/methods/test_to_dict.py @@ -2,8 +2,7 @@ import pytest -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm class TestSeriesToDict: diff --git a/pandas/tests/series/methods/test_to_period.py b/pandas/tests/series/methods/test_to_period.py index b40fc81931e20..f95aad52514c3 100644 --- a/pandas/tests/series/methods/test_to_period.py +++ b/pandas/tests/series/methods/test_to_period.py @@ -6,10 +6,10 @@ DatetimeIndex, PeriodIndex, Series, + _testing as tm, date_range, period_range, ) -import pandas._testing as tm class TestToPeriod: diff --git a/pandas/tests/series/methods/test_to_timestamp.py b/pandas/tests/series/methods/test_to_timestamp.py index 13a2042a2f639..0c71ae48ca08f 100644 --- a/pandas/tests/series/methods/test_to_timestamp.py +++ b/pandas/tests/series/methods/test_to_timestamp.py @@ -2,8 +2,15 @@ import pytest -from pandas import PeriodIndex, Series, Timedelta, date_range, period_range, to_datetime -import pandas._testing as tm +from pandas import ( + PeriodIndex, + Series, + Timedelta, + _testing as tm, + date_range, + period_range, + to_datetime, +) class TestToTimestamp: diff --git a/pandas/tests/series/methods/test_truncate.py b/pandas/tests/series/methods/test_truncate.py index 7c82edbaec177..68bc2ae8e5694 100644 --- a/pandas/tests/series/methods/test_truncate.py +++ b/pandas/tests/series/methods/test_truncate.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import Series, date_range -import pandas._testing as tm +from pandas import Series, _testing as tm, date_range from pandas.tseries.offsets import BDay diff --git a/pandas/tests/series/methods/test_tz_convert.py b/pandas/tests/series/methods/test_tz_convert.py index ce348d5323e62..da7fbe66cc4ff 100644 --- a/pandas/tests/series/methods/test_tz_convert.py +++ b/pandas/tests/series/methods/test_tz_convert.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DatetimeIndex, Series, date_range -import pandas._testing as tm +from pandas import DatetimeIndex, Series, _testing as tm, date_range class TestTZConvert: diff --git a/pandas/tests/series/methods/test_tz_localize.py b/pandas/tests/series/methods/test_tz_localize.py index 532b8d16f0d5c..4a88b4688f573 100644 --- a/pandas/tests/series/methods/test_tz_localize.py +++ b/pandas/tests/series/methods/test_tz_localize.py @@ -3,8 +3,7 @@ from pandas._libs.tslibs import timezones -from pandas import DatetimeIndex, NaT, Series, Timestamp, date_range -import pandas._testing as tm +from pandas import DatetimeIndex, NaT, Series, Timestamp, _testing as tm, date_range class TestTZLocalize: diff --git a/pandas/tests/series/methods/test_unstack.py b/pandas/tests/series/methods/test_unstack.py index cdf6a16e88ad0..50d9a7fbd59c1 100644 --- a/pandas/tests/series/methods/test_unstack.py +++ b/pandas/tests/series/methods/test_unstack.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, Series, _testing as tm def test_unstack(): diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py index d00a4299cb690..6bce0442c0d68 100644 --- a/pandas/tests/series/methods/test_update.py +++ b/pandas/tests/series/methods/test_update.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import CategoricalDtype, DataFrame, NaT, Series, Timestamp -import pandas._testing as tm +from pandas import CategoricalDtype, DataFrame, NaT, Series, Timestamp, _testing as tm class TestUpdate: diff --git a/pandas/tests/series/methods/test_value_counts.py b/pandas/tests/series/methods/test_value_counts.py index f97362ce9c2a9..2906546d6bfea 100644 --- a/pandas/tests/series/methods/test_value_counts.py +++ b/pandas/tests/series/methods/test_value_counts.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Categorical, CategoricalIndex, Series -import pandas._testing as tm +from pandas import Categorical, CategoricalIndex, Series, _testing as tm class TestSeriesValueCounts: diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index 203750757e28d..caac7688fa87e 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import Index, Series -import pandas._testing as tm +from pandas import Index, Series, _testing as tm class TestSeriesAlterAxes: diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index ab8618eb0a7d4..05c09c041ab7b 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -3,11 +3,9 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm +from pandas.util import _test_decorators as td class TestSeriesAnalytics: diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index b174eb0e42776..a4fc097b6e315 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -17,14 +17,14 @@ Timedelta, TimedeltaIndex, Timestamp, + _testing as tm, date_range, period_range, timedelta_range, ) -import pandas._testing as tm from pandas.core.arrays import PeriodArray -import pandas.io.formats.printing as printing +from pandas.io.formats import printing as printing class TestSeriesMisc: diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 5c8a0d224c4f9..abd4da7980e24 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -8,8 +8,15 @@ from pandas._libs.tslibs import IncompatibleFrequency import pandas as pd -from pandas import Categorical, Index, Series, bdate_range, date_range, isna -import pandas._testing as tm +from pandas import ( + Categorical, + Index, + Series, + _testing as tm, + bdate_range, + date_range, + isna, +) from pandas.core import nanops, ops @@ -195,8 +202,8 @@ def test_add_with_duplicate_index(self): tm.assert_series_equal(result, expected) def test_add_na_handling(self): - from decimal import Decimal from datetime import date + from decimal import Decimal s = Series( [Decimal("1.3"), Decimal("2.3")], index=[date(2012, 1, 1), date(2012, 1, 2)] diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 1dd410ad02ee0..96b940bfab9a2 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -2,7 +2,7 @@ from datetime import datetime, timedelta import numpy as np -import numpy.ma as ma +from numpy import ma as ma import pytest from pandas._libs import iNaT, lib @@ -20,12 +20,12 @@ NaT, Series, Timestamp, + _testing as tm, date_range, isna, period_range, timedelta_range, ) -import pandas._testing as tm from pandas.core.arrays import IntervalArray, period_array diff --git a/pandas/tests/series/test_cumulative.py b/pandas/tests/series/test_cumulative.py index 0b4c5f091106a..723573e0252e4 100644 --- a/pandas/tests/series/test_cumulative.py +++ b/pandas/tests/series/test_cumulative.py @@ -11,7 +11,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm def _check_accum_op(name, series, check_dtype=True): diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index d2ad9c8c398ea..de9553bf732b4 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -19,13 +19,13 @@ PeriodIndex, Series, TimedeltaIndex, + _testing as tm, date_range, period_range, timedelta_range, ) -import pandas._testing as tm +from pandas.core import common as com from pandas.core.arrays import PeriodArray -import pandas.core.common as com class TestSeriesDatetimeValues: diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py index bcc0b18134dad..68cbe07bb2235 100644 --- a/pandas/tests/series/test_dtypes.py +++ b/pandas/tests/series/test_dtypes.py @@ -18,9 +18,9 @@ Series, Timedelta, Timestamp, + _testing as tm, date_range, ) -import pandas._testing as tm class TestSeriesDtypes: diff --git a/pandas/tests/series/test_duplicates.py b/pandas/tests/series/test_duplicates.py index 89181a08819b1..42307d7b4b9e8 100644 --- a/pandas/tests/series/test_duplicates.py +++ b/pandas/tests/series/test_duplicates.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Categorical, Series -import pandas._testing as tm +from pandas import Categorical, Series, _testing as tm from pandas.core.construction import create_series_with_explicit_dtype diff --git a/pandas/tests/series/test_internals.py b/pandas/tests/series/test_internals.py index 51410fce7efae..5c409a90a8d30 100644 --- a/pandas/tests/series/test_internals.py +++ b/pandas/tests/series/test_internals.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import NaT, Series, Timestamp -import pandas._testing as tm +from pandas import NaT, Series, Timestamp, _testing as tm from pandas.core.internals.blocks import IntBlock diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py index 708118e950686..6e39b1c0005dd 100644 --- a/pandas/tests/series/test_io.py +++ b/pandas/tests/series/test_io.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.io.common import get_handle diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 0144e4257efe0..1b8528cda751a 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -16,10 +16,10 @@ Series, Timedelta, Timestamp, + _testing as tm, date_range, isna, ) -import pandas._testing as tm class TestSeriesMissingData: diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index e1c9682329271..9d7554f57f89e 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, Series, bdate_range -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm, bdate_range from pandas.core import ops diff --git a/pandas/tests/series/test_period.py b/pandas/tests/series/test_period.py index b54c09e5750fd..3595d399bb9c1 100644 --- a/pandas/tests/series/test_period.py +++ b/pandas/tests/series/test_period.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Period, Series, period_range -import pandas._testing as tm +from pandas import DataFrame, Period, Series, _testing as tm, period_range from pandas.core.arrays import PeriodArray diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py index b861b37b49f89..ec9d258648d55 100644 --- a/pandas/tests/series/test_repr.py +++ b/pandas/tests/series/test_repr.py @@ -10,12 +10,12 @@ Index, MultiIndex, Series, + _testing as tm, date_range, option_context, period_range, timedelta_range, ) -import pandas._testing as tm class TestSeriesRepr: diff --git a/pandas/tests/series/test_subclass.py b/pandas/tests/series/test_subclass.py index 86330b7cc6993..d124eca1f8fc7 100644 --- a/pandas/tests/series/test_subclass.py +++ b/pandas/tests/series/test_subclass.py @@ -1,7 +1,7 @@ import numpy as np import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm class TestSeriesSubclassing: diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 15b6481c08a61..6c5f37fdb0a23 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -2,8 +2,14 @@ import pytest import pandas as pd -from pandas import DataFrame, DatetimeIndex, Series, date_range, timedelta_range -import pandas._testing as tm +from pandas import ( + DataFrame, + DatetimeIndex, + Series, + _testing as tm, + date_range, + timedelta_range, +) class TestTimeSeries: diff --git a/pandas/tests/series/test_timezones.py b/pandas/tests/series/test_timezones.py index 05792dc4f00d2..cec699172ed46 100644 --- a/pandas/tests/series/test_timezones.py +++ b/pandas/tests/series/test_timezones.py @@ -7,8 +7,7 @@ import numpy as np import pytest -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm from pandas.core.indexes.datetimes import date_range diff --git a/pandas/tests/series/test_ufunc.py b/pandas/tests/series/test_ufunc.py index c7fc37a278e83..ccb16b2d1ceaf 100644 --- a/pandas/tests/series/test_ufunc.py +++ b/pandas/tests/series/test_ufunc.py @@ -5,7 +5,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm from pandas.arrays import SparseArray UNARY_UFUNCS = [np.positive, np.floor, np.exp] diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index a080bf0feaebc..fa3ffafdeb882 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -6,9 +6,9 @@ from numpy.random import RandomState import pytest -from pandas._libs import algos as libalgos, groupby as libgroupby, hashtable as ht +from pandas._libs import algos as libalgos, hashtable as ht +from pandas._libs.groupby import group_var_float32, group_var_float64 from pandas.compat.numpy import np_array_datetime64_compat -import pandas.util._test_decorators as td from pandas.core.dtypes.common import ( is_bool_dtype, @@ -28,12 +28,12 @@ IntervalIndex, Series, Timestamp, + _testing as tm, compat, ) -import pandas._testing as tm -import pandas.core.algorithms as algos +from pandas.core import algorithms as algos, common as com from pandas.core.arrays import DatetimeArray -import pandas.core.common as com +from pandas.util import _test_decorators as td class TestFactorize: @@ -1493,7 +1493,7 @@ def test_group_var_constant(self): class TestGroupVarFloat64(GroupVarTestMixin): __test__ = True - algo = staticmethod(libgroupby.group_var_float64) + algo = staticmethod(group_var_float64) dtype = np.float64 rtol = 1e-5 @@ -1516,7 +1516,7 @@ def test_group_var_large_inputs(self): class TestGroupVarFloat32(GroupVarTestMixin): __test__ = True - algo = staticmethod(libgroupby.group_var_float32) + algo = staticmethod(group_var_float32) dtype = np.float32 rtol = 1e-2 diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index bcfed2d0d3a10..82d2251414739 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -10,8 +10,7 @@ import pandas as pd from pandas import Series, Timestamp -from pandas.core import ops -import pandas.core.common as com +from pandas.core import common as com, ops def test_get_callable_name(): @@ -48,7 +47,7 @@ def test_all_not_none(): def test_random_state(): - import numpy.random as npr + from numpy import random as npr # Check with seed state = com.random_state(5) diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index e718a6b759963..d7571c3f36130 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -8,10 +8,8 @@ import numpy as np # noqa import pytest -import pandas.util._test_decorators as td - -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm +from pandas.util import _test_decorators as td def import_module(name): @@ -34,7 +32,7 @@ def test_dask(df): toolz = import_module("toolz") # noqa dask = import_module("dask") # noqa - import dask.dataframe as dd + from dask import dataframe as dd ddf = dd.from_pandas(df, npartitions=3) assert ddf.A is not None @@ -78,8 +76,8 @@ def test_oo_optimizable(): def test_statsmodels(): statsmodels = import_module("statsmodels") # noqa - import statsmodels.api as sm - import statsmodels.formula.api as smf + from statsmodels import api as sm + from statsmodels.formula import api as smf df = sm.datasets.get_rdataset("Guerry", "HistData").data smf.ols("Lottery ~ Literacy + np.log(Pop1831)", data=df).fit() @@ -90,7 +88,7 @@ def test_statsmodels(): def test_scikit_learn(df): sklearn = import_module("sklearn") # noqa - from sklearn import svm, datasets + from sklearn import datasets, svm digits = datasets.load_digits() clf = svm.SVC(gamma=0.001, C=100.0) diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index 2368e93ddc256..8a49e80f04614 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -5,7 +5,7 @@ from numpy.random import randn import pytest -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.api import DataFrame from pandas.core.computation import expressions as expr diff --git a/pandas/tests/test_join.py b/pandas/tests/test_join.py index 129dc275c4d5a..6febe8a4e0e76 100644 --- a/pandas/tests/test_join.py +++ b/pandas/tests/test_join.py @@ -3,8 +3,7 @@ from pandas._libs import join as _join -from pandas import Categorical, DataFrame, Index, merge -import pandas._testing as tm +from pandas import Categorical, DataFrame, Index, _testing as tm, merge class TestIndexer: diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py index b6f59807eaa15..df983dd0bda59 100644 --- a/pandas/tests/test_lib.py +++ b/pandas/tests/test_lib.py @@ -4,8 +4,7 @@ from pandas._libs import lib, writers as libwriters import pandas as pd -from pandas import Index -import pandas._testing as tm +from pandas import Index, _testing as tm class TestMisc: diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 1ba73292dc0b4..e15ec3cd9f110 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -10,8 +10,7 @@ from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, Timestamp -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, _testing as tm AGG_FUNCTIONS = [ "sum", diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index 0d60e6e8a978f..0b1e32ed9c845 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -5,15 +5,13 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - from pandas.core.dtypes.common import is_integer_dtype import pandas as pd -from pandas import Series, isna -import pandas._testing as tm +from pandas import Series, _testing as tm, isna +from pandas.core import nanops as nanops from pandas.core.arrays import DatetimeArray -import pandas.core.nanops as nanops +from pandas.util import _test_decorators as td use_bn = nanops._USE_BOTTLENECK has_c16 = hasattr(np, "complex128") diff --git a/pandas/tests/test_optional_dependency.py b/pandas/tests/test_optional_dependency.py index e5ed69b7703b1..59391f2146cff 100644 --- a/pandas/tests/test_optional_dependency.py +++ b/pandas/tests/test_optional_dependency.py @@ -5,7 +5,7 @@ from pandas.compat._optional import VERSIONS, import_optional_dependency -import pandas._testing as tm +from pandas import _testing as tm def test_import_optional(): diff --git a/pandas/tests/test_register_accessor.py b/pandas/tests/test_register_accessor.py index d839936f731a3..31280dd2dd062 100644 --- a/pandas/tests/test_register_accessor.py +++ b/pandas/tests/test_register_accessor.py @@ -3,7 +3,7 @@ import pytest import pandas as pd -import pandas._testing as tm +from pandas import _testing as tm @contextlib.contextmanager diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py index 98297474243e4..5a25dc9708e25 100644 --- a/pandas/tests/test_sorting.py +++ b/pandas/tests/test_sorting.py @@ -5,10 +5,9 @@ import numpy as np import pytest -from pandas import DataFrame, MultiIndex, Series, array, concat, merge -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, Series, _testing as tm, array, concat, merge +from pandas.core import common as com from pandas.core.algorithms import safe_sort -import pandas.core.common as com from pandas.core.sorting import ( decons_group_index, get_group_index, diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index d9396d70f9112..3b888e24e2297 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -8,9 +8,17 @@ from pandas._libs import lib import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, concat, isna, notna -import pandas._testing as tm -import pandas.core.strings as strings +from pandas import ( + DataFrame, + Index, + MultiIndex, + Series, + _testing as tm, + concat, + isna, + notna, +) +from pandas.core import strings as strings def assert_series_or_index_equal(left, right): diff --git a/pandas/tests/test_take.py b/pandas/tests/test_take.py index 9f0632917037c..4b53799d2ea71 100644 --- a/pandas/tests/test_take.py +++ b/pandas/tests/test_take.py @@ -6,8 +6,8 @@ from pandas._libs import iNaT -import pandas._testing as tm -import pandas.core.algorithms as algos +from pandas import _testing as tm +from pandas.core import algorithms as algos @pytest.fixture(params=[True, False]) diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index d2049892705ea..4f4b13ff64067 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1,5 +1,4 @@ """ test to_datetime """ - import calendar from collections import deque from datetime import datetime, timedelta @@ -14,7 +13,6 @@ from pandas._libs import tslib from pandas._libs.tslibs import iNaT, parsing from pandas.errors import OutOfBoundsDatetime -import pandas.util._test_decorators as td from pandas.core.dtypes.common import is_datetime64_ns_dtype @@ -26,13 +24,14 @@ NaT, Series, Timestamp, + _testing as tm, date_range, isna, to_datetime, ) -import pandas._testing as tm from pandas.core.arrays import DatetimeArray from pandas.core.tools import datetimes as tools +from pandas.util import _test_decorators as td class TestTimeConversionFormats: diff --git a/pandas/tests/tools/test_to_numeric.py b/pandas/tests/tools/test_to_numeric.py index 263887a8ea36e..d814f59377fc7 100644 --- a/pandas/tests/tools/test_to_numeric.py +++ b/pandas/tests/tools/test_to_numeric.py @@ -5,8 +5,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, Series, to_numeric -import pandas._testing as tm +from pandas import DataFrame, Index, Series, _testing as tm, to_numeric @pytest.fixture(params=[None, "ignore", "raise", "coerce"]) diff --git a/pandas/tests/tools/test_to_time.py b/pandas/tests/tools/test_to_time.py index bfd347fd122c3..7605e43faa01d 100644 --- a/pandas/tests/tools/test_to_time.py +++ b/pandas/tests/tools/test_to_time.py @@ -3,12 +3,10 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm from pandas.core.tools.datetimes import to_time as to_time_alias from pandas.core.tools.times import to_time +from pandas.util import _test_decorators as td class TestToTime: diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py index 1e193f22a6698..65578aa62fa2b 100644 --- a/pandas/tests/tools/test_to_timedelta.py +++ b/pandas/tests/tools/test_to_timedelta.py @@ -4,8 +4,7 @@ import pytest import pandas as pd -from pandas import Series, TimedeltaIndex, isna, to_timedelta -import pandas._testing as tm +from pandas import Series, TimedeltaIndex, _testing as tm, isna, to_timedelta class TestTimedeltas: diff --git a/pandas/tests/tseries/frequencies/test_inference.py b/pandas/tests/tseries/frequencies/test_inference.py index 95edd038dab9b..82b7677295500 100644 --- a/pandas/tests/tseries/frequencies/test_inference.py +++ b/pandas/tests/tseries/frequencies/test_inference.py @@ -7,12 +7,18 @@ from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG from pandas.compat import is_platform_windows -from pandas import DatetimeIndex, Index, Series, Timestamp, date_range, period_range -import pandas._testing as tm +from pandas import ( + DatetimeIndex, + Index, + Series, + Timestamp, + _testing as tm, + date_range, + period_range, +) from pandas.core.tools.datetimes import to_datetime -import pandas.tseries.frequencies as frequencies -import pandas.tseries.offsets as offsets +from pandas.tseries import frequencies as frequencies, offsets as offsets def _check_generated_range(start, periods, freq): diff --git a/pandas/tests/tseries/holiday/test_calendar.py b/pandas/tests/tseries/holiday/test_calendar.py index cd3b1aab33a2a..e087a5f3242f7 100644 --- a/pandas/tests/tseries/holiday/test_calendar.py +++ b/pandas/tests/tseries/holiday/test_calendar.py @@ -2,8 +2,7 @@ import pytest -from pandas import DatetimeIndex, offsets, to_datetime -import pandas._testing as tm +from pandas import DatetimeIndex, _testing as tm, offsets, to_datetime from pandas.tseries.holiday import ( AbstractHolidayCalendar, diff --git a/pandas/tests/tseries/holiday/test_holiday.py b/pandas/tests/tseries/holiday/test_holiday.py index a2c146dbd65e8..7166483dc2de2 100644 --- a/pandas/tests/tseries/holiday/test_holiday.py +++ b/pandas/tests/tseries/holiday/test_holiday.py @@ -3,7 +3,7 @@ import pytest from pytz import utc -import pandas._testing as tm +from pandas import _testing as tm from pandas.tseries.holiday import ( MO, diff --git a/pandas/tests/tseries/offsets/conftest.py b/pandas/tests/tseries/offsets/conftest.py index df68c98dca43f..4feb42bd4b3cc 100644 --- a/pandas/tests/tseries/offsets/conftest.py +++ b/pandas/tests/tseries/offsets/conftest.py @@ -2,7 +2,7 @@ from pandas._libs.tslibs.offsets import MonthOffset -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets as offsets @pytest.fixture(params=[getattr(offsets, o) for o in offsets.__all__]) diff --git a/pandas/tests/tseries/offsets/test_fiscal.py b/pandas/tests/tseries/offsets/test_fiscal.py index 7713be67a7e05..f643feabc6ff0 100644 --- a/pandas/tests/tseries/offsets/test_fiscal.py +++ b/pandas/tests/tseries/offsets/test_fiscal.py @@ -8,8 +8,7 @@ from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG -from pandas import Timestamp -import pandas._testing as tm +from pandas import Timestamp, _testing as tm from pandas.tseries.frequencies import get_offset from pandas.tseries.offsets import FY5253, FY5253Quarter diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 8c51908c547f4..aa3ba8cdb3de7 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -9,22 +9,21 @@ OutOfBoundsDatetime, Timestamp, conversion, + offsets as liboffsets, timezones, ) -import pandas._libs.tslibs.offsets as liboffsets from pandas._libs.tslibs.offsets import ApplyTypeError, _get_offset, _offset_map from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG -import pandas.compat as compat from pandas.compat.numpy import np_datetime64_compat from pandas.errors import PerformanceWarning -import pandas._testing as tm +from pandas import _testing as tm, compat as compat from pandas.core.indexes.datetimes import DatetimeIndex, date_range from pandas.core.series import Series from pandas.io.pickle import read_pickle +from pandas.tseries import offsets as offsets from pandas.tseries.holiday import USFederalHolidayCalendar -import pandas.tseries.offsets as offsets from pandas.tseries.offsets import ( FY5253, BaseOffset, diff --git a/pandas/tests/tseries/offsets/test_ticks.py b/pandas/tests/tseries/offsets/test_ticks.py index 10c239c683bc0..2c5b7b98eda67 100644 --- a/pandas/tests/tseries/offsets/test_ticks.py +++ b/pandas/tests/tseries/offsets/test_ticks.py @@ -9,8 +9,7 @@ from pandas._libs.tslibs.offsets import delta_to_tick -from pandas import Timedelta, Timestamp -import pandas._testing as tm +from pandas import Timedelta, Timestamp, _testing as tm from pandas.tseries import offsets from pandas.tseries.offsets import Hour, Micro, Milli, Minute, Nano, Second diff --git a/pandas/tests/tslibs/test_array_to_datetime.py b/pandas/tests/tslibs/test_array_to_datetime.py index a40fcd725d604..40e8d4110039f 100644 --- a/pandas/tests/tslibs/test_array_to_datetime.py +++ b/pandas/tests/tslibs/test_array_to_datetime.py @@ -8,8 +8,7 @@ from pandas._libs import iNaT, tslib from pandas.compat.numpy import np_array_datetime64_compat -from pandas import Timestamp -import pandas._testing as tm +from pandas import Timestamp, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/tslibs/test_conversion.py b/pandas/tests/tslibs/test_conversion.py index 4f184b78f34a1..4b529821102a3 100644 --- a/pandas/tests/tslibs/test_conversion.py +++ b/pandas/tests/tslibs/test_conversion.py @@ -12,8 +12,7 @@ tzconversion, ) -from pandas import Timestamp, date_range -import pandas._testing as tm +from pandas import Timestamp, _testing as tm, date_range def _compare_utc_to_local(tz_didx): diff --git a/pandas/tests/tslibs/test_fields.py b/pandas/tests/tslibs/test_fields.py index a45fcab56759f..94b4755bec5b4 100644 --- a/pandas/tests/tslibs/test_fields.py +++ b/pandas/tests/tslibs/test_fields.py @@ -2,7 +2,7 @@ from pandas._libs.tslibs import fields -import pandas._testing as tm +from pandas import _testing as tm def test_fields_readonly(): diff --git a/pandas/tests/tslibs/test_parsing.py b/pandas/tests/tslibs/test_parsing.py index dc7421ea63464..f1e236c50c4c2 100644 --- a/pandas/tests/tslibs/test_parsing.py +++ b/pandas/tests/tslibs/test_parsing.py @@ -10,9 +10,9 @@ from pandas._libs.tslibs import parsing from pandas._libs.tslibs.parsing import parse_time_string -import pandas.util._test_decorators as td -import pandas._testing as tm +from pandas import _testing as tm +from pandas.util import _test_decorators as td def test_parse_time_string(): diff --git a/pandas/tests/util/test_assert_almost_equal.py b/pandas/tests/util/test_assert_almost_equal.py index c25668c33bfc4..c7bce3f233607 100644 --- a/pandas/tests/util/test_assert_almost_equal.py +++ b/pandas/tests/util/test_assert_almost_equal.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, Series, Timestamp -import pandas._testing as tm +from pandas import DataFrame, Index, Series, Timestamp, _testing as tm def _assert_almost_equal_both(a, b, **kwargs): diff --git a/pandas/tests/util/test_assert_categorical_equal.py b/pandas/tests/util/test_assert_categorical_equal.py index 8957e7a172666..ee77ddc26984e 100644 --- a/pandas/tests/util/test_assert_categorical_equal.py +++ b/pandas/tests/util/test_assert_categorical_equal.py @@ -1,7 +1,6 @@ import pytest -from pandas import Categorical -import pandas._testing as tm +from pandas import Categorical, _testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/util/test_assert_extension_array_equal.py b/pandas/tests/util/test_assert_extension_array_equal.py index d9fdf1491c328..23230ad8bbf3d 100644 --- a/pandas/tests/util/test_assert_extension_array_equal.py +++ b/pandas/tests/util/test_assert_extension_array_equal.py @@ -1,7 +1,7 @@ import numpy as np import pytest -import pandas._testing as tm +from pandas import _testing as tm from pandas.core.arrays.sparse import SparseArray diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index fe3e1ff906919..cb026c0415c45 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -1,8 +1,7 @@ import pytest import pandas as pd -from pandas import DataFrame -import pandas._testing as tm +from pandas import DataFrame, _testing as tm @pytest.fixture(params=[True, False]) diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py index 125af6ef78593..b62d3780a2e4e 100644 --- a/pandas/tests/util/test_assert_index_equal.py +++ b/pandas/tests/util/test_assert_index_equal.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import Categorical, Index, MultiIndex, NaT -import pandas._testing as tm +from pandas import Categorical, Index, MultiIndex, NaT, _testing as tm def test_index_equal_levels_mismatch(): diff --git a/pandas/tests/util/test_assert_interval_array_equal.py b/pandas/tests/util/test_assert_interval_array_equal.py index 96f2973a1528c..5453e3cb25eae 100644 --- a/pandas/tests/util/test_assert_interval_array_equal.py +++ b/pandas/tests/util/test_assert_interval_array_equal.py @@ -1,7 +1,6 @@ import pytest -from pandas import interval_range -import pandas._testing as tm +from pandas import _testing as tm, interval_range @pytest.mark.parametrize( diff --git a/pandas/tests/util/test_assert_numpy_array_equal.py b/pandas/tests/util/test_assert_numpy_array_equal.py index d29ddedd2fdd6..4cd46a2b1dccc 100644 --- a/pandas/tests/util/test_assert_numpy_array_equal.py +++ b/pandas/tests/util/test_assert_numpy_array_equal.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import Timestamp -import pandas._testing as tm +from pandas import Timestamp, _testing as tm def test_assert_numpy_array_equal_shape_mismatch(): diff --git a/pandas/tests/util/test_assert_produces_warning.py b/pandas/tests/util/test_assert_produces_warning.py index 87765c909938d..311f3eace5929 100644 --- a/pandas/tests/util/test_assert_produces_warning.py +++ b/pandas/tests/util/test_assert_produces_warning.py @@ -2,7 +2,7 @@ import pytest -import pandas._testing as tm +from pandas import _testing as tm def f(): diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py index 1284cc9d4f49b..b415737b56f3a 100644 --- a/pandas/tests/util/test_assert_series_equal.py +++ b/pandas/tests/util/test_assert_series_equal.py @@ -1,8 +1,7 @@ import pytest import pandas as pd -from pandas import Categorical, DataFrame, Series -import pandas._testing as tm +from pandas import Categorical, DataFrame, Series, _testing as tm def _assert_series_equal_both(a, b, **kwargs): diff --git a/pandas/tests/util/test_deprecate.py b/pandas/tests/util/test_deprecate.py index ee4f7e3f34f2e..e076a490f3bb0 100644 --- a/pandas/tests/util/test_deprecate.py +++ b/pandas/tests/util/test_deprecate.py @@ -4,7 +4,7 @@ from pandas.util._decorators import deprecate -import pandas._testing as tm +from pandas import _testing as tm def new_func(): diff --git a/pandas/tests/util/test_deprecate_kwarg.py b/pandas/tests/util/test_deprecate_kwarg.py index b165e9fba0e4f..f36acd0068fce 100644 --- a/pandas/tests/util/test_deprecate_kwarg.py +++ b/pandas/tests/util/test_deprecate_kwarg.py @@ -2,7 +2,7 @@ from pandas.util._decorators import deprecate_kwarg -import pandas._testing as tm +from pandas import _testing as tm @deprecate_kwarg("old", "new") diff --git a/pandas/tests/util/test_deprecate_nonkeyword_arguments.py b/pandas/tests/util/test_deprecate_nonkeyword_arguments.py index 05bc617232bdd..bd7ddf72a81f4 100644 --- a/pandas/tests/util/test_deprecate_nonkeyword_arguments.py +++ b/pandas/tests/util/test_deprecate_nonkeyword_arguments.py @@ -1,12 +1,11 @@ """ Tests for the `deprecate_nonkeyword_arguments` decorator """ - import warnings from pandas.util._decorators import deprecate_nonkeyword_arguments -import pandas._testing as tm +from pandas import _testing as tm @deprecate_nonkeyword_arguments(version="1.1", allowed_args=["a", "b"]) diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py index ff29df39e1871..c433932f92033 100644 --- a/pandas/tests/util/test_hashing.py +++ b/pandas/tests/util/test_hashing.py @@ -2,8 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm from pandas.core.util.hashing import hash_tuples from pandas.util import hash_array, hash_pandas_object diff --git a/pandas/tests/util/test_safe_import.py b/pandas/tests/util/test_safe_import.py index bd07bea934ed3..b555c2c0993a6 100644 --- a/pandas/tests/util/test_safe_import.py +++ b/pandas/tests/util/test_safe_import.py @@ -3,7 +3,7 @@ import pytest -import pandas.util._test_decorators as td +from pandas.util import _test_decorators as td @pytest.mark.parametrize("name", ["foo", "hello123"]) diff --git a/pandas/tests/util/test_util.py b/pandas/tests/util/test_util.py index d73a789b876f4..fff6655552ed7 100644 --- a/pandas/tests/util/test_util.py +++ b/pandas/tests/util/test_util.py @@ -2,9 +2,7 @@ import pytest -import pandas.compat as compat - -import pandas._testing as tm +from pandas import _testing as tm, compat as compat def test_rands(): diff --git a/pandas/tests/window/common.py b/pandas/tests/window/common.py index 7e0be331ec8d5..3b87ef05f9173 100644 --- a/pandas/tests/window/common.py +++ b/pandas/tests/window/common.py @@ -1,7 +1,6 @@ import numpy as np -from pandas import Series -import pandas._testing as tm +from pandas import Series, _testing as tm def check_pairwise_moment(frame, dispatch, name, **kwargs): diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py index eb8252d5731be..2fab5e35a4583 100644 --- a/pandas/tests/window/conftest.py +++ b/pandas/tests/window/conftest.py @@ -4,9 +4,8 @@ from numpy.random import randn import pytest -import pandas.util._test_decorators as td - from pandas import DataFrame, Series, bdate_range, notna +from pandas.util import _test_decorators as td @pytest.fixture(params=[True, False]) diff --git a/pandas/tests/window/moments/test_moments_consistency_expanding.py b/pandas/tests/window/moments/test_moments_consistency_expanding.py index 3ec91dcb60610..cc2e01dc498a7 100644 --- a/pandas/tests/window/moments/test_moments_consistency_expanding.py +++ b/pandas/tests/window/moments/test_moments_consistency_expanding.py @@ -4,8 +4,7 @@ from numpy.random import randn import pytest -from pandas import DataFrame, Index, MultiIndex, Series, isna, notna -import pandas._testing as tm +from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm, isna, notna from pandas.tests.window.common import ( moments_consistency_cov_data, moments_consistency_is_constant, diff --git a/pandas/tests/window/moments/test_moments_consistency_rolling.py b/pandas/tests/window/moments/test_moments_consistency_rolling.py index a3de8aa69f840..60399433cf098 100644 --- a/pandas/tests/window/moments/test_moments_consistency_rolling.py +++ b/pandas/tests/window/moments/test_moments_consistency_rolling.py @@ -5,11 +5,8 @@ from numpy.random import randn import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, DatetimeIndex, Index, Series -import pandas._testing as tm +from pandas import DataFrame, DatetimeIndex, Index, Series, _testing as tm from pandas.core.window.common import _flex_binary_moment from pandas.tests.window.common import ( check_pairwise_moment, @@ -21,6 +18,7 @@ moments_consistency_var_data, moments_consistency_var_debiasing_factors, ) +from pandas.util import _test_decorators as td def _rolling_consistency_cases(): diff --git a/pandas/tests/window/moments/test_moments_ewm.py b/pandas/tests/window/moments/test_moments_ewm.py index 89d46a8bb6cb5..d7522f6ef0473 100644 --- a/pandas/tests/window/moments/test_moments_ewm.py +++ b/pandas/tests/window/moments/test_moments_ewm.py @@ -3,8 +3,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm def check_ew(name=None, preserve_nan=False, series=None, frame=None, nan_locs=None): diff --git a/pandas/tests/window/moments/test_moments_rolling.py b/pandas/tests/window/moments/test_moments_rolling.py index 81f020fe7de23..892ae264f52b4 100644 --- a/pandas/tests/window/moments/test_moments_rolling.py +++ b/pandas/tests/window/moments/test_moments_rolling.py @@ -5,13 +5,11 @@ from numpy.random import randn import pytest -import pandas.util._test_decorators as td - import pandas as pd -from pandas import DataFrame, Series, isna, notna -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, isna, notna +from pandas.util import _test_decorators as td -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets as offsets def _check_moment_func( diff --git a/pandas/tests/window/test_api.py b/pandas/tests/window/test_api.py index 28e27791cad35..be608bf196bc5 100644 --- a/pandas/tests/window/test_api.py +++ b/pandas/tests/window/test_api.py @@ -3,12 +3,11 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd from pandas import DataFrame, Index, Series, Timestamp, compat, concat import pandas._testing as tm from pandas.core.base import SpecificationError +from pandas.util import _test_decorators as td def test_getitem(frame): diff --git a/pandas/tests/window/test_apply.py b/pandas/tests/window/test_apply.py index 2aaf6af103e98..3057223eb709a 100644 --- a/pandas/tests/window/test_apply.py +++ b/pandas/tests/window/test_apply.py @@ -2,7 +2,7 @@ import pytest from pandas.errors import NumbaUtilError -import pandas.util._test_decorators as td +from pandas.util._test_decorators import skip_if_no from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, compat, date_range import pandas._testing as tm @@ -133,7 +133,7 @@ def test_invalid_raw_numba(): Series(range(1)).rolling(1).apply(lambda x: x, raw=False, engine="numba") -@td.skip_if_no("numba") +@skip_if_no("numba") def test_invalid_kwargs_nopython(): with pytest.raises(NumbaUtilError, match="numba does not support kwargs with"): Series(range(1)).rolling(1).apply( diff --git a/pandas/tests/window/test_base_indexer.py b/pandas/tests/window/test_base_indexer.py index 4a0212e890d3a..c3b452bac3bcb 100644 --- a/pandas/tests/window/test_base_indexer.py +++ b/pandas/tests/window/test_base_indexer.py @@ -1,8 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm, date_range from pandas.api.indexers import BaseIndexer, FixedForwardWindowIndexer from pandas.core.window.indexers import ExpandingIndexer, VariableOffsetWindowIndexer diff --git a/pandas/tests/window/test_dtypes.py b/pandas/tests/window/test_dtypes.py index 0aa5bf019ff5e..325acd64f0234 100644 --- a/pandas/tests/window/test_dtypes.py +++ b/pandas/tests/window/test_dtypes.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.core.base import DataError # gh-12373 : rolling functions error on float32 data diff --git a/pandas/tests/window/test_ewm.py b/pandas/tests/window/test_ewm.py index 12c314d5e9ec9..cb575eb398b0e 100644 --- a/pandas/tests/window/test_ewm.py +++ b/pandas/tests/window/test_ewm.py @@ -3,8 +3,7 @@ from pandas.errors import UnsupportedFunctionCall -from pandas import DataFrame, DatetimeIndex, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, DatetimeIndex, Series, _testing as tm, date_range from pandas.core.window import ExponentialMovingWindow diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py index 146eca07c523e..347ab0d72724e 100644 --- a/pandas/tests/window/test_expanding.py +++ b/pandas/tests/window/test_expanding.py @@ -4,8 +4,7 @@ from pandas.errors import UnsupportedFunctionCall import pandas as pd -from pandas import DataFrame, Series -import pandas._testing as tm +from pandas import DataFrame, Series, _testing as tm from pandas.core.window import Expanding diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py index 35bdb972a7bc0..7cf1ee7a2e961 100644 --- a/pandas/tests/window/test_numba.py +++ b/pandas/tests/window/test_numba.py @@ -1,14 +1,14 @@ import numpy as np import pytest -import pandas.util._test_decorators as td +from pandas.util._test_decorators import skip_if_no from pandas import Series, option_context import pandas._testing as tm from pandas.core.util.numba_ import NUMBA_FUNC_CACHE -@td.skip_if_no("numba", "0.46.0") +@skip_if_no("numba", "0.46.0") @pytest.mark.filterwarnings("ignore:\\nThe keyword argument") # Filter warnings when parallel=True and the function can't be parallelized by Numba class TestApply: @@ -77,7 +77,7 @@ def func_2(x): tm.assert_series_equal(result, expected) -@td.skip_if_no("numba", "0.46.0") +@skip_if_no("numba", "0.46.0") def test_use_global_config(): def f(x): return np.mean(x) + 2 diff --git a/pandas/tests/window/test_pairwise.py b/pandas/tests/window/test_pairwise.py index e82d4b8cbf770..8e2a264823d52 100644 --- a/pandas/tests/window/test_pairwise.py +++ b/pandas/tests/window/test_pairwise.py @@ -3,8 +3,7 @@ import numpy as np import pytest -from pandas import DataFrame, MultiIndex, Series, date_range -import pandas._testing as tm +from pandas import DataFrame, MultiIndex, Series, _testing as tm, date_range from pandas.core.algorithms import safe_sort diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index bea239a245a4f..1a8e36a14ccf3 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -4,12 +4,12 @@ import pytest from pandas.errors import UnsupportedFunctionCall -import pandas.util._test_decorators as td import pandas as pd from pandas import DataFrame, Series, compat, date_range import pandas._testing as tm from pandas.core.window import Rolling +from pandas.util import _test_decorators as td def test_doc_string(): diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py index 90f919d5565b0..654030d285877 100644 --- a/pandas/tests/window/test_timeseries_window.py +++ b/pandas/tests/window/test_timeseries_window.py @@ -13,7 +13,7 @@ ) import pandas._testing as tm -import pandas.tseries.offsets as offsets +from pandas.tseries import offsets as offsets class TestRollingTS: diff --git a/pandas/tests/window/test_window.py b/pandas/tests/window/test_window.py index a450d29797c41..8273f029d092b 100644 --- a/pandas/tests/window/test_window.py +++ b/pandas/tests/window/test_window.py @@ -2,11 +2,11 @@ import pytest from pandas.errors import UnsupportedFunctionCall -import pandas.util._test_decorators as td import pandas as pd from pandas import Series from pandas.core.window import Window +from pandas.util import _test_decorators as td @td.skip_if_no_scipy diff --git a/pandas/tseries/api.py b/pandas/tseries/api.py index 2094791ecdc60..2dbcc9249a7c6 100644 --- a/pandas/tseries/api.py +++ b/pandas/tseries/api.py @@ -4,5 +4,5 @@ # flake8: noqa +from pandas.tseries import offsets as offsets from pandas.tseries.frequencies import infer_freq -import pandas.tseries.offsets as offsets diff --git a/pandas/util/_doctools.py b/pandas/util/_doctools.py index f413490764124..03d52f7ec9e5f 100644 --- a/pandas/util/_doctools.py +++ b/pandas/util/_doctools.py @@ -53,8 +53,7 @@ def plot(self, left, right, labels=None, vertical: bool = True): vertical : bool, default True If True, use vertical layout. If False, use horizontal layout. """ - import matplotlib.pyplot as plt - import matplotlib.gridspec as gridspec + from matplotlib import gridspec as gridspec, pyplot as plt if not isinstance(left, list): left = [left] @@ -139,7 +138,7 @@ def _make_table(self, ax, df, title: str, height: Optional[float] = None): ax.set_visible(False) return - import pandas.plotting as plotting + from pandas import plotting as plotting idx_nlevels = df.index.nlevels col_nlevels = df.columns.nlevels @@ -166,7 +165,7 @@ def _make_table(self, ax, df, title: str, height: Optional[float] = None): if __name__ == "__main__": - import matplotlib.pyplot as plt + from matplotlib import pyplot as plt p = TablePlotter() diff --git a/requirements-dev.txt b/requirements-dev.txt index 1ec998ffa72d4..76917312e0d32 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -11,7 +11,7 @@ cpplint flake8<3.8.0 flake8-comprehensions>=3.1.0 flake8-rst>=0.6.0,<=0.7.0 -isort==4.3.21 +isort==5.1.1 mypy==0.730 pycodestyle gitpython
- [x] closes #35134 - [x] 0 tests added / 0 passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35163
2020-07-07T17:46:29Z
2020-07-22T14:52:22Z
null
2020-07-22T14:52:48Z
REF: remove always-UTC arg from tz_convert, tz_convert_single
diff --git a/asv_bench/benchmarks/tslibs/tz_convert.py b/asv_bench/benchmarks/tslibs/tz_convert.py index 2a1f559bdf6d4..c2c90024ca5bd 100644 --- a/asv_bench/benchmarks/tslibs/tz_convert.py +++ b/asv_bench/benchmarks/tslibs/tz_convert.py @@ -1,16 +1,23 @@ import numpy as np from pytz import UTC -from pandas._libs.tslibs.tzconversion import tz_convert, tz_localize_to_utc +from pandas._libs.tslibs.tzconversion import tz_localize_to_utc from .tslib import _sizes, _tzs +try: + old_sig = False + from pandas._libs.tslibs.tzconversion import tz_convert_from_utc +except ImportError: + old_sig = True + from pandas._libs.tslibs.tzconversion import tz_convert as tz_convert_from_utc + class TimeTZConvert: - params = ( + params = [ _sizes, [x for x in _tzs if x is not None], - ) + ] param_names = ["size", "tz"] def setup(self, size, tz): @@ -21,7 +28,13 @@ def time_tz_convert_from_utc(self, size, tz): # effectively: # dti = DatetimeIndex(self.i8data, tz=tz) # dti.tz_localize(None) - tz_convert(self.i8data, UTC, tz) + if size >= 10 ** 6 and str(tz) == "tzlocal()": + # asv fill will because each call takes 8+seconds + return + if old_sig: + tz_convert_from_utc(self.i8data, UTC, tz) + else: + tz_convert_from_utc(self.i8data, tz) def time_tz_localize_to_utc(self, size, tz): # effectively: diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py index c2f3478a50ab4..6fe6fa0a13c34 100644 --- a/pandas/_libs/tslibs/__init__.py +++ b/pandas/_libs/tslibs/__init__.py @@ -19,7 +19,7 @@ "ints_to_pytimedelta", "get_resolution", "Timestamp", - "tz_convert_single", + "tz_convert_from_utc_single", "to_offset", "Tick", "BaseOffset", @@ -34,7 +34,7 @@ from .resolution import Resolution from .timedeltas import Timedelta, delta_to_nanoseconds, ints_to_pytimedelta from .timestamps import Timestamp -from .tzconversion import tz_convert_single +from .tzconversion import tz_convert_from_utc_single from .vectorized import ( dt64arr_to_periodarr, get_resolution, diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index fb07e3fe7547e..0f9280ae92d39 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -46,8 +46,7 @@ from pandas._libs.tslibs.np_datetime cimport ( dt64_to_dtstruct, pydate_to_dtstruct, ) -from pandas._libs.tslibs.timezones cimport utc_pytz as UTC -from pandas._libs.tslibs.tzconversion cimport tz_convert_single +from pandas._libs.tslibs.tzconversion cimport tz_convert_from_utc_single from .dtypes cimport PeriodDtypeCode from .timedeltas cimport delta_to_nanoseconds @@ -264,7 +263,7 @@ cdef _to_dt64D(dt): # equiv `Timestamp(dt).value` or `dt.timestamp() * 10**9` nanos = getattr(dt, "nanosecond", 0) i8 = convert_datetime_to_tsobject(dt, tz=None, nanos=nanos).value - dt = tz_convert_single(i8, UTC, dt.tzinfo) + dt = tz_convert_from_utc_single(i8, dt.tzinfo) dt = np.int64(dt).astype('datetime64[ns]') else: dt = np.datetime64(dt) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index a2dacd9d36b14..8cef685933863 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -59,7 +59,7 @@ from pandas._libs.tslibs.timezones cimport ( get_timezone, tz_compare, ) from pandas._libs.tslibs.tzconversion cimport ( - tz_convert_single, + tz_convert_from_utc_single, tz_localize_to_utc_single, ) @@ -1309,7 +1309,7 @@ default 'raise' else: if tz is None: # reset tz - value = tz_convert_single(self.value, UTC, self.tz) + value = tz_convert_from_utc_single(self.value, self.tz) return Timestamp(value, tz=tz, freq=self.freq) else: raise TypeError( @@ -1391,7 +1391,7 @@ default 'raise' tzobj = self.tzinfo value = self.value if tzobj is not None: - value = tz_convert_single(value, UTC, tzobj) + value = tz_convert_from_utc_single(value, tzobj) # setup components dt64_to_dtstruct(value, &dts) diff --git a/pandas/_libs/tslibs/tzconversion.pxd b/pandas/_libs/tslibs/tzconversion.pxd index 7d102868256de..1990afd77a8fb 100644 --- a/pandas/_libs/tslibs/tzconversion.pxd +++ b/pandas/_libs/tslibs/tzconversion.pxd @@ -3,7 +3,7 @@ from numpy cimport int64_t cdef int64_t tz_convert_utc_to_tzlocal(int64_t utc_val, tzinfo tz, bint* fold=*) -cpdef int64_t tz_convert_single(int64_t val, tzinfo tz1, tzinfo tz2) +cpdef int64_t tz_convert_from_utc_single(int64_t val, tzinfo tz) cdef int64_t tz_localize_to_utc_single( int64_t val, tzinfo tz, object ambiguous=*, object nonexistent=* ) except? -1 diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index 98c40e109dbab..a6afd47d93479 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -366,17 +366,16 @@ cdef int64_t tz_convert_utc_to_tzlocal(int64_t utc_val, tzinfo tz, bint* fold=NU return _tz_convert_tzlocal_utc(utc_val, tz, to_utc=False, fold=fold) -cpdef int64_t tz_convert_single(int64_t val, tzinfo tz1, tzinfo tz2): +cpdef int64_t tz_convert_from_utc_single(int64_t val, tzinfo tz): """ - Convert the val (in i8) from timezone1 to timezone2 + Convert the val (in i8) from UTC to tz - This is a single timezone version of tz_convert + This is a single value version of tz_convert_from_utc. Parameters ---------- val : int64 - tz1 : tzinfo - tz2 : tzinfo + tz : tzinfo Returns ------- @@ -384,38 +383,27 @@ cpdef int64_t tz_convert_single(int64_t val, tzinfo tz1, tzinfo tz2): """ cdef: int64_t arr[1] - bint to_utc = is_utc(tz2) - tzinfo tz - - # See GH#17734 We should always be converting either from UTC or to UTC - assert is_utc(tz1) or to_utc if val == NPY_NAT: return val - if to_utc: - tz = tz1 - else: - tz = tz2 - if is_utc(tz): return val elif is_tzlocal(tz): - return _tz_convert_tzlocal_utc(val, tz, to_utc=to_utc) + return _tz_convert_tzlocal_utc(val, tz, to_utc=False) else: arr[0] = val - return _tz_convert_dst(arr, tz, to_utc=to_utc)[0] + return _tz_convert_dst(arr, tz)[0] -def tz_convert(int64_t[:] vals, tzinfo tz1, tzinfo tz2): +def tz_convert_from_utc(int64_t[:] vals, tzinfo tz): """ - Convert the values (in i8) from timezone1 to timezone2 + Convert the values (in i8) from UTC to tz Parameters ---------- vals : int64 ndarray - tz1 : tzinfo - tz2 : tzinfo + tz : tzinfo Returns ------- @@ -423,36 +411,24 @@ def tz_convert(int64_t[:] vals, tzinfo tz1, tzinfo tz2): """ cdef: int64_t[:] converted - bint to_utc = is_utc(tz2) - tzinfo tz - - # See GH#17734 We should always be converting from UTC; otherwise - # should use tz_localize_to_utc. - assert is_utc(tz1) if len(vals) == 0: return np.array([], dtype=np.int64) - if to_utc: - tz = tz1 - else: - tz = tz2 - - converted = _tz_convert_one_way(vals, tz, to_utc=to_utc) + converted = _tz_convert_from_utc(vals, tz) return np.array(converted, dtype=np.int64) @cython.boundscheck(False) @cython.wraparound(False) -cdef int64_t[:] _tz_convert_one_way(int64_t[:] vals, tzinfo tz, bint to_utc): +cdef int64_t[:] _tz_convert_from_utc(int64_t[:] vals, tzinfo tz): """ Convert the given values (in i8) either to UTC or from UTC. Parameters ---------- vals : int64 ndarray - tz1 : tzinfo - to_utc : bool + tz : tzinfo Returns ------- @@ -472,9 +448,9 @@ cdef int64_t[:] _tz_convert_one_way(int64_t[:] vals, tzinfo tz, bint to_utc): if val == NPY_NAT: converted[i] = NPY_NAT else: - converted[i] = _tz_convert_tzlocal_utc(val, tz, to_utc) + converted[i] = _tz_convert_tzlocal_utc(val, tz, to_utc=False) else: - converted = _tz_convert_dst(vals, tz, to_utc) + converted = _tz_convert_dst(vals, tz) return converted @@ -565,9 +541,7 @@ cdef int64_t _tz_convert_tzlocal_utc(int64_t val, tzinfo tz, bint to_utc=True, @cython.boundscheck(False) @cython.wraparound(False) -cdef int64_t[:] _tz_convert_dst( - const int64_t[:] values, tzinfo tz, bint to_utc=True, -): +cdef int64_t[:] _tz_convert_dst(const int64_t[:] values, tzinfo tz): """ tz_convert for non-UTC non-tzlocal cases where we have to check DST transitions pointwise. @@ -576,8 +550,6 @@ cdef int64_t[:] _tz_convert_dst( ---------- values : ndarray[int64_t] tz : tzinfo - to_utc : bool - True if converting _to_ UTC, False if converting _from_ utc Returns ------- @@ -607,10 +579,7 @@ cdef int64_t[:] _tz_convert_dst( if v == NPY_NAT: result[i] = v else: - if to_utc: - result[i] = v - delta - else: - result[i] = v + delta + result[i] = v + delta else: # Previously, this search was done pointwise to try and benefit @@ -629,9 +598,6 @@ cdef int64_t[:] _tz_convert_dst( # it elsewhere? raise ValueError("First time before start of DST info") - if to_utc: - result[i] = v - deltas[pos[i]] - else: - result[i] = v + deltas[pos[i]] + result[i] = v + deltas[pos[i]] return result diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 8eac45cdedaec..5038df85c9160 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -728,7 +728,7 @@ def _local_timestamps(self): This is used to calculate time-of-day information as if the timestamps were timezone-naive. """ - return tzconversion.tz_convert(self.asi8, timezones.UTC, self.tz) + return tzconversion.tz_convert_from_utc(self.asi8, self.tz) def tz_convert(self, tz): """ @@ -960,7 +960,7 @@ def tz_localize(self, tz, ambiguous="raise", nonexistent="raise"): if self.tz is not None: if tz is None: - new_dates = tzconversion.tz_convert(self.asi8, timezones.UTC, self.tz) + new_dates = tzconversion.tz_convert_from_utc(self.asi8, self.tz) else: raise TypeError("Already tz-aware, use tz_convert to convert.") else: diff --git a/pandas/tests/scalar/timestamp/test_timezones.py b/pandas/tests/scalar/timestamp/test_timezones.py index 9611c827be6fe..83764aa184392 100644 --- a/pandas/tests/scalar/timestamp/test_timezones.py +++ b/pandas/tests/scalar/timestamp/test_timezones.py @@ -334,7 +334,7 @@ def test_timestamp_to_datetime_tzoffset(self): def test_timestamp_constructor_near_dst_boundary(self): # GH#11481 & GH#15777 # Naive string timestamps were being localized incorrectly - # with tz_convert_single instead of tz_localize_to_utc + # with tz_convert_from_utc_single instead of tz_localize_to_utc for tz in ["Europe/Brussels", "Europe/Prague"]: result = Timestamp("2015-10-25 01:00", tz=tz) diff --git a/pandas/tests/tslibs/test_api.py b/pandas/tests/tslibs/test_api.py index 957706fcb460e..ccaceb7e6f906 100644 --- a/pandas/tests/tslibs/test_api.py +++ b/pandas/tests/tslibs/test_api.py @@ -47,7 +47,7 @@ def test_namespace(): "delta_to_nanoseconds", "ints_to_pytimedelta", "localize_pydatetime", - "tz_convert_single", + "tz_convert_from_utc_single", "to_offset", ] diff --git a/pandas/tests/tslibs/test_conversion.py b/pandas/tests/tslibs/test_conversion.py index 5a16fea47e90d..b35940c6bb95b 100644 --- a/pandas/tests/tslibs/test_conversion.py +++ b/pandas/tests/tslibs/test_conversion.py @@ -12,9 +12,9 @@ def _compare_utc_to_local(tz_didx): def f(x): - return tzconversion.tz_convert_single(x, UTC, tz_didx.tz) + return tzconversion.tz_convert_from_utc_single(x, tz_didx.tz) - result = tzconversion.tz_convert(tz_didx.asi8, UTC, tz_didx.tz) + result = tzconversion.tz_convert_from_utc(tz_didx.asi8, tz_didx.tz) expected = np.vectorize(f)(tz_didx.asi8) tm.assert_numpy_array_equal(result, expected) @@ -22,9 +22,6 @@ def f(x): def _compare_local_to_utc(tz_didx, naive_didx): # Check that tz_localize behaves the same vectorized and pointwise. - def f(x): - return tzconversion.tz_convert_single(x, tz_didx.tz, UTC) - err1 = err2 = None try: result = tzconversion.tz_localize_to_utc(naive_didx.asi8, tz_didx.tz) @@ -71,7 +68,7 @@ def test_tz_convert_single_matches_tz_convert(tz_aware_fixture, freq): ], ) def test_tz_convert_corner(arr): - result = tzconversion.tz_convert(arr, UTC, timezones.maybe_get_tz("Asia/Tokyo")) + result = tzconversion.tz_convert_from_utc(arr, timezones.maybe_get_tz("Asia/Tokyo")) tm.assert_numpy_array_equal(result, arr) diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index f94c8ef6550a5..23e08c7550646 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -21,7 +21,6 @@ ) from pandas._libs.tslibs.parsing import get_rule_month from pandas._libs.tslibs.resolution import month_position_check -from pandas._libs.tslibs.timezones import UTC from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import ( @@ -198,7 +197,9 @@ def __init__(self, index, warn: bool = True): # the timezone so they are in local time if hasattr(index, "tz"): if index.tz is not None: - self.i8values = tzconversion.tz_convert(self.i8values, UTC, index.tz) + self.i8values = tzconversion.tz_convert_from_utc( + self.i8values, index.tz + ) self.warn = warn
https://api.github.com/repos/pandas-dev/pandas/pulls/35154
2020-07-07T01:53:44Z
2020-07-09T22:00:14Z
2020-07-09T22:00:14Z
2020-07-09T22:04:13Z
BUG: transform with nunique should have dtype int64
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 9bd4ddbb624d9..0e929ff062cff 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1080,6 +1080,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrame.groupby` lost index, when one of the ``agg`` keys referenced an empty list (:issue:`32580`) - Bug in :meth:`Rolling.apply` where ``center=True`` was ignored when ``engine='numba'`` was specified (:issue:`34784`) - Bug in :meth:`DataFrame.ewm.cov` was throwing ``AssertionError`` for :class:`MultiIndex` inputs (:issue:`34440`) +- Bug in :meth:`core.groupby.DataFrameGroupBy.transform` when ``func='nunique'`` and columns are of type ``datetime64``, the result would also be of type ``datetime64`` instead of ``int64`` (:issue:`35109`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/common.py b/pandas/core/common.py index b4f726f4e59a9..e7260a9923ee0 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -5,10 +5,11 @@ """ from collections import abc, defaultdict +import contextlib from datetime import datetime, timedelta from functools import partial import inspect -from typing import Any, Collection, Iterable, List, Union +from typing import Any, Collection, Iterable, Iterator, List, Union import warnings import numpy as np @@ -502,3 +503,21 @@ def convert_to_list_like( return list(values) return [values] + + +@contextlib.contextmanager +def temp_setattr(obj, attr: str, value) -> Iterator[None]: + """Temporarily set attribute on an object. + + Args: + obj: Object whose attribute will be modified. + attr: Attribute to modify. + value: Value to temporarily set attribute to. + + Yields: + obj with modified attribute. + """ + old_value = getattr(obj, attr) + setattr(obj, attr, value) + yield obj + setattr(obj, attr, old_value) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 6f956a3dcc9b6..61a739a009cf8 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -485,8 +485,10 @@ def transform(self, func, *args, engine="cython", engine_kwargs=None, **kwargs): # If func is a reduction, we need to broadcast the # result to the whole group. Compute func result # and deal with possible broadcasting below. - result = getattr(self, func)(*args, **kwargs) - return self._transform_fast(result, func) + # Temporarily set observed for dealing with categoricals. + with com.temp_setattr(self, "observed", True): + result = getattr(self, func)(*args, **kwargs) + return self._transform_fast(result) def _transform_general( self, func, *args, engine="cython", engine_kwargs=None, **kwargs @@ -539,17 +541,14 @@ def _transform_general( result.index = self._selected_obj.index return result - def _transform_fast(self, result, func_nm: str) -> Series: + def _transform_fast(self, result) -> Series: """ fast version of transform, only applicable to builtin/cythonizable functions """ ids, _, ngroup = self.grouper.group_info result = result.reindex(self.grouper.result_index, copy=False) - cast = self._transform_should_cast(func_nm) out = algorithms.take_1d(result._values, ids) - if cast: - out = maybe_cast_result(out, self.obj, how=func_nm) return self.obj._constructor(out, index=self.obj.index, name=self.obj.name) def filter(self, func, dropna=True, *args, **kwargs): @@ -1467,25 +1466,23 @@ def transform(self, func, *args, engine="cython", engine_kwargs=None, **kwargs): # If func is a reduction, we need to broadcast the # result to the whole group. Compute func result # and deal with possible broadcasting below. - result = getattr(self, func)(*args, **kwargs) + # Temporarily set observed for dealing with categoricals. + with com.temp_setattr(self, "observed", True): + result = getattr(self, func)(*args, **kwargs) if isinstance(result, DataFrame) and result.columns.equals( self._obj_with_exclusions.columns ): - return self._transform_fast(result, func) + return self._transform_fast(result) return self._transform_general( func, engine=engine, engine_kwargs=engine_kwargs, *args, **kwargs ) - def _transform_fast(self, result: DataFrame, func_nm: str) -> DataFrame: + def _transform_fast(self, result: DataFrame) -> DataFrame: """ Fast transform path for aggregations """ - # if there were groups with no observations (Categorical only?) - # try casting data to original dtype - cast = self._transform_should_cast(func_nm) - obj = self._obj_with_exclusions # for each col, reshape to to size of original frame @@ -1494,12 +1491,7 @@ def _transform_fast(self, result: DataFrame, func_nm: str) -> DataFrame: result = result.reindex(self.grouper.result_index, copy=False) output = [] for i, _ in enumerate(result.columns): - res = algorithms.take_1d(result.iloc[:, i].values, ids) - # TODO: we have no test cases that get here with EA dtypes; - # maybe_cast_result may not be needed if EAs never get here - if cast: - res = maybe_cast_result(res, obj.iloc[:, i], how=func_nm) - output.append(res) + output.append(algorithms.take_1d(result.iloc[:, i].values, ids)) return self.obj._constructor._from_arrays( output, columns=result.columns, index=obj.index diff --git a/pandas/tests/groupby/test_nunique.py b/pandas/tests/groupby/test_nunique.py index 1475b1ce2907c..c3347b7ae52f3 100644 --- a/pandas/tests/groupby/test_nunique.py +++ b/pandas/tests/groupby/test_nunique.py @@ -167,3 +167,11 @@ def test_nunique_preserves_column_level_names(): result = test.groupby([0, 0, 0]).nunique() expected = pd.DataFrame([2], columns=test.columns) tm.assert_frame_equal(result, expected) + + +def test_nunique_transform_with_datetime(): + # GH 35109 - transform with nunique on datetimes results in integers + df = pd.DataFrame(date_range("2008-12-31", "2009-01-02"), columns=["date"]) + result = df.groupby([0, 0, 1])["date"].transform("nunique") + expected = pd.Series([2, 2, 1], name="date") + tm.assert_series_equal(result, expected)
- [x] closes #35109 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry cc @WillAyd Removes casting on transformations which go through `_transform_fast`. The result is a reduction that is broadcast to the original index, so casting isn't necessary once special care is taken for categoricals when `observed=False` If this PR is accepted, I'll close #35130 which is for the same issue.
https://api.github.com/repos/pandas-dev/pandas/pulls/35152
2020-07-06T22:40:18Z
2020-07-10T22:46:42Z
2020-07-10T22:46:42Z
2020-07-10T22:47:43Z
CI: move py36 slow to azure (#34776)
diff --git a/.travis.yml b/.travis.yml index fdea9876d5d89..b016cf386098e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -58,12 +58,6 @@ matrix: services: - mysql - postgresql - - - env: - - JOB="3.6, slow" ENV_FILE="ci/deps/travis-36-slow.yaml" PATTERN="slow" SQL="1" - services: - - mysql - - postgresql allow_failures: - arch: arm64 env: diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml index 880fdc46f43f5..f716974f6add1 100644 --- a/ci/azure/posix.yml +++ b/ci/azure/posix.yml @@ -30,6 +30,11 @@ jobs: LC_ALL: "zh_CN.utf8" EXTRA_APT: "language-pack-zh-hans" + py36_slow: + ENV_FILE: ci/deps/azure-36-slow.yaml + CONDA_PY: "36" + PATTERN: "slow" + py36_locale: ENV_FILE: ci/deps/azure-36-locale.yaml CONDA_PY: "36" diff --git a/ci/deps/travis-36-slow.yaml b/ci/deps/azure-36-slow.yaml similarity index 100% rename from ci/deps/travis-36-slow.yaml rename to ci/deps/azure-36-slow.yaml diff --git a/ci/setup_env.sh b/ci/setup_env.sh index 4d551294dbb21..aa43d8b7dd00a 100755 --- a/ci/setup_env.sh +++ b/ci/setup_env.sh @@ -166,5 +166,4 @@ if [[ -n ${SQL:0} ]]; then else echo "not using dbs on non-linux Travis builds or Azure Pipelines" fi - echo "done"
- [x] closes #34776 - [x] 0 tests added / 0 passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35151
2020-07-06T22:18:18Z
2020-07-07T13:10:07Z
2020-07-07T13:10:07Z
2020-07-07T22:27:19Z
BUG: pd.crosstab fails when passed multiple columns, margins True and normalize True
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 42f95d88d74ac..f27c83fafef55 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -258,6 +258,7 @@ Reshaping - Bug in :meth:`DataFrame.pivot_table` with ``aggfunc='count'`` or ``aggfunc='sum'`` returning ``NaN`` for missing categories when pivoted on a ``Categorical``. Now returning ``0`` (:issue:`31422`) - Bug in :func:`union_indexes` where input index names are not preserved in some cases. Affects :func:`concat` and :class:`DataFrame` constructor (:issue:`13475`) +- Bug in func :meth:`crosstab` when using multiple columns with ``margins=True`` and ``normalize=True`` (:issue:`35144`) - Sparse diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index ea5916eff3afa..64a9e2dbf6d99 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -670,12 +670,11 @@ def _normalize(table, normalize, margins: bool, margins_name="All"): # keep index and column of pivoted table table_index = table.index table_columns = table.columns + last_ind_or_col = table.iloc[-1, :].name - # check if margin name is in (for MI cases) or equal to last + # check if margin name is not in (for MI cases) and not equal to last # index/column and save the column and index margin - if (margins_name not in table.iloc[-1, :].name) | ( - margins_name != table.iloc[:, -1].name - ): + if (margins_name not in last_ind_or_col) & (margins_name != last_ind_or_col): raise ValueError(f"{margins_name} not in pivoted DataFrame") column_margin = table.iloc[:-1, -1] index_margin = table.iloc[-1, :-1] diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py index 8795af2e11122..6f5550a6f8209 100644 --- a/pandas/tests/reshape/test_crosstab.py +++ b/pandas/tests/reshape/test_crosstab.py @@ -698,3 +698,48 @@ def test_margin_normalize(self): names=["A", "B"], ) tm.assert_frame_equal(result, expected) + + def test_margin_normalize_multiple_columns(self): + # GH 35144 + # use multiple columns with margins and normalization + df = DataFrame( + { + "A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"], + "B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"], + "C": [ + "small", + "large", + "large", + "small", + "small", + "large", + "small", + "small", + "large", + ], + "D": [1, 2, 2, 3, 3, 4, 5, 6, 7], + "E": [2, 4, 5, 5, 6, 6, 8, 9, 9], + } + ) + result = crosstab( + index=df.C, + columns=[df.A, df.B], + margins=True, + margins_name="margin", + normalize=True, + ) + expected = DataFrame( + [ + [0.111111, 0.111111, 0.222222, 0.000000, 0.444444], + [0.111111, 0.111111, 0.111111, 0.222222, 0.555556], + [0.222222, 0.222222, 0.333333, 0.222222, 1.0], + ], + index=["large", "small", "margin"], + ) + expected.columns = MultiIndex( + levels=[["bar", "foo", "margin"], ["", "one", "two"]], + codes=[[0, 0, 1, 1, 2], [1, 2, 1, 2, 0]], + names=["A", "B"], + ) + expected.index.name = "C" + tm.assert_frame_equal(result, expected)
- [x] closes #35144 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35150
2020-07-06T20:09:58Z
2020-08-19T17:59:04Z
2020-08-19T17:59:03Z
2020-08-20T00:09:02Z
ASV: tslibs.fields
diff --git a/asv_bench/benchmarks/tslibs/fields.py b/asv_bench/benchmarks/tslibs/fields.py new file mode 100644 index 0000000000000..0607a799ec707 --- /dev/null +++ b/asv_bench/benchmarks/tslibs/fields.py @@ -0,0 +1,74 @@ +import numpy as np + +from pandas._libs.tslibs.fields import ( + get_date_field, + get_start_end_field, + get_timedelta_field, +) + +from .tslib import _sizes + + +class TimeGetTimedeltaField: + params = [ + _sizes, + ["days", "h", "s", "seconds", "ms", "microseconds", "us", "ns", "nanoseconds"], + ] + param_names = ["size", "field"] + + def setup(self, size, field): + arr = np.random.randint(0, 10, size=size, dtype="i8") + self.i8data = arr + + def time_get_timedelta_field(self, size, field): + get_timedelta_field(self.i8data, field) + + +class TimeGetDateField: + params = [ + _sizes, + [ + "Y", + "M", + "D", + "h", + "m", + "s", + "us", + "ns", + "doy", + "dow", + "woy", + "q", + "dim", + "is_leap_year", + ], + ] + param_names = ["size", "field"] + + def setup(self, size, field): + arr = np.random.randint(0, 10, size=size, dtype="i8") + self.i8data = arr + + def time_get_date_field(self, size, field): + get_date_field(self.i8data, field) + + +class TimeGetStartEndField: + params = [ + _sizes, + ["start", "end"], + ["month", "quarter", "year"], + ["B", None, "QS"], + [12, 3, 5], + ] + param_names = ["size", "side", "period", "freqstr", "month_kw"] + + def setup(self, size, side, period, freqstr, month_kw): + arr = np.random.randint(0, 10, size=size, dtype="i8") + self.i8data = arr + + self.attrname = f"is_{period}_{side}" + + def time_get_start_end_field(self, size, side, period, freqstr, month_kw): + get_start_end_field(self.i8data, self.attrname, freqstr, month_kw=month_kw)
https://api.github.com/repos/pandas-dev/pandas/pulls/35149
2020-07-06T19:41:32Z
2020-07-08T21:51:13Z
2020-07-08T21:51:13Z
2020-07-08T21:57:08Z
Move mark registration
diff --git a/pandas/conftest.py b/pandas/conftest.py index 5fe4cc45b0006..e0adb37e7d2f5 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -44,6 +44,19 @@ # Configuration / Settings # ---------------------------------------------------------------- # pytest +def pytest_configure(config): + # Register marks to avoid warnings in pandas.test() + # sync with setup.cfg + config.addinivalue_line("markers", "single: mark a test as single cpu only") + config.addinivalue_line("markers", "slow: mark a test as slow") + config.addinivalue_line("markers", "network: mark a test as network") + config.addinivalue_line( + "markers", "db: tests requiring a database (mysql or postgres)" + ) + config.addinivalue_line("markers", "high_memory: mark a test as a high-memory only") + config.addinivalue_line("markers", "clipboard: mark a pd.read_clipboard test") + + def pytest_addoption(parser): parser.addoption("--skip-slow", action="store_true", help="skip slow tests") parser.addoption("--skip-network", action="store_true", help="skip network tests") diff --git a/setup.cfg b/setup.cfg index 49a57b7a525f0..074b0b6bdff71 100644 --- a/setup.cfg +++ b/setup.cfg @@ -54,13 +54,6 @@ exclude = # sync minversion with setup.cfg & install.rst minversion = 4.0.2 testpaths = pandas -markers = - single: mark a test as single cpu only - slow: mark a test as slow - network: mark a test as network - db: tests requiring a database (mysql or postgres) - high_memory: mark a test as a high-memory only - clipboard: mark a pd.read_clipboard test doctest_optionflags = NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL ELLIPSIS addopts = --strict-data-files xfail_strict = True
Should avoid warnings like ``` D:\a\1\s\test_venv\lib\site-packages\pandas\tests\plotting\test_series.py:655: PytestUnknownMarkWarning: Unknown pytest.mark.slow - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/latest/mark.html @pytest.mark.slow ``` in https://dev.azure.com/pandas-dev/pandas-wheels/_build/results?buildId=38672&view=logs&j=c0130b29-789d-5a3c-6978-10796a508a7f&t=e120bc6c-1f5e-5a41-8f0a-1d992cd2fbfb
https://api.github.com/repos/pandas-dev/pandas/pulls/35146
2020-07-06T18:06:03Z
2020-07-06T23:28:06Z
2020-07-06T23:28:06Z
2020-10-05T11:22:40Z
improved exception message
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index b12a556a8291d..01f785076cd15 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3270,7 +3270,13 @@ def _can_reindex(self, indexer): """ # trying to reindex on an axis with duplicates if not self.is_unique and len(indexer): - raise ValueError("cannot reindex from a duplicate axis") + msg = ( + """cannot reindex from a duplicate axis + (this usually occurs when trying to join / assign + to a column when the index contains duplicate values).""" + ) + + raise ValueError(msg) def reindex(self, target, method=None, level=None, limit=None, tolerance=None): """
for ValueError: cannot reindex from a duplicate axis - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35142
2020-07-06T16:32:20Z
2020-11-04T08:29:21Z
null
2020-11-04T08:29:21Z
DEPR: Deprecate n-dim indexing for Series
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 9bd4ddbb624d9..926aaaaabf3a9 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -788,6 +788,7 @@ Deprecations - :meth:`Categorical.to_dense` is deprecated and will be removed in a future version, use ``np.asarray(cat)`` instead (:issue:`32639`) - The ``fastpath`` keyword in the ``SingleBlockManager`` constructor is deprecated and will be removed in a future version (:issue:`33092`) - Providing ``suffixes`` as a ``set`` in :func:`pandas.merge` is deprecated. Provide a tuple instead (:issue:`33740`, :issue:`34741`). +- Indexing a series with a multi-dimensional indexer like ``[:, None]`` to return an ndarray now raises a ``FutureWarning``. Convert to a NumPy array before indexing instead (:issue:`27837`) - :meth:`Index.is_mixed` is deprecated and will be removed in a future version, check ``index.inferred_type`` directly instead (:issue:`32922`) - Passing any arguments but the first one to :func:`read_html` as diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py index 6dbcfef46fa98..d9aa02db3e42a 100644 --- a/pandas/core/indexers.py +++ b/pandas/core/indexers.py @@ -295,7 +295,7 @@ def length_of_indexer(indexer, target=None) -> int: raise AssertionError("cannot find the length of the indexer") -def deprecate_ndim_indexing(result): +def deprecate_ndim_indexing(result, stacklevel=3): """ Helper function to raise the deprecation warning for multi-dimensional indexing on 1D Series/Index. @@ -306,11 +306,11 @@ def deprecate_ndim_indexing(result): """ if np.ndim(result) > 1: warnings.warn( - "Support for multi-dimensional indexing (e.g. `index[:, None]`) " - "on an Index is deprecated and will be removed in a future " + "Support for multi-dimensional indexing (e.g. `obj[:, None]`) " + "is deprecated and will be removed in a future " "version. Convert to a numpy array before indexing instead.", - DeprecationWarning, - stacklevel=3, + FutureWarning, + stacklevel=stacklevel, ) diff --git a/pandas/core/series.py b/pandas/core/series.py index be4099d56d43a..6c1d21e4526cf 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -78,7 +78,7 @@ sanitize_array, ) from pandas.core.generic import NDFrame -from pandas.core.indexers import unpack_1tuple +from pandas.core.indexers import deprecate_ndim_indexing, unpack_1tuple from pandas.core.indexes.accessors import CombinedDatetimelikeProperties from pandas.core.indexes.api import Float64Index, Index, MultiIndex, ensure_index import pandas.core.indexes.base as ibase @@ -950,13 +950,9 @@ def _get_with(self, key): def _get_values_tuple(self, key): # mpl hackaround if com.any_none(*key): - # suppress warning from slicing the index with a 2d indexer. - # eventually we'll want Series itself to warn. - with warnings.catch_warnings(): - warnings.filterwarnings( - "ignore", "Support for multi-dim", DeprecationWarning - ) - return self._get_values(key) + result = self._get_values(key) + deprecate_ndim_indexing(result, stacklevel=5) + return result if not isinstance(self.index, MultiIndex): raise ValueError("Can only tuple-index with a MultiIndex") diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 30c58506f619d..c8b780455f862 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -855,7 +855,7 @@ def test_engine_reference_cycle(self): def test_getitem_2d_deprecated(self): # GH#30588 idx = self.create_index() - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): res = idx[:, None] assert isinstance(res, np.ndarray), type(res) diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index b1faaa2115f55..6d6193ceaf27d 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -95,7 +95,7 @@ def test_dti_business_getitem(self): def test_dti_business_getitem_matplotlib_hackaround(self): rng = pd.bdate_range(START, END) - with tm.assert_produces_warning(DeprecationWarning): + with tm.assert_produces_warning(FutureWarning): # GH#30588 multi-dimensional indexing deprecated values = rng[:, None] expected = rng.values[:, None] @@ -122,7 +122,7 @@ def test_dti_custom_getitem(self): def test_dti_custom_getitem_matplotlib_hackaround(self): rng = pd.bdate_range(START, END, freq="C") - with tm.assert_produces_warning(DeprecationWarning): + with tm.assert_produces_warning(FutureWarning): # GH#30588 multi-dimensional indexing deprecated values = rng[:, None] expected = rng.values[:, None] diff --git a/pandas/tests/indexes/interval/test_base.py b/pandas/tests/indexes/interval/test_base.py index 891640234d26e..c316655fbda8a 100644 --- a/pandas/tests/indexes/interval/test_base.py +++ b/pandas/tests/indexes/interval/test_base.py @@ -84,5 +84,5 @@ def test_getitem_2d_deprecated(self): # GH#30588 multi-dim indexing is deprecated, but raising is also acceptable idx = self.create_index() with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"): - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): idx[:, None] diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 099c7ced5e2ce..eaf48421dc071 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -56,7 +56,7 @@ def test_can_hold_identifiers(self): @pytest.mark.parametrize("index", ["datetime"], indirect=True) def test_new_axis(self, index): - with tm.assert_produces_warning(DeprecationWarning): + with tm.assert_produces_warning(FutureWarning): # GH#30588 multi-dimensional indexing deprecated new_index = index[None, :] assert new_index.ndim == 2 @@ -2531,7 +2531,7 @@ def test_shape_of_invalid_index(): # that the returned shape is consistent with this underlying array for # compat with matplotlib (see https://github.com/pandas-dev/pandas/issues/27775) idx = pd.Index([0, 1, 2, 3]) - with tm.assert_produces_warning(DeprecationWarning): + with tm.assert_produces_warning(FutureWarning): # GH#30588 multi-dimensional indexing deprecated assert idx[:, None].shape == (4, 1) diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index 164c63483f71f..6b7cda89a4714 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -51,11 +51,7 @@ class TestSeriesGetitemSlices: def test_getitem_slice_2d(self, datetime_series): # GH#30588 multi-dimensional indexing deprecated - # This is currently failing because the test was relying on - # the DeprecationWarning coming through Index.__getitem__. - # We want to implement a warning specifically for Series.__getitem__ - # at which point this will become a Deprecation/FutureWarning - with tm.assert_produces_warning(None): + with tm.assert_produces_warning(FutureWarning): # GH#30867 Don't want to support this long-term, but # for now ensure that the warning from Index # doesn't comes through via Series.__getitem__. @@ -135,3 +131,9 @@ def test_getitem_generator(string_series): expected = string_series[string_series > 0] tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected) + + +def test_getitem_ndim_deprecated(): + s = pd.Series([0, 1]) + with tm.assert_produces_warning(FutureWarning): + s[:, None]
Closes https://github.com/pandas-dev/pandas/issues/27837
https://api.github.com/repos/pandas-dev/pandas/pulls/35141
2020-07-06T15:14:46Z
2020-07-06T23:25:28Z
2020-07-06T23:25:28Z
2020-07-06T23:25:32Z
Fix regression on datetime in MultiIndex
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 708b687434327..04d1dbceb3342 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1165,6 +1165,10 @@ def _convert_to_indexer(self, key, axis: int, is_setter: bool = False): if len(key) == labels.nlevels: return {"key": key} raise + except InvalidIndexError: + # GH35015, using datetime as column indices raises exception + if not isinstance(labels, ABCMultiIndex): + raise except TypeError: pass except ValueError: diff --git a/pandas/tests/indexing/multiindex/test_datetime.py b/pandas/tests/indexing/multiindex/test_datetime.py index 907d20cd5bd53..a49cb0bc2c43e 100644 --- a/pandas/tests/indexing/multiindex/test_datetime.py +++ b/pandas/tests/indexing/multiindex/test_datetime.py @@ -2,7 +2,16 @@ import numpy as np -from pandas import Index, Period, Series, period_range +from pandas import ( + DataFrame, + Index, + MultiIndex, + Period, + Series, + period_range, + to_datetime, +) +import pandas._testing as tm def test_multiindex_period_datetime(): @@ -20,3 +29,22 @@ def test_multiindex_period_datetime(): # try datetime as index result = s.loc["a", datetime(2012, 1, 1)] assert result == expected + + +def test_multiindex_datetime_columns(): + # GH35015, using datetime as column indices raises exception + + mi = MultiIndex.from_tuples( + [(to_datetime("02/29/2020"), to_datetime("03/01/2020"))], names=["a", "b"] + ) + + df = DataFrame([], columns=mi) + + expected_df = DataFrame( + [], + columns=MultiIndex.from_arrays( + [[to_datetime("02/29/2020")], [to_datetime("03/01/2020")]], names=["a", "b"] + ), + ) + + tm.assert_frame_equal(df, expected_df)
- [x] closes #35015 - [x] tests added / passed - `tests.indexing.multiindex.test_datetime:test_multiindex_datetime_columns` - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry - Not needed - this was a regression
https://api.github.com/repos/pandas-dev/pandas/pulls/35140
2020-07-06T14:27:12Z
2020-07-08T12:43:19Z
2020-07-08T12:43:18Z
2020-07-08T15:40:22Z
CI: pin sphinx <= 3.1.1 for autodoc failure
diff --git a/environment.yml b/environment.yml index 2429f4ab3d699..87f3f4b13b5c5 100644 --- a/environment.yml +++ b/environment.yml @@ -27,7 +27,7 @@ dependencies: # documentation - gitpython # obtain contributors from git for whatsnew - gitdb2=2.0.6 # GH-32060 - - sphinx + - sphinx<=3.1.1 # documentation (jupyter notebooks) - nbconvert>=5.4.1 diff --git a/requirements-dev.txt b/requirements-dev.txt index 44c975a3b3cfb..d5d3fc54b47e7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -16,7 +16,7 @@ mypy==0.730 pycodestyle gitpython gitdb2==2.0.6 -sphinx +sphinx<=3.1.1 nbconvert>=5.4.1 nbsphinx pandoc
xref https://github.com/pandas-dev/pandas/issues/35138
https://api.github.com/repos/pandas-dev/pandas/pulls/35139
2020-07-06T14:03:02Z
2020-07-06T14:30:36Z
2020-07-06T14:30:36Z
2020-07-06T14:35:16Z
CI: pin isort version
diff --git a/environment.yml b/environment.yml index 2429f4ab3d699..24c0832b6fb4c 100644 --- a/environment.yml +++ b/environment.yml @@ -20,7 +20,7 @@ dependencies: - flake8<3.8.0 # temporary pin, GH#34150 - flake8-comprehensions>=3.1.0 # used by flake8, linting of unnecessary comprehensions - flake8-rst>=0.6.0,<=0.7.0 # linting of code blocks in rst files - - isort # check that imports are in the right order + - isort=4.3.21 # check that imports are in the right order - mypy=0.730 - pycodestyle # used by flake8 diff --git a/requirements-dev.txt b/requirements-dev.txt index 44c975a3b3cfb..eda0fa8f32b19 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -11,7 +11,7 @@ cpplint flake8<3.8.0 flake8-comprehensions>=3.1.0 flake8-rst>=0.6.0,<=0.7.0 -isort +isort==4.3.21 mypy==0.730 pycodestyle gitpython
- [X] xref #35134 - [X] 0 tests added / 0 passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry. __this is a CI PR. I don't think we touch whatsnew for those.__ ### Scope <s>Remove the `--recursive` keyword from `code_checks.sh`, so that the newest version of isort can run without errors (it does recursive sorting by default).</s> Pin the version instead, because version 5 has changed the way isort sorts imports. Needs more work to switch safely.
https://api.github.com/repos/pandas-dev/pandas/pulls/35136
2020-07-06T13:04:58Z
2020-07-06T14:19:44Z
2020-07-06T14:19:44Z
2020-07-09T15:12:19Z
CLN: unused imports in tslibs
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index df43ebcfd9df2..e4d05e0d70e2f 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -51,7 +51,6 @@ from pandas._libs.tslibs.timezones cimport utc_pytz as UTC from pandas._libs.tslibs.tzconversion cimport tz_convert_single from .dtypes cimport PeriodDtypeCode -from .fields import get_start_end_field from .timedeltas cimport delta_to_nanoseconds from .timedeltas import Timedelta from .timestamps cimport _Timestamp @@ -99,12 +98,6 @@ def apply_index_wraps(func): # do @functools.wraps(func) manually since it doesn't work on cdef funcs wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ - try: - wrapper.__module__ = func.__module__ - except AttributeError: - # AttributeError: 'method_descriptor' object has no - # attribute '__module__' - pass return wrapper @@ -159,12 +152,6 @@ def apply_wraps(func): # do @functools.wraps(func) manually since it doesn't work on cdef funcs wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ - try: - wrapper.__module__ = func.__module__ - except AttributeError: - # AttributeError: 'method_descriptor' object has no - # attribute '__module__' - pass return wrapper @@ -355,8 +342,7 @@ class ApplyTypeError(TypeError): cdef class BaseOffset: """ - Base class for DateOffset methods that are not overridden by subclasses - and will (after pickle errors are resolved) go into a cdef class. + Base class for DateOffset methods that are not overridden by subclasses. """ _day_opt = None _attributes = tuple(["n", "normalize"]) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index e104b722ea119..c4434f331b044 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -14,7 +14,7 @@ from numpy cimport int64_t, int8_t, uint8_t, ndarray cnp.import_array() from cpython.object cimport (PyObject_RichCompareBool, PyObject_RichCompare, - Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE) + Py_EQ, Py_NE) from cpython.datetime cimport ( datetime, @@ -51,7 +51,7 @@ from pandas._libs.tslibs.np_datetime cimport ( pydatetime_to_dt64, ) from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime -from pandas._libs.tslibs.offsets cimport to_offset, is_tick_object, is_offset_object +from pandas._libs.tslibs.offsets cimport to_offset, is_offset_object from pandas._libs.tslibs.timedeltas cimport is_any_td_scalar, delta_to_nanoseconds from pandas._libs.tslibs.timedeltas import Timedelta from pandas._libs.tslibs.timezones cimport (
https://api.github.com/repos/pandas-dev/pandas/pulls/35133
2020-07-06T02:15:29Z
2020-07-06T23:00:01Z
2020-07-06T23:00:01Z
2020-07-06T23:15:31Z
BUG: transform with nunique should have dtype int64
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 9bd4ddbb624d9..0e929ff062cff 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1080,6 +1080,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrame.groupby` lost index, when one of the ``agg`` keys referenced an empty list (:issue:`32580`) - Bug in :meth:`Rolling.apply` where ``center=True`` was ignored when ``engine='numba'`` was specified (:issue:`34784`) - Bug in :meth:`DataFrame.ewm.cov` was throwing ``AssertionError`` for :class:`MultiIndex` inputs (:issue:`34440`) +- Bug in :meth:`core.groupby.DataFrameGroupBy.transform` when ``func='nunique'`` and columns are of type ``datetime64``, the result would also be of type ``datetime64`` instead of ``int64`` (:issue:`35109`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index d0417d51da497..be073bc2aaead 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -319,6 +319,9 @@ def maybe_cast_result_dtype(dtype: DtypeObj, how: str) -> DtypeObj: return np.dtype(np.int64) elif how in ["add", "cumsum", "sum"] and isinstance(dtype, BooleanDtype): return Int64Dtype() + elif how == "nunique": + return np.dtype(np.int64) + return dtype diff --git a/pandas/tests/groupby/test_nunique.py b/pandas/tests/groupby/test_nunique.py index 1475b1ce2907c..8bd71c0cf6bd7 100644 --- a/pandas/tests/groupby/test_nunique.py +++ b/pandas/tests/groupby/test_nunique.py @@ -167,3 +167,10 @@ def test_nunique_preserves_column_level_names(): result = test.groupby([0, 0, 0]).nunique() expected = pd.DataFrame([2], columns=test.columns) tm.assert_frame_equal(result, expected) + + +def test_nunique_transform_with_datetime(): + df = pd.DataFrame(date_range("2008-12-31", "2009-01-02"), columns=["date"]) + result = df.groupby([0, 0, 1])["date"].transform("nunique") + expected = pd.Series([2, 2, 1], name="date") + tm.assert_series_equal(result, expected)
- [x] closes #35109 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35130
2020-07-05T21:11:37Z
2020-07-10T22:27:22Z
null
2020-07-11T16:00:46Z
support binary file handles in to_csv
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index cc42f952b1733..ab233f653061a 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -1064,6 +1064,23 @@ DD/MM/YYYY instead. For convenience, a ``dayfirst`` keyword is provided: pd.read_csv('tmp.csv', parse_dates=[0]) pd.read_csv('tmp.csv', dayfirst=True, parse_dates=[0]) +Writing CSVs to binary file objects ++++++++++++++++++++++++++++++++++++ + +.. versionadded:: 1.2.0 + +``df.to_csv(..., mode="w+b")`` allows writing a CSV to a file object +opened binary mode. For this to work, it is necessary that ``mode`` +contains a "b": + +.. ipython:: python + + import io + + data = pd.DataFrame([0, 1, 2]) + buffer = io.BytesIO() + data.to_csv(buffer, mode="w+b", encoding="utf-8", compression="gzip") + .. _io.float_precision: Specifying method for floating-point conversion diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 6f173cb2fce12..10dfd8406b8ce 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -13,6 +13,25 @@ including other versions of pandas. Enhancements ~~~~~~~~~~~~ +.. _whatsnew_120.binary_handle_to_csv: + +Support for binary file handles in ``to_csv`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:meth:`to_csv` supports file handles in binary mode (:issue:`19827` and :issue:`35058`) +with ``encoding`` (:issue:`13068` and :issue:`23854`) and ``compression`` (:issue:`22555`). +``mode`` has to contain a ``b`` for binary handles to be supported. + +For example: + +.. ipython:: python + + import io + + data = pd.DataFrame([0, 1, 2]) + buffer = io.BytesIO() + data.to_csv(buffer, mode="w+b", encoding="utf-8", compression="gzip") + .. _whatsnew_120.enhancements.other: Other enhancements @@ -121,7 +140,7 @@ MultiIndex I/O ^^^ -- +- Bug in :meth:`to_csv` caused a ``ValueError`` when it was called with a filename in combination with ``mode`` containing a ``b`` (:issue:`35058`) - Plotting @@ -167,4 +186,4 @@ Other .. _whatsnew_120.contributors: Contributors -~~~~~~~~~~~~ \ No newline at end of file +~~~~~~~~~~~~ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 42d02f37508fc..53b12e1abdee8 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3021,13 +3021,18 @@ def to_csv( ---------- path_or_buf : str or file handle, default None File path or object, if None is provided the result is returned as - a string. If a file object is passed it should be opened with - `newline=''`, disabling universal newlines. + a string. If a non-binary file object is passed, it should be opened + with `newline=''`, disabling universal newlines. If a binary + file object is passed, `mode` needs to contain a `'b'`. .. versionchanged:: 0.24.0 Was previously named "path" for Series. + .. versionchanged:: 1.2.0 + + Support for binary file objects was introduced. + sep : str, default ',' String of length 1. Field delimiter for the output file. na_rep : str, default '' @@ -3056,7 +3061,8 @@ def to_csv( Python write mode, default 'w'. encoding : str, optional A string representing the encoding to use in the output file, - defaults to 'utf-8'. + defaults to 'utf-8'. `encoding` is not supported if `path_or_buf` + is a non-binary file object. compression : str or dict, default 'infer' If str, represents compression mode. If dict, value at 'method' is the compression mode. Compression mode may be any of the following @@ -3080,6 +3086,10 @@ def to_csv( supported for compression modes 'gzip' and 'bz2' as well as 'zip'. + .. versionchanged:: 1.2.0 + + Compression is supported for non-binary file objects. + quoting : optional constant from csv module Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format` then floats are converted to strings and thus csv.QUOTE_NONNUMERIC diff --git a/pandas/io/common.py b/pandas/io/common.py index f39b8279fbdb0..34e4425c657f1 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -407,8 +407,9 @@ def get_handle( memory_map : boolean, default False See parsers._parser_params for more information. is_text : boolean, default True - whether file/buffer is in text format (csv, json, etc.), or in binary - mode (pickle, etc.). + Whether the type of the content passed to the file/buffer is string or + bytes. This is not the same as `"b" not in mode`. If a string content is + passed to a binary file/buffer, a wrapper is inserted. errors : str, default 'strict' Specifies how encoding and decoding errors are to be handled. See the errors argument for :func:`open` for a full list @@ -449,14 +450,14 @@ def get_handle( if is_path: f = gzip.open(path_or_buf, mode, **compression_args) else: - f = gzip.GzipFile(fileobj=path_or_buf, **compression_args) + f = gzip.GzipFile(fileobj=path_or_buf, mode=mode, **compression_args) # BZ Compression elif compression == "bz2": if is_path: f = bz2.BZ2File(path_or_buf, mode, **compression_args) else: - f = bz2.BZ2File(path_or_buf, **compression_args) + f = bz2.BZ2File(path_or_buf, mode=mode, **compression_args) # ZIP Compression elif compression == "zip": @@ -489,10 +490,14 @@ def get_handle( handles.append(f) elif is_path: - if encoding: + # Check whether the filename is to be opened in binary mode. + # Binary mode does not support 'encoding' and 'newline'. + is_binary_mode = "b" in mode + + if encoding and not is_binary_mode: # Encoding f = open(path_or_buf, mode, encoding=encoding, errors=errors, newline="") - elif is_text: + elif is_text and not is_binary_mode: # No explicit encoding f = open(path_or_buf, mode, errors="replace", newline="") else: diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index 5bd51dc8351f6..b10946a20d041 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -3,11 +3,10 @@ """ import csv as csvlib -from io import StringIO +from io import StringIO, TextIOWrapper import os from typing import Hashable, List, Mapping, Optional, Sequence, Union import warnings -from zipfile import ZipFile import numpy as np @@ -159,38 +158,29 @@ def save(self) -> None: """ Create the writer & save. """ - # GH21227 internal compression is not used when file-like passed. - if self.compression and hasattr(self.path_or_buf, "write"): + # GH21227 internal compression is not used for non-binary handles. + if ( + self.compression + and hasattr(self.path_or_buf, "write") + and "b" not in self.mode + ): warnings.warn( - "compression has no effect when passing file-like object as input.", + "compression has no effect when passing a non-binary object as input.", RuntimeWarning, stacklevel=2, ) - - # when zip compression is called. - is_zip = isinstance(self.path_or_buf, ZipFile) or ( - not hasattr(self.path_or_buf, "write") and self.compression == "zip" + self.compression = None + + # get a handle or wrap an existing handle to take care of 1) compression and + # 2) text -> byte conversion + f, handles = get_handle( + self.path_or_buf, + self.mode, + encoding=self.encoding, + errors=self.errors, + compression=dict(self.compression_args, method=self.compression), ) - if is_zip: - # zipfile doesn't support writing string to archive. uses string - # buffer to receive csv writing and dump into zip compression - # file handle. GH21241, GH21118 - f = StringIO() - close = False - elif hasattr(self.path_or_buf, "write"): - f = self.path_or_buf - close = False - else: - f, handles = get_handle( - self.path_or_buf, - self.mode, - encoding=self.encoding, - errors=self.errors, - compression=dict(self.compression_args, method=self.compression), - ) - close = True - try: # Note: self.encoding is irrelevant here self.writer = csvlib.writer( @@ -206,29 +196,23 @@ def save(self) -> None: self._save() finally: - if is_zip: - # GH17778 handles zip compression separately. - buf = f.getvalue() - if hasattr(self.path_or_buf, "write"): - self.path_or_buf.write(buf) - else: - compression = dict(self.compression_args, method=self.compression) - - f, handles = get_handle( - self.path_or_buf, - self.mode, - encoding=self.encoding, - errors=self.errors, - compression=compression, - ) - f.write(buf) - close = True - if close: + if self.should_close: f.close() - for _fh in handles: - _fh.close() - elif self.should_close: + elif ( + isinstance(f, TextIOWrapper) + and not f.closed + and f != self.path_or_buf + and hasattr(self.path_or_buf, "write") + ): + # get_handle uses TextIOWrapper for non-binary handles. TextIOWrapper + # closes the wrapped handle if it is not detached. + f.flush() # make sure everything is written + f.detach() # makes f unusable + del f + elif f != self.path_or_buf: f.close() + for _fh in handles: + _fh.close() def _save_header(self): writer = self.writer diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index 4c86e3a16b135..753b8b6eda9c5 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -607,3 +607,39 @@ def test_to_csv_errors(self, errors): ser.to_csv(path, errors=errors) # No use in reading back the data as it is not the same anymore # due to the error handling + + def test_to_csv_binary_handle(self): + """ + Binary file objects should work if 'mode' contains a 'b'. + + GH 35058 and GH 19827 + """ + df = tm.makeDataFrame() + with tm.ensure_clean() as path: + with open(path, mode="w+b") as handle: + df.to_csv(handle, mode="w+b") + tm.assert_frame_equal(df, pd.read_csv(path, index_col=0)) + + def test_to_csv_encoding_binary_handle(self): + """ + Binary file objects should honor a specified encoding. + + GH 23854 and GH 13068 with binary handles + """ + # example from GH 23854 + content = "a, b, 🐟".encode("utf-8-sig") + buffer = io.BytesIO(content) + df = pd.read_csv(buffer, encoding="utf-8-sig") + + buffer = io.BytesIO() + df.to_csv(buffer, mode="w+b", encoding="utf-8-sig", index=False) + buffer.seek(0) # tests whether file handle wasn't closed + assert buffer.getvalue().startswith(content) + + # example from GH 13068 + with tm.ensure_clean() as path: + with open(path, "w+b") as handle: + pd.DataFrame().to_csv(handle, mode="w+b", encoding="utf-8-sig") + + handle.seek(0) + assert handle.read().startswith(b'\xef\xbb\xbf""') diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index dde38eb55ea7f..5ce2233bc0cd0 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -378,6 +378,17 @@ def test_unknown_engine(self): with pytest.raises(ValueError, match="Unknown engine"): pd.read_csv(path, engine="pyt") + def test_binary_mode(self): + """ + 'encoding' shouldn't be passed to 'open' in binary mode. + + GH 35058 + """ + with tm.ensure_clean() as path: + df = tm.makeDataFrame() + df.to_csv(path, mode="w+b") + tm.assert_frame_equal(df, pd.read_csv(path, index_col=0)) + def test_is_fsspec_url(): assert icom.is_fsspec_url("gcs://pandas/somethingelse.com") diff --git a/pandas/tests/io/test_compression.py b/pandas/tests/io/test_compression.py index 59c9bd0a36d3d..902a3d5d2a397 100644 --- a/pandas/tests/io/test_compression.py +++ b/pandas/tests/io/test_compression.py @@ -114,6 +114,22 @@ def test_compression_warning(compression_only): df.to_csv(f, compression=compression_only) +def test_compression_binary(compression_only): + """ + Binary file handles support compression. + + GH22555 + """ + df = tm.makeDataFrame() + with tm.ensure_clean() as path: + with open(path, mode="wb") as file: + df.to_csv(file, mode="wb", compression=compression_only) + file.seek(0) # file shouldn't be closed + tm.assert_frame_equal( + df, pd.read_csv(path, index_col=0, compression=compression_only) + ) + + def test_with_missing_lzma(): """Tests if import pandas works when lzma is not present.""" # https://github.com/pandas-dev/pandas/issues/27575
- [x] fixes #19827, fixes #35058, fixes #23854 *, fixes #13068 *, and fixes #22555 - [x] 3 tests added - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry The first commit addresses https://github.com/pandas-dev/pandas/issues/35058#issuecomment-653844610: python's `open` cannot take an `encoding` argument when `mode` contains a `'b'` (opened in binary mode). This avoids an error when executing `df.to_csv("output.csv", mode="w+b")`. The second commit fixes #35058, #19827, #23854 *, and #13068 *: `to_csv` supports file handles in binary mode if `mode` contains a `b` and it honors `encoding`. `to_csv` re-invented a lot that was already done in `get_handle`. Let `get_handle` do the heavy lifting and remove all special cases from `to_csv`. The third commit fixes #22555: some compression algorithms did not set the mode to be writeable for file handles. Together with the re-factoring in the second commit, it is now possible to write to binary file handles with compression! *requesting an encoding for a non-binary file handles through `to_csv` still doesn't work but imho also doesn't make sense: specify the encoding yourself when opening the file or use a binary file handle
https://api.github.com/repos/pandas-dev/pandas/pulls/35129
2020-07-05T20:07:33Z
2020-08-07T11:53:10Z
2020-08-07T11:53:09Z
2020-08-07T22:45:53Z
CLN: remove the circular import in NDFrame.dtypes
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d892e2487b31c..9da9a9530480d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5366,9 +5366,8 @@ def dtypes(self): string object dtype: object """ - from pandas import Series # noqa: F811 - - return Series(self._mgr.get_dtypes(), index=self._info_axis, dtype=np.object_) + data = self._mgr.get_dtypes() + return self._constructor_sliced(data, index=self._info_axis, dtype=np.object_) def _to_dict_of_blocks(self, copy: bool_t = True): """
- [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/35128
2020-07-05T13:04:40Z
2020-07-07T00:39:26Z
2020-07-07T00:39:26Z
2020-07-07T07:24:17Z
ENH: make is_list_like handle non iterable numpy-like arrays correctly
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 3a11e7fbbdf33..a78ae49b3b18f 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1045,10 +1045,10 @@ def is_list_like(obj: object, allow_sets: bool = True) -> bool: cdef inline bint c_is_list_like(object obj, bint allow_sets) except -1: return ( isinstance(obj, abc.Iterable) + # avoid numpy-style scalars + and not (hasattr(obj, "ndim") and obj.ndim == 0) # we do not count strings/unicode/bytes as list-like and not isinstance(obj, (str, bytes)) - # exclude zero-dimensional numpy arrays, effectively scalars - and not (util.is_array(obj) and obj.ndim == 0) # exclude sets if allow_sets is False and not (allow_sets is False and isinstance(obj, abc.Set)) ) diff --git a/pandas/_libs/testing.pyx b/pandas/_libs/testing.pyx index 7a2fa471b9ba8..6cd5e45b73e17 100644 --- a/pandas/_libs/testing.pyx +++ b/pandas/_libs/testing.pyx @@ -11,6 +11,7 @@ from pandas._libs.lib import is_complex from pandas._libs.util cimport is_array, is_real_number_object from pandas.core.dtypes.common import is_dtype_equal +from pandas.core.dtypes.inference import is_array_like from pandas.core.dtypes.missing import array_equivalent, isna @@ -99,7 +100,9 @@ cpdef assert_almost_equal(a, b, return True a_is_ndarray = is_array(a) + a_has_size_and_shape = hasattr(a, "size") and hasattr(a, "shape") b_is_ndarray = is_array(b) + b_has_size_and_shape = hasattr(b, "size") and hasattr(b, "shape") if obj is None: if a_is_ndarray or b_is_ndarray: @@ -119,7 +122,7 @@ cpdef assert_almost_equal(a, b, f"Can't compare objects without length, one or both is invalid: ({a}, {b})" ) - if a_is_ndarray and b_is_ndarray: + if (a_is_ndarray and b_is_ndarray) or (a_has_size_and_shape and b_has_size_and_shape): na, nb = a.size, b.size if a.shape != b.shape: from pandas._testing import raise_assert_detail diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 0f4cef772458f..11f88cab54fea 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -60,6 +60,52 @@ def coerce(request): return request.param +class MockNumpyLikeArray: + """ + A class which is numpy-like (e.g. Pint's Quantity) but not actually numpy + + The key is that it is not actually a numpy array so + ``util.is_array(mock_numpy_like_array_instance)`` returns ``False``. Other + important properties are that the class defines a :meth:`__iter__` method + (so that ``isinstance(abc.Iterable)`` returns ``True``) and has a + :meth:`ndim` property which can be used as a check for whether it is a + scalar or not. + """ + + def __init__(self, values): + self._values = values + + def __iter__(self): + iter_values = iter(self._values) + + def it_outer(): + yield from iter_values + + return it_outer() + + def __len__(self): + return len(self._values) + + def __array__(self, t=None): + return self._values + + @property + def ndim(self): + return self._values.ndim + + @property + def dtype(self): + return self._values.dtype + + @property + def size(self): + return self._values.size + + @property + def shape(self): + return self._values.shape + + # collect all objects to be tested for list-like-ness; use tuples of objects, # whether they are list-like or not (special casing for sets), and their ID ll_params = [ @@ -94,6 +140,15 @@ def coerce(request): (np.ndarray((2,) * 4), True, "ndarray-4d"), (np.array([[[[]]]]), True, "ndarray-4d-empty"), (np.array(2), False, "ndarray-0d"), + (MockNumpyLikeArray(np.ndarray((2,) * 1)), True, "duck-ndarray-1d"), + (MockNumpyLikeArray(np.array([])), True, "duck-ndarray-1d-empty"), + (MockNumpyLikeArray(np.ndarray((2,) * 2)), True, "duck-ndarray-2d"), + (MockNumpyLikeArray(np.array([[]])), True, "duck-ndarray-2d-empty"), + (MockNumpyLikeArray(np.ndarray((2,) * 3)), True, "duck-ndarray-3d"), + (MockNumpyLikeArray(np.array([[[]]])), True, "duck-ndarray-3d-empty"), + (MockNumpyLikeArray(np.ndarray((2,) * 4)), True, "duck-ndarray-4d"), + (MockNumpyLikeArray(np.array([[[[]]]])), True, "duck-ndarray-4d-empty"), + (MockNumpyLikeArray(np.array(2)), False, "duck-ndarray-0d"), (1, False, "int"), (b"123", False, "bytes"), (b"", False, "bytes-empty"), @@ -154,6 +209,8 @@ def test_is_array_like(): assert inference.is_array_like(Series([1, 2])) assert inference.is_array_like(np.array(["a", "b"])) assert inference.is_array_like(Index(["2016-01-01"])) + assert inference.is_array_like(np.array([2, 3])) + assert inference.is_array_like(MockNumpyLikeArray(np.array([2, 3]))) class DtypeList(list): dtype = "special" @@ -166,6 +223,23 @@ class DtypeList(list): assert not inference.is_array_like(123) +def test_assert_almost_equal(): + tm.assert_almost_equal(np.array(2), np.array(2)) + eg = MockNumpyLikeArray(np.array(2)) + tm.assert_almost_equal(eg, eg) + + +@pytest.mark.parametrize( + "eg", + ( + np.array(2), + MockNumpyLikeArray(np.array(2)), + ), +) +def test_assert_almost_equal(eg): + tm.assert_almost_equal(eg, eg) + + @pytest.mark.parametrize( "inner", [ @@ -1427,34 +1501,52 @@ def test_is_scalar_builtin_nonscalars(self): assert not is_scalar(slice(None)) assert not is_scalar(Ellipsis) - def test_is_scalar_numpy_array_scalars(self): - assert is_scalar(np.int64(1)) - assert is_scalar(np.float64(1.0)) - assert is_scalar(np.int32(1)) - assert is_scalar(np.complex64(2)) - assert is_scalar(np.object_("foobar")) - assert is_scalar(np.str_("foobar")) - assert is_scalar(np.unicode_("foobar")) - assert is_scalar(np.bytes_(b"foobar")) - assert is_scalar(np.datetime64("2014-01-01")) - assert is_scalar(np.timedelta64(1, "h")) - - def test_is_scalar_numpy_zerodim_arrays(self): - for zerodim in [ - np.array(1), - np.array("foobar"), - np.array(np.datetime64("2014-01-01")), - np.array(np.timedelta64(1, "h")), - np.array(np.datetime64("NaT")), - ]: - assert not is_scalar(zerodim) - assert is_scalar(lib.item_from_zerodim(zerodim)) - + @pytest.mark.parametrize("start", ( + np.int64(1), + np.float64(1.0), + np.int32(1), + np.complex64(2), + np.object_("foobar"), + np.str_("foobar"), + np.unicode_("foobar"), + np.bytes_(b"foobar"), + np.datetime64("2014-01-01"), + np.timedelta64(1, "h"), + )) + @pytest.mark.parametrize("numpy_like", (True, False)) + def test_is_scalar_numpy_array_scalars(self, start, numpy_like): + if numpy_like: + start = MockNumpyLikeArray(start) + + assert is_scalar(start) + + @pytest.mark.parametrize("zerodim", ( + np.array(1), + np.array("foobar"), + np.array(np.datetime64("2014-01-01")), + np.array(np.timedelta64(1, "h")), + np.array(np.datetime64("NaT")), + )) + @pytest.mark.parametrize("numpy_like", (True, False)) + def test_is_scalar_numpy_zerodim_arrays(self, zerodim, numpy_like): + if numpy_like: + zerodim = MockNumpyLikeArray(zerodim) + + assert not is_scalar(zerodim) + assert is_scalar(lib.item_from_zerodim(zerodim)) + + @pytest.mark.parametrize("start", ( + np.array([]), + np.array([[]]), + np.matrix("1; 2"), + )) + @pytest.mark.parametrize("numpy_like", (True, False)) @pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") - def test_is_scalar_numpy_arrays(self): - assert not is_scalar(np.array([])) - assert not is_scalar(np.array([[]])) - assert not is_scalar(np.matrix("1; 2")) + def test_is_scalar_numpy_arrays(self, start, numpy_like): + if numpy_like: + start = MockNumpyLikeArray(start) + + assert not is_scalar(start) def test_is_scalar_pandas_scalars(self): assert is_scalar(Timestamp("2014-01-01"))
- [x] closes #35131 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35127
2020-07-05T05:27:10Z
2021-07-11T23:27:17Z
null
2021-11-26T00:54:47Z
TST: Add test for category equalness on applies (#21239)
diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index 114b3c0d0a3fc..3a32278e2a4b1 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -793,6 +793,18 @@ def test_apply_with_byte_string(self): result = df.apply(lambda x: x.astype("object")) tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize("val", ["asd", 12, None, np.NaN]) + def test_apply_category_equalness(self, val): + # Check if categorical comparisons on apply, GH 21239 + df_values = ["asd", None, 12, "asd", "cde", np.NaN] + df = pd.DataFrame({"a": df_values}, dtype="category") + + result = df.a.apply(lambda x: x == val) + expected = pd.Series( + [np.NaN if pd.isnull(x) else x == val for x in df_values], name="a" + ) + tm.assert_series_equal(result, expected) + class TestInferOutputShape: # the user has supplied an opaque UDF where
- [x] closes #21239 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry The test checks if equalness comparisons through `df.apply()` works correctly for the categorical `dtype`, especially with `np.NaN` and `None` values.
https://api.github.com/repos/pandas-dev/pandas/pulls/35125
2020-07-04T20:51:02Z
2020-07-06T21:28:08Z
2020-07-06T21:28:08Z
2020-07-06T21:28:17Z
CLN: remove kwargs in Index.format
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 2f12a2e4c27ea..3dbee7d0929cb 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -902,7 +902,12 @@ def _mpl_repr(self): # how to represent ourselves to matplotlib return self.values - def format(self, name: bool = False, formatter=None, **kwargs): + def format( + self, + name: bool = False, + formatter: Optional[Callable] = None, + na_rep: str_t = "NaN", + ) -> List[str_t]: """ Render a string representation of the Index. """ @@ -917,7 +922,7 @@ def format(self, name: bool = False, formatter=None, **kwargs): if formatter is not None: return header + list(self.map(formatter)) - return self._format_with_header(header, **kwargs) + return self._format_with_header(header, na_rep=na_rep) def _format_with_header(self, header, na_rep="NaN") -> List[str_t]: from pandas.io.formats.format import format_array diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 7be6aa50fa16b..15a7e25238983 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -9,7 +9,7 @@ from pandas._libs import NaT, Timedelta, iNaT, join as libjoin, lib from pandas._libs.tslibs import BaseOffset, Resolution, Tick, timezones from pandas._libs.tslibs.parsing import DateParseError -from pandas._typing import Label +from pandas._typing import Callable, Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, cache_readonly, doc @@ -338,6 +338,26 @@ def argmax(self, axis=None, skipna=True, *args, **kwargs): # -------------------------------------------------------------------- # Rendering Methods + def format( + self, + name: bool = False, + formatter: Optional[Callable] = None, + na_rep: str = "NaT", + date_format: Optional[str] = None, + ) -> List[str]: + """ + Render a string representation of the Index. + """ + header = [] + if name: + fmt_name = ibase.pprint_thing(self.name, escape_chars=("\t", "\r", "\n")) + header.append(fmt_name) + + if formatter is not None: + return header + list(self.map(formatter)) + + return self._format_with_header(header, na_rep=na_rep, date_format=date_format) + def _format_with_header(self, header, na_rep="NaT", date_format=None) -> List[str]: return header + list( self._format_native_types(na_rep=na_rep, date_format=date_format) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 15db6c51a1f2f..235da89083d0a 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2,6 +2,7 @@ from typing import ( TYPE_CHECKING, Any, + Callable, Hashable, Iterable, List, @@ -1231,13 +1232,17 @@ def _format_native_types(self, na_rep="nan", **kwargs): def format( self, - space=2, + name: Optional[bool] = None, + formatter: Optional[Callable] = None, + na_rep: Optional[str] = None, + names: bool = False, + space: int = 2, sparsify=None, - adjoin=True, - names=False, - na_rep=None, - formatter=None, - ): + adjoin: bool = True, + ) -> List: + if name is not None: + names = name + if len(self) == 0: return [] @@ -1265,13 +1270,13 @@ def format( stringified_levels.append(formatted) result_levels = [] - for lev, name in zip(stringified_levels, self.names): + for lev, lev_name in zip(stringified_levels, self.names): level = [] if names: level.append( - pprint_thing(name, escape_chars=("\t", "\r", "\n")) - if name is not None + pprint_thing(lev_name, escape_chars=("\t", "\r", "\n")) + if lev_name is not None else "" ) @@ -1283,10 +1288,9 @@ def format( if sparsify: sentinel = "" - # GH3547 - # use value of sparsify as sentinel, unless it's an obvious - # "Truthy" value - if sparsify not in [True, 1]: + # GH3547 use value of sparsify as sentinel if it's "Falsey" + assert isinstance(sparsify, bool) or sparsify is lib.no_default + if sparsify in [False, lib.no_default]: sentinel = sparsify # little bit of a kludge job for #1217 result_levels = _sparsify( diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 6d9fd6efe54a3..e5e98039ff77b 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -198,7 +198,7 @@ def _format_data(self, name=None): return None def _format_with_header(self, header, na_rep="NaN") -> List[str]: - return header + list(map(pprint_thing, self._range)) + return header + [pprint_thing(x) for x in self._range] # -------------------------------------------------------------------- _deprecation_message = ( diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 27df014620f56..fe85eab4bfbf5 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -330,9 +330,8 @@ def _get_footer(self) -> str: def _get_formatted_index(self) -> Tuple[List[str], bool]: index = self.tr_series.index - is_multi = isinstance(index, MultiIndex) - if is_multi: + if isinstance(index, MultiIndex): have_header = any(name for name in index.names) fmt_index = index.format(names=True) else: diff --git a/pandas/io/formats/html.py b/pandas/io/formats/html.py index 7ea2417ceb24b..13f0ab1e8a52c 100644 --- a/pandas/io/formats/html.py +++ b/pandas/io/formats/html.py @@ -442,6 +442,7 @@ def _write_hierarchical_rows( frame = self.fmt.tr_frame nrows = len(frame) + assert isinstance(frame.index, MultiIndex) idx_values = frame.index.format(sparsify=False, adjoin=False, names=False) idx_values = list(zip(*idx_values))
Removes kwargs in ``Index.format`` and subclasses. Also changes ``Index._format_with_header`` to have parameter ``na_rep`` not have a default value (in order to not have default value set in two locations). Related to #35118.
https://api.github.com/repos/pandas-dev/pandas/pulls/35122
2020-07-04T13:06:52Z
2020-07-14T22:32:48Z
2020-07-14T22:32:48Z
2020-08-08T08:30:27Z
TST add test case for drop_duplicates
diff --git a/pandas/tests/frame/methods/test_drop_duplicates.py b/pandas/tests/frame/methods/test_drop_duplicates.py index 7c6391140e2bb..cebec215a0d9d 100644 --- a/pandas/tests/frame/methods/test_drop_duplicates.py +++ b/pandas/tests/frame/methods/test_drop_duplicates.py @@ -333,64 +333,73 @@ def test_drop_duplicates_inplace(): ) # single column df = orig.copy() - df.drop_duplicates("A", inplace=True) + return_value = df.drop_duplicates("A", inplace=True) expected = orig[:2] result = df tm.assert_frame_equal(result, expected) + assert return_value is None df = orig.copy() - df.drop_duplicates("A", keep="last", inplace=True) + return_value = df.drop_duplicates("A", keep="last", inplace=True) expected = orig.loc[[6, 7]] result = df tm.assert_frame_equal(result, expected) + assert return_value is None df = orig.copy() - df.drop_duplicates("A", keep=False, inplace=True) + return_value = df.drop_duplicates("A", keep=False, inplace=True) expected = orig.loc[[]] result = df tm.assert_frame_equal(result, expected) assert len(df) == 0 + assert return_value is None # multi column df = orig.copy() - df.drop_duplicates(["A", "B"], inplace=True) + return_value = df.drop_duplicates(["A", "B"], inplace=True) expected = orig.loc[[0, 1, 2, 3]] result = df tm.assert_frame_equal(result, expected) + assert return_value is None df = orig.copy() - df.drop_duplicates(["A", "B"], keep="last", inplace=True) + return_value = df.drop_duplicates(["A", "B"], keep="last", inplace=True) expected = orig.loc[[0, 5, 6, 7]] result = df tm.assert_frame_equal(result, expected) + assert return_value is None df = orig.copy() - df.drop_duplicates(["A", "B"], keep=False, inplace=True) + return_value = df.drop_duplicates(["A", "B"], keep=False, inplace=True) expected = orig.loc[[0]] result = df tm.assert_frame_equal(result, expected) + assert return_value is None # consider everything orig2 = orig.loc[:, ["A", "B", "C"]].copy() df2 = orig2.copy() - df2.drop_duplicates(inplace=True) + return_value = df2.drop_duplicates(inplace=True) # in this case only expected = orig2.drop_duplicates(["A", "B"]) result = df2 tm.assert_frame_equal(result, expected) + assert return_value is None df2 = orig2.copy() - df2.drop_duplicates(keep="last", inplace=True) + return_value = df2.drop_duplicates(keep="last", inplace=True) expected = orig2.drop_duplicates(["A", "B"], keep="last") result = df2 tm.assert_frame_equal(result, expected) + assert return_value is None df2 = orig2.copy() - df2.drop_duplicates(keep=False, inplace=True) + return_value = df2.drop_duplicates(keep=False, inplace=True) expected = orig2.drop_duplicates(["A", "B"], keep=False) result = df2 tm.assert_frame_equal(result, expected) + assert return_value is None @pytest.mark.parametrize("inplace", [True, False])
Add a test case to drop_duplicates for inplace=True.
https://api.github.com/repos/pandas-dev/pandas/pulls/35121
2020-07-04T12:13:06Z
2020-07-08T12:52:26Z
2020-07-08T12:52:25Z
2020-07-08T15:40:09Z
TYP, DOC, CLN:SeriesGroupBy._wrap_applied_output
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 6f956a3dcc9b6..ebb9d82766c1b 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -19,6 +19,7 @@ Iterable, List, Mapping, + Optional, Sequence, Tuple, Type, @@ -30,7 +31,7 @@ import numpy as np from pandas._libs import lib -from pandas._typing import FrameOrSeries +from pandas._typing import FrameOrSeries, FrameOrSeriesUnion from pandas.util._decorators import Appender, Substitution, doc from pandas.core.dtypes.cast import ( @@ -413,12 +414,31 @@ def _wrap_transformed_output( assert isinstance(result, Series) return result - def _wrap_applied_output(self, keys, values, not_indexed_same=False): + def _wrap_applied_output( + self, keys: Index, values: Optional[List[Any]], not_indexed_same: bool = False + ) -> FrameOrSeriesUnion: + """ + Wrap the output of SeriesGroupBy.apply into the expected result. + + Parameters + ---------- + keys : Index + Keys of groups that Series was grouped by. + values : Optional[List[Any]] + Applied output for each group. + not_indexed_same : bool, default False + Whether the applied outputs are not indexed the same as the group axes. + + Returns + ------- + DataFrame or Series + """ if len(keys) == 0: # GH #6265 return self.obj._constructor( [], name=self._selection_name, index=keys, dtype=np.float64 ) + assert values is not None def _get_index() -> Index: if self.grouper.nkeys > 1: @@ -430,7 +450,7 @@ def _get_index() -> Index: if isinstance(values[0], dict): # GH #823 #24880 index = _get_index() - result = self._reindex_output( + result: FrameOrSeriesUnion = self._reindex_output( self.obj._constructor_expanddim(values, index=index) ) # if self.observed is False, @@ -438,11 +458,7 @@ def _get_index() -> Index: result = result.stack(dropna=self.observed) result.name = self._selection_name return result - - if isinstance(values[0], Series): - return self._concat_objects(keys, values, not_indexed_same=not_indexed_same) - elif isinstance(values[0], DataFrame): - # possible that Series -> DataFrame by applied function + elif isinstance(values[0], (Series, DataFrame)): return self._concat_objects(keys, values, not_indexed_same=not_indexed_same) else: # GH #6265 #24880
- [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/35120
2020-07-04T11:14:26Z
2020-07-07T19:19:27Z
2020-07-07T19:19:27Z
2020-07-07T20:18:13Z
REF: make ccalendar self-contained
diff --git a/pandas/_libs/tslibs/ccalendar.pyx b/pandas/_libs/tslibs/ccalendar.pyx index 9f8cf6c28adab..de8fd3911e946 100644 --- a/pandas/_libs/tslibs/ccalendar.pyx +++ b/pandas/_libs/tslibs/ccalendar.pyx @@ -7,11 +7,6 @@ import cython from numpy cimport int64_t, int32_t -from locale import LC_TIME - -from pandas._config.localization import set_locale -from pandas._libs.tslibs.strptime import LocaleTime - # ---------------------------------------------------------------------- # Constants @@ -246,21 +241,3 @@ cpdef int32_t get_day_of_year(int year, int month, int day) nogil: day_of_year = mo_off + day return day_of_year - - -def get_locale_names(name_type: str, locale: object = None): - """ - Returns an array of localized day or month names. - - Parameters - ---------- - name_type : string, attribute of LocaleTime() in which to return localized - names - locale : string - - Returns - ------- - list of locale names - """ - with set_locale(locale, LC_TIME): - return getattr(LocaleTime(), name_type) diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index 126deb67e4189..2351aca749dcc 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -2,6 +2,7 @@ Functions for accessing attributes of Timestamp/datetime64/datetime-like objects and arrays """ +from locale import LC_TIME import cython from cython import Py_ssize_t @@ -11,9 +12,9 @@ cimport numpy as cnp from numpy cimport ndarray, int64_t, int32_t, int8_t, uint32_t cnp.import_array() -from pandas._libs.tslibs.ccalendar import ( - get_locale_names, MONTHS_FULL, DAYS_FULL, -) +from pandas._config.localization import set_locale + +from pandas._libs.tslibs.ccalendar import MONTHS_FULL, DAYS_FULL from pandas._libs.tslibs.ccalendar cimport ( DAY_NANOS, get_days_in_month, is_leapyear, dayofweek, get_week_of_year, @@ -24,6 +25,7 @@ from pandas._libs.tslibs.np_datetime cimport ( npy_datetimestruct, pandas_timedeltastruct, dt64_to_dtstruct, td64_to_tdstruct) from pandas._libs.tslibs.nattype cimport NPY_NAT +from pandas._libs.tslibs.strptime import LocaleTime def get_time_micros(const int64_t[:] dtindex): @@ -704,3 +706,21 @@ def build_isocalendar_sarray(const int64_t[:] dtindex): iso_weeks[i] = ret_val[1] days[i] = ret_val[2] return out + + +def get_locale_names(name_type: str, locale: object = None): + """ + Returns an array of localized day or month names. + + Parameters + ---------- + name_type : string, attribute of LocaleTime() in which to return localized + names + locale : string + + Returns + ------- + list of locale names + """ + with set_locale(locale, LC_TIME): + return getattr(LocaleTime(), name_type)
https://api.github.com/repos/pandas-dev/pandas/pulls/35119
2020-07-04T03:03:43Z
2020-07-07T00:44:21Z
2020-07-07T00:44:21Z
2020-07-07T01:04:23Z
CLN: Index._format_with_header (remove kwargs etc.)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index b12a556a8291d..2f12a2e4c27ea 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2,7 +2,16 @@ from datetime import datetime import operator from textwrap import dedent -from typing import TYPE_CHECKING, Any, Callable, FrozenSet, Hashable, Optional, Union +from typing import ( + TYPE_CHECKING, + Any, + Callable, + FrozenSet, + Hashable, + List, + Optional, + Union, +) import warnings import numpy as np @@ -910,15 +919,12 @@ def format(self, name: bool = False, formatter=None, **kwargs): return self._format_with_header(header, **kwargs) - def _format_with_header(self, header, na_rep="NaN", **kwargs): - values = self._values - + def _format_with_header(self, header, na_rep="NaN") -> List[str_t]: from pandas.io.formats.format import format_array - if is_categorical_dtype(values.dtype): - values = np.array(values) + values = self._values - elif is_object_dtype(values.dtype): + if is_object_dtype(values.dtype): values = lib.maybe_convert_objects(values, safe=1) if is_object_dtype(values.dtype): @@ -929,10 +935,9 @@ def _format_with_header(self, header, na_rep="NaN", **kwargs): if mask.any(): result = np.array(result) result[mask] = na_rep - result = result.tolist() - + result = result.tolist() # type: ignore else: - result = _trim_front(format_array(values, None, justify="left")) + result = trim_front(format_array(values, None, justify="left")) return header + result def to_native_types(self, slicer=None, **kwargs): @@ -5611,7 +5616,7 @@ def ensure_has_len(seq): return seq -def _trim_front(strings): +def trim_front(strings: List[str]) -> List[str]: """ Trims zeros and decimal points. """ diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 2a79c83de7ef2..b0b008de69a94 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -347,6 +347,15 @@ def _format_attrs(self): attrs.append(("length", len(self))) return attrs + def _format_with_header(self, header, na_rep="NaN") -> List[str]: + from pandas.io.formats.format import format_array + + formatted_values = format_array( + self._values, formatter=None, na_rep=na_rep, justify="left" + ) + result = ibase.trim_front(formatted_values) + return header + result + # -------------------------------------------------------------------- @property diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 49b8ec3276e37..7be6aa50fa16b 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -338,8 +338,10 @@ def argmax(self, axis=None, skipna=True, *args, **kwargs): # -------------------------------------------------------------------- # Rendering Methods - def _format_with_header(self, header, na_rep="NaT", **kwargs): - return header + list(self._format_native_types(na_rep, **kwargs)) + def _format_with_header(self, header, na_rep="NaT", date_format=None) -> List[str]: + return header + list( + self._format_native_types(na_rep=na_rep, date_format=date_format) + ) @property def _formatter_func(self): diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index f7a7b382b853f..9548ebbd9c3b2 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1,7 +1,7 @@ """ define the IntervalIndex """ from operator import le, lt import textwrap -from typing import Any, Optional, Tuple, Union +from typing import Any, List, Optional, Tuple, Union import numpy as np @@ -948,8 +948,8 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs): # Rendering Methods # __repr__ associated methods are based on MultiIndex - def _format_with_header(self, header, **kwargs): - return header + list(self._format_native_types(**kwargs)) + def _format_with_header(self, header, na_rep="NaN") -> List[str]: + return header + list(self._format_native_types(na_rep=na_rep)) def _format_native_types(self, na_rep="NaN", quoting=None, **kwargs): # GH 28210: use base method but with different default na_rep diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 49a0f0fb7ae92..6d9fd6efe54a3 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -1,7 +1,7 @@ from datetime import timedelta import operator from sys import getsizeof -from typing import Any, Optional +from typing import Any, List, Optional import warnings import numpy as np @@ -197,7 +197,7 @@ def _format_data(self, name=None): # we are formatting thru the attributes return None - def _format_with_header(self, header, na_rep="NaN", **kwargs): + def _format_with_header(self, header, na_rep="NaN") -> List[str]: return header + list(map(pprint_thing, self._range)) # -------------------------------------------------------------------- diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index f7ba4750bc2ad..6250e99252928 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1524,7 +1524,10 @@ def _get_level_lengths(index, hidden_elements=None): Result is a dictionary of (level, initial_position): span """ - levels = index.format(sparsify=lib.no_default, adjoin=False, names=False) + if isinstance(index, pd.MultiIndex): + levels = index.format(sparsify=lib.no_default, adjoin=False) + else: + levels = index.format() if hidden_elements is None: hidden_elements = []
Refactor of ``Index._format_with_header`` and subclass methods: * remove ``kwargs`` for cleaner signature. * Add return type * Move functionality specific to ``CategoricalIndex`` to that class.
https://api.github.com/repos/pandas-dev/pandas/pulls/35118
2020-07-03T22:10:37Z
2020-07-07T13:20:00Z
2020-07-07T13:20:00Z
2020-08-08T08:30:29Z
CLN: convert lambda to function
diff --git a/pandas/io/formats/printing.py b/pandas/io/formats/printing.py index 36e774305b577..1cf79dc105901 100644 --- a/pandas/io/formats/printing.py +++ b/pandas/io/formats/printing.py @@ -276,9 +276,13 @@ class TableSchemaFormatter(BaseFormatter): formatters[mimetype].enabled = False -default_pprint = lambda x, max_seq_items=None: pprint_thing( - x, escape_chars=("\t", "\r", "\n"), quote_strings=True, max_seq_items=max_seq_items -) +def default_pprint(thing: Any, max_seq_items: Optional[int] = None) -> str: + return pprint_thing( + thing, + escape_chars=("\t", "\r", "\n"), + quote_strings=True, + max_seq_items=max_seq_items, + ) def format_object_summary(
Minor cleanup: conversion to proper function.
https://api.github.com/repos/pandas-dev/pandas/pulls/35117
2020-07-03T21:34:26Z
2020-07-04T15:30:16Z
2020-07-04T15:30:16Z
2020-07-04T15:30:21Z
TST: base test for ExtensionArray.astype to its own type + copy keyword
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 5882b74aa8b05..af63d49a24d7a 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -361,6 +361,7 @@ ExtensionArray ^^^^^^^^^^^^^^ - Fixed Bug where :class:`DataFrame` column set to scalar extension type via a dict instantion was considered an object type rather than the extension type (:issue:`35965`) +- Fixed bug where ``astype()`` with equal dtype and ``copy=False`` would return a new object (:issue:`284881`) - diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index e93cdb608dffb..eae401f9744f0 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -457,6 +457,11 @@ def astype(self, dtype, copy=True): from pandas.core.arrays.string_ import StringDtype dtype = pandas_dtype(dtype) + if is_dtype_equal(dtype, self.dtype): + if not copy: + return self + elif copy: + return self.copy() if isinstance(dtype, StringDtype): # allow conversion to StringArrays return dtype.construct_array_type()._from_sequence(self, copy=False) diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index bd4bdc5ecb46f..3bd36209b3c71 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -375,7 +375,10 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: if isinstance(dtype, BooleanDtype): values, mask = coerce_to_array(self, copy=copy) - return BooleanArray(values, mask, copy=False) + if not copy: + return self + else: + return BooleanArray(values, mask, copy=False) elif isinstance(dtype, StringDtype): return dtype.construct_array_type()._from_sequence(self, copy=False) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 44c0455018a42..372ef7df9dc3a 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -33,6 +33,7 @@ TD64NS_DTYPE, ensure_object, is_datetime64_dtype, + is_dtype_equal, is_float_dtype, is_period_dtype, pandas_dtype, @@ -582,7 +583,11 @@ def astype(self, dtype, copy: bool = True): # We handle Period[T] -> Period[U] # Our parent handles everything else. dtype = pandas_dtype(dtype) - + if is_dtype_equal(dtype, self._dtype): + if not copy: + return self + elif copy: + return self.copy() if is_period_dtype(dtype): return self.asfreq(dtype.freq) return super().astype(dtype, copy=copy) diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index c88af77ea6189..528d78a5414ea 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -1063,6 +1063,11 @@ def astype(self, dtype=None, copy=True): IntIndex Indices: array([2, 3], dtype=int32) """ + if is_dtype_equal(dtype, self._dtype): + if not copy: + return self + elif copy: + return self.copy() dtype = self.dtype.update_dtype(dtype) subtype = dtype._subtype_with_str # TODO copy=False is broken for astype_nansafe with int -> float, so cannot diff --git a/pandas/tests/extension/base/casting.py b/pandas/tests/extension/base/casting.py index 3aaf040a4279b..039b42210224e 100644 --- a/pandas/tests/extension/base/casting.py +++ b/pandas/tests/extension/base/casting.py @@ -1,4 +1,5 @@ import numpy as np +import pytest import pandas as pd from pandas.core.internals import ObjectBlock @@ -56,3 +57,11 @@ def test_astype_empty_dataframe(self, dtype): df = pd.DataFrame() result = df.astype(dtype) self.assert_frame_equal(result, df) + + @pytest.mark.parametrize("copy", [True, False]) + def test_astype_own_type(self, data, copy): + # ensure that astype returns the original object for equal dtype and copy=False + # https://github.com/pandas-dev/pandas/issues/28488 + result = data.astype(data.dtype, copy=copy) + assert (result is data) is (not copy) + self.assert_extension_array_equal(result, data) diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 9147360e71c73..2895f33d5c887 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -7,7 +7,7 @@ import numpy as np from pandas.core.dtypes.base import ExtensionDtype -from pandas.core.dtypes.common import pandas_dtype +from pandas.core.dtypes.common import is_dtype_equal, pandas_dtype import pandas as pd from pandas.api.extensions import no_default, register_extension_dtype @@ -131,9 +131,12 @@ def copy(self): return type(self)(self._data.copy()) def astype(self, dtype, copy=True): + if is_dtype_equal(dtype, self._dtype): + if not copy: + return self dtype = pandas_dtype(dtype) if isinstance(dtype, type(self.dtype)): - return type(self)(self._data, context=dtype.context) + return type(self)(self._data, copy=copy, context=dtype.context) return super().astype(dtype, copy=copy) diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index bbfaacae1b444..c4afcd7a536df 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -177,7 +177,7 @@ def test_take_series(self, data): def test_loc_iloc_frame_single_dtype(self, data, request): npdtype = data.dtype.numpy_dtype - if npdtype == object or npdtype == np.float64: + if npdtype == object: # GH#33125 mark = pytest.mark.xfail( reason="GH#33125 astype doesn't recognize data.dtype" @@ -191,14 +191,6 @@ class TestGroupby(BaseNumPyTests, base.BaseGroupbyTests): def test_groupby_extension_apply( self, data_for_grouping, groupby_apply_op, request ): - # ValueError: Names should be list-like for a MultiIndex - a = "a" - is_identity = groupby_apply_op(a) is a - if data_for_grouping.dtype.numpy_dtype == np.float64 and is_identity: - mark = pytest.mark.xfail( - reason="GH#33125 astype doesn't recognize data.dtype" - ) - request.node.add_marker(mark) super().test_groupby_extension_apply(data_for_grouping, groupby_apply_op) @@ -306,11 +298,7 @@ def test_arith_series_with_array(self, data, all_arithmetic_operators): class TestPrinting(BaseNumPyTests, base.BasePrintingTests): - @pytest.mark.xfail( - reason="GH#33125 PandasArray.astype does not recognize PandasDtype" - ) - def test_series_repr(self, data): - super().test_series_repr(data) + pass @skip_nested
- [] closes #28488 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` n.b. I'm not certain. I get no output on the command line when I run this command. - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35116
2020-07-03T19:58:22Z
2020-09-22T13:41:25Z
2020-09-22T13:41:25Z
2020-09-22T13:41:46Z
CI: suppress external warning
diff --git a/pandas/tests/util/test_show_versions.py b/pandas/tests/util/test_show_versions.py index e36ea662fac8b..6b52a6d3613d3 100644 --- a/pandas/tests/util/test_show_versions.py +++ b/pandas/tests/util/test_show_versions.py @@ -5,6 +5,7 @@ import pandas as pd +@pytest.mark.filterwarnings("ignore:Setuptools is replacing distutils:UserWarning") @pytest.mark.filterwarnings( # openpyxl "ignore:defusedxml.lxml is no longer supported:DeprecationWarning"
https://api.github.com/repos/pandas-dev/pandas/pulls/35115
2020-07-03T19:40:30Z
2020-07-04T17:06:36Z
null
2020-07-04T17:06:43Z
BUG: get_loc with time object matching NaT micros
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 9bd4ddbb624d9..95a9a331e7f6b 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -976,6 +976,7 @@ Indexing - Bug in :meth:`DataFrame.loc` with dictionary of values changes columns with dtype of ``int`` to ``float`` (:issue:`34573`) - Bug in :meth:`Series.loc` when used with a :class:`MultiIndex` would raise an IndexingError when accessing a None value (:issue:`34318`) - Bug in :meth:`DataFrame.reset_index` and :meth:`Series.reset_index` would not preserve data types on an empty :class:`DataFrame` or :class:`Series` with a :class:`MultiIndex` (:issue:`19602`) +- Bug in :class:`Series` and :class:`DataFrame` indexing with a ``time`` key on a :class:`DatetimeIndex` with ``NaT`` entries (:issue:`35114`) Missing ^^^^^^^ diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index 126deb67e4189..582191838b648 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -15,7 +15,6 @@ from pandas._libs.tslibs.ccalendar import ( get_locale_names, MONTHS_FULL, DAYS_FULL, ) from pandas._libs.tslibs.ccalendar cimport ( - DAY_NANOS, get_days_in_month, is_leapyear, dayofweek, get_week_of_year, get_day_of_year, get_iso_calendar, iso_calendar_t, month_offset, @@ -26,27 +25,6 @@ from pandas._libs.tslibs.np_datetime cimport ( from pandas._libs.tslibs.nattype cimport NPY_NAT -def get_time_micros(const int64_t[:] dtindex): - """ - Return the number of microseconds in the time component of a - nanosecond timestamp. - - Parameters - ---------- - dtindex : ndarray[int64_t] - - Returns - ------- - micros : ndarray[int64_t] - """ - cdef: - ndarray[int64_t] micros - - micros = np.mod(dtindex, DAY_NANOS, dtype=np.int64) - micros //= 1000 - return micros - - @cython.wraparound(False) @cython.boundscheck(False) def build_field_sarray(const int64_t[:] dtindex): diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 86c6cdf5b15c7..0317d0b93859b 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -6,7 +6,7 @@ import numpy as np from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib -from pandas._libs.tslibs import Resolution, fields, parsing, timezones, to_offset +from pandas._libs.tslibs import Resolution, parsing, timezones, to_offset from pandas._libs.tslibs.offsets import prefix_mapping from pandas._typing import DtypeObj, Label from pandas.errors import InvalidIndexError @@ -86,7 +86,6 @@ def _new_DatetimeIndex(cls, d): "tzinfo", "dtype", "to_pydatetime", - "_local_timestamps", "_has_same_tz", "_format_native_types", "date", @@ -380,10 +379,22 @@ def union_many(self, others): # -------------------------------------------------------------------- def _get_time_micros(self): + """ + Return the number of microseconds since midnight. + + Returns + ------- + ndarray[int64_t] + """ values = self.asi8 if self.tz is not None and not timezones.is_utc(self.tz): values = self._data._local_timestamps() - return fields.get_time_micros(values) + + nanos = values % (24 * 3600 * 1_000_000_000) + micros = nanos // 1000 + + micros[self._isnan] = -1 + return micros def to_series(self, keep_tz=lib.no_default, index=None, name=None): """ @@ -1094,6 +1105,6 @@ def bdate_range( ) -def _time_to_micros(time): - seconds = time.hour * 60 * 60 + 60 * time.minute + time.second - return 1000000 * seconds + time.microsecond +def _time_to_micros(time_obj: time) -> int: + seconds = time_obj.hour * 60 * 60 + 60 * time_obj.minute + time_obj.second + return 1_000_000 * seconds + time_obj.microsecond diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index b1faaa2115f55..2678eb89d1112 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -471,6 +471,16 @@ def test_get_loc(self): with pytest.raises(NotImplementedError, match=msg): idx.get_loc(time(12, 30), method="pad") + def test_get_loc_time_nat(self): + # GH#35114 + # Case where key's total microseconds happens to match iNaT % 1e6 // 1000 + tic = time(minute=12, second=43, microsecond=145224) + dti = pd.DatetimeIndex([pd.NaT]) + + loc = dti.get_loc(tic) + expected = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(loc, expected) + def test_get_loc_tz_aware(self): # https://github.com/pandas-dev/pandas/issues/32140 dti = pd.date_range(
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35114
2020-07-03T18:37:22Z
2020-07-07T13:14:29Z
2020-07-07T13:14:29Z
2020-07-07T14:30:16Z
PERF: ints_to_pydatetime
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index f494e74bde55f..cf9dfe4a39b8f 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -15,7 +15,7 @@ PyDateTime_IMPORT cimport numpy as cnp -from numpy cimport float64_t, int64_t, ndarray, uint8_t +from numpy cimport float64_t, int64_t, ndarray, uint8_t, intp_t import numpy as np cnp.import_array() @@ -157,13 +157,15 @@ def ints_to_pydatetime( Py_ssize_t i, n = len(arr) ndarray[int64_t] trans int64_t[:] deltas - Py_ssize_t pos + intp_t[:] pos npy_datetimestruct dts object dt, new_tz str typ - int64_t value, delta, local_value + int64_t value, local_value, delta = NPY_NAT # dummy for delta ndarray[object] result = np.empty(n, dtype=object) object (*func_create)(int64_t, npy_datetimestruct, tzinfo, object, bint) + bint use_utc = False, use_tzlocal = False, use_fixed = False + bint use_pytz = False if box == "date": assert (tz is None), "tz should be None when converting to date" @@ -184,66 +186,45 @@ def ints_to_pydatetime( ) if is_utc(tz) or tz is None: - for i in range(n): - value = arr[i] - if value == NPY_NAT: - result[i] = <object>NaT - else: - dt64_to_dtstruct(value, &dts) - result[i] = func_create(value, dts, tz, freq, fold) + use_utc = True elif is_tzlocal(tz): - for i in range(n): - value = arr[i] - if value == NPY_NAT: - result[i] = <object>NaT - else: - # Python datetime objects do not support nanosecond - # resolution (yet, PEP 564). Need to compute new value - # using the i8 representation. - local_value = tz_convert_utc_to_tzlocal(value, tz) - dt64_to_dtstruct(local_value, &dts) - result[i] = func_create(value, dts, tz, freq, fold) + use_tzlocal = True else: trans, deltas, typ = get_dst_info(tz) - - if typ not in ['pytz', 'dateutil']: + if typ not in ["pytz", "dateutil"]: # static/fixed; in this case we know that len(delta) == 1 + use_fixed = True delta = deltas[0] - for i in range(n): - value = arr[i] - if value == NPY_NAT: - result[i] = <object>NaT - else: - # Adjust datetime64 timestamp, recompute datetimestruct - dt64_to_dtstruct(value + delta, &dts) - result[i] = func_create(value, dts, tz, freq, fold) + else: + pos = trans.searchsorted(arr, side="right") - 1 + use_pytz = typ == "pytz" - elif typ == 'dateutil': - # no zone-name change for dateutil tzs - dst etc - # represented in single object. - for i in range(n): - value = arr[i] - if value == NPY_NAT: - result[i] = <object>NaT - else: - # Adjust datetime64 timestamp, recompute datetimestruct - pos = trans.searchsorted(value, side='right') - 1 - dt64_to_dtstruct(value + deltas[pos], &dts) - result[i] = func_create(value, dts, tz, freq, fold) + for i in range(n): + new_tz = tz + value = arr[i] + + if value == NPY_NAT: + result[i] = <object>NaT else: - # pytz - for i in range(n): - value = arr[i] - if value == NPY_NAT: - result[i] = <object>NaT - else: - # Adjust datetime64 timestamp, recompute datetimestruct - pos = trans.searchsorted(value, side='right') - 1 - # find right representation of dst etc in pytz timezone - new_tz = tz._tzinfos[tz._transition_info[pos]] + if use_utc: + local_value = value + elif use_tzlocal: + local_value = tz_convert_utc_to_tzlocal(value, tz) + elif use_fixed: + local_value = value + delta + elif not use_pytz: + # i.e. dateutil + # no zone-name change for dateutil tzs - dst etc + # represented in single object. + local_value = value + deltas[pos[i]] + else: + # pytz + # find right representation of dst etc in pytz timezone + new_tz = tz._tzinfos[tz._transition_info[pos[i]]] + local_value = value + deltas[pos[i]] - dt64_to_dtstruct(value + deltas[pos], &dts) - result[i] = func_create(value, dts, new_tz, freq, fold) + dt64_to_dtstruct(local_value, &dts) + result[i] = func_create(value, dts, new_tz, freq, fold) return result
This refactors ints_to_pydatetime to use a much more concise pattern (similar to #35077 but without the helper function refactored out) that I intend to move all of the ~7 functions using get_dst_info to use. In the process, we are slower on very small arrays and faster on bigger arrays, which I think is a good trade: ``` % asv continuous -E virtualenv -f 1.01 master HEAD -b time_ints_to_pydatetime [...] before after ratio [a4e19fa5] [2492aeb4] <master> <ref-ints_to_pydatetime-3> + 3.95±0.09μs 8.22±0.5μs 2.08 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 0, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) + 4.80±0.2μs 9.53±0.5μs 1.99 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 0, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) + 5.45±0.3μs 9.01±0.2μs 1.65 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('time', 0, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) + 5.31±0.6μs 8.31±0.3μs 1.57 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('datetime', 0, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) + 6.08±1μs 8.84±0.2μs 1.45 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('datetime', 0, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) + 7.00±0.3μs 10.0±0.3μs 1.44 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 1, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) + 7.17±0.1μs 10.3±0.3μs 1.43 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 1, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) + 7.47±0.1μs 9.77±0.2μs 1.31 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('time', 1, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) + 7.08±0.2μs 8.46±0.5μs 1.20 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('time', 1, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) - 10.7±0.6μs 9.48±0.3μs 0.88 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('time', 0, datetime.timezone(datetime.timedelta(seconds=3600))) - 3.38±0.02μs 2.89±0.06μs 0.85 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('date', 0, None) - 74.3±1μs 56.3±1μs 0.76 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 100, datetime.timezone.utc) - 73.4±4μs 54.7±2μs 0.74 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 100, None) - 20.7±3ms 9.31±2ms 0.45 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 10000, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) - 15.4±0.2ms 6.23±1ms 0.40 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('datetime', 10000, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) - 1.75±0.03s 699±5ms 0.40 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 1000000, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) - 1.56±0.05s 614±20ms 0.39 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('datetime', 1000000, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) - 1.65±0.01s 650±10ms 0.39 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 1000000, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) - 156±10μs 57.3±9μs 0.37 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('datetime', 100, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) - 16.8±1ms 5.95±0.2ms 0.36 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 10000, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) - 164±7μs 58.3±0.8μs 0.36 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('datetime', 100, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) - 14.8±0.1ms 5.14±0.5ms 0.35 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('datetime', 10000, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) - 1.42±0.02s 491±20ms 0.34 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('datetime', 1000000, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) - 169±6μs 56.0±3μs 0.33 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('time', 100, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) - 193±30μs 63.1±0.9μs 0.33 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 100, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) - 229±30μs 73.7±3μs 0.32 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('timestamp', 100, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) - 1.65±0.06s 505±20ms 0.31 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('time', 1000000, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) - 159±3μs 46.1±2μs 0.29 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('time', 100, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) - 16.0±1ms 4.64±0.1ms 0.29 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('time', 10000, <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>) - 15.2±0.2ms 3.78±0.2ms 0.25 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('time', 10000, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) - 1.65±0.1s 408±20ms 0.25 tslibs.tslib.TimeIntsToPydatetime.time_ints_to_pydatetime('time', 1000000, tzfile('/usr/share/zoneinfo/Asia/Tokyo')) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/35113
2020-07-03T17:18:38Z
2020-07-06T22:59:08Z
2020-07-06T22:59:08Z
2020-07-07T00:15:07Z
BUG: Mixed DataFrame with Extension Array incorrect aggregation
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 8f3a599bf107c..9c58c01f833a3 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -547,7 +547,9 @@ def _binary_op_method_timedeltalike(op, name): try: other = Timedelta(other) - except ValueError: + except (ValueError, SystemError): + # catch SystemError to workaround NumPy issue + # https://github.com/numpy/numpy/issues/15502 # failed to parse as timedelta return NotImplemented diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 8cef685933863..8f147d067cc84 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -205,10 +205,10 @@ def integer_op_not_supported(obj): # GH#30886 using an fstring raises SystemError int_addsub_msg = ( - f"Addition/subtraction of integers and integer-arrays with {cls} is " + "Addition/subtraction of integers and integer-arrays with {cls} is " "no longer supported. Instead of adding/subtracting `n`, " "use `n * obj.freq`" - ) + ).format(cls=cls) return TypeError(int_addsub_msg) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 3d2200cb45c6e..40fb2432d81bc 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8545,43 +8545,35 @@ def blk_func(values): out[:] = coerce_to_dtypes(out.values, df.dtypes) return out - if not self._is_homogeneous_type: - # try to avoid self.values call - - if filter_type is None and axis == 0 and len(self) > 0: - # operate column-wise - - # numeric_only must be None here, as other cases caught above - # require len(self) > 0 bc frame_apply messes up empty prod/sum - - # this can end up with a non-reduction - # but not always. if the types are mixed - # with datelike then need to make sure a series - - # we only end up here if we have not specified - # numeric_only and yet we have tried a - # column-by-column reduction, where we have mixed type. - # So let's just do what we can - from pandas.core.apply import frame_apply - - opa = frame_apply( - self, func=f, result_type="expand", ignore_failures=True - ) - result = opa.get_result() - if result.ndim == self.ndim: - result = result.iloc[0].rename(None) - return result - if numeric_only is None: data = self values = data.values - try: result = f(values) except TypeError: # e.g. in nanops trying to convert strs to float + # try by-column first + if filter_type is None and axis == 0: + # this can end up with a non-reduction + # but not always. if the types are mixed + # with datelike then need to make sure a series + + # we only end up here if we have not specified + # numeric_only and yet we have tried a + # column-by-column reduction, where we have mixed type. + # So let's just do what we can + from pandas.core.apply import frame_apply + + opa = frame_apply( + self, func=f, result_type="expand", ignore_failures=True + ) + result = opa.get_result() + if result.ndim == self.ndim: + result = result.iloc[0] + return result + # TODO: why doesnt axis matter here? data = _get_data(axis_matters=False) labels = data._get_agg_axis(axis) @@ -8589,7 +8581,6 @@ def blk_func(values): values = data.values with np.errstate(all="ignore"): result = f(values) - else: if numeric_only: data = _get_data(axis_matters=True) diff --git a/pandas/tests/arrays/integer/test_function.py b/pandas/tests/arrays/integer/test_function.py index 44c3077228e80..c584fb9f704b8 100644 --- a/pandas/tests/arrays/integer/test_function.py +++ b/pandas/tests/arrays/integer/test_function.py @@ -133,6 +133,15 @@ def test_integer_array_numpy_sum(values, expected): assert result == expected +def test_mixed_frame_with_integer_sum(): + # https://github.com/pandas-dev/pandas/issues/34520 + df = pd.DataFrame([["a", 1]], columns=list("ab")) + df = df.astype({"b": "Int64"}) + result = df.sum() + expected = pd.Series(["a", 1], index=["a", "b"]) + tm.assert_series_equal(result, expected) + + # TODO(jreback) - these need testing / are broken # shift diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index db8bb5ca3c437..e9af883a717b5 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -351,9 +351,7 @@ def kurt(x): "sum", np.sum, float_frame_with_na, skipna_alternative=np.nansum ) assert_stat_op_calc("mean", np.mean, float_frame_with_na, check_dates=True) - assert_stat_op_calc( - "product", np.prod, float_frame_with_na, skipna_alternative=np.nanprod - ) + assert_stat_op_calc("product", np.prod, float_frame_with_na) assert_stat_op_calc("mad", mad, float_frame_with_na) assert_stat_op_calc("var", var, float_frame_with_na)
- [ ] closes #34520 by reverting #32950
https://api.github.com/repos/pandas-dev/pandas/pulls/35112
2020-07-03T14:51:57Z
2020-07-10T09:14:03Z
null
2020-07-10T09:14:03Z
BUG: reset_index is passing a bad dtype to NumPy
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b6993e9ed851a..87041341ac3a6 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -75,6 +75,7 @@ from pandas.core.dtypes.cast import ( cast_scalar_to_array, coerce_to_dtypes, + construct_1d_arraylike_from_scalar, find_common_type, infer_dtype_from_scalar, invalidate_string_dtypes, @@ -109,7 +110,7 @@ needs_i8_conversion, pandas_dtype, ) -from pandas.core.dtypes.missing import isna, notna +from pandas.core.dtypes.missing import isna, na_value_for_dtype, notna from pandas.core import algorithms, common as com, nanops, ops from pandas.core.accessor import CachedAccessor @@ -4731,8 +4732,11 @@ def _maybe_casted_values(index, labels=None): # we can have situations where the whole mask is -1, # meaning there is nothing found in labels, so make all nan's if mask.all(): - values = np.empty(len(mask), dtype=index.dtype) - values.fill(np.nan) + dtype = index.dtype + fill_value = na_value_for_dtype(dtype) + values = construct_1d_arraylike_from_scalar( + fill_value, len(mask), dtype + ) else: values = values.take(labels) diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index 79442acccb326..cf0bbe144caa5 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -3,6 +3,7 @@ import numpy as np import pytest +import pandas as pd from pandas import ( DataFrame, Index, @@ -299,9 +300,19 @@ def test_reset_index_range(self): tm.assert_frame_equal(result, expected) -def test_reset_index_dtypes_on_empty_frame_with_multiindex(): +@pytest.mark.parametrize( + "array, dtype", + [ + (["a", "b"], object), + ( + pd.period_range("12-1-2000", periods=2, freq="Q-DEC"), + pd.PeriodDtype(freq="Q-DEC"), + ), + ], +) +def test_reset_index_dtypes_on_empty_frame_with_multiindex(array, dtype): # GH 19602 - Preserve dtype on empty DataFrame with MultiIndex - idx = MultiIndex.from_product([[0, 1], [0.5, 1.0], ["a", "b"]]) + idx = MultiIndex.from_product([[0, 1], [0.5, 1.0], array]) result = DataFrame(index=idx)[:0].reset_index().dtypes - expected = Series({"level_0": np.int64, "level_1": np.float64, "level_2": object}) + expected = Series({"level_0": np.int64, "level_1": np.float64, "level_2": dtype}) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/methods/test_reset_index.py b/pandas/tests/series/methods/test_reset_index.py index a11590d42552d..597b43a370ef5 100644 --- a/pandas/tests/series/methods/test_reset_index.py +++ b/pandas/tests/series/methods/test_reset_index.py @@ -1,6 +1,7 @@ import numpy as np import pytest +import pandas as pd from pandas import DataFrame, Index, MultiIndex, RangeIndex, Series import pandas._testing as tm @@ -110,11 +111,21 @@ def test_reset_index_drop_errors(self): s.reset_index("wrong", drop=True) -def test_reset_index_dtypes_on_empty_series_with_multiindex(): +@pytest.mark.parametrize( + "array, dtype", + [ + (["a", "b"], object), + ( + pd.period_range("12-1-2000", periods=2, freq="Q-DEC"), + pd.PeriodDtype(freq="Q-DEC"), + ), + ], +) +def test_reset_index_dtypes_on_empty_series_with_multiindex(array, dtype): # GH 19602 - Preserve dtype on empty Series with MultiIndex - idx = MultiIndex.from_product([[0, 1], [0.5, 1.0], ["a", "b"]]) + idx = MultiIndex.from_product([[0, 1], [0.5, 1.0], array]) result = Series(dtype=object, index=idx)[:0].reset_index().dtypes expected = Series( - {"level_0": np.int64, "level_1": np.float64, "level_2": object, 0: object} + {"level_0": np.int64, "level_1": np.float64, "level_2": dtype, 0: object} ) tm.assert_series_equal(result, expected)
- [ ] closes #35095 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35111
2020-07-03T13:16:44Z
2020-07-06T20:55:03Z
2020-07-06T20:55:03Z
2020-07-07T08:26:07Z
DOC: Fix code formatting and typos in Series.tz_localize
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a66cade3b81b0..d892e2487b31c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9580,8 +9580,9 @@ def tz_localize( dtype: int64 If the DST transition causes nonexistent times, you can shift these - dates forward or backwards with a timedelta object or `'shift_forward'` - or `'shift_backwards'`. + dates forward or backward with a timedelta object or `'shift_forward'` + or `'shift_backward'`. + >>> s = pd.Series(range(2), ... index=pd.DatetimeIndex(['2015-03-29 02:30:00', ... '2015-03-29 03:30:00']))
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry The missing line feed prevented the example from being formatted as code sample.
https://api.github.com/repos/pandas-dev/pandas/pulls/35110
2020-07-03T11:41:52Z
2020-07-03T14:14:19Z
2020-07-03T14:14:19Z
2020-07-03T16:21:10Z
REF: implement tz_localize_to_utc_single
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index f494e74bde55f..e02ad6017efff 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -46,7 +46,6 @@ from pandas._libs.tslibs.timezones cimport ( get_dst_info, is_utc, is_tzlocal, - utc_pytz as UTC, ) from pandas._libs.tslibs.conversion cimport ( _TSObject, @@ -67,8 +66,8 @@ from pandas._libs.tslibs.timestamps cimport create_timestamp_from_ts, _Timestamp from pandas._libs.tslibs.timestamps import Timestamp from pandas._libs.tslibs.tzconversion cimport ( - tz_convert_single, tz_convert_utc_to_tzlocal, + tz_localize_to_utc_single, ) # Note: this is the only non-tslibs intra-pandas dependency here @@ -269,7 +268,7 @@ def _test_parse_iso8601(ts: str): check_dts_bounds(&obj.dts) if out_local == 1: obj.tzinfo = pytz.FixedOffset(out_tzoffset) - obj.value = tz_convert_single(obj.value, obj.tzinfo, UTC) + obj.value = tz_localize_to_utc_single(obj.value, obj.tzinfo) return Timestamp(obj.value, tz=obj.tzinfo) else: return Timestamp(obj.value) @@ -727,7 +726,7 @@ cpdef array_to_datetime( # dateutil.tz.tzoffset objects out_tzoffset_vals.add(out_tzoffset * 60.) tz = pytz.FixedOffset(out_tzoffset) - value = tz_convert_single(value, tz, UTC) + value = tz_localize_to_utc_single(value, tz) out_local = 0 out_tzoffset = 0 else: diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 95500f66db156..67931010ca873 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -39,10 +39,9 @@ from pandas._libs.tslibs.nattype cimport ( c_nat_strings as nat_strings, ) -from pandas._libs.tslibs.tzconversion import tz_localize_to_utc from pandas._libs.tslibs.tzconversion cimport ( tz_convert_utc_to_tzlocal, - tz_convert_single, + tz_localize_to_utc_single, ) # ---------------------------------------------------------------------- @@ -470,7 +469,7 @@ cdef _TSObject _create_tsobject_tz_using_offset(npy_datetimestruct dts, value = dtstruct_to_dt64(&dts) obj.dts = dts obj.tzinfo = pytz.FixedOffset(tzoffset) - obj.value = tz_convert_single(value, obj.tzinfo, UTC) + obj.value = tz_localize_to_utc_single(value, obj.tzinfo) if tz is None: check_overflows(obj) return obj @@ -555,8 +554,8 @@ cdef _TSObject _convert_str_to_tsobject(object ts, tzinfo tz, object unit, ts = dtstruct_to_dt64(&dts) if tz is not None: # shift for _localize_tso - ts = tz_localize_to_utc(np.array([ts], dtype='i8'), tz, - ambiguous='raise')[0] + ts = tz_localize_to_utc_single(ts, tz, + ambiguous="raise") except OutOfBoundsDatetime: # GH#19382 for just-barely-OutOfBounds falling back to dateutil diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index e104b722ea119..9d32acf4fef8f 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -58,8 +58,10 @@ from pandas._libs.tslibs.timezones cimport ( is_utc, maybe_get_tz, treat_tz_as_pytz, utc_pytz as UTC, get_timezone, tz_compare, ) -from pandas._libs.tslibs.tzconversion cimport tz_convert_single -from pandas._libs.tslibs.tzconversion import tz_localize_to_utc +from pandas._libs.tslibs.tzconversion cimport ( + tz_convert_single, + tz_localize_to_utc_single, +) # ---------------------------------------------------------------------- # Constants @@ -1299,9 +1301,9 @@ default 'raise' tz = maybe_get_tz(tz) if not isinstance(ambiguous, str): ambiguous = [ambiguous] - value = tz_localize_to_utc(np.array([self.value], dtype='i8'), tz, - ambiguous=ambiguous, - nonexistent=nonexistent)[0] + value = tz_localize_to_utc_single(self.value, tz, + ambiguous=ambiguous, + nonexistent=nonexistent) return Timestamp(value, tz=tz, freq=self.freq) else: if tz is None: diff --git a/pandas/_libs/tslibs/tzconversion.pxd b/pandas/_libs/tslibs/tzconversion.pxd index 7f445d7549f45..7d102868256de 100644 --- a/pandas/_libs/tslibs/tzconversion.pxd +++ b/pandas/_libs/tslibs/tzconversion.pxd @@ -4,3 +4,6 @@ from numpy cimport int64_t cdef int64_t tz_convert_utc_to_tzlocal(int64_t utc_val, tzinfo tz, bint* fold=*) cpdef int64_t tz_convert_single(int64_t val, tzinfo tz1, tzinfo tz2) +cdef int64_t tz_localize_to_utc_single( + int64_t val, tzinfo tz, object ambiguous=*, object nonexistent=* +) except? -1 diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index d1d6bc40ef288..bbf1000f028f9 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -20,10 +20,48 @@ from pandas._libs.tslibs.ccalendar cimport DAY_NANOS, HOUR_NANOS from pandas._libs.tslibs.nattype cimport NPY_NAT from pandas._libs.tslibs.np_datetime cimport ( npy_datetimestruct, dt64_to_dtstruct) -from pandas._libs.tslibs.timezones cimport get_dst_info, is_tzlocal, is_utc +from pandas._libs.tslibs.timezones cimport ( + get_dst_info, + get_utcoffset, + is_fixed_offset, + is_tzlocal, + is_utc, +) + + +cdef int64_t tz_localize_to_utc_single( + int64_t val, tzinfo tz, object ambiguous=None, object nonexistent=None, +) except? -1: + """See tz_localize_to_utc.__doc__""" + cdef: + int64_t delta + int64_t[:] deltas + + if val == NPY_NAT: + return val + + elif is_utc(tz) or tz is None: + return val + + elif is_tzlocal(tz): + return _tz_convert_tzlocal_utc(val, tz, to_utc=True) + + elif is_fixed_offset(tz): + # TODO: in this case we should be able to use get_utcoffset, + # that returns None for e.g. 'dateutil//usr/share/zoneinfo/Etc/GMT-9' + _, deltas, _ = get_dst_info(tz) + delta = deltas[0] + return val - delta + + else: + return tz_localize_to_utc( + np.array([val], dtype="i8"), + tz, + ambiguous=ambiguous, + nonexistent=nonexistent, + )[0] -# TODO: cdef scalar version to call from convert_str_to_tsobject @cython.boundscheck(False) @cython.wraparound(False) def tz_localize_to_utc(ndarray[int64_t] vals, tzinfo tz, object ambiguous=None,
In addition to implementing `tz_localize_to_utc_single`, this replaces all (but one, xref #35102) usages of tz_convert_single that have UTC as the target timezone. In conjunction with 35102, this will allow us to remove the second kwarg altogether, similar to #35104.
https://api.github.com/repos/pandas-dev/pandas/pulls/35108
2020-07-03T03:59:31Z
2020-07-07T00:14:26Z
2020-07-07T00:14:26Z
2020-07-07T01:08:21Z
TYP: get_utcoffset
diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd index 0784b090b3edb..f51ee41cb99a6 100644 --- a/pandas/_libs/tslibs/timezones.pxd +++ b/pandas/_libs/tslibs/timezones.pxd @@ -1,4 +1,4 @@ -from cpython.datetime cimport tzinfo +from cpython.datetime cimport datetime, timedelta, tzinfo cdef tzinfo utc_pytz @@ -11,7 +11,7 @@ cpdef bint tz_compare(tzinfo start, tzinfo end) cpdef object get_timezone(tzinfo tz) cpdef object maybe_get_tz(object tz) -cdef get_utcoffset(tzinfo tz, obj) +cdef timedelta get_utcoffset(tzinfo tz, datetime obj) cdef bint is_fixed_offset(tzinfo tz) cdef object get_dst_info(tzinfo tz) diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index 0460591048801..3b2104f75956a 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -1,5 +1,5 @@ from datetime import timezone -from cpython.datetime cimport datetime, tzinfo +from cpython.datetime cimport datetime, timedelta, tzinfo # dateutil compat from dateutil.tz import ( @@ -153,7 +153,7 @@ cdef inline object tz_cache_key(tzinfo tz): # UTC Offsets -cdef get_utcoffset(tzinfo tz, obj): +cdef timedelta get_utcoffset(tzinfo tz, datetime obj): try: return tz._utcoffset except AttributeError: diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 64e8582baaa98..fcfbaa4ac2a1c 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -3,7 +3,6 @@ import warnings import numpy as np -from pytz import utc from pandas._libs import lib, tslib from pandas._libs.tslibs import ( @@ -725,7 +724,7 @@ def _local_timestamps(self): This is used to calculate time-of-day information as if the timestamps were timezone-naive. """ - return tzconversion.tz_convert(self.asi8, utc, self.tz) + return tzconversion.tz_convert(self.asi8, timezones.UTC, self.tz) def tz_convert(self, tz): """ diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 7516d9748c18f..f94c8ef6550a5 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -4,7 +4,7 @@ import numpy as np from pandas._libs.algos import unique_deltas -from pandas._libs.tslibs import Timestamp +from pandas._libs.tslibs import Timestamp, tzconversion from pandas._libs.tslibs.ccalendar import ( DAYS, MONTH_ALIASES, @@ -22,7 +22,6 @@ from pandas._libs.tslibs.parsing import get_rule_month from pandas._libs.tslibs.resolution import month_position_check from pandas._libs.tslibs.timezones import UTC -from pandas._libs.tslibs.tzconversion import tz_convert from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import ( @@ -199,7 +198,7 @@ def __init__(self, index, warn: bool = True): # the timezone so they are in local time if hasattr(index, "tz"): if index.tz is not None: - self.i8values = tz_convert(self.i8values, UTC, index.tz) + self.i8values = tzconversion.tz_convert(self.i8values, UTC, index.tz) self.warn = warn
https://api.github.com/repos/pandas-dev/pandas/pulls/35107
2020-07-03T00:15:24Z
2020-07-06T22:51:44Z
2020-07-06T22:51:44Z
2020-07-06T23:20:04Z
PERF: tz_localize(None) from dst, asvs
diff --git a/asv_bench/benchmarks/tslibs/tz_convert.py b/asv_bench/benchmarks/tslibs/tz_convert.py new file mode 100644 index 0000000000000..2a1f559bdf6d4 --- /dev/null +++ b/asv_bench/benchmarks/tslibs/tz_convert.py @@ -0,0 +1,30 @@ +import numpy as np +from pytz import UTC + +from pandas._libs.tslibs.tzconversion import tz_convert, tz_localize_to_utc + +from .tslib import _sizes, _tzs + + +class TimeTZConvert: + params = ( + _sizes, + [x for x in _tzs if x is not None], + ) + param_names = ["size", "tz"] + + def setup(self, size, tz): + arr = np.random.randint(0, 10, size=size, dtype="i8") + self.i8data = arr + + def time_tz_convert_from_utc(self, size, tz): + # effectively: + # dti = DatetimeIndex(self.i8data, tz=tz) + # dti.tz_localize(None) + tz_convert(self.i8data, UTC, tz) + + def time_tz_localize_to_utc(self, size, tz): + # effectively: + # dti = DatetimeIndex(self.i8data) + # dti.tz_localize(tz, ambiguous="NaT", nonexistent="NaT") + tz_localize_to_utc(self.i8data, tz, ambiguous="NaT", nonexistent="NaT") diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index d1d6bc40ef288..9bd935940dc7b 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -551,29 +551,48 @@ cdef int64_t[:] _tz_convert_dst( int64_t[:] result = np.empty(n, dtype=np.int64) ndarray[int64_t] trans int64_t[:] deltas - int64_t v + int64_t v, delta + str typ # tz is assumed _not_ to be tzlocal; that should go # through _tz_convert_tzlocal_utc - trans, deltas, _ = get_dst_info(tz) - if not to_utc: - # We add `offset` below instead of subtracting it - deltas = -1 * np.array(deltas, dtype='i8') + trans, deltas, typ = get_dst_info(tz) - # Previously, this search was done pointwise to try and benefit - # from getting to skip searches for iNaTs. However, it seems call - # overhead dominates the search time so doing it once in bulk - # is substantially faster (GH#24603) - pos = trans.searchsorted(values, side='right') - 1 + if typ not in ["pytz", "dateutil"]: + # FixedOffset, we know len(deltas) == 1 + delta = deltas[0] - for i in range(n): - v = values[i] - if v == NPY_NAT: - result[i] = v - else: - if pos[i] < 0: - raise ValueError('First time before start of DST info') - result[i] = v - deltas[pos[i]] + for i in range(n): + v = values[i] + if v == NPY_NAT: + result[i] = v + else: + if to_utc: + result[i] = v - delta + else: + result[i] = v + delta + + else: + # Previously, this search was done pointwise to try and benefit + # from getting to skip searches for iNaTs. However, it seems call + # overhead dominates the search time so doing it once in bulk + # is substantially faster (GH#24603) + pos = trans.searchsorted(values, side="right") - 1 + + for i in range(n): + v = values[i] + if v == NPY_NAT: + result[i] = v + else: + if pos[i] < 0: + # TODO: How is this reached? Should we be checking for + # it elsewhere? + raise ValueError("First time before start of DST info") + + if to_utc: + result[i] = v - deltas[pos[i]] + else: + result[i] = v + deltas[pos[i]] return result
This makes tz_convert_dst follow the same pattern we use elsewhere, and brings a perf improvement along with it. ``` In [2]: dti = pd.date_range("2016-01-01", periods=10000, freq="S", tz="US/Pacific") In [3]: %timeit dti.tz_localize(None) 89.3 µs ± 627 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- PR 100 µs ± 6.36 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- master ``` The boost comes from not doing a copy, so makes a bigger difference in the scalar case than the array case. ``` In [5]: ts = dti[0] In [6]: %timeit ts.tz_localize(None) 12.4 µs ± 188 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) # <-- PR 16.1 µs ± 215 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) # <-- master ``` The improvement is much bigger for fixed offsets: ``` In [9]: tz = pytz.FixedOffset(-60) In [10]: dti2 = dti.tz_convert(tz) In [11]: %timeit dti2.tz_localize(None) 34.8 µs ± 1.09 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- PR 71.8 µs ± 2.99 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- master ```
https://api.github.com/repos/pandas-dev/pandas/pulls/35106
2020-07-03T00:12:40Z
2020-07-07T00:13:27Z
2020-07-07T00:13:27Z
2020-07-07T01:06:58Z
Extension base test
diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index dbce71b77a425..398d4ae56311e 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -376,7 +376,10 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: if isinstance(dtype, BooleanDtype): values, mask = coerce_to_array(self, copy=copy) - return BooleanArray(values, mask, copy=False) + if copy: + return BooleanArray(values, mask, copy=False) + else: + return self elif isinstance(dtype, StringDtype): return dtype.construct_array_type()._from_sequence(self, copy=False) diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index df43b5d6115ba..690f0426ddf57 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -452,6 +452,8 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: # if we are astyping to an existing IntegerDtype we can fastpath if isinstance(dtype, _IntegerDtype): + if dtype is self.dtype and not copy: + return self result = self._data.astype(dtype.numpy_dtype, copy=False) return dtype.construct_array_type()(result, mask=self._mask, copy=False) elif isinstance(dtype, BooleanDtype): diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index f6dfb1f0f1e62..833af105ed629 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -5,7 +5,7 @@ from numpy.lib.mixins import NDArrayOperatorsMixin from pandas._libs import lib -from pandas._typing import Scalar +from pandas._typing import Scalar, ArrayLike from pandas.compat.numpy import function as nv from pandas.util._decorators import doc from pandas.util._validators import validate_fillna_kwargs @@ -277,6 +277,14 @@ def __setitem__(self, key, value) -> None: self._ndarray[key] = value + def astype(self, dtype, copy: bool = True) -> ArrayLike: + if not copy and dtype == self._dtype: + return self + elif dtype == self._dtype: + return self.copy() + else: + return super().astype(dtype, copy) + def isna(self) -> np.ndarray: return isna(self._ndarray) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 4b4df3445be4e..54fe713516d7f 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -575,7 +575,11 @@ def astype(self, dtype, copy: bool = True): # We handle Period[T] -> Period[U] # Our parent handles everything else. dtype = pandas_dtype(dtype) - + if dtype == self._dtype: + if copy: + return self.copy() + else: + return self if is_period_dtype(dtype): return self.asfreq(dtype.freq) return super().astype(dtype, copy=copy) diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 4996a10002c63..f307ebe521aef 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -1061,6 +1061,10 @@ def astype(self, dtype=None, copy=True): IntIndex Indices: array([2, 3], dtype=int32) """ + if dtype == self.dtype and copy: + return self.copy() + elif dtype == self.dtype and not copy: + return self dtype = self.dtype.update_dtype(dtype) subtype = dtype._subtype_with_str # TODO copy=False is broken for astype_nansafe with int -> float, so cannot diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index ac501a8afbe09..10d4854bc00d8 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -278,6 +278,10 @@ def fillna(self, value=None, method=None, limit=None): return super().fillna(value, method, limit) def astype(self, dtype, copy=True): + if dtype == self.dtype and copy: + return self.copy() + elif dtype == self.dtype and not copy: + return self dtype = pandas_dtype(dtype) if isinstance(dtype, StringDtype): if copy: diff --git a/pandas/tests/extension/base/casting.py b/pandas/tests/extension/base/casting.py index 3aaf040a4279b..14e9b6f8247eb 100644 --- a/pandas/tests/extension/base/casting.py +++ b/pandas/tests/extension/base/casting.py @@ -1,4 +1,5 @@ import numpy as np +import pytest import pandas as pd from pandas.core.internals import ObjectBlock @@ -56,3 +57,9 @@ def test_astype_empty_dataframe(self, dtype): df = pd.DataFrame() result = df.astype(dtype) self.assert_frame_equal(result, df) + + @pytest.mark.parametrize('copy', [True, False]) + def test_astype_own_type(self, data, copy): + result = data.astype(data.dtype, copy=copy) + assert (result is data) is (not copy) + self.assert_extension_array_equal(result, data) diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 4d5be75ff8200..af3783dbfb63d 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -131,6 +131,10 @@ def copy(self): return type(self)(self._data.copy()) def astype(self, dtype, copy=True): + if not copy and dtype == self._dtype: + return self + elif dtype == self._dtype: + return self.copy() dtype = pandas_dtype(dtype) if isinstance(dtype, type(self.dtype)): return type(self)(self._data, context=dtype.context) diff --git a/pandas/tests/extension/test_string.py b/pandas/tests/extension/test_string.py index 27a157d2127f6..f6c1a826f736b 100644 --- a/pandas/tests/extension/test_string.py +++ b/pandas/tests/extension/test_string.py @@ -95,8 +95,8 @@ def test_value_counts(self, all_data, dropna): return super().test_value_counts(all_data, dropna) -class TestCasting(base.BaseCastingTests): - pass +# class TestCasting(base.BaseCastingTests): +# pass class TestComparisonOps(base.BaseComparisonOpsTests):
- [x] closes #28488 - [x] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry The style is not consistent with guidelines etc, and not at all ready to be merged.
https://api.github.com/repos/pandas-dev/pandas/pulls/35105
2020-07-02T23:40:19Z
2020-07-02T23:42:47Z
null
2020-07-02T23:43:04Z
CLN: tz_convert is always from UTC
diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index d1d6bc40ef288..dc01210f2789f 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -388,8 +388,9 @@ def tz_convert(int64_t[:] vals, tzinfo tz1, tzinfo tz2): bint to_utc = is_utc(tz2) tzinfo tz - # See GH#17734 We should always be converting either from UTC or to UTC - assert is_utc(tz1) or to_utc + # See GH#17734 We should always be converting from UTC; otherwise + # should use tz_localize_to_utc. + assert is_utc(tz1) if len(vals) == 0: return np.array([], dtype=np.int64) diff --git a/pandas/tests/tslibs/test_conversion.py b/pandas/tests/tslibs/test_conversion.py index 3a7e06fb14a5f..5a16fea47e90d 100644 --- a/pandas/tests/tslibs/test_conversion.py +++ b/pandas/tests/tslibs/test_conversion.py @@ -20,33 +20,47 @@ def f(x): tm.assert_numpy_array_equal(result, expected) -def _compare_local_to_utc(tz_didx, utc_didx): +def _compare_local_to_utc(tz_didx, naive_didx): + # Check that tz_localize behaves the same vectorized and pointwise. def f(x): return tzconversion.tz_convert_single(x, tz_didx.tz, UTC) - result = tzconversion.tz_convert(utc_didx.asi8, tz_didx.tz, UTC) - expected = np.vectorize(f)(utc_didx.asi8) + err1 = err2 = None + try: + result = tzconversion.tz_localize_to_utc(naive_didx.asi8, tz_didx.tz) + err1 = None + except Exception as err: + err1 = err - tm.assert_numpy_array_equal(result, expected) + try: + expected = naive_didx.map(lambda x: x.tz_localize(tz_didx.tz)).asi8 + except Exception as err: + err2 = err + + if err1 is not None: + assert type(err1) == type(err2) + else: + assert err2 is None + tm.assert_numpy_array_equal(result, expected) def test_tz_convert_single_matches_tz_convert_hourly(tz_aware_fixture): tz = tz_aware_fixture tz_didx = date_range("2014-03-01", "2015-01-10", freq="H", tz=tz) - utc_didx = date_range("2014-03-01", "2015-01-10", freq="H") + naive_didx = date_range("2014-03-01", "2015-01-10", freq="H") _compare_utc_to_local(tz_didx) - _compare_local_to_utc(tz_didx, utc_didx) + _compare_local_to_utc(tz_didx, naive_didx) @pytest.mark.parametrize("freq", ["D", "A"]) def test_tz_convert_single_matches_tz_convert(tz_aware_fixture, freq): tz = tz_aware_fixture tz_didx = date_range("2000-01-01", "2020-01-01", freq=freq, tz=tz) - utc_didx = date_range("2000-01-01", "2020-01-01", freq=freq) + naive_didx = date_range("2000-01-01", "2020-01-01", freq=freq) _compare_utc_to_local(tz_didx) - _compare_local_to_utc(tz_didx, utc_didx) + _compare_local_to_utc(tz_didx, naive_didx) @pytest.mark.parametrize( @@ -57,9 +71,6 @@ def test_tz_convert_single_matches_tz_convert(tz_aware_fixture, freq): ], ) def test_tz_convert_corner(arr): - result = tzconversion.tz_convert(arr, timezones.maybe_get_tz("US/Eastern"), UTC) - tm.assert_numpy_array_equal(result, arr) - result = tzconversion.tz_convert(arr, UTC, timezones.maybe_get_tz("Asia/Tokyo")) tm.assert_numpy_array_equal(result, arr)
Follow-up can remove the unnecessary arg from tz_convert, possibly rename.
https://api.github.com/repos/pandas-dev/pandas/pulls/35104
2020-07-02T22:42:52Z
2020-07-07T00:12:00Z
2020-07-07T00:11:59Z
2020-07-07T01:05:26Z
TYP: maybe_get_tz
diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd index f51ee41cb99a6..136710003d32a 100644 --- a/pandas/_libs/tslibs/timezones.pxd +++ b/pandas/_libs/tslibs/timezones.pxd @@ -9,7 +9,7 @@ cdef bint treat_tz_as_pytz(tzinfo tz) cpdef bint tz_compare(tzinfo start, tzinfo end) cpdef object get_timezone(tzinfo tz) -cpdef object maybe_get_tz(object tz) +cpdef tzinfo maybe_get_tz(object tz) cdef timedelta get_utcoffset(tzinfo tz, datetime obj) cdef bint is_fixed_offset(tzinfo tz) diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index 3b2104f75956a..a8c785704d8e8 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -84,7 +84,7 @@ cpdef inline object get_timezone(tzinfo tz): return tz -cpdef inline object maybe_get_tz(object tz): +cpdef inline tzinfo maybe_get_tz(object tz): """ (Maybe) Construct a timezone object from a string. If tz is a string, use it to construct a timezone object. Otherwise, just return tz. @@ -102,6 +102,12 @@ cpdef inline object maybe_get_tz(object tz): tz = pytz.timezone(tz) elif is_integer_object(tz): tz = pytz.FixedOffset(tz / 60) + elif isinstance(tz, tzinfo): + pass + elif tz is None: + pass + else: + raise TypeError(type(tz)) return tz diff --git a/pandas/tests/tslibs/test_timezones.py b/pandas/tests/tslibs/test_timezones.py index 03cc8fcb6e904..81b41f567976d 100644 --- a/pandas/tests/tslibs/test_timezones.py +++ b/pandas/tests/tslibs/test_timezones.py @@ -106,3 +106,15 @@ def test_infer_tz_mismatch(infer_setup, ordered): with pytest.raises(AssertionError, match=msg): timezones.infer_tzinfo(*args) + + +def test_maybe_get_tz_invalid_types(): + with pytest.raises(TypeError, match="<class 'float'>"): + timezones.maybe_get_tz(44.0) + + with pytest.raises(TypeError, match="<class 'module'>"): + timezones.maybe_get_tz(pytz) + + msg = "<class 'pandas._libs.tslibs.timestamps.Timestamp'>" + with pytest.raises(TypeError, match=msg): + timezones.maybe_get_tz(Timestamp.now("UTC"))
https://api.github.com/repos/pandas-dev/pandas/pulls/35103
2020-07-02T22:27:09Z
2020-07-08T21:52:29Z
2020-07-08T21:52:29Z
2020-07-08T22:07:15Z
REF: standardize tz_convert_single usage
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index e104b722ea119..426e6e0104f89 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -1379,7 +1379,7 @@ default 'raise' cdef: npy_datetimestruct dts - int64_t value, value_tz + int64_t value object k, v datetime ts_input tzinfo_type tzobj @@ -1388,8 +1388,7 @@ default 'raise' tzobj = self.tzinfo value = self.value if tzobj is not None: - value_tz = tz_convert_single(value, tzobj, UTC) - value += value - value_tz + value = tz_convert_single(value, UTC, tzobj) # setup components dt64_to_dtstruct(value, &dts)
I'm increasingly convinced that we can get all tz_convert/tz_convert_single usages to have tz1=UTC, and everything else should go through tz_localize_to_utc.
https://api.github.com/repos/pandas-dev/pandas/pulls/35102
2020-07-02T21:19:33Z
2020-07-07T00:07:34Z
2020-07-07T00:07:34Z
2020-07-07T01:06:17Z
PERF: Fix quantile perf regression
diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py index bb6c6de441558..fa7201a5188a5 100644 --- a/pandas/util/_validators.py +++ b/pandas/util/_validators.py @@ -371,14 +371,13 @@ def validate_percentile(q: Union[float, Iterable[float]]) -> np.ndarray: ValueError if percentiles are not in given interval([0, 1]). """ q_arr = np.asarray(q) - msg = ( - "percentiles should all be in the interval [0, 1]." - f"Try {q_arr / 100.0} instead." - ) + # Don't change this to an f-string. The string formatting + # is too expensive for cases where we don't need it. + msg = "percentiles should all be in the interval [0, 1]. Try {} instead." if q_arr.ndim == 0: if not 0 <= q_arr <= 1: - raise ValueError(msg) + raise ValueError(msg.format(q_arr / 100.0)) else: if not all(0 <= qs <= 1 for qs in q_arr): - raise ValueError(msg) + raise ValueError(msg.format(q_arr / 100.0)) return q_arr
Closes https://github.com/pandas-dev/pandas/issues/35049 ```pyhon 591 µs ± 29.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) 440 µs ± 22.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/35101
2020-07-02T20:44:16Z
2020-07-03T15:07:32Z
2020-07-03T15:07:32Z
2020-07-03T15:07:43Z
Document Tips for Debugging C Extensions
diff --git a/doc/source/development/debugging_extensions.rst b/doc/source/development/debugging_extensions.rst new file mode 100644 index 0000000000000..358c4036df961 --- /dev/null +++ b/doc/source/development/debugging_extensions.rst @@ -0,0 +1,93 @@ +.. _debugging_c_extensions: + +{{ header }} + +====================== +Debugging C extensions +====================== + +Pandas uses select C extensions for high performance IO operations. In case you need to debug segfaults or general issues with those extensions, the following steps may be helpful. + +First, be sure to compile the extensions with the appropriate flags to generate debug symbols and remove optimizations. This can be achieved as follows: + +.. code-block:: sh + + python setup.py build_ext --inplace -j4 --with-debugging-symbols + +Using a debugger +================ + +Assuming you are on a Unix-like operating system, you can use either lldb or gdb to debug. The choice between either is largely dependent on your compilation toolchain - typically you would use lldb if using clang and gdb if using gcc. For macOS users, please note that ``gcc`` is on modern systems an alias for ``clang``, so if using Xcode you usually opt for lldb. Regardless of which debugger you choose, please refer to your operating systems instructions on how to install. + +After installing a debugger you can create a script that hits the extension module you are looking to debug. For demonstration purposes, let's assume you have a script called ``debug_testing.py`` with the following contents: + +.. code-block:: python + + import pandas as pd + + pd.DataFrame([[1, 2]]).to_json() + +Place the ``debug_testing.py`` script in the project root and launch a Python process under your debugger. If using lldb: + +.. code-block:: sh + + lldb python + +If using gdb: + +.. code-block:: sh + + gdb python + +Before executing our script, let's set a breakpoint in our JSON serializer in its entry function called ``objToJSON``. The lldb syntax would look as follows: + +.. code-block:: sh + + breakpoint set --name objToJSON + +Similarly for gdb: + +.. code-block:: sh + + break objToJSON + +.. note:: + + You may get a warning that this breakpoint cannot be resolved in lldb. gdb may give a similar warning and prompt you to make the breakpoint on a future library load, which you should say yes to. This should only happen on the very first invocation as the module you wish to debug has not yet been loaded into memory. + +Now go ahead and execute your script: + +.. code-block:: sh + + run <the_script>.py + +Code execution will halt at the breakpoint defined or at the occurance of any segfault. LLDB's `GDB to LLDB command map <https://lldb.llvm.org/use/map.html>`_ provides a listing of debugger command that you can execute using either debugger. + +Another option to execute the entire test suite under lldb would be to run the following: + +.. code-block:: sh + + lldb -- python -m pytest + +Or for gdb + +.. code-block:: sh + + gdb --args python -m pytest + +Once the process launches, simply type ``run`` and the test suite will begin, stopping at any segmentation fault that may occur. + +Checking memory leaks with valgrind +=================================== + +You can use `Valgrind <https://www.valgrind.org>`_ to check for and log memory leaks in extensions. For instance, to check for a memory leak in a test from the suite you can run: + +.. code-block:: sh + + PYTHONMALLOC=malloc valgrind --leak-check=yes --track-origins=yes --log-file=valgrind-log.txt python -m pytest <path_to_a_test> + +Note that code execution under valgrind will take much longer than usual. While you can run valgrind against extensions compiled with any optimization level, it is suggested to have optimizations turned off from compiled extensions to reduce the amount of false positives. The ``--with-debugging-symbols`` flag passed during package setup will do this for you automatically. + +.. note:: + + For best results, you should run use a Python installation configured with Valgrind support (--with-valgrind) diff --git a/doc/source/development/index.rst b/doc/source/development/index.rst index e842c827b417f..abe2fc1409bfb 100644 --- a/doc/source/development/index.rst +++ b/doc/source/development/index.rst @@ -17,6 +17,7 @@ Development maintaining internals test_writing + debugging_extensions extending developer policies diff --git a/setup.py b/setup.py index 0b1007794bbdb..a25fe95e025b3 100755 --- a/setup.py +++ b/setup.py @@ -421,6 +421,8 @@ def run(self): extra_compile_args.append("-Werror") if debugging_symbols_requested: extra_compile_args.append("-g") + extra_compile_args.append("-UNDEBUG") + extra_compile_args.append("-O0") # Build for at least macOS 10.9 when compiling on a 10.9 system or above, # overriding CPython distuitls behaviour which is to target the version that
Quick notes in case they are helpful to others. Can move to the Wiki as well if we don't want in the standard docs
https://api.github.com/repos/pandas-dev/pandas/pulls/35100
2020-07-02T19:20:06Z
2020-12-10T00:19:42Z
2020-12-10T00:19:42Z
2023-04-12T20:17:09Z
TYP: type unit as str
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index f494e74bde55f..8d8a62a58f25f 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -363,8 +363,8 @@ def format_array_from_datetime( def array_with_unit_to_datetime( ndarray values, - object unit, - str errors='coerce' + str unit, + str errors="coerce" ): """ Convert the ndarray to datetime according to the time unit. @@ -384,7 +384,7 @@ def array_with_unit_to_datetime( ---------- values : ndarray of object Date-like objects to convert. - unit : object + unit : str Time unit to use during conversion. errors : str, default 'raise' Error behavior when parsing. diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index 2cf75944a8196..0eb94fecf7d6b 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -13,7 +13,7 @@ cdef class _TSObject: bint fold -cdef convert_to_tsobject(object ts, tzinfo tz, object unit, +cdef convert_to_tsobject(object ts, tzinfo tz, str unit, bint dayfirst, bint yearfirst, int32_t nanos=*) diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 95500f66db156..a1f074b1b29a8 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -56,8 +56,19 @@ TD64NS_DTYPE = np.dtype('m8[ns]') # Unit Conversion Helpers cdef inline int64_t cast_from_unit(object ts, str unit) except? -1: - """ return a casting of the unit represented to nanoseconds - round the fractional part of a float to our precision, p """ + """ + Return a casting of the unit represented to nanoseconds + round the fractional part of a float to our precision, p. + + Parameters + ---------- + ts : int, float, or None + unit : str + + Returns + ------- + int64_t + """ cdef: int64_t m int p @@ -307,7 +318,7 @@ cdef class _TSObject: return self.value -cdef convert_to_tsobject(object ts, tzinfo tz, object unit, +cdef convert_to_tsobject(object ts, tzinfo tz, str unit, bint dayfirst, bint yearfirst, int32_t nanos=0): """ Extract datetime and int64 from any of: @@ -497,7 +508,7 @@ cdef _TSObject _create_tsobject_tz_using_offset(npy_datetimestruct dts, return obj -cdef _TSObject _convert_str_to_tsobject(object ts, tzinfo tz, object unit, +cdef _TSObject _convert_str_to_tsobject(object ts, tzinfo tz, str unit, bint dayfirst=False, bint yearfirst=False): """ @@ -513,6 +524,7 @@ cdef _TSObject _convert_str_to_tsobject(object ts, tzinfo tz, object unit, Value to be converted to _TSObject tz : tzinfo or None timezone for the timezone-aware output + unit : str or None dayfirst : bool, default False When parsing an ambiguous date string, interpret e.g. "3/4/1975" as April 3, as opposed to the standard US interpretation March 4. diff --git a/pandas/_libs/tslibs/timedeltas.pxd b/pandas/_libs/tslibs/timedeltas.pxd index 70a418d7803d1..4142861e9ad38 100644 --- a/pandas/_libs/tslibs/timedeltas.pxd +++ b/pandas/_libs/tslibs/timedeltas.pxd @@ -3,7 +3,7 @@ from numpy cimport int64_t # Exposed for tslib, not intended for outside use. cpdef int64_t delta_to_nanoseconds(delta) except? -1 -cdef convert_to_timedelta64(object ts, object unit) +cdef convert_to_timedelta64(object ts, str unit) cdef bint is_any_td_scalar(object obj) diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 2862e62e3d522..8f3a599bf107c 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -160,7 +160,7 @@ cpdef int64_t delta_to_nanoseconds(delta) except? -1: raise TypeError(type(delta)) -cdef convert_to_timedelta64(object ts, object unit): +cdef convert_to_timedelta64(object ts, str unit): """ Convert an incoming object to a timedelta64 if possible. Before calling, unit must be standardized to avoid repeated unit conversion @@ -218,7 +218,7 @@ cdef convert_to_timedelta64(object ts, object unit): @cython.boundscheck(False) @cython.wraparound(False) -def array_to_timedelta64(object[:] values, unit=None, errors='raise'): +def array_to_timedelta64(object[:] values, str unit=None, str errors="raise"): """ Convert an ndarray to an array of timedeltas. If errors == 'coerce', coerce non-convertible objects to NaT. Otherwise, raise. @@ -470,7 +470,7 @@ cdef inline timedelta_from_spec(object number, object frac, object unit): return cast_from_unit(float(n), unit) -cpdef inline str parse_timedelta_unit(object unit): +cpdef inline str parse_timedelta_unit(str unit): """ Parameters ---------- diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index e104b722ea119..b79a5c49bdd10 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -1050,6 +1050,7 @@ class Timestamp(_Timestamp): nanosecond = hour tz = minute freq = None + unit = None if getattr(ts_input, 'tzinfo', None) is not None and tz is not None: raise ValueError("Cannot pass a datetime or Timestamp with tzinfo with "
https://api.github.com/repos/pandas-dev/pandas/pulls/35099
2020-07-02T18:10:29Z
2020-07-06T18:01:30Z
2020-07-06T18:01:30Z
2020-07-06T18:33:03Z
BUG: fix union_indexes not supporting sort=False for Index subclasses
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 9bd4ddbb624d9..0b2493cfaf7ff 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1112,6 +1112,7 @@ Reshaping - Fixed bug in :func:`melt` where melting MultiIndex columns with ``col_level`` > 0 would raise a ``KeyError`` on ``id_vars`` (:issue:`34129`) - Bug in :meth:`Series.where` with an empty Series and empty ``cond`` having non-bool dtype (:issue:`34592`) - Fixed regression where :meth:`DataFrame.apply` would raise ``ValueError`` for elements whth ``S`` dtype (:issue:`34529`) +- Bug in :meth:`DataFrame.append` leading to sorting columns even when ``sort=False`` is specified (:issue:`35092`) Sparse ^^^^^^ diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index 4c5a70f4088ee..9849742abcfca 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -214,7 +214,13 @@ def conv(i): return result.union_many(indexes[1:]) else: for other in indexes[1:]: - result = result.union(other) + # GH 35092. Index.union expects sort=None instead of sort=True + # to signify that sort=True isn't fully implemented and + # legacy implementation sometimes might not sort (see GH 24959) + # In this case we currently sort in _get_combined_index + if sort: + sort = None + result = result.union(other, sort=sort) return result elif kind == "array": index = indexes[0] diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index dba243f1a339a..ab4f7781467e7 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2542,11 +2542,13 @@ def test_construct_with_two_categoricalindex_series(self): index=pd.CategoricalIndex(["f", "female", "m", "male", "unknown"]), ) result = DataFrame([s1, s2]) + # GH 35092. Extra s2 columns are now appended to s1 columns + # in original order expected = DataFrame( np.array( - [[np.nan, 39.0, np.nan, 6.0, 4.0], [2.0, 152.0, 2.0, 242.0, 150.0]] + [[39.0, 6.0, 4.0, np.nan, np.nan], [152.0, 242.0, 150.0, 2.0, 2.0]] ), - columns=["f", "female", "m", "male", "unknown"], + columns=["female", "male", "unknown", "f", "m"], ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py index 02a173eb4958d..c85696e02ad39 100644 --- a/pandas/tests/indexes/test_common.py +++ b/pandas/tests/indexes/test_common.py @@ -13,8 +13,9 @@ from pandas.core.dtypes.common import is_period_dtype, needs_i8_conversion import pandas as pd -from pandas import CategoricalIndex, MultiIndex, RangeIndex +from pandas import CategoricalIndex, Index, MultiIndex, RangeIndex import pandas._testing as tm +from pandas.core.indexes.api import union_indexes class TestCommon: @@ -395,3 +396,18 @@ def test_astype_preserves_name(self, index, dtype, copy): assert result.names == index.names else: assert result.name == index.name + + +@pytest.mark.parametrize("arr", [[0, 1, 4, 3]]) +@pytest.mark.parametrize("dtype", ["int8", "int16", "int32", "int64"]) +def test_union_index_no_sort(arr, sort, dtype): + # GH 35092. Check that we don't sort with sort=False + ind1 = Index(arr[:2], dtype=dtype) + ind2 = Index(arr[2:], dtype=dtype) + + # sort is None indicates that we sort the combined index + if sort is None: + arr.sort() + expected = Index(arr, dtype=dtype) + result = union_indexes([ind1, ind2], sort=sort) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index ffeb5ff0f8aaa..ff95d8ad997a4 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -2857,3 +2857,17 @@ def test_concat_frame_axis0_extension_dtypes(): result = pd.concat([df2, df1], ignore_index=True) expected = pd.DataFrame({"a": [4, 5, 6, 1, 2, 3]}, dtype="Int64") tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("sort", [True, False]) +def test_append_sort(sort): + # GH 35092. Check that DataFrame.append respects the sort argument. + df1 = pd.DataFrame(data={0: [1, 2], 1: [3, 4]}) + df2 = pd.DataFrame(data={3: [1, 2], 2: [3, 4]}) + cols = list(df1.columns) + list(df2.columns) + if sort: + cols.sort() + + result = df1.append(df2, sort=sort).columns + expected = type(result)(cols) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index a0fa10802f860..03fda038539e2 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -691,11 +691,11 @@ def test_unbalanced(self): ) df["id"] = df.index exp_data = { - "X": ["X1", "X1", "X2", "X2"], - "A": [1.0, 3.0, 2.0, 4.0], - "B": [5.0, np.nan, 6.0, np.nan], - "id": [0, 0, 1, 1], - "year": [2010, 2011, 2010, 2011], + "X": ["X1", "X2", "X1", "X2"], + "A": [1.0, 2.0, 3.0, 4.0], + "B": [5.0, 6.0, np.nan, np.nan], + "id": [0, 1, 0, 1], + "year": [2010, 2010, 2011, 2011], } expected = pd.DataFrame(exp_data) expected = expected.set_index(["id", "year"])[["X", "A", "B"]] @@ -938,10 +938,10 @@ def test_nonnumeric_suffix(self): ) expected = pd.DataFrame( { - "A": ["X1", "X1", "X2", "X2"], - "colname": ["placebo", "test", "placebo", "test"], - "result": [5.0, np.nan, 6.0, np.nan], - "treatment": [1.0, 3.0, 2.0, 4.0], + "A": ["X1", "X2", "X1", "X2"], + "colname": ["placebo", "placebo", "test", "test"], + "result": [5.0, 6.0, np.nan, np.nan], + "treatment": [1.0, 2.0, 3.0, 4.0], } ) expected = expected.set_index(["A", "colname"]) @@ -985,10 +985,10 @@ def test_float_suffix(self): ) expected = pd.DataFrame( { - "A": ["X1", "X1", "X1", "X1", "X2", "X2", "X2", "X2"], - "colname": [1, 1.1, 1.2, 2.1, 1, 1.1, 1.2, 2.1], - "result": [0.0, np.nan, 5.0, np.nan, 9.0, np.nan, 6.0, np.nan], - "treatment": [np.nan, 1.0, np.nan, 3.0, np.nan, 2.0, np.nan, 4.0], + "A": ["X1", "X2", "X1", "X2", "X1", "X2", "X1", "X2"], + "colname": [1.2, 1.2, 1.0, 1.0, 1.1, 1.1, 2.1, 2.1], + "result": [5.0, 6.0, 0.0, 9.0, np.nan, np.nan, np.nan, np.nan], + "treatment": [np.nan, np.nan, np.nan, np.nan, 1.0, 2.0, 3.0, 4.0], } ) expected = expected.set_index(["A", "colname"]) diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index d9396d70f9112..3a4e54052305e 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -636,8 +636,15 @@ def test_str_cat_align_mixed_inputs(self, join): # mixed list of indexed/unindexed u = np.array(["A", "B", "C", "D"]) expected_outer = Series(["aaA", "bbB", "c-C", "ddD", "-e-"]) + # joint index of rhs [t, u]; u will be forced have index of s - rhs_idx = t.index & s.index if join == "inner" else t.index | s.index + # GH 35092. If right join, maintain order of t.index + if join == "inner": + rhs_idx = t.index & s.index + elif join == "right": + rhs_idx = t.index.union(s.index, sort=False) + else: + rhs_idx = t.index | s.index expected = expected_outer.loc[s.index.join(rhs_idx, how=join)] result = s.str.cat([t, u], join=join, na_rep="-")
- [X] closes #35092 - [X] 1 tests added / 1 passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry # Scope of PR The reason for `DataFrame.append` unnecessarily sorting columns turned out to be that when merging indexes we were not passing the `sort` argument for an `Index` subclass. This PR fixes this bug. # Details At some point down the call stack, `DataFrame.append` calls `union_indexes` in `core.indexes.api`. In it we detect the type of our indexes: ```python indexes, kind = _sanitize_and_check(indexes) ``` We don't pass `sort` for `kind == 'special'` in `union_indexes`. I had some other ideas, but what I ended up doing is to simply pass the `sort` argument to `Index.union` for `kind == 'special'`. We do have to ignore the `sort` argument for `[MultiIndex, RangeIndex, DatetimeIndex, CategoricalIndex]` to avoid breaking tests and backward compatibility, but it doesn't make sense for these ones to not be sorted when joined anyway, in my opinion. # Performance There are no changes to algorithms called. I still did some benchmarking to compare with my previous approach. The current solution didn't have any negative performance impact.
https://api.github.com/repos/pandas-dev/pandas/pulls/35098
2020-07-02T18:05:31Z
2020-07-09T13:02:33Z
2020-07-09T13:02:32Z
2020-07-09T15:11:45Z
TYP: type for get_timezone
diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd index 0179be3cdd8e6..0784b090b3edb 100644 --- a/pandas/_libs/tslibs/timezones.pxd +++ b/pandas/_libs/tslibs/timezones.pxd @@ -8,7 +8,7 @@ cdef bint is_tzlocal(tzinfo tz) cdef bint treat_tz_as_pytz(tzinfo tz) cpdef bint tz_compare(tzinfo start, tzinfo end) -cpdef object get_timezone(object tz) +cpdef object get_timezone(tzinfo tz) cpdef object maybe_get_tz(object tz) cdef get_utcoffset(tzinfo tz, obj) diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index 5bf47efeccfb0..0460591048801 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -1,6 +1,5 @@ from datetime import timezone -from cpython.datetime cimport datetime, tzinfo, PyTZInfo_Check, PyDateTime_IMPORT -PyDateTime_IMPORT +from cpython.datetime cimport datetime, tzinfo # dateutil compat from dateutil.tz import ( @@ -47,7 +46,7 @@ cdef inline bint treat_tz_as_dateutil(tzinfo tz): return hasattr(tz, '_trans_list') and hasattr(tz, '_trans_idx') -cpdef inline object get_timezone(object tz): +cpdef inline object get_timezone(tzinfo tz): """ We need to do several things here: 1) Distinguish between pytz and dateutil timezones @@ -60,9 +59,7 @@ cpdef inline object get_timezone(object tz): the tz name. It needs to be a string so that we can serialize it with UJSON/pytables. maybe_get_tz (below) is the inverse of this process. """ - if not PyTZInfo_Check(tz): - return tz - elif is_utc(tz): + if is_utc(tz): return tz else: if treat_tz_as_dateutil(tz): diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 12eefec0c149b..64e8582baaa98 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -522,13 +522,6 @@ def tzinfo(self): """ return self.tz - @property # NB: override with cache_readonly in immutable subclasses - def _timezone(self): - """ - Comparable timezone both for pytz / dateutil - """ - return timezones.get_timezone(self.tzinfo) - @property # NB: override with cache_readonly in immutable subclasses def is_normalized(self): """ @@ -617,15 +610,17 @@ def _format_native_types(self, na_rep="NaT", date_format=None, **kwargs): # ----------------------------------------------------------------- # Comparison Methods - def _has_same_tz(self, other): - zzone = self._timezone + def _has_same_tz(self, other) -> bool: # vzone shouldn't be None if value is non-datetime like if isinstance(other, np.datetime64): # convert to Timestamp as np.datetime64 doesn't have tz attr other = Timestamp(other) - vzone = timezones.get_timezone(getattr(other, "tzinfo", "__no_tz__")) - return zzone == vzone + + if not hasattr(other, "tzinfo"): + return False + other_tz = other.tzinfo + return timezones.tz_compare(self.tzinfo, other_tz) def _assert_tzawareness_compat(self, other): # adapted from _Timestamp._assert_tzawareness_compat diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index f3c96db0a8d6e..86c6cdf5b15c7 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -74,9 +74,7 @@ def _new_DatetimeIndex(cls, d): DatetimeArray, wrap=True, ) -@inherit_names( - ["_timezone", "is_normalized", "_resolution_obj"], DatetimeArray, cache=True -) +@inherit_names(["is_normalized", "_resolution_obj"], DatetimeArray, cache=True) @inherit_names( [ "_bool_ops",
Nearly done with these
https://api.github.com/repos/pandas-dev/pandas/pulls/35096
2020-07-02T16:55:11Z
2020-07-02T17:34:52Z
2020-07-02T17:34:52Z
2020-07-02T17:41:02Z
TYP: types for tz_compare
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index ea97bab2198eb..37d83a73c6597 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -73,7 +73,7 @@ from pandas._libs.tslibs.nattype cimport ( ) from pandas._libs.tslibs.conversion cimport convert_to_tsobject from pandas._libs.tslibs.timedeltas cimport convert_to_timedelta64 -from pandas._libs.tslibs.timezones cimport get_timezone, tz_compare +from pandas._libs.tslibs.timezones cimport tz_compare from pandas._libs.tslibs.period cimport is_period_object from pandas._libs.tslibs.offsets cimport is_offset_object @@ -1789,7 +1789,7 @@ def is_datetime_with_singletz_array(values: ndarray) -> bool: for i in range(n): base_val = values[i] if base_val is not NaT: - base_tz = get_timezone(getattr(base_val, 'tzinfo', None)) + base_tz = getattr(base_val, 'tzinfo', None) break for j in range(i, n): diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd index 78483bd6fe09e..0179be3cdd8e6 100644 --- a/pandas/_libs/tslibs/timezones.pxd +++ b/pandas/_libs/tslibs/timezones.pxd @@ -7,7 +7,7 @@ cdef bint is_tzlocal(tzinfo tz) cdef bint treat_tz_as_pytz(tzinfo tz) -cpdef bint tz_compare(object start, object end) +cpdef bint tz_compare(tzinfo start, tzinfo end) cpdef object get_timezone(object tz) cpdef object maybe_get_tz(object tz) diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index 112da2eb5b624..5bf47efeccfb0 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -301,7 +301,7 @@ def infer_tzinfo(datetime start, datetime end): return tz -cpdef bint tz_compare(object start, object end): +cpdef bint tz_compare(tzinfo start, tzinfo end): """ Compare string representations of timezones @@ -324,7 +324,6 @@ cpdef bint tz_compare(object start, object end): Returns: ------- bool - """ # GH 18523 return get_timezone(start) == get_timezone(end) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 296f11583c372..12eefec0c149b 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -2266,7 +2266,9 @@ def validate_tz_from_dtype(dtype, tz: Optional[tzinfo]) -> Optional[tzinfo]: return tz -def _infer_tz_from_endpoints(start, end, tz): +def _infer_tz_from_endpoints( + start: Timestamp, end: Timestamp, tz: Optional[tzinfo] +) -> Optional[tzinfo]: """ If a timezone is not explicitly given via `tz`, see if one can be inferred from the `start` and `end` endpoints. If more than one
https://api.github.com/repos/pandas-dev/pandas/pulls/35093
2020-07-02T02:54:43Z
2020-07-02T14:42:06Z
2020-07-02T14:42:06Z
2020-07-02T16:25:05Z
BENCH: implement asvs for ints_to_pydatetime
diff --git a/asv_bench/benchmarks/tslibs/tslib.py b/asv_bench/benchmarks/tslibs/tslib.py new file mode 100644 index 0000000000000..eacf5a5731dc2 --- /dev/null +++ b/asv_bench/benchmarks/tslibs/tslib.py @@ -0,0 +1,55 @@ +""" +ipython analogue: + +tr = TimeIntsToPydatetime() +mi = pd.MultiIndex.from_product( + tr.params[:-1] + ([str(x) for x in tr.params[-1]],) +) +df = pd.DataFrame(np.nan, index=mi, columns=["mean", "stdev"]) +for box in tr.params[0]: + for size in tr.params[1]: + for tz in tr.params[2]: + tr.setup(box, size, tz) + key = (box, size, str(tz)) + print(key) + val = %timeit -o tr.time_ints_to_pydatetime(box, size, tz) + df.loc[key] = (val.average, val.stdev) +""" +from datetime import timedelta, timezone + +from dateutil.tz import gettz, tzlocal +import numpy as np +import pytz + +from pandas._libs.tslib import ints_to_pydatetime + +_tzs = [ + None, + timezone.utc, + timezone(timedelta(minutes=60)), + pytz.timezone("US/Pacific"), + gettz("Asia/Tokyo"), + tzlocal(), +] +_sizes = [0, 1, 100, 10 ** 4, 10 ** 6] + + +class TimeIntsToPydatetime: + params = ( + ["time", "date", "datetime", "timestamp"], + _sizes, + _tzs, + ) + param_names = ["box", "size", "tz"] + # TODO: fold? freq? + + def setup(self, box, size, tz): + arr = np.random.randint(0, 10, size=size, dtype="i8") + self.i8data = arr + + def time_ints_to_pydatetime(self, box, size, tz): + if box == "date": + # ints_to_pydatetime does not allow non-None tz with date; + # this will mean doing some duplicate benchmarks + tz = None + ints_to_pydatetime(self.i8data, tz, box=box)
https://api.github.com/repos/pandas-dev/pandas/pulls/35091
2020-07-01T21:37:44Z
2020-07-02T14:42:55Z
2020-07-02T14:42:55Z
2020-07-02T16:28:10Z
TST: update gbq service account key
diff --git a/ci/travis_encrypt_gbq.sh b/ci/travis_encrypt_gbq.sh index e404ca73a405e..7d5692d9520af 100755 --- a/ci/travis_encrypt_gbq.sh +++ b/ci/travis_encrypt_gbq.sh @@ -19,7 +19,7 @@ if [[ ! -f $GBQ_JSON_FILE ]]; then fi echo "Encrypting $GBQ_JSON_FILE..." -read -d "\n" TRAVIS_KEY TRAVIS_IV <<<$(travis encrypt-file $GBQ_JSON_FILE \ +read -d "\n" TRAVIS_KEY TRAVIS_IV <<<$(travis encrypt-file -r pandas-dev/pandas $GBQ_JSON_FILE \ travis_gbq.json.enc -f | grep -o "\w*_iv\|\w*_key"); echo "Adding your secure key to travis_gbq_config.txt ..." diff --git a/ci/travis_gbq.json.enc b/ci/travis_gbq.json.enc index c2a33bbd6f263..6e0b6cee4048c 100644 Binary files a/ci/travis_gbq.json.enc and b/ci/travis_gbq.json.enc differ diff --git a/ci/travis_gbq_config.txt b/ci/travis_gbq_config.txt index 0b28cdedbd0d7..dc857c450331c 100644 --- a/ci/travis_gbq_config.txt +++ b/ci/travis_gbq_config.txt @@ -1,2 +1,2 @@ -TRAVIS_IV_ENV=encrypted_1d9d7b1f171b_iv -TRAVIS_KEY_ENV=encrypted_1d9d7b1f171b_key +TRAVIS_IV_ENV=encrypted_e05c934e101e_iv +TRAVIS_KEY_ENV=encrypted_e05c934e101e_key diff --git a/ci/travis_process_gbq_encryption.sh b/ci/travis_process_gbq_encryption.sh index 9967d40e49f0a..fccf8e1e8deff 100755 --- a/ci/travis_process_gbq_encryption.sh +++ b/ci/travis_process_gbq_encryption.sh @@ -7,7 +7,7 @@ if [[ -n ${SERVICE_ACCOUNT_KEY} ]]; then elif [[ -n ${!TRAVIS_IV_ENV} ]]; then openssl aes-256-cbc -K ${!TRAVIS_KEY_ENV} -iv ${!TRAVIS_IV_ENV} \ -in ci/travis_gbq.json.enc -out ci/travis_gbq.json -d; - export GBQ_PROJECT_ID='pandas-travis'; + export GBQ_PROJECT_ID='pandas-gbq-tests'; echo 'Successfully decrypted gbq credentials' fi diff --git a/pandas/tests/io/test_gbq.py b/pandas/tests/io/test_gbq.py index 870d78ef1c533..df107259d38cd 100644 --- a/pandas/tests/io/test_gbq.py +++ b/pandas/tests/io/test_gbq.py @@ -148,7 +148,6 @@ def mock_read_gbq(sql, **kwargs): @pytest.mark.single -@pytest.mark.xfail(reason="skipping gbq integration for now, xref #34779") class TestToGBQIntegrationWithServiceAccountKeyPath: @pytest.fixture() def gbq_dataset(self):
Re-enable gbq integration tests. - [ ] closes #34779 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35090
2020-07-01T20:06:54Z
2020-07-09T23:41:00Z
2020-07-09T23:41:00Z
2020-07-09T23:41:00Z
CLN: tighter typing in libconversion
diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index 623d9f14d646b..2cf75944a8196 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -13,11 +13,11 @@ cdef class _TSObject: bint fold -cdef convert_to_tsobject(object ts, object tz, object unit, +cdef convert_to_tsobject(object ts, tzinfo tz, object unit, bint dayfirst, bint yearfirst, int32_t nanos=*) -cdef _TSObject convert_datetime_to_tsobject(datetime ts, object tz, +cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz, int32_t nanos=*) cdef int64_t get_datetime64_nanos(object val) except? -1 diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index ac24dd546d9d3..82a9ad9d3f49b 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -306,7 +306,7 @@ cdef class _TSObject: return self.value -cdef convert_to_tsobject(object ts, object tz, object unit, +cdef convert_to_tsobject(object ts, tzinfo tz, object unit, bint dayfirst, bint yearfirst, int32_t nanos=0): """ Extract datetime and int64 from any of: @@ -325,13 +325,10 @@ cdef convert_to_tsobject(object ts, object tz, object unit, cdef: _TSObject obj - if tz is not None: - tz = maybe_get_tz(tz) - obj = _TSObject() if isinstance(ts, str): - return convert_str_to_tsobject(ts, tz, unit, dayfirst, yearfirst) + return _convert_str_to_tsobject(ts, tz, unit, dayfirst, yearfirst) if ts is None or ts is NaT: obj.value = NPY_NAT @@ -373,16 +370,16 @@ cdef convert_to_tsobject(object ts, object tz, object unit, f'Timestamp') if tz is not None: - localize_tso(obj, tz) + _localize_tso(obj, tz) if obj.value != NPY_NAT: - # check_overflows needs to run after localize_tso + # check_overflows needs to run after _localize_tso check_dts_bounds(&obj.dts) check_overflows(obj) return obj -cdef _TSObject convert_datetime_to_tsobject(datetime ts, object tz, +cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz, int32_t nanos=0): """ Convert a datetime (or Timestamp) input `ts`, along with optional timezone @@ -445,8 +442,8 @@ cdef _TSObject convert_datetime_to_tsobject(datetime ts, object tz, return obj -cdef _TSObject create_tsobject_tz_using_offset(npy_datetimestruct dts, - int tzoffset, tzinfo tz=None): +cdef _TSObject _create_tsobject_tz_using_offset(npy_datetimestruct dts, + int tzoffset, tzinfo tz=None): """ Convert a datetimestruct `dts`, along with initial timezone offset `tzoffset` to a _TSObject (with timezone object `tz` - optional). @@ -499,9 +496,9 @@ cdef _TSObject create_tsobject_tz_using_offset(npy_datetimestruct dts, return obj -cdef _TSObject convert_str_to_tsobject(object ts, object tz, object unit, - bint dayfirst=False, - bint yearfirst=False): +cdef _TSObject _convert_str_to_tsobject(object ts, tzinfo tz, object unit, + bint dayfirst=False, + bint yearfirst=False): """ Convert a string input `ts`, along with optional timezone object`tz` to a _TSObject. @@ -531,11 +528,6 @@ cdef _TSObject convert_str_to_tsobject(object ts, object tz, object unit, int out_local = 0, out_tzoffset = 0 bint do_parse_datetime_string = False - if tz is not None: - tz = maybe_get_tz(tz) - - assert isinstance(ts, str) - if len(ts) == 0 or ts in nat_strings: ts = NaT elif ts == 'now': @@ -556,12 +548,12 @@ cdef _TSObject convert_str_to_tsobject(object ts, object tz, object unit, if not string_to_dts_failed: check_dts_bounds(&dts) if out_local == 1: - return create_tsobject_tz_using_offset(dts, - out_tzoffset, tz) + return _create_tsobject_tz_using_offset(dts, + out_tzoffset, tz) else: ts = dtstruct_to_dt64(&dts) if tz is not None: - # shift for localize_tso + # shift for _localize_tso ts = tz_localize_to_utc(np.array([ts], dtype='i8'), tz, ambiguous='raise')[0] @@ -612,7 +604,7 @@ cdef inline check_overflows(_TSObject obj): # ---------------------------------------------------------------------- # Localization -cdef inline void localize_tso(_TSObject obj, tzinfo tz): +cdef inline void _localize_tso(_TSObject obj, tzinfo tz): """ Given the UTC nanosecond timestamp in obj.value, find the wall-clock representation of that timestamp in the given timezone. diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 1328bc8a5175f..e104b722ea119 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -20,6 +20,7 @@ from cpython.datetime cimport ( datetime, time, tzinfo, + tzinfo as tzinfo_type, # alias bc `tzinfo` is a kwarg below PyDateTime_Check, PyDelta_Check, PyTZInfo_Check, @@ -932,7 +933,7 @@ class Timestamp(_Timestamp): second=None, microsecond=None, nanosecond=None, - tzinfo=None, + tzinfo_type tzinfo=None, *, fold=None ): @@ -957,18 +958,17 @@ class Timestamp(_Timestamp): # # Mixing pydatetime positional and keyword arguments is forbidden! - cdef _TSObject ts + cdef: + _TSObject ts + tzinfo_type tzobj _date_attributes = [year, month, day, hour, minute, second, microsecond, nanosecond] if tzinfo is not None: - if not PyTZInfo_Check(tzinfo): - # tzinfo must be a datetime.tzinfo object, GH#17690 - raise TypeError( - f"tzinfo must be a datetime.tzinfo object, not {type(tzinfo)}" - ) - elif tz is not None: + # GH#17690 tzinfo must be a datetime.tzinfo object, ensured + # by the cython annotation. + if tz is not None: raise ValueError('Can provide at most one of tz, tzinfo') # User passed tzinfo instead of tz; avoid silently ignoring @@ -1055,7 +1055,8 @@ class Timestamp(_Timestamp): raise ValueError("Cannot pass a datetime or Timestamp with tzinfo with " "the tz parameter. Use tz_convert instead.") - ts = convert_to_tsobject(ts_input, tz, unit, 0, 0, nanosecond or 0) + tzobj = maybe_get_tz(tz) + ts = convert_to_tsobject(ts_input, tzobj, unit, 0, 0, nanosecond or 0) if ts.value == NPY_NAT: return NaT @@ -1378,15 +1379,16 @@ default 'raise' cdef: npy_datetimestruct dts - int64_t value, value_tz, offset - object _tzinfo, result, k, v + int64_t value, value_tz + object k, v datetime ts_input + tzinfo_type tzobj # set to naive if needed - _tzinfo = self.tzinfo + tzobj = self.tzinfo value = self.value - if _tzinfo is not None: - value_tz = tz_convert_single(value, _tzinfo, UTC) + if tzobj is not None: + value_tz = tz_convert_single(value, tzobj, UTC) value += value - value_tz # setup components @@ -1419,30 +1421,30 @@ default 'raise' if nanosecond is not None: dts.ps = validate('nanosecond', nanosecond) * 1000 if tzinfo is not object: - _tzinfo = tzinfo + tzobj = tzinfo # reconstruct & check bounds - if _tzinfo is not None and treat_tz_as_pytz(_tzinfo): + if tzobj is not None and treat_tz_as_pytz(tzobj): # replacing across a DST boundary may induce a new tzinfo object # see GH#18319 - ts_input = _tzinfo.localize(datetime(dts.year, dts.month, dts.day, - dts.hour, dts.min, dts.sec, - dts.us), - is_dst=not bool(fold)) - _tzinfo = ts_input.tzinfo + ts_input = tzobj.localize(datetime(dts.year, dts.month, dts.day, + dts.hour, dts.min, dts.sec, + dts.us), + is_dst=not bool(fold)) + tzobj = ts_input.tzinfo else: kwargs = {'year': dts.year, 'month': dts.month, 'day': dts.day, 'hour': dts.hour, 'minute': dts.min, 'second': dts.sec, - 'microsecond': dts.us, 'tzinfo': _tzinfo, + 'microsecond': dts.us, 'tzinfo': tzobj, 'fold': fold} ts_input = datetime(**kwargs) - ts = convert_datetime_to_tsobject(ts_input, _tzinfo) + ts = convert_datetime_to_tsobject(ts_input, tzobj) value = ts.value + (dts.ps // 1000) if value != NPY_NAT: check_dts_bounds(&dts) - return create_timestamp_from_ts(value, dts, _tzinfo, self.freq, fold) + return create_timestamp_from_ts(value, dts, tzobj, self.freq, fold) def to_julian_date(self) -> np.float64: """ diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py index 770753f42a4c8..316a299ba1cbb 100644 --- a/pandas/tests/scalar/timestamp/test_constructors.py +++ b/pandas/tests/scalar/timestamp/test_constructors.py @@ -174,7 +174,10 @@ def test_constructor_invalid(self): def test_constructor_invalid_tz(self): # GH#17690 - msg = "must be a datetime.tzinfo" + msg = ( + "Argument 'tzinfo' has incorrect type " + r"\(expected datetime.tzinfo, got str\)" + ) with pytest.raises(TypeError, match=msg): Timestamp("2017-10-22", tzinfo="US/Eastern")
https://api.github.com/repos/pandas-dev/pandas/pulls/35088
2020-07-01T18:42:24Z
2020-07-02T14:44:10Z
2020-07-02T14:44:10Z
2020-07-02T16:27:03Z
PERF: tz_convert/tz_convert_single
diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index a096b2807c640..d1d6bc40ef288 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -345,36 +345,28 @@ cpdef int64_t tz_convert_single(int64_t val, tzinfo tz1, tzinfo tz2): converted: int64 """ cdef: - int64_t utc_date int64_t arr[1] + bint to_utc = is_utc(tz2) + tzinfo tz # See GH#17734 We should always be converting either from UTC or to UTC - assert is_utc(tz1) or is_utc(tz2) + assert is_utc(tz1) or to_utc if val == NPY_NAT: return val - # Convert to UTC - if is_tzlocal(tz1): - utc_date = _tz_convert_tzlocal_utc(val, tz1, to_utc=True) - elif not is_utc(tz1): - arr[0] = val - utc_date = _tz_convert_dst(arr, tz1, to_utc=True)[0] + if to_utc: + tz = tz1 else: - utc_date = val + tz = tz2 - if is_utc(tz2): - return utc_date - elif is_tzlocal(tz2): - return _tz_convert_tzlocal_utc(utc_date, tz2, to_utc=False) + if is_utc(tz): + return val + elif is_tzlocal(tz): + return _tz_convert_tzlocal_utc(val, tz, to_utc=to_utc) else: - # Convert UTC to other timezone - arr[0] = utc_date - # Note: at least with cython 0.28.3, doing a lookup `[0]` in the next - # line is sensitive to the declared return type of _tz_convert_dst; - # if it is declared as returning ndarray[int64_t], a compile-time error - # is raised. - return _tz_convert_dst(arr, tz2, to_utc=False)[0] + arr[0] = val + return _tz_convert_dst(arr, tz, to_utc=to_utc)[0] def tz_convert(int64_t[:] vals, tzinfo tz1, tzinfo tz2): @@ -392,14 +384,22 @@ def tz_convert(int64_t[:] vals, tzinfo tz1, tzinfo tz2): int64 ndarray of converted """ cdef: - int64_t[:] utc_dates, converted + int64_t[:] converted + bint to_utc = is_utc(tz2) + tzinfo tz + + # See GH#17734 We should always be converting either from UTC or to UTC + assert is_utc(tz1) or to_utc if len(vals) == 0: return np.array([], dtype=np.int64) - # Convert to UTC - utc_dates = _tz_convert_one_way(vals, tz1, to_utc=True) - converted = _tz_convert_one_way(utc_dates, tz2, to_utc=False) + if to_utc: + tz = tz1 + else: + tz = tz2 + + converted = _tz_convert_one_way(vals, tz, to_utc=to_utc) return np.array(converted, dtype=np.int64) diff --git a/pandas/tests/tslibs/test_conversion.py b/pandas/tests/tslibs/test_conversion.py index fd8c9df026674..3a7e06fb14a5f 100644 --- a/pandas/tests/tslibs/test_conversion.py +++ b/pandas/tests/tslibs/test_conversion.py @@ -57,9 +57,10 @@ def test_tz_convert_single_matches_tz_convert(tz_aware_fixture, freq): ], ) def test_tz_convert_corner(arr): - result = tzconversion.tz_convert( - arr, timezones.maybe_get_tz("US/Eastern"), timezones.maybe_get_tz("Asia/Tokyo") - ) + result = tzconversion.tz_convert(arr, timezones.maybe_get_tz("US/Eastern"), UTC) + tm.assert_numpy_array_equal(result, arr) + + result = tzconversion.tz_convert(arr, UTC, timezones.maybe_get_tz("Asia/Tokyo")) tm.assert_numpy_array_equal(result, arr)
Making these follow the same pattern we use elsewhere, we get a perf bump: ``` In [2]: dti = pd.date_range("2016-01-01", periods=10000, tz="US/Pacific") In [3]: %timeit dti.tz_localize(None) 91.4 µs ± 3.06 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- PR 102 µs ± 6.43 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- master In [4]: ts = pd.Timestamp.now("US/Pacific") In [5]: %timeit ts.tz_localize(None) 17.2 µs ± 307 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- PR 19.6 µs ± 233 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- PR ``` Next up is making sure we have full asv coverage for tz_convert/tz_convert_single, analogous to #35075. That can either be separate or added to this PR.
https://api.github.com/repos/pandas-dev/pandas/pulls/35087
2020-07-01T17:04:08Z
2020-07-02T16:59:10Z
2020-07-02T16:59:10Z
2020-07-02T17:17:01Z
CLN: Removed unreached else block GH33478
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index dab8475d9580c..6f956a3dcc9b6 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1218,7 +1218,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False): return self.obj._constructor() elif isinstance(first_not_none, DataFrame): return self._concat_objects(keys, values, not_indexed_same=not_indexed_same) - elif self.grouper.groupings is not None: + else: if len(self.grouper.groupings) > 1: key_index = self.grouper.result_index @@ -1373,10 +1373,6 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False): # of columns return self.obj._constructor_sliced(values, index=key_index) - else: - # Handle cases like BinGrouper - return self._concat_objects(keys, values, not_indexed_same=not_indexed_same) - def _transform_general( self, func, *args, engine="cython", engine_kwargs=None, **kwargs ):
Unreached else block in method _wrap_applied_output was removed. Local tests passed before and after change - [ ] xref #33478 (Not fully closed, this addresses 1 part) - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35086
2020-07-01T17:01:14Z
2020-07-02T14:51:28Z
2020-07-02T14:51:28Z
2020-07-05T06:46:06Z
Fix numpy warning
diff --git a/pandas/conftest.py b/pandas/conftest.py index d74c43069574f..5fe4cc45b0006 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -256,9 +256,7 @@ def nselect_method(request): # ---------------------------------------------------------------- # Missing values & co. # ---------------------------------------------------------------- -@pytest.fixture( - params=[None, np.nan, pd.NaT, float("nan"), np.float("NaN"), pd.NA], ids=str -) +@pytest.fixture(params=[None, np.nan, pd.NaT, float("nan"), pd.NA], ids=str) def nulls_fixture(request): """ Fixture for each null type in pandas.
https://api.github.com/repos/pandas-dev/pandas/pulls/35085
2020-07-01T16:31:59Z
2020-07-06T15:19:37Z
2020-07-06T15:19:37Z
2020-07-06T15:19:43Z
TYP: annotations, typing for infer_tzinfo
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index ac24dd546d9d3..9ee76a8c291a8 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -246,11 +246,12 @@ def datetime_to_datetime64(ndarray[object] values): """ cdef: Py_ssize_t i, n = len(values) - object val, inferred_tz = None + object val int64_t[:] iresult npy_datetimestruct dts _TSObject _ts bint found_naive = False + tzinfo inferred_tz = None result = np.empty(n, dtype='M8[ns]') iresult = result.view('i8') diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index 7d8aabcc47835..112da2eb5b624 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -1,5 +1,5 @@ from datetime import timezone -from cpython.datetime cimport tzinfo, PyTZInfo_Check, PyDateTime_IMPORT +from cpython.datetime cimport datetime, tzinfo, PyTZInfo_Check, PyDateTime_IMPORT PyDateTime_IMPORT # dateutil compat @@ -286,7 +286,7 @@ cdef object get_dst_info(tzinfo tz): return dst_cache[cache_key] -def infer_tzinfo(start, end): +def infer_tzinfo(datetime start, datetime end): if start is not None and end is not None: tz = start.tzinfo if not tz_compare(tz, end.tzinfo): diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 461f71ff821fa..296f11583c372 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1,4 +1,4 @@ -from datetime import datetime, time, timedelta +from datetime import datetime, time, timedelta, tzinfo from typing import Optional, Union import warnings @@ -1908,6 +1908,7 @@ def sequence_to_dt64ns( inferred_freq = None dtype = _validate_dt64_dtype(dtype) + tz = timezones.maybe_get_tz(tz) if not hasattr(data, "dtype"): # e.g. list, tuple @@ -1950,14 +1951,14 @@ def sequence_to_dt64ns( data, inferred_tz = objects_to_datetime64ns( data, dayfirst=dayfirst, yearfirst=yearfirst ) - tz = maybe_infer_tz(tz, inferred_tz) + tz = _maybe_infer_tz(tz, inferred_tz) data_dtype = data.dtype # `data` may have originally been a Categorical[datetime64[ns, tz]], # so we need to handle these types. if is_datetime64tz_dtype(data_dtype): # DatetimeArray -> ndarray - tz = maybe_infer_tz(tz, data.tz) + tz = _maybe_infer_tz(tz, data.tz) result = data._data elif is_datetime64_dtype(data_dtype): @@ -2144,7 +2145,9 @@ def maybe_convert_dtype(data, copy): # Validation and Inference -def maybe_infer_tz(tz, inferred_tz): +def _maybe_infer_tz( + tz: Optional[tzinfo], inferred_tz: Optional[tzinfo] +) -> Optional[tzinfo]: """ If a timezone is inferred from data, check that it is compatible with the user-provided timezone, if any. @@ -2216,7 +2219,7 @@ def _validate_dt64_dtype(dtype): return dtype -def validate_tz_from_dtype(dtype, tz): +def validate_tz_from_dtype(dtype, tz: Optional[tzinfo]) -> Optional[tzinfo]: """ If the given dtype is a DatetimeTZDtype, extract the implied tzinfo object from it and check that it does not conflict with the given diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 981b380f8b5e9..b67a1c5781d91 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -4714,7 +4714,7 @@ def _set_tz( if tz is not None: name = getattr(values, "name", None) values = values.ravel() - tz = timezones.get_timezone(_ensure_decoded(tz)) + tz = _ensure_decoded(tz) values = DatetimeIndex(values, name=name) values = values.tz_localize("UTC").tz_convert(tz) elif coerce:
Keeping these orthogonal
https://api.github.com/repos/pandas-dev/pandas/pulls/35084
2020-07-01T15:54:22Z
2020-07-02T00:16:06Z
2020-07-02T00:16:06Z
2020-07-02T00:43:11Z
No fastcall attribute in POWER platform
diff --git a/pandas/_libs/src/ujson/lib/ultrajson.h b/pandas/_libs/src/ujson/lib/ultrajson.h index 69284e1c3f2ab..757cabdbbc730 100644 --- a/pandas/_libs/src/ujson/lib/ultrajson.h +++ b/pandas/_libs/src/ujson/lib/ultrajson.h @@ -94,7 +94,7 @@ typedef __int64 JSLONG; #define EXPORTFUNCTION __declspec(dllexport) #define FASTCALL_MSVC __fastcall -#define FASTCALL_ATTR + #define INLINE_PREFIX static __inline #else @@ -108,12 +108,6 @@ typedef uint32_t JSUINT32; #define FASTCALL_MSVC -#if !defined __x86_64__ && !defined __aarch64__ -#define FASTCALL_ATTR __attribute__((fastcall)) -#else -#define FASTCALL_ATTR -#endif - #define INLINE_PREFIX static inline typedef uint8_t JSUINT8; diff --git a/pandas/_libs/src/ujson/lib/ultrajsondec.c b/pandas/_libs/src/ujson/lib/ultrajsondec.c index 36eb170f8048f..81327fd9efb06 100644 --- a/pandas/_libs/src/ujson/lib/ultrajsondec.c +++ b/pandas/_libs/src/ujson/lib/ultrajsondec.c @@ -68,7 +68,7 @@ struct DecoderState { JSONObjectDecoder *dec; }; -JSOBJ FASTCALL_MSVC decode_any(struct DecoderState *ds) FASTCALL_ATTR; +JSOBJ FASTCALL_MSVC decode_any(struct DecoderState *ds); typedef JSOBJ (*PFN_DECODER)(struct DecoderState *ds); static JSOBJ SetError(struct DecoderState *ds, int offset, @@ -99,7 +99,7 @@ double createDouble(double intNeg, double intValue, double frcValue, return (intValue + (frcValue * g_pow10[frcDecimalCount])) * intNeg; } -FASTCALL_ATTR JSOBJ FASTCALL_MSVC decodePreciseFloat(struct DecoderState *ds) { +JSOBJ FASTCALL_MSVC decodePreciseFloat(struct DecoderState *ds) { char *end; double value; errno = 0; @@ -114,7 +114,7 @@ FASTCALL_ATTR JSOBJ FASTCALL_MSVC decodePreciseFloat(struct DecoderState *ds) { return ds->dec->newDouble(ds->prv, value); } -FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_numeric(struct DecoderState *ds) { +JSOBJ FASTCALL_MSVC decode_numeric(struct DecoderState *ds) { int intNeg = 1; int mantSize = 0; JSUINT64 intValue; @@ -340,7 +340,7 @@ FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_numeric(struct DecoderState *ds) { pow(10.0, expValue * expNeg)); } -FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_true(struct DecoderState *ds) { +JSOBJ FASTCALL_MSVC decode_true(struct DecoderState *ds) { char *offset = ds->start; offset++; @@ -356,7 +356,7 @@ FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_true(struct DecoderState *ds) { return SetError(ds, -1, "Unexpected character found when decoding 'true'"); } -FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_false(struct DecoderState *ds) { +JSOBJ FASTCALL_MSVC decode_false(struct DecoderState *ds) { char *offset = ds->start; offset++; @@ -373,7 +373,7 @@ FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_false(struct DecoderState *ds) { return SetError(ds, -1, "Unexpected character found when decoding 'false'"); } -FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_null(struct DecoderState *ds) { +JSOBJ FASTCALL_MSVC decode_null(struct DecoderState *ds) { char *offset = ds->start; offset++; @@ -389,7 +389,7 @@ FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_null(struct DecoderState *ds) { return SetError(ds, -1, "Unexpected character found when decoding 'null'"); } -FASTCALL_ATTR void FASTCALL_MSVC SkipWhitespace(struct DecoderState *ds) { +void FASTCALL_MSVC SkipWhitespace(struct DecoderState *ds) { char *offset; for (offset = ds->start; (ds->end - offset) > 0; offset++) { @@ -677,7 +677,7 @@ static const JSUINT8 g_decoderLookup[256] = { DS_UTFLENERROR, }; -FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_string(struct DecoderState *ds) { +JSOBJ FASTCALL_MSVC decode_string(struct DecoderState *ds) { JSUTF16 sur[2] = {0}; int iSur = 0; int index; @@ -957,7 +957,7 @@ FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_string(struct DecoderState *ds) { } } -FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_array(struct DecoderState *ds) { +JSOBJ FASTCALL_MSVC decode_array(struct DecoderState *ds) { JSOBJ itemValue; JSOBJ newObj; int len; @@ -1021,7 +1021,7 @@ FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_array(struct DecoderState *ds) { } } -FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_object(struct DecoderState *ds) { +JSOBJ FASTCALL_MSVC decode_object(struct DecoderState *ds) { JSOBJ itemName; JSOBJ itemValue; JSOBJ newObj; @@ -1104,7 +1104,7 @@ FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_object(struct DecoderState *ds) { } } -FASTCALL_ATTR JSOBJ FASTCALL_MSVC decode_any(struct DecoderState *ds) { +JSOBJ FASTCALL_MSVC decode_any(struct DecoderState *ds) { for (;;) { switch (*ds->start) { case '\"': diff --git a/pandas/_libs/src/ujson/lib/ultrajsonenc.c b/pandas/_libs/src/ujson/lib/ultrajsonenc.c index 51aa39a16920e..5343999c369f7 100644 --- a/pandas/_libs/src/ujson/lib/ultrajsonenc.c +++ b/pandas/_libs/src/ujson/lib/ultrajsonenc.c @@ -393,7 +393,7 @@ void Buffer_Realloc(JSONObjectEncoder *enc, size_t cbNeeded) { enc->end = enc->start + newSize; } -FASTCALL_ATTR INLINE_PREFIX void FASTCALL_MSVC +INLINE_PREFIX void FASTCALL_MSVC Buffer_AppendShortHexUnchecked(char *outputOffset, unsigned short value) { *(outputOffset++) = g_hexChars[(value & 0xf000) >> 12]; *(outputOffset++) = g_hexChars[(value & 0x0f00) >> 8]; @@ -722,7 +722,7 @@ int Buffer_EscapeStringValidated(JSOBJ obj, JSONObjectEncoder *enc, #define Buffer_AppendCharUnchecked(__enc, __chr) *((__enc)->offset++) = __chr; -FASTCALL_ATTR INLINE_PREFIX void FASTCALL_MSVC strreverse(char *begin, +INLINE_PREFIX void FASTCALL_MSVC strreverse(char *begin, char *end) { char aux; while (end > begin) aux = *end, *end-- = *begin, *begin++ = aux;
Compiling the development branch of pandas fail in AIX. pandas/_libs/src/ujson/lib/ultrajsonenc.c:397:1: error: ‘fastcall’ attribute directive ignored [-Werror=attributes] Buffer_AppendShortHexUnchecked(char *outputOffset, unsigned short value) { ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pandas/_libs/src/ujson/lib/ultrajsonenc.c:726:59: error: ‘fastcall’ attribute directive ignored [-Werror=attributes] char *end) { ^~~~ cc1: all warnings being treated as errors The fastcall attribute is not available in POWER platform also.
https://api.github.com/repos/pandas-dev/pandas/pulls/35083
2020-07-01T14:45:30Z
2020-07-09T23:54:09Z
2020-07-09T23:54:09Z
2020-07-15T18:05:17Z
CLN: stronger typing in libtimezones
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index ba6cee3d7ad8e..1328bc8a5175f 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -991,7 +991,7 @@ class Timestamp(_Timestamp): "Timestamp from components." ) - if tz is not None and treat_tz_as_pytz(tz): + if tz is not None and PyTZInfo_Check(tz) and treat_tz_as_pytz(tz): raise ValueError( "pytz timezones do not support fold. Please use dateutil " "timezones." diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd index 14c0523787422..b65d45c103621 100644 --- a/pandas/_libs/tslibs/timezones.pxd +++ b/pandas/_libs/tslibs/timezones.pxd @@ -2,10 +2,10 @@ from cpython.datetime cimport tzinfo cdef tzinfo utc_pytz -cpdef bint is_utc(object tz) -cdef bint is_tzlocal(object tz) +cpdef bint is_utc(tzinfo tz) +cdef bint is_tzlocal(tzinfo tz) -cdef bint treat_tz_as_pytz(object tz) +cdef bint treat_tz_as_pytz(tzinfo tz) cpdef bint tz_compare(object start, object end) cpdef object get_timezone(object tz) diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index 7fbb50fcbfd41..4756fc83aa75b 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -1,5 +1,6 @@ -from cpython.datetime cimport tzinfo from datetime import timezone +from cpython.datetime cimport tzinfo, PyTZInfo_Check, PyDateTime_IMPORT +PyDateTime_IMPORT # dateutil compat from dateutil.tz import ( @@ -29,20 +30,20 @@ cdef tzinfo utc_pytz = UTC # ---------------------------------------------------------------------- -cpdef inline bint is_utc(object tz): +cpdef inline bint is_utc(tzinfo tz): return tz is utc_pytz or tz is utc_stdlib or isinstance(tz, _dateutil_tzutc) -cdef inline bint is_tzlocal(object tz): +cdef inline bint is_tzlocal(tzinfo tz): return isinstance(tz, _dateutil_tzlocal) -cdef inline bint treat_tz_as_pytz(object tz): +cdef inline bint treat_tz_as_pytz(tzinfo tz): return (hasattr(tz, '_utc_transition_times') and hasattr(tz, '_transition_info')) -cdef inline bint treat_tz_as_dateutil(object tz): +cdef inline bint treat_tz_as_dateutil(tzinfo tz): return hasattr(tz, '_trans_list') and hasattr(tz, '_trans_idx') @@ -59,7 +60,9 @@ cpdef inline object get_timezone(object tz): the tz name. It needs to be a string so that we can serialize it with UJSON/pytables. maybe_get_tz (below) is the inverse of this process. """ - if is_utc(tz): + if not PyTZInfo_Check(tz): + return tz + elif is_utc(tz): return tz else: if treat_tz_as_dateutil(tz): @@ -325,7 +328,7 @@ cpdef bint tz_compare(object start, object end): return get_timezone(start) == get_timezone(end) -def tz_standardize(tz: object): +def tz_standardize(tz: tzinfo): """ If the passed tz is a pytz timezone object, "normalize" it to the a consistent version
https://api.github.com/repos/pandas-dev/pandas/pulls/35082
2020-07-01T14:41:49Z
2020-07-01T17:07:40Z
2020-07-01T17:07:40Z
2020-07-01T17:14:03Z
TYP: stronger typing in libtimezones
diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd index 14c0523787422..2428993c45f56 100644 --- a/pandas/_libs/tslibs/timezones.pxd +++ b/pandas/_libs/tslibs/timezones.pxd @@ -14,4 +14,4 @@ cpdef object maybe_get_tz(object tz) cdef get_utcoffset(tzinfo tz, obj) cdef bint is_fixed_offset(tzinfo tz) -cdef object get_dst_info(object tz) +cdef object get_dst_info(tzinfo tz) diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index 7fbb50fcbfd41..4b8244c269828 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -116,7 +116,7 @@ def _p_tz_cache_key(tz): dst_cache = {} -cdef inline object tz_cache_key(object tz): +cdef inline object tz_cache_key(tzinfo tz): """ Return the key in the cache for the timezone info object or None if unknown. @@ -210,13 +210,16 @@ cdef int64_t[:] unbox_utcoffsets(object transinfo): # Daylight Savings -cdef object get_dst_info(object tz): +cdef object get_dst_info(tzinfo tz): """ - return a tuple of : - (UTC times of DST transitions, - UTC offsets in microseconds corresponding to DST transitions, - string of type of transitions) - + Returns + ------- + ndarray[int64_t] + Nanosecond UTC times of DST transitions. + ndarray[int64_t] + Nanosecond UTC offsets corresponding to DST transitions. + str + Desscribing the type of tzinfo object. """ cache_key = tz_cache_key(tz) if cache_key is None: @@ -225,7 +228,7 @@ cdef object get_dst_info(object tz): num = int(get_utcoffset(tz, None).total_seconds()) * 1_000_000_000 return (np.array([NPY_NAT + 1], dtype=np.int64), np.array([num], dtype=np.int64), - None) + "unknown") if cache_key not in dst_cache: if treat_tz_as_pytz(tz): @@ -267,14 +270,13 @@ cdef object get_dst_info(object tz): # (under the just-deleted code that returned empty arrays) raise AssertionError("dateutil tzinfo is not a FixedOffset " "and has an empty `_trans_list`.", tz) - else: - # static tzinfo - # TODO: This case is not hit in tests (2018-07-17); is it possible? + # static tzinfo, we can get here with pytz.StaticTZInfo + # which are not caught by treat_tz_as_pytz trans = np.array([NPY_NAT + 1], dtype=np.int64) - num = int(get_utcoffset(tz, None).total_seconds()) * 1000000000 + num = int(get_utcoffset(tz, None).total_seconds()) * 1_000_000_000 deltas = np.array([num], dtype=np.int64) - typ = 'static' + typ = "static" dst_cache[cache_key] = (trans, deltas, typ)
https://api.github.com/repos/pandas-dev/pandas/pulls/35079
2020-07-01T03:26:34Z
2020-07-01T15:28:46Z
2020-07-01T15:28:46Z
2020-07-01T15:42:29Z
BUG: DataFrameGroupBy.__getitem__ fails to propagate dropna
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 260b92b5989c1..df010c3776f7c 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -128,7 +128,7 @@ Indexing Missing ^^^^^^^ -- +- Bug in :meth:`SeriesGroupBy.transform` now correctly handles missing values for `dropna=False` (:issue:`35014`) - MultiIndex diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 740463f0cf356..1fed193dba02c 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -35,11 +35,11 @@ from pandas.util._decorators import Appender, Substitution, doc from pandas.core.dtypes.cast import ( + find_common_type, maybe_cast_result, maybe_cast_result_dtype, maybe_convert_objects, maybe_downcast_numeric, - maybe_downcast_to_dtype, ) from pandas.core.dtypes.common import ( ensure_int64, @@ -513,7 +513,6 @@ def _transform_general( """ Transform with a non-str `func`. """ - if maybe_use_numba(engine): numba_func, cache_key = generate_numba_func( func, engine_kwargs, kwargs, "groupby_transform" @@ -535,24 +534,23 @@ def _transform_general( if isinstance(res, (ABCDataFrame, ABCSeries)): res = res._values - indexer = self._get_index(name) - ser = klass(res, indexer) - results.append(ser) + results.append(klass(res, index=group.index)) # check for empty "results" to avoid concat ValueError if results: from pandas.core.reshape.concat import concat - result = concat(results).sort_index() + concatenated = concat(results) + result = self._set_result_index_ordered(concatenated) else: result = self.obj._constructor(dtype=np.float64) - # we will only try to coerce the result type if # we have a numeric dtype, as these are *always* user-defined funcs # the cython take a different path (and casting) - dtype = self._selected_obj.dtype - if is_numeric_dtype(dtype): - result = maybe_downcast_to_dtype(result, dtype) + if is_numeric_dtype(result.dtype): + common_dtype = find_common_type([self._selected_obj.dtype, result.dtype]) + if common_dtype is result.dtype: + result = maybe_downcast_numeric(result, self._selected_obj.dtype) result.name = self._selected_obj.name result.index = self._selected_obj.index diff --git a/pandas/tests/groupby/test_groupby_dropna.py b/pandas/tests/groupby/test_groupby_dropna.py index 1a525d306e9f5..adf62c4723526 100644 --- a/pandas/tests/groupby/test_groupby_dropna.py +++ b/pandas/tests/groupby/test_groupby_dropna.py @@ -162,6 +162,40 @@ def test_groupby_dropna_series_by(dropna, expected): tm.assert_series_equal(result, expected) +@pytest.mark.parametrize( + "dropna,df_expected,s_expected", + [ + pytest.param( + True, + pd.DataFrame({"B": [2, 2, 1]}), + pd.Series(data=[2, 2, 1], name="B"), + marks=pytest.mark.xfail(raises=ValueError), + ), + ( + False, + pd.DataFrame({"B": [2, 2, 1, 1]}), + pd.Series(data=[2, 2, 1, 1], name="B"), + ), + ], +) +def test_slice_groupby_then_transform(dropna, df_expected, s_expected): + # GH35014 + + df = pd.DataFrame({"A": [0, 0, 1, None], "B": [1, 2, 3, None]}) + gb = df.groupby("A", dropna=dropna) + + res = gb.transform(len) + tm.assert_frame_equal(res, df_expected) + + gb_slice = gb[["B"]] + res = gb_slice.transform(len) + tm.assert_frame_equal(res, df_expected) + + gb_slice = gb["B"] + res = gb["B"].transform(len) + tm.assert_series_equal(res, s_expected) + + @pytest.mark.parametrize( "dropna, tuples, outputs", [
- [x] closes #35014 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35078
2020-07-01T02:50:08Z
2020-08-07T21:33:06Z
2020-08-07T21:33:06Z
2020-08-07T21:53:39Z
REF: de-duplicate DST tzconversion code
diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index d5f10374d2860..d6c78cfe27ea0 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -1,17 +1,15 @@ from cpython.datetime cimport tzinfo import numpy as np -from numpy cimport ndarray, int64_t, int32_t +from numpy cimport ndarray, int64_t, int32_t, intp_t from pandas._libs.tslibs.util cimport get_nat from pandas._libs.tslibs.dtypes import Resolution from pandas._libs.tslibs.np_datetime cimport ( npy_datetimestruct, dt64_to_dtstruct) -from pandas._libs.tslibs.timezones cimport ( - is_utc, is_tzlocal, get_dst_info) from pandas._libs.tslibs.ccalendar cimport get_days_in_month -from pandas._libs.tslibs.tzconversion cimport tz_convert_utc_to_tzlocal +from pandas._libs.tslibs.tzconversion cimport Localizer # ---------------------------------------------------------------------- # Constants @@ -39,51 +37,19 @@ def get_resolution(const int64_t[:] stamps, tzinfo tz=None): Py_ssize_t i, n = len(stamps) npy_datetimestruct dts int reso = RESO_DAY, curr_reso - ndarray[int64_t] trans - int64_t[:] deltas - Py_ssize_t[:] pos - int64_t local_val, delta - - if is_utc(tz) or tz is None: - for i in range(n): - if stamps[i] == NPY_NAT: - continue - dt64_to_dtstruct(stamps[i], &dts) - curr_reso = _reso_stamp(&dts) - if curr_reso < reso: - reso = curr_reso - elif is_tzlocal(tz): - for i in range(n): - if stamps[i] == NPY_NAT: - continue - local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) - dt64_to_dtstruct(local_val, &dts) - curr_reso = _reso_stamp(&dts) - if curr_reso < reso: - reso = curr_reso - else: - # Adjust datetime64 timestamp, recompute datetimestruct - trans, deltas, typ = get_dst_info(tz) - - if typ not in ['pytz', 'dateutil']: - # static/fixed; in this case we know that len(delta) == 1 - delta = deltas[0] - for i in range(n): - if stamps[i] == NPY_NAT: - continue - dt64_to_dtstruct(stamps[i] + delta, &dts) - curr_reso = _reso_stamp(&dts) - if curr_reso < reso: - reso = curr_reso - else: - pos = trans.searchsorted(stamps, side='right') - 1 - for i in range(n): - if stamps[i] == NPY_NAT: - continue - dt64_to_dtstruct(stamps[i] + deltas[pos[i]], &dts) - curr_reso = _reso_stamp(&dts) - if curr_reso < reso: - reso = curr_reso + int64_t local_val + Localizer localizer = Localizer(tz, stamps) + + for i in range(n): + if stamps[i] == NPY_NAT: + continue + + local_val = localizer.get_local_timestamp(stamps[i], i) + + dt64_to_dtstruct(local_val, &dts) + curr_reso = _reso_stamp(&dts) + if curr_reso < reso: + reso = curr_reso return Resolution(reso) diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd index f51ee41cb99a6..aff62fa9bba52 100644 --- a/pandas/_libs/tslibs/timezones.pxd +++ b/pandas/_libs/tslibs/timezones.pxd @@ -1,5 +1,7 @@ from cpython.datetime cimport datetime, timedelta, tzinfo +from numpy cimport int64_t, intp_t, ndarray + cdef tzinfo utc_pytz cpdef bint is_utc(tzinfo tz) diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index 3b2104f75956a..8a6b7e0743e90 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -17,7 +17,7 @@ UTC = pytz.utc import numpy as np cimport numpy as cnp -from numpy cimport int64_t +from numpy cimport int64_t, intp_t, ndarray cnp.import_array() # ---------------------------------------------------------------------- @@ -192,10 +192,10 @@ cdef object _get_utc_trans_times_from_dateutil_tz(tzinfo tz): return new_trans -cdef int64_t[:] unbox_utcoffsets(object transinfo): +cdef ndarray[int64_t, ndim=1] unbox_utcoffsets(object transinfo): cdef: Py_ssize_t i, sz - int64_t[:] arr + ndarray[int64_t, ndim=1] arr sz = len(transinfo) arr = np.empty(sz, dtype='i8') @@ -209,7 +209,6 @@ cdef int64_t[:] unbox_utcoffsets(object transinfo): # ---------------------------------------------------------------------- # Daylight Savings - cdef object get_dst_info(tzinfo tz): """ Returns diff --git a/pandas/_libs/tslibs/tzconversion.pxd b/pandas/_libs/tslibs/tzconversion.pxd index 7d102868256de..3e1cbc9df0010 100644 --- a/pandas/_libs/tslibs/tzconversion.pxd +++ b/pandas/_libs/tslibs/tzconversion.pxd @@ -1,5 +1,5 @@ from cpython.datetime cimport tzinfo -from numpy cimport int64_t +from numpy cimport int64_t, intp_t, ndarray cdef int64_t tz_convert_utc_to_tzlocal(int64_t utc_val, tzinfo tz, bint* fold=*) @@ -7,3 +7,16 @@ cpdef int64_t tz_convert_single(int64_t val, tzinfo tz1, tzinfo tz2) cdef int64_t tz_localize_to_utc_single( int64_t val, tzinfo tz, object ambiguous=*, object nonexistent=* ) except? -1 + + +cdef class Localizer: + cdef: + bint use_utc, use_tzlocal, use_fixed, use_pytz + int noffsets + int64_t* utcoffsets + intp_t* positions + ndarray positions_arr # needed to avoid segfault + int64_t delta + tzinfo tz + + cdef inline int64_t get_local_timestamp(self, int64_t utc_value, Py_ssize_t i) diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index 98c40e109dbab..45dc2b1de39c3 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -29,6 +29,61 @@ from pandas._libs.tslibs.timezones cimport ( ) +cdef class Localizer: + # cdef: + # bint use_utc, use_tzlocal, use_fixed, use_pytz + # int noffsets + # int64_t* utcoffsets + # intp_t* positions + # ndarray positions_arr # needed to avoid segfault + # int64_t delta + # tzinfo tz + + def __cinit__(self, tzinfo tz, int64_t[:] values): + cdef: + ndarray[intp_t, ndim=1] pos + ndarray[int64_t, ndim=1] deltas + + self.use_utc = self.use_tzlocal = self.use_fixed = self.use_pytz = False + self.delta = NPY_NAT # placeholder + self.utcoffsets = NULL + self.positions = NULL + self.noffsets = 0 + self.tz = tz + + if tz is None or is_utc(tz): + self.use_utc = True + elif is_tzlocal(tz): + self.use_tzlocal = True + else: + trans, deltas, typ = get_dst_info(tz) + self.noffsets = len(deltas) + if typ not in ["pytz", "dateutil"]: + # Fixed Offset + self.use_fixed = True + self.delta = deltas[0] + else: + self.utcoffsets = <int64_t*>deltas.data + pos = trans.searchsorted(values, side="right") - 1 + self.positions_arr = pos + self.positions = <intp_t*>pos.data + self.use_pytz = typ == "pytz" + + cdef inline int64_t get_local_timestamp(self, int64_t utc_value, Py_ssize_t i): + cdef: + int64_t local_val + + if self.use_utc: + local_val = utc_value + elif self.use_tzlocal: + local_val = tz_convert_utc_to_tzlocal(utc_value, self.tz) + elif self.use_fixed: + local_val = utc_value + self.delta + else: + local_val = utc_value + self.utcoffsets[self.positions[i]] + return local_val + + cdef int64_t tz_localize_to_utc_single( int64_t val, tzinfo tz, object ambiguous=None, object nonexistent=None, ) except? -1:
This implements TZConvertInfo to de-duplicate a bunch of tzconversion code. This uses the new pattern on get_resolution. The other usages I intend to update in individual follow-ups in which I'll check that we have good asv coverage the affected functions. Sits on top of #35075 (actually, that was broken off of this) Perf-improving according to the newly implemented asvs: ``` $ asv continuous -E virtualenv -f 1.01 master HEAD -b resolution [...] before after ratio [559189ad] [8114413b] - 1.89±0.08μs 1.64±0.05μs 0.87 tslibs.resolution.TimeResolution.time_get_resolution('s', 1, None) ``` L50-L57 in libresolution is going to end up being repeated, should become a helper function. Doing that separately since it tentatively looks like that may have a perf hit if not done carefully. xref https://github.com/pandas-dev/pandas/commit/652a3de6f4fd4e93ee84cd4b84741f3b1e713cea#r30437889
https://api.github.com/repos/pandas-dev/pandas/pulls/35077
2020-07-01T02:18:50Z
2020-07-08T17:36:47Z
null
2021-11-20T23:22:38Z
BENCH: implement asvs for get_resolution
diff --git a/asv_bench/benchmarks/tslibs/resolution.py b/asv_bench/benchmarks/tslibs/resolution.py new file mode 100644 index 0000000000000..274aa1ad6d4a9 --- /dev/null +++ b/asv_bench/benchmarks/tslibs/resolution.py @@ -0,0 +1,50 @@ +""" +ipython analogue: + +tr = TimeResolution() +mi = pd.MultiIndex.from_product(tr.params[:-1] + ([str(x) for x in tr.params[-1]],)) +df = pd.DataFrame(np.nan, index=mi, columns=["mean", "stdev"]) + +for unit in tr.params[0]: + for size in tr.params[1]: + for tz in tr.params[2]: + tr.setup(unit, size, tz) + key = (unit, size, str(tz)) + print(key) + + val = %timeit -o tr.time_get_resolution(unit, size, tz) + + df.loc[key] = (val.average, val.stdev) + +""" +from datetime import timedelta, timezone + +from dateutil.tz import gettz, tzlocal +import numpy as np +import pytz + +from pandas._libs.tslibs.resolution import get_resolution + + +class TimeResolution: + params = ( + ["D", "h", "m", "s", "us", "ns"], + [1, 100, 10 ** 4, 10 ** 6], + [ + None, + timezone.utc, + timezone(timedelta(minutes=60)), + pytz.timezone("US/Pacific"), + gettz("Asia/Tokyo"), + tzlocal(), + ], + ) + param_names = ["unit", "size", "tz"] + + def setup(self, unit, size, tz): + arr = np.random.randint(0, 10, size=size, dtype="i8") + arr = arr.view(f"M8[{unit}]").astype("M8[ns]").view("i8") + self.i8data = arr + + def time_get_resolution(self, unit, size, tz): + get_resolution(self.i8data, tz)
https://api.github.com/repos/pandas-dev/pandas/pulls/35075
2020-06-30T22:34:26Z
2020-07-02T14:57:19Z
2020-07-02T14:57:19Z
2020-07-02T16:22:48Z
TST: Test for groupby transform on categorical column
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 60c82bf1fb71c..4de61f719dfbb 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -1509,3 +1509,53 @@ def test_aggregate_categorical_with_isnan(): index=index, ) tm.assert_frame_equal(result, expected) + + +def test_categorical_transform(): + # GH 29037 + df = pd.DataFrame( + { + "package_id": [1, 1, 1, 2, 2, 3], + "status": [ + "Waiting", + "OnTheWay", + "Delivered", + "Waiting", + "OnTheWay", + "Waiting", + ], + } + ) + + delivery_status_type = pd.CategoricalDtype( + categories=["Waiting", "OnTheWay", "Delivered"], ordered=True + ) + df["status"] = df["status"].astype(delivery_status_type) + df["last_status"] = df.groupby("package_id")["status"].transform(max) + result = df.copy() + + expected = pd.DataFrame( + { + "package_id": [1, 1, 1, 2, 2, 3], + "status": [ + "Waiting", + "OnTheWay", + "Delivered", + "Waiting", + "OnTheWay", + "Waiting", + ], + "last_status": [ + "Delivered", + "Delivered", + "Delivered", + "OnTheWay", + "OnTheWay", + "Waiting", + ], + } + ) + + expected["status"] = expected["status"].astype(delivery_status_type) + + tm.assert_frame_equal(result, expected)
Added test for groupby transform on categorical column - [x] closes #29037 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/35074
2020-06-30T22:31:58Z
2020-07-01T18:25:40Z
2020-07-01T18:25:40Z
2020-07-01T18:25:49Z
REF: de-duplicate month_offset in tslibs.fields
diff --git a/pandas/_libs/tslibs/ccalendar.pxd b/pandas/_libs/tslibs/ccalendar.pxd index b55780fe7d5b9..41cc477413607 100644 --- a/pandas/_libs/tslibs/ccalendar.pxd +++ b/pandas/_libs/tslibs/ccalendar.pxd @@ -14,3 +14,5 @@ cpdef int32_t get_day_of_year(int year, int month, int day) nogil cdef int64_t DAY_NANOS cdef int64_t HOUR_NANOS cdef dict c_MONTH_NUMBERS + +cdef int32_t* month_offset diff --git a/pandas/_libs/tslibs/ccalendar.pyx b/pandas/_libs/tslibs/ccalendar.pyx index 2006214169a74..9f8cf6c28adab 100644 --- a/pandas/_libs/tslibs/ccalendar.pyx +++ b/pandas/_libs/tslibs/ccalendar.pyx @@ -27,7 +27,7 @@ cdef int* sakamoto_arr = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4] # The first 13 entries give the month days elapsed as of the first of month N # (or the total number of days in the year for N=13) in non-leap years. # The remaining 13 entries give the days elapsed in leap years. -cdef int32_t* _month_offset = [ +cdef int32_t* month_offset = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366] @@ -242,7 +242,7 @@ cpdef int32_t get_day_of_year(int year, int month, int day) nogil: isleap = is_leapyear(year) - mo_off = _month_offset[isleap * 13 + month - 1] + mo_off = month_offset[isleap * 13 + month - 1] day_of_year = mo_off + day return day_of_year diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index 0e5a6d3c4db46..126deb67e4189 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -17,7 +17,9 @@ from pandas._libs.tslibs.ccalendar import ( from pandas._libs.tslibs.ccalendar cimport ( DAY_NANOS, get_days_in_month, is_leapyear, dayofweek, get_week_of_year, - get_day_of_year, get_iso_calendar, iso_calendar_t) + get_day_of_year, get_iso_calendar, iso_calendar_t, + month_offset, +) from pandas._libs.tslibs.np_datetime cimport ( npy_datetimestruct, pandas_timedeltastruct, dt64_to_dtstruct, td64_to_tdstruct) @@ -155,19 +157,10 @@ def get_start_end_field(const int64_t[:] dtindex, str field, int end_month = 12 int start_month = 1 ndarray[int8_t] out - ndarray[int32_t, ndim=2] _month_offset bint isleap npy_datetimestruct dts int mo_off, dom, doy, dow, ldom - _month_offset = np.array( - [ - [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365], - [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366], - ], - dtype=np.int32, - ) - out = np.zeros(count, dtype='int8') if freqstr: @@ -226,10 +219,10 @@ def get_start_end_field(const int64_t[:] dtindex, str field, dt64_to_dtstruct(dtindex[i], &dts) isleap = is_leapyear(dts.year) - mo_off = _month_offset[isleap, dts.month - 1] + mo_off = month_offset[isleap * 13 + dts.month - 1] dom = dts.day doy = mo_off + dom - ldom = _month_offset[isleap, dts.month] + ldom = month_offset[isleap * 13 + dts.month] dow = dayofweek(dts.year, dts.month, dts.day) if (ldom == doy and dow < 5) or ( @@ -244,10 +237,10 @@ def get_start_end_field(const int64_t[:] dtindex, str field, dt64_to_dtstruct(dtindex[i], &dts) isleap = is_leapyear(dts.year) - mo_off = _month_offset[isleap, dts.month - 1] + mo_off = month_offset[isleap * 13 + dts.month - 1] dom = dts.day doy = mo_off + dom - ldom = _month_offset[isleap, dts.month] + ldom = month_offset[isleap * 13 + dts.month] if ldom == doy: out[i] = 1 @@ -288,10 +281,10 @@ def get_start_end_field(const int64_t[:] dtindex, str field, dt64_to_dtstruct(dtindex[i], &dts) isleap = is_leapyear(dts.year) - mo_off = _month_offset[isleap, dts.month - 1] + mo_off = month_offset[isleap * 13 + dts.month - 1] dom = dts.day doy = mo_off + dom - ldom = _month_offset[isleap, dts.month] + ldom = month_offset[isleap * 13 + dts.month] dow = dayofweek(dts.year, dts.month, dts.day) if ((dts.month - end_month) % 3 == 0) and ( @@ -307,10 +300,10 @@ def get_start_end_field(const int64_t[:] dtindex, str field, dt64_to_dtstruct(dtindex[i], &dts) isleap = is_leapyear(dts.year) - mo_off = _month_offset[isleap, dts.month - 1] + mo_off = month_offset[isleap * 13 + dts.month - 1] dom = dts.day doy = mo_off + dom - ldom = _month_offset[isleap, dts.month] + ldom = month_offset[isleap * 13 + dts.month] if ((dts.month - end_month) % 3 == 0) and (ldom == doy): out[i] = 1 @@ -352,10 +345,10 @@ def get_start_end_field(const int64_t[:] dtindex, str field, dt64_to_dtstruct(dtindex[i], &dts) isleap = is_leapyear(dts.year) dom = dts.day - mo_off = _month_offset[isleap, dts.month - 1] + mo_off = month_offset[isleap * 13 + dts.month - 1] doy = mo_off + dom dow = dayofweek(dts.year, dts.month, dts.day) - ldom = _month_offset[isleap, dts.month] + ldom = month_offset[isleap * 13 + dts.month] if (dts.month == end_month) and ( (ldom == doy and dow < 5) or ( @@ -370,10 +363,10 @@ def get_start_end_field(const int64_t[:] dtindex, str field, dt64_to_dtstruct(dtindex[i], &dts) isleap = is_leapyear(dts.year) - mo_off = _month_offset[isleap, dts.month - 1] + mo_off = month_offset[isleap * 13 + dts.month - 1] dom = dts.day doy = mo_off + dom - ldom = _month_offset[isleap, dts.month] + ldom = month_offset[isleap * 13 + dts.month] if (dts.month == end_month) and (ldom == doy): out[i] = 1
https://api.github.com/repos/pandas-dev/pandas/pulls/35073
2020-06-30T22:27:50Z
2020-07-01T00:13:59Z
2020-07-01T00:13:59Z
2020-07-01T00:51:43Z
Add test apply dtype
diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index 8f0d3d9fbc734..114b3c0d0a3fc 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -1501,3 +1501,12 @@ def test_consistency_of_aggregates_of_columns_with_missing_values(self, df, meth tm.assert_series_equal( none_in_first_column_result, none_in_second_column_result ) + + @pytest.mark.parametrize("col", [1, 1.0, True, "a", np.nan]) + def test_apply_dtype(self, col): + # GH 31466 + df = pd.DataFrame([[1.0, col]], columns=["a", "b"]) + result = df.apply(lambda x: x.dtype) + expected = df.dtypes + + tm.assert_series_equal(result, expected)
- [x] closes #31466 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35072
2020-06-30T22:19:14Z
2020-07-01T16:53:35Z
2020-07-01T16:53:34Z
2020-07-01T21:11:57Z
CLN: remove unnecessary get_timezone calls
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 884715f482cad..c1162ed482048 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -27,7 +27,7 @@ from pandas._libs.tslibs.util cimport ( from pandas._libs.tslibs.timezones cimport ( is_utc, is_tzlocal, is_fixed_offset, get_utcoffset, get_dst_info, - get_timezone, maybe_get_tz, tz_compare, + maybe_get_tz, tz_compare, utc_pytz as UTC, ) from pandas._libs.tslibs.parsing import parse_datetime_string @@ -267,7 +267,7 @@ def datetime_to_datetime64(ndarray[object] values): if not tz_compare(val.tzinfo, inferred_tz): raise ValueError('Array must be all same time zone') else: - inferred_tz = get_timezone(val.tzinfo) + inferred_tz = val.tzinfo _ts = convert_datetime_to_tsobject(val, None) iresult[i] = _ts.value diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index 925b3c5615435..a096b2807c640 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -20,8 +20,7 @@ from pandas._libs.tslibs.ccalendar cimport DAY_NANOS, HOUR_NANOS from pandas._libs.tslibs.nattype cimport NPY_NAT from pandas._libs.tslibs.np_datetime cimport ( npy_datetimestruct, dt64_to_dtstruct) -from pandas._libs.tslibs.timezones cimport ( - get_dst_info, is_tzlocal, is_utc, get_timezone) +from pandas._libs.tslibs.timezones cimport get_dst_info, is_tzlocal, is_utc # TODO: cdef scalar version to call from convert_str_to_tsobject @@ -358,13 +357,13 @@ cpdef int64_t tz_convert_single(int64_t val, tzinfo tz1, tzinfo tz2): # Convert to UTC if is_tzlocal(tz1): utc_date = _tz_convert_tzlocal_utc(val, tz1, to_utc=True) - elif not is_utc(get_timezone(tz1)): + elif not is_utc(tz1): arr[0] = val utc_date = _tz_convert_dst(arr, tz1, to_utc=True)[0] else: utc_date = val - if is_utc(get_timezone(tz2)): + if is_utc(tz2): return utc_date elif is_tzlocal(tz2): return _tz_convert_tzlocal_utc(utc_date, tz2, to_utc=False)
https://api.github.com/repos/pandas-dev/pandas/pulls/35071
2020-06-30T22:10:02Z
2020-07-01T00:12:55Z
2020-07-01T00:12:55Z
2020-07-01T00:50:32Z
PERF: _maybe_convert_value_to_local
diff --git a/asv_bench/benchmarks/tslibs/timestamp.py b/asv_bench/benchmarks/tslibs/timestamp.py index 3ef9b814dd79e..b7e11089535d7 100644 --- a/asv_bench/benchmarks/tslibs/timestamp.py +++ b/asv_bench/benchmarks/tslibs/timestamp.py @@ -63,9 +63,6 @@ def time_tz(self, tz, freq): def time_dayofweek(self, tz, freq): self.ts.dayofweek - def time_weekday_name(self, tz, freq): - self.ts.day_name - def time_dayofyear(self, tz, freq): self.ts.dayofyear @@ -108,6 +105,9 @@ def time_microsecond(self, tz, freq): def time_month_name(self, tz, freq): self.ts.month_name() + def time_weekday_name(self, tz, freq): + self.ts.day_name() + class TimestampOps: params = [None, "US/Eastern", pytz.UTC, dateutil.tz.tzutc()] diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 15fcfc742ecf3..5d3a0d490ada6 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -47,6 +47,7 @@ from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT from pandas._libs.tslibs.np_datetime cimport ( check_dts_bounds, npy_datetimestruct, dt64_to_dtstruct, cmp_scalar, + pydatetime_to_dt64, ) from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime from pandas._libs.tslibs.offsets cimport to_offset, is_tick_object, is_offset_object @@ -447,9 +448,13 @@ cdef class _Timestamp(ABCTimestamp): """Convert UTC i8 value to local i8 value if tz exists""" cdef: int64_t val - val = self.value - if self.tz is not None and not is_utc(self.tz): - val = tz_convert_single(self.value, UTC, self.tz) + tzinfo own_tz = self.tzinfo + npy_datetimestruct dts + + if own_tz is not None and not is_utc(own_tz): + val = pydatetime_to_dt64(self, &dts) + self.nanosecond + else: + val = self.value return val cdef bint _get_start_end_field(self, str field):
Also fixes an incorrect asv. ``` In [2]: ts = pd.Timestamp.now("US/Pacific") In [3]: %timeit ts.day_name() 9.13 µs ± 309 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) # <-- PR 26.4 µs ± 1.23 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- master ```
https://api.github.com/repos/pandas-dev/pandas/pulls/35070
2020-06-30T21:34:39Z
2020-06-30T23:26:29Z
2020-06-30T23:26:29Z
2020-07-01T00:52:20Z
PERF: Timestamp.normalize
diff --git a/asv_bench/benchmarks/tslibs/timestamp.py b/asv_bench/benchmarks/tslibs/timestamp.py index b7e11089535d7..40f8e561f5238 100644 --- a/asv_bench/benchmarks/tslibs/timestamp.py +++ b/asv_bench/benchmarks/tslibs/timestamp.py @@ -1,17 +1,29 @@ -import datetime +from datetime import datetime, timedelta, timezone -import dateutil +from dateutil.tz import gettz, tzlocal, tzutc import numpy as np import pytz from pandas import Timestamp +# One case for each type of tzinfo object that has its own code path +# in tzconversion code. +_tzs = [ + None, + pytz.timezone("Europe/Amsterdam"), + gettz("US/Central"), + pytz.UTC, + tzutc(), + timezone(timedelta(minutes=60)), + tzlocal(), +] + class TimestampConstruction: def setup(self): self.npdatetime64 = np.datetime64("2020-01-01 00:00:00") - self.dttime_unaware = datetime.datetime(2020, 1, 1, 0, 0, 0) - self.dttime_aware = datetime.datetime(2020, 1, 1, 0, 0, 0, 0, pytz.UTC) + self.dttime_unaware = datetime(2020, 1, 1, 0, 0, 0) + self.dttime_aware = datetime(2020, 1, 1, 0, 0, 0, 0, pytz.UTC) self.ts = Timestamp("2020-01-01 00:00:00") def time_parse_iso8601_no_tz(self): @@ -49,7 +61,6 @@ def time_from_pd_timestamp(self): class TimestampProperties: - _tzs = [None, pytz.timezone("Europe/Amsterdam"), pytz.UTC, dateutil.tz.tzutc()] _freqs = [None, "B"] params = [_tzs, _freqs] param_names = ["tz", "freq"] @@ -110,7 +121,7 @@ def time_weekday_name(self, tz, freq): class TimestampOps: - params = [None, "US/Eastern", pytz.UTC, dateutil.tz.tzutc()] + params = _tzs param_names = ["tz"] def setup(self, tz): @@ -148,7 +159,7 @@ def time_ceil(self, tz): class TimestampAcrossDst: def setup(self): - dt = datetime.datetime(2016, 3, 27, 1) + dt = datetime(2016, 3, 27, 1) self.tzinfo = pytz.timezone("CET").localize(dt, is_dst=False).tzinfo self.ts2 = Timestamp(dt) diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index 94f6d1d9020d2..623d9f14d646b 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -26,3 +26,4 @@ cpdef datetime localize_pydatetime(datetime dt, object tz) cdef int64_t cast_from_unit(object ts, str unit) except? -1 cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo tz) +cdef int64_t normalize_i8_stamp(int64_t local_val) nogil diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 884715f482cad..5da873a0d1c02 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -795,14 +795,14 @@ cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo t result[i] = NPY_NAT continue local_val = stamps[i] - result[i] = _normalize_i8_stamp(local_val) + result[i] = normalize_i8_stamp(local_val) elif is_tzlocal(tz): for i in range(n): if stamps[i] == NPY_NAT: result[i] = NPY_NAT continue local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) - result[i] = _normalize_i8_stamp(local_val) + result[i] = normalize_i8_stamp(local_val) else: # Adjust datetime64 timestamp, recompute datetimestruct trans, deltas, typ = get_dst_info(tz) @@ -815,7 +815,7 @@ cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo t result[i] = NPY_NAT continue local_val = stamps[i] + delta - result[i] = _normalize_i8_stamp(local_val) + result[i] = normalize_i8_stamp(local_val) else: pos = trans.searchsorted(stamps, side='right') - 1 for i in range(n): @@ -823,13 +823,13 @@ cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo t result[i] = NPY_NAT continue local_val = stamps[i] + deltas[pos[i]] - result[i] = _normalize_i8_stamp(local_val) + result[i] = normalize_i8_stamp(local_val) return result.base # `.base` to access underlying ndarray @cython.cdivision -cdef inline int64_t _normalize_i8_stamp(int64_t local_val) nogil: +cdef inline int64_t normalize_i8_stamp(int64_t local_val) nogil: """ Round the localized nanosecond timestamp down to the previous midnight. diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 159e4366d1f3f..ba6cee3d7ad8e 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -40,7 +40,7 @@ from pandas._libs.tslibs.conversion cimport ( _TSObject, convert_to_tsobject, convert_datetime_to_tsobject, - normalize_i8_timestamps, + normalize_i8_stamp, ) from pandas._libs.tslibs.fields import get_start_end_field, get_date_name_field from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT @@ -553,6 +553,20 @@ cdef class _Timestamp(ABCTimestamp): """ return ccalendar.get_days_in_month(self.year, self.month) + # ----------------------------------------------------------------- + # Transformation Methods + + def normalize(self) -> "Timestamp": + """ + Normalize Timestamp to midnight, preserving tz information. + """ + cdef: + local_val = self._maybe_convert_value_to_local() + int64_t normalized + + normalized = normalize_i8_stamp(local_val) + return Timestamp(normalized).tz_localize(self.tzinfo) + # ----------------------------------------------------------------- # Pickle Methods @@ -1455,18 +1469,6 @@ default 'raise' self.nanosecond / 3600.0 / 1e+9 ) / 24.0) - def normalize(self): - """ - Normalize Timestamp to midnight, preserving tz information. - """ - cdef: - ndarray[int64_t] normalized - tzinfo own_tz = self.tzinfo # could be None - - normalized = normalize_i8_timestamps( - np.array([self.value], dtype="i8"), tz=own_tz) - return Timestamp(normalized[0]).tz_localize(own_tz) - # Aliases Timestamp.weekofyear = Timestamp.week
The perf is actually a wash here, verging on slightly negative. The really worthwhile thing is the improved asvs. The big perf gain is being split into a separate PR that optimizes _maybe_convert_value_to_local to the tune of 40%.
https://api.github.com/repos/pandas-dev/pandas/pulls/35068
2020-06-30T20:24:44Z
2020-07-01T01:40:42Z
2020-07-01T01:40:42Z
2020-07-01T01:47:16Z
CLN: type tz kwarg in create_timestamp_from_ts
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 44693d60486a9..f494e74bde55f 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -8,6 +8,7 @@ from cpython.datetime cimport ( datetime, time, timedelta, + tzinfo, ) # import datetime C API PyDateTime_IMPORT @@ -77,9 +78,9 @@ from pandas._libs.missing cimport checknull_with_nat_and_na cdef inline object create_datetime_from_ts( int64_t value, npy_datetimestruct dts, - object tz, + tzinfo tz, object freq, - bint fold + bint fold, ): """ Convenience routine to construct a datetime.datetime from its parts. @@ -92,7 +93,7 @@ cdef inline object create_datetime_from_ts( cdef inline object create_date_from_ts( int64_t value, npy_datetimestruct dts, - object tz, + tzinfo tz, object freq, bint fold ): @@ -106,7 +107,7 @@ cdef inline object create_date_from_ts( cdef inline object create_time_from_ts( int64_t value, npy_datetimestruct dts, - object tz, + tzinfo tz, object freq, bint fold ): @@ -120,7 +121,7 @@ cdef inline object create_time_from_ts( @cython.boundscheck(False) def ints_to_pydatetime( const int64_t[:] arr, - object tz=None, + tzinfo tz=None, object freq=None, bint fold=False, str box="datetime" @@ -162,7 +163,7 @@ def ints_to_pydatetime( str typ int64_t value, delta, local_value ndarray[object] result = np.empty(n, dtype=object) - object (*func_create)(int64_t, npy_datetimestruct, object, object, bint) + object (*func_create)(int64_t, npy_datetimestruct, tzinfo, object, bint) if box == "date": assert (tz is None), "tz should be None when converting to date" @@ -178,7 +179,9 @@ def ints_to_pydatetime( elif box == "datetime": func_create = create_datetime_from_ts else: - raise ValueError("box must be one of 'datetime', 'date', 'time' or 'timestamp'") + raise ValueError( + "box must be one of 'datetime', 'date', 'time' or 'timestamp'" + ) if is_utc(tz) or tz is None: for i in range(n): diff --git a/pandas/_libs/tslibs/timestamps.pxd b/pandas/_libs/tslibs/timestamps.pxd index 27b659980e526..307b6dfc90715 100644 --- a/pandas/_libs/tslibs/timestamps.pxd +++ b/pandas/_libs/tslibs/timestamps.pxd @@ -1,4 +1,4 @@ -from cpython.datetime cimport datetime +from cpython.datetime cimport datetime, tzinfo from numpy cimport int64_t @@ -8,7 +8,7 @@ from pandas._libs.tslibs.np_datetime cimport npy_datetimestruct cdef object create_timestamp_from_ts(int64_t value, npy_datetimestruct dts, - object tz, object freq, bint fold) + tzinfo tz, object freq, bint fold) cdef class _Timestamp(ABCTimestamp): diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 15fcfc742ecf3..355dc0dbc5820 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -69,7 +69,7 @@ _no_input = object() cdef inline object create_timestamp_from_ts(int64_t value, npy_datetimestruct dts, - object tz, object freq, bint fold): + tzinfo tz, object freq, bint fold): """ convenience routine to construct a Timestamp from its parts """ cdef _Timestamp ts_base ts_base = _Timestamp.__new__(Timestamp, dts.year, dts.month,
Perf is indistinguishable
https://api.github.com/repos/pandas-dev/pandas/pulls/35067
2020-06-30T20:17:05Z
2020-06-30T21:58:44Z
2020-06-30T21:58:44Z
2020-06-30T22:09:05Z
DOC: Remove mypy from pre commit
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b7fd797fb7230..fcd0ecdc9fcd2 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -30,15 +30,3 @@ repos: - id: isort language: python_venv exclude: ^pandas/__init__\.py$|^pandas/core/api\.py$ -- repo: https://github.com/pre-commit/mirrors-mypy - rev: v0.730 - hooks: - - id: mypy - args: - # As long as a some files are excluded from check-untyped-defs - # we have to exclude it from the pre-commit hook as the configuration - # is based on modules but the hook runs on files. - - --no-check-untyped-defs - - --follow-imports - - skip - files: pandas/
- [x] closes #34902 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/35066
2020-06-30T19:08:56Z
2020-09-01T11:42:05Z
2020-09-01T11:42:04Z
2020-09-01T11:42:05Z
CLN: type get_resolution tz as tzinfo
diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index 4dbecc76ad986..d5f10374d2860 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -1,3 +1,4 @@ +from cpython.datetime cimport tzinfo import numpy as np from numpy cimport ndarray, int64_t, int32_t @@ -8,7 +9,7 @@ from pandas._libs.tslibs.dtypes import Resolution from pandas._libs.tslibs.np_datetime cimport ( npy_datetimestruct, dt64_to_dtstruct) from pandas._libs.tslibs.timezones cimport ( - is_utc, is_tzlocal, maybe_get_tz, get_dst_info) + is_utc, is_tzlocal, get_dst_info) from pandas._libs.tslibs.ccalendar cimport get_days_in_month from pandas._libs.tslibs.tzconversion cimport tz_convert_utc_to_tzlocal @@ -33,7 +34,7 @@ cdef: # ---------------------------------------------------------------------- -def get_resolution(const int64_t[:] stamps, tz=None): +def get_resolution(const int64_t[:] stamps, tzinfo tz=None): cdef: Py_ssize_t i, n = len(stamps) npy_datetimestruct dts @@ -43,9 +44,6 @@ def get_resolution(const int64_t[:] stamps, tz=None): Py_ssize_t[:] pos int64_t local_val, delta - if tz is not None: - tz = maybe_get_tz(tz) - if is_utc(tz) or tz is None: for i in range(n): if stamps[i] == NPY_NAT: diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index 6e6b106b8f21a..925b3c5615435 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -21,7 +21,7 @@ from pandas._libs.tslibs.nattype cimport NPY_NAT from pandas._libs.tslibs.np_datetime cimport ( npy_datetimestruct, dt64_to_dtstruct) from pandas._libs.tslibs.timezones cimport ( - get_dst_info, is_tzlocal, is_utc, get_timezone, get_utcoffset) + get_dst_info, is_tzlocal, is_utc, get_timezone) # TODO: cdef scalar version to call from convert_str_to_tsobject
https://api.github.com/repos/pandas-dev/pandas/pulls/35065
2020-06-30T19:07:11Z
2020-06-30T21:05:52Z
2020-06-30T21:05:52Z
2020-06-30T21:23:41Z
Assorted ujson Cleanups
diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c index 1de9642761961..e841f00489887 100644 --- a/pandas/_libs/src/ujson/python/objToJSON.c +++ b/pandas/_libs/src/ujson/python/objToJSON.c @@ -324,19 +324,6 @@ static npy_float64 total_seconds(PyObject *td) { return double_val; } -static PyObject *get_item(PyObject *obj, Py_ssize_t i) { - PyObject *tmp = PyLong_FromSsize_t(i); - PyObject *ret; - - if (tmp == 0) { - return 0; - } - ret = PyObject_GetItem(obj, tmp); - Py_DECREF(tmp); - - return ret; -} - static char *PyBytesToUTF8(JSOBJ _obj, JSONTypeContext *Py_UNUSED(tc), size_t *_outLen) { PyObject *obj = (PyObject *)_obj; @@ -704,7 +691,6 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { PdBlockContext *blkCtxt; NpyArrContext *npyarr; Py_ssize_t i; - PyArray_Descr *dtype; NpyIter *iter; NpyIter_IterNextFunc *iternext; npy_int64 **dataptr; @@ -712,10 +698,6 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { npy_intp idx; PRINTMARK(); - - i = 0; - blocks = NULL; - dtype = PyArray_DescrFromType(NPY_INT64); obj = (PyObject *)_obj; GET_TC(tc)->iterGetName = GET_TC(tc)->transpose @@ -726,7 +708,7 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { if (!blkCtxt) { PyErr_NoMemory(); GET_TC(tc)->iterNext = NpyArr_iterNextNone; - goto BLKRET; + return; } GET_TC(tc)->pdblock = blkCtxt; @@ -739,7 +721,7 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { blkCtxt->cindices = NULL; GET_TC(tc)->iterNext = NpyArr_iterNextNone; - goto BLKRET; + return; } blkCtxt->npyCtxts = @@ -747,30 +729,30 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { if (!blkCtxt->npyCtxts) { PyErr_NoMemory(); GET_TC(tc)->iterNext = NpyArr_iterNextNone; - goto BLKRET; - } - for (i = 0; i < blkCtxt->ncols; i++) { - blkCtxt->npyCtxts[i] = NULL; + return; } blkCtxt->cindices = PyObject_Malloc(sizeof(int) * blkCtxt->ncols); if (!blkCtxt->cindices) { PyErr_NoMemory(); GET_TC(tc)->iterNext = NpyArr_iterNextNone; - goto BLKRET; + return; } blocks = get_sub_attr(obj, "_mgr", "blocks"); if (!blocks) { GET_TC(tc)->iterNext = NpyArr_iterNextNone; - goto BLKRET; + return; + } else if (!PyTuple_Check(blocks)) { + PyErr_SetString(PyExc_TypeError, "blocks must be a tuple!"); + goto BLKRET; } // force transpose so each NpyArrContext strides down its column GET_TC(tc)->transpose = 1; for (i = 0; i < PyObject_Length(blocks); i++) { - block = get_item(blocks, i); + block = PyTuple_GET_ITEM(blocks, i); if (!block) { GET_TC(tc)->iterNext = NpyArr_iterNextNone; goto BLKRET; @@ -779,7 +761,6 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { tmp = PyObject_CallMethod(block, "get_block_values_for_json", NULL); if (!tmp) { ((JSONObjectEncoder *)tc->encoder)->errorMsg = ""; - Py_DECREF(block); GET_TC(tc)->iterNext = NpyArr_iterNextNone; goto BLKRET; } @@ -787,23 +768,20 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { values = PyArray_Transpose((PyArrayObject *)tmp, NULL); Py_DECREF(tmp); if (!values) { - Py_DECREF(block); GET_TC(tc)->iterNext = NpyArr_iterNextNone; goto BLKRET; } locs = (PyArrayObject *)get_sub_attr(block, "mgr_locs", "as_array"); if (!locs) { - Py_DECREF(block); Py_DECREF(values); GET_TC(tc)->iterNext = NpyArr_iterNextNone; goto BLKRET; } iter = NpyIter_New(locs, NPY_ITER_READONLY, NPY_KEEPORDER, - NPY_NO_CASTING, dtype); + NPY_NO_CASTING, NULL); if (!iter) { - Py_DECREF(block); Py_DECREF(values); Py_DECREF(locs); GET_TC(tc)->iterNext = NpyArr_iterNextNone; @@ -812,7 +790,6 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { iternext = NpyIter_GetIterNext(iter, NULL); if (!iternext) { NpyIter_Deallocate(iter); - Py_DECREF(block); Py_DECREF(values); Py_DECREF(locs); GET_TC(tc)->iterNext = NpyArr_iterNextNone; @@ -846,15 +823,13 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { } while (iternext(iter)); NpyIter_Deallocate(iter); - Py_DECREF(block); Py_DECREF(values); Py_DECREF(locs); } GET_TC(tc)->npyarr = blkCtxt->npyCtxts[0]; BLKRET: - Py_XDECREF(dtype); - Py_XDECREF(blocks); + Py_DECREF(blocks); } void PdBlock_iterEnd(JSOBJ obj, JSONTypeContext *tc) {
I think it would be great if we could move the block iteration out of JSON as it has generic functionality that we could use down in C. This isn't it, but a small set of cleanups I noticed while looking at that
https://api.github.com/repos/pandas-dev/pandas/pulls/35064
2020-06-30T18:05:02Z
2020-07-01T15:22:49Z
2020-07-01T15:22:49Z
2020-07-01T15:23:26Z
ENH: support index=True/False keyword for io.sql.get_schema
diff --git a/doc/source/reference/io.rst b/doc/source/reference/io.rst index 0037d4a4410c3..9502d319075ce 100644 --- a/doc/source/reference/io.rst +++ b/doc/source/reference/io.rst @@ -126,6 +126,7 @@ SQL read_sql_table read_sql_query read_sql + io.sql.get_schema Google BigQuery ~~~~~~~~~~~~~~~ diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 3c436b55c19c2..0558f296a2a08 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -730,6 +730,7 @@ I/O - :meth:`read_fwf` was inferring compression with ``compression=None`` which was not consistent with the other :meth:``read_*`` functions (:issue:`37909`) - :meth:`DataFrame.to_html` was ignoring ``formatters`` argument for ``ExtensionDtype`` columns (:issue:`36525`) - Bumped minimum xarray version to 0.12.3 to avoid reference to the removed ``Panel`` class (:issue:`27101`) +- :meth:`~pandas.io.sql.get_schema` now accepts ``index`` parameter to include index of the DataFrame in the schema (:issue:`9084`) Period ^^^^^^ diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 5678133d5a706..c766c04224cec 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -1462,12 +1462,13 @@ def _create_sql_schema( keys: Optional[List[str]] = None, dtype: Optional[dict] = None, schema: Optional[str] = None, + index: Optional[bool] = False, ): table = SQLTable( table_name, self, frame=frame, - index=False, + index=index, keys=keys, dtype=dtype, schema=schema, @@ -1862,12 +1863,20 @@ def drop_table(self, name, schema=None): drop_sql = f"DROP TABLE {_get_valid_sqlite_name(name)}" self.execute(drop_sql) - def _create_sql_schema(self, frame, table_name, keys=None, dtype=None, schema=None): + def _create_sql_schema( + self, + frame, + table_name, + keys=None, + dtype=None, + schema=None, + index=False, + ): table = SQLiteTable( table_name, self, frame=frame, - index=False, + index=index, keys=keys, dtype=dtype, schema=schema, @@ -1875,7 +1884,7 @@ def _create_sql_schema(self, frame, table_name, keys=None, dtype=None, schema=No return str(table.sql_schema()) -def get_schema(frame, name, keys=None, con=None, dtype=None, schema=None): +def get_schema(frame, name, keys=None, con=None, dtype=None, schema=None, index=False): """ Get the SQL db table schema for the given frame. @@ -1886,19 +1895,28 @@ def get_schema(frame, name, keys=None, con=None, dtype=None, schema=None): name of SQL table keys : string or sequence, default: None columns to use a primary key - con: an open SQL database connection object or a SQLAlchemy connectable + con : an open SQL database connection object or a SQLAlchemy connectable Using SQLAlchemy makes it possible to use any DB supported by that library, default: None If a DBAPI2 object, only sqlite3 is supported. dtype : dict of column name to SQL type, default None Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type, or a string for sqlite3 fallback connection. - schema: str, default: None + schema : str, default: None Optional specifying the schema to be used in creating the table. .. versionadded:: 1.2.0 + index : boolean, default: False + Whether to include the index of the DataFrame in the sql schema. + + .. versionadded:: 1.2.0 + + Returns + ------- + string + The SQL schema for the given frame. """ pandas_sql = pandasSQL_builder(con=con) return pandas_sql._create_sql_schema( - frame, name, keys=keys, dtype=dtype, schema=schema + frame, name, keys=keys, dtype=dtype, schema=schema, index=index ) diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 0195b61d13798..86b1f7a2bea3c 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -894,6 +894,20 @@ def test_get_schema_keys(self): constraint_sentence = 'CONSTRAINT test_pk PRIMARY KEY ("A", "B")' assert constraint_sentence in create_sql + def test_get_schema_with_index(self): + # GH 9084 + df = DataFrame({"one": [1, 2, 3], "two": [1, 2, 3]}, index=list("abc")) + + schema_without_index = sql.get_schema(df, "test", con=self.conn) + assert "index TEXT" not in schema_without_index + + schema_with_index = sql.get_schema(df, "test", index=True, con=self.conn) + assert '"index" TEXT' in schema_with_index + + df.index.name = "new_index" + schema_with_index_rename = sql.get_schema(df, "test", index=True, con=self.conn) + assert df.index.name in schema_with_index_rename + def test_chunksize_read(self): df = DataFrame(np.random.randn(22, 5), columns=list("abcde")) df.to_sql("test_chunksize", self.conn, index=False)
- [x] closes #9084 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35063
2020-06-30T18:04:42Z
2021-02-11T01:33:00Z
null
2022-11-18T02:21:00Z
CLN: collect Timestamp methods
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 15fcfc742ecf3..9af31c64658d6 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -265,37 +265,6 @@ cdef class _Timestamp(ABCTimestamp): self._assert_tzawareness_compat(ots) return cmp_scalar(self.value, ots.value, op) - def __reduce_ex__(self, protocol): - # python 3.6 compat - # https://bugs.python.org/issue28730 - # now __reduce_ex__ is defined and higher priority than __reduce__ - return self.__reduce__() - - def __repr__(self) -> str: - stamp = self._repr_base - zone = None - - try: - stamp += self.strftime('%z') - if self.tzinfo: - zone = get_timezone(self.tzinfo) - except ValueError: - year2000 = self.replace(year=2000) - stamp += year2000.strftime('%z') - if self.tzinfo: - zone = get_timezone(self.tzinfo) - - try: - stamp += zone.strftime(' %%Z') - except AttributeError: - # e.g. tzlocal has no `strftime` - pass - - tz = f", tz='{zone}'" if zone is not None else "" - freq = "" if self.freq is None else f", freq='{self.freqstr}'" - - return f"Timestamp('{stamp}'{tz}{freq})" - cdef bint _compare_outside_nanorange(_Timestamp self, datetime other, int op) except -1: cdef: @@ -312,46 +281,6 @@ cdef class _Timestamp(ABCTimestamp): elif other.tzinfo is None: raise TypeError('Cannot compare tz-naive and tz-aware timestamps') - cpdef datetime to_pydatetime(_Timestamp self, bint warn=True): - """ - Convert a Timestamp object to a native Python datetime object. - - If warn=True, issue a warning if nanoseconds is nonzero. - """ - if self.nanosecond != 0 and warn: - warnings.warn("Discarding nonzero nanoseconds in conversion", - UserWarning, stacklevel=2) - - return datetime(self.year, self.month, self.day, - self.hour, self.minute, self.second, - self.microsecond, self.tzinfo) - - cpdef to_datetime64(self): - """ - Return a numpy.datetime64 object with 'ns' precision. - """ - return np.datetime64(self.value, 'ns') - - def to_numpy(self, dtype=None, copy=False) -> np.datetime64: - """ - Convert the Timestamp to a NumPy datetime64. - - .. versionadded:: 0.25.0 - - This is an alias method for `Timestamp.to_datetime64()`. The dtype and - copy parameters are available here only for compatibility. Their values - will not affect the return value. - - Returns - ------- - numpy.datetime64 - - See Also - -------- - DatetimeIndex.to_numpy : Similar method for DatetimeIndex. - """ - return self.to_datetime64() - def __add__(self, other): cdef: int64_t nanos = 0 @@ -619,9 +548,69 @@ cdef class _Timestamp(ABCTimestamp): """ return ccalendar.get_days_in_month(self.year, self.month) + # ----------------------------------------------------------------- + # Pickle Methods + + def __reduce_ex__(self, protocol): + # python 3.6 compat + # https://bugs.python.org/issue28730 + # now __reduce_ex__ is defined and higher priority than __reduce__ + return self.__reduce__() + + def __setstate__(self, state): + self.value = state[0] + self.freq = state[1] + self.tzinfo = state[2] + + def __reduce__(self): + object_state = self.value, self.freq, self.tzinfo + return (Timestamp, object_state) + # ----------------------------------------------------------------- # Rendering Methods + def isoformat(self, sep: str = "T") -> str: + base = super(_Timestamp, self).isoformat(sep=sep) + if self.nanosecond == 0: + return base + + if self.tzinfo is not None: + base1, base2 = base[:-6], base[-6:] + else: + base1, base2 = base, "" + + if self.microsecond != 0: + base1 += f"{self.nanosecond:03d}" + else: + base1 += f".{self.nanosecond:09d}" + + return base1 + base2 + + def __repr__(self) -> str: + stamp = self._repr_base + zone = None + + try: + stamp += self.strftime('%z') + if self.tzinfo: + zone = get_timezone(self.tzinfo) + except ValueError: + year2000 = self.replace(year=2000) + stamp += year2000.strftime('%z') + if self.tzinfo: + zone = get_timezone(self.tzinfo) + + try: + stamp += zone.strftime(' %%Z') + except AttributeError: + # e.g. tzlocal has no `strftime` + pass + + tz = f", tz='{zone}'" if zone is not None else "" + freq = "" if self.freq is None else f", freq='{self.freqstr}'" + + return f"Timestamp('{stamp}'{tz}{freq})" + @property def _repr_base(self) -> str: return f"{self._date_repr} {self._time_repr}" @@ -656,6 +645,7 @@ cdef class _Timestamp(ABCTimestamp): return self._repr_base # ----------------------------------------------------------------- + # Conversion Methods @property def asm8(self) -> np.datetime64: @@ -670,6 +660,64 @@ cdef class _Timestamp(ABCTimestamp): # Note: Naive timestamps will not match datetime.stdlib return round(self.value / 1e9, 6) + cpdef datetime to_pydatetime(_Timestamp self, bint warn=True): + """ + Convert a Timestamp object to a native Python datetime object. + + If warn=True, issue a warning if nanoseconds is nonzero. + """ + if self.nanosecond != 0 and warn: + warnings.warn("Discarding nonzero nanoseconds in conversion", + UserWarning, stacklevel=2) + + return datetime(self.year, self.month, self.day, + self.hour, self.minute, self.second, + self.microsecond, self.tzinfo) + + cpdef to_datetime64(self): + """ + Return a numpy.datetime64 object with 'ns' precision. + """ + return np.datetime64(self.value, "ns") + + def to_numpy(self, dtype=None, copy=False) -> np.datetime64: + """ + Convert the Timestamp to a NumPy datetime64. + + .. versionadded:: 0.25.0 + + This is an alias method for `Timestamp.to_datetime64()`. The dtype and + copy parameters are available here only for compatibility. Their values + will not affect the return value. + + Returns + ------- + numpy.datetime64 + + See Also + -------- + DatetimeIndex.to_numpy : Similar method for DatetimeIndex. + """ + return self.to_datetime64() + + def to_period(self, freq=None): + """ + Return an period of which this timestamp is an observation. + """ + from pandas import Period + + if self.tz is not None: + # GH#21333 + warnings.warn( + "Converting to Period representation will drop timezone information.", + UserWarning, + ) + + if freq is None: + freq = self.freq + + return Period(self, freq=freq) + # ---------------------------------------------------------------------- @@ -1156,33 +1204,6 @@ timedelta}, default 'raise' "Use tz_localize() or tz_convert() as appropriate" ) - def __setstate__(self, state): - self.value = state[0] - self.freq = state[1] - self.tzinfo = state[2] - - def __reduce__(self): - object_state = self.value, self.freq, self.tzinfo - return (Timestamp, object_state) - - def to_period(self, freq=None): - """ - Return an period of which this timestamp is an observation. - """ - from pandas import Period - - if self.tz is not None: - # GH#21333 - warnings.warn( - "Converting to Period representation will drop timezone information.", - UserWarning, - ) - - if freq is None: - freq = self.freq - - return Period(self, freq=freq) - @property def freqstr(self): """ @@ -1404,23 +1425,6 @@ default 'raise' return create_timestamp_from_ts(value, dts, _tzinfo, self.freq, fold) - def isoformat(self, sep='T'): - base = super(_Timestamp, self).isoformat(sep=sep) - if self.nanosecond == 0: - return base - - if self.tzinfo is not None: - base1, base2 = base[:-6], base[-6:] - else: - base1, base2 = base, "" - - if self.microsecond != 0: - base1 += f"{self.nanosecond:03d}" - else: - base1 += f".{self.nanosecond:09d}" - - return base1 + base2 - def to_julian_date(self) -> np.float64: """ Convert TimeStamp to a Julian Date.
https://api.github.com/repos/pandas-dev/pandas/pulls/35062
2020-06-30T14:17:22Z
2020-06-30T22:49:53Z
2020-06-30T22:49:53Z
2020-07-01T00:57:22Z
Fixed #34859: Added support for '0' and '1' in BooleanArray._from_sequence_of_strings method
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 040253ebe7279..74dca91636577 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -328,6 +328,7 @@ Other enhancements - :meth:`DataFrame.to_html` and :meth:`DataFrame.to_string`'s ``col_space`` parameter now accepts a list or dict to change only some specific columns' width (:issue:`28917`). - :meth:`DataFrame.to_excel` can now also write OpenOffice spreadsheet (.ods) files (:issue:`27222`) - :meth:`~Series.explode` now accepts ``ignore_index`` to reset the index, similarly to :meth:`pd.concat` or :meth:`DataFrame.sort_values` (:issue:`34932`). +- :meth:`read_csv` now accepts string values like "0", "0.0", "1", "1.0" as convertible to the nullable boolean dtype (:issue:`34859`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 9f1c2c6e668ad..dbce71b77a425 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -286,9 +286,9 @@ def _from_sequence_of_strings( def map_string(s): if isna(s): return s - elif s in ["True", "TRUE", "true"]: + elif s in ["True", "TRUE", "true", "1", "1.0"]: return True - elif s in ["False", "FALSE", "false"]: + elif s in ["False", "FALSE", "false", "0", "0.0"]: return False else: raise ValueError(f"{s} cannot be cast to bool") diff --git a/pandas/tests/arrays/boolean/test_construction.py b/pandas/tests/arrays/boolean/test_construction.py index f7354a089df3b..2f5c61304d415 100644 --- a/pandas/tests/arrays/boolean/test_construction.py +++ b/pandas/tests/arrays/boolean/test_construction.py @@ -247,10 +247,11 @@ def test_coerce_to_numpy_array(): def test_to_boolean_array_from_strings(): result = BooleanArray._from_sequence_of_strings( - np.array(["True", "False", np.nan], dtype=object) + np.array(["True", "False", "1", "1.0", "0", "0.0", np.nan], dtype=object) ) expected = BooleanArray( - np.array([True, False, False]), np.array([False, False, True]) + np.array([True, False, True, True, False, False, False]), + np.array([False, False, False, False, False, False, True]), ) tm.assert_extension_array_equal(result, expected) diff --git a/pandas/tests/io/parser/test_dtypes.py b/pandas/tests/io/parser/test_dtypes.py index 6298d1e5498f3..6ac310e3b2227 100644 --- a/pandas/tests/io/parser/test_dtypes.py +++ b/pandas/tests/io/parser/test_dtypes.py @@ -561,9 +561,13 @@ def test_boolean_dtype(all_parsers): "True", "TRUE", "true", + "1", + "1.0", "False", "FALSE", "false", + "0", + "0.0", "NaN", "nan", "NA", @@ -576,7 +580,23 @@ def test_boolean_dtype(all_parsers): expected = pd.DataFrame( { "a": pd.array( - [True, True, True, False, False, False, None, None, None, None, None], + [ + True, + True, + True, + True, + True, + False, + False, + False, + False, + False, + None, + None, + None, + None, + None, + ], dtype="boolean", ) }
- [ ] closes #34859 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35061
2020-06-30T12:34:39Z
2020-07-02T15:01:40Z
2020-07-02T15:01:39Z
2020-07-03T05:38:12Z
Fix issue #31708 Series.astype(str, skipna=True) vanished in the 1.0 release
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a66cade3b81b0..42d9ddc0605bf 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5383,7 +5383,11 @@ def _to_dict_of_blocks(self, copy: bool_t = True): } def astype( - self: FrameOrSeries, dtype, copy: bool_t = True, errors: str = "raise" + self: FrameOrSeries, + dtype, + copy: bool_t = True, + errors: str = "raise", + skipna: bool_t = False, ) -> FrameOrSeries: """ Cast a pandas object to a specified dtype ``dtype``. @@ -5404,6 +5408,10 @@ def astype( - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object. + skipna : bool, default False + When ``deep=False`` (default) nan values will be casted to proper + dtype. + Preserve nan values when ``skipna=True``. Returns ------- @@ -5499,6 +5507,19 @@ def astype( 1 2020-01-01 19:00:00-05:00 2 2020-01-02 19:00:00-05:00 dtype: datetime64[ns, US/Eastern] + + By default NaN values will be casted to dtype: + >>> pd.Series([None, 1]).astype(str) + 0 nan + 1 1.0 + dtype: object + + Skip casting NaN values: + + >>> pd.Series([None, 1]).astype(str, skipna=True) + 0 NaN + 1 1.0 + dtype: object """ if is_dict_like(dtype): if self.ndim == 1: # i.e. Series @@ -5520,7 +5541,12 @@ def astype( for col_name, col in self.items(): if col_name in dtype: results.append( - col.astype(dtype=dtype[col_name], copy=copy, errors=errors) + col.astype( + dtype=dtype[col_name], + copy=copy, + errors=errors, + skipna=skipna, + ) ) else: results.append(col.copy() if copy else col) @@ -5529,13 +5555,15 @@ def astype( # GH 18099/22869: columnwise conversion to extension dtype # GH 24704: use iloc to handle duplicate column names results = [ - self.iloc[:, i].astype(dtype, copy=copy) + self.iloc[:, i].astype(dtype, copy=copy, skipna=skipna) for i in range(len(self.columns)) ] else: # else, only a single dtype is given - new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors,) + new_data = self._mgr.astype( + dtype=dtype, copy=copy, errors=errors, skipna=skipna + ) return self._constructor(new_data).__finalize__(self, method="astype") # GH 33113: handle empty frame or series diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 6207785fb2975..3d2013444f2c0 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -516,7 +516,9 @@ def f(mask, val, idx): return self.split_and_operate(None, f, False) - def astype(self, dtype, copy: bool = False, errors: str = "raise"): + def astype( + self, dtype, copy: bool = False, errors: str = "raise", skipna: bool = False + ): """ Coerce to the new dtype. @@ -528,6 +530,10 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"): errors : str, {'raise', 'ignore'}, default 'ignore' - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object + skipna : bool, default False + When ``skipna=False`` (default) nan values will be casted to proper + dtype. + Skip casting nan values when ``skipna=True``. Returns ------- @@ -592,7 +598,7 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"): # _astype_nansafe works fine with 1-d only vals1d = values.ravel() try: - values = astype_nansafe(vals1d, dtype, copy=True) + values = astype_nansafe(vals1d, dtype, copy=True, skipna=skipna) except (ValueError, TypeError): # e.g. astype_nansafe can fail on object-dtype of strings # trying to convert to float @@ -2094,7 +2100,9 @@ def _maybe_coerce_values(self, values): assert isinstance(values, np.ndarray), type(values) return values - def astype(self, dtype, copy: bool = False, errors: str = "raise"): + def astype( + self, dtype, copy: bool = False, errors: str = "raise", skipna: bool = False + ): """ these automatically copy, so copy=True has no effect raise on an except if raise == True @@ -2113,7 +2121,7 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"): return self.make_block(values) # delegate - return super().astype(dtype=dtype, copy=copy, errors=errors) + return super().astype(dtype=dtype, copy=copy, errors=errors, skipna=skipna) def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index b2f2277d9a7dc..79244600e4e0a 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -560,9 +560,11 @@ def downcast(self) -> "BlockManager": return self.apply("downcast") def astype( - self, dtype, copy: bool = False, errors: str = "raise" + self, dtype, copy: bool = False, errors: str = "raise", skipna: bool = False ) -> "BlockManager": - return self.apply("astype", dtype=dtype, copy=copy, errors=errors) + return self.apply( + "astype", dtype=dtype, copy=copy, errors=errors, skipna=skipna + ) def convert( self, diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py index bcc0b18134dad..ad35402db709a 100644 --- a/pandas/tests/series/test_dtypes.py +++ b/pandas/tests/series/test_dtypes.py @@ -495,3 +495,14 @@ def test_reindex_astype_order_consistency(self): s1 = s.reindex(new_index).astype(temp_dtype).astype(new_dtype) s2 = s.astype(temp_dtype).reindex(new_index).astype(new_dtype) tm.assert_series_equal(s1, s2) + + def test_astype_skipna_default(self): + arr = Series([1.0, np.nan, 3.0, 4.0]) + result = arr.astype(str) + tm.assert_series_equal(result, Series(["1.0", "nan", "3.0", "4.0"])) + + def test_astype_skipna_true(self): + # GH 31708 + arr = Series([1.0, np.nan, 3.0, 4.0]) + result = arr.astype(str, skipna=True) + tm.assert_series_equal(result, Series(["1.0", np.nan, "3.0", "4.0"]))
- [ ] closes #31708 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/35060
2020-06-30T08:58:48Z
2020-07-17T10:35:12Z
null
2023-05-11T01:19:46Z