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
DEPS: Add warning if pyarrow is not installed
diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index dd5d090e098b0..a3cffb4b03b93 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -92,7 +92,10 @@ jobs: - name: "Numpy Dev" env_file: actions-311-numpydev.yaml pattern: "not slow and not network and not single_cpu" - test_args: "-W error::DeprecationWarning -W error::FutureWarning" + # Currently restricted the warnings that error to Deprecation Warnings from numpy + # done since pyarrow isn't compatible with numpydev always + # TODO: work with pyarrow to revert this? + test_args: "-W error::DeprecationWarning:numpy -W error::FutureWarning:numpy" - name: "Pyarrow Nightly" env_file: actions-311-pyarrownightly.yaml pattern: "not slow and not network and not single_cpu" diff --git a/pandas/__init__.py b/pandas/__init__.py index 7fab662ed2de4..ed524c2bb3619 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -202,8 +202,37 @@ FutureWarning, stacklevel=2, ) -# Don't allow users to use pandas.os or pandas.warnings -del os, warnings + +# DeprecationWarning for missing pyarrow +from pandas.compat.pyarrow import pa_version_under10p1, pa_not_found + +if pa_version_under10p1: + # pyarrow is either too old or nonexistent, warn + from pandas.compat._optional import VERSIONS + + if pa_not_found: + pa_msg = "was not found to be installed on your system." + else: + pa_msg = ( + f"was too old on your system - pyarrow {VERSIONS['pyarrow']} " + "is the current minimum supported version as of this release." + ) + + warnings.warn( + f""" +Pyarrow will become a required dependency of pandas in the next major release of pandas (pandas 3.0), +(to allow more performant data types, such as the Arrow string type, and better interoperability with other libraries) +but {pa_msg} +If this would cause problems for you, +please provide us feedback at https://github.com/pandas-dev/pandas/issues/54466 + """, # noqa: E501 + DeprecationWarning, + stacklevel=2, + ) + del VERSIONS, pa_msg + +# Delete all unnecessary imported modules +del pa_version_under10p1, pa_not_found, warnings, os # module level doc-string __doc__ = """ diff --git a/pandas/compat/pyarrow.py b/pandas/compat/pyarrow.py index beb4814914101..2e151123ef2c9 100644 --- a/pandas/compat/pyarrow.py +++ b/pandas/compat/pyarrow.py @@ -8,6 +8,7 @@ import pyarrow as pa _palv = Version(Version(pa.__version__).base_version) + pa_not_found = False pa_version_under10p1 = _palv < Version("10.0.1") pa_version_under11p0 = _palv < Version("11.0.0") pa_version_under12p0 = _palv < Version("12.0.0") @@ -16,6 +17,7 @@ pa_version_under14p1 = _palv < Version("14.0.1") pa_version_under15p0 = _palv < Version("15.0.0") except ImportError: + pa_not_found = True pa_version_under10p1 = True pa_version_under11p0 = True pa_version_under12p0 = True diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index e8a1c961c8cb6..fe24755e8cc23 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -8,6 +8,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import Series import pandas._testing as tm @@ -265,3 +267,23 @@ def test_bz2_missing_import(): code = textwrap.dedent(code) call = [sys.executable, "-c", code] subprocess.check_output(call) + + +@td.skip_if_installed("pyarrow") +@pytest.mark.parametrize("module", ["pandas", "pandas.arrays"]) +def test_pyarrow_missing_warn(module): + # GH56896 + response = subprocess.run( + [sys.executable, "-c", f"import {module}"], + capture_output=True, + check=True, + ) + msg = """ +Pyarrow will become a required dependency of pandas in the next major release of pandas (pandas 3.0), +(to allow more performant data types, such as the Arrow string type, and better interoperability with other libraries) +but was not found to be installed on your system. +If this would cause problems for you, +please provide us feedback at https://github.com/pandas-dev/pandas/issues/54466 +""" # noqa: E501 + stderr_msg = response.stderr.decode("utf-8") + assert msg in stderr_msg, stderr_msg
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. ~~Not sure how to add a test for this - importing our warning asserters would cause the warning the be raised! 🤣 ~~ EDIT: Nvm, figured it out. (I've checked by hand that the warning is both raised when you import pandas directly and import a submodule of pandas e.g. ``pandas.arrays``. I also double checked that the warning only occurs once and not on every import.)
https://api.github.com/repos/pandas-dev/pandas/pulls/56896
2024-01-15T21:26:56Z
2024-01-19T17:12:49Z
2024-01-19T17:12:49Z
2024-01-22T11:04:40Z
BUG: assert_frame_equal raising TypeError with check_like and mixed dtype in Index or columns
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 448260148c83d..fa5347aa7a507 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -29,6 +29,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) - Fixed regression in :meth:`Series.fillna` that raised ``RecursionError`` with ``datetime64[ns, UTC]`` dtype (:issue:`38851`) - Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) +- Fixed regression in :func:`pandas.testing.assert_frame_equal` raising ``TypeError`` with ``check_like=True`` when :class:`Index` or columns have mixed dtype (:issue:`39168`) - Fixed regression in :meth:`DataFrame.groupby` when aggregating an :class:`ExtensionDType` that could fail for non-numeric values (:issue:`38980`) - Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``KeyError`` with :class:`MultiIndex` and list-like columns indexer enlarging :class:`DataFrame` (:issue:`39147`) - Fixed regression in comparisons between ``NaT`` and ``datetime.date`` objects incorrectly returning ``True`` (:issue:`39151`) @@ -42,7 +43,7 @@ Bug fixes - Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) - Bug in :func:`read_csv` not closing an opened file handle when a ``csv.Error`` or ``UnicodeDecodeError`` occurred while initializing (:issue:`39024`) -- +- Bug in :func:`pandas.testing.assert_index_equal` raising ``TypeError`` with ``check_order=False`` when :class:`Index` has mixed dtype (:issue:`39168`) .. --------------------------------------------------------------------------- diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 69e17199c9a90..b20cc0897ec18 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -29,7 +29,7 @@ Series, TimedeltaIndex, ) -from pandas.core.algorithms import take_1d +from pandas.core.algorithms import safe_sort, take_1d from pandas.core.arrays import ( DatetimeArray, ExtensionArray, @@ -344,8 +344,8 @@ def _get_ilevel_values(index, level): # If order doesn't matter then sort the index entries if not check_order: - left = left.sort_values() - right = right.sort_values() + left = Index(safe_sort(left)) + right = Index(safe_sort(right)) # MultiIndex special comparison for little-friendly error messages if left.nlevels > 1: diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index bb721afda2b8b..a594751808532 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -299,3 +299,9 @@ def test_allows_duplicate_labels(): with pytest.raises(AssertionError, match="<Flags"): tm.assert_frame_equal(left, right) + + +def test_assert_frame_equal_columns_mixed_dtype(): + # GH#39168 + df = DataFrame([[0, 1, 2]], columns=["foo", "bar", 42], index=[1, "test", 2]) + tm.assert_frame_equal(df, df, check_like=True) diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py index 988a0e7b24379..42c6db3d0b684 100644 --- a/pandas/tests/util/test_assert_index_equal.py +++ b/pandas/tests/util/test_assert_index_equal.py @@ -192,3 +192,9 @@ def test_index_equal_category_mismatch(check_categorical): tm.assert_index_equal(idx1, idx2, check_categorical=check_categorical) else: tm.assert_index_equal(idx1, idx2, check_categorical=check_categorical) + + +def test_assert_index_equal_mixed_dtype(): + # GH#39168 + idx = Index(["foo", "bar", 42]) + tm.assert_index_equal(idx, idx, check_order=False)
- [x] closes #39168 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry Worked on 1.1.5 for assert_frame_equal and was not supported for assert_index_equal
https://api.github.com/repos/pandas-dev/pandas/pulls/39204
2021-01-16T02:18:32Z
2021-01-16T14:21:19Z
2021-01-16T14:21:18Z
2021-01-16T14:59:56Z
REGR: to_stata tried to remove file before closing it
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 2d9290dda060a..1a243c846d01c 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -17,6 +17,7 @@ Fixed regressions - Fixed regression in :meth:`~DataFrame.to_csv` that created corrupted zip files when there were more rows than ``chunksize`` (:issue:`38714`) - Fixed regression in :meth:`read_csv` and other read functions were the encoding error policy (``errors``) did not default to ``"replace"`` when no encoding was specified (:issue:`38989`) - Fixed regression in :func:`read_excel` with non-rawbyte file handles (:issue:`38788`) +- Fixed regression in :meth:`DataFrame.to_stata` not removing the created file when an error occured (:issue:`39202`) - Fixed regression in ``DataFrame.__setitem__`` raising ``ValueError`` when expanding :class:`DataFrame` and new column is from type ``"0 - name"`` (:issue:`39010`) - Fixed regression in setting with :meth:`DataFrame.loc` raising ``ValueError`` when :class:`DataFrame` has unsorted :class:`MultiIndex` columns and indexer is a scalar (:issue:`38601`) - Fixed regression in setting with :meth:`DataFrame.loc` raising ``KeyError`` with :class:`MultiIndex` and list-like columns indexer enlarging :class:`DataFrame` (:issue:`39147`) diff --git a/pandas/_testing/contexts.py b/pandas/_testing/contexts.py index d72dc8c3af104..71530b9537fc8 100644 --- a/pandas/_testing/contexts.py +++ b/pandas/_testing/contexts.py @@ -1,7 +1,11 @@ from contextlib import contextmanager import os +from pathlib import Path +import random from shutil import rmtree +import string import tempfile +from typing import IO, Any, Union import numpy as np @@ -73,66 +77,48 @@ def setTZ(tz): @contextmanager -def ensure_clean(filename=None, return_filelike=False, **kwargs): +def ensure_clean(filename=None, return_filelike: bool = False, **kwargs: Any): """ Gets a temporary path and agrees to remove on close. + This implementation does not use tempfile.mkstemp to avoid having a file handle. + If the code using the returned path wants to delete the file itself, windows + requires that no program has a file handle to it. + Parameters ---------- filename : str (optional) - if None, creates a temporary file which is then removed when out of - scope. if passed, creates temporary file with filename as ending. + suffix of the created file. return_filelike : bool (default False) if True, returns a file-like which is *always* cleaned. Necessary for savefig and other functions which want to append extensions. **kwargs - Additional keywords passed in for creating a temporary file. - :meth:`tempFile.TemporaryFile` is used when `return_filelike` is ``True``. - :meth:`tempfile.mkstemp` is used when `return_filelike` is ``False``. - Note that the `filename` parameter will be passed in as the `suffix` - argument to either function. + Additional keywords are passed to open(). - See Also - -------- - tempfile.TemporaryFile - tempfile.mkstemp """ - filename = filename or "" - fd = None - - kwargs["suffix"] = filename + folder = Path(tempfile.gettempdir()) - if return_filelike: - f = tempfile.TemporaryFile(**kwargs) - - try: - yield f - finally: - f.close() - else: - # Don't generate tempfile if using a path with directory specified. - if len(os.path.dirname(filename)): - raise ValueError("Can't pass a qualified name to ensure_clean()") + if filename is None: + filename = "" + filename = ( + "".join(random.choices(string.ascii_letters + string.digits, k=30)) + filename + ) + path = folder / filename - try: - fd, filename = tempfile.mkstemp(**kwargs) - except UnicodeEncodeError: - import pytest + path.touch() - pytest.skip("no unicode file names on this system") + handle_or_str: Union[str, IO] = str(path) + if return_filelike: + kwargs.setdefault("mode", "w+b") + handle_or_str = open(path, **kwargs) - try: - yield filename - finally: - try: - os.close(fd) - except OSError: - print(f"Couldn't close file descriptor: {fd} (file: {filename})") - try: - if os.path.exists(filename): - os.remove(filename) - except OSError as e: - print(f"Exception on removing file: {e}") + try: + yield handle_or_str + finally: + if not isinstance(handle_or_str, str): + handle_or_str.close() + if path.is_file(): + path.unlink() @contextmanager diff --git a/pandas/io/stata.py b/pandas/io/stata.py index c9cd94b7cc711..3ea3da89c7cb1 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -15,7 +15,6 @@ import datetime from io import BytesIO import os -from pathlib import Path import struct import sys from typing import ( @@ -2466,8 +2465,8 @@ def write_file(self) -> None: if self.handles.compression["method"] is not None: # ZipFile creates a file (with the same name) for each write call. # Write it first into a buffer and then write the buffer to the ZipFile. - self._output_file = self.handles.handle - self.handles.handle = BytesIO() + self._output_file, self.handles.handle = self.handles.handle, BytesIO() + self.handles.created_handles.append(self.handles.handle) try: self._write_header( @@ -2488,20 +2487,23 @@ def write_file(self) -> None: self._write_value_labels() self._write_file_close_tag() self._write_map() - except Exception as exc: self._close() - if isinstance(self._fname, (str, Path)): + except Exception as exc: + self.handles.close() + # Only @runtime_checkable protocols can be used with instance and class + # checks + if isinstance( + self._fname, (str, os.PathLike) # type: ignore[misc] + ) and os.path.isfile(self._fname): try: os.unlink(self._fname) except OSError: warnings.warn( f"This save was not successful but {self._fname} could not " - "be deleted. This file is not valid.", + "be deleted. This file is not valid.", ResourceWarning, ) raise exc - else: - self._close() def _close(self) -> None: """ @@ -2513,11 +2515,8 @@ def _close(self) -> None: # write compression if self._output_file is not None: assert isinstance(self.handles.handle, BytesIO) - bio = self.handles.handle - bio.seek(0) - self.handles.handle = self._output_file - self.handles.handle.write(bio.read()) # type: ignore[arg-type] - bio.close() + bio, self.handles.handle = self.handles.handle, self._output_file + self.handles.handle.write(bio.getvalue()) # type: ignore[arg-type] def _write_map(self) -> None: """No-op, future compatibility""" diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index b12413fbb56c6..e23f7228cc7e1 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -657,30 +657,27 @@ def test_excel_date_datetime_format(self, engine, ext, path): ) with tm.ensure_clean(ext) as filename2: - writer1 = ExcelWriter(path) - writer2 = ExcelWriter( + with ExcelWriter(path) as writer1: + df.to_excel(writer1, "test1") + + with ExcelWriter( filename2, date_format="DD.MM.YYYY", datetime_format="DD.MM.YYYY HH-MM-SS", - ) - - df.to_excel(writer1, "test1") - df.to_excel(writer2, "test1") - - writer1.close() - writer2.close() + ) as writer2: + df.to_excel(writer2, "test1") - reader1 = ExcelFile(path) - reader2 = ExcelFile(filename2) + with ExcelFile(path) as reader1: + rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0) - rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0) - rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0) + with ExcelFile(filename2) as reader2: + rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0) - tm.assert_frame_equal(rs1, rs2) + tm.assert_frame_equal(rs1, rs2) - # Since the reader returns a datetime object for dates, - # we need to use df_expected to check the result. - tm.assert_frame_equal(rs2, df_expected) + # Since the reader returns a datetime object for dates, + # we need to use df_expected to check the result. + tm.assert_frame_equal(rs2, df_expected) def test_to_excel_interval_no_labels(self, path): # see gh-19242 @@ -862,7 +859,7 @@ def test_to_excel_unicode_filename(self, ext, path): f = open(filename, "wb") except UnicodeEncodeError: pytest.skip("No unicode file names on this system") - else: + finally: f.close() df = DataFrame( @@ -872,15 +869,15 @@ def test_to_excel_unicode_filename(self, ext, path): ) df.to_excel(filename, "test1", float_format="%.2f") - reader = ExcelFile(filename) - result = pd.read_excel(reader, sheet_name="test1", index_col=0) + with ExcelFile(filename) as reader: + result = pd.read_excel(reader, sheet_name="test1", index_col=0) - expected = DataFrame( - [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]], - index=["A", "B"], - columns=["X", "Y", "Z"], - ) - tm.assert_frame_equal(result, expected) + expected = DataFrame( + [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]], + index=["A", "B"], + columns=["X", "Y", "Z"], + ) + tm.assert_frame_equal(result, expected) # FIXME: dont leave commented-out # def test_to_excel_header_styling_xls(self, engine, ext): @@ -1374,8 +1371,8 @@ def test_excelfile_fspath(self): with tm.ensure_clean("foo.xlsx") as path: df = DataFrame({"A": [1, 2]}) df.to_excel(path) - xl = ExcelFile(path) - result = os.fspath(xl) + with ExcelFile(path) as xl: + result = os.fspath(xl) assert result == path def test_excelwriter_fspath(self): diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index 6416cb93c7ff5..ef4de5961a696 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -545,12 +545,12 @@ def test_to_csv_zip_arguments(self, compression, archive_name): df.to_csv( path, compression={"method": compression, "archive_name": archive_name} ) - zp = ZipFile(path) - expected_arcname = path if archive_name is None else archive_name - expected_arcname = os.path.basename(expected_arcname) - assert len(zp.filelist) == 1 - archived_file = os.path.basename(zp.filelist[0].filename) - assert archived_file == expected_arcname + with ZipFile(path) as zp: + expected_arcname = path if archive_name is None else archive_name + expected_arcname = os.path.basename(expected_arcname) + assert len(zp.filelist) == 1 + archived_file = os.path.basename(zp.filelist[0].filename) + assert archived_file == expected_arcname @pytest.mark.parametrize("df_new_type", ["Int64"]) def test_to_csv_na_rep_long_string(self, df_new_type): diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 035460185fa81..5897b91a5fa70 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -555,6 +555,7 @@ def test_invalid_timestamp(self, version): msg = "time_stamp should be datetime type" with pytest.raises(ValueError, match=msg): original.to_stata(path, time_stamp=time_stamp, version=version) + assert not os.path.isfile(path) def test_numeric_column_names(self): original = DataFrame(np.reshape(np.arange(25.0), (5, 5))) @@ -1921,10 +1922,10 @@ def test_compression_dict(method, file_ext): compression = {"method": method, "archive_name": archive_name} df.to_stata(path, compression=compression) if method == "zip" or file_ext == "zip": - zp = zipfile.ZipFile(path, "r") - assert len(zp.filelist) == 1 - assert zp.filelist[0].filename == archive_name - fp = io.BytesIO(zp.read(zp.filelist[0])) + with zipfile.ZipFile(path, "r") as zp: + assert len(zp.filelist) == 1 + assert zp.filelist[0].filename == archive_name + fp = io.BytesIO(zp.read(zp.filelist[0])) else: fp = path reread = read_stata(fp, index_col="index")
Spin-off from #39047: If an error occurred during `to_stata`, the code tried to first remove the file and then close the file handle: 1. removing the file failed on Windows (it is still opened) 2. It created an empty file when closing the handle
https://api.github.com/repos/pandas-dev/pandas/pulls/39202
2021-01-16T01:24:02Z
2021-01-18T15:22:07Z
2021-01-18T15:22:07Z
2021-01-19T15:54:08Z
Backport PR #39196 on branch 1.2.x (REGR: NaT.__richmp__(dateobj))
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 55fddb8b732e2..ad026d28d6a2e 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -30,7 +30,7 @@ Fixed regressions - Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) - Fixed regression in :meth:`DataFrame.groupby` when aggregating an :class:`ExtensionDType` that could fail for non-numeric values (:issue:`38980`) - Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``KeyError`` with :class:`MultiIndex` and list-like columns indexer enlarging :class:`DataFrame` (:issue:`39147`) -- +- Fixed regression in comparisons between ``NaT`` and ``datetime.date`` objects incorrectly returning ``True`` (:issue:`39151`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 561143f48e0ec..3a61de62daf39 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -1,4 +1,7 @@ +import warnings + from cpython.datetime cimport ( + PyDate_Check, PyDateTime_Check, PyDateTime_IMPORT, PyDelta_Check, @@ -125,6 +128,21 @@ cdef class _NaT(datetime): return NotImplemented return result + elif PyDate_Check(other): + # GH#39151 don't defer to datetime.date object + if op == Py_EQ: + return False + if op == Py_NE: + return True + warnings.warn( + "Comparison of NaT with datetime.date is deprecated in " + "order to match the standard library behavior. " + "In a future version these will be considered non-comparable.", + FutureWarning, + stacklevel=1, + ) + return False + return NotImplemented def __add__(self, other): diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 2ea7602b00206..20de0effc30e1 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -575,6 +575,40 @@ def test_nat_comparisons_invalid(other, op): op(other, NaT) +def test_compare_date(): + # GH#39151 comparing NaT with date object is deprecated + # See also: tests.scalar.timestamps.test_comparisons::test_compare_date + + dt = Timestamp.now().to_pydatetime().date() + + for left, right in [(NaT, dt), (dt, NaT)]: + assert not left == right + assert left != right + + with tm.assert_produces_warning(FutureWarning): + assert not left < right + with tm.assert_produces_warning(FutureWarning): + assert not left <= right + with tm.assert_produces_warning(FutureWarning): + assert not left > right + with tm.assert_produces_warning(FutureWarning): + assert not left >= right + + # Once the deprecation is enforced, the following assertions + # can be enabled: + # assert not left == right + # assert left != right + # + # with pytest.raises(TypeError): + # left < right + # with pytest.raises(TypeError): + # left <= right + # with pytest.raises(TypeError): + # left > right + # with pytest.raises(TypeError): + # left >= right + + @pytest.mark.parametrize( "obj", [
Backport PR #39196: REGR: NaT.__richmp__(dateobj)
https://api.github.com/repos/pandas-dev/pandas/pulls/39201
2021-01-16T01:18:22Z
2021-01-16T10:06:32Z
2021-01-16T10:06:32Z
2021-01-16T10:06:32Z
Backport PR #39193 on branch 1.2.x (CI: Set xfail to strict=False for network tests)
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index 726c5ebffe9b5..11e14ac61a831 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -208,7 +208,7 @@ def test_read_s3_fails(self, s3so): with pytest.raises(IOError): read_csv("s3://cant_get_it/file.csv") - @pytest.mark.xfail(reason="GH#39155 s3fs upgrade") + @pytest.mark.xfail(reason="GH#39155 s3fs upgrade", strict=False) def test_write_s3_csv_fails(self, tips_df, s3so): # GH 32486 # Attempting to write to an invalid S3 path should raise @@ -224,7 +224,7 @@ def test_write_s3_csv_fails(self, tips_df, s3so): "s3://an_s3_bucket_data_doesnt_exit/not_real.csv", storage_options=s3so ) - @pytest.mark.xfail(reason="GH#39155 s3fs upgrade") + @pytest.mark.xfail(reason="GH#39155 s3fs upgrade", strict=False) @td.skip_if_no("pyarrow") def test_write_s3_parquet_fails(self, tips_df, s3so): # GH 27679
Backport PR #39193: CI: Set xfail to strict=False for network tests
https://api.github.com/repos/pandas-dev/pandas/pulls/39200
2021-01-16T01:15:19Z
2021-01-16T11:37:35Z
2021-01-16T11:37:35Z
2021-01-16T11:37:35Z
Backport PR #39188 on branch 1.2.x (REGR: Different results from DataFrame.apply and str accessor)
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 55fddb8b732e2..982eb21f5a5da 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -25,6 +25,7 @@ Fixed regressions - Fixed regression in :func:`read_excel` with non-rawbyte file handles (:issue:`38788`) - Fixed regression in :meth:`Rolling.skew` and :meth:`Rolling.kurt` modifying the object inplace (:issue:`38908`) - Fixed regression in :meth:`read_csv` and other read functions were the encoding error policy (``errors``) did not default to ``"replace"`` when no encoding was specified (:issue:`38989`) +- Fixed regression in :meth:`DataFrame.apply` with ``axis=1`` using str accessor in apply function (:issue:`38979`) - Fixed regression in :meth:`DataFrame.replace` raising ``ValueError`` when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) - Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) - Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 2713b76189157..ca12012ec135f 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -109,7 +109,7 @@ def wrapper(self, *args, **kwargs): def _map_and_wrap(name, docstring): @forbid_nonstring_types(["bytes"], name=name) def wrapper(self): - result = getattr(self._array, f"_str_{name}")() + result = getattr(self._data.array, f"_str_{name}")() return self._wrap_result(result) wrapper.__doc__ = docstring @@ -154,8 +154,7 @@ def __init__(self, data): self._inferred_dtype = self._validate(data) self._is_categorical = is_categorical_dtype(data.dtype) self._is_string = isinstance(data.dtype, StringDtype) - array = data.array - self._array = array + self._data = data self._index = self._name = None if isinstance(data, ABCSeries): @@ -219,7 +218,7 @@ def _validate(data): return inferred_dtype def __getitem__(self, key): - result = self._array._str_getitem(key) + result = self._data.array._str_getitem(key) return self._wrap_result(result) def __iter__(self): @@ -744,13 +743,13 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): @Appender(_shared_docs["str_split"] % {"side": "beginning", "method": "split"}) @forbid_nonstring_types(["bytes"]) def split(self, pat=None, n=-1, expand=False): - result = self._array._str_split(pat, n, expand) + result = self._data.array._str_split(pat, n, expand) return self._wrap_result(result, returns_string=expand, expand=expand) @Appender(_shared_docs["str_split"] % {"side": "end", "method": "rsplit"}) @forbid_nonstring_types(["bytes"]) def rsplit(self, pat=None, n=-1, expand=False): - result = self._array._str_rsplit(pat, n=n) + result = self._data.array._str_rsplit(pat, n=n) return self._wrap_result(result, expand=expand, returns_string=expand) _shared_docs[ @@ -846,7 +845,7 @@ def rsplit(self, pat=None, n=-1, expand=False): ) @forbid_nonstring_types(["bytes"]) def partition(self, sep=" ", expand=True): - result = self._array._str_partition(sep, expand) + result = self._data.array._str_partition(sep, expand) return self._wrap_result(result, expand=expand, returns_string=expand) @Appender( @@ -860,7 +859,7 @@ def partition(self, sep=" ", expand=True): ) @forbid_nonstring_types(["bytes"]) def rpartition(self, sep=" ", expand=True): - result = self._array._str_rpartition(sep, expand) + result = self._data.array._str_rpartition(sep, expand) return self._wrap_result(result, expand=expand, returns_string=expand) def get(self, i): @@ -914,7 +913,7 @@ def get(self, i): 5 None dtype: object """ - result = self._array._str_get(i) + result = self._data.array._str_get(i) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -980,7 +979,7 @@ def join(self, sep): 4 NaN dtype: object """ - result = self._array._str_join(sep) + result = self._data.array._str_join(sep) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -1108,7 +1107,7 @@ def contains(self, pat, case=True, flags=0, na=None, regex=True): 4 False dtype: bool """ - result = self._array._str_contains(pat, case, flags, na, regex) + result = self._data.array._str_contains(pat, case, flags, na, regex) return self._wrap_result(result, fill_value=na, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -1140,7 +1139,7 @@ def match(self, pat, case=True, flags=0, na=None): re.match. extract : Extract matched groups. """ - result = self._array._str_match(pat, case=case, flags=flags, na=na) + result = self._data.array._str_match(pat, case=case, flags=flags, na=na) return self._wrap_result(result, fill_value=na, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -1173,7 +1172,7 @@ def fullmatch(self, pat, case=True, flags=0, na=None): matches the regular expression. extract : Extract matched groups. """ - result = self._array._str_fullmatch(pat, case=case, flags=flags, na=na) + result = self._data.array._str_fullmatch(pat, case=case, flags=flags, na=na) return self._wrap_result(result, fill_value=na, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -1309,7 +1308,7 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None): ) warnings.warn(msg, FutureWarning, stacklevel=3) regex = True - result = self._array._str_replace( + result = self._data.array._str_replace( pat, repl, n=n, case=case, flags=flags, regex=regex ) return self._wrap_result(result) @@ -1355,7 +1354,7 @@ def repeat(self, repeats): 2 ccc dtype: object """ - result = self._array._str_repeat(repeats) + result = self._data.array._str_repeat(repeats) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -1423,7 +1422,7 @@ def pad(self, width, side="left", fillchar=" "): msg = f"width must be of integer type, not {type(width).__name__}" raise TypeError(msg) - result = self._array._str_pad(width, side=side, fillchar=fillchar) + result = self._data.array._str_pad(width, side=side, fillchar=fillchar) return self._wrap_result(result) _shared_docs[ @@ -1597,7 +1596,7 @@ def slice(self, start=None, stop=None, step=None): 2 cm dtype: object """ - result = self._array._str_slice(start, stop, step) + result = self._data.array._str_slice(start, stop, step) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -1673,7 +1672,7 @@ def slice_replace(self, start=None, stop=None, repl=None): 4 aXde dtype: object """ - result = self._array._str_slice_replace(start, stop, repl) + result = self._data.array._str_slice_replace(start, stop, repl) return self._wrap_result(result) def decode(self, encoding, errors="strict"): @@ -1699,7 +1698,7 @@ def decode(self, encoding, errors="strict"): else: decoder = codecs.getdecoder(encoding) f = lambda x: decoder(x, errors)[0] - arr = self._array + arr = self._data.array # assert isinstance(arr, (StringArray,)) result = arr._str_map(f) return self._wrap_result(result) @@ -1720,7 +1719,7 @@ def encode(self, encoding, errors="strict"): ------- encoded : Series/Index of objects """ - result = self._array._str_encode(encoding, errors) + result = self._data.array._str_encode(encoding, errors) return self._wrap_result(result, returns_string=False) _shared_docs[ @@ -1798,7 +1797,7 @@ def encode(self, encoding, errors="strict"): ) @forbid_nonstring_types(["bytes"]) def strip(self, to_strip=None): - result = self._array._str_strip(to_strip) + result = self._data.array._str_strip(to_strip) return self._wrap_result(result) @Appender( @@ -1807,7 +1806,7 @@ def strip(self, to_strip=None): ) @forbid_nonstring_types(["bytes"]) def lstrip(self, to_strip=None): - result = self._array._str_lstrip(to_strip) + result = self._data.array._str_lstrip(to_strip) return self._wrap_result(result) @Appender( @@ -1816,7 +1815,7 @@ def lstrip(self, to_strip=None): ) @forbid_nonstring_types(["bytes"]) def rstrip(self, to_strip=None): - result = self._array._str_rstrip(to_strip) + result = self._data.array._str_rstrip(to_strip) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -1875,7 +1874,7 @@ def wrap(self, width, **kwargs): 1 another line\nto be\nwrapped dtype: object """ - result = self._array._str_wrap(width, **kwargs) + result = self._data.array._str_wrap(width, **kwargs) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -1917,7 +1916,7 @@ def get_dummies(self, sep="|"): """ # we need to cast to Series of strings as only that has all # methods available for making the dummies... - result, name = self._array._str_get_dummies(sep) + result, name = self._data.array._str_get_dummies(sep) return self._wrap_result( result, name=name, @@ -1944,7 +1943,7 @@ def translate(self, table): ------- Series or Index """ - result = self._array._str_translate(table) + result = self._data.array._str_translate(table) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -2012,7 +2011,7 @@ def count(self, pat, flags=0): >>> pd.Index(['A', 'A', 'Aaba', 'cat']).str.count('a') Int64Index([0, 0, 2, 1], dtype='int64') """ - result = self._array._str_count(pat, flags) + result = self._data.array._str_count(pat, flags) return self._wrap_result(result, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -2069,7 +2068,7 @@ def startswith(self, pat, na=None): 3 False dtype: bool """ - result = self._array._str_startswith(pat, na=na) + result = self._data.array._str_startswith(pat, na=na) return self._wrap_result(result, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -2126,7 +2125,7 @@ def endswith(self, pat, na=None): 3 False dtype: bool """ - result = self._array._str_endswith(pat, na=na) + result = self._data.array._str_endswith(pat, na=na) return self._wrap_result(result, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -2219,7 +2218,7 @@ def findall(self, pat, flags=0): 2 [b, b] dtype: object """ - result = self._array._str_findall(pat, flags) + result = self._data.array._str_findall(pat, flags) return self._wrap_result(result, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -2426,7 +2425,7 @@ def find(self, sub, start=0, end=None): msg = f"expected a string object, not {type(sub).__name__}" raise TypeError(msg) - result = self._array._str_find(sub, start, end) + result = self._data.array._str_find(sub, start, end) return self._wrap_result(result, returns_string=False) @Appender( @@ -2443,7 +2442,7 @@ def rfind(self, sub, start=0, end=None): msg = f"expected a string object, not {type(sub).__name__}" raise TypeError(msg) - result = self._array._str_rfind(sub, start=start, end=end) + result = self._data.array._str_rfind(sub, start=start, end=end) return self._wrap_result(result, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -2463,7 +2462,7 @@ def normalize(self, form): ------- normalized : Series/Index of objects """ - result = self._array._str_normalize(form) + result = self._data.array._str_normalize(form) return self._wrap_result(result) _shared_docs[ @@ -2510,7 +2509,7 @@ def index(self, sub, start=0, end=None): msg = f"expected a string object, not {type(sub).__name__}" raise TypeError(msg) - result = self._array._str_index(sub, start=start, end=end) + result = self._data.array._str_index(sub, start=start, end=end) return self._wrap_result(result, returns_string=False) @Appender( @@ -2528,7 +2527,7 @@ def rindex(self, sub, start=0, end=None): msg = f"expected a string object, not {type(sub).__name__}" raise TypeError(msg) - result = self._array._str_rindex(sub, start=start, end=end) + result = self._data.array._str_rindex(sub, start=start, end=end) return self._wrap_result(result, returns_string=False) def len(self): @@ -2577,7 +2576,7 @@ def len(self): 5 3.0 dtype: float64 """ - result = self._array._str_len() + result = self._data.array._str_len() return self._wrap_result(result, returns_string=False) _shared_docs[ @@ -2677,37 +2676,37 @@ def len(self): @Appender(_shared_docs["casemethods"] % _doc_args["lower"]) @forbid_nonstring_types(["bytes"]) def lower(self): - result = self._array._str_lower() + result = self._data.array._str_lower() return self._wrap_result(result) @Appender(_shared_docs["casemethods"] % _doc_args["upper"]) @forbid_nonstring_types(["bytes"]) def upper(self): - result = self._array._str_upper() + result = self._data.array._str_upper() return self._wrap_result(result) @Appender(_shared_docs["casemethods"] % _doc_args["title"]) @forbid_nonstring_types(["bytes"]) def title(self): - result = self._array._str_title() + result = self._data.array._str_title() return self._wrap_result(result) @Appender(_shared_docs["casemethods"] % _doc_args["capitalize"]) @forbid_nonstring_types(["bytes"]) def capitalize(self): - result = self._array._str_capitalize() + result = self._data.array._str_capitalize() return self._wrap_result(result) @Appender(_shared_docs["casemethods"] % _doc_args["swapcase"]) @forbid_nonstring_types(["bytes"]) def swapcase(self): - result = self._array._str_swapcase() + result = self._data.array._str_swapcase() return self._wrap_result(result) @Appender(_shared_docs["casemethods"] % _doc_args["casefold"]) @forbid_nonstring_types(["bytes"]) def casefold(self): - result = self._array._str_casefold() + result = self._data.array._str_casefold() return self._wrap_result(result) _shared_docs[ diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 538a52d84b73a..a15b2d03079d4 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -3670,3 +3670,11 @@ def test_str_get_stringarray_multiple_nans(): result = s.str.get(2) expected = Series(pd.array([pd.NA, pd.NA, pd.NA, "c"])) tm.assert_series_equal(result, expected) + + +def test_str_accessor_in_apply_func(): + # https://github.com/pandas-dev/pandas/issues/38979 + df = DataFrame(zip("abc", "def")) + expected = Series(["A/D", "B/E", "C/F"]) + result = df.apply(lambda f: "/".join(f.str.upper()), axis=1) + tm.assert_series_equal(result, expected)
Backport PR #39188: REGR: Different results from DataFrame.apply and str accessor
https://api.github.com/repos/pandas-dev/pandas/pulls/39199
2021-01-16T01:13:14Z
2021-01-16T02:50:59Z
2021-01-16T02:50:59Z
2021-01-16T02:50:59Z
Backport PR #39191 on branch 1.2.x (Revert "BUG/REG: RollingGroupby MultiIndex levels dropped (#38737)")
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 55fddb8b732e2..ebac06b80ad67 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -15,7 +15,6 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`to_csv` that created corrupted zip files when there were more rows than ``chunksize`` (:issue:`38714`) -- Fixed regression in ``groupby().rolling()`` where :class:`MultiIndex` levels were dropped (:issue:`38523`) - Fixed regression in repr of float-like strings of an ``object`` dtype having trailing 0's truncated after the decimal (:issue:`38708`) - Fixed regression in :meth:`DataFrame.groupby()` with :class:`Categorical` grouping column not showing unused categories for ``grouped.indices`` (:issue:`38642`) - Fixed regression in :meth:`DataFrame.any` and :meth:`DataFrame.all` not returning a result for tz-aware ``datetime64`` columns (:issue:`38723`) diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py index 4007ef50932fc..3aeb3b664b27f 100644 --- a/pandas/core/shared_docs.py +++ b/pandas/core/shared_docs.py @@ -108,7 +108,7 @@ Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group. group_keys : bool, default True - When calling ``groupby().apply()``, add group keys to index to identify pieces. + When calling apply, add group keys to index to identify pieces. squeeze : bool, default False Reduce the dimensionality of the return type if possible, otherwise return a consistent type. diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index e50a907901dc7..e6185f8ae0679 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -767,22 +767,28 @@ def _apply( numba_cache_key, **kwargs, ) - # Reconstruct the resulting MultiIndex + # Reconstruct the resulting MultiIndex from tuples # 1st set of levels = group by labels - # 2nd set of levels = original DataFrame/Series index - grouped_object_index = self.obj.index - grouped_index_name = [*grouped_object_index.names] - groupby_keys = [grouping.name for grouping in self._groupby.grouper._groupings] - result_index_names = groupby_keys + grouped_index_name + # 2nd set of levels = original index + # Ignore 2nd set of levels if a group by label include an index level + result_index_names = [ + grouping.name for grouping in self._groupby.grouper._groupings + ] + grouped_object_index = None - drop_columns = [ + column_keys = [ key - for key in groupby_keys + for key in result_index_names if key not in self.obj.index.names or key is None ] - if len(drop_columns) != len(groupby_keys): - # Our result will have kept groupby columns which should be dropped - result = result.drop(columns=drop_columns, errors="ignore") + + if len(column_keys) == len(result_index_names): + grouped_object_index = self.obj.index + grouped_index_name = [*grouped_object_index.names] + result_index_names += grouped_index_name + else: + # Our result will have still kept the column in the result + result = result.drop(columns=column_keys, errors="ignore") codes = self._groupby.grouper.codes levels = self._groupby.grouper.levels diff --git a/pandas/tests/window/test_groupby.py b/pandas/tests/window/test_groupby.py index f915da3330ba7..b89fb35ac3a70 100644 --- a/pandas/tests/window/test_groupby.py +++ b/pandas/tests/window/test_groupby.py @@ -556,31 +556,23 @@ def test_groupby_rolling_nans_in_index(self, rollings, key): with pytest.raises(ValueError, match=f"{key} must be monotonic"): df.groupby("c").rolling("60min", **rollings) - @pytest.mark.parametrize("group_keys", [True, False]) - def test_groupby_rolling_group_keys(self, group_keys): + def test_groupby_rolling_group_keys(self): # GH 37641 - # GH 38523: GH 37641 actually was not a bug. - # group_keys only applies to groupby.apply directly arrays = [["val1", "val1", "val2"], ["val1", "val1", "val2"]] index = MultiIndex.from_arrays(arrays, names=("idx1", "idx2")) s = Series([1, 2, 3], index=index) - result = s.groupby(["idx1", "idx2"], group_keys=group_keys).rolling(1).mean() + result = s.groupby(["idx1", "idx2"], group_keys=False).rolling(1).mean() expected = Series( [1.0, 2.0, 3.0], index=MultiIndex.from_tuples( - [ - ("val1", "val1", "val1", "val1"), - ("val1", "val1", "val1", "val1"), - ("val2", "val2", "val2", "val2"), - ], - names=["idx1", "idx2", "idx1", "idx2"], + [("val1", "val1"), ("val1", "val1"), ("val2", "val2")], + names=["idx1", "idx2"], ), ) tm.assert_series_equal(result, expected) def test_groupby_rolling_index_level_and_column_label(self): - # The groupby keys should not appear as a resulting column arrays = [["val1", "val1", "val2"], ["val1", "val1", "val2"]] index = MultiIndex.from_arrays(arrays, names=("idx1", "idx2")) @@ -589,12 +581,7 @@ def test_groupby_rolling_index_level_and_column_label(self): expected = DataFrame( {"B": [0.0, 1.0, 2.0]}, index=MultiIndex.from_tuples( - [ - ("val1", 1, "val1", "val1"), - ("val1", 1, "val1", "val1"), - ("val2", 2, "val2", "val2"), - ], - names=["idx1", "A", "idx1", "idx2"], + [("val1", 1), ("val1", 1), ("val2", 2)], names=["idx1", "A"] ), ) tm.assert_frame_equal(result, expected) @@ -653,30 +640,6 @@ def test_groupby_rolling_resulting_multiindex(self): ) tm.assert_index_equal(result.index, expected_index) - def test_groupby_level(self): - # GH 38523 - arrays = [ - ["Falcon", "Falcon", "Parrot", "Parrot"], - ["Captive", "Wild", "Captive", "Wild"], - ] - index = MultiIndex.from_arrays(arrays, names=("Animal", "Type")) - df = DataFrame({"Max Speed": [390.0, 350.0, 30.0, 20.0]}, index=index) - result = df.groupby(level=0)["Max Speed"].rolling(2).sum() - expected = Series( - [np.nan, 740.0, np.nan, 50.0], - index=MultiIndex.from_tuples( - [ - ("Falcon", "Falcon", "Captive"), - ("Falcon", "Falcon", "Wild"), - ("Parrot", "Parrot", "Captive"), - ("Parrot", "Parrot", "Wild"), - ], - names=["Animal", "Animal", "Type"], - ), - name="Max Speed", - ) - tm.assert_series_equal(result, expected) - class TestExpanding: def setup_method(self):
Backport PR #39191: Revert "BUG/REG: RollingGroupby MultiIndex levels dropped (#38737)"
https://api.github.com/repos/pandas-dev/pandas/pulls/39198
2021-01-16T01:11:24Z
2021-01-16T02:14:58Z
2021-01-16T02:14:58Z
2021-01-16T02:14:58Z
REGR: NaT.__richmp__(dateobj)
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 55fddb8b732e2..ad026d28d6a2e 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -30,7 +30,7 @@ Fixed regressions - Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) - Fixed regression in :meth:`DataFrame.groupby` when aggregating an :class:`ExtensionDType` that could fail for non-numeric values (:issue:`38980`) - Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``KeyError`` with :class:`MultiIndex` and list-like columns indexer enlarging :class:`DataFrame` (:issue:`39147`) -- +- Fixed regression in comparisons between ``NaT`` and ``datetime.date`` objects incorrectly returning ``True`` (:issue:`39151`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 561143f48e0ec..3a61de62daf39 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -1,4 +1,7 @@ +import warnings + from cpython.datetime cimport ( + PyDate_Check, PyDateTime_Check, PyDateTime_IMPORT, PyDelta_Check, @@ -125,6 +128,21 @@ cdef class _NaT(datetime): return NotImplemented return result + elif PyDate_Check(other): + # GH#39151 don't defer to datetime.date object + if op == Py_EQ: + return False + if op == Py_NE: + return True + warnings.warn( + "Comparison of NaT with datetime.date is deprecated in " + "order to match the standard library behavior. " + "In a future version these will be considered non-comparable.", + FutureWarning, + stacklevel=1, + ) + return False + return NotImplemented def __add__(self, other): diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 055117680c8b9..3c331f62a1501 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -584,6 +584,40 @@ def test_nat_comparisons_invalid(other_and_type, symbol_and_op): op(other, NaT) +def test_compare_date(): + # GH#39151 comparing NaT with date object is deprecated + # See also: tests.scalar.timestamps.test_comparisons::test_compare_date + + dt = Timestamp.now().to_pydatetime().date() + + for left, right in [(NaT, dt), (dt, NaT)]: + assert not left == right + assert left != right + + with tm.assert_produces_warning(FutureWarning): + assert not left < right + with tm.assert_produces_warning(FutureWarning): + assert not left <= right + with tm.assert_produces_warning(FutureWarning): + assert not left > right + with tm.assert_produces_warning(FutureWarning): + assert not left >= right + + # Once the deprecation is enforced, the following assertions + # can be enabled: + # assert not left == right + # assert left != right + # + # with pytest.raises(TypeError): + # left < right + # with pytest.raises(TypeError): + # left <= right + # with pytest.raises(TypeError): + # left > right + # with pytest.raises(TypeError): + # left >= right + + @pytest.mark.parametrize( "obj", [
- [x] closes #39151 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39196
2021-01-15T22:24:18Z
2021-01-16T01:18:12Z
2021-01-16T01:18:12Z
2021-01-16T01:49:33Z
TST/REF: split large categorical indexing test
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index b36e790f8023b..549a3c8e4a681 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -977,3 +977,11 @@ def loc(x): def iloc(x): return x.iloc + + +def at(x): + return x.at + + +def iat(x): + return x.iat diff --git a/pandas/tests/frame/indexing/test_categorical.py b/pandas/tests/frame/indexing/test_categorical.py index 6137cadc93125..b3e0783d7388f 100644 --- a/pandas/tests/frame/indexing/test_categorical.py +++ b/pandas/tests/frame/indexing/test_categorical.py @@ -7,6 +7,9 @@ from pandas import Categorical, DataFrame, Index, Series import pandas._testing as tm +msg1 = "Cannot setitem on a Categorical with a new category, set the categories first" +msg2 = "Cannot set a Categorical with another, without identical categories" + class TestDataFrameIndexingCategorical: def test_assignment(self): @@ -54,47 +57,44 @@ def test_assignment(self): cat = Categorical([1, 2, 3, 10], categories=[1, 2, 3, 4, 10]) df = DataFrame(Series(cat)) - def test_assigning_ops(self): - # systematically test the assigning operations: - # for all slicing ops: - # for value in categories and value not in categories: - - # - assign a single value -> exp_single_cats_value - - # - assign a complete row (mixed values) -> exp_single_row - - # assign multiple rows (mixed values) (-> array) -> exp_multi_row - - # assign a part of a column with dtype == categorical -> - # exp_parts_cats_col - - # assign a part of a column with dtype != categorical -> - # exp_parts_cats_col - + @pytest.fixture + def orig(self): cats = Categorical(["a", "a", "a", "a", "a", "a", "a"], categories=["a", "b"]) idx = Index(["h", "i", "j", "k", "l", "m", "n"]) values = [1, 1, 1, 1, 1, 1, 1] orig = DataFrame({"cats": cats, "values": values}, index=idx) + return orig - # the expected values - # changed single row + @pytest.fixture + def exp_single_row(self): + # The expected values if we change a single row cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) idx1 = Index(["h", "i", "j", "k", "l", "m", "n"]) values1 = [1, 1, 2, 1, 1, 1, 1] exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1) + return exp_single_row + @pytest.fixture + def exp_multi_row(self): + # assign multiple rows (mixed values) (-> array) -> exp_multi_row # changed multiple rows cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) idx2 = Index(["h", "i", "j", "k", "l", "m", "n"]) values2 = [1, 1, 2, 2, 1, 1, 1] exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2) + return exp_multi_row + @pytest.fixture + def exp_parts_cats_col(self): # changed part of the cats column cats3 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) idx3 = Index(["h", "i", "j", "k", "l", "m", "n"]) values3 = [1, 1, 1, 1, 1, 1, 1] exp_parts_cats_col = DataFrame({"cats": cats3, "values": values3}, index=idx3) + return exp_parts_cats_col + @pytest.fixture + def exp_single_cats_value(self): # changed single value in cats col cats4 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) idx4 = Index(["h", "i", "j", "k", "l", "m", "n"]) @@ -102,222 +102,129 @@ def test_assigning_ops(self): exp_single_cats_value = DataFrame( {"cats": cats4, "values": values4}, index=idx4 ) + return exp_single_cats_value - # iloc - # ############### - # - assign a single value -> exp_single_cats_value - df = orig.copy() - df.iloc[2, 0] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - df = orig.copy() - df.iloc[df.index == "j", 0] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - # - assign a single value not in the current categories set - msg1 = ( - "Cannot setitem on a Categorical with a new category, " - "set the categories first" - ) - msg2 = "Cannot set a Categorical with another, without identical categories" - with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.iloc[2, 0] = "c" - - # - assign a complete row (mixed values) -> exp_single_row - df = orig.copy() - df.iloc[2, :] = ["b", 2] - tm.assert_frame_equal(df, exp_single_row) - - # - assign a complete row (mixed values) not in categories set - with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.iloc[2, :] = ["c", 2] - + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_loc_iloc_setitem_list_of_lists(self, orig, exp_multi_row, indexer): # - assign multiple rows (mixed values) -> exp_multi_row df = orig.copy() - df.iloc[2:4, :] = [["b", 2], ["b", 2]] - tm.assert_frame_equal(df, exp_multi_row) - with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.iloc[2:4, :] = [["c", 2], ["c", 2]] + key = slice(2, 4) + if indexer is tm.loc: + key = slice("j", "k") - # assign a part of a column with dtype == categorical -> - # exp_parts_cats_col - df = orig.copy() - df.iloc[2:4, 0] = Categorical(["b", "b"], categories=["a", "b"]) - tm.assert_frame_equal(df, exp_parts_cats_col) - - with pytest.raises(ValueError, match=msg2): - # different categories -> not sure if this should fail or pass - df = orig.copy() - df.iloc[2:4, 0] = Categorical(list("bb"), categories=list("abc")) - - with pytest.raises(ValueError, match=msg2): - # different values - df = orig.copy() - df.iloc[2:4, 0] = Categorical(list("cc"), categories=list("abc")) + indexer(df)[key, :] = [["b", 2], ["b", 2]] + tm.assert_frame_equal(df, exp_multi_row) - # assign a part of a column with dtype != categorical -> - # exp_parts_cats_col df = orig.copy() - df.iloc[2:4, 0] = ["b", "b"] - tm.assert_frame_equal(df, exp_parts_cats_col) - with pytest.raises(ValueError, match=msg1): - df.iloc[2:4, 0] = ["c", "c"] + indexer(df)[key, :] = [["c", 2], ["c", 2]] - # loc - # ############## + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc, tm.at, tm.iat]) + def test_loc_iloc_at_iat_setitem_single_value_in_categories( + self, orig, exp_single_cats_value, indexer + ): # - assign a single value -> exp_single_cats_value df = orig.copy() - df.loc["j", "cats"] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - df = orig.copy() - df.loc[df.index == "j", "cats"] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - # - assign a single value not in the current categories set - with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.loc["j", "cats"] = "c" - - # - assign a complete row (mixed values) -> exp_single_row - df = orig.copy() - df.loc["j", :] = ["b", 2] - tm.assert_frame_equal(df, exp_single_row) - # - assign a complete row (mixed values) not in categories set - with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.loc["j", :] = ["c", 2] + key = (2, 0) + if indexer in [tm.loc, tm.at]: + key = (df.index[2], df.columns[0]) - # - assign multiple rows (mixed values) -> exp_multi_row - df = orig.copy() - df.loc["j":"k", :] = [["b", 2], ["b", 2]] - tm.assert_frame_equal(df, exp_multi_row) + # "b" is among the categories for df["cat"}] + indexer(df)[key] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + # "c" is not among the categories for df["cat"] with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.loc["j":"k", :] = [["c", 2], ["c", 2]] + indexer(df)[key] = "c" - # assign a part of a column with dtype == categorical -> - # exp_parts_cats_col + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_loc_iloc_setitem_mask_single_value_in_categories( + self, orig, exp_single_cats_value, indexer + ): + # mask with single True df = orig.copy() - df.loc["j":"k", "cats"] = Categorical(["b", "b"], categories=["a", "b"]) - tm.assert_frame_equal(df, exp_parts_cats_col) - with pytest.raises(ValueError, match=msg2): - # different categories -> not sure if this should fail or pass - df = orig.copy() - df.loc["j":"k", "cats"] = Categorical( - ["b", "b"], categories=["a", "b", "c"] - ) - - with pytest.raises(ValueError, match=msg2): - # different values - df = orig.copy() - df.loc["j":"k", "cats"] = Categorical( - ["c", "c"], categories=["a", "b", "c"] - ) + mask = df.index == "j" + key = 0 + if indexer is tm.loc: + key = df.columns[key] - # assign a part of a column with dtype != categorical -> - # exp_parts_cats_col - df = orig.copy() - df.loc["j":"k", "cats"] = ["b", "b"] - tm.assert_frame_equal(df, exp_parts_cats_col) - - with pytest.raises(ValueError, match=msg1): - df.loc["j":"k", "cats"] = ["c", "c"] - - # loc - # ############## - # - assign a single value -> exp_single_cats_value - df = orig.copy() - df.loc["j", df.columns[0]] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - df = orig.copy() - df.loc[df.index == "j", df.columns[0]] = "b" + indexer(df)[mask, key] = "b" tm.assert_frame_equal(df, exp_single_cats_value) - # - assign a single value not in the current categories set - with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.loc["j", df.columns[0]] = "c" - + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_iloc_setitem_full_row_non_categorical_rhs( + self, orig, exp_single_row, indexer + ): # - assign a complete row (mixed values) -> exp_single_row df = orig.copy() - df.loc["j", :] = ["b", 2] - tm.assert_frame_equal(df, exp_single_row) - # - assign a complete row (mixed values) not in categories set - with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.loc["j", :] = ["c", 2] + key = 2 + if indexer is tm.loc: + key = df.index[2] - # - assign multiple rows (mixed values) -> exp_multi_row - df = orig.copy() - df.loc["j":"k", :] = [["b", 2], ["b", 2]] - tm.assert_frame_equal(df, exp_multi_row) + # not categorical dtype, but "b" _is_ among the categories for df["cat"] + indexer(df)[key, :] = ["b", 2] + tm.assert_frame_equal(df, exp_single_row) + # "c" is not among the categories for df["cat"] with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.loc["j":"k", :] = [["c", 2], ["c", 2]] + indexer(df)[key, :] = ["c", 2] + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_loc_iloc_setitem_partial_col_categorical_rhs( + self, orig, exp_parts_cats_col, indexer + ): # assign a part of a column with dtype == categorical -> # exp_parts_cats_col df = orig.copy() - df.loc["j":"k", df.columns[0]] = Categorical(["b", "b"], categories=["a", "b"]) + + key = (slice(2, 4), 0) + if indexer is tm.loc: + key = (slice("j", "k"), df.columns[0]) + + # same categories as we currently have in df["cats"] + compat = Categorical(["b", "b"], categories=["a", "b"]) + indexer(df)[key] = compat tm.assert_frame_equal(df, exp_parts_cats_col) + # categories do not match df["cat"]'s, but "b" is among them + semi_compat = Categorical(list("bb"), categories=list("abc")) with pytest.raises(ValueError, match=msg2): - # different categories -> not sure if this should fail or pass - df = orig.copy() - df.loc["j":"k", df.columns[0]] = Categorical( - ["b", "b"], categories=["a", "b", "c"] - ) + # different categories but holdable values + # -> not sure if this should fail or pass + indexer(df)[key] = semi_compat + # categories do not match df["cat"]'s, and "c" is not among them + incompat = Categorical(list("cc"), categories=list("abc")) with pytest.raises(ValueError, match=msg2): # different values - df = orig.copy() - df.loc["j":"k", df.columns[0]] = Categorical( - ["c", "c"], categories=["a", "b", "c"] - ) - - # assign a part of a column with dtype != categorical -> - # exp_parts_cats_col - df = orig.copy() - df.loc["j":"k", df.columns[0]] = ["b", "b"] - tm.assert_frame_equal(df, exp_parts_cats_col) - - with pytest.raises(ValueError, match=msg1): - df.loc["j":"k", df.columns[0]] = ["c", "c"] + indexer(df)[key] = incompat - # iat + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_loc_iloc_setitem_non_categorical_rhs( + self, orig, exp_parts_cats_col, indexer + ): + # assign a part of a column with dtype != categorical -> exp_parts_cats_col df = orig.copy() - df.iat[2, 0] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - # - assign a single value not in the current categories set - with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.iat[2, 0] = "c" + key = (slice(2, 4), 0) + if indexer is tm.loc: + key = (slice("j", "k"), df.columns[0]) - # at - # - assign a single value -> exp_single_cats_value - df = orig.copy() - df.at["j", "cats"] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) + # "b" is among the categories for df["cat"] + indexer(df)[key] = ["b", "b"] + tm.assert_frame_equal(df, exp_parts_cats_col) - # - assign a single value not in the current categories set + # "c" not part of the categories with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.at["j", "cats"] = "c" + indexer(df)[key] = ["c", "c"] + def test_setitem_mask_categorical(self, exp_multi_row): # fancy indexing + catsf = Categorical( ["a", "a", "c", "c", "a", "a", "a"], categories=["a", "b", "c"] ) @@ -331,19 +238,12 @@ def test_assigning_ops(self): ) assert return_value is None - df[df["cats"] == "c"] = ["b", 2] + mask = df["cats"] == "c" + df[mask] = ["b", 2] # category c is kept in .categories tm.assert_frame_equal(df, exp_fancy) - # set_value - df = orig.copy() - df.at["j", "cats"] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - with pytest.raises(ValueError, match=msg1): - df = orig.copy() - df.at["j", "cats"] = "c" - + def test_loc_setitem_categorical_values_partial_column_slice(self): # Assigning a Category to parts of a int/... column uses the values of # the Categorical df = DataFrame({"a": [1, 1, 1, 1, 1], "b": list("aaaaa")}) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 7c73917e44b22..8b13bafdd012f 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -395,73 +395,64 @@ def test_loc_general(self): tm.assert_series_equal(result, expected) assert result.dtype == object - def test_loc_setitem_consistency(self): - # GH 6149 - # coerce similarly for setitem and loc when rows have a null-slice - expected = DataFrame( + @pytest.fixture + def frame_for_consistency(self): + return DataFrame( { - "date": Series(0, index=range(5), dtype=np.int64), + "date": date_range("2000-01-01", "2000-01-5"), "val": Series(range(5), dtype=np.int64), } ) - df = DataFrame( + def test_loc_setitem_consistency(self, frame_for_consistency): + # GH 6149 + # coerce similarly for setitem and loc when rows have a null-slice + expected = DataFrame( { - "date": date_range("2000-01-01", "2000-01-5"), + "date": Series(0, index=range(5), dtype=np.int64), "val": Series(range(5), dtype=np.int64), } ) + df = frame_for_consistency.copy() df.loc[:, "date"] = 0 tm.assert_frame_equal(df, expected) - df = DataFrame( - { - "date": date_range("2000-01-01", "2000-01-5"), - "val": Series(range(5), dtype=np.int64), - } - ) + df = frame_for_consistency.copy() df.loc[:, "date"] = np.array(0, dtype=np.int64) tm.assert_frame_equal(df, expected) - df = DataFrame( - { - "date": date_range("2000-01-01", "2000-01-5"), - "val": Series(range(5), dtype=np.int64), - } - ) + df = frame_for_consistency.copy() df.loc[:, "date"] = np.array([0, 0, 0, 0, 0], dtype=np.int64) tm.assert_frame_equal(df, expected) + def test_loc_setitem_consistency_dt64_to_str(self, frame_for_consistency): + # GH 6149 + # coerce similarly for setitem and loc when rows have a null-slice + expected = DataFrame( { "date": Series("foo", index=range(5)), "val": Series(range(5), dtype=np.int64), } ) - df = DataFrame( - { - "date": date_range("2000-01-01", "2000-01-5"), - "val": Series(range(5), dtype=np.int64), - } - ) + df = frame_for_consistency.copy() df.loc[:, "date"] = "foo" tm.assert_frame_equal(df, expected) + def test_loc_setitem_consistency_dt64_to_float(self, frame_for_consistency): + # GH 6149 + # coerce similarly for setitem and loc when rows have a null-slice expected = DataFrame( { "date": Series(1.0, index=range(5)), "val": Series(range(5), dtype=np.int64), } ) - df = DataFrame( - { - "date": date_range("2000-01-01", "2000-01-5"), - "val": Series(range(5), dtype=np.int64), - } - ) + df = frame_for_consistency.copy() df.loc[:, "date"] = 1.0 tm.assert_frame_equal(df, expected) + def test_loc_setitem_consistency_single_row(self): # GH 15494 # setting on frame with single row df = DataFrame({"date": Series([Timestamp("20180101")])})
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39195
2021-01-15T21:52:18Z
2021-01-16T00:55:12Z
2021-01-16T00:55:12Z
2021-01-16T02:03:13Z
REGR: fillna on datetime64[ns, UTC] column hits RecursionError
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 55fddb8b732e2..eb9fd89bc8b22 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -27,6 +27,7 @@ Fixed regressions - Fixed regression in :meth:`read_csv` and other read functions were the encoding error policy (``errors``) did not default to ``"replace"`` when no encoding was specified (:issue:`38989`) - Fixed regression in :meth:`DataFrame.replace` raising ``ValueError`` when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) - Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) +- Fixed regression in :meth:`Series.fillna` that raised ``RecursionError`` with ``datetime64[ns, UTC]`` dtype (:issue:`38851`) - Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) - Fixed regression in :meth:`DataFrame.groupby` when aggregating an :class:`ExtensionDType` that could fail for non-numeric values (:issue:`38980`) - Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``KeyError`` with :class:`MultiIndex` and list-like columns indexer enlarging :class:`DataFrame` (:issue:`39147`) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 2f3a06afa2a68..d6e6fcf158a07 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1968,7 +1968,13 @@ class IntBlock(NumericBlock): class DatetimeLikeBlockMixin(HybridMixin, Block): """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock.""" - _can_hold_na = True + @property + def _holder(self): + return DatetimeArray + + @property + def fill_value(self): + return np.datetime64("NaT", "ns") def get_values(self, dtype: Optional[Dtype] = None): """ @@ -2052,8 +2058,10 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List["Block"]: class DatetimeBlock(DatetimeLikeBlockMixin): __slots__ = () is_datetime = True - _holder = DatetimeArray - fill_value = np.datetime64("NaT", "ns") + + @property + def _can_hold_na(self): + return True def _maybe_coerce_values(self, values): """ @@ -2099,18 +2107,18 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): is_extension = True internal_values = Block.internal_values - - _holder = DatetimeBlock._holder _can_hold_element = DatetimeBlock._can_hold_element to_native_types = DatetimeBlock.to_native_types diff = DatetimeBlock.diff - fillna = DatetimeBlock.fillna # i.e. Block.fillna - fill_value = DatetimeBlock.fill_value - _can_hold_na = DatetimeBlock._can_hold_na + fill_value = np.datetime64("NaT", "ns") where = DatetimeBlock.where array_values = ExtensionBlock.array_values + @property + def _holder(self): + return DatetimeArray + def _maybe_coerce_values(self, values): """ Input validation for values passed to __init__. Ensure that @@ -2175,6 +2183,17 @@ def external_values(self): # return an object-dtype ndarray of Timestamps. return np.asarray(self.values.astype("datetime64[ns]", copy=False)) + def fillna(self, value, limit=None, inplace=False, downcast=None): + # We support filling a DatetimeTZ with a `value` whose timezone + # is different by coercing to object. + if self._can_hold_element(value): + return super().fillna(value, limit, inplace, downcast) + + # different timezones, or a non-tz + return self.astype(object).fillna( + value, limit=limit, inplace=inplace, downcast=downcast + ) + def quantile(self, qs, interpolation="linear", axis=0): naive = self.values.view("M8[ns]") @@ -2211,9 +2230,11 @@ def _check_ndim(self, values, ndim): return ndim -class TimeDeltaBlock(DatetimeLikeBlockMixin): +class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock): __slots__ = () is_timedelta = True + _can_hold_na = True + is_numeric = False fill_value = np.timedelta64("NaT", "ns") def _maybe_coerce_values(self, values): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index cc5576719ff43..c7d419840fb13 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1891,7 +1891,7 @@ def _consolidate(blocks): merged_blocks = _merge_blocks( list(group_blocks), dtype=dtype, can_consolidate=_can_consolidate ) - new_blocks.extend(merged_blocks) + new_blocks = extend_blocks(merged_blocks, new_blocks) return new_blocks diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index 3fa411b421015..69a9a81e66ac4 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone import numpy as np import pytest @@ -13,6 +13,7 @@ Series, Timedelta, Timestamp, + date_range, isna, ) import pandas._testing as tm @@ -724,6 +725,14 @@ def test_fillna_method_and_limit_invalid(self): with pytest.raises(ValueError, match=msg): ser.fillna(1, limit=limit, method=method) + def test_fillna_datetime64_with_timezone_tzinfo(self): + # https://github.com/pandas-dev/pandas/issues/38851 + s = Series(date_range("2020", periods=3, tz="UTC")) + expected = s.astype(object) + s[1] = NaT + result = s.fillna(datetime(2020, 1, 2, tzinfo=timezone.utc)) + tm.assert_series_equal(result, expected) + class TestFillnaPad: def test_fillna_bug(self):
- [ ] closes #38851 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry @jbrockmendel this reverts #37040 in it's entirety for backport feel free to push to this branch if we **need** any of the ancillary cleanup on 1.2.x otherwise can open a new PR to add those cleanups back to master.
https://api.github.com/repos/pandas-dev/pandas/pulls/39194
2021-01-15T20:20:22Z
2021-01-16T01:09:21Z
2021-01-16T01:09:21Z
2021-01-16T12:32:09Z
CI: Set xfail to strict=False for network tests
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index 8ddb860597ddd..3727fe9484084 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -209,7 +209,7 @@ def test_read_s3_fails(self, s3so): with pytest.raises(IOError, match=msg): read_csv("s3://cant_get_it/file.csv") - @pytest.mark.xfail(reason="GH#39155 s3fs upgrade") + @pytest.mark.xfail(reason="GH#39155 s3fs upgrade", strict=False) def test_write_s3_csv_fails(self, tips_df, s3so): # GH 32486 # Attempting to write to an invalid S3 path should raise @@ -225,7 +225,7 @@ def test_write_s3_csv_fails(self, tips_df, s3so): "s3://an_s3_bucket_data_doesnt_exit/not_real.csv", storage_options=s3so ) - @pytest.mark.xfail(reason="GH#39155 s3fs upgrade") + @pytest.mark.xfail(reason="GH#39155 s3fs upgrade", strict=False) @td.skip_if_no("pyarrow") def test_write_s3_parquet_fails(self, tips_df, s3so): # GH 27679
- [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them This one is ugly. Botocore and boto3 were upgraded tonight to 1.19.55 and 1.16.55. Since aiobotocore requires them to be .52 this is no longer installed, but aiobotocore is an required dependency from s3fs 0.5.*. So this get's downgraded to 0.4.2 were only botocore was a required dependency (no version specification). As soon as the requirements of aiobotocore are updated again this will switch back to s3fs=0.5.2 which will cause the tests to fail again. Hence setting them to strict=False sorry for the long explanation :)
https://api.github.com/repos/pandas-dev/pandas/pulls/39193
2021-01-15T19:55:06Z
2021-01-16T01:14:54Z
2021-01-16T01:14:54Z
2021-01-16T15:01:19Z
Revert "BUG/REG: RollingGroupby MultiIndex levels dropped (#38737)"
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 55fddb8b732e2..ebac06b80ad67 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -15,7 +15,6 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`to_csv` that created corrupted zip files when there were more rows than ``chunksize`` (:issue:`38714`) -- Fixed regression in ``groupby().rolling()`` where :class:`MultiIndex` levels were dropped (:issue:`38523`) - Fixed regression in repr of float-like strings of an ``object`` dtype having trailing 0's truncated after the decimal (:issue:`38708`) - Fixed regression in :meth:`DataFrame.groupby()` with :class:`Categorical` grouping column not showing unused categories for ``grouped.indices`` (:issue:`38642`) - Fixed regression in :meth:`DataFrame.any` and :meth:`DataFrame.all` not returning a result for tz-aware ``datetime64`` columns (:issue:`38723`) diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py index c1aed4eb3409b..ad2eafe7295b0 100644 --- a/pandas/core/shared_docs.py +++ b/pandas/core/shared_docs.py @@ -108,7 +108,7 @@ Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group. group_keys : bool, default True - When calling ``groupby().apply()``, add group keys to index to identify pieces. + When calling apply, add group keys to index to identify pieces. squeeze : bool, default False Reduce the dimensionality of the return type if possible, otherwise return a consistent type. diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 29e7050639a2d..2dce27a76eb00 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -794,22 +794,28 @@ def _apply( numba_cache_key, **kwargs, ) - # Reconstruct the resulting MultiIndex + # Reconstruct the resulting MultiIndex from tuples # 1st set of levels = group by labels - # 2nd set of levels = original DataFrame/Series index - grouped_object_index = self.obj.index - grouped_index_name = [*grouped_object_index.names] - groupby_keys = [grouping.name for grouping in self._groupby.grouper._groupings] - result_index_names = groupby_keys + grouped_index_name + # 2nd set of levels = original index + # Ignore 2nd set of levels if a group by label include an index level + result_index_names = [ + grouping.name for grouping in self._groupby.grouper._groupings + ] + grouped_object_index = None - drop_columns = [ + column_keys = [ key - for key in groupby_keys + for key in result_index_names if key not in self.obj.index.names or key is None ] - if len(drop_columns) != len(groupby_keys): - # Our result will have kept groupby columns which should be dropped - result = result.drop(columns=drop_columns, errors="ignore") + + if len(column_keys) == len(result_index_names): + grouped_object_index = self.obj.index + grouped_index_name = [*grouped_object_index.names] + result_index_names += grouped_index_name + else: + # Our result will have still kept the column in the result + result = result.drop(columns=column_keys, errors="ignore") codes = self._groupby.grouper.codes levels = self._groupby.grouper.levels diff --git a/pandas/tests/window/test_groupby.py b/pandas/tests/window/test_groupby.py index f915da3330ba7..b89fb35ac3a70 100644 --- a/pandas/tests/window/test_groupby.py +++ b/pandas/tests/window/test_groupby.py @@ -556,31 +556,23 @@ def test_groupby_rolling_nans_in_index(self, rollings, key): with pytest.raises(ValueError, match=f"{key} must be monotonic"): df.groupby("c").rolling("60min", **rollings) - @pytest.mark.parametrize("group_keys", [True, False]) - def test_groupby_rolling_group_keys(self, group_keys): + def test_groupby_rolling_group_keys(self): # GH 37641 - # GH 38523: GH 37641 actually was not a bug. - # group_keys only applies to groupby.apply directly arrays = [["val1", "val1", "val2"], ["val1", "val1", "val2"]] index = MultiIndex.from_arrays(arrays, names=("idx1", "idx2")) s = Series([1, 2, 3], index=index) - result = s.groupby(["idx1", "idx2"], group_keys=group_keys).rolling(1).mean() + result = s.groupby(["idx1", "idx2"], group_keys=False).rolling(1).mean() expected = Series( [1.0, 2.0, 3.0], index=MultiIndex.from_tuples( - [ - ("val1", "val1", "val1", "val1"), - ("val1", "val1", "val1", "val1"), - ("val2", "val2", "val2", "val2"), - ], - names=["idx1", "idx2", "idx1", "idx2"], + [("val1", "val1"), ("val1", "val1"), ("val2", "val2")], + names=["idx1", "idx2"], ), ) tm.assert_series_equal(result, expected) def test_groupby_rolling_index_level_and_column_label(self): - # The groupby keys should not appear as a resulting column arrays = [["val1", "val1", "val2"], ["val1", "val1", "val2"]] index = MultiIndex.from_arrays(arrays, names=("idx1", "idx2")) @@ -589,12 +581,7 @@ def test_groupby_rolling_index_level_and_column_label(self): expected = DataFrame( {"B": [0.0, 1.0, 2.0]}, index=MultiIndex.from_tuples( - [ - ("val1", 1, "val1", "val1"), - ("val1", 1, "val1", "val1"), - ("val2", 2, "val2", "val2"), - ], - names=["idx1", "A", "idx1", "idx2"], + [("val1", 1), ("val1", 1), ("val2", 2)], names=["idx1", "A"] ), ) tm.assert_frame_equal(result, expected) @@ -653,30 +640,6 @@ def test_groupby_rolling_resulting_multiindex(self): ) tm.assert_index_equal(result.index, expected_index) - def test_groupby_level(self): - # GH 38523 - arrays = [ - ["Falcon", "Falcon", "Parrot", "Parrot"], - ["Captive", "Wild", "Captive", "Wild"], - ] - index = MultiIndex.from_arrays(arrays, names=("Animal", "Type")) - df = DataFrame({"Max Speed": [390.0, 350.0, 30.0, 20.0]}, index=index) - result = df.groupby(level=0)["Max Speed"].rolling(2).sum() - expected = Series( - [np.nan, 740.0, np.nan, 50.0], - index=MultiIndex.from_tuples( - [ - ("Falcon", "Falcon", "Captive"), - ("Falcon", "Falcon", "Wild"), - ("Parrot", "Parrot", "Captive"), - ("Parrot", "Parrot", "Wild"), - ], - names=["Animal", "Animal", "Type"], - ), - name="Max Speed", - ) - tm.assert_series_equal(result, expected) - class TestExpanding: def setup_method(self):
This reverts commit a37f1a45e83d7f803d7fcab7d384da28e9c1e714. reverts PR #38737 I think we ended up deciding to revert on master and backport to keep master and 1.2.x in sync and not release this change in 1.2.1 to allow for further discussion. once this revert PR merged: - [x] backport - [x] the blocker tag can then be removed from #38787 - [x] #38523 will be reopen temporarily - [ ] @mroeschke will open a new PR with these changes (in draft? milestoned 1.2.2?) if not these changes, the mutliindex with a single level may still need resolution (and backport) to close #38523 cc @mroeschke @jorisvandenbossche add 1.2.1 milestone for this revert for backport.
https://api.github.com/repos/pandas-dev/pandas/pulls/39191
2021-01-15T17:26:31Z
2021-01-16T01:10:14Z
2021-01-16T01:10:14Z
2021-01-16T09:58:33Z
REGR: Different results from DataFrame.apply and str accessor
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 1c8db4dd32393..731836086aaa8 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -25,6 +25,7 @@ Fixed regressions - Fixed regression in :func:`read_excel` with non-rawbyte file handles (:issue:`38788`) - Fixed regression in :meth:`Rolling.skew` and :meth:`Rolling.kurt` modifying the object inplace (:issue:`38908`) - Fixed regression in :meth:`read_csv` and other read functions were the encoding error policy (``errors``) did not default to ``"replace"`` when no encoding was specified (:issue:`38989`) +- Fixed regression in :meth:`DataFrame.apply` with ``axis=1`` using str accessor in apply function (:issue:`38979`) - Fixed regression in :meth:`DataFrame.replace` raising ``ValueError`` when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) - Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) - Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index eb14f75ab56f7..067fff3e0a744 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -104,7 +104,7 @@ def wrapper(self, *args, **kwargs): def _map_and_wrap(name, docstring): @forbid_nonstring_types(["bytes"], name=name) def wrapper(self): - result = getattr(self._array, f"_str_{name}")() + result = getattr(self._data.array, f"_str_{name}")() return self._wrap_result(result) wrapper.__doc__ = docstring @@ -149,8 +149,7 @@ def __init__(self, data): self._inferred_dtype = self._validate(data) self._is_categorical = is_categorical_dtype(data.dtype) self._is_string = isinstance(data.dtype, StringDtype) - array = data.array - self._array = array + self._data = data self._index = self._name = None if isinstance(data, ABCSeries): @@ -214,7 +213,7 @@ def _validate(data): return inferred_dtype def __getitem__(self, key): - result = self._array._str_getitem(key) + result = self._data.array._str_getitem(key) return self._wrap_result(result) def __iter__(self): @@ -739,13 +738,13 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): @Appender(_shared_docs["str_split"] % {"side": "beginning", "method": "split"}) @forbid_nonstring_types(["bytes"]) def split(self, pat=None, n=-1, expand=False): - result = self._array._str_split(pat, n, expand) + result = self._data.array._str_split(pat, n, expand) return self._wrap_result(result, returns_string=expand, expand=expand) @Appender(_shared_docs["str_split"] % {"side": "end", "method": "rsplit"}) @forbid_nonstring_types(["bytes"]) def rsplit(self, pat=None, n=-1, expand=False): - result = self._array._str_rsplit(pat, n=n) + result = self._data.array._str_rsplit(pat, n=n) return self._wrap_result(result, expand=expand, returns_string=expand) _shared_docs[ @@ -841,7 +840,7 @@ def rsplit(self, pat=None, n=-1, expand=False): ) @forbid_nonstring_types(["bytes"]) def partition(self, sep=" ", expand=True): - result = self._array._str_partition(sep, expand) + result = self._data.array._str_partition(sep, expand) return self._wrap_result(result, expand=expand, returns_string=expand) @Appender( @@ -855,7 +854,7 @@ def partition(self, sep=" ", expand=True): ) @forbid_nonstring_types(["bytes"]) def rpartition(self, sep=" ", expand=True): - result = self._array._str_rpartition(sep, expand) + result = self._data.array._str_rpartition(sep, expand) return self._wrap_result(result, expand=expand, returns_string=expand) def get(self, i): @@ -909,7 +908,7 @@ def get(self, i): 5 None dtype: object """ - result = self._array._str_get(i) + result = self._data.array._str_get(i) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -975,7 +974,7 @@ def join(self, sep): 4 NaN dtype: object """ - result = self._array._str_join(sep) + result = self._data.array._str_join(sep) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -1103,7 +1102,7 @@ def contains(self, pat, case=True, flags=0, na=None, regex=True): 4 False dtype: bool """ - result = self._array._str_contains(pat, case, flags, na, regex) + result = self._data.array._str_contains(pat, case, flags, na, regex) return self._wrap_result(result, fill_value=na, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -1135,7 +1134,7 @@ def match(self, pat, case=True, flags=0, na=None): re.match. extract : Extract matched groups. """ - result = self._array._str_match(pat, case=case, flags=flags, na=na) + result = self._data.array._str_match(pat, case=case, flags=flags, na=na) return self._wrap_result(result, fill_value=na, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -1168,7 +1167,7 @@ def fullmatch(self, pat, case=True, flags=0, na=None): matches the regular expression. extract : Extract matched groups. """ - result = self._array._str_fullmatch(pat, case=case, flags=flags, na=na) + result = self._data.array._str_fullmatch(pat, case=case, flags=flags, na=na) return self._wrap_result(result, fill_value=na, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -1304,7 +1303,7 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None): ) warnings.warn(msg, FutureWarning, stacklevel=3) regex = True - result = self._array._str_replace( + result = self._data.array._str_replace( pat, repl, n=n, case=case, flags=flags, regex=regex ) return self._wrap_result(result) @@ -1350,7 +1349,7 @@ def repeat(self, repeats): 2 ccc dtype: object """ - result = self._array._str_repeat(repeats) + result = self._data.array._str_repeat(repeats) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -1418,7 +1417,7 @@ def pad(self, width, side="left", fillchar=" "): msg = f"width must be of integer type, not {type(width).__name__}" raise TypeError(msg) - result = self._array._str_pad(width, side=side, fillchar=fillchar) + result = self._data.array._str_pad(width, side=side, fillchar=fillchar) return self._wrap_result(result) _shared_docs[ @@ -1592,7 +1591,7 @@ def slice(self, start=None, stop=None, step=None): 2 cm dtype: object """ - result = self._array._str_slice(start, stop, step) + result = self._data.array._str_slice(start, stop, step) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -1668,7 +1667,7 @@ def slice_replace(self, start=None, stop=None, repl=None): 4 aXde dtype: object """ - result = self._array._str_slice_replace(start, stop, repl) + result = self._data.array._str_slice_replace(start, stop, repl) return self._wrap_result(result) def decode(self, encoding, errors="strict"): @@ -1694,7 +1693,7 @@ def decode(self, encoding, errors="strict"): else: decoder = codecs.getdecoder(encoding) f = lambda x: decoder(x, errors)[0] - arr = self._array + arr = self._data.array # assert isinstance(arr, (StringArray,)) result = arr._str_map(f) return self._wrap_result(result) @@ -1715,7 +1714,7 @@ def encode(self, encoding, errors="strict"): ------- encoded : Series/Index of objects """ - result = self._array._str_encode(encoding, errors) + result = self._data.array._str_encode(encoding, errors) return self._wrap_result(result, returns_string=False) _shared_docs[ @@ -1793,7 +1792,7 @@ def encode(self, encoding, errors="strict"): ) @forbid_nonstring_types(["bytes"]) def strip(self, to_strip=None): - result = self._array._str_strip(to_strip) + result = self._data.array._str_strip(to_strip) return self._wrap_result(result) @Appender( @@ -1802,7 +1801,7 @@ def strip(self, to_strip=None): ) @forbid_nonstring_types(["bytes"]) def lstrip(self, to_strip=None): - result = self._array._str_lstrip(to_strip) + result = self._data.array._str_lstrip(to_strip) return self._wrap_result(result) @Appender( @@ -1811,7 +1810,7 @@ def lstrip(self, to_strip=None): ) @forbid_nonstring_types(["bytes"]) def rstrip(self, to_strip=None): - result = self._array._str_rstrip(to_strip) + result = self._data.array._str_rstrip(to_strip) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -1870,7 +1869,7 @@ def wrap(self, width, **kwargs): 1 another line\nto be\nwrapped dtype: object """ - result = self._array._str_wrap(width, **kwargs) + result = self._data.array._str_wrap(width, **kwargs) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -1912,7 +1911,7 @@ def get_dummies(self, sep="|"): """ # we need to cast to Series of strings as only that has all # methods available for making the dummies... - result, name = self._array._str_get_dummies(sep) + result, name = self._data.array._str_get_dummies(sep) return self._wrap_result( result, name=name, @@ -1939,7 +1938,7 @@ def translate(self, table): ------- Series or Index """ - result = self._array._str_translate(table) + result = self._data.array._str_translate(table) return self._wrap_result(result) @forbid_nonstring_types(["bytes"]) @@ -2007,7 +2006,7 @@ def count(self, pat, flags=0): >>> pd.Index(['A', 'A', 'Aaba', 'cat']).str.count('a') Int64Index([0, 0, 2, 1], dtype='int64') """ - result = self._array._str_count(pat, flags) + result = self._data.array._str_count(pat, flags) return self._wrap_result(result, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -2064,7 +2063,7 @@ def startswith(self, pat, na=None): 3 False dtype: bool """ - result = self._array._str_startswith(pat, na=na) + result = self._data.array._str_startswith(pat, na=na) return self._wrap_result(result, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -2121,7 +2120,7 @@ def endswith(self, pat, na=None): 3 False dtype: bool """ - result = self._array._str_endswith(pat, na=na) + result = self._data.array._str_endswith(pat, na=na) return self._wrap_result(result, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -2214,7 +2213,7 @@ def findall(self, pat, flags=0): 2 [b, b] dtype: object """ - result = self._array._str_findall(pat, flags) + result = self._data.array._str_findall(pat, flags) return self._wrap_result(result, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -2421,7 +2420,7 @@ def find(self, sub, start=0, end=None): msg = f"expected a string object, not {type(sub).__name__}" raise TypeError(msg) - result = self._array._str_find(sub, start, end) + result = self._data.array._str_find(sub, start, end) return self._wrap_result(result, returns_string=False) @Appender( @@ -2438,7 +2437,7 @@ def rfind(self, sub, start=0, end=None): msg = f"expected a string object, not {type(sub).__name__}" raise TypeError(msg) - result = self._array._str_rfind(sub, start=start, end=end) + result = self._data.array._str_rfind(sub, start=start, end=end) return self._wrap_result(result, returns_string=False) @forbid_nonstring_types(["bytes"]) @@ -2458,7 +2457,7 @@ def normalize(self, form): ------- normalized : Series/Index of objects """ - result = self._array._str_normalize(form) + result = self._data.array._str_normalize(form) return self._wrap_result(result) _shared_docs[ @@ -2505,7 +2504,7 @@ def index(self, sub, start=0, end=None): msg = f"expected a string object, not {type(sub).__name__}" raise TypeError(msg) - result = self._array._str_index(sub, start=start, end=end) + result = self._data.array._str_index(sub, start=start, end=end) return self._wrap_result(result, returns_string=False) @Appender( @@ -2523,7 +2522,7 @@ def rindex(self, sub, start=0, end=None): msg = f"expected a string object, not {type(sub).__name__}" raise TypeError(msg) - result = self._array._str_rindex(sub, start=start, end=end) + result = self._data.array._str_rindex(sub, start=start, end=end) return self._wrap_result(result, returns_string=False) def len(self): @@ -2572,7 +2571,7 @@ def len(self): 5 3.0 dtype: float64 """ - result = self._array._str_len() + result = self._data.array._str_len() return self._wrap_result(result, returns_string=False) _shared_docs[ @@ -2672,37 +2671,37 @@ def len(self): @Appender(_shared_docs["casemethods"] % _doc_args["lower"]) @forbid_nonstring_types(["bytes"]) def lower(self): - result = self._array._str_lower() + result = self._data.array._str_lower() return self._wrap_result(result) @Appender(_shared_docs["casemethods"] % _doc_args["upper"]) @forbid_nonstring_types(["bytes"]) def upper(self): - result = self._array._str_upper() + result = self._data.array._str_upper() return self._wrap_result(result) @Appender(_shared_docs["casemethods"] % _doc_args["title"]) @forbid_nonstring_types(["bytes"]) def title(self): - result = self._array._str_title() + result = self._data.array._str_title() return self._wrap_result(result) @Appender(_shared_docs["casemethods"] % _doc_args["capitalize"]) @forbid_nonstring_types(["bytes"]) def capitalize(self): - result = self._array._str_capitalize() + result = self._data.array._str_capitalize() return self._wrap_result(result) @Appender(_shared_docs["casemethods"] % _doc_args["swapcase"]) @forbid_nonstring_types(["bytes"]) def swapcase(self): - result = self._array._str_swapcase() + result = self._data.array._str_swapcase() return self._wrap_result(result) @Appender(_shared_docs["casemethods"] % _doc_args["casefold"]) @forbid_nonstring_types(["bytes"]) def casefold(self): - result = self._array._str_casefold() + result = self._data.array._str_casefold() return self._wrap_result(result) _shared_docs[ diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index ac9b160ab0968..8e25d5a43ee3d 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -3670,3 +3670,11 @@ def test_str_get_stringarray_multiple_nans(): result = s.str.get(2) expected = Series(pd.array([pd.NA, pd.NA, pd.NA, "c"])) tm.assert_series_equal(result, expected) + + +def test_str_accessor_in_apply_func(): + # https://github.com/pandas-dev/pandas/issues/38979 + df = DataFrame(zip("abc", "def")) + expected = Series(["A/D", "B/E", "C/F"]) + result = df.apply(lambda f: "/".join(f.str.upper()), axis=1) + tm.assert_series_equal(result, expected)
- [ ] closes #38979 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry @jbrockmendel despite my comment https://github.com/pandas-dev/pandas/issues/38979#issuecomment-760470446, I had no joy trying to locate the caching issue.
https://api.github.com/repos/pandas-dev/pandas/pulls/39188
2021-01-15T15:17:31Z
2021-01-16T01:12:46Z
2021-01-16T01:12:46Z
2021-01-16T10:02:08Z
Backport PR #39161 on branch 1.2.x (Fix regression in loc setitem raising KeyError when enlarging df with multiindex)
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 1c8db4dd32393..55fddb8b732e2 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -29,7 +29,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) - Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) - Fixed regression in :meth:`DataFrame.groupby` when aggregating an :class:`ExtensionDType` that could fail for non-numeric values (:issue:`38980`) -- +- Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``KeyError`` with :class:`MultiIndex` and list-like columns indexer enlarging :class:`DataFrame` (:issue:`39147`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 9ddce9c0aab66..94ddbbdf589d4 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -660,9 +660,9 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None): if self.ndim != 2: return - if isinstance(key, tuple) and not isinstance(self.obj.index, ABCMultiIndex): + if isinstance(key, tuple) and len(key) > 1: # key may be a tuple if we are .loc - # if index is not a MultiIndex, set key to column part + # if length of key is > 1 set key to column part key = key[column_axis] axis = column_axis diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index 42525fc575397..f381a3b205e8c 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -305,6 +305,21 @@ def test_multiindex_one_dimensional_tuple_columns(self, indexer): expected = DataFrame([0, 2], index=mi) tm.assert_frame_equal(obj, expected) + @pytest.mark.parametrize( + "indexer, exp_value", [(slice(None), 1.0), ((1, 2), np.nan)] + ) + def test_multiindex_setitem_columns_enlarging(self, indexer, exp_value): + # GH#39147 + mi = MultiIndex.from_tuples([(1, 2), (3, 4)]) + df = DataFrame([[1, 2], [3, 4]], index=mi, columns=["a", "b"]) + df.loc[indexer, ["c", "d"]] = 1.0 + expected = DataFrame( + [[1, 2, 1.0, 1.0], [3, 4, exp_value, exp_value]], + index=mi, + columns=["a", "b", "c", "d"], + ) + tm.assert_frame_equal(df, expected) + @pytest.mark.parametrize( "indexer, pos",
Backport PR #39161: Fix regression in loc setitem raising KeyError when enlarging df with multiindex
https://api.github.com/repos/pandas-dev/pandas/pulls/39187
2021-01-15T14:15:10Z
2021-01-15T15:21:15Z
2021-01-15T15:21:15Z
2021-01-15T15:21:15Z
REF: extract classes in pandas/core/describe.py
diff --git a/pandas/core/describe.py b/pandas/core/describe.py index 22de5ae1e082f..09862b72c4a4f 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -5,13 +5,14 @@ """ from __future__ import annotations +from abc import ABC, abstractmethod from typing import TYPE_CHECKING, List, Optional, Sequence, Union, cast import warnings import numpy as np from pandas._libs.tslibs import Timestamp -from pandas._typing import FrameOrSeries, Hashable +from pandas._typing import FrameOrSeries, FrameOrSeriesUnion, Hashable from pandas.util._validators import validate_percentile from pandas.core.dtypes.common import ( @@ -62,106 +63,138 @@ def describe_ndframe( """ percentiles = refine_percentiles(percentiles) + describer: NDFrameDescriberAbstract if obj.ndim == 1: - result_series = describe_series( - cast("Series", obj), - percentiles, - datetime_is_numeric, + describer = SeriesDescriber( + obj=cast("Series", obj), + datetime_is_numeric=datetime_is_numeric, + ) + else: + describer = DataFrameDescriber( + obj=cast("DataFrame", obj), + include=include, + exclude=exclude, + datetime_is_numeric=datetime_is_numeric, ) - return cast(FrameOrSeries, result_series) - - frame = cast("DataFrame", obj) - - if frame.ndim == 2 and frame.columns.size == 0: - raise ValueError("Cannot describe a DataFrame without columns") - - result_frame = describe_frame( - frame=frame, - include=include, - exclude=exclude, - percentiles=percentiles, - datetime_is_numeric=datetime_is_numeric, - ) - return cast(FrameOrSeries, result_frame) + result = describer.describe(percentiles=percentiles) + return cast(FrameOrSeries, result) -def describe_series( - series: "Series", - percentiles: Sequence[float], - datetime_is_numeric: bool, -) -> Series: - """Describe series. - The reason for the delegation to ``describe_1d`` only: - to allow for a proper stacklevel of the FutureWarning. +class NDFrameDescriberAbstract(ABC): + """Abstract class for describing dataframe or series. Parameters ---------- - series : Series - Series to be described. - percentiles : list-like of numbers - The percentiles to include in the output. - datetime_is_numeric : bool, default False + obj : Series or DataFrame + Object to be described. + datetime_is_numeric : bool Whether to treat datetime dtypes as numeric. - - Returns - ------- - Series """ - return describe_1d( - series, - percentiles, - datetime_is_numeric, - is_series=True, - ) + def __init__(self, obj: "FrameOrSeriesUnion", datetime_is_numeric: bool): + self.obj = obj + self.datetime_is_numeric = datetime_is_numeric -def describe_frame( - frame: "DataFrame", - include: Optional[Union[str, Sequence[str]]], - exclude: Optional[Union[str, Sequence[str]]], - percentiles: Sequence[float], - datetime_is_numeric: bool, -) -> DataFrame: - """Describe DataFrame. + @abstractmethod + def describe(self, percentiles: Sequence[float]) -> FrameOrSeriesUnion: + """Do describe either series or dataframe. + + Parameters + ---------- + percentiles : list-like of numbers + The percentiles to include in the output. + """ + + +class SeriesDescriber(NDFrameDescriberAbstract): + """Class responsible for creating series description.""" + + obj: "Series" + + def describe(self, percentiles: Sequence[float]) -> Series: + return describe_1d( + self.obj, + percentiles=percentiles, + datetime_is_numeric=self.datetime_is_numeric, + is_series=True, + ) + + +class DataFrameDescriber(NDFrameDescriberAbstract): + """Class responsible for creating dataobj description. Parameters ---------- - frame : DataFrame + obj : DataFrame DataFrame to be described. - include : 'all', list-like of dtypes or None (default), optional + include : 'all', list-like of dtypes or None A white list of data types to include in the result. - exclude : list-like of dtypes or None (default), optional, + exclude : list-like of dtypes or None A black list of data types to omit from the result. - percentiles : list-like of numbers - The percentiles to include in the output. - datetime_is_numeric : bool, default False + datetime_is_numeric : bool Whether to treat datetime dtypes as numeric. - - Returns - ------- - DataFrame """ - data = select_columns( - frame=frame, - include=include, - exclude=exclude, - datetime_is_numeric=datetime_is_numeric, - ) - ldesc = [ - describe_1d(s, percentiles, datetime_is_numeric, is_series=False) - for _, s in data.items() - ] - - col_names = reorder_columns(ldesc) - d = concat( - [x.reindex(col_names, copy=False) for x in ldesc], - axis=1, - sort=False, - ) - d.columns = data.columns.copy() - return d + def __init__( + self, + obj: "DataFrame", + *, + include: Optional[Union[str, Sequence[str]]], + exclude: Optional[Union[str, Sequence[str]]], + datetime_is_numeric: bool, + ): + self.include = include + self.exclude = exclude + + if obj.ndim == 2 and obj.columns.size == 0: + raise ValueError("Cannot describe a DataFrame without columns") + + super().__init__(obj, datetime_is_numeric=datetime_is_numeric) + + def describe(self, percentiles: Sequence[float]) -> DataFrame: + data = self._select_data() + + ldesc = [ + describe_1d( + series, + percentiles=percentiles, + datetime_is_numeric=self.datetime_is_numeric, + is_series=False, + ) + for _, series in data.items() + ] + + col_names = reorder_columns(ldesc) + d = concat( + [x.reindex(col_names, copy=False) for x in ldesc], + axis=1, + sort=False, + ) + d.columns = data.columns.copy() + return d + + def _select_data(self): + """Select columns to be described.""" + if (self.include is None) and (self.exclude is None): + # when some numerics are found, keep only numerics + default_include = [np.number] + if self.datetime_is_numeric: + default_include.append("datetime") + data = self.obj.select_dtypes(include=default_include) + if len(data.columns) == 0: + data = self.obj + elif self.include == "all": + if self.exclude is not None: + msg = "exclude must be None when include is 'all'" + raise ValueError(msg) + data = self.obj + else: + data = self.obj.select_dtypes( + include=self.include, + exclude=self.exclude, + ) + return data def reorder_columns(ldesc: Sequence["Series"]) -> List[Hashable]: @@ -175,32 +208,6 @@ def reorder_columns(ldesc: Sequence["Series"]) -> List[Hashable]: return names -def select_columns( - frame: "DataFrame", - include: Optional[Union[str, Sequence[str]]], - exclude: Optional[Union[str, Sequence[str]]], - datetime_is_numeric: bool, -) -> DataFrame: - """Select columns to be described.""" - if (include is None) and (exclude is None): - # when some numerics are found, keep only numerics - default_include = [np.number] - if datetime_is_numeric: - default_include.append("datetime") - data = frame.select_dtypes(include=default_include) - if len(data.columns) == 0: - data = frame - elif include == "all": - if exclude is not None: - msg = "exclude must be None when include is 'all'" - raise ValueError(msg) - data = frame - else: - data = frame.select_dtypes(include=include, exclude=exclude) - - return data - - def describe_numeric_1d(series: "Series", percentiles: Sequence[float]) -> Series: """Describe series containing numerical data.
- [ ] xref #36833 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Extract classes ``SeriesDescriber`` and ``DataFrameDescriber``. In the next steps I am going to enable strategy pattern and move corresponding describe functions to the concrete strategy classes (for each datatype).
https://api.github.com/repos/pandas-dev/pandas/pulls/39186
2021-01-15T12:12:34Z
2021-01-19T20:23:32Z
2021-01-19T20:23:32Z
2021-01-20T03:31:05Z
DOC: set the documentation language
diff --git a/doc/source/conf.py b/doc/source/conf.py index 488f172fa1d1e..7f7ddd8209272 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -164,7 +164,7 @@ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -# language = None +language = "en" # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used:
Ensures the language is specified in the generated HTML. [Documentation on the configuration option.](https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language) Before: ``` $ curl -s https://pandas.pydata.org/docs/dev/getting_started/comparison/comparison_with_spreadsheets.html | grep "<html" <html> ``` After: ``` $ python make.py --single getting_started/comparison/comparison_with_spreadsheets.rst $ grep "<html" build/html/getting_started/comparison/comparison_with_spreadsheets.html <html lang="en"> ``` - [ ] ~~closes #xxxx~~ - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] ~~whatsnew entry~~
https://api.github.com/repos/pandas-dev/pandas/pulls/39185
2021-01-15T07:22:26Z
2021-01-21T17:46:42Z
2021-01-21T17:46:42Z
2021-01-21T17:46:42Z
CI/DOC: Add option to build whatsnew
diff --git a/doc/make.py b/doc/make.py index d90cd2428360d..a81ba7afd9f81 100755 --- a/doc/make.py +++ b/doc/make.py @@ -41,12 +41,14 @@ def __init__( self, num_jobs=0, include_api=True, + whatsnew=False, single_doc=None, verbosity=0, warnings_are_errors=False, ): self.num_jobs = num_jobs self.include_api = include_api + self.whatsnew = whatsnew self.verbosity = verbosity self.warnings_are_errors = warnings_are_errors @@ -56,6 +58,8 @@ def __init__( os.environ["SPHINX_PATTERN"] = single_doc elif not include_api: os.environ["SPHINX_PATTERN"] = "-api" + elif whatsnew: + os.environ["SPHINX_PATTERN"] = "whatsnew" self.single_doc_html = None if single_doc and single_doc.endswith(".rst"): @@ -235,6 +239,9 @@ def html(self): self._open_browser(self.single_doc_html) else: self._add_redirects() + if self.whatsnew: + self._open_browser(os.path.join("whatsnew", "index.html")) + return ret_code def latex(self, force=False): @@ -302,6 +309,12 @@ def main(): argparser.add_argument( "--no-api", default=False, help="omit api and autosummary", action="store_true" ) + argparser.add_argument( + "--whatsnew", + default=False, + help="only build whatsnew (and api for links)", + action="store_true", + ) argparser.add_argument( "--single", metavar="FILENAME", @@ -353,6 +366,7 @@ def main(): builder = DocBuilder( args.num_jobs, not args.no_api, + args.whatsnew, args.single, args.verbosity, args.warnings_are_errors, diff --git a/doc/source/conf.py b/doc/source/conf.py index 7f7ddd8209272..7cd9743e463d0 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -91,8 +91,8 @@ # (e.g. '10min.rst' or 'pandas.DataFrame.head') source_path = os.path.dirname(os.path.abspath(__file__)) pattern = os.environ.get("SPHINX_PATTERN") -single_doc = pattern is not None and pattern != "-api" -include_api = pattern != "-api" +single_doc = pattern is not None and pattern not in ("-api", "whatsnew") +include_api = pattern is None or pattern == "whatsnew" if pattern: for dirname, dirs, fnames in os.walk(source_path): reldir = os.path.relpath(dirname, source_path) @@ -104,7 +104,13 @@ continue elif pattern == "-api" and reldir.startswith("reference"): exclude_patterns.append(fname) - elif pattern != "-api" and fname != pattern: + elif ( + pattern == "whatsnew" + and not reldir.startswith("reference") + and reldir != "whatsnew" + ): + exclude_patterns.append(fname) + elif single_doc and fname != pattern: exclude_patterns.append(fname) with open(os.path.join(source_path, "index.rst.template")) as f: diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index bf1d7d5fce32a..f3630a44d29cd 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -604,6 +604,10 @@ reducing the turn-around time for checking your changes. python make.py clean python make.py --single pandas.DataFrame.join + # compile whatsnew and API section (to resolve links in the whatsnew) + python make.py clean + python make.py --whatsnew + For comparison, a full documentation build may take 15 minutes, but a single section may take 15 seconds. Subsequent builds, which only process portions you have changed, will be faster.
- [ ] closes #xxxx - [ ] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Adds the option to compile the whatsnew. It also builds the API (to resolve links) and opens the whatsnew page in a browser when complete. This is the most frequent reason why I build the docs, and cuts down build time by 40% on my machine.
https://api.github.com/repos/pandas-dev/pandas/pulls/39182
2021-01-15T03:51:04Z
2021-02-12T16:37:31Z
2021-02-12T16:37:31Z
2021-02-12T22:00:44Z
Backport PR #39177 on branch 1.2.x (CI: Pin nbformat to 5.0.8)
diff --git a/environment.yml b/environment.yml index b99b856187fb6..6f3f81d8a4d77 100644 --- a/environment.yml +++ b/environment.yml @@ -68,7 +68,7 @@ dependencies: # unused (required indirectly may be?) - ipywidgets - - nbformat + - nbformat=5.0.8 - notebook>=5.7.5 - pip diff --git a/requirements-dev.txt b/requirements-dev.txt index 17ca6b8401501..f0d65104ead8e 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -42,7 +42,7 @@ pytest-instafail seaborn statsmodels ipywidgets -nbformat +nbformat==5.0.8 notebook>=5.7.5 pip blosc
Backport PR #39177: CI: Pin nbformat to 5.0.8
https://api.github.com/repos/pandas-dev/pandas/pulls/39179
2021-01-14T22:28:58Z
2021-01-14T23:24:36Z
2021-01-14T23:24:36Z
2021-01-14T23:24:37Z
CI: Pin nbformat to 5.0.8
diff --git a/environment.yml b/environment.yml index 09736aeea25f2..be6fb9a4cac7d 100644 --- a/environment.yml +++ b/environment.yml @@ -68,7 +68,7 @@ dependencies: # unused (required indirectly may be?) - ipywidgets - - nbformat + - nbformat=5.0.8 - notebook>=5.7.5 - pip diff --git a/requirements-dev.txt b/requirements-dev.txt index 80fd7b243f6ce..054c924daa81c 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -42,7 +42,7 @@ pytest-instafail seaborn statsmodels ipywidgets -nbformat +nbformat==5.0.8 notebook>=5.7.5 pip blosc
- [x] xref #39176 cc @jreback nbformat should be enoguh I hope.
https://api.github.com/repos/pandas-dev/pandas/pulls/39177
2021-01-14T21:44:04Z
2021-01-14T22:27:58Z
2021-01-14T22:27:58Z
2021-01-14T22:29:08Z
CLN,TYP Remove string return annotations
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 9601be40fdebb..88d18e3e230c6 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -145,11 +145,12 @@ repos: language: pygrep types_or: [python, cython] - id: unwanted-typing - name: Check for use of comment-based annotation syntax and missing error codes + name: Check for outdated annotation syntax and missing error codes entry: | (?x) \#\ type:\ (?!ignore)| - \#\ type:\s?ignore(?!\[) + \#\ type:\s?ignore(?!\[)| + \)\ ->\ \" language: pygrep types: [python] - id: np-bool diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py index 80ee1f2e20154..e6940d78dbaa2 100644 --- a/pandas/compat/pickle_compat.py +++ b/pandas/compat/pickle_compat.py @@ -1,6 +1,7 @@ """ Support pre-0.12 series pickle compatibility. """ +from __future__ import annotations import contextlib import copy @@ -64,7 +65,7 @@ class _LoadSparseSeries: # https://github.com/python/mypy/issues/1020 # error: Incompatible return type for "__new__" (returns "Series", but must return # a subtype of "_LoadSparseSeries") - def __new__(cls) -> "Series": # type: ignore[misc] + def __new__(cls) -> Series: # type: ignore[misc] from pandas import Series warnings.warn( @@ -82,7 +83,7 @@ class _LoadSparseFrame: # https://github.com/python/mypy/issues/1020 # error: Incompatible return type for "__new__" (returns "DataFrame", but must # return a subtype of "_LoadSparseFrame") - def __new__(cls) -> "DataFrame": # type: ignore[misc] + def __new__(cls) -> DataFrame: # type: ignore[misc] from pandas import DataFrame warnings.warn( diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 2bc908186f7f4..2cb8d58c7ec39 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import numbers from typing import TYPE_CHECKING, List, Optional, Tuple, Type, Union import warnings @@ -93,7 +95,7 @@ def _is_numeric(self) -> bool: def __from_arrow__( self, array: Union["pyarrow.Array", "pyarrow.ChunkedArray"] - ) -> "BooleanArray": + ) -> BooleanArray: """ Construct BooleanArray from pyarrow Array/ChunkedArray. """ @@ -276,7 +278,7 @@ def dtype(self) -> BooleanDtype: @classmethod def _from_sequence( cls, scalars, *, dtype: Optional[Dtype] = None, copy: bool = False - ) -> "BooleanArray": + ) -> BooleanArray: if dtype: assert dtype == "boolean" values, mask = coerce_to_array(scalars, copy=copy) @@ -291,7 +293,7 @@ def _from_sequence_of_strings( copy: bool = False, true_values: Optional[List[str]] = None, false_values: Optional[List[str]] = None, - ) -> "BooleanArray": + ) -> BooleanArray: true_values_union = cls._TRUE_VALUES.union(true_values or []) false_values_union = cls._FALSE_VALUES.union(false_values or []) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index fe5db3ec5fd8c..2c04d5f4d45c6 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from csv import QUOTE_NONNUMERIC from functools import partial import operator @@ -740,7 +742,7 @@ def _set_categories(self, categories, fastpath=False): self._dtype = new_dtype - def _set_dtype(self, dtype: CategoricalDtype) -> "Categorical": + def _set_dtype(self, dtype: CategoricalDtype) -> Categorical: """ Internal method for directly updating the CategoricalDtype @@ -1740,7 +1742,7 @@ def fillna(self, value=None, method=None, limit=None): def _ndarray(self) -> np.ndarray: return self._codes - def _from_backing_data(self, arr: np.ndarray) -> "Categorical": + def _from_backing_data(self, arr: np.ndarray) -> Categorical: return self._constructor(arr, dtype=self.dtype, fastpath=True) def _box_func(self, i: int): @@ -2160,7 +2162,7 @@ def _concat_same_type( # ------------------------------------------------------------------ - def _encode_with_my_categories(self, other: "Categorical") -> "Categorical": + def _encode_with_my_categories(self, other: "Categorical") -> Categorical: """ Re-encode another categorical using this Categorical's categories. diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 86c8d15a21227..144a7186f5826 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from datetime import datetime, time, timedelta, tzinfo from typing import Optional, Union, cast import warnings @@ -291,7 +293,7 @@ def __init__(self, values, dtype=DT64NS_DTYPE, freq=None, copy=False): @classmethod def _simple_new( cls, values, freq: Optional[BaseOffset] = None, dtype=DT64NS_DTYPE - ) -> "DatetimeArray": + ) -> DatetimeArray: assert isinstance(values, np.ndarray) if values.dtype != DT64NS_DTYPE: assert values.dtype == "i8" diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py index 2a47c2aa1c914..dc46cf9e3cf68 100644 --- a/pandas/core/arrays/floating.py +++ b/pandas/core/arrays/floating.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import List, Optional, Tuple, Type import warnings @@ -242,14 +244,14 @@ def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False): @classmethod def _from_sequence( cls, scalars, *, dtype=None, copy: bool = False - ) -> "FloatingArray": + ) -> FloatingArray: values, mask = coerce_to_array(scalars, dtype=dtype, copy=copy) return FloatingArray(values, mask) @classmethod def _from_sequence_of_strings( cls, strings, *, dtype=None, copy: bool = False - ) -> "FloatingArray": + ) -> FloatingArray: scalars = to_numeric(strings, errors="raise") return cls._from_sequence(scalars, dtype=dtype, copy=copy) diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 28045585d0a88..f128d2ee6c92f 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import Dict, List, Optional, Tuple, Type import warnings @@ -303,14 +305,14 @@ def __abs__(self): @classmethod def _from_sequence( cls, scalars, *, dtype: Optional[Dtype] = None, copy: bool = False - ) -> "IntegerArray": + ) -> IntegerArray: values, mask = coerce_to_array(scalars, dtype=dtype, copy=copy) return IntegerArray(values, mask) @classmethod def _from_sequence_of_strings( cls, strings, *, dtype: Optional[Dtype] = None, copy: bool = False - ) -> "IntegerArray": + ) -> IntegerArray: scalars = to_numeric(strings, errors="raise") return cls._from_sequence(scalars, dtype=dtype, copy=copy) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index ee3a521d68392..0afcfd86a2de5 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import operator from operator import le, lt import textwrap @@ -861,7 +863,7 @@ def copy(self: IntervalArrayT) -> IntervalArrayT: def isna(self) -> np.ndarray: return isna(self._left) - def shift(self, periods: int = 1, fill_value: object = None) -> "IntervalArray": + def shift(self, periods: int = 1, fill_value: object = None) -> IntervalArray: if not len(self) or periods == 0: return self.copy() diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index e4a98a54ee94c..510e0b447bb5c 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -346,7 +346,7 @@ def factorize(self, na_sentinel: int = -1) -> Tuple[np.ndarray, ExtensionArray]: uniques = type(self)(uniques, np.zeros(len(uniques), dtype=bool)) return codes, uniques - def value_counts(self, dropna: bool = True) -> "Series": + def value_counts(self, dropna: bool = True) -> Series: """ Returns a Series containing counts of each unique value. diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 9ed6306e5b9bc..85dffb1113d35 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import numbers from typing import Optional, Tuple, Type, Union @@ -75,7 +77,7 @@ def _is_boolean(self) -> bool: return self.kind == "b" @classmethod - def construct_from_string(cls, string: str) -> "PandasDtype": + def construct_from_string(cls, string: str) -> PandasDtype: try: dtype = np.dtype(string) except TypeError as err: @@ -174,7 +176,7 @@ def __init__(self, values: Union[np.ndarray, "PandasArray"], copy: bool = False) @classmethod def _from_sequence( cls, scalars, *, dtype: Optional[Dtype] = None, copy: bool = False - ) -> "PandasArray": + ) -> PandasArray: if isinstance(dtype, PandasDtype): dtype = dtype._dtype @@ -184,10 +186,10 @@ def _from_sequence( return cls(result) @classmethod - def _from_factorized(cls, values, original) -> "PandasArray": + def _from_factorized(cls, values, original) -> PandasArray: return cls(values) - def _from_backing_data(self, arr: np.ndarray) -> "PandasArray": + def _from_backing_data(self, arr: np.ndarray) -> PandasArray: return type(self)(arr) # ------------------------------------------------------------------------ diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 235bd2753742f..749ec0a2b8848 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from datetime import timedelta import operator from typing import Any, Callable, List, Optional, Sequence, Type, Union @@ -191,7 +193,7 @@ def _simple_new( values: np.ndarray, freq: Optional[BaseOffset] = None, dtype: Optional[Dtype] = None, - ) -> "PeriodArray": + ) -> PeriodArray: # alias for PeriodArray.__init__ assertion_msg = "Should be numpy array of type i8" assert isinstance(values, np.ndarray) and values.dtype == "i8", assertion_msg @@ -204,7 +206,7 @@ def _from_sequence( *, dtype: Optional[Dtype] = None, copy: bool = False, - ) -> "PeriodArray": + ) -> PeriodArray: if dtype and isinstance(dtype, PeriodDtype): freq = dtype.freq else: @@ -225,11 +227,11 @@ def _from_sequence( @classmethod def _from_sequence_of_strings( cls, strings, *, dtype: Optional[Dtype] = None, copy=False - ) -> "PeriodArray": + ) -> PeriodArray: return cls._from_sequence(strings, dtype=dtype, copy=copy) @classmethod - def _from_datetime64(cls, data, freq, tz=None) -> "PeriodArray": + def _from_datetime64(cls, data, freq, tz=None) -> PeriodArray: """ Construct a PeriodArray from a datetime64 array @@ -504,7 +506,7 @@ def _box_func(self, x) -> Union[Period, NaTType]: return Period._from_ordinal(ordinal=x, freq=self.freq) @doc(**_shared_doc_kwargs, other="PeriodIndex", other_name="PeriodIndex") - def asfreq(self, freq=None, how: str = "E") -> "PeriodArray": + def asfreq(self, freq=None, how: str = "E") -> PeriodArray: """ Convert the {klass} to the specified frequency `freq`. @@ -675,7 +677,7 @@ def _sub_period_array(self, other): def _addsub_int_array( self, other: np.ndarray, op: Callable[[Any, Any], Any] - ) -> "PeriodArray": + ) -> PeriodArray: """ Add or subtract array of integers; equivalent to applying `_time_shift` pointwise. diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index b4d4fd5cc7106..4cae2e48c84c8 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -1,6 +1,8 @@ """ SparseArray data structure """ +from __future__ import annotations + from collections import abc import numbers import operator @@ -812,7 +814,7 @@ def _get_val_at(self, loc): val = maybe_box_datetimelike(val, self.sp_values.dtype) return val - def take(self, indices, *, allow_fill=False, fill_value=None) -> "SparseArray": + def take(self, indices, *, allow_fill=False, fill_value=None) -> SparseArray: if is_scalar(indices): raise ValueError(f"'indices' must be an array, not a scalar '{indices}'.") indices = np.asarray(indices, dtype=np.int32) @@ -1403,7 +1405,7 @@ def _arith_method(self, other, op): other = SparseArray(other, fill_value=self.fill_value, dtype=dtype) return _sparse_array_op(self, other, op, op_name) - def _cmp_method(self, other, op) -> "SparseArray": + def _cmp_method(self, other, op) -> SparseArray: if not is_scalar(other) and not isinstance(other, type(self)): # convert list-like to ndarray other = np.asarray(other) @@ -1431,19 +1433,19 @@ def _cmp_method(self, other, op) -> "SparseArray": _logical_method = _cmp_method - def _unary_method(self, op) -> "SparseArray": + def _unary_method(self, op) -> SparseArray: fill_value = op(np.array(self.fill_value)).item() values = op(self.sp_values) dtype = SparseDtype(values.dtype, fill_value) return type(self)._simple_new(values, self.sp_index, dtype) - def __pos__(self) -> "SparseArray": + def __pos__(self) -> SparseArray: return self._unary_method(operator.pos) - def __neg__(self) -> "SparseArray": + def __neg__(self) -> SparseArray: return self._unary_method(operator.neg) - def __invert__(self) -> "SparseArray": + def __invert__(self) -> SparseArray: return self._unary_method(operator.invert) # ---------- diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index 14bdd063fa41a..4e4c8f1aad671 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -1,4 +1,5 @@ """Sparse Dtype""" +from __future__ import annotations import re from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type @@ -185,7 +186,7 @@ def construct_array_type(cls) -> Type["SparseArray"]: return SparseArray @classmethod - def construct_from_string(cls, string: str) -> "SparseDtype": + def construct_from_string(cls, string: str) -> SparseDtype: """ Construct a SparseDtype from a string form. diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index 3d0ac3380ec39..3234d36b3dbe7 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import TYPE_CHECKING, Optional, Type, Union import numpy as np @@ -84,7 +86,7 @@ def __repr__(self) -> str: def __from_arrow__( self, array: Union["pyarrow.Array", "pyarrow.ChunkedArray"] - ) -> "StringArray": + ) -> StringArray: """ Construct StringArray from pyarrow Array/ChunkedArray. """ diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 274feb75e9452..4c073883abf89 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -105,7 +105,7 @@ def __repr__(self) -> str: def __from_arrow__( self, array: Union["pa.Array", "pa.ChunkedArray"] - ) -> "ArrowStringArray": + ) -> ArrowStringArray: """ Construct StringArray from pyarrow Array/ChunkedArray. """ @@ -507,7 +507,7 @@ def __setitem__(self, key: Union[int, np.ndarray], value: Any) -> None: def take( self, indices: Sequence[int], allow_fill: bool = False, fill_value: Any = None - ) -> "ExtensionArray": + ) -> ExtensionArray: """ Take elements from an array. diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 62d5a4d30563b..e9160c92435a4 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from datetime import timedelta from typing import List, Optional, Union @@ -206,7 +208,7 @@ def __init__(self, values, dtype=TD64NS_DTYPE, freq=lib.no_default, copy=False): @classmethod def _simple_new( cls, values, freq: Optional[BaseOffset] = None, dtype=TD64NS_DTYPE - ) -> "TimedeltaArray": + ) -> TimedeltaArray: assert dtype == TD64NS_DTYPE, dtype assert isinstance(values, np.ndarray), type(values) if values.dtype != TD64NS_DTYPE: @@ -222,7 +224,7 @@ def _simple_new( @classmethod def _from_sequence( cls, data, *, dtype=TD64NS_DTYPE, copy: bool = False - ) -> "TimedeltaArray": + ) -> TimedeltaArray: if dtype: _validate_td64_dtype(dtype) @@ -239,7 +241,7 @@ def _from_sequence_not_strict( copy: bool = False, freq=lib.no_default, unit=None, - ) -> "TimedeltaArray": + ) -> TimedeltaArray: if dtype: _validate_td64_dtype(dtype) @@ -467,7 +469,7 @@ def _addsub_object_array(self, other, op): ) from err @unpack_zerodim_and_defer("__mul__") - def __mul__(self, other) -> "TimedeltaArray": + def __mul__(self, other) -> TimedeltaArray: if is_scalar(other): # numpy will accept float and int, raise TypeError for others result = self._data * other @@ -743,15 +745,15 @@ def __rdivmod__(self, other): res2 = other - res1 * self return res1, res2 - def __neg__(self) -> "TimedeltaArray": + def __neg__(self) -> TimedeltaArray: if self.freq is not None: return type(self)(-self._data, freq=-self.freq) return type(self)(-self._data) - def __pos__(self) -> "TimedeltaArray": + def __pos__(self) -> TimedeltaArray: return type(self)(self._data, freq=self.freq) - def __abs__(self) -> "TimedeltaArray": + def __abs__(self) -> TimedeltaArray: # Note: freq is not preserved return type(self)(np.abs(self._data)) diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index b819886687817..a8f4f0f2859d2 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -1,4 +1,5 @@ """ manage PyTables query interface via Expressions """ +from __future__ import annotations import ast from functools import partial @@ -180,7 +181,7 @@ def generate(self, v) -> str: val = v.tostring(self.encoding) return f"({self.lhs} {self.op} {val})" - def convert_value(self, v) -> "TermValue": + def convert_value(self, v) -> TermValue: """ convert the expression that is in the term to something that is accepted by pytables diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index d2708da04b7e9..c2ba7f9892ef0 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -1,6 +1,7 @@ """ Module for scope operations """ +from __future__ import annotations import datetime import inspect @@ -19,7 +20,7 @@ def ensure_scope( level: int, global_dict=None, local_dict=None, resolvers=(), target=None, **kwargs -) -> "Scope": +) -> Scope: """Ensure that we are grabbing the correct scope.""" return Scope( level + 1, diff --git a/pandas/core/describe.py b/pandas/core/describe.py index 5a4c0deb7503c..22de5ae1e082f 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -3,6 +3,7 @@ Method NDFrame.describe() delegates actual execution to function describe_ndframe(). """ +from __future__ import annotations from typing import TYPE_CHECKING, List, Optional, Sequence, Union, cast import warnings @@ -88,7 +89,7 @@ def describe_series( series: "Series", percentiles: Sequence[float], datetime_is_numeric: bool, -) -> "Series": +) -> Series: """Describe series. The reason for the delegation to ``describe_1d`` only: @@ -121,7 +122,7 @@ def describe_frame( exclude: Optional[Union[str, Sequence[str]]], percentiles: Sequence[float], datetime_is_numeric: bool, -) -> "DataFrame": +) -> DataFrame: """Describe DataFrame. Parameters @@ -179,7 +180,7 @@ def select_columns( include: Optional[Union[str, Sequence[str]]], exclude: Optional[Union[str, Sequence[str]]], datetime_is_numeric: bool, -) -> "DataFrame": +) -> DataFrame: """Select columns to be described.""" if (include is None) and (exclude is None): # when some numerics are found, keep only numerics @@ -200,7 +201,7 @@ def select_columns( return data -def describe_numeric_1d(series: "Series", percentiles: Sequence[float]) -> "Series": +def describe_numeric_1d(series: "Series", percentiles: Sequence[float]) -> Series: """Describe series containing numerical data. Parameters @@ -223,7 +224,7 @@ def describe_numeric_1d(series: "Series", percentiles: Sequence[float]) -> "Seri return Series(d, index=stat_index, name=series.name) -def describe_categorical_1d(data: "Series", is_series: bool) -> "Series": +def describe_categorical_1d(data: "Series", is_series: bool) -> Series: """Describe series containing categorical data. Parameters @@ -285,7 +286,7 @@ def describe_categorical_1d(data: "Series", is_series: bool) -> "Series": return Series(result, index=names, name=data.name, dtype=dtype) -def describe_timestamp_1d(data: "Series", percentiles: Sequence[float]) -> "Series": +def describe_timestamp_1d(data: "Series", percentiles: Sequence[float]) -> Series: """Describe series containing datetime64 dtype. Parameters @@ -315,7 +316,7 @@ def describe_1d( datetime_is_numeric: bool, *, is_series: bool, -) -> "Series": +) -> Series: """Describe series. Parameters diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 55755724f1ace..0941967ef6bee 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -944,7 +944,7 @@ def coerce_indexer_dtype(indexer, categories): def astype_dt64_to_dt64tz( values: ArrayLike, dtype: DtypeObj, copy: bool, via_utc: bool = False -) -> "DatetimeArray": +) -> DatetimeArray: # GH#33401 we have inconsistent behaviors between # Datetimeindex[naive].astype(tzaware) # Series[dt64].astype(tzaware) diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index d75ae77373403..cefab33976ba8 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -1,6 +1,7 @@ """ Define extension dtypes. """ +from __future__ import annotations import re from typing import ( @@ -162,7 +163,7 @@ def __init__(self, categories=None, ordered: Ordered = False): @classmethod def _from_fastpath( cls, categories=None, ordered: Optional[bool] = None - ) -> "CategoricalDtype": + ) -> CategoricalDtype: self = cls.__new__(cls) self._finalize(categories, ordered, fastpath=True) return self @@ -170,7 +171,7 @@ def _from_fastpath( @classmethod def _from_categorical_dtype( cls, dtype: "CategoricalDtype", categories=None, ordered: Ordered = None - ) -> "CategoricalDtype": + ) -> CategoricalDtype: if categories is ordered is None: return dtype if categories is None: @@ -186,7 +187,7 @@ def _from_values_or_dtype( categories=None, ordered: Optional[bool] = None, dtype: Optional[Dtype] = None, - ) -> "CategoricalDtype": + ) -> CategoricalDtype: """ Construct dtype from the input parameters used in :class:`Categorical`. @@ -275,7 +276,7 @@ def _from_values_or_dtype( return cast(CategoricalDtype, dtype) @classmethod - def construct_from_string(cls, string: str_type) -> "CategoricalDtype": + def construct_from_string(cls, string: str_type) -> CategoricalDtype: """ Construct a CategoricalDtype from a string. @@ -514,7 +515,7 @@ def validate_categories(categories, fastpath: bool = False): def update_dtype( self, dtype: Union[str_type, "CategoricalDtype"] - ) -> "CategoricalDtype": + ) -> CategoricalDtype: """ Returns a CategoricalDtype with categories and ordered taken from dtype if specified, otherwise falling back to self if unspecified @@ -706,7 +707,7 @@ def construct_array_type(cls) -> Type["DatetimeArray"]: return DatetimeArray @classmethod - def construct_from_string(cls, string: str_type) -> "DatetimeTZDtype": + def construct_from_string(cls, string: str_type) -> DatetimeTZDtype: """ Construct a DatetimeTZDtype from a string. @@ -865,7 +866,7 @@ def _parse_dtype_strict(cls, freq): raise ValueError("could not construct PeriodDtype") @classmethod - def construct_from_string(cls, string: str_type) -> "PeriodDtype": + def construct_from_string(cls, string: str_type) -> PeriodDtype: """ Strict construction from a string, raise a TypeError if not possible @@ -953,7 +954,7 @@ def construct_array_type(cls) -> Type["PeriodArray"]: def __from_arrow__( self, array: Union["pyarrow.Array", "pyarrow.ChunkedArray"] - ) -> "PeriodArray": + ) -> PeriodArray: """ Construct PeriodArray from pyarrow Array/ChunkedArray. """ @@ -1184,7 +1185,7 @@ def is_dtype(cls, dtype: object) -> bool: def __from_arrow__( self, array: Union["pyarrow.Array", "pyarrow.ChunkedArray"] - ) -> "IntervalArray": + ) -> IntervalArray: """ Construct IntervalArray from pyarrow Array/ChunkedArray. """ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 91766a3fbfb8d..ffc84ad94459a 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9418,7 +9418,7 @@ def asfreq( how: Optional[str] = None, normalize: bool = False, fill_value=None, - ) -> "DataFrame": + ) -> DataFrame: return super().asfreq( freq=freq, method=method, @@ -9442,7 +9442,7 @@ def resample( level=None, origin: Union[str, "TimestampConvertibleTypes"] = "start_day", offset: Optional["TimedeltaConvertibleTypes"] = None, - ) -> "Resampler": + ) -> Resampler: return super().resample( rule=rule, axis=axis, diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index c561204c1c125..2bcd5964d3736 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -5,6 +5,8 @@ These are user facing as the result of the ``df.groupby(...)`` operations, which here returns a DataFrameGroupBy object. """ +from __future__ import annotations + from collections import abc, namedtuple import copy from functools import partial diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 2c0ba5b05c19b..517b848742541 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -5,6 +5,7 @@ operations, primarily in cython. These classes (BaseGrouper and BinGrouper) are contained *in* the SeriesGroupBy and DataFrameGroupBy objects. """ +from __future__ import annotations import collections from typing import ( @@ -149,7 +150,7 @@ def get_iterator( yield key, group.__finalize__(data, method="groupby") @final - def _get_splitter(self, data: FrameOrSeries, axis: int = 0) -> "DataSplitter": + def _get_splitter(self, data: FrameOrSeries, axis: int = 0) -> DataSplitter: """ Returns ------- @@ -909,7 +910,7 @@ def names(self) -> List[Hashable]: return [self.binlabels.name] @property - def groupings(self) -> "List[grouper.Grouping]": + def groupings(self) -> List[grouper.Grouping]: return [ grouper.Grouping(lvl, lvl, in_axis=False, level=None, name=name) for lvl, name in zip(self.levels, self.names) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index dba1a7df45234..0b46b43514d92 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from copy import copy as copy_func from datetime import datetime from itertools import zip_longest @@ -263,7 +265,7 @@ def _outer_indexer(self, left, right): def __new__( cls, data=None, dtype=None, copy=False, name=None, tupleize_cols=True, **kwargs - ) -> "Index": + ) -> Index: if kwargs: warnings.warn( @@ -4517,7 +4519,7 @@ def append(self, other): return self._concat(to_concat, name) - def _concat(self, to_concat: List["Index"], name: Hashable) -> "Index": + def _concat(self, to_concat: List["Index"], name: Hashable) -> Index: """ Concatenate multiple Index objects. """ @@ -5273,7 +5275,7 @@ def map(self, mapper, na_action=None): # TODO: De-duplicate with map, xref GH#32349 @final - def _transform_index(self, func, level=None) -> "Index": + def _transform_index(self, func, level=None) -> Index: """ Apply function to all values found in index. @@ -6119,7 +6121,7 @@ def _validate_join_method(method: str): raise ValueError(f"do not recognize join method {method}") -def default_index(n: int) -> "RangeIndex": +def default_index(n: int) -> RangeIndex: from pandas.core.indexes.range import RangeIndex return RangeIndex(0, n, name=None) diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index b7f93295837e0..7a178a29b2fd6 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from datetime import date, datetime, time, timedelta, tzinfo import operator from typing import TYPE_CHECKING, Optional, Tuple @@ -239,40 +241,38 @@ def strftime(self, date_format) -> Index: return Index(arr, name=self.name) @doc(DatetimeArray.tz_convert) - def tz_convert(self, tz) -> "DatetimeIndex": + def tz_convert(self, tz) -> DatetimeIndex: arr = self._data.tz_convert(tz) return type(self)._simple_new(arr, name=self.name) @doc(DatetimeArray.tz_localize) - def tz_localize( - self, tz, ambiguous="raise", nonexistent="raise" - ) -> "DatetimeIndex": + def tz_localize(self, tz, ambiguous="raise", nonexistent="raise") -> DatetimeIndex: arr = self._data.tz_localize(tz, ambiguous, nonexistent) return type(self)._simple_new(arr, name=self.name) @doc(DatetimeArray.to_period) - def to_period(self, freq=None) -> "PeriodIndex": + def to_period(self, freq=None) -> PeriodIndex: from pandas.core.indexes.api import PeriodIndex arr = self._data.to_period(freq) return PeriodIndex._simple_new(arr, name=self.name) @doc(DatetimeArray.to_perioddelta) - def to_perioddelta(self, freq) -> "TimedeltaIndex": + def to_perioddelta(self, freq) -> TimedeltaIndex: from pandas.core.indexes.api import TimedeltaIndex arr = self._data.to_perioddelta(freq) return TimedeltaIndex._simple_new(arr, name=self.name) @doc(DatetimeArray.to_julian_date) - def to_julian_date(self) -> "Float64Index": + def to_julian_date(self) -> Float64Index: from pandas.core.indexes.api import Float64Index arr = self._data.to_julian_date() return Float64Index._simple_new(arr, name=self.name) @doc(DatetimeArray.isocalendar) - def isocalendar(self) -> "DataFrame": + def isocalendar(self) -> DataFrame: df = self._data.isocalendar() return df.set_index(self) diff --git a/pandas/core/indexes/frozen.py b/pandas/core/indexes/frozen.py index 8c4437f2cdeb9..3956dbaba5a68 100644 --- a/pandas/core/indexes/frozen.py +++ b/pandas/core/indexes/frozen.py @@ -6,6 +6,7 @@ - .names (FrozenList) """ +from __future__ import annotations from typing import Any @@ -24,7 +25,7 @@ class FrozenList(PandasObject, list): # Side note: This has to be of type list. Otherwise, # it messes up PyTables type checks. - def union(self, other) -> "FrozenList": + def union(self, other) -> FrozenList: """ Returns a FrozenList with other concatenated to the end of self. @@ -42,7 +43,7 @@ def union(self, other) -> "FrozenList": other = list(other) return type(self)(super().__add__(other)) - def difference(self, other) -> "FrozenList": + def difference(self, other) -> FrozenList: """ Returns a FrozenList with elements from other removed from self. diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 60755d88fff7f..22101f778a79a 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1,4 +1,6 @@ """ define the IntervalIndex """ +from __future__ import annotations + from functools import wraps from operator import le, lt import textwrap @@ -941,7 +943,7 @@ def _intersection(self, other, sort): return taken - def _intersection_unique(self, other: "IntervalIndex") -> "IntervalIndex": + def _intersection_unique(self, other: "IntervalIndex") -> IntervalIndex: """ Used when the IntervalIndex does not have any common endpoint, no matter left or right. @@ -964,7 +966,7 @@ def _intersection_unique(self, other: "IntervalIndex") -> "IntervalIndex": return self.take(indexer) - def _intersection_non_unique(self, other: "IntervalIndex") -> "IntervalIndex": + def _intersection_non_unique(self, other: "IntervalIndex") -> IntervalIndex: """ Used when the IntervalIndex does have some common endpoints, on either sides. diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 485d4f809eabd..a04933fc5ddfc 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from functools import wraps from sys import getsizeof from typing import ( @@ -404,7 +406,7 @@ def _verify_integrity( return new_codes @classmethod - def from_arrays(cls, arrays, sortorder=None, names=lib.no_default) -> "MultiIndex": + def from_arrays(cls, arrays, sortorder=None, names=lib.no_default) -> MultiIndex: """ Convert arrays to MultiIndex. @@ -700,7 +702,7 @@ def array(self): ) @cache_readonly - def dtypes(self) -> "Series": + def dtypes(self) -> Series: """ Return the dtypes as a Series for the underlying MultiIndex """ diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index d5dc68b77df61..b9b8f5d2ddca6 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from datetime import datetime, timedelta from typing import Any, Optional import warnings @@ -155,7 +157,7 @@ class PeriodIndex(DatetimeIndexOpsMixin): other_name="PeriodArray", **_shared_doc_kwargs, ) - def asfreq(self, freq=None, how: str = "E") -> "PeriodIndex": + def asfreq(self, freq=None, how: str = "E") -> PeriodIndex: arr = self._data.asfreq(freq, how) return type(self)._simple_new(arr, name=self.name) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 66a70fbea238a..5bd406bfdbc55 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from datetime import timedelta import operator from sys import getsizeof @@ -121,7 +123,7 @@ def __new__( @classmethod def from_range( cls, data: range, name=None, dtype: Optional[Dtype] = None - ) -> "RangeIndex": + ) -> RangeIndex: """ Create RangeIndex from a range object. @@ -139,7 +141,7 @@ def from_range( return cls._simple_new(data, name=name) @classmethod - def _simple_new(cls, values: range, name: Hashable = None) -> "RangeIndex": + def _simple_new(cls, values: range, name: Hashable = None) -> RangeIndex: result = object.__new__(cls) assert isinstance(values, range) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index ad1e49c5f75aa..90ba03b312e56 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -104,7 +104,7 @@ class IndexingMixin: """ @property - def iloc(self) -> "_iLocIndexer": + def iloc(self) -> _iLocIndexer: """ Purely integer-location based indexing for selection by position. @@ -241,7 +241,7 @@ def iloc(self) -> "_iLocIndexer": return _iLocIndexer("iloc", self) @property - def loc(self) -> "_LocIndexer": + def loc(self) -> _LocIndexer: """ Access a group of rows and columns by label(s) or a boolean array. @@ -501,7 +501,7 @@ def loc(self) -> "_LocIndexer": return _LocIndexer("loc", self) @property - def at(self) -> "_AtIndexer": + def at(self) -> _AtIndexer: """ Access a single value for a row/column label pair. @@ -550,7 +550,7 @@ def at(self) -> "_AtIndexer": return _AtIndexer("at", self) @property - def iat(self) -> "_iAtIndexer": + def iat(self) -> _iAtIndexer: """ Access a single value for a row/column pair by integer position. diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 134bf59ed7f9c..99edec3c606d4 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -1,6 +1,8 @@ """ Experimental manager based on storing a collection of 1D arrays """ +from __future__ import annotations + from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, TypeVar, Union import numpy as np @@ -126,7 +128,7 @@ def set_axis(self, axis: int, new_labels: Index) -> None: self._axes[axis] = new_labels - def consolidate(self) -> "ArrayManager": + def consolidate(self) -> ArrayManager: return self def is_consolidated(self) -> bool: @@ -185,7 +187,7 @@ def reduce( indexer = np.arange(self.shape[0]) return new_mgr, indexer - def operate_blockwise(self, other: "ArrayManager", array_op) -> "ArrayManager": + def operate_blockwise(self, other: "ArrayManager", array_op) -> ArrayManager: """ Apply array_op blockwise with another (aligned) BlockManager. """ @@ -318,10 +320,10 @@ def apply_with_block(self: T, f, align_keys=None, **kwargs) -> T: # TODO quantile - def isna(self, func) -> "ArrayManager": + def isna(self, func) -> ArrayManager: return self.apply("apply", func=func) - def where(self, other, cond, align: bool, errors: str, axis: int) -> "ArrayManager": + def where(self, other, cond, align: bool, errors: str, axis: int) -> ArrayManager: if align: align_keys = ["other", "cond"] else: @@ -338,7 +340,7 @@ def where(self, other, cond, align: bool, errors: str, axis: int) -> "ArrayManag ) # TODO what is this used for? - # def setitem(self, indexer, value) -> "ArrayManager": + # def setitem(self, indexer, value) -> ArrayManager: # return self.apply_with_block("setitem", indexer=indexer, value=value) def putmask(self, mask, new, align: bool = True, axis: int = 0): @@ -357,13 +359,13 @@ def putmask(self, mask, new, align: bool = True, axis: int = 0): axis=axis, ) - def diff(self, n: int, axis: int) -> "ArrayManager": + def diff(self, n: int, axis: int) -> ArrayManager: return self.apply_with_block("diff", n=n, axis=axis) - def interpolate(self, **kwargs) -> "ArrayManager": + def interpolate(self, **kwargs) -> ArrayManager: return self.apply_with_block("interpolate", **kwargs) - def shift(self, periods: int, axis: int, fill_value) -> "ArrayManager": + def shift(self, periods: int, axis: int, fill_value) -> ArrayManager: if fill_value is lib.no_default: fill_value = None @@ -375,7 +377,7 @@ def shift(self, periods: int, axis: int, fill_value) -> "ArrayManager": "shift", periods=periods, axis=axis, fill_value=fill_value ) - def fillna(self, value, limit, inplace: bool, downcast) -> "ArrayManager": + def fillna(self, value, limit, inplace: bool, downcast) -> ArrayManager: # TODO implement downcast inplace = validate_bool_kwarg(inplace, "inplace") @@ -399,12 +401,10 @@ def array_fillna(array, value, limit, inplace): return self.apply(array_fillna, value=value, limit=limit, inplace=inplace) - def downcast(self) -> "ArrayManager": + def downcast(self) -> ArrayManager: return self.apply_with_block("downcast") - def astype( - self, dtype, copy: bool = False, errors: str = "raise" - ) -> "ArrayManager": + def astype(self, dtype, copy: bool = False, errors: str = "raise") -> ArrayManager: return self.apply("astype", dtype=dtype, copy=copy) # , errors=errors) def convert( @@ -413,7 +413,7 @@ def convert( datetime: bool = True, numeric: bool = True, timedelta: bool = True, - ) -> "ArrayManager": + ) -> ArrayManager: return self.apply_with_block( "convert", copy=copy, @@ -422,7 +422,7 @@ def convert( timedelta=timedelta, ) - def replace(self, value, **kwargs) -> "ArrayManager": + def replace(self, value, **kwargs) -> ArrayManager: assert np.ndim(value) == 0, value # TODO "replace" is right now implemented on the blocks, we should move # it to general array algos so it can be reused here @@ -472,7 +472,7 @@ def is_view(self) -> bool: def is_single_block(self) -> bool: return False - def get_bool_data(self, copy: bool = False) -> "ArrayManager": + def get_bool_data(self, copy: bool = False) -> ArrayManager: """ Parameters ---------- @@ -485,7 +485,7 @@ def get_bool_data(self, copy: bool = False) -> "ArrayManager": new_axes = [self._axes[0], self._axes[1][mask]] return type(self)(arrays, new_axes) - def get_numeric_data(self, copy: bool = False) -> "ArrayManager": + def get_numeric_data(self, copy: bool = False) -> ArrayManager: """ Parameters ---------- @@ -588,7 +588,7 @@ def as_array( return result # return arr.transpose() if transpose else arr - def get_slice(self, slobj: slice, axis: int = 0) -> "ArrayManager": + def get_slice(self, slobj: slice, axis: int = 0) -> ArrayManager: axis = self._normalize_axis(axis) if axis == 0: @@ -631,7 +631,7 @@ def fast_xs(self, loc: int) -> ArrayLike: result = dtype.construct_array_type()._from_sequence(result, dtype=dtype) return result - def iget(self, i: int) -> "SingleBlockManager": + def iget(self, i: int) -> SingleBlockManager: """ Return the data as a SingleBlockManager. """ @@ -834,7 +834,7 @@ def equals(self, other: object) -> bool: # TODO raise NotImplementedError - def unstack(self, unstacker, fill_value) -> "ArrayManager": + def unstack(self, unstacker, fill_value) -> ArrayManager: """ Return a BlockManager with all blocks unstacked.. diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d6e6fcf158a07..1356b9d3b2ca3 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import inspect import re from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, Union, cast @@ -113,7 +115,7 @@ class Block(PandasObject): @classmethod def _simple_new( cls, values: ArrayLike, placement: BlockPlacement, ndim: int - ) -> "Block": + ) -> Block: """ Fastpath constructor, does *no* validation """ @@ -272,7 +274,7 @@ def mgr_locs(self, new_mgr_locs): self._mgr_locs = new_mgr_locs - def make_block(self, values, placement=None) -> "Block": + def make_block(self, values, placement=None) -> Block: """ Create a new block, with type inference propagate any values that are not specified diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index c7d419840fb13..ad9cdcfa1b07f 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from collections import defaultdict import itertools from typing import ( @@ -369,7 +371,7 @@ def reduce( new_mgr = type(self).from_blocks(res_blocks, [self.items, index]) return new_mgr, indexer - def operate_blockwise(self, other: "BlockManager", array_op) -> "BlockManager": + def operate_blockwise(self, other: "BlockManager", array_op) -> BlockManager: """ Apply array_op blockwise with another (aligned) BlockManager. """ @@ -448,7 +450,7 @@ def quantile( interpolation="linear", qs=None, numeric_only=None, - ) -> "BlockManager": + ) -> BlockManager: """ Iterate over blocks applying quantile reduction. This routine is intended for reduction type operations and @@ -540,10 +542,10 @@ def get_axe(block, qs, axes): make_block(values, ndim=1, placement=np.arange(len(values))), axes[0] ) - def isna(self, func) -> "BlockManager": + def isna(self, func) -> BlockManager: return self.apply("apply", func=func) - def where(self, other, cond, align: bool, errors: str, axis: int) -> "BlockManager": + def where(self, other, cond, align: bool, errors: str, axis: int) -> BlockManager: if align: align_keys = ["other", "cond"] else: @@ -559,7 +561,7 @@ def where(self, other, cond, align: bool, errors: str, axis: int) -> "BlockManag axis=axis, ) - def setitem(self, indexer, value) -> "BlockManager": + def setitem(self, indexer, value) -> BlockManager: return self.apply("setitem", indexer=indexer, value=value) def putmask(self, mask, new, align: bool = True, axis: int = 0): @@ -578,13 +580,13 @@ def putmask(self, mask, new, align: bool = True, axis: int = 0): axis=axis, ) - def diff(self, n: int, axis: int) -> "BlockManager": + def diff(self, n: int, axis: int) -> BlockManager: return self.apply("diff", n=n, axis=axis) - def interpolate(self, **kwargs) -> "BlockManager": + def interpolate(self, **kwargs) -> BlockManager: return self.apply("interpolate", **kwargs) - def shift(self, periods: int, axis: int, fill_value) -> "BlockManager": + def shift(self, periods: int, axis: int, fill_value) -> BlockManager: if fill_value is lib.no_default: fill_value = None @@ -609,17 +611,15 @@ def shift(self, periods: int, axis: int, fill_value) -> "BlockManager": return self.apply("shift", periods=periods, axis=axis, fill_value=fill_value) - def fillna(self, value, limit, inplace: bool, downcast) -> "BlockManager": + def fillna(self, value, limit, inplace: bool, downcast) -> BlockManager: return self.apply( "fillna", value=value, limit=limit, inplace=inplace, downcast=downcast ) - def downcast(self) -> "BlockManager": + def downcast(self) -> BlockManager: return self.apply("downcast") - def astype( - self, dtype, copy: bool = False, errors: str = "raise" - ) -> "BlockManager": + def astype(self, dtype, copy: bool = False, errors: str = "raise") -> BlockManager: return self.apply("astype", dtype=dtype, copy=copy, errors=errors) def convert( @@ -628,7 +628,7 @@ def convert( datetime: bool = True, numeric: bool = True, timedelta: bool = True, - ) -> "BlockManager": + ) -> BlockManager: return self.apply( "convert", copy=copy, @@ -637,7 +637,7 @@ def convert( timedelta=timedelta, ) - def replace(self, to_replace, value, inplace: bool, regex: bool) -> "BlockManager": + def replace(self, to_replace, value, inplace: bool, regex: bool) -> BlockManager: assert np.ndim(value) == 0, value return self.apply( "replace", to_replace=to_replace, value=value, inplace=inplace, regex=regex @@ -663,7 +663,7 @@ def replace_list( bm._consolidate_inplace() return bm - def to_native_types(self, **kwargs) -> "BlockManager": + def to_native_types(self, **kwargs) -> BlockManager: """ Convert values to native types (strings / python objects) that are used in formatting (repr / csv). @@ -707,7 +707,7 @@ def is_view(self) -> bool: return False - def get_bool_data(self, copy: bool = False) -> "BlockManager": + def get_bool_data(self, copy: bool = False) -> BlockManager: """ Select blocks that are bool-dtype and columns from object-dtype blocks that are all-bool. @@ -732,7 +732,7 @@ def get_bool_data(self, copy: bool = False) -> "BlockManager": return self._combine(new_blocks, copy) - def get_numeric_data(self, copy: bool = False) -> "BlockManager": + def get_numeric_data(self, copy: bool = False) -> BlockManager: """ Parameters ---------- @@ -765,7 +765,7 @@ def _combine( return type(self).from_blocks(new_blocks, axes) - def get_slice(self, slobj: slice, axis: int = 0) -> "BlockManager": + def get_slice(self, slobj: slice, axis: int = 0) -> BlockManager: if axis == 0: new_blocks = self._slice_take_blocks_ax0(slobj) @@ -966,7 +966,7 @@ def fast_xs(self, loc: int) -> ArrayLike: return result - def consolidate(self) -> "BlockManager": + def consolidate(self) -> BlockManager: """ Join together blocks having same dtype @@ -989,7 +989,7 @@ def _consolidate_inplace(self) -> None: self._known_consolidated = True self._rebuild_blknos_and_blklocs() - def iget(self, i: int) -> "SingleBlockManager": + def iget(self, i: int) -> SingleBlockManager: """ Return the data as a SingleBlockManager. """ @@ -1470,7 +1470,7 @@ def equals(self, other: object) -> bool: return blockwise_all(self, other, array_equals) - def unstack(self, unstacker, fill_value) -> "BlockManager": + def unstack(self, unstacker, fill_value) -> BlockManager: """ Return a BlockManager with all blocks unstacked.. @@ -1539,9 +1539,7 @@ def __init__( self.blocks = (block,) @classmethod - def from_blocks( - cls, blocks: List[Block], axes: List[Index] - ) -> "SingleBlockManager": + def from_blocks(cls, blocks: List[Block], axes: List[Index]) -> SingleBlockManager: """ Constructor for BlockManager and SingleBlockManager with same signature. """ @@ -1550,7 +1548,7 @@ def from_blocks( return cls(blocks[0], axes[0], do_integrity_check=False) @classmethod - def from_array(cls, array: ArrayLike, index: Index) -> "SingleBlockManager": + def from_array(cls, array: ArrayLike, index: Index) -> SingleBlockManager: """ Constructor for if we have an array that is not yet a Block. """ @@ -1574,7 +1572,7 @@ def _blklocs(self): """ compat with BlockManager """ return None - def get_slice(self, slobj: slice, axis: int = 0) -> "SingleBlockManager": + def get_slice(self, slobj: slice, axis: int = 0) -> SingleBlockManager: if axis >= self.ndim: raise IndexError("Requested axis not found in manager") diff --git a/pandas/core/internals/ops.py b/pandas/core/internals/ops.py index d7ea5d613d96a..562740a275acb 100644 --- a/pandas/core/internals/ops.py +++ b/pandas/core/internals/ops.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from collections import namedtuple from typing import TYPE_CHECKING, Iterator, List, Tuple @@ -45,7 +47,7 @@ def _iter_block_pairs( def operate_blockwise( left: "BlockManager", right: "BlockManager", array_op -) -> "BlockManager": +) -> BlockManager: # At this point we have already checked the parent DataFrames for # assert rframe._indexed_same(lframe) diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index cea8cc1ff28b4..e6bd344d958d3 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -323,9 +323,7 @@ def should_reindex_frame_op( return False -def frame_arith_method_with_reindex( - left: DataFrame, right: DataFrame, op -) -> "DataFrame": +def frame_arith_method_with_reindex(left: DataFrame, right: DataFrame, op) -> DataFrame: """ For DataFrame-with-DataFrame operations that require reindexing, operate only on shared columns, then reindex. diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index d4729a0a59baa..7e6ff6ae358bb 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -1,6 +1,7 @@ """ Concat routines. """ +from __future__ import annotations from collections import abc from typing import ( @@ -61,7 +62,7 @@ def concat( verify_integrity: bool = False, sort: bool = False, copy: bool = True, -) -> "DataFrame": +) -> DataFrame: ... diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index e58e27438ad33..b5f8b2d02207b 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -33,7 +33,7 @@ def melt( value_name="value", col_level=None, ignore_index: bool = True, -) -> "DataFrame": +) -> DataFrame: # If multiindex, gather names of columns on all level for checking presence # of `id_vars` and `value_vars` if isinstance(frame.columns, MultiIndex): @@ -141,7 +141,7 @@ def melt( @deprecate_kwarg(old_arg_name="label", new_arg_name=None) -def lreshape(data: DataFrame, groups, dropna: bool = True, label=None) -> "DataFrame": +def lreshape(data: DataFrame, groups, dropna: bool = True, label=None) -> DataFrame: """ Reshape wide-format data to long. Generalized inverse of DataFrame.pivot. @@ -237,7 +237,7 @@ def lreshape(data: DataFrame, groups, dropna: bool = True, label=None) -> "DataF def wide_to_long( df: DataFrame, stubnames, i, j, sep: str = "", suffix: str = r"\d+" -) -> "DataFrame": +) -> DataFrame: r""" Wide panel to long format. Less flexible but more user-friendly than melt. diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index cf5fd58748bb0..18e3f3a48afdb 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -77,7 +77,7 @@ def merge( copy: bool = True, indicator: bool = False, validate: Optional[str] = None, -) -> "DataFrame": +) -> DataFrame: op = _MergeOperation( left, right, @@ -168,7 +168,7 @@ def merge_ordered( fill_method: Optional[str] = None, suffixes: Suffixes = ("_x", "_y"), how: str = "outer", -) -> "DataFrame": +) -> DataFrame: """ Perform merge with optional filling/interpolation. @@ -315,7 +315,7 @@ def merge_asof( tolerance=None, allow_exact_matches: bool = True, direction: str = "backward", -) -> "DataFrame": +) -> DataFrame: """ Perform an asof merge. @@ -2160,7 +2160,7 @@ def _any(x) -> bool: return x is not None and com.any_not_none(*x) -def _validate_operand(obj: FrameOrSeries) -> "DataFrame": +def _validate_operand(obj: FrameOrSeries) -> DataFrame: if isinstance(obj, ABCDataFrame): return obj elif isinstance(obj, ABCSeries): diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 4c335802e5546..7ac98d7fcbd33 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -50,7 +50,7 @@ def pivot_table( dropna=True, margins_name="All", observed=False, -) -> "DataFrame": +) -> DataFrame: index = _convert_by(index) columns = _convert_by(columns) @@ -428,7 +428,7 @@ def pivot( index: Optional[IndexLabel] = None, columns: Optional[IndexLabel] = None, values: Optional[IndexLabel] = None, -) -> "DataFrame": +) -> DataFrame: if columns is None: raise TypeError("pivot() missing 1 required argument: 'columns'") @@ -475,7 +475,7 @@ def crosstab( margins_name: str = "All", dropna: bool = True, normalize=False, -) -> "DataFrame": +) -> DataFrame: """ Compute a simple cross tabulation of two (or more) factors. By default computes a frequency table of the factors unless an array of values and an diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index fc8d2aee1e6cd..d389f19598d14 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import itertools from typing import List, Optional, Union @@ -738,7 +740,7 @@ def get_dummies( sparse: bool = False, drop_first: bool = False, dtype: Optional[Dtype] = None, -) -> "DataFrame": +) -> DataFrame: """ Convert categorical variable into dummy/indicator variables. diff --git a/pandas/core/series.py b/pandas/core/series.py index 15c7d2b964d79..b248899a171ff 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1,6 +1,8 @@ """ Data structure for 1-dimensional cross-sectional and time series data """ +from __future__ import annotations + from io import StringIO from shutil import get_terminal_size from textwrap import dedent @@ -620,7 +622,7 @@ def __len__(self) -> int: """ return len(self._mgr) - def view(self, dtype: Optional[Dtype] = None) -> "Series": + def view(self, dtype: Optional[Dtype] = None) -> Series: """ Create a new view of the Series. @@ -765,7 +767,7 @@ def axes(self) -> List[Index]: # Indexing Methods @Appender(generic.NDFrame.take.__doc__) - def take(self, indices, axis=0, is_copy=None, **kwargs) -> "Series": + def take(self, indices, axis=0, is_copy=None, **kwargs) -> Series: if is_copy is not None: warnings.warn( "is_copy is deprecated and will be removed in a future version. " @@ -807,7 +809,7 @@ def _ixs(self, i: int, axis: int = 0): """ return self._values[i] - def _slice(self, slobj: slice, axis: int = 0) -> "Series": + def _slice(self, slobj: slice, axis: int = 0) -> Series: # axis kwarg is retained for compat with NDFrame method # _slice is *always* positional return self._get_values(slobj) @@ -1060,7 +1062,7 @@ def _set_value(self, label, value, takeable: bool = False): def _is_mixed_type(self): return False - def repeat(self, repeats, axis=None) -> "Series": + def repeat(self, repeats, axis=None) -> Series: """ Repeat elements of a Series. @@ -1533,7 +1535,7 @@ def to_dict(self, into=dict): into_c = com.standardize_mapping(into) return into_c(self.items()) - def to_frame(self, name=None) -> "DataFrame": + def to_frame(self, name=None) -> DataFrame: """ Convert Series to DataFrame. @@ -1565,7 +1567,7 @@ def to_frame(self, name=None) -> "DataFrame": return df - def _set_name(self, name, inplace=False) -> "Series": + def _set_name(self, name, inplace=False) -> Series: """ Set the Series name. @@ -1674,7 +1676,7 @@ def groupby( squeeze: bool = no_default, observed: bool = False, dropna: bool = True, - ) -> "SeriesGroupBy": + ) -> SeriesGroupBy: from pandas.core.groupby.generic import SeriesGroupBy if squeeze is not no_default: @@ -1761,7 +1763,7 @@ def count(self, level=None): self, method="count" ) - def mode(self, dropna=True) -> "Series": + def mode(self, dropna=True) -> Series: """ Return the mode(s) of the Series. @@ -1931,7 +1933,7 @@ def drop_duplicates(self, keep="first", inplace=False) -> Optional["Series"]: else: return result - def duplicated(self, keep="first") -> "Series": + def duplicated(self, keep="first") -> Series: """ Indicate duplicate Series values. @@ -2150,7 +2152,7 @@ def idxmax(self, axis=0, skipna=True, *args, **kwargs): return np.nan return self.index[i] - def round(self, decimals=0, *args, **kwargs) -> "Series": + def round(self, decimals=0, *args, **kwargs) -> Series: """ Round each value in a Series to the given number of decimals. @@ -2402,7 +2404,7 @@ def cov( dtype: float64""" ), ) - def diff(self, periods: int = 1) -> "Series": + def diff(self, periods: int = 1) -> Series: """ First discrete difference of element. @@ -2820,7 +2822,7 @@ def compare( keep_equal=keep_equal, ) - def combine(self, other, func, fill_value=None) -> "Series": + def combine(self, other, func, fill_value=None) -> Series: """ Combine the Series with a Series or scalar according to `func`. @@ -2918,7 +2920,7 @@ def combine(self, other, func, fill_value=None) -> "Series": new_values = maybe_cast_to_extension_array(type(self._values), new_values) return self._constructor(new_values, index=new_index, name=new_name) - def combine_first(self, other) -> "Series": + def combine_first(self, other) -> Series: """ Combine Series values, choosing the calling Series's values first. @@ -3406,7 +3408,7 @@ def sort_index( key, ) - def argsort(self, axis=0, kind="quicksort", order=None) -> "Series": + def argsort(self, axis=0, kind="quicksort", order=None) -> Series: """ Return the integer indices that would sort the Series values. @@ -3448,7 +3450,7 @@ def argsort(self, axis=0, kind="quicksort", order=None) -> "Series": np.argsort(values, kind=kind), index=self.index, dtype="int64" ).__finalize__(self, method="argsort") - def nlargest(self, n=5, keep="first") -> "Series": + def nlargest(self, n=5, keep="first") -> Series: """ Return the largest `n` elements. @@ -3546,7 +3548,7 @@ def nlargest(self, n=5, keep="first") -> "Series": """ return algorithms.SelectNSeries(self, n=n, keep=keep).nlargest() - def nsmallest(self, n=5, keep="first") -> "Series": + def nsmallest(self, n=5, keep="first") -> Series: """ Return the smallest `n` elements. @@ -3643,7 +3645,7 @@ def nsmallest(self, n=5, keep="first") -> "Series": """ return algorithms.SelectNSeries(self, n=n, keep=keep).nsmallest() - def swaplevel(self, i=-2, j=-1, copy=True) -> "Series": + def swaplevel(self, i=-2, j=-1, copy=True) -> Series: """ Swap levels i and j in a :class:`MultiIndex`. @@ -3667,7 +3669,7 @@ def swaplevel(self, i=-2, j=-1, copy=True) -> "Series": self, method="swaplevel" ) - def reorder_levels(self, order) -> "Series": + def reorder_levels(self, order) -> Series: """ Rearrange index levels using input order. @@ -3690,7 +3692,7 @@ def reorder_levels(self, order) -> "Series": result.index = result.index.reorder_levels(order) return result - def explode(self, ignore_index: bool = False) -> "Series": + def explode(self, ignore_index: bool = False) -> Series: """ Transform each element of a list-like to a row. @@ -3804,7 +3806,7 @@ def unstack(self, level=-1, fill_value=None): # ---------------------------------------------------------------------- # function application - def map(self, arg, na_action=None) -> "Series": + def map(self, arg, na_action=None) -> Series: """ Map values of Series according to input correspondence. @@ -3884,7 +3886,7 @@ def map(self, arg, na_action=None) -> "Series": self, method="map" ) - def _gotitem(self, key, ndim, subset=None) -> "Series": + def _gotitem(self, key, ndim, subset=None) -> Series: """ Sub-classes to define. Return a sliced object. @@ -4293,7 +4295,7 @@ def drop( level=None, inplace=False, errors="raise", - ) -> "Series": + ) -> Series: """ Return Series with specified index labels removed. @@ -4486,7 +4488,7 @@ def _replace_single(self, to_replace, method: str, inplace: bool, limit): return result @doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"]) - def shift(self, periods=1, freq=None, axis=0, fill_value=None) -> "Series": + def shift(self, periods=1, freq=None, axis=0, fill_value=None) -> Series: return super().shift( periods=periods, freq=freq, axis=axis, fill_value=fill_value ) @@ -4545,7 +4547,7 @@ def memory_usage(self, index=True, deep=False): v += self.index.memory_usage(deep=deep) return v - def isin(self, values) -> "Series": + def isin(self, values) -> Series: """ Whether elements in Series are contained in `values`. @@ -4603,7 +4605,7 @@ def isin(self, values) -> "Series": self, method="isin" ) - def between(self, left, right, inclusive=True) -> "Series": + def between(self, left, right, inclusive=True) -> Series: """ Return boolean Series equivalent to left <= series <= right. @@ -4688,7 +4690,7 @@ def _convert_dtypes( convert_integer: bool = True, convert_boolean: bool = True, convert_floating: bool = True, - ) -> "Series": + ) -> Series: input_series = self if infer_objects: input_series = input_series.infer_objects() @@ -4712,19 +4714,19 @@ def _convert_dtypes( return result @doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) - def isna(self) -> "Series": + def isna(self) -> Series: return generic.NDFrame.isna(self) @doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) - def isnull(self) -> "Series": + def isnull(self) -> Series: return super().isnull() @doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) - def notna(self) -> "Series": + def notna(self) -> Series: return super().notna() @doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) - def notnull(self) -> "Series": + def notnull(self) -> Series: return super().notnull() def dropna(self, axis=0, inplace=False, how=None): @@ -4826,7 +4828,7 @@ def asfreq( how: Optional[str] = None, normalize: bool = False, fill_value=None, - ) -> "Series": + ) -> Series: return super().asfreq( freq=freq, method=method, @@ -4850,7 +4852,7 @@ def resample( level=None, origin: Union[str, "TimestampConvertibleTypes"] = "start_day", offset: Optional["TimedeltaConvertibleTypes"] = None, - ) -> "Resampler": + ) -> Resampler: return super().resample( rule=rule, axis=axis, @@ -4866,7 +4868,7 @@ def resample( offset=offset, ) - def to_timestamp(self, freq=None, how="start", copy=True) -> "Series": + def to_timestamp(self, freq=None, how="start", copy=True) -> Series: """ Cast to DatetimeIndex of Timestamps, at *beginning* of period. @@ -4895,7 +4897,7 @@ def to_timestamp(self, freq=None, how="start", copy=True) -> "Series": self, method="to_timestamp" ) - def to_period(self, freq=None, copy=True) -> "Series": + def to_period(self, freq=None, copy=True) -> Series: """ Convert Series from DatetimeIndex to PeriodIndex. diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 9417b626386fc..8869533be30fb 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -1,4 +1,6 @@ """ miscellaneous sorting / groupby utilities """ +from __future__ import annotations + from collections import defaultdict from typing import ( TYPE_CHECKING, @@ -419,7 +421,7 @@ def nargminmax(values, method: str): def _ensure_key_mapped_multiindex( index: "MultiIndex", key: Callable, level=None -) -> "MultiIndex": +) -> MultiIndex: """ Returns a new MultiIndex in which key has been applied to all levels specified in level (or all levels if level diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index aff55bc0a1fd5..88ce5865ee8c2 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from collections import abc from datetime import datetime from functools import partial @@ -146,7 +148,7 @@ def _maybe_cache( format: Optional[str], cache: bool, convert_listlike: Callable, -) -> "Series": +) -> Series: """ Create a cache of unique dates from an array of dates @@ -214,7 +216,7 @@ def _convert_and_box_cache( arg: DatetimeScalarOrArrayConvertible, cache_array: "Series", name: Optional[str] = None, -) -> "Index": +) -> Index: """ Convert array of dates with a cache and wrap the result in an Index. @@ -586,7 +588,7 @@ def to_datetime( infer_datetime_format: bool = ..., origin=..., cache: bool = ..., -) -> "Series": +) -> Series: ... diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 983f7220c2fb9..670fdc011bd96 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import datetime from functools import partial from textwrap import dedent @@ -77,7 +79,7 @@ def get_center_of_mass( return float(comass) -def wrap_result(obj: "Series", result: np.ndarray) -> "Series": +def wrap_result(obj: "Series", result: np.ndarray) -> Series: """ Wrap a single 1D result. """ diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 2dce27a76eb00..3c8b69c4aaa80 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -362,7 +362,7 @@ def _get_window_indexer(self) -> BaseIndexer: def _apply_series( self, homogeneous_func: Callable[..., ArrayLike], name: Optional[str] = None - ) -> "Series": + ) -> Series: """ Series version of _apply_blockwise """ diff --git a/pandas/io/common.py b/pandas/io/common.py index 1fee840c5ed4a..47811d47e7238 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -1,4 +1,5 @@ """Common IO api utilities""" +from __future__ import annotations import bz2 from collections import abc @@ -97,7 +98,7 @@ def close(self) -> None: self.created_handles = [] self.is_wrapped = False - def __enter__(self) -> "IOHandles": + def __enter__(self) -> IOHandles: return self def __exit__(self, *args: Any) -> None: @@ -783,7 +784,7 @@ def __getattr__(self, name: str): return lambda: self.attributes[name] return getattr(self.mmap, name) - def __iter__(self) -> "_MMapWrapper": + def __iter__(self) -> _MMapWrapper: return self def __next__(self) -> str: diff --git a/pandas/io/formats/info.py b/pandas/io/formats/info.py index c4575bc07c149..9693008abcf7f 100644 --- a/pandas/io/formats/info.py +++ b/pandas/io/formats/info.py @@ -312,7 +312,7 @@ def to_buffer(self, buf: Optional[IO[str]] = None) -> None: fmt.buffer_put_lines(buf, lines) @abstractmethod - def _create_table_builder(self) -> "TableBuilderAbstract": + def _create_table_builder(self) -> TableBuilderAbstract: """Create instance of table builder.""" @@ -376,7 +376,7 @@ def _initialize_show_counts(self, show_counts: Optional[bool]) -> bool: else: return show_counts - def _create_table_builder(self) -> "DataFrameTableBuilder": + def _create_table_builder(self) -> DataFrameTableBuilder: """ Create instance of table builder based on verbosity and display settings. """ @@ -485,7 +485,7 @@ def _fill_non_empty_info(self) -> None: """Add lines to the info table, pertaining to non-empty dataframe.""" @property - def data(self) -> "DataFrame": + def data(self) -> DataFrame: """DataFrame.""" return self.info.data diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index b6c1336ede597..0d702a9794234 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1,6 +1,8 @@ """ Module for applying conditional formatting to DataFrames and Series. """ +from __future__ import annotations + from collections import defaultdict from contextlib import contextmanager import copy @@ -445,7 +447,7 @@ def format_attr(pair): "table_attributes": table_attr, } - def format(self, formatter, subset=None, na_rep: Optional[str] = None) -> "Styler": + def format(self, formatter, subset=None, na_rep: Optional[str] = None) -> Styler: """ Format the text display value of cells. @@ -516,7 +518,7 @@ def format(self, formatter, subset=None, na_rep: Optional[str] = None) -> "Style self._display_funcs[(i, j)] = formatter return self - def set_td_classes(self, classes: DataFrame) -> "Styler": + def set_td_classes(self, classes: DataFrame) -> Styler: """ Add string based CSS class names to data cells that will appear within the `Styler` HTML result. These classes are added within specified `<td>` elements. @@ -656,7 +658,7 @@ def _update_ctx(self, attrs: DataFrame) -> None: for pair in c.split(";"): self.ctx[(i, j)].append(pair) - def _copy(self, deepcopy: bool = False) -> "Styler": + def _copy(self, deepcopy: bool = False) -> Styler: styler = Styler( self.data, precision=self.precision, @@ -673,13 +675,13 @@ def _copy(self, deepcopy: bool = False) -> "Styler": styler._todo = self._todo return styler - def __copy__(self) -> "Styler": + def __copy__(self) -> Styler: """ Deep copy by default. """ return self._copy(deepcopy=False) - def __deepcopy__(self, memo) -> "Styler": + def __deepcopy__(self, memo) -> Styler: return self._copy(deepcopy=True) def clear(self) -> None: @@ -712,7 +714,7 @@ def _apply( axis: Optional[Axis] = 0, subset=None, **kwargs, - ) -> "Styler": + ) -> Styler: subset = slice(None) if subset is None else subset subset = non_reducing_slice(subset) data = self.data.loc[subset] @@ -751,7 +753,7 @@ def apply( axis: Optional[Axis] = 0, subset=None, **kwargs, - ) -> "Styler": + ) -> Styler: """ Apply a function column-wise, row-wise, or table-wise. @@ -802,7 +804,7 @@ def apply( ) return self - def _applymap(self, func: Callable, subset=None, **kwargs) -> "Styler": + def _applymap(self, func: Callable, subset=None, **kwargs) -> Styler: func = partial(func, **kwargs) # applymap doesn't take kwargs? if subset is None: subset = pd.IndexSlice[:] @@ -811,7 +813,7 @@ def _applymap(self, func: Callable, subset=None, **kwargs) -> "Styler": self._update_ctx(result) return self - def applymap(self, func: Callable, subset=None, **kwargs) -> "Styler": + def applymap(self, func: Callable, subset=None, **kwargs) -> Styler: """ Apply a function elementwise. @@ -848,7 +850,7 @@ def where( other: Optional[str] = None, subset=None, **kwargs, - ) -> "Styler": + ) -> Styler: """ Apply a function elementwise. @@ -884,7 +886,7 @@ def where( lambda val: value if cond(val) else other, subset=subset, **kwargs ) - def set_precision(self, precision: int) -> "Styler": + def set_precision(self, precision: int) -> Styler: """ Set the precision used to render. @@ -899,7 +901,7 @@ def set_precision(self, precision: int) -> "Styler": self.precision = precision return self - def set_table_attributes(self, attributes: str) -> "Styler": + def set_table_attributes(self, attributes: str) -> Styler: """ Set the table attributes. @@ -939,7 +941,7 @@ def export(self) -> List[Tuple[Callable, Tuple, Dict]]: """ return self._todo - def use(self, styles: List[Tuple[Callable, Tuple, Dict]]) -> "Styler": + def use(self, styles: List[Tuple[Callable, Tuple, Dict]]) -> Styler: """ Set the styles on the current Styler. @@ -961,7 +963,7 @@ def use(self, styles: List[Tuple[Callable, Tuple, Dict]]) -> "Styler": self._todo.extend(styles) return self - def set_uuid(self, uuid: str) -> "Styler": + def set_uuid(self, uuid: str) -> Styler: """ Set the uuid for a Styler. @@ -976,7 +978,7 @@ def set_uuid(self, uuid: str) -> "Styler": self.uuid = uuid return self - def set_caption(self, caption: str) -> "Styler": + def set_caption(self, caption: str) -> Styler: """ Set the caption on a Styler. @@ -991,7 +993,7 @@ def set_caption(self, caption: str) -> "Styler": self.caption = caption return self - def set_table_styles(self, table_styles, axis=0, overwrite=True) -> "Styler": + def set_table_styles(self, table_styles, axis=0, overwrite=True) -> Styler: """ Set the table styles on a Styler. @@ -1082,7 +1084,7 @@ def set_table_styles(self, table_styles, axis=0, overwrite=True) -> "Styler": self.table_styles = table_styles return self - def set_na_rep(self, na_rep: str) -> "Styler": + def set_na_rep(self, na_rep: str) -> Styler: """ Set the missing data representation on a Styler. @@ -1099,7 +1101,7 @@ def set_na_rep(self, na_rep: str) -> "Styler": self.na_rep = na_rep return self - def hide_index(self) -> "Styler": + def hide_index(self) -> Styler: """ Hide any indices from rendering. @@ -1110,7 +1112,7 @@ def hide_index(self) -> "Styler": self.hidden_index = True return self - def hide_columns(self, subset) -> "Styler": + def hide_columns(self, subset) -> Styler: """ Hide columns from rendering. @@ -1141,7 +1143,7 @@ def highlight_null( self, null_color: str = "red", subset: Optional[IndexLabel] = None, - ) -> "Styler": + ) -> Styler: """ Shade the background ``null_color`` for missing values. @@ -1170,7 +1172,7 @@ def background_gradient( text_color_threshold: float = 0.408, vmin: Optional[float] = None, vmax: Optional[float] = None, - ) -> "Styler": + ) -> Styler: """ Color the background in a gradient style. @@ -1307,7 +1309,7 @@ def css(rgba) -> str: columns=s.columns, ) - def set_properties(self, subset=None, **kwargs) -> "Styler": + def set_properties(self, subset=None, **kwargs) -> Styler: """ Method to set one or more non-data dependent properties or each cell. @@ -1401,7 +1403,7 @@ def bar( align: str = "left", vmin: Optional[float] = None, vmax: Optional[float] = None, - ) -> "Styler": + ) -> Styler: """ Draw bar chart in the cell backgrounds. @@ -1478,7 +1480,7 @@ def bar( def highlight_max( self, subset=None, color: str = "yellow", axis: Optional[Axis] = 0 - ) -> "Styler": + ) -> Styler: """ Highlight the maximum by shading the background. @@ -1500,7 +1502,7 @@ def highlight_max( def highlight_min( self, subset=None, color: str = "yellow", axis: Optional[Axis] = 0 - ) -> "Styler": + ) -> Styler: """ Highlight the minimum by shading the background. @@ -1528,7 +1530,7 @@ def _highlight_handler( color: str = "yellow", axis: Optional[Axis] = None, max_: bool = True, - ) -> "Styler": + ) -> Styler: subset = non_reducing_slice(maybe_numeric_slice(self.data, subset)) self.apply( self._highlight_extrema, color=color, axis=axis, subset=subset, max_=max_ diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py index 39f25750aa774..260d688ccb0cc 100644 --- a/pandas/io/gbq.py +++ b/pandas/io/gbq.py @@ -34,7 +34,7 @@ def read_gbq( use_bqstorage_api: Optional[bool] = None, max_results: Optional[int] = None, progress_bar_type: Optional[str] = None, -) -> "DataFrame": +) -> DataFrame: """ Load data from Google BigQuery. diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py index 40aeee67ce2da..bff13ec188b0e 100644 --- a/pandas/io/json/_normalize.py +++ b/pandas/io/json/_normalize.py @@ -1,5 +1,6 @@ # --------------------------------------------------------------------- # JSON normalization routines +from __future__ import annotations from collections import abc, defaultdict import copy @@ -118,7 +119,7 @@ def _json_normalize( errors: str = "raise", sep: str = ".", max_level: Optional[int] = None, -) -> "DataFrame": +) -> DataFrame: """ Normalize semi-structured JSON data into a flat table. diff --git a/pandas/io/orc.py b/pandas/io/orc.py index d9e9f3e1770be..a219be99540dc 100644 --- a/pandas/io/orc.py +++ b/pandas/io/orc.py @@ -1,4 +1,5 @@ """ orc compat """ +from __future__ import annotations import distutils from typing import TYPE_CHECKING, List, Optional @@ -13,7 +14,7 @@ def read_orc( path: FilePathOrBuffer, columns: Optional[List[str]] = None, **kwargs -) -> "DataFrame": +) -> DataFrame: """ Load an ORC object from the file path, returning a DataFrame. diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index 44b58f244a2ad..0a322059ed77c 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -1,4 +1,5 @@ """ parquet compat """ +from __future__ import annotations from distutils.version import LooseVersion import io @@ -23,7 +24,7 @@ ) -def get_engine(engine: str) -> "BaseImpl": +def get_engine(engine: str) -> BaseImpl: """ return our implementation """ if engine == "auto": engine = get_option("io.parquet.engine") diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index f1d0af60e1c7f..0225811d95244 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -2,6 +2,8 @@ High level interface to PyTables for reading and writing pandas data structures to disk """ +from __future__ import annotations + from contextlib import suppress import copy from datetime import date, tzinfo @@ -1771,7 +1773,7 @@ def _read_group(self, group: "Node"): s.infer_axes() return s.read() - def _identify_group(self, key: str, append: bool) -> "Node": + def _identify_group(self, key: str, append: bool) -> Node: """Identify HDF5 group based on key, delete/create group if needed.""" group = self.get_node(key) @@ -1789,7 +1791,7 @@ def _identify_group(self, key: str, append: bool) -> "Node": return group - def _create_nodes_and_group(self, key: str) -> "Node": + def _create_nodes_and_group(self, key: str) -> Node: """Create nodes from key and return group name.""" # assertion for mypy assert self._handle is not None @@ -2326,7 +2328,7 @@ def take_data(self): return self.data @classmethod - def _get_atom(cls, values: ArrayLike) -> "Col": + def _get_atom(cls, values: ArrayLike) -> Col: """ Get an appropriately typed and shaped pytables.Col object for values. """ @@ -2376,7 +2378,7 @@ def get_atom_coltype(cls, kind: str) -> Type["Col"]: return getattr(_tables(), col_name) @classmethod - def get_atom_data(cls, shape, kind: str) -> "Col": + def get_atom_data(cls, shape, kind: str) -> Col: return cls.get_atom_coltype(kind=kind)(shape=shape[0]) @classmethod @@ -2533,7 +2535,7 @@ def get_atom_string(cls, shape, itemsize): return _tables().StringCol(itemsize=itemsize) @classmethod - def get_atom_data(cls, shape, kind: str) -> "Col": + def get_atom_data(cls, shape, kind: str) -> Col: return cls.get_atom_coltype(kind=kind)() @classmethod diff --git a/pandas/io/stata.py b/pandas/io/stata.py index f3a74189eba85..c9cd94b7cc711 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -9,6 +9,8 @@ You can find more information on http://presbrey.mit.edu/PyDTA and https://www.statsmodels.org/devel/ """ +from __future__ import annotations + from collections import abc import datetime from io import BytesIO @@ -1072,7 +1074,7 @@ def __init__( self._read_header() self._setup_dtype() - def __enter__(self) -> "StataReader": + def __enter__(self) -> StataReader: """ enter context manager """ return self diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index d0c05af5dce8b..8e81751d88fa1 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -130,7 +130,7 @@ def radviz( color=None, colormap=None, **kwds, -) -> "Axes": +) -> Axes: import matplotlib.pyplot as plt def normalize(series): @@ -219,7 +219,7 @@ def andrews_curves( color=None, colormap=None, **kwds, -) -> "Axes": +) -> Axes: import matplotlib.pyplot as plt def function(amplitudes): @@ -284,7 +284,7 @@ def bootstrap_plot( size: int = 50, samples: int = 500, **kwds, -) -> "Figure": +) -> Figure: import matplotlib.pyplot as plt @@ -346,7 +346,7 @@ def parallel_coordinates( axvlines_kwds=None, sort_labels: bool = False, **kwds, -) -> "Axes": +) -> Axes: import matplotlib.pyplot as plt if axvlines_kwds is None: @@ -415,7 +415,7 @@ def parallel_coordinates( def lag_plot( series: "Series", lag: int = 1, ax: Optional["Axes"] = None, **kwds -) -> "Axes": +) -> Axes: # workaround because `c='b'` is hardcoded in matplotlib's scatter method import matplotlib.pyplot as plt @@ -432,9 +432,7 @@ def lag_plot( return ax -def autocorrelation_plot( - series: "Series", ax: Optional["Axes"] = None, **kwds -) -> "Axes": +def autocorrelation_plot(series: "Series", ax: Optional["Axes"] = None, **kwds) -> Axes: import matplotlib.pyplot as plt n = len(series) diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index cc2dde0f2179a..c88c310d512be 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import itertools from typing import ( TYPE_CHECKING, @@ -148,7 +150,7 @@ def _get_colors_from_colormap( return [colormap(num) for num in np.linspace(0, 1, num=num_colors)] -def _get_cmap_instance(colormap: Union[str, "Colormap"]) -> "Colormap": +def _get_cmap_instance(colormap: Union[str, "Colormap"]) -> Colormap: """Get instance of matplotlib colormap.""" if isinstance(colormap, str): cmap = colormap diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index f288e6ebb783c..7440daeb0a632 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -1,4 +1,6 @@ # being a bit too dynamic +from __future__ import annotations + from math import ceil from typing import TYPE_CHECKING, Iterable, List, Sequence, Tuple, Union import warnings @@ -32,7 +34,7 @@ def format_date_labels(ax: "Axes", rot): def table( ax, data: FrameOrSeriesUnion, rowLabels=None, colLabels=None, **kwargs -) -> "Table": +) -> Table: if isinstance(data, ABCSeries): data = data.to_frame() elif isinstance(data, ABCDataFrame):
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them this was just done with ```python parser = argparse.ArgumentParser() parser.add_argument('paths', nargs='*', type=Path) args = parser.parse_args() for path in args.paths: text = path.read_text() text = re.sub(r'-> "(\w+)"', '-> \\1', text) path.write_text(text) ``` There's other to do (which I'll get to in other PRs), but this already gets rid of a big load of them
https://api.github.com/repos/pandas-dev/pandas/pulls/39174
2021-01-14T16:49:32Z
2021-01-16T11:15:51Z
2021-01-16T11:15:51Z
2021-01-16T11:33:14Z
REF: extract more functions in pandas/core/describe.py
diff --git a/pandas/core/describe.py b/pandas/core/describe.py index 4c178de2a182e..5a4c0deb7503c 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -25,7 +25,7 @@ from pandas.io.formats.format import format_percentiles if TYPE_CHECKING: - from pandas import Series + from pandas import DataFrame, Series def describe_ndframe( @@ -59,52 +59,145 @@ def describe_ndframe( ------- Dataframe or series description. """ - if obj.ndim == 2 and obj.columns.size == 0: - raise ValueError("Cannot describe a DataFrame without columns") - - percentiles = _refine_percentiles(percentiles) + percentiles = refine_percentiles(percentiles) if obj.ndim == 1: - series = cast("Series", obj) - # Incompatible return value type - # (got "Series", expected "FrameOrSeries") [return-value] - return describe_1d( - series, + result_series = describe_series( + cast("Series", obj), percentiles, datetime_is_numeric, - is_series=True, - ) # type:ignore[return-value] - elif (include is None) and (exclude is None): - # when some numerics are found, keep only numerics - default_include = [np.number] - if datetime_is_numeric: - default_include.append("datetime") - data = obj.select_dtypes(include=default_include) - if len(data.columns) == 0: - data = obj - elif include == "all": - if exclude is not None: - msg = "exclude must be None when include is 'all'" - raise ValueError(msg) - data = obj - else: - data = obj.select_dtypes(include=include, exclude=exclude) + ) + return cast(FrameOrSeries, result_series) + + frame = cast("DataFrame", obj) + + if frame.ndim == 2 and frame.columns.size == 0: + raise ValueError("Cannot describe a DataFrame without columns") + + result_frame = describe_frame( + frame=frame, + include=include, + exclude=exclude, + percentiles=percentiles, + datetime_is_numeric=datetime_is_numeric, + ) + return cast(FrameOrSeries, result_frame) + + +def describe_series( + series: "Series", + percentiles: Sequence[float], + datetime_is_numeric: bool, +) -> "Series": + """Describe series. + + The reason for the delegation to ``describe_1d`` only: + to allow for a proper stacklevel of the FutureWarning. + + Parameters + ---------- + series : Series + Series to be described. + percentiles : list-like of numbers + The percentiles to include in the output. + datetime_is_numeric : bool, default False + Whether to treat datetime dtypes as numeric. + + Returns + ------- + Series + """ + return describe_1d( + series, + percentiles, + datetime_is_numeric, + is_series=True, + ) + + +def describe_frame( + frame: "DataFrame", + include: Optional[Union[str, Sequence[str]]], + exclude: Optional[Union[str, Sequence[str]]], + percentiles: Sequence[float], + datetime_is_numeric: bool, +) -> "DataFrame": + """Describe DataFrame. + + Parameters + ---------- + frame : DataFrame + DataFrame to be described. + include : 'all', list-like of dtypes or None (default), optional + A white list of data types to include in the result. + exclude : list-like of dtypes or None (default), optional, + A black list of data types to omit from the result. + percentiles : list-like of numbers + The percentiles to include in the output. + datetime_is_numeric : bool, default False + Whether to treat datetime dtypes as numeric. + + Returns + ------- + DataFrame + """ + data = select_columns( + frame=frame, + include=include, + exclude=exclude, + datetime_is_numeric=datetime_is_numeric, + ) ldesc = [ describe_1d(s, percentiles, datetime_is_numeric, is_series=False) for _, s in data.items() ] - # set a convenient order for rows + + col_names = reorder_columns(ldesc) + d = concat( + [x.reindex(col_names, copy=False) for x in ldesc], + axis=1, + sort=False, + ) + d.columns = data.columns.copy() + return d + + +def reorder_columns(ldesc: Sequence["Series"]) -> List[Hashable]: + """Set a convenient order for rows for display.""" names: List[Hashable] = [] ldesc_indexes = sorted((x.index for x in ldesc), key=len) for idxnames in ldesc_indexes: for name in idxnames: if name not in names: names.append(name) + return names - d = concat([x.reindex(names, copy=False) for x in ldesc], axis=1, sort=False) - d.columns = data.columns.copy() - return d + +def select_columns( + frame: "DataFrame", + include: Optional[Union[str, Sequence[str]]], + exclude: Optional[Union[str, Sequence[str]]], + datetime_is_numeric: bool, +) -> "DataFrame": + """Select columns to be described.""" + if (include is None) and (exclude is None): + # when some numerics are found, keep only numerics + default_include = [np.number] + if datetime_is_numeric: + default_include.append("datetime") + data = frame.select_dtypes(include=default_include) + if len(data.columns) == 0: + data = frame + elif include == "all": + if exclude is not None: + msg = "exclude must be None when include is 'all'" + raise ValueError(msg) + data = frame + else: + data = frame.select_dtypes(include=include, exclude=exclude) + + return data def describe_numeric_1d(series: "Series", percentiles: Sequence[float]) -> "Series": @@ -150,9 +243,9 @@ def describe_categorical_1d(data: "Series", is_series: bool) -> "Series": top, freq = objcounts.index[0], objcounts.iloc[0] if is_datetime64_any_dtype(data.dtype): if is_series: - stacklevel = 5 - else: stacklevel = 6 + else: + stacklevel = 7 warnings.warn( "Treating datetime data as categorical rather than numeric in " "`.describe` is deprecated and will be removed in a future " @@ -253,7 +346,7 @@ def describe_1d( return describe_categorical_1d(data, is_series) -def _refine_percentiles(percentiles: Optional[Sequence[float]]) -> Sequence[float]: +def refine_percentiles(percentiles: Optional[Sequence[float]]) -> Sequence[float]: """Ensure that percentiles are unique and sorted. Parameters
- [ ] xref #36833 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Extracted ``describe_series``, ``describe_frame`` and ``select_column`` in ``pandas/core/describe.py``. The next time I think I will introduce the classes ``SeriesDescriber`` and ``DataFrameDescriber`` and will start moving the functions into the methods incrementally, if that is OK.
https://api.github.com/repos/pandas-dev/pandas/pulls/39170
2021-01-14T15:35:23Z
2021-01-14T16:34:39Z
2021-01-14T16:34:39Z
2021-01-15T10:16:56Z
REF/TYP: extract function/type args in describe.py
diff --git a/pandas/core/describe.py b/pandas/core/describe.py index 4a67725449ca8..4c178de2a182e 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -4,7 +4,7 @@ Method NDFrame.describe() delegates actual execution to function describe_ndframe(). """ -from typing import TYPE_CHECKING, List, Optional, Sequence, Union +from typing import TYPE_CHECKING, List, Optional, Sequence, Union, cast import warnings import numpy as np @@ -62,32 +62,14 @@ def describe_ndframe( if obj.ndim == 2 and obj.columns.size == 0: raise ValueError("Cannot describe a DataFrame without columns") - if percentiles is not None: - # explicit conversion of `percentiles` to list - percentiles = list(percentiles) - - # get them all to be in [0, 1] - validate_percentile(percentiles) - - # median should always be included - if 0.5 not in percentiles: - percentiles.append(0.5) - percentiles = np.asarray(percentiles) - else: - percentiles = np.array([0.25, 0.5, 0.75]) - - # sort and check for duplicates - unique_pcts = np.unique(percentiles) - assert percentiles is not None - if len(unique_pcts) < len(percentiles): - raise ValueError("percentiles cannot contain duplicates") - percentiles = unique_pcts + percentiles = _refine_percentiles(percentiles) if obj.ndim == 1: + series = cast("Series", obj) # Incompatible return value type # (got "Series", expected "FrameOrSeries") [return-value] return describe_1d( - obj, + series, percentiles, datetime_is_numeric, is_series=True, @@ -125,14 +107,14 @@ def describe_ndframe( return d -def describe_numeric_1d(series, percentiles) -> "Series": +def describe_numeric_1d(series: "Series", percentiles: Sequence[float]) -> "Series": """Describe series containing numerical data. Parameters ---------- series : Series Series to be described. - percentiles : list-like of numbers, optional + percentiles : list-like of numbers The percentiles to include in the output. """ from pandas import Series @@ -148,7 +130,7 @@ def describe_numeric_1d(series, percentiles) -> "Series": return Series(d, index=stat_index, name=series.name) -def describe_categorical_1d(data, is_series) -> "Series": +def describe_categorical_1d(data: "Series", is_series: bool) -> "Series": """Describe series containing categorical data. Parameters @@ -210,14 +192,14 @@ def describe_categorical_1d(data, is_series) -> "Series": return Series(result, index=names, name=data.name, dtype=dtype) -def describe_timestamp_1d(data, percentiles) -> "Series": +def describe_timestamp_1d(data: "Series", percentiles: Sequence[float]) -> "Series": """Describe series containing datetime64 dtype. Parameters ---------- data : Series Series to be described. - percentiles : list-like of numbers, optional + percentiles : list-like of numbers The percentiles to include in the output. """ # GH-30164 @@ -234,14 +216,20 @@ def describe_timestamp_1d(data, percentiles) -> "Series": return Series(d, index=stat_index, name=data.name) -def describe_1d(data, percentiles, datetime_is_numeric, *, is_series) -> "Series": +def describe_1d( + data: "Series", + percentiles: Sequence[float], + datetime_is_numeric: bool, + *, + is_series: bool, +) -> "Series": """Describe series. Parameters ---------- data : Series Series to be described. - percentiles : list-like of numbers, optional + percentiles : list-like of numbers The percentiles to include in the output. datetime_is_numeric : bool, default False Whether to treat datetime dtypes as numeric. @@ -263,3 +251,35 @@ def describe_1d(data, percentiles, datetime_is_numeric, *, is_series) -> "Series return describe_numeric_1d(data, percentiles) else: return describe_categorical_1d(data, is_series) + + +def _refine_percentiles(percentiles: Optional[Sequence[float]]) -> Sequence[float]: + """Ensure that percentiles are unique and sorted. + + Parameters + ---------- + percentiles : list-like of numbers, optional + The percentiles to include in the output. + """ + if percentiles is None: + return np.array([0.25, 0.5, 0.75]) + + # explicit conversion of `percentiles` to list + percentiles = list(percentiles) + + # get them all to be in [0, 1] + validate_percentile(percentiles) + + # median should always be included + if 0.5 not in percentiles: + percentiles.append(0.5) + + percentiles = np.asarray(percentiles) + + # sort and check for duplicates + unique_pcts = np.unique(percentiles) + assert percentiles is not None + if len(unique_pcts) < len(percentiles): + raise ValueError("percentiles cannot contain duplicates") + + return unique_pcts
- [ ] xref #36833 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Extracted function ``_refine_percentiles`` and typed function arguments in ``pandas/core/describe.py``.
https://api.github.com/repos/pandas-dev/pandas/pulls/39165
2021-01-14T07:40:16Z
2021-01-14T14:20:43Z
2021-01-14T14:20:43Z
2021-01-15T12:14:26Z
API/BUG: always try to operate inplace when setting with loc/iloc[foo, bar]
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index f7204ceb9d412..68130baff1847 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -181,6 +181,46 @@ Preserve dtypes in :meth:`~pandas.DataFrame.combine_first` combined.dtypes +Try operating inplace when setting values with ``loc`` and ``iloc`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When setting an entire column using ``loc`` or ``iloc``, pandas will try to +insert the values into the existing data rather than create an entirely new array. + +.. ipython:: python + + df = pd.DataFrame(range(3), columns=["A"], dtype="float64") + values = df.values + new = np.array([5, 6, 7], dtype="int64") + df.loc[[0, 1, 2], "A"] = new + +In both the new and old behavior, the data in ``values`` is overwritten, but in +the old behavior the dtype of ``df["A"]`` changed to ``int64``. + +*pandas 1.2.x* + +.. code-block:: ipython + + In [1]: df.dtypes + Out[1]: + A int64 + dtype: object + In [2]: np.shares_memory(df["A"].values, new) + Out[2]: False + In [3]: np.shares_memory(df["A"].values, values) + Out[3]: False + +In pandas 1.3.0, ``df`` continues to share data with ``values`` + +*pandas 1.3.0* + +.. ipython:: python + + df.dtypes + np.shares_memory(df["A"], new) + np.shares_memory(df["A"], values) + + .. _whatsnew_130.notable_bug_fixes.setitem_with_bool_casting: Consistent Casting With Setting Into Boolean Series diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index bded503a1e6db..31d2baf6c64f1 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1866,7 +1866,6 @@ def _setitem_single_column(self, loc: int, value, plane_indexer): ser = value elif is_array_like(value) and is_exact_shape_match(ser, value): ser = value - else: # set the item, possibly having a dtype change ser = ser.copy() diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index f2b8499a316b7..63fae32acf3ff 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -92,6 +92,8 @@ Categorical, DatetimeArray, ExtensionArray, + FloatingArray, + IntegerArray, PandasArray, ) from pandas.core.base import PandasObject @@ -994,6 +996,7 @@ def setitem(self, indexer, value): # length checking check_setitem_lengths(indexer, value, values) exact_match = is_exact_shape_match(values, arr_value) + if is_empty_indexer(indexer, arr_value): # GH#8669 empty indexers pass @@ -1007,18 +1010,14 @@ def setitem(self, indexer, value): # GH25495 - If the current dtype is not categorical, # we need to create a new categorical block values[indexer] = value - if values.ndim == 2: - # TODO(EA2D): special case not needed with 2D EAs - if values.shape[-1] != 1: - # shouldn't get here (at least until 2D EAs) - raise NotImplementedError - values = values[:, 0] - return self.make_block(Categorical(values, dtype=arr_value.dtype)) elif exact_match and is_ea_value: # GH#32395 if we're going to replace the values entirely, just # substitute in the new array - return self.make_block(arr_value) + if not self.is_object and isinstance(value, (IntegerArray, FloatingArray)): + values[indexer] = value.to_numpy(value.dtype.numpy_dtype) + else: + values[indexer] = np.asarray(value) # if we are an exact match (ex-broadcasting), # then use the resultant dtype @@ -1026,8 +1025,6 @@ def setitem(self, indexer, value): # We are setting _all_ of the array's values, so can cast to new dtype values[indexer] = value - values = values.astype(arr_value.dtype, copy=False) - elif is_ea_value: # GH#38952 if values.ndim == 1: @@ -1892,6 +1889,10 @@ class NumericBlock(Block): is_numeric = True def _can_hold_element(self, element: Any) -> bool: + element = extract_array(element, extract_numpy=True) + if isinstance(element, (IntegerArray, FloatingArray)): + if element._mask.any(): + return False return can_hold_element(self.dtype, element) @property diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py index 16b9b8e8efdea..34c9c097fbfd5 100644 --- a/pandas/tests/extension/base/setitem.py +++ b/pandas/tests/extension/base/setitem.py @@ -339,13 +339,20 @@ def test_setitem_with_expansion_dataframe_column(self, data, full_indexer): key = full_indexer(df) result.loc[key, "data"] = df["data"] + self.assert_frame_equal(result, expected) def test_setitem_series(self, data, full_indexer): # https://github.com/pandas-dev/pandas/issues/32395 - ser = expected = pd.Series(data, name="data") + ser = pd.Series(data, name="data") result = pd.Series(index=ser.index, dtype=object, name="data") + # because result has object dtype, the attempt to do setting inplace + # is successful, and object dtype is retained key = full_indexer(ser) result.loc[key] = ser + + expected = pd.Series( + data.astype(object), index=ser.index, name="data", dtype=object + ) self.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 98e173ee23f01..e8995bc654428 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -425,6 +425,23 @@ def test_setitem_slice(self, data, box_in_series): def test_setitem_loc_iloc_slice(self, data): super().test_setitem_loc_iloc_slice(data) + def test_setitem_with_expansion_dataframe_column(self, data, full_indexer): + # https://github.com/pandas-dev/pandas/issues/32395 + df = expected = pd.DataFrame({"data": pd.Series(data)}) + result = pd.DataFrame(index=df.index) + + # because result has object dtype, the attempt to do setting inplace + # is successful, and object dtype is retained + key = full_indexer(df) + result.loc[key, "data"] = df["data"] + + # base class method has expected = df; PandasArray behaves oddly because + # we patch _typ for these tests. + if data.dtype.numpy_dtype != object: + if not isinstance(key, slice) or key != slice(None): + expected = pd.DataFrame({"data": data.to_numpy()}) + self.assert_frame_equal(result, expected) + @skip_nested class TestParsing(BaseNumPyTests, base.BaseParsingTests): diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index d0fdf81121c71..ad5f54174952d 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -67,10 +67,6 @@ def test_iloc_setitem_fullcol_categorical(self, indexer, key): frame = DataFrame({0: range(3)}, dtype=object) cat = Categorical(["alpha", "beta", "gamma"]) - expected = DataFrame({0: cat}) - # NB: pending GH#38896, the expected likely should become - # expected= DataFrame({"A": cat.astype(object)}) - # and should remain a view on the original values assert frame._mgr.blocks[0]._can_hold_element(cat) @@ -78,22 +74,24 @@ def test_iloc_setitem_fullcol_categorical(self, indexer, key): orig_vals = df.values indexer(df)[key, 0] = cat - overwrite = not isinstance(key, slice) + overwrite = isinstance(key, slice) and key == slice(None) - tm.assert_frame_equal(df, expected) - - # TODO: this inconsistency is likely undesired GH#39986 if overwrite: - # check that we overwrote underlying - tm.assert_numpy_array_equal(orig_vals, df.values) + # TODO: GH#39986 this probably shouldn't behave differently + expected = DataFrame({0: cat}) + assert not np.shares_memory(df.values, orig_vals) + else: + expected = DataFrame({0: cat}).astype(object) + assert np.shares_memory(df.values, orig_vals) - # but we don't have a view on orig_vals - orig_vals[0, 0] = 19 - assert df.iloc[0, 0] != 19 + tm.assert_frame_equal(df, expected) # check we dont have a view on cat (may be undesired GH#39986) df.iloc[0, 0] = "gamma" - assert cat[0] != "gamma" + if overwrite: + assert cat[0] != "gamma" + else: + assert cat[0] != "gamma" @pytest.mark.parametrize("box", [pd_array, Series]) def test_iloc_setitem_ea_inplace(self, frame_or_series, box): diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index f55a0ae2c199b..7f0fed71ca5f1 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -620,6 +620,7 @@ def test_float_index_non_scalar_assignment(self): expected = DataFrame({"a": [1, 1, 3], "b": [1, 1, 5]}, index=df.index) tm.assert_frame_equal(expected, df) + def test_loc_setitem_fullindex_views(self): df = DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}, index=[1.0, 2.0, 3.0]) df2 = df.copy() df.loc[df.index] = df.loc[df.index] diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 5b6c042a11332..9dbce283d2a8f 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -588,32 +588,19 @@ def test_loc_modify_datetime(self): tm.assert_frame_equal(df, expected) - def test_loc_setitem_frame(self): - df = DataFrame(np.random.randn(4, 4), index=list("abcd"), columns=list("ABCD")) - - df.loc["a", "A"] = 1 - result = df.loc["a", "A"] - assert result == 1 - - result = df.iloc[0, 0] - assert result == 1 - - df.loc[:, "B":"D"] = 0 - expected = df.loc[:, "B":"D"] - result = df.iloc[:, 1:] - tm.assert_frame_equal(result, expected) - - # GH 6254 - # setting issue - df = DataFrame(index=[3, 5, 4], columns=["A"]) + def test_loc_setitem_frame_with_reindex(self): + # GH#6254 setting issue + df = DataFrame(index=[3, 5, 4], columns=["A"], dtype=float) df.loc[[4, 3, 5], "A"] = np.array([1, 2, 3], dtype="int64") - expected = DataFrame({"A": Series([1, 2, 3], index=[4, 3, 5])}).reindex( - index=[3, 5, 4] - ) + + # setting integer values into a float dataframe with loc is inplace, + # so we retain float dtype + ser = Series([2, 3, 1], index=[3, 5, 4], dtype=float) + expected = DataFrame({"A": ser}) tm.assert_frame_equal(df, expected) - # GH 6252 - # setting with an empty frame + def test_loc_setitem_empty_frame(self): + # GH#6252 setting with an empty frame keys1 = ["@" + str(i) for i in range(5)] val1 = np.arange(5, dtype="int64") @@ -628,11 +615,31 @@ def test_loc_setitem_frame(self): df["B"] = np.nan df.loc[keys2, "B"] = val2 - expected = DataFrame( - {"A": Series(val1, index=keys1), "B": Series(val2, index=keys2)} - ).reindex(index=index) + # Because df["A"] was initialized as float64, setting values into it + # is inplace, so that dtype is retained + sera = Series(val1, index=keys1, dtype=np.float64) + serb = Series(val2, index=keys2) + expected = DataFrame({"A": sera, "B": serb}).reindex(index=index) tm.assert_frame_equal(df, expected) + def test_loc_setitem_frame(self): + df = DataFrame(np.random.randn(4, 4), index=list("abcd"), columns=list("ABCD")) + + result = df.iloc[0, 0] + + df.loc["a", "A"] = 1 + result = df.loc["a", "A"] + assert result == 1 + + result = df.iloc[0, 0] + assert result == 1 + + df.loc[:, "B":"D"] = 0 + expected = df.loc[:, "B":"D"] + result = df.iloc[:, 1:] + tm.assert_frame_equal(result, expected) + + def test_loc_setitem_frame_nan_int_coercion_invalid(self): # GH 8669 # invalid coercion of nan -> int df = DataFrame({"A": [1, 2, 3], "B": np.nan}) @@ -640,6 +647,7 @@ def test_loc_setitem_frame(self): expected = DataFrame({"A": [1, 2, 3], "B": np.nan}) tm.assert_frame_equal(df, expected) + def test_loc_setitem_frame_mixed_labels(self): # GH 6546 # setting with mixed labels df = DataFrame({1: [1, 2], 2: [3, 4], "a": ["a", "b"]}) @@ -1063,8 +1071,15 @@ def test_loc_setitem_str_to_small_float_conversion_type(self): expected = DataFrame(col_data, columns=["A"], dtype=object) tm.assert_frame_equal(result, expected) - # change the dtype of the elements from object to float one by one + # assigning with loc/iloc attempts to set the values inplace, which + # in this case is succesful result.loc[result.index, "A"] = [float(x) for x in col_data] + expected = DataFrame(col_data, columns=["A"], dtype=float).astype(object) + tm.assert_frame_equal(result, expected) + + # assigning the entire column using __setitem__ swaps in the new array + # GH#??? + result["A"] = [float(x) for x in col_data] expected = DataFrame(col_data, columns=["A"], dtype=float) tm.assert_frame_equal(result, expected) @@ -1219,7 +1234,9 @@ def test_loc_setitem_datetimeindex_tz(self, idxer, tz_naive_fixture): tz = tz_naive_fixture idx = date_range(start="2015-07-12", periods=3, freq="H", tz=tz) expected = DataFrame(1.2, index=idx, columns=["var"]) - result = DataFrame(index=idx, columns=["var"]) + # if result started off with object dtype, tehn the .loc.__setitem__ + # below would retain object dtype + result = DataFrame(index=idx, columns=["var"], dtype=np.float64) result.loc[:, idxer] = expected tm.assert_frame_equal(result, expected)
- [x] closes #38896 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry (The PR title should have a caveat "in cases that make it to `BlockManager.setitem`) Discussed briefly on today's call. The main idea, as discussed in #38896 and #33457, is that `df[col] = ser` should _not_ alter the existing `df[col]._values`, while `df.iloc[:, num] = ser` should _always_ try to operate inplace before falling back to casting. This PR focuses on the latter case. ATM, restricting to cases where we a) get to Block.setitem, b) _could_ do the setitem inplace, and c) are setting all the entries in the array, we have 4 different behaviors. Examples are posted at the bottom of this post. This PR changes Block.setitem so that in the _can_hold_element case we _always_ operate inplace, always retain the same underlying array. ------ Existing Behavior 1) If the `new_values` being set are categorical, we overwrite existing values and then discard them, do _not_ get a view on new_values. (only can replicate with Series until #39136) ``` ser = pd.Series(np.arange(5), dtype=object) cat = pd.Categorical(ser)[::-1] vals = ser.values ser.iloc[ser.index] = cat assert (vals == cat).all() # <-- vals are overwritten assert ser.dtype == cat.dtype # < -- vals are discarded assert not np.shares_memory(ser._values.codes, cat.codes) # <-- we also dont get a view on the new values ``` 2) If the new_values are any other EA, we do _not_ overwrite existing values and _do_ get a view on the new_values. ``` df = pd.DataFrame({"A": np.arange(5, dtype=np.int32)}) arr = pd.array(df["A"].values) + 1 vals = df.values df.iloc[df.index, 0] = arr assert (df.dtypes == arr.dtype).all() # <-- cast assert not (vals == df).any(axis=None) # <-- did not overwrite original ``` 3) If the new_values are a new non-EA dtype, we overwrite the old values and create a new array, get a view on neither. ``` df = tm.makeDataFrame() # <-- float64 old = df.values new = np.arange(df.size).astype(np.int16).reshape(df.shape) df.iloc[:, [0, 1, 2, 3]] = new assert (old == new).all() assert not np.shares_memory(df.values, old) assert not np.shares_memory(df.values, new) ``` 4) If the new_values have the same dtype as the existing, we overwrite existing and keep the same array ``` df = tm.makeDataFrame() # <-- float64 old = df.values new = np.arange(df.size).astype(np.float64).reshape(df.shape) df.iloc[:, [0, 1, 2, 3]] = new assert (old == new).all() assert np.shares_memory(df.values, old) assert not np.shares_memory(df.values, new) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/39163
2021-01-14T02:49:27Z
2021-03-05T00:09:35Z
2021-03-05T00:09:34Z
2021-03-08T22:15:38Z
Fix regression in loc setitem raising KeyError when enlarging df with multiindex
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 1c8db4dd32393..55fddb8b732e2 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -29,7 +29,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) - Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) - Fixed regression in :meth:`DataFrame.groupby` when aggregating an :class:`ExtensionDType` that could fail for non-numeric values (:issue:`38980`) -- +- Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``KeyError`` with :class:`MultiIndex` and list-like columns indexer enlarging :class:`DataFrame` (:issue:`39147`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index ac0955c6c3e4c..8cd1b23b75edd 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -662,9 +662,9 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None): if self.ndim != 2: return - if isinstance(key, tuple) and not isinstance(self.obj.index, ABCMultiIndex): + if isinstance(key, tuple) and len(key) > 1: # key may be a tuple if we are .loc - # if index is not a MultiIndex, set key to column part + # if length of key is > 1 set key to column part key = key[column_axis] axis = column_axis diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index ba01caba544f4..402668321600b 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -308,6 +308,21 @@ def test_multiindex_one_dimensional_tuple_columns(self, indexer): expected = DataFrame([0, 2], index=mi) tm.assert_frame_equal(obj, expected) + @pytest.mark.parametrize( + "indexer, exp_value", [(slice(None), 1.0), ((1, 2), np.nan)] + ) + def test_multiindex_setitem_columns_enlarging(self, indexer, exp_value): + # GH#39147 + mi = MultiIndex.from_tuples([(1, 2), (3, 4)]) + df = DataFrame([[1, 2], [3, 4]], index=mi, columns=["a", "b"]) + df.loc[indexer, ["c", "d"]] = 1.0 + expected = DataFrame( + [[1, 2, 1.0, 1.0], [3, 4, exp_value, exp_value]], + index=mi, + columns=["a", "b", "c", "d"], + ) + tm.assert_frame_equal(df, expected) + @pytest.mark.parametrize( "indexer, pos",
- [x] closes #39147 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry The previous fix only viewed row indexers not column indexers
https://api.github.com/repos/pandas-dev/pandas/pulls/39161
2021-01-14T00:03:38Z
2021-01-15T14:14:18Z
2021-01-15T14:14:18Z
2021-01-15T16:04:31Z
Backport PR #39029: BUG: read_csv does not close file during an error in _make_reader
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 849b599141c2b..1c8db4dd32393 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -40,7 +40,7 @@ Bug fixes ~~~~~~~~~ - Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) -- +- Bug in :func:`read_csv` not closing an opened file handle when a ``csv.Error`` or ``UnicodeDecodeError`` occurred while initializing (:issue:`39024`) - .. --------------------------------------------------------------------------- diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index fcbf7ec3897fc..d99abbea90a51 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -2288,7 +2288,11 @@ def __init__(self, f: Union[FilePathOrBuffer, List], **kwds): self._open_handles(f, kwds) assert self.handles is not None assert hasattr(self.handles.handle, "readline") - self._make_reader(self.handles.handle) + try: + self._make_reader(self.handles.handle) + except (csv.Error, UnicodeDecodeError): + self.close() + raise # Get columns in two steps: infer from data, then # infer column indices from self.usecols if it is specified. diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index d42bd7a004584..8871ea7205a46 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -8,8 +8,10 @@ from inspect import signature from io import BytesIO, StringIO import os +from pathlib import Path import platform from urllib.error import URLError +import warnings import numpy as np import pytest @@ -2369,3 +2371,22 @@ def test_context_manageri_user_provided(all_parsers, datapath): assert False except AssertionError: assert not reader._engine.handles.handle.closed + + +@td.check_file_leaks +def test_open_file(all_parsers): + # GH 39024 + parser = all_parsers + if parser.engine == "c": + pytest.skip() + + with tm.ensure_clean() as path: + file = Path(path) + file.write_bytes(b"\xe4\na\n1") + + # should not trigger a ResourceWarning + warnings.simplefilter("always", category=ResourceWarning) + with warnings.catch_warnings(record=True) as record: + with pytest.raises(csv.Error, match="Could not determine delimiter"): + parser.read_csv(file, sep=None) + assert len(record) == 0, record[0].message
Backport PR #39029
https://api.github.com/repos/pandas-dev/pandas/pulls/39160
2021-01-13T23:58:39Z
2021-01-14T13:09:09Z
2021-01-14T13:09:09Z
2021-01-19T15:54:13Z
Backport PR #39156 on branch 1.2.x (CI: Mark network test as xfail)
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index 97f82b9a01a9a..726c5ebffe9b5 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -208,6 +208,7 @@ def test_read_s3_fails(self, s3so): with pytest.raises(IOError): read_csv("s3://cant_get_it/file.csv") + @pytest.mark.xfail(reason="GH#39155 s3fs upgrade") def test_write_s3_csv_fails(self, tips_df, s3so): # GH 32486 # Attempting to write to an invalid S3 path should raise @@ -223,6 +224,7 @@ def test_write_s3_csv_fails(self, tips_df, s3so): "s3://an_s3_bucket_data_doesnt_exit/not_real.csv", storage_options=s3so ) + @pytest.mark.xfail(reason="GH#39155 s3fs upgrade") @td.skip_if_no("pyarrow") def test_write_s3_parquet_fails(self, tips_df, s3so): # GH 27679
Backport PR #39156: CI: Mark network test as xfail
https://api.github.com/repos/pandas-dev/pandas/pulls/39157
2021-01-13T23:40:30Z
2021-01-14T00:29:42Z
2021-01-14T00:29:42Z
2021-01-14T00:29:42Z
CI: Mark network test as xfail
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index c22945e931f18..8ddb860597ddd 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -209,6 +209,7 @@ def test_read_s3_fails(self, s3so): with pytest.raises(IOError, match=msg): read_csv("s3://cant_get_it/file.csv") + @pytest.mark.xfail(reason="GH#39155 s3fs upgrade") def test_write_s3_csv_fails(self, tips_df, s3so): # GH 32486 # Attempting to write to an invalid S3 path should raise @@ -224,6 +225,7 @@ def test_write_s3_csv_fails(self, tips_df, s3so): "s3://an_s3_bucket_data_doesnt_exit/not_real.csv", storage_options=s3so ) + @pytest.mark.xfail(reason="GH#39155 s3fs upgrade") @td.skip_if_no("pyarrow") def test_write_s3_parquet_fails(self, tips_df, s3so): # GH 27679
- [x] xref #39155 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them https://github.com/pandas-dev/pandas/issues/39155#issuecomment-759783358
https://api.github.com/repos/pandas-dev/pandas/pulls/39156
2021-01-13T22:52:12Z
2021-01-13T23:38:47Z
2021-01-13T23:38:47Z
2021-01-13T23:41:29Z
BUG: Minor fix setitem_cache_updating tests
diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 0047b396c68b0..119091657223a 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -36,7 +36,7 @@ def test_setitem_cache_updating(self): # GH 5424 cont = ["one", "two", "three", "four", "five", "six", "seven"] - for do_ref in [False, False]: + for do_ref in [True, False]: df = DataFrame({"a": cont, "b": cont[3:] + cont[:3], "c": np.arange(7)}) # ref the cache
BUG: tiny fix in tests, i guess from rapid development ;) -> https://github.com/pandas-dev/pandas/issues/5424#issuecomment-27658793
https://api.github.com/repos/pandas-dev/pandas/pulls/39153
2021-01-13T20:16:26Z
2021-01-14T15:56:14Z
2021-01-14T15:56:14Z
2021-01-14T15:56:19Z
CLN remove 'import pandas as pd' from pandas/core/generic.py
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9e3f6f8e36175..207523fa55c5e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -85,7 +85,6 @@ from pandas.core.dtypes.inference import is_hashable from pandas.core.dtypes.missing import isna, notna -import pandas as pd from pandas.core import arraylike, indexing, missing, nanops import pandas.core.algorithms as algos from pandas.core.arrays import ExtensionArray @@ -106,6 +105,7 @@ from pandas.core.internals import ArrayManager, BlockManager from pandas.core.missing import find_valid_index from pandas.core.ops import align_method_FRAME +from pandas.core.reshape.concat import concat from pandas.core.shared_docs import _shared_docs from pandas.core.sorting import get_indexer_indexer from pandas.core.window import Expanding, ExponentialMovingWindow, Rolling, Window @@ -5304,7 +5304,11 @@ def sample( "when sampling from a Series." ) - weights = pd.Series(weights, dtype="float64") + if isinstance(self, ABCSeries): + func = self._constructor + else: + func = self._constructor_sliced + weights = func(weights, dtype="float64") if len(weights) != axis_length: raise ValueError( @@ -5890,7 +5894,7 @@ def astype( return self.copy() # GH 19920: retain column metadata after concat - result = pd.concat(results, axis=1, copy=False) + result = concat(results, axis=1, copy=False) result.columns = self.columns return result @@ -6254,7 +6258,7 @@ def convert_dtypes( ) for col_name, col in self.items() ] - result = pd.concat(results, axis=1, copy=False) + result = concat(results, axis=1, copy=False) return result # ---------------------------------------------------------------------- @@ -6532,10 +6536,8 @@ def replace( if isinstance(to_replace, (tuple, list)): if isinstance(self, ABCDataFrame): - from pandas import Series - return self.apply( - Series._replace_single, + self._constructor_sliced._replace_single, args=(to_replace, method, inplace, limit), ) self = cast("Series", self)
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them --- will do the rest (excluding `pandas/tests`) and add a check if this is the kind of thing we want
https://api.github.com/repos/pandas-dev/pandas/pulls/39152
2021-01-13T17:55:04Z
2021-01-14T19:18:37Z
2021-01-14T19:18:37Z
2021-01-31T13:28:25Z
DOC: 1.3 release notes
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 170d3eeb1e252..196d2f2d968a7 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -33,17 +33,12 @@ For example: storage_options=headers ) -.. _whatsnew_130.window_method_table: - -:class:`Rolling` and :class:`Expanding` now support a ``method`` argument with a -``'table'`` option that performs the windowing operation over an entire :class:`DataFrame`. -See ref:`window.overview` for performance and functional benefits. (:issue:`15095`, :issue:`38995`) - .. _whatsnew_130.enhancements.other: Other enhancements ^^^^^^^^^^^^^^^^^^ +- :class:`Rolling` and :class:`Expanding` now support a ``method`` argument with a ``'table'`` option that performs the windowing operation over an entire :class:`DataFrame`. See ref:`window.overview` for performance and functional benefits (:issue:`15095`, :issue:`38995`) - Added :meth:`MultiIndex.dtypes` (:issue:`37062`) - Added ``end`` and ``end_day`` options for ``origin`` in :meth:`DataFrame.resample` (:issue:`37804`) - Improve error message when ``usecols`` and ``names`` do not match for :func:`read_csv` and ``engine="c"`` (:issue:`29042`) @@ -55,7 +50,7 @@ Other enhancements - :func:`pandas.read_excel` can now auto detect .xlsb files (:issue:`35416`) - :meth:`.Rolling.sum`, :meth:`.Expanding.sum`, :meth:`.Rolling.mean`, :meth:`.Expanding.mean`, :meth:`.Rolling.median`, :meth:`.Expanding.median`, :meth:`.Rolling.max`, :meth:`.Expanding.max`, :meth:`.Rolling.min`, and :meth:`.Expanding.min` now support ``Numba`` execution with the ``engine`` keyword (:issue:`38895`) - :meth:`DataFrame.apply` can now accept NumPy unary operators as strings, e.g. ``df.apply("sqrt")``, which was already the case for :meth:`Series.apply` (:issue:`39116`) -- :meth:`DataFrame.apply` can now accept non-callable DataFrame properties as strings, e.g. ``df.apply("size")``, which was already the case for :meth:`Series.apply` (:issue:`39116`) +- :meth:`DataFrame.apply` can now accept non-callable :class:`DataFrame` properties as strings, e.g. ``df.apply("size")``, which was already the case for :meth:`Series.apply` (:issue:`39116`) .. --------------------------------------------------------------------------- @@ -157,10 +152,10 @@ Other API changes Deprecations ~~~~~~~~~~~~ -- Deprecating allowing scalars passed to the :class:`Categorical` constructor (:issue:`38433`) -- Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`,:issue:`21311`,:issue:`22315`,:issue:`26974`) +- Deprecated allowing scalars to be passed to the :class:`Categorical` constructor (:issue:`38433`) +- Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`, :issue:`21311`, :issue:`22315`, :issue:`26974`) - Deprecated ``astype`` of datetimelike (``timedelta64[ns]``, ``datetime64[ns]``, ``Datetime64TZDtype``, ``PeriodDtype``) to integer dtypes, use ``values.view(...)`` instead (:issue:`38544`) -- Deprecated :meth:`MultiIndex.is_lexsorted` and :meth:`MultiIndex.lexsort_depth` as a public methods, users should use :meth:`MultiIndex.is_monotonic_increasing` instead (:issue:`32259`) +- Deprecated :meth:`MultiIndex.is_lexsorted` and :meth:`MultiIndex.lexsort_depth`, use :meth:`MultiIndex.is_monotonic_increasing` instead (:issue:`32259`) - Deprecated keyword ``try_cast`` in :meth:`Series.where`, :meth:`Series.mask`, :meth:`DataFrame.where`, :meth:`DataFrame.mask`; cast results manually if desired (:issue:`38836`) - Deprecated comparison of :class:`Timestamp` object with ``datetime.date`` objects. Instead of e.g. ``ts <= mydate`` use ``ts <= pd.Timestamp(mydate)`` or ``ts.date() <= mydate`` (:issue:`36131`) - Deprecated :attr:`Rolling.win_type` returning ``"freq"`` (:issue:`38963`) @@ -185,23 +180,20 @@ Performance improvements Bug fixes ~~~~~~~~~ -- -- - Categorical ^^^^^^^^^^^ - Bug in :class:`CategoricalIndex` incorrectly failing to raise ``TypeError`` when scalar data is passed (:issue:`38614`) - Bug in ``CategoricalIndex.reindex`` failed when ``Index`` passed with elements all in category (:issue:`28690`) - Bug where constructing a :class:`Categorical` from an object-dtype array of ``date`` objects did not round-trip correctly with ``astype`` (:issue:`38552`) - Bug in constructing a :class:`DataFrame` from an ``ndarray`` and a :class:`CategoricalDtype` (:issue:`38857`) -- Bug in :meth:`DataFrame.reindex` was throwing ``IndexError`` when new index contained duplicates and old index was :class:`CategoricalIndex` (:issue:`38906`) +- Bug in :meth:`DataFrame.reindex` was raising ``IndexError`` when new index contained duplicates and old index was :class:`CategoricalIndex` (:issue:`38906`) Datetimelike ^^^^^^^^^^^^ - Bug in :class:`DataFrame` and :class:`Series` constructors sometimes dropping nanoseconds from :class:`Timestamp` (resp. :class:`Timedelta`) ``data``, with ``dtype=datetime64[ns]`` (resp. ``timedelta64[ns]``) (:issue:`38032`) - Bug in :meth:`DataFrame.first` and :meth:`Series.first` returning two months for offset one month when first day is last calendar day (:issue:`29623`) - Bug in constructing a :class:`DataFrame` or :class:`Series` with mismatched ``datetime64`` data and ``timedelta64`` dtype, or vice-versa, failing to raise ``TypeError`` (:issue:`38575`, :issue:`38764`, :issue:`38792`) -- Bug in constructing a :class:`Series` or :class:`DataFrame` with a ``datetime`` object out of bounds for ``datetime64[ns]`` dtype or a ``timedelta`` object ouf of bounds for ``timedelta64[ns]`` dtype (:issue:`38792`, :issue:`38965`) +- Bug in constructing a :class:`Series` or :class:`DataFrame` with a ``datetime`` object out of bounds for ``datetime64[ns]`` dtype or a ``timedelta`` object out of bounds for ``timedelta64[ns]`` dtype (:issue:`38792`, :issue:`38965`) - Bug in :meth:`DatetimeIndex.intersection`, :meth:`DatetimeIndex.symmetric_difference`, :meth:`PeriodIndex.intersection`, :meth:`PeriodIndex.symmetric_difference` always returning object-dtype when operating with :class:`CategoricalIndex` (:issue:`38741`) - Bug in :meth:`Series.where` incorrectly casting ``datetime64`` values to ``int64`` (:issue:`37682`) - Bug in :class:`Categorical` incorrectly typecasting ``datetime`` object to ``Timestamp`` (:issue:`38878`) @@ -265,9 +257,9 @@ Missing MultiIndex ^^^^^^^^^^ -- Bug in :meth:`DataFrame.drop` raising ``TypeError`` when :class:`MultiIndex` is non-unique and no level is provided (:issue:`36293`) +- Bug in :meth:`DataFrame.drop` raising ``TypeError`` when :class:`MultiIndex` is non-unique and ``level`` is not provided (:issue:`36293`) - Bug in :meth:`MultiIndex.intersection` duplicating ``NaN`` in result (:issue:`38623`) -- Bug in :meth:`MultiIndex.equals` incorrectly returning ``True`` when :class:`MultiIndex` containing ``NaN`` even when they are differntly ordered (:issue:`38439`) +- Bug in :meth:`MultiIndex.equals` incorrectly returning ``True`` when :class:`MultiIndex` containing ``NaN`` even when they are differently ordered (:issue:`38439`) - Bug in :meth:`MultiIndex.intersection` always returning empty when intersecting with :class:`CategoricalIndex` (:issue:`38653`) I/O @@ -282,14 +274,13 @@ I/O - Bug in :func:`read_csv` raising ``TypeError`` when ``names`` and ``parse_dates`` is specified for ``engine="c"`` (:issue:`33699`) - Bug in :func:`read_clipboard`, :func:`DataFrame.to_clipboard` not working in WSL (:issue:`38527`) - Allow custom error values for parse_dates argument of :func:`read_sql`, :func:`read_sql_query` and :func:`read_sql_table` (:issue:`35185`) -- Bug in :func:`to_hdf` raising ``KeyError`` when trying to apply - for subclasses of ``DataFrame`` or ``Series`` (:issue:`33748`). +- Bug in :func:`to_hdf` raising ``KeyError`` when trying to apply for subclasses of ``DataFrame`` or ``Series`` (:issue:`33748`) - Bug in :meth:`~HDFStore.put` raising a wrong ``TypeError`` when saving a DataFrame with non-string dtype (:issue:`34274`) - Bug in :func:`json_normalize` resulting in the first element of a generator object not being included in the returned ``DataFrame`` (:issue:`35923`) - Bug in :func:`read_excel` forward filling :class:`MultiIndex` names with multiple header and index columns specified (:issue:`34673`) -- :func:`pandas.read_excel` now respects :func:``pandas.set_option`` (:issue:`34252`) +- :func:`read_excel` now respects :func:`set_option` (:issue:`34252`) - Bug in :func:`read_csv` not switching ``true_values`` and ``false_values`` for nullable ``boolean`` dtype (:issue:`34655`) -- Bug in :func:``read_json`` when ``orient="split"`` does not maintan numeric string index (:issue:`28556`) +- Bug in :func:`read_json` when ``orient="split"`` does not maintain numeric string index (:issue:`28556`) Period ^^^^^^ @@ -311,7 +302,7 @@ Groupby/resample/rolling - Bug in :meth:`.GroupBy.indices` would contain non-existent indices when null values were present in the groupby keys (:issue:`9304`) - Fixed bug in :meth:`DataFrameGroupBy.sum` and :meth:`SeriesGroupBy.sum` causing loss of precision through using Kahan summation (:issue:`38778`) - Fixed bug in :meth:`DataFrameGroupBy.cumsum`, :meth:`SeriesGroupBy.cumsum`, :meth:`DataFrameGroupBy.mean` and :meth:`SeriesGroupBy.mean` causing loss of precision through using Kahan summation (:issue:`38934`) -- Bug in :meth:`.Resampler.aggregate` and :meth:`DataFrame.transform` raising ``TypeError`` instead of ``SpecificationError`` when missing keys having mixed dtypes (:issue:`39025`) +- Bug in :meth:`.Resampler.aggregate` and :meth:`DataFrame.transform` raising ``TypeError`` instead of ``SpecificationError`` when missing keys had mixed dtypes (:issue:`39025`) Reshaping ^^^^^^^^^ @@ -332,13 +323,13 @@ Sparse ExtensionArray ^^^^^^^^^^^^^^ -- Bug in :meth:`DataFrame.where` when ``other`` is a :class:`Series` with ExtensionArray dtype (:issue:`38729`) +- Bug in :meth:`DataFrame.where` when ``other`` is a :class:`Series` with :class:`ExtensionArray` dtype (:issue:`38729`) - Fixed bug where :meth:`Series.idxmax`, :meth:`Series.idxmin` and ``argmax/min`` fail when the underlying data is :class:`ExtensionArray` (:issue:`32749`, :issue:`33719`, :issue:`36566`) - Other ^^^^^ -- Bug in :class:`Index` constructor sometimes silently ignorning a a specified ``dtype`` (:issue:`38879`) +- Bug in :class:`Index` constructor sometimes silently ignorning a specified ``dtype`` (:issue:`38879`) - -
https://api.github.com/repos/pandas-dev/pandas/pulls/39150
2021-01-13T16:49:36Z
2021-01-14T15:58:21Z
2021-01-14T15:58:21Z
2021-01-14T15:58:26Z
REF: implement is_exact_match
diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py index a221f77f26170..79479c6db8d9d 100644 --- a/pandas/core/indexers.py +++ b/pandas/core/indexers.py @@ -5,7 +5,7 @@ import numpy as np -from pandas._typing import Any, AnyArrayLike +from pandas._typing import Any, AnyArrayLike, ArrayLike from pandas.core.dtypes.common import ( is_array_like, @@ -270,6 +270,27 @@ def maybe_convert_indices(indices, n: int): # Unsorted +def is_exact_shape_match(target: ArrayLike, value: ArrayLike) -> bool: + """ + Is setting this value into this target overwriting the entire column? + + Parameters + ---------- + target : np.ndarray or ExtensionArray + value : np.ndarray or ExtensionArray + + Returns + ------- + bool + """ + return ( + len(value.shape) > 0 + and len(target.shape) > 0 + and value.shape[0] == target.shape[0] + and value.size == target.size + ) + + def length_of_indexer(indexer, target=None) -> int: """ Return the expected length of target[indexer] diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index ac0955c6c3e4c..f1f3265c9f970 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -33,6 +33,7 @@ from pandas.core.construction import array as pd_array from pandas.core.indexers import ( check_array_indexer, + is_exact_shape_match, is_list_like_indexer, length_of_indexer, ) @@ -1815,6 +1816,9 @@ def _setitem_single_column(self, loc: int, value, plane_indexer): # GH#6149 (null slice), GH#10408 (full bounds) if com.is_null_slice(pi) or com.is_full_slice(pi, len(self.obj)): ser = value + elif is_array_like(value) and is_exact_shape_match(ser, value): + ser = value + else: # set the item, possibly having a dtype change ser = ser.copy() diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 9eb4bdc5dbae3..0216334a4c0aa 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -75,6 +75,7 @@ from pandas.core.indexers import ( check_setitem_lengths, is_empty_indexer, + is_exact_shape_match, is_scalar_indexer, ) import pandas.core.missing as missing @@ -903,15 +904,7 @@ def setitem(self, indexer, value): # coerce if block dtype can store value values = self.values - if self._can_hold_element(value): - # We only get here for non-Extension Blocks, so _try_coerce_args - # is only relevant for DatetimeBlock and TimedeltaBlock - if self.dtype.kind in ["m", "M"]: - arr = self.array_values().T - arr[indexer] = value - return self - - else: + if not self._can_hold_element(value): # current dtype cannot store value, coerce to common dtype # TODO: can we just use coerce_to_target_dtype for all this if hasattr(value, "dtype"): @@ -932,6 +925,11 @@ def setitem(self, indexer, value): return self.astype(dtype).setitem(indexer, value) + if self.dtype.kind in ["m", "M"]: + arr = self.array_values().T + arr[indexer] = value + return self + # value must be storable at this moment if is_extension_array_dtype(getattr(value, "dtype", None)): # We need to be careful not to allow through strings that @@ -947,11 +945,7 @@ def setitem(self, indexer, value): # length checking check_setitem_lengths(indexer, value, values) - exact_match = ( - len(arr_value.shape) - and arr_value.shape[0] == values.shape[0] - and arr_value.size == values.size - ) + exact_match = is_exact_shape_match(values, arr_value) if is_empty_indexer(indexer, arr_value): # GH#8669 empty indexers pass
Working to smooth out some inconsistencies in setitem between code paths.
https://api.github.com/repos/pandas-dev/pandas/pulls/39149
2021-01-13T16:14:38Z
2021-01-14T14:23:03Z
2021-01-14T14:23:03Z
2021-01-14T15:33:08Z
Backport PR #38982 on branch 1.2.x (REGR: Bug fix for ExtensionArray groupby aggregation on non-numeric types)
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 36b4b4fa77c4a..849b599141c2b 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -28,6 +28,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.replace` raising ``ValueError`` when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) - Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) - Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) +- Fixed regression in :meth:`DataFrame.groupby` when aggregating an :class:`ExtensionDType` that could fail for non-numeric values (:issue:`38980`) - - diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index e2ba2768a885a..b86d54024c62d 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -543,7 +543,9 @@ def _ea_wrap_cython_operation( result = type(orig_values)._from_sequence(res_values) return result - raise NotImplementedError(values.dtype) + raise NotImplementedError( + f"function is not implemented for this dtype: {values.dtype}" + ) @final def _cython_operation( diff --git a/pandas/tests/extension/base/groupby.py b/pandas/tests/extension/base/groupby.py index 94d0ef7bbea84..c81304695f353 100644 --- a/pandas/tests/extension/base/groupby.py +++ b/pandas/tests/extension/base/groupby.py @@ -33,6 +33,22 @@ def test_groupby_extension_agg(self, as_index, data_for_grouping): expected = expected.reset_index() self.assert_frame_equal(result, expected) + def test_groupby_agg_extension(self, data_for_grouping): + # GH#38980 groupby agg on extension type fails for non-numeric types + df = pd.DataFrame({"A": [1, 1, 2, 2, 3, 3, 1, 4], "B": data_for_grouping}) + + expected = df.iloc[[0, 2, 4, 7]] + expected = expected.set_index("A") + + result = df.groupby("A").agg({"B": "first"}) + self.assert_frame_equal(result, expected) + + result = df.groupby("A").agg("first") + self.assert_frame_equal(result, expected) + + result = df.groupby("A").first() + self.assert_frame_equal(result, expected) + def test_groupby_extension_no_sort(self, data_for_grouping): df = pd.DataFrame({"A": [1, 1, 2, 2, 3, 3, 1, 4], "B": data_for_grouping}) result = df.groupby("B", sort=False).A.mean() diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 233b658d29782..08768bda312ba 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -197,6 +197,10 @@ class TestGroupby(BaseDecimal, base.BaseGroupbyTests): def test_groupby_apply_identity(self, data_for_grouping): super().test_groupby_apply_identity(data_for_grouping) + @pytest.mark.xfail(reason="GH#39098: Converts agg result to object") + def test_groupby_agg_extension(self, data_for_grouping): + super().test_groupby_agg_extension(data_for_grouping) + class TestSetitem(BaseDecimal, base.BaseSetitemTests): pass diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 3a5e49796c53b..164a39498ec73 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -313,6 +313,10 @@ def test_groupby_extension_apply(self): def test_groupby_extension_agg(self, as_index, data_for_grouping): super().test_groupby_extension_agg(as_index, data_for_grouping) + @pytest.mark.xfail(reason="GH#39098: Converts agg result to object") + def test_groupby_agg_extension(self, data_for_grouping): + super().test_groupby_agg_extension(data_for_grouping) + class TestArithmeticOps(BaseJSON, base.BaseArithmeticOpsTests): def test_error(self, data, all_arithmetic_operators): diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py index ced7ea9261310..86a0bc9213256 100644 --- a/pandas/tests/extension/test_boolean.py +++ b/pandas/tests/extension/test_boolean.py @@ -291,6 +291,22 @@ def test_groupby_extension_agg(self, as_index, data_for_grouping): expected = expected.reset_index() self.assert_frame_equal(result, expected) + def test_groupby_agg_extension(self, data_for_grouping): + # GH#38980 groupby agg on extension type fails for non-numeric types + df = pd.DataFrame({"A": [1, 1, 2, 2, 3, 3, 1], "B": data_for_grouping}) + + expected = df.iloc[[0, 2, 4]] + expected = expected.set_index("A") + + result = df.groupby("A").agg({"B": "first"}) + self.assert_frame_equal(result, expected) + + result = df.groupby("A").agg("first") + self.assert_frame_equal(result, expected) + + result = df.groupby("A").first() + self.assert_frame_equal(result, expected) + def test_groupby_extension_no_sort(self, data_for_grouping): df = pd.DataFrame({"A": [1, 1, 2, 2, 3, 3, 1], "B": data_for_grouping}) result = df.groupby("B", sort=False).A.mean()
Backport PR #38982: REGR: Bug fix for ExtensionArray groupby aggregation on non-numeric types
https://api.github.com/repos/pandas-dev/pandas/pulls/39145
2021-01-13T13:20:16Z
2021-01-13T14:00:07Z
2021-01-13T14:00:07Z
2021-01-13T14:00:07Z
ENH: Allow Series.apply to accept list-like and dict-like
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 0cb46a5164674..3082c2278966d 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -50,7 +50,8 @@ Other enhancements - :func:`pandas.read_excel` can now auto detect .xlsb files (:issue:`35416`) - :meth:`.Rolling.sum`, :meth:`.Expanding.sum`, :meth:`.Rolling.mean`, :meth:`.Expanding.mean`, :meth:`.Rolling.median`, :meth:`.Expanding.median`, :meth:`.Rolling.max`, :meth:`.Expanding.max`, :meth:`.Rolling.min`, and :meth:`.Expanding.min` now support ``Numba`` execution with the ``engine`` keyword (:issue:`38895`) - :meth:`DataFrame.apply` can now accept NumPy unary operators as strings, e.g. ``df.apply("sqrt")``, which was already the case for :meth:`Series.apply` (:issue:`39116`) -- :meth:`DataFrame.apply` can now accept non-callable :class:`DataFrame` properties as strings, e.g. ``df.apply("size")``, which was already the case for :meth:`Series.apply` (:issue:`39116`) +- :meth:`DataFrame.apply` can now accept non-callable DataFrame properties as strings, e.g. ``df.apply("size")``, which was already the case for :meth:`Series.apply` (:issue:`39116`) +- :meth:`Series.apply` can now accept list-like or dictionary-like arguments that aren't lists or dictionaries, e.g. ``ser.apply(np.array(["sum", "mean"]))``, which was already the case for :meth:`DataFrame.apply` (:issue:`39140`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index 72a98da44428b..2145551833e90 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -704,7 +704,8 @@ def agg_dict_like( # if we have a dict of any non-scalars # eg. {'A' : ['mean']}, normalize all to # be list-likes - if any(is_aggregator(x) for x in arg.values()): + # Cannot use arg.values() because arg may be a Series + if any(is_aggregator(x) for _, x in arg.items()): new_arg: AggFuncTypeDict = {} for k, v in arg.items(): if not isinstance(v, (tuple, list, dict)): diff --git a/pandas/core/apply.py b/pandas/core/apply.py index f3e759610b784..f7c7220985138 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -195,6 +195,20 @@ def maybe_apply_str(self) -> Optional[FrameOrSeriesUnion]: self.kwds["axis"] = self.axis return self.obj._try_aggregate_string_function(f, *self.args, **self.kwds) + def maybe_apply_multiple(self) -> Optional[FrameOrSeriesUnion]: + """ + Compute apply in case of a list-like or dict-like. + + Returns + ------- + result: Series, DataFrame, or None + Result when self.f is a list-like or dict-like, None otherwise. + """ + # Note: dict-likes are list-like + if not is_list_like(self.f): + return None + return self.obj.aggregate(self.f, self.axis, *self.args, **self.kwds) + class FrameApply(Apply): obj: DataFrame @@ -248,12 +262,9 @@ def agg_axis(self) -> Index: def apply(self) -> FrameOrSeriesUnion: """ compute the results """ # dispatch to agg - if is_list_like(self.f) or is_dict_like(self.f): - # pandas\core\apply.py:144: error: "aggregate" of "DataFrame" gets - # multiple values for keyword argument "axis" - return self.obj.aggregate( # type: ignore[misc] - self.f, axis=self.axis, *self.args, **self.kwds - ) + result = self.maybe_apply_multiple() + if result is not None: + return result # all empty if len(self.columns) == 0 and len(self.index) == 0: @@ -587,16 +598,14 @@ def __init__( def apply(self) -> FrameOrSeriesUnion: obj = self.obj - func = self.f - args = self.args - kwds = self.kwds if len(obj) == 0: return self.apply_empty_result() # dispatch to agg - if isinstance(func, (list, dict)): - return obj.aggregate(func, *args, **kwds) + result = self.maybe_apply_multiple() + if result is not None: + return result # if we are a string, try to dispatch result = self.maybe_apply_str() diff --git a/pandas/tests/series/apply/test_series_apply.py b/pandas/tests/series/apply/test_series_apply.py index b8c6291415ef7..a5c40af5c7f35 100644 --- a/pandas/tests/series/apply/test_series_apply.py +++ b/pandas/tests/series/apply/test_series_apply.py @@ -7,7 +7,7 @@ from pandas.core.dtypes.common import is_number import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, isna, timedelta_range +from pandas import DataFrame, Index, MultiIndex, Series, concat, isna, timedelta_range import pandas._testing as tm from pandas.core.base import SpecificationError @@ -827,3 +827,75 @@ def test_apply_to_timedelta(self): b = Series(list_of_strings).apply(pd.to_timedelta) # noqa # Can't compare until apply on a Series gives the correct dtype # assert_series_equal(a, b) + + +@pytest.mark.parametrize( + "ops, names", + [ + ([np.sum], ["sum"]), + ([np.sum, np.mean], ["sum", "mean"]), + (np.array([np.sum]), ["sum"]), + (np.array([np.sum, np.mean]), ["sum", "mean"]), + ], +) +@pytest.mark.parametrize("how", ["agg", "apply"]) +def test_apply_listlike_reducer(string_series, ops, names, how): + # GH 39140 + expected = Series({name: op(string_series) for name, op in zip(names, ops)}) + expected.name = "series" + result = getattr(string_series, how)(ops) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "ops", + [ + {"A": np.sum}, + {"A": np.sum, "B": np.mean}, + Series({"A": np.sum}), + Series({"A": np.sum, "B": np.mean}), + ], +) +@pytest.mark.parametrize("how", ["agg", "apply"]) +def test_apply_dictlike_reducer(string_series, ops, how): + # GH 39140 + expected = Series({name: op(string_series) for name, op in ops.items()}) + expected.name = string_series.name + result = getattr(string_series, how)(ops) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "ops, names", + [ + ([np.sqrt], ["sqrt"]), + ([np.abs, np.sqrt], ["absolute", "sqrt"]), + (np.array([np.sqrt]), ["sqrt"]), + (np.array([np.abs, np.sqrt]), ["absolute", "sqrt"]), + ], +) +def test_apply_listlike_transformer(string_series, ops, names): + # GH 39140 + with np.errstate(all="ignore"): + expected = concat([op(string_series) for op in ops], axis=1) + expected.columns = names + result = string_series.apply(ops) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "ops", + [ + {"A": np.sqrt}, + {"A": np.sqrt, "B": np.exp}, + Series({"A": np.sqrt}), + Series({"A": np.sqrt, "B": np.exp}), + ], +) +def test_apply_dictlike_transformer(string_series, ops): + # GH 39140 + with np.errstate(all="ignore"): + expected = concat({name: op(string_series) for name, op in ops.items()}) + expected.name = string_series.name + result = string_series.apply(ops) + tm.assert_series_equal(result, expected)
- [x] closes #39140 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry I only added the Series.apply list/dict-like addition to the whatsnew. For both Series and DataFrame .agg, this PR also enables passing a Series as a dict-like, but other dict-likes already work. It didn't seem notable to add this to the whatsnew.
https://api.github.com/repos/pandas-dev/pandas/pulls/39141
2021-01-13T04:30:13Z
2021-01-14T20:48:36Z
2021-01-14T20:48:36Z
2021-01-15T01:27:53Z
BUG: Placeholders not being filled on docstrings
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2d6a3513bf991..6a80fa3e93362 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -10587,8 +10587,10 @@ def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): # [assignment] cls.all = all # type: ignore[assignment] + # error: Argument 1 to "doc" has incompatible type "Optional[str]"; expected + # "Union[str, Callable[..., Any]]" @doc( - NDFrame.mad, + NDFrame.mad.__doc__, # type: ignore[arg-type] desc="Return the mean absolute deviation of the values " "over the requested axis.", name1=name1,
- [x] closes #39115 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/39139
2021-01-13T02:29:00Z
2021-01-17T15:59:40Z
2021-01-17T15:59:39Z
2021-01-17T16:00:43Z
ASV: Add xlrd engine for xls file
diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py index 96f02d37db1e1..7efaeddecd423 100644 --- a/asv_bench/benchmarks/io/excel.py +++ b/asv_bench/benchmarks/io/excel.py @@ -40,9 +40,10 @@ def time_write_excel(self, engine): class ReadExcel: - params = ["openpyxl", "odf"] + params = ["xlrd", "openpyxl", "odf"] param_names = ["engine"] fname_excel = "spreadsheet.xlsx" + fname_excel_xls = "spreadsheet.xls" fname_odf = "spreadsheet.ods" def _create_odf(self): @@ -63,10 +64,16 @@ def setup_cache(self): self.df = _generate_dataframe() self.df.to_excel(self.fname_excel, sheet_name="Sheet1") + self.df.to_excel(self.fname_excel_xls, sheet_name="Sheet1") self._create_odf() def time_read_excel(self, engine): - fname = self.fname_odf if engine == "odf" else self.fname_excel + if engine == "xlrd": + fname = self.fname_excel_xls + elif engine == "odf": + fname = self.fname_odf + else: + fname = self.fname_excel read_excel(fname, engine=engine)
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them Is one parametrized function more efficient than multiple functions during setup and teardown? If not I would make a separate function for the xls benchmark cc @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/39137
2021-01-12T22:44:37Z
2021-01-13T13:41:20Z
2021-01-13T13:41:20Z
2021-01-13T16:55:12Z
BUG: setting categorical values into object dtype DataFrame
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 0cb46a5164674..25bd3b43be3ed 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -186,6 +186,8 @@ Categorical - Bug in ``CategoricalIndex.reindex`` failed when ``Index`` passed with elements all in category (:issue:`28690`) - Bug where constructing a :class:`Categorical` from an object-dtype array of ``date`` objects did not round-trip correctly with ``astype`` (:issue:`38552`) - Bug in constructing a :class:`DataFrame` from an ``ndarray`` and a :class:`CategoricalDtype` (:issue:`38857`) +- Bug in :meth:`DataFrame.reindex` was throwing ``IndexError`` when new index contained duplicates and old index was :class:`CategoricalIndex` (:issue:`38906`) +- Bug in setting categorical values into an object-dtype column in a :class:`DataFrame` (:issue:`39136`) - Bug in :meth:`DataFrame.reindex` was raising ``IndexError`` when new index contained duplicates and old index was :class:`CategoricalIndex` (:issue:`38906`) Datetimelike diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 0216334a4c0aa..6f6f17171537f 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -959,7 +959,13 @@ def setitem(self, indexer, value): # GH25495 - If the current dtype is not categorical, # we need to create a new categorical block values[indexer] = value - return self.make_block(Categorical(self.values, dtype=arr_value.dtype)) + if values.ndim == 2: + # TODO(EA2D): special case not needed with 2D EAs + if values.shape[-1] != 1: + # shouldn't get here (at least until 2D EAs) + raise NotImplementedError + values = values[:, 0] + return self.make_block(Categorical(values, dtype=arr_value.dtype)) elif exact_match and is_ea_value: # GH#32395 if we're going to replace the values entirely, just diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 7dcb30efb8184..1668123e782ff 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -65,6 +65,50 @@ def test_iloc_getitem_list_int(self): class TestiLocBaseIndependent: """Tests Independent Of Base Class""" + @pytest.mark.parametrize( + "key", + [ + slice(None), + slice(3), + range(3), + [0, 1, 2], + Index(range(3)), + np.asarray([0, 1, 2]), + ], + ) + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_iloc_setitem_fullcol_categorical(self, indexer, key): + frame = DataFrame({0: range(3)}, dtype=object) + + cat = Categorical(["alpha", "beta", "gamma"]) + expected = DataFrame({0: cat}) + # NB: pending GH#38896, the expected likely should become + # expected= DataFrame({"A": cat.astype(object)}) + # and should remain a view on the original values + + assert frame._mgr.blocks[0]._can_hold_element(cat) + + df = frame.copy() + orig_vals = df.values + indexer(df)[key, 0] = cat + + overwrite = not isinstance(key, slice) + + tm.assert_frame_equal(df, expected) + + # TODO: this inconsistency is likely undesired GH#39986 + if overwrite: + # check that we overwrote underlying + tm.assert_numpy_array_equal(orig_vals, df.values) + + # but we don't have a view on orig_vals + orig_vals[0, 0] = 19 + assert df.iloc[0, 0] != 19 + + # check we dont have a view on cat (may be undesired GH#39986) + df.iloc[0, 0] = "gamma" + assert cat[0] != "gamma" + @pytest.mark.parametrize("box", [pd_array, Series]) def test_iloc_setitem_ea_inplace(self, frame_or_series, box): # GH#38952 Case with not setting a full column
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry ``` df = pd.DataFrame({"A": range(3)}, dtype=object) cat = pd.Categorical(["alpha", "beta", "gamma"]) df.iloc[range(3), 0] = cat >>> df A 0 NaN 1 2 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/39136
2021-01-12T22:24:38Z
2021-01-14T20:48:17Z
2021-01-14T20:48:17Z
2021-01-14T21:54:22Z
BUG: Close resources opened by pyxlsb
diff --git a/pandas/io/common.py b/pandas/io/common.py index 12a886d057199..1fee840c5ed4a 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -292,13 +292,12 @@ def _get_filepath_or_buffer( # assuming storage_options is to be interpretted as headers req_info = urllib.request.Request(filepath_or_buffer, headers=storage_options) - req = urlopen(req_info) - content_encoding = req.headers.get("Content-Encoding", None) - if content_encoding == "gzip": - # Override compression based on Content-Encoding header - compression = {"method": "gzip"} - reader = BytesIO(req.read()) - req.close() + with urlopen(req_info) as req: + content_encoding = req.headers.get("Content-Encoding", None) + if content_encoding == "gzip": + # Override compression based on Content-Encoding header + compression = {"method": "gzip"} + reader = BytesIO(req.read()) return IOArgs( filepath_or_buffer=reader, encoding=encoding, diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 11797823cddc2..962ba2c7f9ef7 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -410,6 +410,9 @@ def load_workbook(self, filepath_or_buffer): pass def close(self): + if hasattr(self.book, "close"): + # pyxlsb opens a TemporaryFile + self.book.close() self.handles.close() @property @@ -483,6 +486,9 @@ def parse( sheet = self.get_sheet_by_index(asheetname) data = self.get_sheet_data(sheet, convert_float) + if hasattr(sheet, "close"): + # pyxlsb opens two TemporaryFiles + sheet.close() usecols = maybe_convert_usecols(usecols) if not data: diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 34b36e2549b62..e37acb2ee6bea 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -465,6 +465,12 @@ def __init__(self, path): else: self.headers = {"Content-Encoding": None} + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + def read(self): return self.file.read()
Spin-off from #39047: - Close resources opened by pyxlsb - Use context manager when opening non-fsspec URLs (I'm not sure whether that reduced any `ResourceWarning`s but it can't hurt)
https://api.github.com/repos/pandas-dev/pandas/pulls/39134
2021-01-12T22:01:14Z
2021-01-13T13:22:03Z
2021-01-13T13:22:03Z
2021-01-13T15:20:28Z
PERF: cythonize kendall correlation
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 05b4417f427ab..65b821fe2b8a8 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -205,7 +205,7 @@ Performance improvements - Performance improvement in :meth:`IntervalIndex.isin` (:issue:`38353`) - Performance improvement in :meth:`Series.mean` for nullable data types (:issue:`34814`) - Performance improvement in :meth:`Series.isin` for nullable data types (:issue:`38340`) -- +- Performance improvement in :meth:`DataFrame.corr` for method=kendall (:issue:`28329`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index 76bfb001cea81..080a84bef1e58 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -393,6 +393,100 @@ def nancorr_spearman(ndarray[float64_t, ndim=2] mat, Py_ssize_t minp=1) -> ndarr return result +# ---------------------------------------------------------------------- +# Kendall correlation +# Wikipedia article: https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient + +@cython.boundscheck(False) +@cython.wraparound(False) +def nancorr_kendall(ndarray[float64_t, ndim=2] mat, Py_ssize_t minp=1) -> ndarray: + """ + Perform kendall correlation on a 2d array + + Parameters + ---------- + mat : np.ndarray[float64_t, ndim=2] + Array to compute kendall correlation on + minp : int, default 1 + Minimum number of observations required per pair of columns + to have a valid result. + + Returns + ------- + numpy.ndarray[float64_t, ndim=2] + Correlation matrix + """ + cdef: + Py_ssize_t i, j, k, xi, yi, N, K + ndarray[float64_t, ndim=2] result + ndarray[float64_t, ndim=2] ranked_mat + ndarray[uint8_t, ndim=2] mask + float64_t currj + ndarray[uint8_t, ndim=1] valid + ndarray[int64_t] sorted_idxs + ndarray[float64_t, ndim=1] col + int64_t n_concordant + int64_t total_concordant = 0 + int64_t total_discordant = 0 + float64_t kendall_tau + int64_t n_obs + const int64_t[:] labels_n + + N, K = (<object>mat).shape + + result = np.empty((K, K), dtype=np.float64) + mask = np.isfinite(mat) + + ranked_mat = np.empty((N, K), dtype=np.float64) + # For compatibility when calling rank_1d + labels_n = np.zeros(N, dtype=np.int64) + + for i in range(K): + ranked_mat[:, i] = rank_1d(mat[:, i], labels_n) + + for xi in range(K): + sorted_idxs = ranked_mat[:, xi].argsort() + ranked_mat = ranked_mat[sorted_idxs] + mask = mask[sorted_idxs] + for yi in range(xi + 1, K): + valid = mask[:, xi] & mask[:, yi] + if valid.sum() < minp: + result[xi, yi] = NaN + result[yi, xi] = NaN + else: + # Get columns and order second column using 1st column ranks + if not valid.all(): + col = ranked_mat[valid.nonzero()][:, yi] + else: + col = ranked_mat[:, yi] + n_obs = col.shape[0] + total_concordant = 0 + total_discordant = 0 + for j in range(n_obs - 1): + currj = col[j] + # Count num concordant and discordant pairs + n_concordant = 0 + for k in range(j, n_obs): + if col[k] > currj: + n_concordant += 1 + total_concordant += n_concordant + total_discordant += (n_obs - 1 - j - n_concordant) + # Note: we do total_concordant+total_discordant here which is + # equivalent to the C(n, 2), the total # of pairs, + # listed on wikipedia + kendall_tau = (total_concordant - total_discordant) / \ + (total_concordant + total_discordant) + result[xi, yi] = kendall_tau + result[yi, xi] = kendall_tau + + if mask[:, xi].sum() > minp: + result[xi, xi] = 1 + else: + result[xi, xi] = NaN + + return result + + # ---------------------------------------------------------------------- ctypedef fused algos_t: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0a1ea4041a10b..288292589e940 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8463,8 +8463,7 @@ def corr(self, method="pearson", min_periods=1) -> DataFrame: min_periods : int, optional Minimum number of observations required per pair of columns - to have a valid result. Currently only available for Pearson - and Spearman correlation. + to have a valid result. Returns ------- @@ -8498,7 +8497,9 @@ def corr(self, method="pearson", min_periods=1) -> DataFrame: correl = libalgos.nancorr(mat, minp=min_periods) elif method == "spearman": correl = libalgos.nancorr_spearman(mat, minp=min_periods) - elif method == "kendall" or callable(method): + elif method == "kendall": + correl = libalgos.nancorr_kendall(mat, minp=min_periods) + elif callable(method): if min_periods is None: min_periods = 1 mat = mat.T
- [x] closes #28329 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry ASV's. before after ratio [a6bc6ecc] [1eb86441] <perf-cythonize-kendall~2^2> <perf-cythonize-kendall> - 81M 57.6M 0.71 stat_ops.Correlation.peakmem_corr_wide('kendall') - 1.41±0.02s 362±7ms 0.26 stat_ops.Correlation.time_corr_wide_nans('kendall') - 1.57±0.04s 398±4ms 0.25 stat_ops.Correlation.time_corr_wide('kendall') - 34.6±4ms 8.75±0.06ms 0.25 stat_ops.Correlation.time_corr('kendall') SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. PERFORMANCE INCREASED.
https://api.github.com/repos/pandas-dev/pandas/pulls/39132
2021-01-12T20:39:16Z
2021-01-20T21:08:10Z
2021-01-20T21:08:09Z
2021-01-23T20:26:53Z
CLN: remove redundant consolidation
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index a1b06f3c9d6a1..ac0955c6c3e4c 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1865,7 +1865,6 @@ def _setitem_single_block(self, indexer, value, name: str): self.obj._check_is_chained_assignment_possible() # actually do the set - self.obj._consolidate_inplace() self.obj._mgr = self.obj._mgr.setitem(indexer=indexer, value=value) self.obj._maybe_update_cacher(clear=True)
We only get here with nblocks == 1
https://api.github.com/repos/pandas-dev/pandas/pulls/39127
2021-01-12T15:58:47Z
2021-01-13T13:21:12Z
2021-01-13T13:21:11Z
2021-01-13T15:35:15Z
DOC: fixed a minor mistake worksheet -> workbook
diff --git a/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst b/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst index c92d2a660d753..13029173b2e65 100644 --- a/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst +++ b/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst @@ -35,7 +35,7 @@ General terminology translation ``DataFrame`` ~~~~~~~~~~~~~ -A ``DataFrame`` in pandas is analogous to an Excel worksheet. While an Excel worksheet can contain +A ``DataFrame`` in pandas is analogous to an Excel worksheet. While an Excel workbook can contain multiple worksheets, pandas ``DataFrame``\s exist independently. ``Series``
A small typo related to #38990 A worksheet can't have multiple worksheets, but a workbook can. Minor fix but may confuse the newcomers - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39124
2021-01-12T10:12:41Z
2021-01-12T13:51:58Z
2021-01-12T13:51:58Z
2021-01-12T13:52:02Z
REF: eliminate inner functions in describe
diff --git a/pandas/core/describe.py b/pandas/core/describe.py index 1b5fbaf0e78f9..4a67725449ca8 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -83,98 +83,15 @@ def describe_ndframe( raise ValueError("percentiles cannot contain duplicates") percentiles = unique_pcts - formatted_percentiles = format_percentiles(percentiles) - - def describe_numeric_1d(series) -> "Series": - from pandas import Series - - stat_index = ["count", "mean", "std", "min"] + formatted_percentiles + ["max"] - d = ( - [series.count(), series.mean(), series.std(), series.min()] - + series.quantile(percentiles).tolist() - + [series.max()] - ) - return Series(d, index=stat_index, name=series.name) - - def describe_categorical_1d(data) -> "Series": - names = ["count", "unique"] - objcounts = data.value_counts() - count_unique = len(objcounts[objcounts != 0]) - result = [data.count(), count_unique] - dtype = None - if result[1] > 0: - top, freq = objcounts.index[0], objcounts.iloc[0] - if is_datetime64_any_dtype(data.dtype): - if obj.ndim == 1: - stacklevel = 5 - else: - stacklevel = 6 - warnings.warn( - "Treating datetime data as categorical rather than numeric in " - "`.describe` is deprecated and will be removed in a future " - "version of pandas. Specify `datetime_is_numeric=True` to " - "silence this warning and adopt the future behavior now.", - FutureWarning, - stacklevel=stacklevel, - ) - tz = data.dt.tz - asint = data.dropna().values.view("i8") - top = Timestamp(top) - if top.tzinfo is not None and tz is not None: - # Don't tz_localize(None) if key is already tz-aware - top = top.tz_convert(tz) - else: - top = top.tz_localize(tz) - names += ["top", "freq", "first", "last"] - result += [ - top, - freq, - Timestamp(asint.min(), tz=tz), - Timestamp(asint.max(), tz=tz), - ] - else: - names += ["top", "freq"] - result += [top, freq] - - # If the DataFrame is empty, set 'top' and 'freq' to None - # to maintain output shape consistency - else: - names += ["top", "freq"] - result += [np.nan, np.nan] - dtype = "object" - - from pandas import Series - - return Series(result, index=names, name=data.name, dtype=dtype) - - def describe_timestamp_1d(data) -> "Series": - # GH-30164 - from pandas import Series - - stat_index = ["count", "mean", "min"] + formatted_percentiles + ["max"] - d = ( - [data.count(), data.mean(), data.min()] - + data.quantile(percentiles).tolist() - + [data.max()] - ) - return Series(d, index=stat_index, name=data.name) - - def describe_1d(data) -> "Series": - if is_bool_dtype(data.dtype): - return describe_categorical_1d(data) - elif is_numeric_dtype(data): - return describe_numeric_1d(data) - elif is_datetime64_any_dtype(data.dtype) and datetime_is_numeric: - return describe_timestamp_1d(data) - elif is_timedelta64_dtype(data.dtype): - return describe_numeric_1d(data) - else: - return describe_categorical_1d(data) - if obj.ndim == 1: # Incompatible return value type # (got "Series", expected "FrameOrSeries") [return-value] - return describe_1d(obj) # type:ignore[return-value] + return describe_1d( + obj, + percentiles, + datetime_is_numeric, + is_series=True, + ) # type:ignore[return-value] elif (include is None) and (exclude is None): # when some numerics are found, keep only numerics default_include = [np.number] @@ -191,7 +108,10 @@ def describe_1d(data) -> "Series": else: data = obj.select_dtypes(include=include, exclude=exclude) - ldesc = [describe_1d(s) for _, s in data.items()] + ldesc = [ + describe_1d(s, percentiles, datetime_is_numeric, is_series=False) + for _, s in data.items() + ] # set a convenient order for rows names: List[Hashable] = [] ldesc_indexes = sorted((x.index for x in ldesc), key=len) @@ -203,3 +123,143 @@ def describe_1d(data) -> "Series": d = concat([x.reindex(names, copy=False) for x in ldesc], axis=1, sort=False) d.columns = data.columns.copy() return d + + +def describe_numeric_1d(series, percentiles) -> "Series": + """Describe series containing numerical data. + + Parameters + ---------- + series : Series + Series to be described. + percentiles : list-like of numbers, optional + The percentiles to include in the output. + """ + from pandas import Series + + formatted_percentiles = format_percentiles(percentiles) + + stat_index = ["count", "mean", "std", "min"] + formatted_percentiles + ["max"] + d = ( + [series.count(), series.mean(), series.std(), series.min()] + + series.quantile(percentiles).tolist() + + [series.max()] + ) + return Series(d, index=stat_index, name=series.name) + + +def describe_categorical_1d(data, is_series) -> "Series": + """Describe series containing categorical data. + + Parameters + ---------- + data : Series + Series to be described. + is_series : bool + True if the original object is a Series. + False if the one column of the DataFrame is described. + """ + names = ["count", "unique"] + objcounts = data.value_counts() + count_unique = len(objcounts[objcounts != 0]) + result = [data.count(), count_unique] + dtype = None + if result[1] > 0: + top, freq = objcounts.index[0], objcounts.iloc[0] + if is_datetime64_any_dtype(data.dtype): + if is_series: + stacklevel = 5 + else: + stacklevel = 6 + warnings.warn( + "Treating datetime data as categorical rather than numeric in " + "`.describe` is deprecated and will be removed in a future " + "version of pandas. Specify `datetime_is_numeric=True` to " + "silence this warning and adopt the future behavior now.", + FutureWarning, + stacklevel=stacklevel, + ) + tz = data.dt.tz + asint = data.dropna().values.view("i8") + top = Timestamp(top) + if top.tzinfo is not None and tz is not None: + # Don't tz_localize(None) if key is already tz-aware + top = top.tz_convert(tz) + else: + top = top.tz_localize(tz) + names += ["top", "freq", "first", "last"] + result += [ + top, + freq, + Timestamp(asint.min(), tz=tz), + Timestamp(asint.max(), tz=tz), + ] + else: + names += ["top", "freq"] + result += [top, freq] + + # If the DataFrame is empty, set 'top' and 'freq' to None + # to maintain output shape consistency + else: + names += ["top", "freq"] + result += [np.nan, np.nan] + dtype = "object" + + from pandas import Series + + return Series(result, index=names, name=data.name, dtype=dtype) + + +def describe_timestamp_1d(data, percentiles) -> "Series": + """Describe series containing datetime64 dtype. + + Parameters + ---------- + data : Series + Series to be described. + percentiles : list-like of numbers, optional + The percentiles to include in the output. + """ + # GH-30164 + from pandas import Series + + formatted_percentiles = format_percentiles(percentiles) + + stat_index = ["count", "mean", "min"] + formatted_percentiles + ["max"] + d = ( + [data.count(), data.mean(), data.min()] + + data.quantile(percentiles).tolist() + + [data.max()] + ) + return Series(d, index=stat_index, name=data.name) + + +def describe_1d(data, percentiles, datetime_is_numeric, *, is_series) -> "Series": + """Describe series. + + Parameters + ---------- + data : Series + Series to be described. + percentiles : list-like of numbers, optional + The percentiles to include in the output. + datetime_is_numeric : bool, default False + Whether to treat datetime dtypes as numeric. + is_series : bool + True if the original object is a Series. + False if the one column of the DataFrame is described. + + Returns + ------- + Series + """ + if is_bool_dtype(data.dtype): + return describe_categorical_1d(data, is_series) + elif is_numeric_dtype(data): + return describe_numeric_1d(data, percentiles) + elif is_datetime64_any_dtype(data.dtype) and datetime_is_numeric: + return describe_timestamp_1d(data, percentiles) + elif is_timedelta64_dtype(data.dtype): + return describe_numeric_1d(data, percentiles) + else: + return describe_categorical_1d(data, is_series)
- [ ] xref #36833 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Remove inner functions in ``describe_ndframe``, while passing the required arguments.
https://api.github.com/repos/pandas-dev/pandas/pulls/39121
2021-01-12T06:50:56Z
2021-01-13T13:52:36Z
2021-01-13T13:52:35Z
2021-01-14T07:07:42Z
BUG: Series.__setitem__ with mismatched IntervalDtype
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 38178e41afe95..bd13fdd26195b 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -249,6 +249,7 @@ Indexing - Bug in :meth:`DataFrame.iloc.__setitem__` and :meth:`DataFrame.loc.__setitem__` with mixed dtypes when setting with a dictionary value (:issue:`38335`) - Bug in :meth:`DataFrame.loc` dropping levels of :class:`MultiIndex` when :class:`DataFrame` used as input has only one row (:issue:`10521`) - Bug in setting ``timedelta64`` values into numeric :class:`Series` failing to cast to object dtype (:issue:`39086`) +- Bug in setting :class:`Interval` values into a :class:`Series` or :class:`DataFrame` with mismatched :class:`IntervalDtype` incorrectly casting the new values to the existing dtype (:issue:`39120`) Missing ^^^^^^^ diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index b31bc0934fe60..ef93e80d83d04 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -613,6 +613,18 @@ def _validate_listlike(self, value, allow_object: bool = False): # We treat empty list as our own dtype. return type(self)._from_sequence([], dtype=self.dtype) + if hasattr(value, "dtype") and value.dtype == object: + # `array` below won't do inference if value is an Index or Series. + # so do so here. in the Index case, inferred_type may be cached. + if lib.infer_dtype(value) in self._infer_matches: + try: + value = type(self)._from_sequence(value) + except (ValueError, TypeError): + if allow_object: + return value + msg = self._validation_error_message(value, True) + raise TypeError(msg) + # Do type inference if necessary up front # e.g. we passed PeriodIndex.values and got an ndarray of Periods value = array(value) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 56550a8665816..ee3a521d68392 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -955,12 +955,22 @@ def _validate_listlike(self, value): # list-like of intervals try: array = IntervalArray(value) - # TODO: self._check_closed_matches(array, name="value") + self._check_closed_matches(array, name="value") value_left, value_right = array.left, array.right except TypeError as err: # wrong type: not interval or NA msg = f"'value' should be an interval type, got {type(value)} instead." raise TypeError(msg) from err + + try: + self.left._validate_fill_value(value_left) + except (ValueError, TypeError) as err: + msg = ( + "'value' should be a compatible interval type, " + f"got {type(value)} instead." + ) + raise TypeError(msg) from err + return value_left, value_right def _validate_scalar(self, value): @@ -995,10 +1005,12 @@ def _validate_setitem_value(self, value): value = np.timedelta64("NaT") value_left, value_right = value, value - elif is_interval_dtype(value) or isinstance(value, Interval): + elif isinstance(value, Interval): # scalar interval self._check_closed_matches(value, name="value") value_left, value_right = value.left, value.right + self.left._validate_fill_value(value_left) + self.left._validate_fill_value(value_right) else: return self._validate_listlike(value) diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index e5da085249acf..26599bd6ab871 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -152,6 +152,10 @@ def _validate_fill_value(self, value): raise TypeError value = int(value) + elif hasattr(value, "dtype") and value.dtype.kind in ["m", "M"]: + # TODO: if we're checking arraylike here, do so systematically + raise TypeError + return value def _convert_tolerance(self, tolerance, target): diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 6f6f17171537f..2f3a06afa2a68 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1,6 +1,6 @@ import inspect import re -from typing import TYPE_CHECKING, Any, List, Optional, Type, Union, cast +from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, Union, cast import numpy as np @@ -28,7 +28,6 @@ infer_dtype_from_scalar, maybe_downcast_numeric, maybe_downcast_to_dtype, - maybe_infer_dtype_type, maybe_promote, maybe_upcast, soft_convert_objects, @@ -51,7 +50,7 @@ ) from pandas.core.dtypes.dtypes import CategoricalDtype, ExtensionDtype from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCPandasArray, ABCSeries -from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna +from pandas.core.dtypes.missing import isna import pandas.core.algorithms as algos from pandas.core.array_algos.putmask import ( @@ -1879,7 +1878,24 @@ def _unstack(self, unstacker, fill_value, new_placement): return blocks, mask -class ObjectValuesExtensionBlock(ExtensionBlock): +class HybridMixin: + """ + Mixin for Blocks backed (maybe indirectly) by ExtensionArrays. + """ + + array_values: Callable + + def _can_hold_element(self, element: Any) -> bool: + values = self.array_values() + + try: + values._validate_setitem_value(element) + return True + except (ValueError, TypeError): + return False + + +class ObjectValuesExtensionBlock(HybridMixin, ExtensionBlock): """ Block providing backwards-compatibility for `.values`. @@ -1890,16 +1906,6 @@ class ObjectValuesExtensionBlock(ExtensionBlock): def external_values(self): return self.values.astype(object) - def _can_hold_element(self, element: Any) -> bool: - if is_valid_nat_for_dtype(element, self.dtype): - return True - if isinstance(element, list) and len(element) == 0: - return True - tipo = maybe_infer_dtype_type(element) - if tipo is not None: - return issubclass(tipo.type, self.dtype.type) - return isinstance(element, self.dtype.type) - class NumericBlock(Block): __slots__ = () @@ -1959,7 +1965,7 @@ class IntBlock(NumericBlock): _can_hold_na = False -class DatetimeLikeBlockMixin(Block): +class DatetimeLikeBlockMixin(HybridMixin, Block): """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock.""" _can_hold_na = True @@ -2042,15 +2048,6 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List["Block"]: nb = self.make_block_same_class(res_values) return [nb] - def _can_hold_element(self, element: Any) -> bool: - arr = self.array_values() - - try: - arr._validate_setitem_value(element) - return True - except (TypeError, ValueError): - return False - class DatetimeBlock(DatetimeLikeBlockMixin): __slots__ = () diff --git a/pandas/tests/arrays/interval/test_interval.py b/pandas/tests/arrays/interval/test_interval.py index f999f79bc389b..425a0ca070c3c 100644 --- a/pandas/tests/arrays/interval/test_interval.py +++ b/pandas/tests/arrays/interval/test_interval.py @@ -123,6 +123,31 @@ def test_set_na(self, left_right_dtypes): tm.assert_extension_array_equal(result, expected) + def test_setitem_mismatched_closed(self): + arr = IntervalArray.from_breaks(range(4)) + orig = arr.copy() + other = arr.set_closed("both") + + msg = "'value.closed' is 'both', expected 'right'" + with pytest.raises(ValueError, match=msg): + arr[0] = other[0] + with pytest.raises(ValueError, match=msg): + arr[:1] = other[:1] + with pytest.raises(ValueError, match=msg): + arr[:0] = other[:0] + with pytest.raises(ValueError, match=msg): + arr[:] = other[::-1] + with pytest.raises(ValueError, match=msg): + arr[:] = list(other[::-1]) + with pytest.raises(ValueError, match=msg): + arr[:] = other[::-1].astype(object) + with pytest.raises(ValueError, match=msg): + arr[:] = other[::-1].astype("category") + + # empty list should be no-op + arr[:0] = [] + tm.assert_interval_array_equal(arr, orig) + def test_repr(): # GH 25022 diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 81bcff410a4d3..36a52e5802396 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -8,11 +8,9 @@ from pandas.compat.numpy import np_version_under1p18 import pandas as pd +from pandas import DatetimeIndex, Index, Period, PeriodIndex, TimedeltaIndex import pandas._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 -from pandas.core.indexes.timedeltas import TimedeltaIndex +from pandas.core.arrays import DatetimeArray, PandasArray, PeriodArray, TimedeltaArray # TODO: more freq variants @@ -402,6 +400,37 @@ def test_setitem(self): expected[:2] = expected[-2:] tm.assert_numpy_array_equal(arr.asi8, expected) + @pytest.mark.parametrize( + "box", + [ + Index, + pd.Series, + np.array, + list, + PandasArray, + ], + ) + def test_setitem_object_dtype(self, box, arr1d): + + expected = arr1d.copy()[::-1] + if expected.dtype.kind in ["m", "M"]: + expected = expected._with_freq(None) + + vals = expected + if box is list: + vals = list(vals) + elif box is np.array: + # if we do np.array(x).astype(object) then dt64 and td64 cast to ints + vals = np.array(vals.astype(object)) + elif box is PandasArray: + vals = box(np.asarray(vals, dtype=object)) + else: + vals = box(vals).astype(object) + + arr1d[:] = vals + + tm.assert_equal(arr1d, expected) + def test_setitem_strs(self, arr1d, request): # Check that we parse strs in both scalar and listlike if isinstance(arr1d, DatetimeArray): diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 3c949ad694abd..f9ba05f7092d4 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -7,8 +7,20 @@ from pandas._libs.internals import BlockPlacement +from pandas.core.dtypes.common import is_scalar + import pandas as pd -from pandas import Categorical, DataFrame, DatetimeIndex, Index, Series +from pandas import ( + Categorical, + DataFrame, + DatetimeIndex, + Index, + IntervalIndex, + Series, + Timedelta, + Timestamp, + period_range, +) import pandas._testing as tm import pandas.core.algorithms as algos from pandas.core.arrays import DatetimeArray, SparseArray, TimedeltaArray @@ -1074,9 +1086,30 @@ def test_blockplacement_add_int_raises(self, val): class TestCanHoldElement: + @pytest.fixture( + params=[ + lambda x: x, + lambda x: x.to_series(), + lambda x: x._data, + lambda x: list(x), + lambda x: x.astype(object), + lambda x: np.asarray(x), + lambda x: x[0], + lambda x: x[:0], + ] + ) + def element(self, request): + """ + Functions that take an Index and return an element that should have + blk._can_hold_element(element) for a Block with this index's dtype. + """ + return request.param + def test_datetime_block_can_hold_element(self): block = create_block("datetime", [0]) + assert block._can_hold_element([]) + # We will check that block._can_hold_element iff arr.__setitem__ works arr = pd.array(block.values.ravel()) @@ -1101,6 +1134,111 @@ def test_datetime_block_can_hold_element(self): with pytest.raises(TypeError, match=msg): arr[0] = val + @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64]) + def test_interval_can_hold_element_emptylist(self, dtype, element): + arr = np.array([1, 3, 4], dtype=dtype) + ii = IntervalIndex.from_breaks(arr) + blk = make_block(ii._data, [1], ndim=2) + + assert blk._can_hold_element([]) + # TODO: check this holds for all blocks + + @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64]) + def test_interval_can_hold_element(self, dtype, element): + arr = np.array([1, 3, 4, 9], dtype=dtype) + ii = IntervalIndex.from_breaks(arr) + blk = make_block(ii._data, [1], ndim=2) + + elem = element(ii) + self.check_series_setitem(elem, ii, True) + assert blk._can_hold_element(elem) + + # Careful: to get the expected Series-inplace behavior we need + # `elem` to not have the same length as `arr` + ii2 = IntervalIndex.from_breaks(arr[:-1], closed="neither") + elem = element(ii2) + self.check_series_setitem(elem, ii, False) + assert not blk._can_hold_element(elem) + + ii3 = IntervalIndex.from_breaks([Timestamp(1), Timestamp(3), Timestamp(4)]) + elem = element(ii3) + self.check_series_setitem(elem, ii, False) + assert not blk._can_hold_element(elem) + + ii4 = IntervalIndex.from_breaks([Timedelta(1), Timedelta(3), Timedelta(4)]) + elem = element(ii4) + self.check_series_setitem(elem, ii, False) + assert not blk._can_hold_element(elem) + + def test_period_can_hold_element_emptylist(self): + pi = period_range("2016", periods=3, freq="A") + blk = make_block(pi._data, [1], ndim=2) + + assert blk._can_hold_element([]) + + def test_period_can_hold_element(self, element): + pi = period_range("2016", periods=3, freq="A") + + elem = element(pi) + self.check_series_setitem(elem, pi, True) + + # Careful: to get the expected Series-inplace behavior we need + # `elem` to not have the same length as `arr` + pi2 = pi.asfreq("D")[:-1] + elem = element(pi2) + self.check_series_setitem(elem, pi, False) + + dti = pi.to_timestamp("S")[:-1] + elem = element(dti) + self.check_series_setitem(elem, pi, False) + + def check_setting(self, elem, index: Index, inplace: bool): + self.check_series_setitem(elem, index, inplace) + self.check_frame_setitem(elem, index, inplace) + + def check_can_hold_element(self, obj, elem, inplace: bool): + blk = obj._mgr.blocks[0] + if inplace: + assert blk._can_hold_element(elem) + else: + assert not blk._can_hold_element(elem) + + def check_series_setitem(self, elem, index: Index, inplace: bool): + arr = index._data.copy() + ser = Series(arr) + + self.check_can_hold_element(ser, elem, inplace) + + if is_scalar(elem): + ser[0] = elem + else: + ser[: len(elem)] = elem + + if inplace: + assert ser.array is arr # i.e. setting was done inplace + else: + assert ser.dtype == object + + def check_frame_setitem(self, elem, index: Index, inplace: bool): + arr = index._data.copy() + df = DataFrame(arr) + + self.check_can_hold_element(df, elem, inplace) + + if is_scalar(elem): + df.iloc[0, 0] = elem + else: + df.iloc[: len(elem), 0] = elem + + if inplace: + # assertion here implies setting was done inplace + + # error: Item "ArrayManager" of "Union[ArrayManager, BlockManager]" + # has no attribute "blocks" [union-attr] + assert df._mgr.blocks[0].values is arr # type:ignore[union-attr] + else: + assert df.dtypes[0] == object + class TestShouldStore: def test_should_store_categorical(self):
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39120
2021-01-12T02:00:14Z
2021-01-15T14:12:37Z
2021-01-15T14:12:37Z
2021-01-15T15:18:04Z
ENH: Allow numpy ops and DataFrame properties as str arguments to DataFrame.apply
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index e978bf102dedd..db2e2ba3a2e1e 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -54,6 +54,8 @@ Other enhancements - Add support for dict-like names in :class:`MultiIndex.set_names` and :class:`MultiIndex.rename` (:issue:`20421`) - :func:`pandas.read_excel` can now auto detect .xlsb files (:issue:`35416`) - :meth:`.Rolling.sum`, :meth:`.Expanding.sum`, :meth:`.Rolling.mean`, :meth:`.Expanding.mean`, :meth:`.Rolling.median`, :meth:`.Expanding.median`, :meth:`.Rolling.max`, :meth:`.Expanding.max`, :meth:`.Rolling.min`, and :meth:`.Expanding.min` now support ``Numba`` execution with the ``engine`` keyword (:issue:`38895`) +- :meth:`DataFrame.apply` can now accept NumPy unary operators as strings, e.g. ``df.apply("sqrt")``, which was already the case for :meth:`Series.apply` (:issue:`39116`) +- :meth:`DataFrame.apply` can now accept non-callable DataFrame properties as strings, e.g. ``df.apply("size")``, which was already the case for :meth:`Series.apply` (:issue:`39116`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/apply.py b/pandas/core/apply.py index a618e2a92551d..f3e759610b784 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -151,9 +151,11 @@ def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]: if _axis is None: _axis = getattr(obj, "axis", 0) - if isinstance(arg, str): - return obj._try_aggregate_string_function(arg, *args, **kwargs), None - elif is_dict_like(arg): + result = self.maybe_apply_str() + if result is not None: + return result, None + + if is_dict_like(arg): arg = cast(AggFuncTypeDict, arg) return agg_dict_like(obj, arg, _axis), True elif is_list_like(arg): @@ -171,6 +173,28 @@ def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]: # caller can react return result, True + def maybe_apply_str(self) -> Optional[FrameOrSeriesUnion]: + """ + Compute apply in case of a string. + + Returns + ------- + result: Series, DataFrame, or None + Result when self.f is a string, None otherwise. + """ + f = self.f + if not isinstance(f, str): + return None + # Support for `frame.transform('method')` + # Some methods (shift, etc.) require the axis argument, others + # don't, so inspect and insert if necessary. + func = getattr(self.obj, f, None) + if callable(func): + sig = inspect.getfullargspec(func) + if "axis" in sig.args: + self.kwds["axis"] = self.axis + return self.obj._try_aggregate_string_function(f, *self.args, **self.kwds) + class FrameApply(Apply): obj: DataFrame @@ -236,15 +260,9 @@ def apply(self) -> FrameOrSeriesUnion: return self.apply_empty_result() # string dispatch - if isinstance(self.f, str): - # Support for `frame.transform('method')` - # Some methods (shift, etc.) require the axis argument, others - # don't, so inspect and insert if necessary. - func = getattr(self.obj, self.f) - sig = inspect.getfullargspec(func) - if "axis" in sig.args: - self.kwds["axis"] = self.axis - return func(*self.args, **self.kwds) + result = self.maybe_apply_str() + if result is not None: + return result # ufunc elif isinstance(self.f, np.ufunc): @@ -581,8 +599,9 @@ def apply(self) -> FrameOrSeriesUnion: return obj.aggregate(func, *args, **kwds) # if we are a string, try to dispatch - if isinstance(func, str): - return obj._try_aggregate_string_function(func, *args, **kwds) + result = self.maybe_apply_str() + if result is not None: + return result return self.apply_standard() diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py index 9e5d1dcdea85c..2b72ba3cf2773 100644 --- a/pandas/tests/frame/apply/test_frame_apply.py +++ b/pandas/tests/frame/apply/test_frame_apply.py @@ -166,8 +166,16 @@ def test_apply_standard_nonunique(self): pytest.param([1, None], {"numeric_only": True}, id="args_and_kwds"), ], ) - def test_apply_with_string_funcs(self, float_frame, func, args, kwds): - result = float_frame.apply(func, *args, **kwds) + @pytest.mark.parametrize("how", ["agg", "apply"]) + def test_apply_with_string_funcs(self, request, float_frame, func, args, kwds, how): + if len(args) > 1 and how == "agg": + request.node.add_marker( + pytest.mark.xfail( + reason="agg/apply signature mismatch - agg passes 2nd " + "argument to func" + ) + ) + result = getattr(float_frame, how)(func, *args, **kwds) expected = getattr(float_frame, func)(*args, **kwds) tm.assert_series_equal(result, expected) @@ -1314,30 +1322,32 @@ def test_nuiscance_columns(self): ) tm.assert_frame_equal(result, expected) - def test_non_callable_aggregates(self): + @pytest.mark.parametrize("how", ["agg", "apply"]) + def test_non_callable_aggregates(self, how): # GH 16405 # 'size' is a property of frame/series # validate that this is working + # GH 39116 - expand to apply df = DataFrame( {"A": [None, 2, 3], "B": [1.0, np.nan, 3.0], "C": ["foo", None, "bar"]} ) # Function aggregate - result = df.agg({"A": "count"}) + result = getattr(df, how)({"A": "count"}) expected = Series({"A": 2}) tm.assert_series_equal(result, expected) # Non-function aggregate - result = df.agg({"A": "size"}) + result = getattr(df, how)({"A": "size"}) expected = Series({"A": 3}) tm.assert_series_equal(result, expected) # Mix function and non-function aggs - result1 = df.agg(["count", "size"]) - result2 = df.agg( + result1 = getattr(df, how)(["count", "size"]) + result2 = getattr(df, how)( {"A": ["count", "size"], "B": ["count", "size"], "C": ["count", "size"]} ) expected = DataFrame( @@ -1352,13 +1362,13 @@ def test_non_callable_aggregates(self): tm.assert_frame_equal(result2, expected, check_like=True) # Just functional string arg is same as calling df.arg() - result = df.agg("count") + result = getattr(df, how)("count") expected = df.count() tm.assert_series_equal(result, expected) # Just a string attribute arg same as calling df.arg - result = df.agg("size") + result = getattr(df, how)("size") expected = df.size assert result == expected @@ -1577,3 +1587,28 @@ def test_apply_raw_returns_string(): result = df.apply(lambda x: x[0], axis=1, raw=True) expected = Series(["aa", "bbb"]) tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "op", ["abs", "ceil", "cos", "cumsum", "exp", "log", "sqrt", "square"] +) +@pytest.mark.parametrize("how", ["transform", "apply"]) +def test_apply_np_transformer(float_frame, op, how): + # GH 39116 + result = getattr(float_frame, how)(op) + expected = getattr(np, op)(float_frame) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("op", ["mean", "median", "std", "var"]) +@pytest.mark.parametrize("how", ["agg", "apply"]) +def test_apply_np_reducer(float_frame, op, how): + # GH 39116 + float_frame = DataFrame({"a": [1, 2], "b": [3, 4]}) + result = getattr(float_frame, how)(op) + # pandas ddof defaults to 1, numpy to 0 + kwargs = {"ddof": 1} if op in ("std", "var") else {} + expected = Series( + getattr(np, op)(float_frame, axis=0, **kwargs), index=float_frame.columns + ) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/apply/test_series_apply.py b/pandas/tests/series/apply/test_series_apply.py index 1242126c19527..b8c6291415ef7 100644 --- a/pandas/tests/series/apply/test_series_apply.py +++ b/pandas/tests/series/apply/test_series_apply.py @@ -338,19 +338,21 @@ def test_reduce(self, string_series): ) tm.assert_series_equal(result, expected) - def test_non_callable_aggregates(self): + @pytest.mark.parametrize("how", ["agg", "apply"]) + def test_non_callable_aggregates(self, how): # test agg using non-callable series attributes + # GH 39116 - expand to apply s = Series([1, 2, None]) # Calling agg w/ just a string arg same as calling s.arg - result = s.agg("size") + result = getattr(s, how)("size") expected = s.size assert result == expected # test when mixed w/ callable reducers - result = s.agg(["size", "count", "mean"]) + result = getattr(s, how)(["size", "count", "mean"]) expected = Series({"size": 3.0, "count": 2.0, "mean": 1.5}) - tm.assert_series_equal(result[expected.index], expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "series, func, expected",
- [x] closes #39116 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39118
2021-01-11T23:35:03Z
2021-01-12T01:15:07Z
2021-01-12T01:15:07Z
2021-01-12T01:27:48Z
Backport PR #39112 on branch 1.2.x (DOC: minor cleanup of 1.2.1 release notes)
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index e26405c3a332a..36b4b4fa77c4a 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -14,9 +14,8 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- The deprecated attributes ``_AXIS_NAMES`` and ``_AXIS_NUMBERS`` of :class:`DataFrame` and :class:`Series` will no longer show up in ``dir`` or ``inspect.getmembers`` calls (:issue:`38740`) - Fixed regression in :meth:`to_csv` that created corrupted zip files when there were more rows than ``chunksize`` (:issue:`38714`) -- Fixed a regression in ``groupby().rolling()`` where :class:`MultiIndex` levels were dropped (:issue:`38523`) +- Fixed regression in ``groupby().rolling()`` where :class:`MultiIndex` levels were dropped (:issue:`38523`) - Fixed regression in repr of float-like strings of an ``object`` dtype having trailing 0's truncated after the decimal (:issue:`38708`) - Fixed regression in :meth:`DataFrame.groupby()` with :class:`Categorical` grouping column not showing unused categories for ``grouped.indices`` (:issue:`38642`) - Fixed regression in :meth:`DataFrame.any` and :meth:`DataFrame.all` not returning a result for tz-aware ``datetime64`` columns (:issue:`38723`) @@ -24,11 +23,13 @@ Fixed regressions - Fixed regression in :meth:`.GroupBy.sem` where the presence of non-numeric columns would cause an error instead of being dropped (:issue:`38774`) - Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``ValueError`` when :class:`DataFrame` has unsorted :class:`MultiIndex` columns and indexer is a scalar (:issue:`38601`) - Fixed regression in :func:`read_excel` with non-rawbyte file handles (:issue:`38788`) -- Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) - Fixed regression in :meth:`Rolling.skew` and :meth:`Rolling.kurt` modifying the object inplace (:issue:`38908`) - Fixed regression in :meth:`read_csv` and other read functions were the encoding error policy (``errors``) did not default to ``"replace"`` when no encoding was specified (:issue:`38989`) -- Fixed regression in :meth:`DataFrame.replace` raising ValueError when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) +- Fixed regression in :meth:`DataFrame.replace` raising ``ValueError`` when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) - Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) +- Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) +- +- .. --------------------------------------------------------------------------- @@ -37,13 +38,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ -I/O -^^^ - -- Bumped minimum fastparquet version to 0.4.0 to avoid ``AttributeError`` from numba (:issue:`38344`) -- Bumped minimum pymysql version to 0.8.1 to avoid test failures (:issue:`38344`) -- Fixed ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) - +- Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) - - @@ -53,8 +48,14 @@ I/O Other ~~~~~ + +- The deprecated attributes ``_AXIS_NAMES`` and ``_AXIS_NUMBERS`` of :class:`DataFrame` and :class:`Series` will no longer show up in ``dir`` or ``inspect.getmembers`` calls (:issue:`38740`) +- Bumped minimum fastparquet version to 0.4.0 to avoid ``AttributeError`` from numba (:issue:`38344`) +- Bumped minimum pymysql version to 0.8.1 to avoid test failures (:issue:`38344`) - Fixed build failure on MacOS 11 in Python 3.9.1 (:issue:`38766`) - Added reference to backwards incompatible ``check_freq`` arg of :func:`testing.assert_frame_equal` and :func:`testing.assert_series_equal` in :ref:`pandas 1.1.0 whats new <whatsnew_110.api_breaking.testing.check_freq>` (:issue:`34050`) +- +- .. ---------------------------------------------------------------------------
Backport PR #39112: DOC: minor cleanup of 1.2.1 release notes
https://api.github.com/repos/pandas-dev/pandas/pulls/39114
2021-01-11T20:02:12Z
2021-01-12T00:00:27Z
2021-01-12T00:00:27Z
2021-01-12T00:00:27Z
DOC: minor cleanup of 1.2.1 release notes
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index e26405c3a332a..36b4b4fa77c4a 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -14,9 +14,8 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- The deprecated attributes ``_AXIS_NAMES`` and ``_AXIS_NUMBERS`` of :class:`DataFrame` and :class:`Series` will no longer show up in ``dir`` or ``inspect.getmembers`` calls (:issue:`38740`) - Fixed regression in :meth:`to_csv` that created corrupted zip files when there were more rows than ``chunksize`` (:issue:`38714`) -- Fixed a regression in ``groupby().rolling()`` where :class:`MultiIndex` levels were dropped (:issue:`38523`) +- Fixed regression in ``groupby().rolling()`` where :class:`MultiIndex` levels were dropped (:issue:`38523`) - Fixed regression in repr of float-like strings of an ``object`` dtype having trailing 0's truncated after the decimal (:issue:`38708`) - Fixed regression in :meth:`DataFrame.groupby()` with :class:`Categorical` grouping column not showing unused categories for ``grouped.indices`` (:issue:`38642`) - Fixed regression in :meth:`DataFrame.any` and :meth:`DataFrame.all` not returning a result for tz-aware ``datetime64`` columns (:issue:`38723`) @@ -24,11 +23,13 @@ Fixed regressions - Fixed regression in :meth:`.GroupBy.sem` where the presence of non-numeric columns would cause an error instead of being dropped (:issue:`38774`) - Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``ValueError`` when :class:`DataFrame` has unsorted :class:`MultiIndex` columns and indexer is a scalar (:issue:`38601`) - Fixed regression in :func:`read_excel` with non-rawbyte file handles (:issue:`38788`) -- Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) - Fixed regression in :meth:`Rolling.skew` and :meth:`Rolling.kurt` modifying the object inplace (:issue:`38908`) - Fixed regression in :meth:`read_csv` and other read functions were the encoding error policy (``errors``) did not default to ``"replace"`` when no encoding was specified (:issue:`38989`) -- Fixed regression in :meth:`DataFrame.replace` raising ValueError when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) +- Fixed regression in :meth:`DataFrame.replace` raising ``ValueError`` when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) - Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) +- Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) +- +- .. --------------------------------------------------------------------------- @@ -37,13 +38,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ -I/O -^^^ - -- Bumped minimum fastparquet version to 0.4.0 to avoid ``AttributeError`` from numba (:issue:`38344`) -- Bumped minimum pymysql version to 0.8.1 to avoid test failures (:issue:`38344`) -- Fixed ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`) - +- Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) - - @@ -53,8 +48,14 @@ I/O Other ~~~~~ + +- The deprecated attributes ``_AXIS_NAMES`` and ``_AXIS_NUMBERS`` of :class:`DataFrame` and :class:`Series` will no longer show up in ``dir`` or ``inspect.getmembers`` calls (:issue:`38740`) +- Bumped minimum fastparquet version to 0.4.0 to avoid ``AttributeError`` from numba (:issue:`38344`) +- Bumped minimum pymysql version to 0.8.1 to avoid test failures (:issue:`38344`) - Fixed build failure on MacOS 11 in Python 3.9.1 (:issue:`38766`) - Added reference to backwards incompatible ``check_freq`` arg of :func:`testing.assert_frame_equal` and :func:`testing.assert_series_equal` in :ref:`pandas 1.1.0 whats new <whatsnew_110.api_breaking.testing.check_freq>` (:issue:`34050`) +- +- .. ---------------------------------------------------------------------------
https://api.github.com/repos/pandas-dev/pandas/pulls/39112
2021-01-11T18:36:11Z
2021-01-11T19:59:39Z
2021-01-11T19:59:39Z
2021-01-11T20:03:50Z
DOC: NDFrame fillna method add use case
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2f4340c17c5a7..e34cdf1482021 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6317,7 +6317,7 @@ def fillna( ... [3, 4, np.nan, 1], ... [np.nan, np.nan, np.nan, 5], ... [np.nan, 3, np.nan, 4]], - ... columns=list('ABCD')) + ... columns=list("ABCD")) >>> df A B C D 0 NaN 2.0 NaN 0 @@ -6336,7 +6336,7 @@ def fillna( We can also propagate non-null values forward or backward. - >>> df.fillna(method='ffill') + >>> df.fillna(method="ffill") A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 @@ -6346,7 +6346,7 @@ def fillna( Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1, 2, and 3 respectively. - >>> values = {{'A': 0, 'B': 1, 'C': 2, 'D': 3}} + >>> values = {{"A": 0, "B": 1, "C": 2, "D": 3}} >>> df.fillna(value=values) A B C D 0 0.0 2.0 2.0 0 @@ -6362,6 +6362,17 @@ def fillna( 1 3.0 4.0 NaN 1 2 NaN 1.0 NaN 5 3 NaN 3.0 NaN 4 + + When filling using a DataFrame, replacement happens along + the same column names and same indices + + >>> df2 = pd.DataFrame(np.zeros((4, 4)), columns=list("ABCE")) + >>> df.fillna(df2) + A B C D + 0 0.0 2.0 0.0 0 + 1 3.0 4.0 0.0 1 + 2 0.0 0.0 0.0 5 + 3 0.0 3.0 0.0 4 """ inplace = validate_bool_kwarg(inplace, "inplace") value, method = validate_fillna_kwargs(value, method)
- [x] closes #38917 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry cc @MarcoGorelli
https://api.github.com/repos/pandas-dev/pandas/pulls/39109
2021-01-11T15:49:45Z
2021-01-25T16:40:38Z
2021-01-25T16:40:37Z
2021-01-25T16:40:42Z
TYP: replace Label alias from pandas._typing with Hashable
diff --git a/pandas/_typing.py b/pandas/_typing.py index 0b50dd69f7abb..91cb01dac76fb 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -84,9 +84,8 @@ FrameOrSeries = TypeVar("FrameOrSeries", bound="NDFrame") Axis = Union[str, int] -Label = Optional[Hashable] -IndexLabel = Union[Label, Sequence[Label]] -Level = Union[Label, int] +IndexLabel = Union[Hashable, Sequence[Hashable]] +Level = Union[Hashable, int] Shape = Tuple[int, ...] Suffixes = Tuple[str, str] Ordered = Optional[bool] @@ -99,11 +98,11 @@ "ExtensionDtype", NpDtype, Type[Union[str, float, int, complex, bool, object]] ] # DtypeArg specifies all allowable dtypes in a functions its dtype argument -DtypeArg = Union[Dtype, Dict[Label, Dtype]] +DtypeArg = Union[Dtype, Dict[Hashable, Dtype]] DtypeObj = Union[np.dtype, "ExtensionDtype"] # For functions like rename that convert one label to another -Renamer = Union[Mapping[Label, Any], Callable[[Label], Label]] +Renamer = Union[Mapping[Hashable, Any], Callable[[Hashable], Hashable]] # to maintain type information across generic functions and parametrization T = TypeVar("T") @@ -120,7 +119,7 @@ # types of `func` kwarg for DataFrame.aggregate and Series.aggregate AggFuncTypeBase = Union[Callable, str] -AggFuncTypeDict = Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]] +AggFuncTypeDict = Dict[Hashable, Union[AggFuncTypeBase, List[AggFuncTypeBase]]] AggFuncType = Union[ AggFuncTypeBase, List[AggFuncTypeBase], @@ -155,8 +154,8 @@ FormattersType = Union[ List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable] ] -ColspaceType = Mapping[Label, Union[str, int]] +ColspaceType = Mapping[Hashable, Union[str, int]] FloatFormatType = Union[str, Callable, "EngFormatter"] ColspaceArgType = Union[ - str, int, Sequence[Union[str, int]], Mapping[Label, Union[str, int]] + str, int, Sequence[Union[str, int]], Mapping[Hashable, Union[str, int]] ] diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index cd169a250b49b..72a98da44428b 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -11,6 +11,7 @@ Callable, DefaultDict, Dict, + Hashable, Iterable, List, Optional, @@ -28,7 +29,6 @@ Axis, FrameOrSeries, FrameOrSeriesUnion, - Label, ) from pandas.core.dtypes.cast import is_nested_object @@ -294,9 +294,9 @@ def maybe_mangle_lambdas(agg_spec: Any) -> Any: def relabel_result( result: FrameOrSeries, func: Dict[str, List[Union[Callable, str]]], - columns: Iterable[Label], + columns: Iterable[Hashable], order: Iterable[int], -) -> Dict[Label, "Series"]: +) -> Dict[Hashable, "Series"]: """ Internal function to reorder result if relabelling is True for dataframe.agg, and return the reordered result in dict. @@ -323,7 +323,7 @@ def relabel_result( reordered_indexes = [ pair[0] for pair in sorted(zip(columns, order), key=lambda t: t[1]) ] - reordered_result_in_dict: Dict[Label, "Series"] = {} + reordered_result_in_dict: Dict[Hashable, "Series"] = {} idx = 0 reorder_mask = not isinstance(result, ABCSeries) and len(result.columns) > 1 @@ -493,7 +493,7 @@ def transform_dict_like( # GH 15931 - deprecation of renaming keys raise SpecificationError("nested renamer is not supported") - results: Dict[Label, FrameOrSeriesUnion] = {} + results: Dict[Hashable, FrameOrSeriesUnion] = {} for name, how in func.items(): colg = obj._gotitem(name, ndim=1) try: diff --git a/pandas/core/computation/parsing.py b/pandas/core/computation/parsing.py index 732b0650e5bd7..3c2f7f2793358 100644 --- a/pandas/core/computation/parsing.py +++ b/pandas/core/computation/parsing.py @@ -6,9 +6,7 @@ from keyword import iskeyword import token import tokenize -from typing import Iterator, Tuple - -from pandas._typing import Label +from typing import Hashable, Iterator, Tuple # A token value Python's tokenizer probably will never use. BACKTICK_QUOTED_STRING = 100 @@ -90,7 +88,7 @@ def clean_backtick_quoted_toks(tok: Tuple[int, str]) -> Tuple[int, str]: return toknum, tokval -def clean_column_name(name: "Label") -> "Label": +def clean_column_name(name: Hashable) -> Hashable: """ Function to emulate the cleaning of a backtick quoted name. diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e65e9302dd4d5..3e331a7a23e17 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -61,7 +61,6 @@ FrameOrSeriesUnion, IndexKeyFunc, IndexLabel, - Label, Level, PythonFuncType, Renamer, @@ -992,7 +991,7 @@ def style(self) -> Styler: """ @Appender(_shared_docs["items"]) - def items(self) -> Iterable[Tuple[Label, Series]]: + def items(self) -> Iterable[Tuple[Hashable, Series]]: if self.columns.is_unique and hasattr(self, "_item_cache"): for k in self.columns: yield k, self._get_item_cache(k) @@ -1001,10 +1000,10 @@ def items(self) -> Iterable[Tuple[Label, Series]]: yield k, self._ixs(i, axis=1) @Appender(_shared_docs["items"]) - def iteritems(self) -> Iterable[Tuple[Label, Series]]: + def iteritems(self) -> Iterable[Tuple[Hashable, Series]]: yield from self.items() - def iterrows(self) -> Iterable[Tuple[Label, Series]]: + def iterrows(self) -> Iterable[Tuple[Hashable, Series]]: """ Iterate over DataFrame rows as (index, Series) pairs. @@ -2121,14 +2120,14 @@ def _from_arrays( def to_stata( self, path: FilePathOrBuffer, - convert_dates: Optional[Dict[Label, str]] = None, + convert_dates: Optional[Dict[Hashable, str]] = None, write_index: bool = True, byteorder: Optional[str] = None, time_stamp: Optional[datetime.datetime] = None, data_label: Optional[str] = None, - variable_labels: Optional[Dict[Label, str]] = None, + variable_labels: Optional[Dict[Hashable, str]] = None, version: Optional[int] = 114, - convert_strl: Optional[Sequence[Label]] = None, + convert_strl: Optional[Sequence[Hashable]] = None, compression: CompressionOptions = "infer", storage_options: StorageOptions = None, ) -> None: @@ -4483,7 +4482,7 @@ def fillna( downcast=downcast, ) - def pop(self, item: Label) -> Series: + def pop(self, item: Hashable) -> Series: """ Return item and drop from frame. Raise KeyError if not found. @@ -4546,7 +4545,7 @@ def replace( ) def _replace_columnwise( - self, mapping: Dict[Label, Tuple[Any, Any]], inplace: bool, regex + self, mapping: Dict[Hashable, Tuple[Any, Any]], inplace: bool, regex ): """ Dispatch to Series.replace column-wise. @@ -4724,7 +4723,7 @@ def set_index( "one-dimensional arrays." ) - missing: List[Label] = [] + missing: List[Hashable] = [] for col in keys: if isinstance(col, (Index, Series, np.ndarray, list, abc.Iterator)): # arrays are fine as long as they are one-dimensional @@ -4752,7 +4751,7 @@ def set_index( frame = self.copy() arrays = [] - names: List[Label] = [] + names: List[Hashable] = [] if append: names = list(self.index.names) if isinstance(self.index, MultiIndex): @@ -4761,7 +4760,7 @@ def set_index( else: arrays.append(self.index) - to_remove: List[Label] = [] + to_remove: List[Hashable] = [] for col in keys: if isinstance(col, MultiIndex): for n in range(col.nlevels): @@ -4819,7 +4818,7 @@ def reset_index( # type: ignore[misc] drop: bool = ..., inplace: Literal[False] = ..., col_level: Hashable = ..., - col_fill: Label = ..., + col_fill: Hashable = ..., ) -> DataFrame: ... @@ -4830,7 +4829,7 @@ def reset_index( drop: bool = ..., inplace: Literal[True] = ..., col_level: Hashable = ..., - col_fill: Label = ..., + col_fill: Hashable = ..., ) -> None: ... @@ -4840,7 +4839,7 @@ def reset_index( drop: bool = False, inplace: bool = False, col_level: Hashable = 0, - col_fill: Label = "", + col_fill: Hashable = "", ) -> Optional[DataFrame]: """ Reset the index, or a level of it. @@ -5630,7 +5629,7 @@ def sort_index( def value_counts( self, - subset: Optional[Sequence[Label]] = None, + subset: Optional[Sequence[Hashable]] = None, normalize: bool = False, sort: bool = True, ascending: bool = False, @@ -7511,7 +7510,7 @@ def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame: def _gotitem( self, - key: Union[Label, List[Label]], + key: IndexLabel, ndim: int, subset: Optional[FrameOrSeriesUnion] = None, ) -> FrameOrSeriesUnion: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2f4340c17c5a7..ce1e962614c58 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -44,7 +44,6 @@ IndexKeyFunc, IndexLabel, JSONSerializable, - Label, Level, NpDtype, Renamer, @@ -526,7 +525,7 @@ def _get_axis_resolvers(self, axis: str) -> Dict[str, Union[Series, MultiIndex]] return d @final - def _get_index_resolvers(self) -> Dict[Label, Union[Series, MultiIndex]]: + def _get_index_resolvers(self) -> Dict[Hashable, Union[Series, MultiIndex]]: from pandas.core.computation.parsing import clean_column_name d: Dict[str, Union[Series, MultiIndex]] = {} @@ -536,7 +535,7 @@ def _get_index_resolvers(self) -> Dict[Label, Union[Series, MultiIndex]]: return {clean_column_name(k): v for k, v in d.items() if not isinstance(k, int)} @final - def _get_cleaned_column_resolvers(self) -> Dict[Label, Series]: + def _get_cleaned_column_resolvers(self) -> Dict[Hashable, Series]: """ Return the special character free column resolvers of a dataframe. @@ -776,7 +775,7 @@ def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: result = self.set_axis(new_labels, axis=axis, inplace=False) return result - def pop(self, item: Label) -> Union[Series, Any]: + def pop(self, item: Hashable) -> Union[Series, Any]: result = self[item] del self[item] if self.ndim == 2: @@ -3225,7 +3224,7 @@ def to_csv( sep: str = ",", na_rep: str = "", float_format: Optional[str] = None, - columns: Optional[Sequence[Label]] = None, + columns: Optional[Sequence[Hashable]] = None, header: Union[bool_t, List[str]] = True, index: bool_t = True, index_label: Optional[IndexLabel] = None, @@ -10214,7 +10213,7 @@ def describe_1d(data) -> "Series": ldesc = [describe_1d(s) for _, s in data.items()] # set a convenient order for rows - names: List[Label] = [] + names: List[Hashable] = [] ldesc_indexes = sorted((x.index for x in ldesc), key=len) for idxnames in ldesc_indexes: for name in idxnames: diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index f2899a7ca704b..174a2f4052b06 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -15,6 +15,7 @@ Callable, Dict, FrozenSet, + Hashable, Iterable, List, Mapping, @@ -30,7 +31,7 @@ import numpy as np from pandas._libs import lib, reduction as libreduction -from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion, Label +from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion from pandas.util._decorators import Appender, Substitution, doc from pandas.core.dtypes.cast import ( @@ -1129,7 +1130,7 @@ def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: axis = self.axis obj = self._obj_with_exclusions - result: Dict[Label, Union[NDFrame, np.ndarray]] = {} + result: Dict[Hashable, Union[NDFrame, np.ndarray]] = {} if axis != obj._info_axis_number: for name, data in self: fres = func(data, *args, **kwargs) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index aef4c036abc65..fff2f5b631e86 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -43,7 +43,6 @@ class providing the base-class of operations. FrameOrSeries, FrameOrSeriesUnion, IndexLabel, - Label, Scalar, final, ) @@ -522,7 +521,7 @@ def __init__( axis: int = 0, level: Optional[IndexLabel] = None, grouper: Optional["ops.BaseGrouper"] = None, - exclusions: Optional[Set[Label]] = None, + exclusions: Optional[Set[Hashable]] = None, selection: Optional[IndexLabel] = None, as_index: bool = True, sort: bool = True, @@ -860,7 +859,7 @@ def get_group(self, name, obj=None): return obj._take_with_is_copy(inds, axis=self.axis) - def __iter__(self) -> Iterator[Tuple[Label, FrameOrSeries]]: + def __iter__(self) -> Iterator[Tuple[Hashable, FrameOrSeries]]: """ Groupby iterator. diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 26fb23087ed55..00cc762c7c136 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -7,7 +7,7 @@ import numpy as np -from pandas._typing import FrameOrSeries, Label, final +from pandas._typing import FrameOrSeries, final from pandas.errors import InvalidIndexError from pandas.util._decorators import cache_readonly @@ -616,7 +616,7 @@ def get_grouper( mutated: bool = False, validate: bool = True, dropna: bool = True, -) -> Tuple["ops.BaseGrouper", Set[Label], FrameOrSeries]: +) -> Tuple["ops.BaseGrouper", Set[Hashable], FrameOrSeries]: """ Create and return a BaseGrouper, which is an internal mapping of how to create the grouper indexers. @@ -741,7 +741,7 @@ def get_grouper( levels = [level] * len(keys) groupings: List[Grouping] = [] - exclusions: Set[Label] = set() + exclusions: Set[Hashable] = set() # if the actual grouper should be obj[key] def is_in_axis(key) -> bool: diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 62d11183691f0..45897666b6ccf 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -24,7 +24,7 @@ from pandas._libs import NaT, iNaT, lib import pandas._libs.groupby as libgroupby import pandas._libs.reduction as libreduction -from pandas._typing import ArrayLike, F, FrameOrSeries, Label, Shape, final +from pandas._typing import ArrayLike, F, FrameOrSeries, Shape, final from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly @@ -134,7 +134,7 @@ def nkeys(self) -> int: def get_iterator( self, data: FrameOrSeries, axis: int = 0 - ) -> Iterator[Tuple[Label, FrameOrSeries]]: + ) -> Iterator[Tuple[Hashable, FrameOrSeries]]: """ Groupby iterator @@ -260,7 +260,7 @@ def levels(self) -> List[Index]: return [ping.group_index for ping in self.groupings] @property - def names(self) -> List[Label]: + def names(self) -> List[Hashable]: return [ping.name for ping in self.groupings] @final @@ -903,7 +903,7 @@ def levels(self) -> List[Index]: return [self.binlabels] @property - def names(self) -> List[Label]: + def names(self) -> List[Hashable]: return [self.binlabels.name] @property diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index b51c165ccfde6..b051dc1811190 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -28,7 +28,7 @@ from pandas._libs.lib import is_datetime_array, no_default from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime, Timestamp from pandas._libs.tslibs.timezones import tz_compare -from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Label, Shape, final +from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Shape, final from pandas.compat.numpy import function as nv from pandas.errors import DuplicateLabelError, InvalidIndexError from pandas.util._decorators import Appender, cache_readonly, doc @@ -235,7 +235,7 @@ def _outer_indexer(self, left, right): _typ = "index" _data: Union[ExtensionArray, np.ndarray] _id: Optional[_Identity] = None - _name: Label = None + _name: Hashable = None # MultiIndex.levels previously allowed setting the index name. We # don't allow this anymore, and raise if it happens rather than # failing silently. @@ -486,7 +486,7 @@ def asi8(self): return None @classmethod - def _simple_new(cls, values, name: Label = None): + def _simple_new(cls, values, name: Hashable = None): """ We require that we have a dtype compat for the values. If we are passed a non-dtype compat, then coerce using the constructor. @@ -570,7 +570,7 @@ def _get_attributes_dict(self): """ return {k: getattr(self, k, None) for k in self._attributes} - def _shallow_copy(self, values=None, name: Label = no_default): + def _shallow_copy(self, values=None, name: Hashable = no_default): """ Create a new Index with the same class as the caller, don't copy the data, use the same object attributes with passed in attributes taking @@ -888,10 +888,10 @@ def repeat(self, repeats, axis=None): def copy( self: _IndexT, - name: Optional[Label] = None, + name: Optional[Hashable] = None, deep: bool = False, dtype: Optional[Dtype] = None, - names: Optional[Sequence[Label]] = None, + names: Optional[Sequence[Hashable]] = None, ) -> _IndexT: """ Make a copy of this object. @@ -1308,7 +1308,9 @@ def name(self, value): self._name = value @final - def _validate_names(self, name=None, names=None, deep: bool = False) -> List[Label]: + def _validate_names( + self, name=None, names=None, deep: bool = False + ) -> List[Hashable]: """ Handles the quirks of having a singular 'name' parameter for general Index and plural 'names' parameter for MultiIndex. @@ -4506,7 +4508,7 @@ def append(self, other): return self._concat(to_concat, name) - def _concat(self, to_concat: List["Index"], name: Label) -> "Index": + def _concat(self, to_concat: List["Index"], name: Hashable) -> "Index": """ Concatenate multiple Index objects. """ @@ -5374,8 +5376,8 @@ def _get_string_slice(self, key: str_t): def slice_indexer( self, - start: Optional[Label] = None, - end: Optional[Label] = None, + start: Optional[Hashable] = None, + end: Optional[Hashable] = None, step: Optional[int] = None, kind: Optional[str_t] = None, ) -> slice: @@ -6114,7 +6116,7 @@ def default_index(n: int) -> "RangeIndex": return RangeIndex(0, n, name=None) -def maybe_extract_name(name, obj, cls) -> Label: +def maybe_extract_name(name, obj, cls) -> Hashable: """ If no name is passed, then extract it from data, validating hashability. """ @@ -6296,7 +6298,7 @@ def _try_convert_to_int_array( raise ValueError -def get_unanimous_names(*indexes: Index) -> Tuple[Label, ...]: +def get_unanimous_names(*indexes: Index) -> Tuple[Hashable, ...]: """ Return common name if all indices agree, otherwise None (level-by-level). diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 24920e9b5faa7..a8a872ff38fb8 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -1,4 +1,4 @@ -from typing import Any, List, Optional +from typing import Any, Hashable, List, Optional import warnings import numpy as np @@ -7,7 +7,7 @@ from pandas._libs import index as libindex from pandas._libs.lib import no_default -from pandas._typing import ArrayLike, Dtype, Label +from pandas._typing import ArrayLike, Dtype from pandas.util._decorators import Appender, doc from pandas.core.dtypes.common import ( @@ -201,7 +201,7 @@ def __new__( return cls._simple_new(data, name=name) @classmethod - def _simple_new(cls, values: Categorical, name: Label = None): + def _simple_new(cls, values: Categorical, name: Optional[Hashable] = None): assert isinstance(values, Categorical), type(values) result = object.__new__(cls) @@ -221,7 +221,7 @@ def _simple_new(cls, values: Categorical, name: Label = None): def _shallow_copy( # type:ignore[override] self, values: Optional[Categorical] = None, - name: Label = no_default, + name: Hashable = no_default, ): name = self.name if name is no_default else name @@ -605,7 +605,7 @@ def map(self, mapper): mapped = self._values.map(mapper) return Index(mapped, name=self.name) - def _concat(self, to_concat: List["Index"], name: Label) -> Index: + def _concat(self, to_concat: List["Index"], name: Hashable) -> Index: # if calling index is category, don't check dtype of others try: codes = np.concatenate([self._is_dtype_compat(c).codes for c in to_concat]) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 7d214829b1871..50a4f589c59c1 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -2,13 +2,24 @@ Base and utility classes for tseries type pandas objects. """ from datetime import datetime -from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type, TypeVar, Union, cast +from typing import ( + TYPE_CHECKING, + Any, + Hashable, + List, + Optional, + Tuple, + Type, + TypeVar, + Union, + cast, +) import numpy as np from pandas._libs import NaT, Timedelta, iNaT, join as libjoin, lib from pandas._libs.tslibs import BaseOffset, Resolution, Tick -from pandas._typing import Callable, Label +from pandas._typing import Callable from pandas.compat.numpy import function as nv from pandas.util._decorators import Appender, cache_readonly, doc @@ -108,7 +119,7 @@ class DatetimeIndexOpsMixin(NDArrayBackedExtensionIndex): def _simple_new( cls, values: Union[DatetimeArray, TimedeltaArray, PeriodArray], - name: Label = None, + name: Optional[Hashable] = None, ): assert isinstance(values, cls._data_cls), type(values) diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index f597175bf2ae2..2c4f40d5275e1 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -1,12 +1,11 @@ """ Shared methods for Index subclasses backed by ExtensionArray. """ -from typing import List, Optional, TypeVar +from typing import Hashable, List, Optional, TypeVar import numpy as np from pandas._libs import lib -from pandas._typing import Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly, doc @@ -215,7 +214,7 @@ class ExtensionIndex(Index): @doc(Index._shallow_copy) def _shallow_copy( - self, values: Optional[ExtensionArray] = None, name: Label = lib.no_default + self, values: Optional[ExtensionArray] = None, name: Hashable = lib.no_default ): name = self.name if name is lib.no_default else name diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index fdac4028af281..60755d88fff7f 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -2,7 +2,7 @@ from functools import wraps from operator import le, lt import textwrap -from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, cast +from typing import TYPE_CHECKING, Any, Hashable, List, Optional, Tuple, Union, cast import numpy as np @@ -11,7 +11,7 @@ from pandas._libs import lib from pandas._libs.interval import Interval, IntervalMixin, IntervalTree from pandas._libs.tslibs import BaseOffset, Timedelta, Timestamp, to_offset -from pandas._typing import Dtype, DtypeObj, Label +from pandas._typing import Dtype, DtypeObj from pandas.errors import InvalidIndexError from pandas.util._decorators import Appender, cache_readonly from pandas.util._exceptions import rewrite_exception @@ -210,7 +210,7 @@ def __new__( return cls._simple_new(array, name) @classmethod - def _simple_new(cls, array: IntervalArray, name: Label = None): + def _simple_new(cls, array: IntervalArray, name: Hashable = None): """ Construct from an IntervalArray diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index f058645c4abda..485d4f809eabd 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -20,7 +20,7 @@ from pandas._libs import algos as libalgos, index as libindex, lib from pandas._libs.hashtable import duplicated_int64 -from pandas._typing import AnyArrayLike, DtypeObj, Label, Scalar, Shape +from pandas._typing import AnyArrayLike, DtypeObj, Scalar, Shape from pandas.compat.numpy import function as nv from pandas.errors import InvalidIndexError, PerformanceWarning, UnsortedIndexError from pandas.util._decorators import Appender, cache_readonly, doc @@ -475,7 +475,7 @@ def from_tuples( cls, tuples, sortorder: Optional[int] = None, - names: Optional[Sequence[Label]] = None, + names: Optional[Sequence[Hashable]] = None, ): """ Convert list of tuples to MultiIndex. @@ -517,7 +517,7 @@ def from_tuples( elif is_iterator(tuples): tuples = list(tuples) - arrays: List[Sequence[Label]] + arrays: List[Sequence[Hashable]] if len(tuples) == 0: if names is None: raise TypeError("Cannot infer number of levels from empty list") diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 59793d1a63813..e5da085249acf 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -1,10 +1,10 @@ -from typing import Any, Optional +from typing import Any, Hashable, Optional import warnings import numpy as np from pandas._libs import index as libindex, lib -from pandas._typing import Dtype, DtypeObj, Label +from pandas._typing import Dtype, DtypeObj from pandas.util._decorators import doc from pandas.core.dtypes.cast import astype_nansafe @@ -115,7 +115,7 @@ def _maybe_cast_slice_bound(self, label, side: str, kind): # ---------------------------------------------------------------- @doc(Index._shallow_copy) - def _shallow_copy(self, values=None, name: Label = lib.no_default): + def _shallow_copy(self, values=None, name: Hashable = lib.no_default): if values is not None and not self._can_hold_na and values.dtype.kind == "f": name = self.name if name is lib.no_default else name # Ensure we are not returning an Int64Index with float data: diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 4256ad93695e9..66a70fbea238a 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -1,14 +1,14 @@ from datetime import timedelta import operator from sys import getsizeof -from typing import Any, List, Optional, Tuple +from typing import Any, Hashable, List, Optional, Tuple import warnings import numpy as np from pandas._libs import index as libindex from pandas._libs.lib import no_default -from pandas._typing import Dtype, Label +from pandas._typing import Dtype from pandas.compat.numpy import function as nv from pandas.util._decorators import cache_readonly, doc @@ -139,7 +139,7 @@ def from_range( return cls._simple_new(data, name=name) @classmethod - def _simple_new(cls, values: range, name: Label = None) -> "RangeIndex": + def _simple_new(cls, values: range, name: Hashable = None) -> "RangeIndex": result = object.__new__(cls) assert isinstance(values, range) @@ -400,7 +400,7 @@ def __iter__(self): yield from self._range @doc(Int64Index._shallow_copy) - def _shallow_copy(self, values=None, name: Label = no_default): + def _shallow_copy(self, values=None, name: Hashable = no_default): name = self.name if name is no_default else name if values is not None: diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index f1cd221bae15c..5161cf7038fe8 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -3,13 +3,23 @@ constructors before passing them to a BlockManager. """ from collections import abc -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Hashable, + List, + Optional, + Sequence, + Tuple, + Union, +) import numpy as np import numpy.ma as ma from pandas._libs import lib -from pandas._typing import Axis, DtypeObj, Label, Scalar +from pandas._typing import Axis, DtypeObj, Scalar from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, @@ -391,7 +401,7 @@ def extract_index(data) -> Index: index = Index([]) elif len(data) > 0: raw_lengths = [] - indexes: List[Union[List[Label], Index]] = [] + indexes: List[Union[List[Hashable], Index]] = [] have_raw_arrays = False have_series = False @@ -459,7 +469,7 @@ def _get_names_from_index(data): if not has_some_name: return ibase.default_index(len(data)) - index: List[Label] = list(range(len(data))) + index: List[Hashable] = list(range(len(data))) count = 0 for i, s in enumerate(data): n = getattr(s, "name", None) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index d27efd98ab079..fd503280eeafb 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -5,6 +5,7 @@ Callable, DefaultDict, Dict, + Hashable, List, Optional, Sequence, @@ -17,7 +18,7 @@ import numpy as np from pandas._libs import internals as libinternals, lib -from pandas._typing import ArrayLike, Dtype, DtypeObj, Label, Shape +from pandas._typing import ArrayLike, Dtype, DtypeObj, Shape from pandas.errors import PerformanceWarning from pandas.util._validators import validate_bool_kwarg @@ -1166,7 +1167,7 @@ def value_getitem(placement): # Newly created block's dtype may already be present. self._known_consolidated = False - def insert(self, loc: int, item: Label, value, allow_duplicates: bool = False): + def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False): """ Insert item at selected position. diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 5799b579fd0dc..d4729a0a59baa 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -5,6 +5,7 @@ from collections import abc from typing import ( TYPE_CHECKING, + Hashable, Iterable, List, Mapping, @@ -17,7 +18,7 @@ import numpy as np -from pandas._typing import FrameOrSeriesUnion, Label +from pandas._typing import FrameOrSeriesUnion from pandas.util._decorators import cache_readonly from pandas.core.dtypes.concat import concat_compat @@ -50,7 +51,7 @@ @overload def concat( - objs: Union[Iterable["DataFrame"], Mapping[Label, "DataFrame"]], + objs: Union[Iterable["DataFrame"], Mapping[Hashable, "DataFrame"]], axis=0, join: str = "outer", ignore_index: bool = False, @@ -66,7 +67,7 @@ def concat( @overload def concat( - objs: Union[Iterable["NDFrame"], Mapping[Label, "NDFrame"]], + objs: Union[Iterable["NDFrame"], Mapping[Hashable, "NDFrame"]], axis=0, join: str = "outer", ignore_index: bool = False, @@ -81,7 +82,7 @@ def concat( def concat( - objs: Union[Iterable["NDFrame"], Mapping[Label, "NDFrame"]], + objs: Union[Iterable["NDFrame"], Mapping[Hashable, "NDFrame"]], axis=0, join="outer", ignore_index: bool = False, @@ -306,7 +307,7 @@ class _Concatenator: def __init__( self, - objs: Union[Iterable["NDFrame"], Mapping[Label, "NDFrame"]], + objs: Union[Iterable["NDFrame"], Mapping[Hashable, "NDFrame"]], axis=0, join: str = "outer", keys=None, @@ -560,7 +561,7 @@ def _get_concat_axis(self) -> Index: idx = ibase.default_index(len(self.objs)) return idx elif self.keys is None: - names: List[Label] = [None] * len(self.objs) + names: List[Hashable] = [None] * len(self.objs) num = 0 has_names = False for i, x in enumerate(self.objs): diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index bdbd8c7b8dff6..4c335802e5546 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -4,6 +4,7 @@ TYPE_CHECKING, Callable, Dict, + Hashable, List, Optional, Sequence, @@ -15,7 +16,7 @@ import numpy as np -from pandas._typing import FrameOrSeriesUnion, Label +from pandas._typing import FrameOrSeriesUnion, IndexLabel from pandas.util._decorators import Appender, Substitution from pandas.core.dtypes.cast import maybe_downcast_to_dtype @@ -424,9 +425,9 @@ def _convert_by(by): @Appender(_shared_docs["pivot"], indents=1) def pivot( data: DataFrame, - index: Optional[Union[Label, Sequence[Label]]] = None, - columns: Optional[Union[Label, Sequence[Label]]] = None, - values: Optional[Union[Label, Sequence[Label]]] = None, + index: Optional[IndexLabel] = None, + columns: Optional[IndexLabel] = None, + values: Optional[IndexLabel] = None, ) -> "DataFrame": if columns is None: raise TypeError("pivot() missing 1 required argument: 'columns'") @@ -454,7 +455,7 @@ def pivot( if is_list_like(values) and not isinstance(values, tuple): # Exclude tuple because it is seen as a single column name - values = cast(Sequence[Label], values) + values = cast(Sequence[Hashable], values) indexed = data._constructor( data[values]._values, index=index, columns=values ) diff --git a/pandas/core/series.py b/pandas/core/series.py index 897e7c65466ae..e55d3eb05f74c 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -9,6 +9,7 @@ TYPE_CHECKING, Any, Callable, + Hashable, Iterable, List, Optional, @@ -32,7 +33,6 @@ DtypeObj, FrameOrSeriesUnion, IndexKeyFunc, - Label, NpDtype, StorageOptions, ValueKeyFunc, @@ -193,7 +193,7 @@ class Series(base.IndexOpsMixin, generic.NDFrame): _typ = "series" _HANDLED_TYPES = (Index, ExtensionArray, np.ndarray) - _name: Label + _name: Hashable _metadata: List[str] = ["name"] _internal_names_set = {"index"} | generic.NDFrame._internal_names_set _accessors = {"dt", "cat", "str", "sparse"} @@ -462,7 +462,7 @@ def dtypes(self) -> DtypeObj: return self.dtype @property - def name(self) -> Label: + def name(self) -> Hashable: """ Return the name of the Series. @@ -512,7 +512,7 @@ def name(self) -> Label: return self._name @name.setter - def name(self, value: Label) -> None: + def name(self, value: Hashable) -> None: validate_all_hashable(value, error_name=f"{type(self).__name__}.name") object.__setattr__(self, "_name", value) @@ -1453,7 +1453,7 @@ def to_markdown( # ---------------------------------------------------------------------- - def items(self) -> Iterable[Tuple[Label, Any]]: + def items(self) -> Iterable[Tuple[Hashable, Any]]: """ Lazily iterate over (index, value) tuples. @@ -1483,7 +1483,7 @@ def items(self) -> Iterable[Tuple[Label, Any]]: return zip(iter(self.index), iter(self)) @Appender(items.__doc__) - def iteritems(self) -> Iterable[Tuple[Label, Any]]: + def iteritems(self) -> Iterable[Tuple[Hashable, Any]]: return self.items() # ---------------------------------------------------------------------- @@ -2706,7 +2706,7 @@ def _binop(self, other, func, level=None, fill_value=None): return ret def _construct_result( - self, result: Union[ArrayLike, Tuple[ArrayLike, ArrayLike]], name: Label + self, result: Union[ArrayLike, Tuple[ArrayLike, ArrayLike]], name: Hashable ) -> Union["Series", Tuple["Series", "Series"]]: """ Construct an appropriately-labelled Series from the result of an op. @@ -4409,7 +4409,7 @@ def fillna( downcast=downcast, ) - def pop(self, item: Label) -> Any: + def pop(self, item: Hashable) -> Any: """ Return item and drops from series. Raise KeyError if not found. diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 56e171e1a5db1..aff55bc0a1fd5 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -5,6 +5,7 @@ from typing import ( TYPE_CHECKING, Callable, + Hashable, List, Optional, Tuple, @@ -32,7 +33,7 @@ guess_datetime_format, ) from pandas._libs.tslibs.strptime import array_strptime -from pandas._typing import AnyArrayLike, ArrayLike, Label, Timezone +from pandas._typing import AnyArrayLike, ArrayLike, Timezone from pandas.core.dtypes.common import ( ensure_object, @@ -181,7 +182,7 @@ def _maybe_cache( def _box_as_indexlike( - dt_array: ArrayLike, utc: Optional[bool] = None, name: Label = None + dt_array: ArrayLike, utc: Optional[bool] = None, name: Hashable = None ) -> Index: """ Properly boxes the ndarray of datetimes to DatetimeIndex @@ -267,7 +268,7 @@ def _return_parsed_timezone_results(result, timezones, tz, name): def _convert_listlike_datetimes( arg, format: Optional[str], - name: Label = None, + name: Hashable = None, tz: Optional[Timezone] = None, unit: Optional[str] = None, errors: Optional[str] = None, diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index 65c51c78383a9..74756b0c57092 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -4,7 +4,17 @@ import csv as csvlib import os -from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Sequence, Union +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Hashable, + Iterator, + List, + Optional, + Sequence, + Union, +) import numpy as np @@ -14,7 +24,6 @@ FilePathOrBuffer, FloatFormatType, IndexLabel, - Label, StorageOptions, ) @@ -40,7 +49,7 @@ def __init__( formatter: "DataFrameFormatter", path_or_buf: FilePathOrBuffer[str] = "", sep: str = ",", - cols: Optional[Sequence[Label]] = None, + cols: Optional[Sequence[Hashable]] = None, index_label: Optional[IndexLabel] = None, mode: str = "w", encoding: Optional[str] = None, @@ -129,7 +138,9 @@ def _initialize_quotechar(self, quotechar: Optional[str]) -> Optional[str]: def has_mi_columns(self) -> bool: return bool(isinstance(self.obj.columns, ABCMultiIndex)) - def _initialize_columns(self, cols: Optional[Sequence[Label]]) -> Sequence[Label]: + def _initialize_columns( + self, cols: Optional[Sequence[Hashable]] + ) -> Sequence[Hashable]: # validate mi options if self.has_mi_columns: if cols is not None: @@ -195,7 +206,7 @@ def _need_to_save_header(self) -> bool: return bool(self._has_aliases or self.header) @property - def write_cols(self) -> Sequence[Label]: + def write_cols(self) -> Sequence[Hashable]: if self._has_aliases: assert not isinstance(self.header, bool) if len(self.header) != len(self.cols): @@ -208,8 +219,8 @@ def write_cols(self) -> Sequence[Label]: return self.cols @property - def encoded_labels(self) -> List[Label]: - encoded_labels: List[Label] = [] + def encoded_labels(self) -> List[Hashable]: + encoded_labels: List[Hashable] = [] if self.index and self.index_label: assert isinstance(self.index_label, Sequence) @@ -259,7 +270,7 @@ def _save_header(self) -> None: for row in self._generate_multiindex_header_rows(): self.writer.writerow(row) - def _generate_multiindex_header_rows(self) -> Iterator[List[Label]]: + def _generate_multiindex_header_rows(self) -> Iterator[List[Hashable]]: columns = self.obj.columns for i in range(columns.nlevels): # we need at least 1 index column to write our col names diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 0cad67169feff..b027d8139f24b 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -5,13 +5,23 @@ from functools import reduce import itertools import re -from typing import Callable, Dict, Iterable, Mapping, Optional, Sequence, Union, cast +from typing import ( + Callable, + Dict, + Hashable, + Iterable, + Mapping, + Optional, + Sequence, + Union, + cast, +) import warnings import numpy as np from pandas._libs.lib import is_list_like -from pandas._typing import Label, StorageOptions +from pandas._typing import IndexLabel, StorageOptions from pandas.util._decorators import doc from pandas.core.dtypes import missing @@ -440,10 +450,10 @@ def __init__( df, na_rep: str = "", float_format: Optional[str] = None, - cols: Optional[Sequence[Label]] = None, - header: Union[Sequence[Label], bool] = True, + cols: Optional[Sequence[Hashable]] = None, + header: Union[Sequence[Hashable], bool] = True, index: bool = True, - index_label: Optional[Union[Label, Sequence[Label]]] = None, + index_label: Optional[IndexLabel] = None, merge_cells: bool = False, inf_rep: str = "inf", style_converter: Optional[Callable] = None, diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 6426f9e780eef..2c17551a7c3b9 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -18,6 +18,7 @@ Any, Callable, Dict, + Hashable, Iterable, List, Mapping, @@ -47,7 +48,6 @@ FloatFormatType, FormattersType, IndexLabel, - Label, StorageOptions, ) @@ -1032,7 +1032,7 @@ def to_csv( path_or_buf: Optional[FilePathOrBuffer[str]] = None, encoding: Optional[str] = None, sep: str = ",", - columns: Optional[Sequence[Label]] = None, + columns: Optional[Sequence[Hashable]] = None, index_label: Optional[IndexLabel] = None, mode: str = "w", compression: CompressionOptions = "infer", diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 6ed31f38893dc..b6c1336ede597 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -11,6 +11,7 @@ Callable, DefaultDict, Dict, + Hashable, List, Optional, Sequence, @@ -24,7 +25,7 @@ from pandas._config import get_option from pandas._libs import lib -from pandas._typing import Axis, FrameOrSeries, FrameOrSeriesUnion, Label +from pandas._typing import Axis, FrameOrSeries, FrameOrSeriesUnion, IndexLabel from pandas.compat._optional import import_optional_dependency from pandas.util._decorators import doc @@ -215,10 +216,10 @@ def to_excel( sheet_name: str = "Sheet1", na_rep: str = "", float_format: Optional[str] = None, - columns: Optional[Sequence[Label]] = None, - header: Union[Sequence[Label], bool] = True, + columns: Optional[Sequence[Hashable]] = None, + header: Union[Sequence[Hashable], bool] = True, index: bool = True, - index_label: Optional[Union[Label, Sequence[Label]]] = None, + index_label: Optional[IndexLabel] = None, startrow: int = 0, startcol: int = 0, engine: Optional[str] = None, @@ -1139,7 +1140,7 @@ def _highlight_null(v, null_color: str) -> str: def highlight_null( self, null_color: str = "red", - subset: Optional[Union[Label, Sequence[Label]]] = None, + subset: Optional[IndexLabel] = None, ) -> "Styler": """ Shade the background ``null_color`` for missing values. diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index d2b02038f8b78..d1275590306ef 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -14,6 +14,7 @@ Any, Callable, Dict, + Hashable, List, Optional, Sequence, @@ -29,14 +30,7 @@ from pandas._libs import lib, writers as libwriters from pandas._libs.tslibs import timezones -from pandas._typing import ( - ArrayLike, - DtypeArg, - FrameOrSeries, - FrameOrSeriesUnion, - Label, - Shape, -) +from pandas._typing import ArrayLike, DtypeArg, FrameOrSeries, FrameOrSeriesUnion, Shape from pandas.compat._optional import import_optional_dependency from pandas.compat.pickle_compat import patch_pickle from pandas.errors import PerformanceWarning @@ -2935,7 +2929,7 @@ def read_multi_index( levels = [] codes = [] - names: List[Label] = [] + names: List[Hashable] = [] for i in range(nlevels): level_key = f"{key}_level{i}" node = getattr(self.group, level_key) @@ -3084,7 +3078,7 @@ class SeriesFixed(GenericFixed): pandas_kind = "series" attributes = ["name"] - name: Label + name: Hashable @property def shape(self): @@ -3235,7 +3229,7 @@ class Table(Fixed): pandas_kind = "wide_table" format_type: str = "table" # GH#30962 needed by dask table_type: str - levels: Union[int, List[Label]] = 1 + levels: Union[int, List[Hashable]] = 1 is_table = True index_axes: List[IndexCol] @@ -3333,7 +3327,7 @@ def is_multi_index(self) -> bool: def validate_multiindex( self, obj: FrameOrSeriesUnion - ) -> Tuple[DataFrame, List[Label]]: + ) -> Tuple[DataFrame, List[Hashable]]: """ validate that we can store the multi-index; reset and return the new object @@ -3476,7 +3470,7 @@ def get_attrs(self): self.nan_rep = getattr(self.attrs, "nan_rep", None) self.encoding = _ensure_encoding(getattr(self.attrs, "encoding", None)) self.errors = _ensure_decoded(getattr(self.attrs, "errors", "strict")) - self.levels: List[Label] = getattr(self.attrs, "levels", None) or [] + self.levels: List[Hashable] = getattr(self.attrs, "levels", None) or [] self.index_axes = [a for a in self.indexables if a.is_an_indexable] self.values_axes = [a for a in self.indexables if not a.is_an_indexable] @@ -4622,7 +4616,7 @@ class GenericTable(AppendableFrameTable): table_type = "generic_table" ndim = 2 obj_type = DataFrame - levels: List[Label] + levels: List[Hashable] @property def pandas_type(self) -> str: diff --git a/pandas/io/sas/sasreader.py b/pandas/io/sas/sasreader.py index 243218129fda6..d193971a6721e 100644 --- a/pandas/io/sas/sasreader.py +++ b/pandas/io/sas/sasreader.py @@ -2,9 +2,9 @@ Read SAS sas7bdat or xport files. """ from abc import ABCMeta, abstractmethod -from typing import TYPE_CHECKING, Optional, Union, overload +from typing import TYPE_CHECKING, Hashable, Optional, Union, overload -from pandas._typing import FilePathOrBuffer, Label +from pandas._typing import FilePathOrBuffer from pandas.io.common import stringify_path @@ -37,7 +37,7 @@ def __exit__(self, exc_type, exc_value, traceback): def read_sas( filepath_or_buffer: FilePathOrBuffer, format: Optional[str] = ..., - index: Optional[Label] = ..., + index: Optional[Hashable] = ..., encoding: Optional[str] = ..., chunksize: int = ..., iterator: bool = ..., @@ -49,7 +49,7 @@ def read_sas( def read_sas( filepath_or_buffer: FilePathOrBuffer, format: Optional[str] = ..., - index: Optional[Label] = ..., + index: Optional[Hashable] = ..., encoding: Optional[str] = ..., chunksize: None = ..., iterator: bool = ..., @@ -60,7 +60,7 @@ def read_sas( def read_sas( filepath_or_buffer: FilePathOrBuffer, format: Optional[str] = None, - index: Optional[Label] = None, + index: Optional[Hashable] = None, encoding: Optional[str] = None, chunksize: Optional[int] = None, iterator: bool = False, diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 88485f99c07aa..f3a74189eba85 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -16,7 +16,18 @@ from pathlib import Path import struct import sys -from typing import Any, AnyStr, Dict, List, Optional, Sequence, Tuple, Union, cast +from typing import ( + Any, + AnyStr, + Dict, + Hashable, + List, + Optional, + Sequence, + Tuple, + Union, + cast, +) import warnings from dateutil.relativedelta import relativedelta @@ -24,13 +35,7 @@ from pandas._libs.lib import infer_dtype from pandas._libs.writers import max_len_string_array -from pandas._typing import ( - Buffer, - CompressionOptions, - FilePathOrBuffer, - Label, - StorageOptions, -) +from pandas._typing import Buffer, CompressionOptions, FilePathOrBuffer, StorageOptions from pandas.util._decorators import Appender, doc from pandas.core.dtypes.common import ( @@ -1959,7 +1964,7 @@ def _convert_datetime_to_stata_type(fmt: str) -> np.dtype: raise NotImplementedError(f"Format {fmt} not implemented") -def _maybe_convert_to_int_keys(convert_dates: Dict, varlist: List[Label]) -> Dict: +def _maybe_convert_to_int_keys(convert_dates: Dict, varlist: List[Hashable]) -> Dict: new_dict = {} for key in convert_dates: if not convert_dates[key].startswith("%"): # make sure proper fmts @@ -2144,12 +2149,12 @@ def __init__( self, fname: FilePathOrBuffer, data: DataFrame, - convert_dates: Optional[Dict[Label, str]] = None, + convert_dates: Optional[Dict[Hashable, str]] = None, write_index: bool = True, byteorder: Optional[str] = None, time_stamp: Optional[datetime.datetime] = None, data_label: Optional[str] = None, - variable_labels: Optional[Dict[Label, str]] = None, + variable_labels: Optional[Dict[Hashable, str]] = None, compression: CompressionOptions = "infer", storage_options: StorageOptions = None, ): @@ -2170,7 +2175,7 @@ def __init__( self._byteorder = _set_endianness(byteorder) self._fname = fname self.type_converters = {253: np.int32, 252: np.int16, 251: np.int8} - self._converted_names: Dict[Label, str] = {} + self._converted_names: Dict[Hashable, str] = {} def _write(self, to_write: str) -> None: """ @@ -2292,8 +2297,8 @@ def _check_column_names(self, data: DataFrame) -> DataFrame: dates are exported, the variable name is propagated to the date conversion dictionary """ - converted_names: Dict[Label, str] = {} - columns: List[Label] = list(data.columns) + converted_names: Dict[Hashable, str] = {} + columns = list(data.columns) original_columns = columns[:] duplicate_var_id = 0 @@ -3023,18 +3028,18 @@ def __init__( self, fname: FilePathOrBuffer, data: DataFrame, - convert_dates: Optional[Dict[Label, str]] = None, + convert_dates: Optional[Dict[Hashable, str]] = None, write_index: bool = True, byteorder: Optional[str] = None, time_stamp: Optional[datetime.datetime] = None, data_label: Optional[str] = None, - variable_labels: Optional[Dict[Label, str]] = None, - convert_strl: Optional[Sequence[Label]] = None, + variable_labels: Optional[Dict[Hashable, str]] = None, + convert_strl: Optional[Sequence[Hashable]] = None, compression: CompressionOptions = "infer", storage_options: StorageOptions = None, ): # Copy to new list since convert_strl might be modified later - self._convert_strl: List[Label] = [] + self._convert_strl: List[Hashable] = [] if convert_strl is not None: self._convert_strl.extend(convert_strl) @@ -3424,13 +3429,13 @@ def __init__( self, fname: FilePathOrBuffer, data: DataFrame, - convert_dates: Optional[Dict[Label, str]] = None, + convert_dates: Optional[Dict[Hashable, str]] = None, write_index: bool = True, byteorder: Optional[str] = None, time_stamp: Optional[datetime.datetime] = None, data_label: Optional[str] = None, - variable_labels: Optional[Dict[Label, str]] = None, - convert_strl: Optional[Sequence[Label]] = None, + variable_labels: Optional[Dict[Hashable, str]] = None, + convert_strl: Optional[Sequence[Hashable]] = None, version: Optional[int] = None, compression: CompressionOptions = "infer", storage_options: StorageOptions = None, diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index ab8f94596ff1a..597217ec67b0e 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -5,7 +5,7 @@ from pandas._config import get_option -from pandas._typing import Label +from pandas._typing import IndexLabel from pandas.util._decorators import Appender, Substitution from pandas.core.dtypes.common import is_integer, is_list_like @@ -102,7 +102,7 @@ def hist_series( def hist_frame( data: DataFrame, - column: Union[Label, Sequence[Label]] = None, + column: IndexLabel = None, by=None, grid: bool = True, xlabelsize: Optional[int] = None, diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index f0e15c19da5d3..aa8e0665a7310 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1,10 +1,9 @@ -from typing import TYPE_CHECKING, List, Optional, Tuple +from typing import TYPE_CHECKING, Hashable, List, Optional, Tuple import warnings from matplotlib.artist import Artist import numpy as np -from pandas._typing import Label from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly @@ -107,8 +106,8 @@ def __init__( ylim=None, xticks=None, yticks=None, - xlabel: Optional[Label] = None, - ylabel: Optional[Label] = None, + xlabel: Optional[Hashable] = None, + ylabel: Optional[Hashable] = None, sort_columns=False, fontsize=None, secondary_y=False, @@ -170,7 +169,7 @@ def __init__( self.grid = grid self.legend = legend self.legend_handles: List[Artist] = [] - self.legend_labels: List[Label] = [] + self.legend_labels: List[Hashable] = [] self.logx = kwds.pop("logx", False) self.logy = kwds.pop("logy", False) diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index 64078abfd9220..d0c05af5dce8b 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -1,14 +1,12 @@ from __future__ import annotations import random -from typing import TYPE_CHECKING, Dict, List, Optional, Set +from typing import TYPE_CHECKING, Dict, Hashable, List, Optional, Set import matplotlib.lines as mlines import matplotlib.patches as patches import numpy as np -from pandas._typing import Label - from pandas.core.dtypes.missing import notna from pandas.io.formats.printing import pprint_thing @@ -150,7 +148,7 @@ def normalize(series): ax.set_xlim(-1, 1) ax.set_ylim(-1, 1) - to_plot: Dict[Label, List[List]] = {} + to_plot: Dict[Hashable, List[List]] = {} colors = get_standard_colors( num_colors=len(classes), colormap=colormap, color_type="random", color=color )
- [ ] closes #37134 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39107
2021-01-11T14:13:46Z
2021-01-11T17:07:01Z
2021-01-11T17:07:01Z
2021-01-11T18:12:15Z
sync release notes on 1.2.x from master
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index e612c379606ef..e26405c3a332a 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -25,10 +25,10 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``ValueError`` when :class:`DataFrame` has unsorted :class:`MultiIndex` columns and indexer is a scalar (:issue:`38601`) - Fixed regression in :func:`read_excel` with non-rawbyte file handles (:issue:`38788`) - Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) -- Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) - Fixed regression in :meth:`Rolling.skew` and :meth:`Rolling.kurt` modifying the object inplace (:issue:`38908`) - Fixed regression in :meth:`read_csv` and other read functions were the encoding error policy (``errors``) did not default to ``"replace"`` when no encoding was specified (:issue:`38989`) - Fixed regression in :meth:`DataFrame.replace` raising ValueError when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) +- Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) .. ---------------------------------------------------------------------------
PR direct against 1.2.x syncing release notes between 1.2.x and master
https://api.github.com/repos/pandas-dev/pandas/pulls/39105
2021-01-11T13:42:27Z
2021-01-11T14:56:20Z
2021-01-11T14:56:20Z
2021-01-11T14:56:25Z
TYP: fix mypy errors in pandas/core/arraylike.py
diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py index cb185dcf78f63..e17ba45f30d6c 100644 --- a/pandas/core/arraylike.py +++ b/pandas/core/arraylike.py @@ -228,7 +228,7 @@ def _maybe_fallback(ufunc: Callable, method: str, *inputs: Any, **kwargs: Any): return NotImplemented -def array_ufunc(self, ufunc: Callable, method: str, *inputs: Any, **kwargs: Any): +def array_ufunc(self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any): """ Compatibility with numpy ufuncs. @@ -341,9 +341,7 @@ def reconstruct(result): result = result.__finalize__(self) return result - if self.ndim > 1 and ( - len(inputs) > 1 or ufunc.nout > 1 # type: ignore[attr-defined] - ): + if self.ndim > 1 and (len(inputs) > 1 or ufunc.nout > 1): # Just give up on preserving types in the complex case. # In theory we could preserve them for them. # * nout>1 is doable if BlockManager.apply took nout and @@ -367,7 +365,7 @@ def reconstruct(result): # Those can have an axis keyword and thus can't be called block-by-block result = getattr(ufunc, method)(np.asarray(inputs[0]), **kwargs) - if ufunc.nout > 1: # type: ignore[attr-defined] + if ufunc.nout > 1: result = tuple(reconstruct(x) for x in result) else: result = reconstruct(result)
- [ ] xref #37715 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Handle ignored mypy errors in ``pandas/core/arraylike.py``.
https://api.github.com/repos/pandas-dev/pandas/pulls/39104
2021-01-11T13:29:06Z
2021-02-15T16:43:18Z
2021-02-15T16:43:18Z
2021-02-15T16:43:22Z
MOVE: describe to pandas/core/describe.py
diff --git a/pandas/core/describe.py b/pandas/core/describe.py new file mode 100644 index 0000000000000..1b5fbaf0e78f9 --- /dev/null +++ b/pandas/core/describe.py @@ -0,0 +1,205 @@ +""" +Module responsible for execution of NDFrame.describe() method. + +Method NDFrame.describe() delegates actual execution to function describe_ndframe(). +""" + +from typing import TYPE_CHECKING, List, Optional, Sequence, Union +import warnings + +import numpy as np + +from pandas._libs.tslibs import Timestamp +from pandas._typing import FrameOrSeries, Hashable +from pandas.util._validators import validate_percentile + +from pandas.core.dtypes.common import ( + is_bool_dtype, + is_datetime64_any_dtype, + is_numeric_dtype, + is_timedelta64_dtype, +) + +from pandas.core.reshape.concat import concat + +from pandas.io.formats.format import format_percentiles + +if TYPE_CHECKING: + from pandas import Series + + +def describe_ndframe( + *, + obj: FrameOrSeries, + include: Optional[Union[str, Sequence[str]]], + exclude: Optional[Union[str, Sequence[str]]], + datetime_is_numeric: bool, + percentiles: Optional[Sequence[float]], +) -> FrameOrSeries: + """Describe series or dataframe. + + Called from pandas.core.generic.NDFrame.describe() + + Parameters + ---------- + obj: DataFrame or Series + Either dataframe or series to be described. + include : 'all', list-like of dtypes or None (default), optional + A white list of data types to include in the result. Ignored for ``Series``. + exclude : list-like of dtypes or None (default), optional, + A black list of data types to omit from the result. Ignored for ``Series``. + datetime_is_numeric : bool, default False + Whether to treat datetime dtypes as numeric. + percentiles : list-like of numbers, optional + The percentiles to include in the output. All should fall between 0 and 1. + The default is ``[.25, .5, .75]``, which returns the 25th, 50th, and + 75th percentiles. + + Returns + ------- + Dataframe or series description. + """ + if obj.ndim == 2 and obj.columns.size == 0: + raise ValueError("Cannot describe a DataFrame without columns") + + if percentiles is not None: + # explicit conversion of `percentiles` to list + percentiles = list(percentiles) + + # get them all to be in [0, 1] + validate_percentile(percentiles) + + # median should always be included + if 0.5 not in percentiles: + percentiles.append(0.5) + percentiles = np.asarray(percentiles) + else: + percentiles = np.array([0.25, 0.5, 0.75]) + + # sort and check for duplicates + unique_pcts = np.unique(percentiles) + assert percentiles is not None + if len(unique_pcts) < len(percentiles): + raise ValueError("percentiles cannot contain duplicates") + percentiles = unique_pcts + + formatted_percentiles = format_percentiles(percentiles) + + def describe_numeric_1d(series) -> "Series": + from pandas import Series + + stat_index = ["count", "mean", "std", "min"] + formatted_percentiles + ["max"] + d = ( + [series.count(), series.mean(), series.std(), series.min()] + + series.quantile(percentiles).tolist() + + [series.max()] + ) + return Series(d, index=stat_index, name=series.name) + + def describe_categorical_1d(data) -> "Series": + names = ["count", "unique"] + objcounts = data.value_counts() + count_unique = len(objcounts[objcounts != 0]) + result = [data.count(), count_unique] + dtype = None + if result[1] > 0: + top, freq = objcounts.index[0], objcounts.iloc[0] + if is_datetime64_any_dtype(data.dtype): + if obj.ndim == 1: + stacklevel = 5 + else: + stacklevel = 6 + warnings.warn( + "Treating datetime data as categorical rather than numeric in " + "`.describe` is deprecated and will be removed in a future " + "version of pandas. Specify `datetime_is_numeric=True` to " + "silence this warning and adopt the future behavior now.", + FutureWarning, + stacklevel=stacklevel, + ) + tz = data.dt.tz + asint = data.dropna().values.view("i8") + top = Timestamp(top) + if top.tzinfo is not None and tz is not None: + # Don't tz_localize(None) if key is already tz-aware + top = top.tz_convert(tz) + else: + top = top.tz_localize(tz) + names += ["top", "freq", "first", "last"] + result += [ + top, + freq, + Timestamp(asint.min(), tz=tz), + Timestamp(asint.max(), tz=tz), + ] + else: + names += ["top", "freq"] + result += [top, freq] + + # If the DataFrame is empty, set 'top' and 'freq' to None + # to maintain output shape consistency + else: + names += ["top", "freq"] + result += [np.nan, np.nan] + dtype = "object" + + from pandas import Series + + return Series(result, index=names, name=data.name, dtype=dtype) + + def describe_timestamp_1d(data) -> "Series": + # GH-30164 + from pandas import Series + + stat_index = ["count", "mean", "min"] + formatted_percentiles + ["max"] + d = ( + [data.count(), data.mean(), data.min()] + + data.quantile(percentiles).tolist() + + [data.max()] + ) + return Series(d, index=stat_index, name=data.name) + + def describe_1d(data) -> "Series": + if is_bool_dtype(data.dtype): + return describe_categorical_1d(data) + elif is_numeric_dtype(data): + return describe_numeric_1d(data) + elif is_datetime64_any_dtype(data.dtype) and datetime_is_numeric: + return describe_timestamp_1d(data) + elif is_timedelta64_dtype(data.dtype): + return describe_numeric_1d(data) + else: + return describe_categorical_1d(data) + + if obj.ndim == 1: + # Incompatible return value type + # (got "Series", expected "FrameOrSeries") [return-value] + return describe_1d(obj) # type:ignore[return-value] + elif (include is None) and (exclude is None): + # when some numerics are found, keep only numerics + default_include = [np.number] + if datetime_is_numeric: + default_include.append("datetime") + data = obj.select_dtypes(include=default_include) + if len(data.columns) == 0: + data = obj + elif include == "all": + if exclude is not None: + msg = "exclude must be None when include is 'all'" + raise ValueError(msg) + data = obj + else: + data = obj.select_dtypes(include=include, exclude=exclude) + + ldesc = [describe_1d(s) for _, s in data.items()] + # set a convenient order for rows + names: List[Hashable] = [] + ldesc_indexes = sorted((x.index for x in ldesc), key=len) + for idxnames in ldesc_indexes: + for name in idxnames: + if name not in names: + names.append(name) + + d = concat([x.reindex(names, copy=False) for x in ldesc], axis=1, sort=False) + d.columns = data.columns.copy() + return d diff --git a/pandas/core/generic.py b/pandas/core/generic.py index ce1e962614c58..0daeed0e393e6 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -57,11 +57,7 @@ from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError, InvalidIndexError from pandas.util._decorators import doc, rewrite_axis_style_signature -from pandas.util._validators import ( - validate_bool_kwarg, - validate_fillna_kwargs, - validate_percentile, -) +from pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs from pandas.core.dtypes.common import ( ensure_int64, @@ -95,6 +91,7 @@ from pandas.core.base import PandasObject, SelectionMixin import pandas.core.common as com from pandas.core.construction import create_series_with_explicit_dtype, extract_array +from pandas.core.describe import describe_ndframe from pandas.core.flags import Flags from pandas.core.indexes import base as ibase from pandas.core.indexes.api import ( @@ -113,11 +110,7 @@ from pandas.core.window import Expanding, ExponentialMovingWindow, Rolling, Window from pandas.io.formats import format as fmt -from pandas.io.formats.format import ( - DataFrameFormatter, - DataFrameRenderer, - format_percentiles, -) +from pandas.io.formats.format import DataFrameFormatter, DataFrameRenderer from pandas.io.formats.printing import pprint_thing if TYPE_CHECKING: @@ -10084,145 +10077,13 @@ def describe( 75% NaN 2.5 max NaN 3.0 """ - if self.ndim == 2 and self.columns.size == 0: - raise ValueError("Cannot describe a DataFrame without columns") - - if percentiles is not None: - # explicit conversion of `percentiles` to list - percentiles = list(percentiles) - - # get them all to be in [0, 1] - validate_percentile(percentiles) - - # median should always be included - if 0.5 not in percentiles: - percentiles.append(0.5) - percentiles = np.asarray(percentiles) - else: - percentiles = np.array([0.25, 0.5, 0.75]) - - # sort and check for duplicates - unique_pcts = np.unique(percentiles) - if len(unique_pcts) < len(percentiles): - raise ValueError("percentiles cannot contain duplicates") - percentiles = unique_pcts - - formatted_percentiles = format_percentiles(percentiles) - - def describe_numeric_1d(series) -> "Series": - stat_index = ( - ["count", "mean", "std", "min"] + formatted_percentiles + ["max"] - ) - d = ( - [series.count(), series.mean(), series.std(), series.min()] - + series.quantile(percentiles).tolist() - + [series.max()] - ) - return pd.Series(d, index=stat_index, name=series.name) - - def describe_categorical_1d(data) -> "Series": - names = ["count", "unique"] - objcounts = data.value_counts() - count_unique = len(objcounts[objcounts != 0]) - result = [data.count(), count_unique] - dtype = None - if result[1] > 0: - top, freq = objcounts.index[0], objcounts.iloc[0] - if is_datetime64_any_dtype(data.dtype): - if self.ndim == 1: - stacklevel = 4 - else: - stacklevel = 5 - warnings.warn( - "Treating datetime data as categorical rather than numeric in " - "`.describe` is deprecated and will be removed in a future " - "version of pandas. Specify `datetime_is_numeric=True` to " - "silence this warning and adopt the future behavior now.", - FutureWarning, - stacklevel=stacklevel, - ) - tz = data.dt.tz - asint = data.dropna().values.view("i8") - top = Timestamp(top) - if top.tzinfo is not None and tz is not None: - # Don't tz_localize(None) if key is already tz-aware - top = top.tz_convert(tz) - else: - top = top.tz_localize(tz) - names += ["top", "freq", "first", "last"] - result += [ - top, - freq, - Timestamp(asint.min(), tz=tz), - Timestamp(asint.max(), tz=tz), - ] - else: - names += ["top", "freq"] - result += [top, freq] - - # If the DataFrame is empty, set 'top' and 'freq' to None - # to maintain output shape consistency - else: - names += ["top", "freq"] - result += [np.nan, np.nan] - dtype = "object" - - return pd.Series(result, index=names, name=data.name, dtype=dtype) - - def describe_timestamp_1d(data) -> "Series": - # GH-30164 - stat_index = ["count", "mean", "min"] + formatted_percentiles + ["max"] - d = ( - [data.count(), data.mean(), data.min()] - + data.quantile(percentiles).tolist() - + [data.max()] - ) - return pd.Series(d, index=stat_index, name=data.name) - - def describe_1d(data) -> "Series": - if is_bool_dtype(data.dtype): - return describe_categorical_1d(data) - elif is_numeric_dtype(data): - return describe_numeric_1d(data) - elif is_datetime64_any_dtype(data.dtype) and datetime_is_numeric: - return describe_timestamp_1d(data) - elif is_timedelta64_dtype(data.dtype): - return describe_numeric_1d(data) - else: - return describe_categorical_1d(data) - - if self.ndim == 1: - # Incompatible return value type - # (got "Series", expected "FrameOrSeries") [return-value] - return describe_1d(self) # type:ignore[return-value] - elif (include is None) and (exclude is None): - # when some numerics are found, keep only numerics - default_include = [np.number] - if datetime_is_numeric: - default_include.append("datetime") - data = self.select_dtypes(include=default_include) - if len(data.columns) == 0: - data = self - elif include == "all": - if exclude is not None: - msg = "exclude must be None when include is 'all'" - raise ValueError(msg) - data = self - else: - data = self.select_dtypes(include=include, exclude=exclude) - - ldesc = [describe_1d(s) for _, s in data.items()] - # set a convenient order for rows - names: List[Hashable] = [] - ldesc_indexes = sorted((x.index for x in ldesc), key=len) - for idxnames in ldesc_indexes: - for name in idxnames: - if name not in names: - names.append(name) - - d = pd.concat([x.reindex(names, copy=False) for x in ldesc], axis=1, sort=False) - d.columns = data.columns.copy() - return d + return describe_ndframe( + obj=self, + include=include, + exclude=exclude, + datetime_is_numeric=datetime_is_numeric, + percentiles=percentiles, + ) @final def pct_change(
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Move ``describe`` functionality to a separate module and prepare for the further refactor/simplification (xref #36833). - Created new module ``pandas/core/describe.py`` - Delegate the functionality of ``NDFrame.describe`` to function ``describe_ndframe`` in the new module
https://api.github.com/repos/pandas-dev/pandas/pulls/39102
2021-01-11T13:01:20Z
2021-01-11T19:58:28Z
2021-01-11T19:58:28Z
2021-01-12T06:26:12Z
TST: add test for describe include/exclude
diff --git a/pandas/tests/frame/methods/test_describe.py b/pandas/tests/frame/methods/test_describe.py index b7692eee16bf8..148263bad0eb0 100644 --- a/pandas/tests/frame/methods/test_describe.py +++ b/pandas/tests/frame/methods/test_describe.py @@ -1,4 +1,5 @@ import numpy as np +import pytest import pandas as pd from pandas import Categorical, DataFrame, Series, Timestamp, date_range @@ -360,3 +361,13 @@ def test_describe_percentiles_integer_idx(self): ], ) tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("exclude", ["x", "y", ["x", "y"], ["x", "z"]]) + def test_describe_when_include_all_exclude_not_allowed(self, exclude): + """ + When include is 'all', then setting exclude != None is not allowed. + """ + df = DataFrame({"x": [1], "y": [2], "z": [3]}) + msg = "exclude must be None when include is 'all'" + with pytest.raises(ValueError, match=msg): + df.describe(include="all", exclude=exclude)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Added test for checking that if include is 'all' then setting exclude will raise ValueError. This case was not covered.
https://api.github.com/repos/pandas-dev/pandas/pulls/39101
2021-01-11T12:33:50Z
2021-01-11T14:15:27Z
2021-01-11T14:15:26Z
2021-01-11T14:15:30Z
BUG: reindex raising TypeError with timezone aware index and tolerance for ffill and bfill
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index cb97fdeccd579..3d19f5ebe4381 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -247,6 +247,7 @@ Indexing - Bug in :meth:`CategoricalIndex.get_indexer` failing to raise ``InvalidIndexError`` when non-unique (:issue:`38372`) - Bug in inserting many new columns into a :class:`DataFrame` causing incorrect subsequent indexing behavior (:issue:`38380`) - Bug in :meth:`DataFrame.loc`, :meth:`Series.loc`, :meth:`DataFrame.__getitem__` and :meth:`Series.__getitem__` returning incorrect elements for non-monotonic :class:`DatetimeIndex` for string slices (:issue:`33146`) +- Bug in :meth:`DataFrame.reindex` and :meth:`Series.reindex` with timezone aware indexes raising ``TypeError`` for ``method="ffill"`` and ``method="bfill"`` and specified ``tolerance`` (:issue:`38566`) - Bug in :meth:`DataFrame.__setitem__` raising ``ValueError`` with empty :class:`DataFrame` and specified columns for string indexer and non empty :class:`DataFrame` to set (:issue:`38831`) - Bug in :meth:`DataFrame.iloc.__setitem__` and :meth:`DataFrame.loc.__setitem__` with mixed dtypes when setting with a dictionary value (:issue:`38335`) - Bug in :meth:`DataFrame.loc` dropping levels of :class:`MultiIndex` when :class:`DataFrame` used as input has only one row (:issue:`10521`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index a2e9737f305ba..b51c165ccfde6 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3378,7 +3378,7 @@ def _get_fill_indexer( else: indexer = self._get_fill_indexer_searchsorted(target, method, limit) if tolerance is not None and len(self): - indexer = self._filter_indexer_tolerance(target_values, indexer, tolerance) + indexer = self._filter_indexer_tolerance(target._values, indexer, tolerance) return indexer @final diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py index 3e4e16955b44a..c49375758345c 100644 --- a/pandas/tests/frame/methods/test_reindex.py +++ b/pandas/tests/frame/methods/test_reindex.py @@ -177,6 +177,21 @@ def test_reindex_frame_add_nat(self): assert mask[-5:].all() assert not mask[:-5].any() + @pytest.mark.parametrize( + "method, exp_values", + [("ffill", [0, 1, 2, 3]), ("bfill", [1.0, 2.0, 3.0, np.nan])], + ) + def test_reindex_frame_tz_ffill_bfill(self, frame_or_series, method, exp_values): + # GH#38566 + obj = frame_or_series( + [0, 1, 2, 3], + index=date_range("2020-01-01 00:00:00", periods=4, freq="H", tz="UTC"), + ) + new_index = date_range("2020-01-01 00:01:00", periods=4, freq="H", tz="UTC") + result = obj.reindex(new_index, method=method, tolerance=pd.Timedelta("1 hour")) + expected = frame_or_series(exp_values, index=new_index) + tm.assert_equal(result, expected) + def test_reindex_limit(self): # GH 28631 data = [["A", "A", "A"], ["B", "B", "B"], ["C", "C", "C"], ["D", "D", "D"]]
- [x] closes #38566 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry Is there a better place for these tests? EDIT: Technically a regression, but since it persists since 1.0.0 is it worth backporting?
https://api.github.com/repos/pandas-dev/pandas/pulls/39095
2021-01-10T22:20:57Z
2021-01-11T14:00:35Z
2021-01-11T14:00:35Z
2021-01-12T21:54:49Z
REF: implement dtypes.cast.can_hold_element
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 6c8711d940558..55755724f1ace 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1880,3 +1880,46 @@ def validate_numeric_casting(dtype: np.dtype, value: Scalar) -> None: raise ValueError( f"Cannot assign {type(value).__name__} to float/integer series" ) + + +def can_hold_element(dtype: np.dtype, element: Any) -> bool: + """ + Can we do an inplace setitem with this element in an array with this dtype? + + Parameters + ---------- + dtype : np.dtype + element : Any + + Returns + ------- + bool + """ + tipo = maybe_infer_dtype_type(element) + + if dtype.kind in ["i", "u"]: + if tipo is not None: + return tipo.kind in ["i", "u"] and dtype.itemsize >= tipo.itemsize + + # We have not inferred an integer from the dtype + # check if we have a builtin int or a float equal to an int + return is_integer(element) or (is_float(element) and element.is_integer()) + + elif dtype.kind == "f": + if tipo is not None: + return tipo.kind in ["f", "i", "u"] + return lib.is_integer(element) or lib.is_float(element) + + elif dtype.kind == "c": + if tipo is not None: + return tipo.kind in ["c", "f", "i", "u"] + return ( + lib.is_integer(element) or lib.is_complex(element) or lib.is_float(element) + ) + + elif dtype.kind == "b": + if tipo is not None: + return tipo.kind == "b" + return lib.is_bool(element) + + raise NotImplementedError(dtype) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index bb83c4543a989..9eb4bdc5dbae3 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -21,6 +21,7 @@ from pandas.core.dtypes.cast import ( astype_dt64_to_dt64tz, astype_nansafe, + can_hold_element, convert_scalar_for_putitemlike, find_common_type, infer_dtype_from, @@ -40,7 +41,6 @@ is_datetime64tz_dtype, is_dtype_equal, is_extension_array_dtype, - is_float, is_integer, is_list_like, is_object_dtype, @@ -1906,24 +1906,14 @@ class NumericBlock(Block): is_numeric = True _can_hold_na = True + def _can_hold_element(self, element: Any) -> bool: + return can_hold_element(self.dtype, element) + class FloatBlock(NumericBlock): __slots__ = () is_float = True - def _can_hold_element(self, element: Any) -> bool: - tipo = maybe_infer_dtype_type(element) - if tipo is not None: - return issubclass(tipo.type, (np.floating, np.integer)) and not issubclass( - tipo.type, np.timedelta64 - ) - return isinstance( - element, (float, int, np.floating, np.int_) - ) and not isinstance( - element, - (bool, np.bool_, np.timedelta64), - ) - def to_native_types( self, na_rep="", float_format=None, decimal=".", quoting=None, **kwargs ): @@ -1962,32 +1952,12 @@ class ComplexBlock(NumericBlock): __slots__ = () is_complex = True - def _can_hold_element(self, element: Any) -> bool: - tipo = maybe_infer_dtype_type(element) - if tipo is not None: - return tipo.kind in ["c", "f", "i", "u"] - return ( - lib.is_integer(element) or lib.is_complex(element) or lib.is_float(element) - ) - class IntBlock(NumericBlock): __slots__ = () is_integer = True _can_hold_na = False - def _can_hold_element(self, element: Any) -> bool: - tipo = maybe_infer_dtype_type(element) - if tipo is not None: - return ( - issubclass(tipo.type, np.integer) - and not issubclass(tipo.type, np.timedelta64) - and self.dtype.itemsize >= tipo.itemsize - ) - # We have not inferred an integer from the dtype - # check if we have a builtin int or a float equal to an int - return is_integer(element) or (is_float(element) and element.is_integer()) - class DatetimeLikeBlockMixin(Block): """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock.""" @@ -2284,12 +2254,6 @@ class BoolBlock(NumericBlock): is_bool = True _can_hold_na = False - def _can_hold_element(self, element: Any) -> bool: - tipo = maybe_infer_dtype_type(element) - if tipo is not None: - return issubclass(tipo.type, np.bool_) - return isinstance(element, (bool, np.bool_)) - class ObjectBlock(Block): __slots__ = ()
Passes the tests added by #39086, gets us close to collapsing the NumericBlock subclasses and just using NumericBlock directly.
https://api.github.com/repos/pandas-dev/pandas/pulls/39094
2021-01-10T20:24:47Z
2021-01-11T19:59:08Z
2021-01-11T19:59:08Z
2021-01-11T21:52:28Z
TYP: NDFrame.pipe, GroupBy.pipe etc.
diff --git a/pandas/core/common.py b/pandas/core/common.py index a6514b5167460..e23091b2efa45 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -8,7 +8,18 @@ import contextlib from functools import partial import inspect -from typing import Any, Collection, Iterable, Iterator, List, Optional, Union, cast +from typing import ( + Any, + Callable, + Collection, + Iterable, + Iterator, + List, + Optional, + Tuple, + Union, + cast, +) import warnings import numpy as np @@ -405,7 +416,9 @@ def random_state(state=None): ) -def pipe(obj, func, *args, **kwargs): +def pipe( + obj, func: Union[Callable[..., T], Tuple[Callable[..., T], str]], *args, **kwargs +) -> T: """ Apply a function ``func`` to object ``obj`` either by passing obj as the first argument to the function or, in the case that the func is a tuple, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2f4340c17c5a7..9508d98d3817b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -49,6 +49,7 @@ NpDtype, Renamer, StorageOptions, + T, TimedeltaConvertibleTypes, TimestampConvertibleTypes, ValueKeyFunc, @@ -5356,7 +5357,12 @@ def sample( @final @doc(klass=_shared_doc_kwargs["klass"]) - def pipe(self, func, *args, **kwargs): + def pipe( + self, + func: Union[Callable[..., T], Tuple[Callable[..., T], str]], + *args, + **kwargs, + ) -> T: r""" Apply func(self, \*args, \*\*kwargs). diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index aef4c036abc65..741de5e23f9bc 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -6,6 +6,7 @@ class providing the base-class of operations. (defined in pandas.core.groupby.generic) expose these user-facing objects to provide specific functionality. """ +from __future__ import annotations from contextlib import contextmanager import datetime @@ -45,6 +46,7 @@ class providing the base-class of operations. IndexLabel, Label, Scalar, + T, final, ) from pandas.compat.numpy import function as nv @@ -476,7 +478,7 @@ def f(self): @contextmanager -def group_selection_context(groupby: "BaseGroupBy") -> Iterator["BaseGroupBy"]: +def group_selection_context(groupby: BaseGroupBy) -> Iterator[BaseGroupBy]: """ Set / reset the group_selection_context. """ @@ -724,8 +726,8 @@ def _set_group_selection(self) -> None: @final def _set_result_index_ordered( - self, result: "OutputFrameOrSeries" - ) -> "OutputFrameOrSeries": + self, result: OutputFrameOrSeries + ) -> OutputFrameOrSeries: # set the result index on the passed values object and # return the new object, xref 8046 @@ -790,7 +792,12 @@ def __getattr__(self, attr: str): ), ) @Appender(_pipe_template) - def pipe(self, func, *args, **kwargs): + def pipe( + self, + func: Union[Callable[..., T], Tuple[Callable[..., T], str]], + *args, + **kwargs, + ) -> T: return com.pipe(self, func, *args, **kwargs) plot = property(GroupByPlot) @@ -3058,7 +3065,7 @@ def get_groupby( by: Optional[_KeysArgType] = None, axis: int = 0, level=None, - grouper: "Optional[ops.BaseGrouper]" = None, + grouper: Optional[ops.BaseGrouper] = None, exclusions=None, selection=None, as_index: bool = True, diff --git a/pandas/core/resample.py b/pandas/core/resample.py index e432ec6cb54a2..f6c1da723a1d9 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1,7 +1,9 @@ +from __future__ import annotations + import copy from datetime import timedelta from textwrap import dedent -from typing import Dict, Optional, Union, no_type_check +from typing import Callable, Dict, Optional, Tuple, Union, no_type_check import numpy as np @@ -14,7 +16,7 @@ Timestamp, to_offset, ) -from pandas._typing import TimedeltaConvertibleTypes, TimestampConvertibleTypes +from pandas._typing import T, TimedeltaConvertibleTypes, TimestampConvertibleTypes from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, Substitution, doc @@ -231,7 +233,12 @@ def _assure_grouper(self): 2012-08-04 1""", ) @Appender(_pipe_template) - def pipe(self, func, *args, **kwargs): + def pipe( + self, + func: Union[Callable[..., T], Tuple[Callable[..., T], str]], + *args, + **kwargs, + ) -> T: return super().pipe(func, *args, **kwargs) _agg_see_also_doc = dedent(
Type up `pipe` function and methods. This allows type checkers to understand the return value type from pipes, which is nice.
https://api.github.com/repos/pandas-dev/pandas/pulls/39093
2021-01-10T18:10:43Z
2021-01-15T10:55:45Z
2021-01-15T10:55:45Z
2021-01-15T14:05:49Z
CLN: Numpy compat functions namespace
diff --git a/pandas/__init__.py b/pandas/__init__.py index cc5d835a52833..2b64100075987 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -19,7 +19,7 @@ del hard_dependencies, dependency, missing_dependencies # numpy compat -from pandas.compat.numpy import ( +from pandas.compat import ( np_version_under1p17 as _np_version_under1p17, np_version_under1p18 as _np_version_under1p18, is_numpy_dev as _is_numpy_dev, diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 2ac9b9e2c875c..eb6cf4f9d7d85 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -12,6 +12,15 @@ import warnings from pandas._typing import F +from pandas.compat.numpy import ( + is_numpy_dev, + np_array_datetime64_compat, + np_datetime64_compat, + np_version_under1p17, + np_version_under1p18, + np_version_under1p19, + np_version_under1p20, +) PY38 = sys.version_info >= (3, 8) PY39 = sys.version_info >= (3, 9) @@ -118,3 +127,14 @@ def get_lzma_file(lzma): "might be required to solve this issue." ) return lzma.LZMAFile + + +__all__ = [ + "is_numpy_dev", + "np_array_datetime64_compat", + "np_datetime64_compat", + "np_version_under1p17", + "np_version_under1p18", + "np_version_under1p19", + "np_version_under1p20", +] diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py index a2444b7ba5a0d..1d8077da76469 100644 --- a/pandas/compat/numpy/__init__.py +++ b/pandas/compat/numpy/__init__.py @@ -10,8 +10,8 @@ _nlv = LooseVersion(_np_version) 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") +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" diff --git a/pandas/core/array_algos/masked_reductions.py b/pandas/core/array_algos/masked_reductions.py index ec0f2c61e0a29..553cdc557ec95 100644 --- a/pandas/core/array_algos/masked_reductions.py +++ b/pandas/core/array_algos/masked_reductions.py @@ -8,7 +8,7 @@ import numpy as np from pandas._libs import missing as libmissing -from pandas.compat.numpy import np_version_under1p17 +from pandas.compat import np_version_under1p17 from pandas.core.nanops import check_below_min_count diff --git a/pandas/core/common.py b/pandas/core/common.py index e23091b2efa45..aa24e12bf2cf1 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -26,7 +26,7 @@ from pandas._libs import lib from pandas._typing import AnyArrayLike, NpDtype, Scalar, T -from pandas.compat.numpy import np_version_under1p18 +from pandas.compat import np_version_under1p18 from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike from pandas.core.dtypes.common import ( diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index a3d30cf0bc3c6..b2d88b3556388 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -12,7 +12,7 @@ from pandas._libs.tslibs.conversion import localize_pydatetime from pandas._libs.tslibs.offsets import shift_months -from pandas.compat.numpy import np_datetime64_compat +from pandas.compat import np_datetime64_compat from pandas.errors import PerformanceWarning import pandas as pd diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py index 8ba984e649e35..0c1b10f66a73b 100644 --- a/pandas/tests/arrays/integer/test_arithmetic.py +++ b/pandas/tests/arrays/integer/test_arithmetic.py @@ -3,7 +3,7 @@ import numpy as np import pytest -from pandas.compat.numpy import _np_version_under1p20 +from pandas.compat import np_version_under1p20 import pandas as pd import pandas._testing as tm @@ -208,7 +208,7 @@ def test_arith_coerce_scalar(data, all_arithmetic_operators): expected = op(s.astype(float), other) expected = expected.astype("Float64") # rfloordiv results in nan instead of inf - if all_arithmetic_operators == "__rfloordiv__" and _np_version_under1p20: + if all_arithmetic_operators == "__rfloordiv__" and np_version_under1p20: # for numpy 1.20 https://github.com/numpy/numpy/pull/16161 # updated floordiv, now matches our behavior defined in core.ops mask = ( diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py index 61f4e3e50d09d..013814681b5f6 100644 --- a/pandas/tests/arrays/sparse/test_arithmetics.py +++ b/pandas/tests/arrays/sparse/test_arithmetics.py @@ -3,7 +3,7 @@ import numpy as np import pytest -from pandas.compat.numpy import _np_version_under1p20 +from pandas.compat import np_version_under1p20 import pandas as pd import pandas._testing as tm @@ -122,7 +122,7 @@ def test_float_scalar( ): op = all_arithmetic_functions - if not _np_version_under1p20: + if not np_version_under1p20: if op in [operator.floordiv, ops.rfloordiv]: mark = pytest.mark.xfail(strict=False, reason="GH#38172") request.node.add_marker(mark) @@ -169,7 +169,7 @@ def test_float_same_index_with_nans( # when sp_index are the same op = all_arithmetic_functions - if not _np_version_under1p20: + if not np_version_under1p20: if op in [operator.floordiv, ops.rfloordiv]: mark = pytest.mark.xfail(strict=False, reason="GH#38172") request.node.add_marker(mark) @@ -349,7 +349,7 @@ def test_bool_array_logical(self, kind, fill_value): def test_mixed_array_float_int(self, kind, mix, all_arithmetic_functions, request): op = all_arithmetic_functions - if not _np_version_under1p20: + if not np_version_under1p20: if op in [operator.floordiv, ops.rfloordiv] and mix: mark = pytest.mark.xfail(strict=True, reason="GH#38172") request.node.add_marker(mark) diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 36a52e5802396..d42bfca1271aa 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -5,7 +5,7 @@ import pytest from pandas._libs import NaT, OutOfBoundsDatetime, Timestamp -from pandas.compat.numpy import np_version_under1p18 +from pandas.compat import np_version_under1p18 import pandas as pd from pandas import DatetimeIndex, Index, Period, PeriodIndex, TimedeltaIndex diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py index e9713e38f9874..4151781f0dbf5 100644 --- a/pandas/tests/base/test_value_counts.py +++ b/pandas/tests/base/test_value_counts.py @@ -6,7 +6,7 @@ import pytest from pandas._libs import iNaT -from pandas.compat.numpy import np_array_datetime64_compat +from pandas.compat import np_array_datetime64_compat from pandas.core.dtypes.common import needs_i8_conversion diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 3e16ec134db46..37ee61417eeab 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -8,8 +8,7 @@ import numpy as np import pytest -from pandas.compat import is_platform_windows -from pandas.compat.numpy import np_version_under1p17 +from pandas.compat import is_platform_windows, np_version_under1p17 from pandas.errors import PerformanceWarning import pandas.util._test_decorators as td diff --git a/pandas/tests/frame/methods/test_sample.py b/pandas/tests/frame/methods/test_sample.py index 6c1c352d8286c..e17c14940746d 100644 --- a/pandas/tests/frame/methods/test_sample.py +++ b/pandas/tests/frame/methods/test_sample.py @@ -1,7 +1,7 @@ import numpy as np import pytest -from pandas.compat.numpy import np_version_under1p17 +from pandas.compat import np_version_under1p17 from pandas import DataFrame, Series import pandas._testing as tm diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 6a0f86e133752..a6aaf3a6af750 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.numpy import _np_version_under1p19 +from pandas.compat import np_version_under1p19 from pandas.core.dtypes.common import is_integer_dtype from pandas.core.dtypes.dtypes import DatetimeTZDtype, IntervalDtype, PeriodDtype @@ -149,7 +149,7 @@ def test_constructor_dtype_list_data(self): assert df.loc[1, 0] is None assert df.loc[0, 1] == "2" - @pytest.mark.skipif(_np_version_under1p19, reason="NumPy change.") + @pytest.mark.skipif(np_version_under1p19, reason="NumPy change.") def test_constructor_list_of_2d_raises(self): # https://github.com/pandas-dev/pandas/issues/32289 a = DataFrame() diff --git a/pandas/tests/indexes/multi/test_analytics.py b/pandas/tests/indexes/multi/test_analytics.py index 25e2f6a3777d1..e842fafda0327 100644 --- a/pandas/tests/indexes/multi/test_analytics.py +++ b/pandas/tests/indexes/multi/test_analytics.py @@ -1,7 +1,7 @@ import numpy as np import pytest -from pandas.compat.numpy import np_version_under1p17 +from pandas.compat import np_version_under1p17 import pandas as pd from pandas import Index, MultiIndex, date_range, period_range diff --git a/pandas/tests/indexes/period/test_searchsorted.py b/pandas/tests/indexes/period/test_searchsorted.py index 6ffdbbfcd2ce6..5e1a3b899755d 100644 --- a/pandas/tests/indexes/period/test_searchsorted.py +++ b/pandas/tests/indexes/period/test_searchsorted.py @@ -2,7 +2,7 @@ import pytest from pandas._libs.tslibs import IncompatibleFrequency -from pandas.compat.numpy import np_version_under1p18 +from pandas.compat import np_version_under1p18 from pandas import NaT, Period, PeriodIndex, Series, array import pandas._testing as tm diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 1eca7f7a5d261..ad15bfa335acc 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -9,8 +9,7 @@ import pytest from pandas._libs.tslib import Timestamp -from pandas.compat import IS64 -from pandas.compat.numpy import np_datetime64_compat +from pandas.compat import IS64, np_datetime64_compat from pandas.util._test_decorators import async_mark import pandas as pd diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py index 47f7b7f37cf48..f7f6456f736c0 100644 --- a/pandas/tests/indexes/test_numpy_compat.py +++ b/pandas/tests/indexes/test_numpy_compat.py @@ -1,7 +1,7 @@ import numpy as np import pytest -from pandas.compat.numpy import np_version_under1p17, np_version_under1p18 +from pandas.compat import np_version_under1p17, np_version_under1p18 from pandas import ( DatetimeIndex, diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 8b13bafdd012f..aec5e3adfe111 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -7,7 +7,7 @@ import numpy as np import pytest -from pandas.compat.numpy import is_numpy_dev +from pandas.compat import is_numpy_dev import pandas.util._test_decorators as td import pandas as pd diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index c0b29d5019675..eb640e324e676 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -15,8 +15,7 @@ from pandas._libs.tslib import Timestamp from pandas._libs.tslibs import parsing from pandas._libs.tslibs.parsing import parse_datetime_string -from pandas.compat import is_platform_windows -from pandas.compat.numpy import np_array_datetime64_compat +from pandas.compat import is_platform_windows, np_array_datetime64_compat import pandas as pd from pandas import DataFrame, DatetimeIndex, Index, MultiIndex, Series diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py index 38e67a0e55a79..4f332bfbac397 100644 --- a/pandas/tests/plotting/test_converter.py +++ b/pandas/tests/plotting/test_converter.py @@ -7,8 +7,7 @@ import pandas._config.config as cf -from pandas.compat import is_platform_windows -from pandas.compat.numpy import np_datetime64_compat +from pandas.compat import is_platform_windows, np_datetime64_compat import pandas.util._test_decorators as td from pandas import Index, Period, Series, Timestamp, date_range diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 9b87e32510b41..55787f73d7a2f 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -10,7 +10,7 @@ from pandas._libs.tslibs.parsing import DateParseError from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG, IncompatibleFrequency from pandas._libs.tslibs.timezones import dateutil_gettz, maybe_get_tz -from pandas.compat.numpy import np_datetime64_compat +from pandas.compat import np_datetime64_compat import pandas as pd from pandas import NaT, Period, Timedelta, Timestamp, offsets diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index 7aefd42ada322..41671343c2800 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -7,7 +7,7 @@ import numpy as np import pytest -from pandas.compat.numpy import is_numpy_dev +from pandas.compat import is_numpy_dev import pandas as pd from pandas import NaT, Timedelta, Timestamp, compat, offsets diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 36d1b0911c909..f2a95044dec61 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -12,7 +12,7 @@ from pytz import timezone, utc from pandas._libs.tslibs.timezones import dateutil_gettz as gettz, get_timezone -from pandas.compat.numpy import np_datetime64_compat +from pandas.compat import np_datetime64_compat import pandas.util._test_decorators as td from pandas import NaT, Timedelta, Timestamp diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 93900fa223966..fb982c02acd99 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -6,8 +6,7 @@ import pytest from pandas._libs import algos as libalgos, hashtable as ht -from pandas.compat import IS64 -from pandas.compat.numpy import np_array_datetime64_compat +from pandas.compat import IS64, np_array_datetime64_compat import pandas.util._test_decorators as td from pandas.core.dtypes.common import ( diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 8e1186b790e3d..696395e50dd02 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -6,7 +6,7 @@ import numpy as np import pytest -from pandas.compat.numpy import np_version_under1p17 +from pandas.compat import np_version_under1p17 import pandas as pd from pandas import Series diff --git a/pandas/tests/tseries/offsets/test_business_day.py b/pandas/tests/tseries/offsets/test_business_day.py index d3c4fb50e2ab0..9b3ded9844e24 100644 --- a/pandas/tests/tseries/offsets/test_business_day.py +++ b/pandas/tests/tseries/offsets/test_business_day.py @@ -7,7 +7,7 @@ import pytest from pandas._libs.tslibs.offsets import ApplyTypeError, BDay, BMonthEnd, CDay -from pandas.compat.numpy import np_datetime64_compat +from pandas.compat import np_datetime64_compat from pandas import DatetimeIndex, _testing as tm, read_pickle from pandas.tests.tseries.offsets.common import ( diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index b65f8084e4bec..8d718d055f02d 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -11,7 +11,7 @@ import pandas._libs.tslibs.offsets as liboffsets from pandas._libs.tslibs.offsets import _get_offset, _offset_map from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG -from pandas.compat.numpy import np_datetime64_compat +from pandas.compat import np_datetime64_compat from pandas.errors import PerformanceWarning from pandas import DatetimeIndex diff --git a/pandas/tests/tslibs/test_array_to_datetime.py b/pandas/tests/tslibs/test_array_to_datetime.py index e3f586d391fc6..24fdb3840bf52 100644 --- a/pandas/tests/tslibs/test_array_to_datetime.py +++ b/pandas/tests/tslibs/test_array_to_datetime.py @@ -6,7 +6,7 @@ import pytz from pandas._libs import iNaT, tslib -from pandas.compat.numpy import np_array_datetime64_compat +from pandas.compat import np_array_datetime64_compat from pandas import Timestamp import pandas._testing as tm
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them Should we do something about the private variables ``_np_version_under1p19`` and ``_np_version_under1p20`` too? cc @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/39092
2021-01-10T17:49:13Z
2021-01-21T18:11:23Z
2021-01-21T18:11:23Z
2021-01-21T20:18:17Z
CI: Skip numpy dev failing tests
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 2ac9b9e2c875c..ab62abe3bfeff 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -12,6 +12,7 @@ import warnings from pandas._typing import F +from pandas.compat.numpy import is_numpy_dev PY38 = sys.version_info >= (3, 8) PY39 = sys.version_info >= (3, 9) @@ -118,3 +119,8 @@ def get_lzma_file(lzma): "might be required to solve this issue." ) return lzma.LZMAFile + + +__all__ = [ + "is_numpy_dev", +] diff --git a/pandas/tests/arithmetic/test_interval.py b/pandas/tests/arithmetic/test_interval.py index 46db9100b8b93..353062abec974 100644 --- a/pandas/tests/arithmetic/test_interval.py +++ b/pandas/tests/arithmetic/test_interval.py @@ -3,6 +3,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + from pandas.core.dtypes.common import is_list_like import pandas as pd @@ -252,6 +254,7 @@ def test_compare_length_mismatch_errors(self, op, other_constructor, length): with pytest.raises(ValueError, match="Lengths must match to compare"): op(array, other) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") @pytest.mark.parametrize( "constructor, expected_type, assert_func", [ diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py index d02078814f60f..9391aae639a4c 100644 --- a/pandas/tests/base/test_misc.py +++ b/pandas/tests/base/test_misc.py @@ -3,7 +3,7 @@ import numpy as np import pytest -from pandas.compat import IS64, PYPY +from pandas.compat import IS64, PYPY, is_numpy_dev from pandas.core.dtypes.common import is_categorical_dtype, is_object_dtype @@ -116,6 +116,9 @@ def test_searchsorted(index_or_series_obj): # See gh-14833 pytest.skip("np.searchsorted doesn't work on pd.MultiIndex") + if is_object_dtype(obj) and is_numpy_dev: + pytest.skip("GH#39089 Numpy changed dtype inference") + max_obj = max(obj, default=0) index = np.searchsorted(obj, max_obj) assert 0 <= index <= len(obj) diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index 472e783c977f0..bfca150f01c34 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -3,6 +3,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + from pandas.core.dtypes.common import is_bool_dtype import pandas as pd @@ -392,6 +394,9 @@ def test_hash_pandas_object_works(self, data, as_frame): b = pd.util.hash_pandas_object(data) self.assert_equal(a, b) + @pytest.mark.xfail( + is_numpy_dev, reason="GH#39089 Numpy changed dtype inference", strict=False + ) def test_searchsorted(self, data_for_sorting, as_series): b, c, a = data_for_sorting arr = type(data_for_sorting)._from_sequence([a, b, c]) diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py index 9ec56c3429b22..9e5d1dcdea85c 100644 --- a/pandas/tests/frame/apply/test_frame_apply.py +++ b/pandas/tests/frame/apply/test_frame_apply.py @@ -5,6 +5,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd @@ -582,6 +584,7 @@ def test_apply_dict(self): tm.assert_frame_equal(reduce_false, df) tm.assert_series_equal(reduce_none, dicts) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_applymap(self, float_frame): applied = float_frame.applymap(lambda x: x * 2) tm.assert_frame_equal(applied, float_frame * 2) diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 3b1a8ebcb13d0..6a16b93c8da2f 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -5,6 +5,7 @@ import pytest from pandas._libs import iNaT +from pandas.compat import is_numpy_dev from pandas.core.dtypes.common import is_integer @@ -254,6 +255,8 @@ def inc(x): ) def test_setitem_same_column(self, cols, values, expected): # GH 23239 + if cols == ["C", "D", "D", "a"] and is_numpy_dev: + pytest.skip("GH#39089 Numpy changed dtype inference") df = DataFrame([values], columns=cols) df["a"] = df["a"] result = df["a"].values[0] diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index 747ee25e97331..58e1bd146191f 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -3,6 +3,7 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev from pandas.errors import PerformanceWarning import pandas as pd @@ -107,6 +108,7 @@ def test_drop_names(self): expected = Index(["a", "b", "c"], name="first") tm.assert_index_equal(dropped.index, expected) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_drop(self): simple = DataFrame({"A": [1, 2, 3, 4], "B": [0, 1, 2, 3]}) tm.assert_frame_equal(simple.drop("A", axis=1), simple[["B"]]) diff --git a/pandas/tests/frame/methods/test_isin.py b/pandas/tests/frame/methods/test_isin.py index 5e50e63016f26..985ebd168461e 100644 --- a/pandas/tests/frame/methods/test_isin.py +++ b/pandas/tests/frame/methods/test_isin.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + import pandas as pd from pandas import DataFrame, MultiIndex, Series import pandas._testing as tm @@ -32,6 +34,7 @@ def test_isin_empty(self, empty): result = df.isin(empty) tm.assert_frame_equal(result, expected) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_isin_dict(self): df = DataFrame({"A": ["a", "b", "c"], "B": ["a", "e", "f"]}) d = {"A": ["a"]} diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index 1b570028964df..a5c9cbdd388a7 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -6,6 +6,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + import pandas as pd from pandas import DataFrame, Index, Series, Timestamp, date_range import pandas._testing as tm @@ -1508,6 +1510,7 @@ def test_replace_no_replacement_dtypes(self, dtype, value): result = df.replace(to_replace=[None, -np.inf, np.inf], value=value) tm.assert_frame_equal(result, df) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") @pytest.mark.parametrize("replacement", [np.nan, 5]) def test_replace_with_duplicate_columns(self, replacement): # GH 24798 diff --git a/pandas/tests/frame/methods/test_to_csv.py b/pandas/tests/frame/methods/test_to_csv.py index 4cf0b1febf0af..e76b9c5d773ad 100644 --- a/pandas/tests/frame/methods/test_to_csv.py +++ b/pandas/tests/frame/methods/test_to_csv.py @@ -5,6 +5,7 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev from pandas.errors import ParserError import pandas as pd @@ -181,6 +182,7 @@ def test_to_csv_cols_reordering(self): tm.assert_frame_equal(df[cols], rs_c, check_names=False) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_to_csv_new_dupe_cols(self): import pandas as pd diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index 8dcf6f2188058..bbcfd8b1aea1b 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + import pandas as pd from pandas import DataFrame, MultiIndex, Series, date_range import pandas._testing as tm @@ -14,6 +16,7 @@ def check(result, expected=None): class TestDataFrameNonuniqueIndexes: + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_column_dups_operations(self): # assignment @@ -310,6 +313,7 @@ def test_column_dups2(self): result = df.dropna(subset=["A", "C"], how="all") tm.assert_frame_equal(result, expected) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_getitem_boolean_series_with_duplicate_columns(self): # boolean indexing # GH 4879 @@ -337,6 +341,7 @@ def test_getitem_boolean_frame_with_duplicate_columns(self): result = df[df > 6] check(result, expected) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self): # `df.A > 6` is a DataFrame with a different shape from df dups = ["A", "A", "C", "D"] diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 8d7fcbfcfe694..00467af83c59c 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -4,6 +4,7 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev from pandas.errors import UnsupportedFunctionCall import pandas as pd @@ -1004,6 +1005,7 @@ def test_frame_describe_unstacked_format(): tm.assert_frame_equal(result, expected) +@pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") @pytest.mark.filterwarnings( "ignore:" "indexing past lexsort depth may impact performance:" diff --git a/pandas/tests/groupby/test_quantile.py b/pandas/tests/groupby/test_quantile.py index c8d6d09577c2b..ad32956b6053a 100644 --- a/pandas/tests/groupby/test_quantile.py +++ b/pandas/tests/groupby/test_quantile.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + import pandas as pd from pandas import DataFrame, Index import pandas._testing as tm @@ -71,6 +73,7 @@ def test_quantile_array(): tm.assert_frame_equal(result, expected) +@pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_quantile_array2(): # https://github.com/pandas-dev/pandas/pull/28085#issuecomment-524066959 df = DataFrame( @@ -106,6 +109,7 @@ def test_quantile_array_no_sort(): tm.assert_frame_equal(result, expected) +@pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_quantile_array_multiple_levels(): df = DataFrame( {"A": [0, 1, 2], "B": [3, 4, 5], "c": ["a", "a", "a"], "d": ["a", "a", "b"]} @@ -216,6 +220,8 @@ def test_quantile_missing_group_values_correct_results( @pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0]]) def test_groupby_quantile_nullable_array(values, q): # https://github.com/pandas-dev/pandas/issues/33136 + if isinstance(q, list): + pytest.skip("GH#39089 Numpy changed dtype inference") df = DataFrame({"a": ["x"] * 3 + ["y"] * 3, "b": values}) result = df.groupby("a")["b"].quantile(q) @@ -256,6 +262,7 @@ def test_groupby_timedelta_quantile(): tm.assert_frame_equal(result, expected) +@pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_columns_groupby_quantile(): # GH 33795 df = DataFrame( diff --git a/pandas/tests/indexes/base_class/test_indexing.py b/pandas/tests/indexes/base_class/test_indexing.py index fd04a820037b9..1c38903631724 100644 --- a/pandas/tests/indexes/base_class/test_indexing.py +++ b/pandas/tests/indexes/base_class/test_indexing.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + from pandas import Index import pandas._testing as tm @@ -13,6 +15,7 @@ def test_get_slice_bounds_within(self, kind, side, expected): result = index.get_slice_bound("e", kind=kind, side=side) assert result == expected + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") @pytest.mark.parametrize("kind", ["getitem", "loc", None]) @pytest.mark.parametrize("side", ["left", "right"]) @pytest.mark.parametrize( diff --git a/pandas/tests/indexes/base_class/test_where.py b/pandas/tests/indexes/base_class/test_where.py index 0c8969735e14e..76bc3fbfc5b81 100644 --- a/pandas/tests/indexes/base_class/test_where.py +++ b/pandas/tests/indexes/base_class/test_where.py @@ -1,10 +1,14 @@ import numpy as np +import pytest + +from pandas.compat import is_numpy_dev from pandas import Index import pandas._testing as tm class TestWhere: + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_where_intlike_str_doesnt_cast_ints(self): idx = Index(range(3)) mask = np.array([True, False, True]) diff --git a/pandas/tests/indexes/categorical/test_indexing.py b/pandas/tests/indexes/categorical/test_indexing.py index 13e622a61b4bd..06cbcd3857c75 100644 --- a/pandas/tests/indexes/categorical/test_indexing.py +++ b/pandas/tests/indexes/categorical/test_indexing.py @@ -1,6 +1,7 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev from pandas.errors import InvalidIndexError import pandas as pd @@ -129,6 +130,7 @@ def test_take_invalid_kwargs(self): class TestGetLoc: + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_get_loc(self): # GH 12531 cidx1 = CategoricalIndex(list("abcde"), categories=list("edabc")) diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index 02ef3cb0e2afb..51bbf6c6cca2e 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -4,6 +4,7 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev from pandas.errors import InvalidIndexError import pandas as pd @@ -916,6 +917,9 @@ def test_searchsorted_different_argument_classes(klass): tm.assert_numpy_array_equal(result, expected) +@pytest.mark.xfail( + is_numpy_dev, reason="GH#39089 Numpy changed dtype inference", strict=False +) @pytest.mark.parametrize( "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2] ) diff --git a/pandas/tests/indexes/period/test_constructors.py b/pandas/tests/indexes/period/test_constructors.py index 75c8c766b0e67..fee7d57a76f97 100644 --- a/pandas/tests/indexes/period/test_constructors.py +++ b/pandas/tests/indexes/period/test_constructors.py @@ -2,6 +2,7 @@ import pytest from pandas._libs.tslibs.period import IncompatibleFrequency +from pandas.compat import is_numpy_dev from pandas.core.dtypes.dtypes import PeriodDtype @@ -304,6 +305,7 @@ def test_constructor_incompat_freq(self): ) ) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_constructor_mixed(self): idx = PeriodIndex(["2011-01", NaT, Period("2011-01", freq="M")]) exp = PeriodIndex(["2011-01", "NaT", "2011-01"], freq="M") diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 1eca7f7a5d261..c635eb583f3b9 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -9,7 +9,7 @@ import pytest from pandas._libs.tslib import Timestamp -from pandas.compat import IS64 +from pandas.compat import IS64, is_numpy_dev from pandas.compat.numpy import np_datetime64_compat from pandas.util._test_decorators import async_mark @@ -1358,6 +1358,7 @@ def test_slice_float_locs(self, dtype): assert index2.slice_locs(8.5, 1.5) == (2, 6) assert index2.slice_locs(10.5, -1) == (0, n) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_slice_locs_dup(self): index = Index(["a", "a", "b", "c", "d", "d"]) assert index.slice_locs("a", "d") == (0, 6) @@ -1397,6 +1398,9 @@ def test_slice_locs_na_raises(self): with pytest.raises(KeyError, match=""): index.slice_locs(end=1.5) + @pytest.mark.xfail( + is_numpy_dev, reason="GH#39089 Numpy changed dtype inference", strict=False + ) @pytest.mark.parametrize( "in_slice,expected", [ diff --git a/pandas/tests/indexes/test_engines.py b/pandas/tests/indexes/test_engines.py index 9ea70a457e516..97a5e0a7bd291 100644 --- a/pandas/tests/indexes/test_engines.py +++ b/pandas/tests/indexes/test_engines.py @@ -4,6 +4,7 @@ import pytest from pandas._libs import algos as libalgos, index as libindex +from pandas.compat import is_numpy_dev import pandas as pd import pandas._testing as tm @@ -198,6 +199,7 @@ def test_is_unique(self): engine = self.engine_type(lambda: arr, len(arr)) assert engine.is_unique is False + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_get_loc(self): # unique arr = np.array(self.values, dtype=self.dtype) diff --git a/pandas/tests/indexes/timedeltas/test_delete.py b/pandas/tests/indexes/timedeltas/test_delete.py index 63f2b450aa818..77223348951f7 100644 --- a/pandas/tests/indexes/timedeltas/test_delete.py +++ b/pandas/tests/indexes/timedeltas/test_delete.py @@ -1,3 +1,7 @@ +import pytest + +from pandas.compat import is_numpy_dev + from pandas import TimedeltaIndex, timedelta_range import pandas._testing as tm @@ -60,6 +64,7 @@ def test_delete_slice(self): assert result.name == expected.name assert result.freq == expected.freq + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_delete_doesnt_infer_freq(self): # GH#30655 behavior matches DatetimeIndex diff --git a/pandas/tests/indexing/multiindex/test_getitem.py b/pandas/tests/indexing/multiindex/test_getitem.py index 6c0d1c285acf3..0ad9f947d2039 100644 --- a/pandas/tests/indexing/multiindex/test_getitem.py +++ b/pandas/tests/indexing/multiindex/test_getitem.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + from pandas import DataFrame, Index, MultiIndex, Series import pandas._testing as tm from pandas.core.indexing import IndexingError @@ -261,6 +263,7 @@ def test_frame_mi_access(dataframe_with_duplicate_index, indexer): tm.assert_frame_equal(result, expected) +@pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_frame_mi_access_returns_series(dataframe_with_duplicate_index): # GH 4146, not returning a block manager when selecting a unique index # from a duplicate index @@ -272,6 +275,7 @@ def test_frame_mi_access_returns_series(dataframe_with_duplicate_index): tm.assert_series_equal(result, expected) +@pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_frame_mi_access_returns_frame(dataframe_with_duplicate_index): # selecting a non_unique from the 2nd level df = dataframe_with_duplicate_index diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index 37153bef8d77b..ba01caba544f4 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series import pandas._testing as tm @@ -144,6 +146,7 @@ def test_loc_multiindex_list_missing_label(self, key, pos): with pytest.raises(KeyError, match="not in index"): df.loc[key] + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_loc_multiindex_too_many_dims_raises(self): # GH 14885 s = Series( diff --git a/pandas/tests/indexing/multiindex/test_partial.py b/pandas/tests/indexing/multiindex/test_partial.py index c203d986efd23..79a0d1125a4a3 100644 --- a/pandas/tests/indexing/multiindex/test_partial.py +++ b/pandas/tests/indexing/multiindex/test_partial.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + from pandas import ( DataFrame, Float64Index, @@ -96,6 +98,7 @@ def test_fancy_slice_partial( expected = ymd[(lev >= 1) & (lev <= 3)] tm.assert_frame_equal(result, expected) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_getitem_partial_column_select(self): idx = MultiIndex( codes=[[0, 0, 0], [0, 1, 1], [1, 0, 1]], diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 90fa6e94d1bc8..0047b396c68b0 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + import pandas as pd from pandas import DataFrame, Series, Timestamp, date_range, option_context import pandas._testing as tm @@ -347,6 +349,7 @@ def test_detect_chained_assignment_warnings_errors(self): with pytest.raises(com.SettingWithCopyError, match=msg): df.loc[0]["A"] = 111 + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_detect_chained_assignment_warnings_filter_and_dupe_cols(self): # xref gh-13017. with option_context("chained_assignment", "warn"): diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index ce48fd1e5c905..60b199ff5f616 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -4,6 +4,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + from pandas import DataFrame, Series, Timedelta, Timestamp, date_range import pandas._testing as tm from pandas.tests.indexing.common import Base @@ -128,6 +130,7 @@ def test_imethods_with_dups(self): result = df.iat[2, 0] assert result == 2 + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_frame_at_with_duplicate_axes(self): # GH#33041 arr = np.random.randn(6).reshape(3, 2) diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index da3ac81c4aa17..100705cc5bd9c 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -5,6 +5,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + from pandas.core.dtypes.common import is_categorical_dtype, is_object_dtype from pandas.core.dtypes.dtypes import CategoricalDtype @@ -2037,6 +2039,7 @@ def test_merge_suffix(col1, col2, kwargs, expected_cols): tm.assert_frame_equal(result, expected) +@pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") @pytest.mark.parametrize( "how,expected", [ diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 5dc0c40ef42dd..055117680c8b9 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -6,7 +6,7 @@ import pytz from pandas._libs.tslibs import iNaT -import pandas.compat as compat +from pandas.compat import PY38, is_numpy_dev from pandas.core.dtypes.common import is_datetime64_any_dtype @@ -59,6 +59,7 @@ def test_nat_fields(nat, idx): assert result is False +@pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_nat_vector_field_access(): idx = DatetimeIndex(["1/1/2000", None, None, "1/4/2000"]) @@ -134,7 +135,7 @@ def test_round_nat(klass, method, freq): pytest.param( "fromisocalendar", marks=pytest.mark.skipif( - not compat.PY38, + not PY38, reason="'fromisocalendar' was added in stdlib datetime in python 3.8", ), ), @@ -310,7 +311,7 @@ def test_overlap_public_nat_methods(klass, expected): # is considered to be with Timestamp and NaT, not Timedelta. # "fromisocalendar" was introduced in 3.8 - if klass is Timestamp and not compat.PY38: + if klass is Timestamp and not PY38: expected.remove("fromisocalendar") assert _get_overlap_public_nat_methods(klass) == expected diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index dbc751dd614a1..43b66c0d55dc1 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -5,6 +5,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + from pandas.core.dtypes.common import is_scalar import pandas as pd @@ -225,6 +227,7 @@ def test_getitem_dups_with_missing(): s[["foo", "bar", "bah", "bam"]] +@pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_getitem_dups(): s = Series(range(5), index=["A", "A", "B", "C", "C"], dtype=np.int64) expected = Series([3, 4], index=["C", "C"], dtype=np.int64) diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py index edcec386cd8ba..aee1874f41ebb 100644 --- a/pandas/tests/series/indexing/test_where.py +++ b/pandas/tests/series/indexing/test_where.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + from pandas.core.dtypes.common import is_integer import pandas as pd @@ -347,6 +349,7 @@ def test_where_dups(): tm.assert_series_equal(comb, expected) +@pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_where_numeric_with_string(): # GH 9280 s = Series([1, 2, 3]) diff --git a/pandas/tests/series/methods/test_clip.py b/pandas/tests/series/methods/test_clip.py index 5a5a397222b87..8e04b331d0066 100644 --- a/pandas/tests/series/methods/test_clip.py +++ b/pandas/tests/series/methods/test_clip.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_numpy_dev + import pandas as pd from pandas import Series, Timestamp, isna, notna import pandas._testing as tm @@ -18,6 +20,7 @@ def test_clip(self, datetime_series): tm.assert_series_equal(result, expected) assert isinstance(expected, Series) + @pytest.mark.xfail(is_numpy_dev, reason="GH#39089 Numpy changed dtype inference") def test_clip_types_and_nulls(self): sers = [
- [x] xref #39089 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/39090
2021-01-10T13:23:02Z
2021-01-10T19:00:37Z
2021-01-10T19:00:37Z
2021-01-10T20:12:33Z
BUG: setting td64 value into Series[numeric]
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 3d19f5ebe4381..e978bf102dedd 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -251,7 +251,7 @@ Indexing - Bug in :meth:`DataFrame.__setitem__` raising ``ValueError`` with empty :class:`DataFrame` and specified columns for string indexer and non empty :class:`DataFrame` to set (:issue:`38831`) - Bug in :meth:`DataFrame.iloc.__setitem__` and :meth:`DataFrame.loc.__setitem__` with mixed dtypes when setting with a dictionary value (:issue:`38335`) - Bug in :meth:`DataFrame.loc` dropping levels of :class:`MultiIndex` when :class:`DataFrame` used as input has only one row (:issue:`10521`) -- +- Bug in setting ``timedelta64`` values into numeric :class:`Series` failing to cast to object dtype (:issue:`39086`) Missing ^^^^^^^ diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index b1b7c28c04ebd..6c8711d940558 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1874,9 +1874,9 @@ def validate_numeric_casting(dtype: np.dtype, value: Scalar) -> None: ): raise ValueError("Cannot assign nan to integer series") - if ( - issubclass(dtype.type, (np.integer, np.floating, complex)) - and not issubclass(dtype.type, np.bool_) - and is_bool(value) - ): - raise ValueError("Cannot assign bool to float/integer series") + if dtype.kind in ["i", "u", "f", "c"]: + if is_bool(value) or isinstance(value, np.timedelta64): + # numpy will cast td64 to integer if we're not careful + raise ValueError( + f"Cannot assign {type(value).__name__} to float/integer series" + ) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 653b5ccf5f1ba..bb83c4543a989 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -678,11 +678,7 @@ def convert( def _can_hold_element(self, element: Any) -> bool: """ require the same dtype as ourselves """ - dtype = self.values.dtype.type - tipo = maybe_infer_dtype_type(element) - if tipo is not None: - return issubclass(tipo.type, dtype) - return isinstance(element, dtype) + raise NotImplementedError("Implemented on subclasses") def should_store(self, value: ArrayLike) -> bool: """ @@ -1969,10 +1965,10 @@ class ComplexBlock(NumericBlock): def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: - return issubclass(tipo.type, (np.floating, np.integer, np.complexfloating)) - return isinstance( - element, (float, int, complex, np.float_, np.int_) - ) and not isinstance(element, (bool, np.bool_)) + return tipo.kind in ["c", "f", "i", "u"] + return ( + lib.is_integer(element) or lib.is_complex(element) or lib.is_float(element) + ) class IntBlock(NumericBlock): diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 8e4a6d50f5070..7f469f361fec7 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -395,3 +395,27 @@ def test_setitem_slice_into_readonly_backing_data(): series[1:3] = 1 assert not array.any() + + +@pytest.mark.parametrize( + "key", [0, slice(0, 1), [0], np.array([0]), range(1)], ids=type +) +@pytest.mark.parametrize("dtype", [complex, int, float]) +def test_setitem_td64_into_complex(key, dtype, indexer_sli): + # timedelta64 should not be treated as integers + arr = np.arange(5).astype(dtype) + ser = Series(arr) + td = np.timedelta64(4, "ns") + + indexer_sli(ser)[key] = td + assert ser.dtype == object + assert arr[0] == 0 # original array is unchanged + + if not isinstance(key, int) and not ( + indexer_sli is tm.loc and isinstance(key, slice) + ): + # skip key/indexer_sli combinations that will have mismatched lengths + ser = Series(arr) + indexer_sli(ser)[key] = np.full((1,), td) + assert ser.dtype == object + assert arr[0] == 0 # original array is unchanged
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39086
2021-01-10T07:19:15Z
2021-01-11T17:06:30Z
2021-01-11T17:06:30Z
2021-01-11T17:22:34Z
IntervalIndex/IntervalArray __repr__ remove redundant closed
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 284305b588e4e..56550a8665816 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -149,7 +149,7 @@ >>> pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)]) <IntervalArray> [(0, 1], (1, 5]] - Length: 2, closed: right, dtype: interval[int64, right] + Length: 2, dtype: interval[int64, right] It may also be constructed using one of the constructor methods: :meth:`IntervalArray.from_arrays`, @@ -354,7 +354,7 @@ def _from_factorized(cls, values, original): >>> pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3]) <IntervalArray> [(0, 1], (1, 2], (2, 3]] - Length: 3, closed: right, dtype: interval[int64, right] + Length: 3, dtype: interval[int64, right] """ ), } @@ -425,7 +425,7 @@ def from_breaks( >>> pd.arrays.IntervalArray.from_arrays([0, 1, 2], [1, 2, 3]) <IntervalArray> [(0, 1], (1, 2], (2, 3]] - Length: 3, closed: right, dtype: interval[int64, right] + Length: 3, dtype: interval[int64, right] """ ), } @@ -484,7 +484,7 @@ def from_arrays( >>> pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 2)]) <IntervalArray> [(0, 1], (1, 2]] - Length: 2, closed: right, dtype: interval[int64, right] + Length: 2, dtype: interval[int64, right] """ ), } @@ -1071,11 +1071,7 @@ def __repr__(self) -> str: data = self._format_data() class_name = f"<{type(self).__name__}>\n" - template = ( - f"{class_name}" - f"{data}\n" - f"Length: {len(self)}, closed: {self.closed}, dtype: {self.dtype}" - ) + template = f"{class_name}{data}\nLength: {len(self)}, dtype: {self.dtype}" return template def _format_space(self): @@ -1185,7 +1181,7 @@ def mid(self): >>> intervals <IntervalArray> [(0, 1], (1, 3], (2, 4]] - Length: 3, closed: right, dtype: interval[int64, right] + Length: 3, dtype: interval[int64, right] """ ), } @@ -1249,11 +1245,11 @@ def closed(self): >>> index <IntervalArray> [(0, 1], (1, 2], (2, 3]] - Length: 3, closed: right, dtype: interval[int64, right] + Length: 3, dtype: interval[int64, right] >>> index.set_closed('both') <IntervalArray> [[0, 1], [1, 2], [2, 3]] - Length: 3, closed: both, dtype: interval[int64, both] + Length: 3, dtype: interval[int64, both] """ ), } @@ -1452,7 +1448,7 @@ def repeat(self, repeats, axis=None): >>> intervals <IntervalArray> [(0, 1], (1, 3], (2, 4]] - Length: 3, closed: right, dtype: interval[int64, right] + Length: 3, dtype: interval[int64, right] """ ), } diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index b6213e99513c1..fdac4028af281 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -51,7 +51,6 @@ default_pprint, ensure_index, maybe_extract_name, - unpack_nested_dtype, ) from pandas.core.indexes.datetimes import DatetimeIndex, date_range from pandas.core.indexes.extension import ExtensionIndex, inherit_names @@ -157,7 +156,6 @@ def wrapped(self, other, sort=False): >>> pd.interval_range(start=0, end=5) IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]], - closed='right', dtype='interval[int64, right]') It may also be constructed using one of the constructor @@ -242,7 +240,6 @@ def _simple_new(cls, array: IntervalArray, name: Label = None): -------- >>> pd.IntervalIndex.from_breaks([0, 1, 2, 3]) IntervalIndex([(0, 1], (1, 2], (2, 3]], - closed='right', dtype='interval[int64, right]') """ ), @@ -273,7 +270,6 @@ def from_breaks( -------- >>> pd.IntervalIndex.from_arrays([0, 1, 2], [1, 2, 3]) IntervalIndex([(0, 1], (1, 2], (2, 3]], - closed='right', dtype='interval[int64, right]') """ ), @@ -305,7 +301,6 @@ def from_arrays( -------- >>> pd.IntervalIndex.from_tuples([(0, 1), (1, 2)]) IntervalIndex([(0, 1], (1, 2]], - closed='right', dtype='interval[int64, right]') """ ), @@ -445,7 +440,6 @@ def is_overlapping(self) -> bool: >>> index = pd.IntervalIndex.from_tuples([(0, 2), (1, 3), (4, 5)]) >>> index IntervalIndex([(0, 2], (1, 3], (4, 5]], - closed='right', dtype='interval[int64, right]') >>> index.is_overlapping True @@ -455,7 +449,6 @@ def is_overlapping(self) -> bool: >>> index = pd.interval_range(0, 3, closed='both') >>> index IntervalIndex([[0, 1], [1, 2], [2, 3]], - closed='both', dtype='interval[int64, both]') >>> index.is_overlapping True @@ -465,7 +458,6 @@ def is_overlapping(self) -> bool: >>> index = pd.interval_range(0, 3, closed='left') >>> index IntervalIndex([[0, 1), [1, 2), [2, 3)], - closed='left', dtype='interval[int64, left]') >>> index.is_overlapping False @@ -777,17 +769,11 @@ def _convert_list_indexer(self, keyarr): def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: if not isinstance(dtype, IntervalDtype): return False + if self.closed != dtype.closed: + return False common_subtype = find_common_type([self.dtype.subtype, dtype.subtype]) return not is_object_dtype(common_subtype) - def _should_compare(self, other) -> bool: - other = unpack_nested_dtype(other) - if is_object_dtype(other.dtype): - return True - if not self._is_comparable_dtype(other.dtype): - return False - return other.closed == self.closed - # -------------------------------------------------------------------- @cache_readonly @@ -911,7 +897,7 @@ def _format_data(self, name=None): return summary + "," + self._format_space() def _format_attrs(self): - attrs = [("closed", repr(self.closed))] + attrs = [] if self.name is not None: attrs.append(("name", default_pprint(self.name))) attrs.append(("dtype", f"'{self.dtype}'")) @@ -1117,7 +1103,6 @@ def interval_range( >>> pd.interval_range(start=0, end=5) IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]], - closed='right', dtype='interval[int64, right]') Additionally, datetime-like input is also supported. @@ -1126,7 +1111,7 @@ def interval_range( ... end=pd.Timestamp('2017-01-04')) IntervalIndex([(2017-01-01, 2017-01-02], (2017-01-02, 2017-01-03], (2017-01-03, 2017-01-04]], - closed='right', dtype='interval[datetime64[ns], right]') + dtype='interval[datetime64[ns], right]') The ``freq`` parameter specifies the frequency between the left and right. endpoints of the individual intervals within the ``IntervalIndex``. For @@ -1134,7 +1119,7 @@ def interval_range( >>> pd.interval_range(start=0, periods=4, freq=1.5) IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]], - closed='right', dtype='interval[float64, right]') + dtype='interval[float64, right]') Similarly, for datetime-like ``start`` and ``end``, the frequency must be convertible to a DateOffset. @@ -1143,14 +1128,13 @@ def interval_range( ... periods=3, freq='MS') IntervalIndex([(2017-01-01, 2017-02-01], (2017-02-01, 2017-03-01], (2017-03-01, 2017-04-01]], - closed='right', dtype='interval[datetime64[ns], right]') + dtype='interval[datetime64[ns], right]') Specify ``start``, ``end``, and ``periods``; the frequency is generated automatically (linearly spaced). >>> pd.interval_range(start=0, end=6, periods=4) IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]], - closed='right', dtype='interval[float64, right]') The ``closed`` parameter specifies which endpoints of the individual @@ -1158,7 +1142,7 @@ def interval_range( >>> pd.interval_range(end=5, periods=4, closed='both') IntervalIndex([[1, 2], [2, 3], [3, 4], [4, 5]], - closed='both', dtype='interval[int64, both]') + dtype='interval[int64, both]') """ start = maybe_box_datetimelike(start) end = maybe_box_datetimelike(end) diff --git a/pandas/tests/arrays/interval/test_interval.py b/pandas/tests/arrays/interval/test_interval.py index af291ca98a91a..f999f79bc389b 100644 --- a/pandas/tests/arrays/interval/test_interval.py +++ b/pandas/tests/arrays/interval/test_interval.py @@ -131,7 +131,7 @@ def test_repr(): expected = ( "<IntervalArray>\n" "[(0, 1], (1, 2]]\n" - "Length: 2, closed: right, dtype: interval[int64, right]" + "Length: 2, dtype: interval[int64, right]" ) assert result == expected
https://api.github.com/repos/pandas-dev/pandas/pulls/39085
2021-01-10T06:16:13Z
2021-01-11T14:01:47Z
2021-01-11T14:01:47Z
2021-01-11T16:12:58Z
Backport PR #39071 on branch 1.2.x (Regression in loc.setitem raising ValueError with unordered MultiIndex columns and scalar indexer)
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 8b0d100b9e1b3..e612c379606ef 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -22,6 +22,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.any` and :meth:`DataFrame.all` not returning a result for tz-aware ``datetime64`` columns (:issue:`38723`) - Fixed regression in :meth:`DataFrame.__setitem__` raising ``ValueError`` when expanding :class:`DataFrame` and new column is from type ``"0 - name"`` (:issue:`39010`) - Fixed regression in :meth:`.GroupBy.sem` where the presence of non-numeric columns would cause an error instead of being dropped (:issue:`38774`) +- Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``ValueError`` when :class:`DataFrame` has unsorted :class:`MultiIndex` columns and indexer is a scalar (:issue:`38601`) - Fixed regression in :func:`read_excel` with non-rawbyte file handles (:issue:`38788`) - Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) - Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index e7cf8cae28b88..9ddce9c0aab66 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -13,6 +13,7 @@ from pandas.core.dtypes.common import ( is_array_like, + is_bool_dtype, is_hashable, is_integer, is_iterator, @@ -1925,12 +1926,14 @@ def _ensure_iterable_column_indexer(self, column_indexer): """ Ensure that our column indexer is something that can be iterated over. """ - # Ensure we have something we can iterate over if is_integer(column_indexer): ilocs = [column_indexer] elif isinstance(column_indexer, slice): - ri = Index(range(len(self.obj.columns))) - ilocs = ri[column_indexer] + ilocs = np.arange(len(self.obj.columns))[column_indexer] + elif isinstance(column_indexer, np.ndarray) and is_bool_dtype( + column_indexer.dtype + ): + ilocs = np.arange(len(column_indexer))[column_indexer] else: ilocs = column_indexer return ilocs diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 49eb570c4ffe0..32dfe5858d1d0 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1682,6 +1682,21 @@ def test_getitem_interval_index_partial_indexing(self): res = df.loc[:, 0.5] tm.assert_series_equal(res, expected) + @pytest.mark.parametrize("indexer", ["A", ["A"], ("A", slice(None))]) + def test_setitem_unsorted_multiindex_columns(self, indexer): + # GH#38601 + mi = MultiIndex.from_tuples([("A", 4), ("B", "3"), ("A", "2")]) + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=mi) + obj = df.copy() + obj.loc[:, indexer] = np.zeros((2, 2), dtype=int) + expected = DataFrame([[0, 2, 0], [0, 5, 0]], columns=mi) + tm.assert_frame_equal(obj, expected) + + df = df.sort_index(1) + df.loc[:, indexer] = np.zeros((2, 2), dtype=int) + expected = expected.sort_index(1) + tm.assert_frame_equal(df, expected) + class TestDataFrameIndexingUInt64: def test_setitem(self, uint64_frame):
Backport PR #39071: Regression in loc.setitem raising ValueError with unordered MultiIndex columns and scalar indexer
https://api.github.com/repos/pandas-dev/pandas/pulls/39084
2021-01-10T04:01:18Z
2021-01-11T13:15:03Z
2021-01-11T13:15:03Z
2021-01-11T13:18:58Z
CLN: Simplify optional dependency
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index def881b8fd863..6110ca794e2c2 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -62,8 +62,7 @@ def _get_version(module: types.ModuleType) -> str: def import_optional_dependency( name: str, extra: str = "", - raise_on_missing: bool = True, - on_version: str = "raise", + errors: str = "raise", min_version: Optional[str] = None, ): """ @@ -79,17 +78,16 @@ def import_optional_dependency( The module name. extra : str Additional text to include in the ImportError message. - raise_on_missing : bool, default True - Whether to raise if the optional dependency is not found. - When False and the module is not present, None is returned. - on_version : str {'raise', 'warn'} - What to do when a dependency's version is too old. + errors : str {'raise', 'warn', 'ignore'} + What to do when a dependency is not found or its version is too old. * raise : Raise an ImportError - * warn : Warn that the version is too old. Returns None - * ignore: Return the module, even if the version is too old. + * warn : Only applicable when a module's version is to old. + Warns that the version is too old and returns None + * ignore: If the module is not installed, return None, otherwise, + return the module, even if the version is too old. It's expected that users validate the version locally when - using ``on_version="ignore"`` (see. ``io/html.py``) + using ``errors="ignore"`` (see. ``io/html.py``) min_version : str, default None Specify a minimum version that is different from the global pandas minimum version required. @@ -97,11 +95,13 @@ def import_optional_dependency( ------- maybe_module : Optional[ModuleType] The imported module, when found and the version is correct. - None is returned when the package is not found and `raise_on_missing` - is False, or when the package's version is too old and `on_version` + None is returned when the package is not found and `errors` + is False, or when the package's version is too old and `errors` is ``'warn'``. """ + assert errors in {"warn", "raise", "ignore"} + package_name = INSTALL_MAPPING.get(name) install_name = package_name if package_name is not None else name @@ -112,7 +112,7 @@ def import_optional_dependency( try: module = importlib.import_module(name) except ImportError: - if raise_on_missing: + if errors == "raise": raise ImportError(msg) from None else: return None @@ -128,15 +128,14 @@ def import_optional_dependency( if minimum_version: version = _get_version(module_to_get) if distutils.version.LooseVersion(version) < minimum_version: - assert on_version in {"warn", "raise", "ignore"} msg = ( f"Pandas requires version '{minimum_version}' or newer of '{parent}' " f"(version '{version}' currently installed)." ) - if on_version == "warn": + if errors == "warn": warnings.warn(msg, UserWarning) return None - elif on_version == "raise": + elif errors == "raise": raise ImportError(msg) return module diff --git a/pandas/core/computation/check.py b/pandas/core/computation/check.py index 6c7261b3b33c9..7be617de63a40 100644 --- a/pandas/core/computation/check.py +++ b/pandas/core/computation/check.py @@ -1,6 +1,6 @@ from pandas.compat._optional import import_optional_dependency -ne = import_optional_dependency("numexpr", raise_on_missing=False, on_version="warn") +ne = import_optional_dependency("numexpr", errors="warn") NUMEXPR_INSTALLED = ne is not None if NUMEXPR_INSTALLED: NUMEXPR_VERSION = ne.__version__ diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 0c01ef21efbb5..fb9b20bd43d7c 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -34,7 +34,7 @@ from pandas.core.construction import extract_array -bn = import_optional_dependency("bottleneck", raise_on_missing=False, on_version="warn") +bn = import_optional_dependency("bottleneck", errors="warn") _BOTTLENECK_INSTALLED = bn is not None _USE_BOTTLENECK = False diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index b0ec8a1082a0e..aa6b4697f4d2c 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -1053,12 +1053,7 @@ def __init__( self._io = stringify_path(path_or_buffer) # Determine xlrd version if installed - if ( - import_optional_dependency( - "xlrd", raise_on_missing=False, on_version="ignore" - ) - is None - ): + if import_optional_dependency("xlrd", errors="ignore") is None: xlrd_version = None else: import xlrd diff --git a/pandas/io/excel/_util.py b/pandas/io/excel/_util.py index b5d0d1347f119..ab8e0fca4bf38 100644 --- a/pandas/io/excel/_util.py +++ b/pandas/io/excel/_util.py @@ -57,22 +57,14 @@ def get_default_engine(ext, mode="reader"): assert mode in ["reader", "writer"] if mode == "writer": # Prefer xlsxwriter over openpyxl if installed - xlsxwriter = import_optional_dependency( - "xlsxwriter", raise_on_missing=False, on_version="warn" - ) + xlsxwriter = import_optional_dependency("xlsxwriter", errors="warn") if xlsxwriter: _default_writers["xlsx"] = "xlsxwriter" return _default_writers[ext] else: if ( - import_optional_dependency( - "openpyxl", raise_on_missing=False, on_version="ignore" - ) - is None - and import_optional_dependency( - "xlrd", raise_on_missing=False, on_version="ignore" - ) - is not None + import_optional_dependency("openpyxl", errors="ignore") is None + and import_optional_dependency("xlrd", errors="ignore") is not None ): # if no openpyxl but xlrd installed, return xlrd # the version is handled elsewhere diff --git a/pandas/io/html.py b/pandas/io/html.py index 4a2d4af62f3e9..c445ee81ec8ed 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -39,17 +39,13 @@ def _importers(): return global _HAS_BS4, _HAS_LXML, _HAS_HTML5LIB - bs4 = import_optional_dependency("bs4", raise_on_missing=False, on_version="ignore") + bs4 = import_optional_dependency("bs4", errors="ignore") _HAS_BS4 = bs4 is not None - lxml = import_optional_dependency( - "lxml.etree", raise_on_missing=False, on_version="ignore" - ) + lxml = import_optional_dependency("lxml.etree", errors="ignore") _HAS_LXML = lxml is not None - html5lib = import_optional_dependency( - "html5lib", raise_on_missing=False, on_version="ignore" - ) + html5lib = import_optional_dependency("html5lib", errors="ignore") _HAS_HTML5LIB = html5lib is not None _IMPORTS = True diff --git a/pandas/tests/io/excel/__init__.py b/pandas/tests/io/excel/__init__.py index b7ceb28573484..7df035e6da17a 100644 --- a/pandas/tests/io/excel/__init__.py +++ b/pandas/tests/io/excel/__init__.py @@ -24,10 +24,7 @@ ] -if ( - import_optional_dependency("xlrd", raise_on_missing=False, on_version="ignore") - is None -): +if import_optional_dependency("xlrd", errors="ignore") is None: xlrd_version = None else: import xlrd diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py index 19949cefa13d9..2d19b570e5d06 100644 --- a/pandas/tests/io/excel/test_xlrd.py +++ b/pandas/tests/io/excel/test_xlrd.py @@ -52,12 +52,7 @@ def test_excel_table_sheet_by_index(datapath, read_ext): def test_excel_file_warning_with_xlsx_file(datapath): # GH 29375 path = datapath("io", "data", "excel", "test1.xlsx") - has_openpyxl = ( - import_optional_dependency( - "openpyxl", raise_on_missing=False, on_version="ignore" - ) - is not None - ) + has_openpyxl = import_optional_dependency("openpyxl", errors="ignore") is not None if not has_openpyxl: with tm.assert_produces_warning( FutureWarning, @@ -73,12 +68,7 @@ def test_excel_file_warning_with_xlsx_file(datapath): def test_read_excel_warning_with_xlsx_file(datapath): # GH 29375 path = datapath("io", "data", "excel", "test1.xlsx") - has_openpyxl = ( - import_optional_dependency( - "openpyxl", raise_on_missing=False, on_version="ignore" - ) - is not None - ) + has_openpyxl = import_optional_dependency("openpyxl", errors="ignore") is not None if not has_openpyxl: if xlrd_version >= "2": with pytest.raises( diff --git a/pandas/tests/test_optional_dependency.py b/pandas/tests/test_optional_dependency.py index 304ec124ac8c5..b9cab2428c0d1 100644 --- a/pandas/tests/test_optional_dependency.py +++ b/pandas/tests/test_optional_dependency.py @@ -13,7 +13,7 @@ def test_import_optional(): with pytest.raises(ImportError, match=match): import_optional_dependency("notapackage") - result = import_optional_dependency("notapackage", raise_on_missing=False) + result = import_optional_dependency("notapackage", errors="ignore") assert result is None @@ -38,7 +38,7 @@ def test_bad_version(monkeypatch): assert result is module with tm.assert_produces_warning(UserWarning): - result = import_optional_dependency("fakemodule", on_version="warn") + result = import_optional_dependency("fakemodule", errors="warn") assert result is None module.__version__ = "1.0.0" # exact match is OK @@ -63,7 +63,7 @@ def test_submodule(monkeypatch): import_optional_dependency("fakemodule.submodule") with tm.assert_produces_warning(UserWarning): - result = import_optional_dependency("fakemodule.submodule", on_version="warn") + result = import_optional_dependency("fakemodule.submodule", errors="warn") assert result is None module.__version__ = "1.0.0" # exact match is OK diff --git a/pandas/util/_print_versions.py b/pandas/util/_print_versions.py index 5256cc29d5543..381dab4e3ce45 100644 --- a/pandas/util/_print_versions.py +++ b/pandas/util/_print_versions.py @@ -80,9 +80,7 @@ def _get_dependency_info() -> Dict[str, JSONSerializable]: result: Dict[str, JSONSerializable] = {} for modname in deps: - mod = import_optional_dependency( - modname, raise_on_missing=False, on_version="ignore" - ) + mod = import_optional_dependency(modname, errors="ignore") result[modname] = _get_version(mod) if mod else None return result
- [x] closes #38936 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39083
2021-01-10T03:06:44Z
2021-01-11T13:59:41Z
2021-01-11T13:59:41Z
2021-01-11T18:08:54Z
REF: Remove Apply.get_result
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 874b40f224a26..a618e2a92551d 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -40,7 +40,6 @@ def frame_apply( obj: DataFrame, - how: str, func: AggFuncType, axis: Axis = 0, raw: bool = False, @@ -58,7 +57,6 @@ def frame_apply( return klass( obj, - how, func, raw=raw, result_type=result_type, @@ -69,7 +67,6 @@ def frame_apply( def series_apply( obj: Series, - how: str, func: AggFuncType, convert_dtype: bool = True, args=None, @@ -77,7 +74,6 @@ def series_apply( ) -> SeriesApply: return SeriesApply( obj, - how, func, convert_dtype, args, @@ -91,16 +87,13 @@ class Apply(metaclass=abc.ABCMeta): def __init__( self, obj: FrameOrSeriesUnion, - how: str, func, raw: bool, result_type: Optional[str], args, kwds, ): - assert how in ("apply", "agg") self.obj = obj - self.how = how self.raw = raw self.args = args or () self.kwds = kwds or {} @@ -132,12 +125,6 @@ def f(x): def index(self) -> Index: return self.obj.index - def get_result(self): - if self.how == "apply": - return self.apply() - else: - return self.agg() - @abc.abstractmethod def apply(self) -> FrameOrSeriesUnion: pass @@ -234,12 +221,6 @@ def dtypes(self) -> Series: def agg_axis(self) -> Index: return self.obj._get_agg_axis(self.axis) - def get_result(self): - if self.how == "apply": - return self.apply() - else: - return self.agg() - def apply(self) -> FrameOrSeriesUnion: """ compute the results """ # dispatch to agg @@ -570,7 +551,6 @@ class SeriesApply(Apply): def __init__( self, obj: Series, - how: str, func: AggFuncType, convert_dtype: bool, args, @@ -580,7 +560,6 @@ def __init__( super().__init__( obj, - how, func, raw=False, result_type=None, diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e65e9302dd4d5..1d8280ae3b2f1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7646,13 +7646,12 @@ def _aggregate(self, arg, axis: Axis = 0, *args, **kwargs): op = frame_apply( self if axis == 0 else self.T, - how="agg", func=arg, axis=0, args=args, kwds=kwargs, ) - result, how = op.get_result() + result, how = op.agg() if axis == 1: # NDFrame.aggregate returns a tuple, and we need to transpose @@ -7819,7 +7818,6 @@ def apply( op = frame_apply( self, - how="apply", func=func, axis=axis, raw=raw, @@ -7827,7 +7825,7 @@ def apply( args=args, kwds=kwds, ) - return op.get_result() + return op.apply() def applymap( self, func: PythonFuncType, na_action: Optional[str] = None diff --git a/pandas/core/series.py b/pandas/core/series.py index 6586ac8b01840..b90ec00fc1d67 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3944,8 +3944,8 @@ def aggregate(self, func=None, axis=0, *args, **kwargs): if func is None: func = dict(kwargs.items()) - op = series_apply(self, "agg", func, args=args, kwds=kwargs) - result, how = op.get_result() + op = series_apply(self, func, args=args, kwds=kwargs) + result, how = op.agg() if result is None: # we can be called from an inner function which @@ -4077,8 +4077,8 @@ def apply(self, func, convert_dtype=True, args=(), **kwds): Helsinki 2.484907 dtype: float64 """ - op = series_apply(self, "apply", func, convert_dtype, args, kwds) - return op.get_result() + op = series_apply(self, func, convert_dtype, args, kwds) + return op.apply() def _reduce( self,
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them Slightly simpler and allows typing of the result that we get out of Apply. Having both apply and agg go through get_result would mean typing the result as `Union[FrameOrSeriesUnion, Tuple[bool, Optional[FrameOrSeriesUnion]]]`
https://api.github.com/repos/pandas-dev/pandas/pulls/39082
2021-01-10T02:05:25Z
2021-01-11T14:27:04Z
2021-01-11T14:27:04Z
2021-01-11T14:32:14Z
Backport PR #39077 on branch 1.2.x (Remove xlrd benchmark after xlrd was updated to 2.0.1 on conda-forge)
diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py index 80af2cff41769..96f02d37db1e1 100644 --- a/asv_bench/benchmarks/io/excel.py +++ b/asv_bench/benchmarks/io/excel.py @@ -40,7 +40,7 @@ def time_write_excel(self, engine): class ReadExcel: - params = ["xlrd", "openpyxl", "odf"] + params = ["openpyxl", "odf"] param_names = ["engine"] fname_excel = "spreadsheet.xlsx" fname_odf = "spreadsheet.ods"
Backport PR #39077: Remove xlrd benchmark after xlrd was updated to 2.0.1 on conda-forge
https://api.github.com/repos/pandas-dev/pandas/pulls/39078
2021-01-10T00:42:17Z
2021-01-10T02:32:08Z
2021-01-10T02:32:08Z
2021-01-10T02:32:08Z
Remove xlrd benchmark after xlrd was updated to 2.0.1 on conda-forge
diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py index 80af2cff41769..96f02d37db1e1 100644 --- a/asv_bench/benchmarks/io/excel.py +++ b/asv_bench/benchmarks/io/excel.py @@ -40,7 +40,7 @@ def time_write_excel(self, engine): class ReadExcel: - params = ["xlrd", "openpyxl", "odf"] + params = ["openpyxl", "odf"] param_names = ["engine"] fname_excel = "spreadsheet.xlsx" fname_odf = "spreadsheet.ods"
- [x] closes #39076 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry Is pinning here the right thing to do in environment.yml? cc @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/39077
2021-01-09T22:19:47Z
2021-01-10T00:41:50Z
2021-01-10T00:41:50Z
2021-01-10T20:27:25Z
Backport PR #39065 on branch 1.2.x (Regression in replace raising ValueError for bytes object)
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 4b7a4180ee9f9..28d84c380956c 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -26,6 +26,7 @@ Fixed regressions - Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) - Fixed regression in :meth:`Rolling.skew` and :meth:`Rolling.kurt` modifying the object inplace (:issue:`38908`) - Fixed regression in :meth:`read_csv` and other read functions were the encoding error policy (``errors``) did not default to ``"replace"`` when no encoding was specified (:issue:`38989`) +- Fixed regression in :meth:`DataFrame.replace` raising ValueError when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index fe07823a80783..b8de2ea0892db 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2482,7 +2482,7 @@ class ObjectBlock(Block): _can_hold_na = True def _maybe_coerce_values(self, values): - if issubclass(values.dtype.type, str): + if issubclass(values.dtype.type, (str, bytes)): values = np.array(values, dtype=object) return values diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index ab750bca7e069..1b570028964df 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -1636,3 +1636,10 @@ def test_replace_unicode(self): result = df1.replace(columns_values_map) expected = DataFrame({"positive": np.ones(3)}) tm.assert_frame_equal(result, expected) + + def test_replace_bytes(self, frame_or_series): + # GH#38900 + obj = frame_or_series(["o"]).astype("|S") + expected = obj.copy() + obj = obj.replace({None: np.nan}) + tm.assert_equal(obj, expected)
Backport PR #39065: Regression in replace raising ValueError for bytes object
https://api.github.com/repos/pandas-dev/pandas/pulls/39075
2021-01-09T22:06:34Z
2021-01-10T02:32:32Z
2021-01-10T02:32:32Z
2021-01-10T02:32:32Z
Fixed #39073 Add STUMPY to Pandas ecosystem docs
diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index e84f156035725..bb89b91954518 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -85,6 +85,14 @@ Featuretools is a Python library for automated feature engineering built on top Compose is a machine learning tool for labeling data and prediction engineering. It allows you to structure the labeling process by parameterizing prediction problems and transforming time-driven relational data into target values with cutoff times that can be used for supervised learning. +`STUMPY <https://github.com/TDAmeritrade/stumpy>`__ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +STUMPY is a powerful and scalable Python library for modern time series analysis. +At its core, STUMPY efficiently computes something called a +`matrix profile <https://stumpy.readthedocs.io/en/latest/Tutorial_The_Matrix_Profile.html>`__, +which can be used for a wide variety of time series data mining tasks. + .. _ecosystem.visualization: Visualization
- [ ] closes #39073 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39074
2021-01-09T21:56:27Z
2021-01-10T02:39:04Z
2021-01-10T02:39:04Z
2021-01-10T02:39:08Z
TST GH26807 Break up pandas/tests/io/pytables/test_store.py
diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py new file mode 100644 index 0000000000000..3eebeee9788c6 --- /dev/null +++ b/pandas/tests/io/pytables/test_append.py @@ -0,0 +1,927 @@ +import datetime +from datetime import timedelta +import re +from warnings import catch_warnings + +import numpy as np +import pytest + +from pandas._libs.tslibs import Timestamp + +import pandas as pd +from pandas import ( + DataFrame, + MultiIndex, + Series, + _testing as tm, + concat, + date_range, + read_hdf, +) +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_path, + ensure_clean_store, +) + +pytestmark = pytest.mark.single + + +@pytest.mark.filterwarnings("ignore:object name:tables.exceptions.NaturalNameWarning") +def test_append(setup_path): + + with ensure_clean_store(setup_path) as store: + + # this is allowed by almost always don't want to do it + # tables.NaturalNameWarning): + with catch_warnings(record=True): + + df = tm.makeTimeDataFrame() + _maybe_remove(store, "df1") + store.append("df1", df[:10]) + store.append("df1", df[10:]) + tm.assert_frame_equal(store["df1"], df) + + _maybe_remove(store, "df2") + store.put("df2", df[:10], format="table") + store.append("df2", df[10:]) + tm.assert_frame_equal(store["df2"], df) + + _maybe_remove(store, "df3") + store.append("/df3", df[:10]) + store.append("/df3", df[10:]) + tm.assert_frame_equal(store["df3"], df) + + # this is allowed by almost always don't want to do it + # tables.NaturalNameWarning + _maybe_remove(store, "/df3 foo") + store.append("/df3 foo", df[:10]) + store.append("/df3 foo", df[10:]) + tm.assert_frame_equal(store["df3 foo"], df) + + # dtype issues - mizxed type in a single object column + df = DataFrame(data=[[1, 2], [0, 1], [1, 2], [0, 0]]) + df["mixed_column"] = "testing" + df.loc[2, "mixed_column"] = np.nan + _maybe_remove(store, "df") + store.append("df", df) + tm.assert_frame_equal(store["df"], df) + + # uints - test storage of uints + uint_data = DataFrame( + { + "u08": Series( + np.random.randint(0, high=255, size=5), dtype=np.uint8 + ), + "u16": Series( + np.random.randint(0, high=65535, size=5), dtype=np.uint16 + ), + "u32": Series( + np.random.randint(0, high=2 ** 30, size=5), dtype=np.uint32 + ), + "u64": Series( + [2 ** 58, 2 ** 59, 2 ** 60, 2 ** 61, 2 ** 62], + dtype=np.uint64, + ), + }, + index=np.arange(5), + ) + _maybe_remove(store, "uints") + store.append("uints", uint_data) + tm.assert_frame_equal(store["uints"], uint_data) + + # uints - test storage of uints in indexable columns + _maybe_remove(store, "uints") + # 64-bit indices not yet supported + store.append("uints", uint_data, data_columns=["u08", "u16", "u32"]) + tm.assert_frame_equal(store["uints"], uint_data) + + +def test_append_series(setup_path): + + with ensure_clean_store(setup_path) as store: + + # basic + ss = tm.makeStringSeries() + ts = tm.makeTimeSeries() + ns = Series(np.arange(100)) + + store.append("ss", ss) + result = store["ss"] + tm.assert_series_equal(result, ss) + assert result.name is None + + store.append("ts", ts) + result = store["ts"] + tm.assert_series_equal(result, ts) + assert result.name is None + + ns.name = "foo" + store.append("ns", ns) + result = store["ns"] + tm.assert_series_equal(result, ns) + assert result.name == ns.name + + # select on the values + expected = ns[ns > 60] + result = store.select("ns", "foo>60") + tm.assert_series_equal(result, expected) + + # select on the index and values + expected = ns[(ns > 70) & (ns.index < 90)] + result = store.select("ns", "foo>70 and index<90") + tm.assert_series_equal(result, expected) + + # multi-index + mi = DataFrame(np.random.randn(5, 1), columns=["A"]) + mi["B"] = np.arange(len(mi)) + mi["C"] = "foo" + mi.loc[3:5, "C"] = "bar" + mi.set_index(["C", "B"], inplace=True) + s = mi.stack() + s.index = s.index.droplevel(2) + store.append("mi", s) + tm.assert_series_equal(store["mi"], s) + + +def test_append_some_nans(setup_path): + + with ensure_clean_store(setup_path) as store: + df = DataFrame( + { + "A": Series(np.random.randn(20)).astype("int32"), + "A1": np.random.randn(20), + "A2": np.random.randn(20), + "B": "foo", + "C": "bar", + "D": Timestamp("20010101"), + "E": datetime.datetime(2001, 1, 2, 0, 0), + }, + index=np.arange(20), + ) + # some nans + _maybe_remove(store, "df1") + df.loc[0:15, ["A1", "B", "D", "E"]] = np.nan + store.append("df1", df[:10]) + store.append("df1", df[10:]) + tm.assert_frame_equal(store["df1"], df) + + # first column + df1 = df.copy() + df1.loc[:, "A1"] = np.nan + _maybe_remove(store, "df1") + store.append("df1", df1[:10]) + store.append("df1", df1[10:]) + tm.assert_frame_equal(store["df1"], df1) + + # 2nd column + df2 = df.copy() + df2.loc[:, "A2"] = np.nan + _maybe_remove(store, "df2") + store.append("df2", df2[:10]) + store.append("df2", df2[10:]) + tm.assert_frame_equal(store["df2"], df2) + + # datetimes + df3 = df.copy() + df3.loc[:, "E"] = np.nan + _maybe_remove(store, "df3") + store.append("df3", df3[:10]) + store.append("df3", df3[10:]) + tm.assert_frame_equal(store["df3"], df3) + + +def test_append_all_nans(setup_path): + + with ensure_clean_store(setup_path) as store: + + df = DataFrame( + {"A1": np.random.randn(20), "A2": np.random.randn(20)}, + index=np.arange(20), + ) + df.loc[0:15, :] = np.nan + + # nan some entire rows (dropna=True) + _maybe_remove(store, "df") + store.append("df", df[:10], dropna=True) + store.append("df", df[10:], dropna=True) + tm.assert_frame_equal(store["df"], df[-4:]) + + # nan some entire rows (dropna=False) + _maybe_remove(store, "df2") + store.append("df2", df[:10], dropna=False) + store.append("df2", df[10:], dropna=False) + tm.assert_frame_equal(store["df2"], df) + + # tests the option io.hdf.dropna_table + pd.set_option("io.hdf.dropna_table", False) + _maybe_remove(store, "df3") + store.append("df3", df[:10]) + store.append("df3", df[10:]) + tm.assert_frame_equal(store["df3"], df) + + pd.set_option("io.hdf.dropna_table", True) + _maybe_remove(store, "df4") + store.append("df4", df[:10]) + store.append("df4", df[10:]) + tm.assert_frame_equal(store["df4"], df[-4:]) + + # nan some entire rows (string are still written!) + df = DataFrame( + { + "A1": np.random.randn(20), + "A2": np.random.randn(20), + "B": "foo", + "C": "bar", + }, + index=np.arange(20), + ) + + df.loc[0:15, :] = np.nan + + _maybe_remove(store, "df") + store.append("df", df[:10], dropna=True) + store.append("df", df[10:], dropna=True) + tm.assert_frame_equal(store["df"], df) + + _maybe_remove(store, "df2") + store.append("df2", df[:10], dropna=False) + store.append("df2", df[10:], dropna=False) + tm.assert_frame_equal(store["df2"], df) + + # nan some entire rows (but since we have dates they are still + # written!) + df = DataFrame( + { + "A1": np.random.randn(20), + "A2": np.random.randn(20), + "B": "foo", + "C": "bar", + "D": Timestamp("20010101"), + "E": datetime.datetime(2001, 1, 2, 0, 0), + }, + index=np.arange(20), + ) + + df.loc[0:15, :] = np.nan + + _maybe_remove(store, "df") + store.append("df", df[:10], dropna=True) + store.append("df", df[10:], dropna=True) + tm.assert_frame_equal(store["df"], df) + + _maybe_remove(store, "df2") + store.append("df2", df[:10], dropna=False) + store.append("df2", df[10:], dropna=False) + tm.assert_frame_equal(store["df2"], df) + + +def test_append_frame_column_oriented(setup_path): + with ensure_clean_store(setup_path) as store: + + # column oriented + df = tm.makeTimeDataFrame() + df.index = df.index._with_freq(None) # freq doesnt round-trip + + _maybe_remove(store, "df1") + store.append("df1", df.iloc[:, :2], axes=["columns"]) + store.append("df1", df.iloc[:, 2:]) + tm.assert_frame_equal(store["df1"], df) + + result = store.select("df1", "columns=A") + expected = df.reindex(columns=["A"]) + tm.assert_frame_equal(expected, result) + + # selection on the non-indexable + result = store.select("df1", ("columns=A", "index=df.index[0:4]")) + expected = df.reindex(columns=["A"], index=df.index[0:4]) + tm.assert_frame_equal(expected, result) + + # this isn't supported + msg = re.escape( + "passing a filterable condition to a non-table indexer " + "[Filter: Not Initialized]" + ) + with pytest.raises(TypeError, match=msg): + store.select("df1", "columns=A and index>df.index[4]") + + +def test_append_with_different_block_ordering(setup_path): + + # GH 4096; using same frames, but different block orderings + with ensure_clean_store(setup_path) as store: + + for i in range(10): + + df = DataFrame(np.random.randn(10, 2), columns=list("AB")) + df["index"] = range(10) + df["index"] += i * 10 + df["int64"] = Series([1] * len(df), dtype="int64") + df["int16"] = Series([1] * len(df), dtype="int16") + + if i % 2 == 0: + del df["int64"] + df["int64"] = Series([1] * len(df), dtype="int64") + if i % 3 == 0: + a = df.pop("A") + df["A"] = a + + df.set_index("index", inplace=True) + + store.append("df", df) + + # test a different ordering but with more fields (like invalid + # combinate) + with ensure_clean_store(setup_path) as store: + + df = DataFrame(np.random.randn(10, 2), columns=list("AB"), dtype="float64") + df["int64"] = Series([1] * len(df), dtype="int64") + df["int16"] = Series([1] * len(df), dtype="int16") + store.append("df", df) + + # store additional fields in different blocks + df["int16_2"] = Series([1] * len(df), dtype="int16") + msg = re.escape( + "cannot match existing table structure for [int16] on appending data" + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + # store multiple additional fields in different blocks + df["float_3"] = Series([1.0] * len(df), dtype="float64") + msg = re.escape( + "cannot match existing table structure for [A,B] on appending data" + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + +def test_append_with_strings(setup_path): + + with ensure_clean_store(setup_path) as store: + with catch_warnings(record=True): + + def check_col(key, name, size): + assert ( + getattr(store.get_storer(key).table.description, name).itemsize + == size + ) + + # avoid truncation on elements + df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]]) + store.append("df_big", df) + tm.assert_frame_equal(store.select("df_big"), df) + check_col("df_big", "values_block_1", 15) + + # appending smaller string ok + df2 = DataFrame([[124, "asdqy"], [346, "dggnhefbdfb"]]) + store.append("df_big", df2) + expected = concat([df, df2]) + tm.assert_frame_equal(store.select("df_big"), expected) + check_col("df_big", "values_block_1", 15) + + # avoid truncation on elements + df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]]) + store.append("df_big2", df, min_itemsize={"values": 50}) + tm.assert_frame_equal(store.select("df_big2"), df) + check_col("df_big2", "values_block_1", 50) + + # bigger string on next append + store.append("df_new", df) + df_new = DataFrame( + [[124, "abcdefqhij"], [346, "abcdefghijklmnopqrtsuvwxyz"]] + ) + msg = ( + r"Trying to store a string with len \[26\] in " + r"\[values_block_1\] column but\n" + r"this column has a limit of \[15\]!\n" + "Consider using min_itemsize to preset the sizes on these " + "columns" + ) + with pytest.raises(ValueError, match=msg): + store.append("df_new", df_new) + + # min_itemsize on Series index (GH 11412) + df = tm.makeMixedDataFrame().set_index("C") + store.append("ss", df["B"], min_itemsize={"index": 4}) + tm.assert_series_equal(store.select("ss"), df["B"]) + + # same as above, with data_columns=True + store.append("ss2", df["B"], data_columns=True, min_itemsize={"index": 4}) + tm.assert_series_equal(store.select("ss2"), df["B"]) + + # min_itemsize in index without appending (GH 10381) + store.put("ss3", df, format="table", min_itemsize={"index": 6}) + # just make sure there is a longer string: + df2 = df.copy().reset_index().assign(C="longer").set_index("C") + store.append("ss3", df2) + tm.assert_frame_equal(store.select("ss3"), pd.concat([df, df2])) + + # same as above, with a Series + store.put("ss4", df["B"], format="table", min_itemsize={"index": 6}) + store.append("ss4", df2["B"]) + tm.assert_series_equal(store.select("ss4"), pd.concat([df["B"], df2["B"]])) + + # with nans + _maybe_remove(store, "df") + df = tm.makeTimeDataFrame() + df["string"] = "foo" + df.loc[df.index[1:4], "string"] = np.nan + df["string2"] = "bar" + df.loc[df.index[4:8], "string2"] = np.nan + df["string3"] = "bah" + df.loc[df.index[1:], "string3"] = np.nan + store.append("df", df) + result = store.select("df") + tm.assert_frame_equal(result, df) + + with ensure_clean_store(setup_path) as store: + + def check_col(key, name, size): + assert getattr(store.get_storer(key).table.description, name).itemsize, size + + df = DataFrame({"A": "foo", "B": "bar"}, index=range(10)) + + # a min_itemsize that creates a data_column + _maybe_remove(store, "df") + store.append("df", df, min_itemsize={"A": 200}) + check_col("df", "A", 200) + assert store.get_storer("df").data_columns == ["A"] + + # a min_itemsize that creates a data_column2 + _maybe_remove(store, "df") + store.append("df", df, data_columns=["B"], min_itemsize={"A": 200}) + check_col("df", "A", 200) + assert store.get_storer("df").data_columns == ["B", "A"] + + # a min_itemsize that creates a data_column2 + _maybe_remove(store, "df") + store.append("df", df, data_columns=["B"], min_itemsize={"values": 200}) + check_col("df", "B", 200) + check_col("df", "values_block_0", 200) + assert store.get_storer("df").data_columns == ["B"] + + # infer the .typ on subsequent appends + _maybe_remove(store, "df") + store.append("df", df[:5], min_itemsize=200) + store.append("df", df[5:], min_itemsize=200) + tm.assert_frame_equal(store["df"], df) + + # invalid min_itemsize keys + df = DataFrame(["foo", "foo", "foo", "barh", "barh", "barh"], columns=["A"]) + _maybe_remove(store, "df") + msg = re.escape( + "min_itemsize has the key [foo] which is not an axis or data_column" + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df, min_itemsize={"foo": 20, "foobar": 20}) + + +def test_append_with_empty_string(setup_path): + + with ensure_clean_store(setup_path) as store: + + # with all empty strings (GH 12242) + df = DataFrame({"x": ["a", "b", "c", "d", "e", "f", ""]}) + store.append("df", df[:-1], min_itemsize={"x": 1}) + store.append("df", df[-1:], min_itemsize={"x": 1}) + tm.assert_frame_equal(store.select("df"), df) + + +def test_append_with_data_columns(setup_path): + + with ensure_clean_store(setup_path) as store: + df = tm.makeTimeDataFrame() + df.iloc[0, df.columns.get_loc("B")] = 1.0 + _maybe_remove(store, "df") + store.append("df", df[:2], data_columns=["B"]) + store.append("df", df[2:]) + tm.assert_frame_equal(store["df"], df) + + # check that we have indices created + assert store._handle.root.df.table.cols.index.is_indexed is True + assert store._handle.root.df.table.cols.B.is_indexed is True + + # data column searching + result = store.select("df", "B>0") + expected = df[df.B > 0] + tm.assert_frame_equal(result, expected) + + # data column searching (with an indexable and a data_columns) + result = store.select("df", "B>0 and index>df.index[3]") + df_new = df.reindex(index=df.index[4:]) + expected = df_new[df_new.B > 0] + tm.assert_frame_equal(result, expected) + + # data column selection with a string data_column + df_new = df.copy() + df_new["string"] = "foo" + df_new.loc[df_new.index[1:4], "string"] = np.nan + df_new.loc[df_new.index[5:6], "string"] = "bar" + _maybe_remove(store, "df") + store.append("df", df_new, data_columns=["string"]) + result = store.select("df", "string='foo'") + expected = df_new[df_new.string == "foo"] + tm.assert_frame_equal(result, expected) + + # using min_itemsize and a data column + def check_col(key, name, size): + assert ( + getattr(store.get_storer(key).table.description, name).itemsize == size + ) + + with ensure_clean_store(setup_path) as store: + _maybe_remove(store, "df") + store.append("df", df_new, data_columns=["string"], min_itemsize={"string": 30}) + check_col("df", "string", 30) + _maybe_remove(store, "df") + store.append("df", df_new, data_columns=["string"], min_itemsize=30) + check_col("df", "string", 30) + _maybe_remove(store, "df") + store.append("df", df_new, data_columns=["string"], min_itemsize={"values": 30}) + check_col("df", "string", 30) + + with ensure_clean_store(setup_path) as store: + df_new["string2"] = "foobarbah" + df_new["string_block1"] = "foobarbah1" + df_new["string_block2"] = "foobarbah2" + _maybe_remove(store, "df") + store.append( + "df", + df_new, + data_columns=["string", "string2"], + min_itemsize={"string": 30, "string2": 40, "values": 50}, + ) + check_col("df", "string", 30) + check_col("df", "string2", 40) + check_col("df", "values_block_1", 50) + + with ensure_clean_store(setup_path) as store: + # multiple data columns + df_new = df.copy() + df_new.iloc[0, df_new.columns.get_loc("A")] = 1.0 + df_new.iloc[0, df_new.columns.get_loc("B")] = -1.0 + df_new["string"] = "foo" + + sl = df_new.columns.get_loc("string") + df_new.iloc[1:4, sl] = np.nan + df_new.iloc[5:6, sl] = "bar" + + df_new["string2"] = "foo" + sl = df_new.columns.get_loc("string2") + df_new.iloc[2:5, sl] = np.nan + df_new.iloc[7:8, sl] = "bar" + _maybe_remove(store, "df") + store.append("df", df_new, data_columns=["A", "B", "string", "string2"]) + result = store.select("df", "string='foo' and string2='foo' and A>0 and B<0") + expected = df_new[ + (df_new.string == "foo") + & (df_new.string2 == "foo") + & (df_new.A > 0) + & (df_new.B < 0) + ] + tm.assert_frame_equal(result, expected, check_freq=False) + # FIXME: 2020-05-07 freq check randomly fails in the CI + + # yield an empty frame + result = store.select("df", "string='foo' and string2='cool'") + expected = df_new[(df_new.string == "foo") & (df_new.string2 == "cool")] + tm.assert_frame_equal(result, expected) + + with ensure_clean_store(setup_path) as store: + # doc example + df_dc = df.copy() + df_dc["string"] = "foo" + df_dc.loc[df_dc.index[4:6], "string"] = np.nan + df_dc.loc[df_dc.index[7:9], "string"] = "bar" + df_dc["string2"] = "cool" + df_dc["datetime"] = Timestamp("20010102") + df_dc = df_dc._convert(datetime=True) + df_dc.loc[df_dc.index[3:5], ["A", "B", "datetime"]] = np.nan + + _maybe_remove(store, "df_dc") + store.append( + "df_dc", df_dc, data_columns=["B", "C", "string", "string2", "datetime"] + ) + result = store.select("df_dc", "B>0") + + expected = df_dc[df_dc.B > 0] + tm.assert_frame_equal(result, expected) + + result = store.select("df_dc", ["B > 0", "C > 0", "string == foo"]) + expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == "foo")] + tm.assert_frame_equal(result, expected, check_freq=False) + # FIXME: 2020-12-07 intermittent build failures here with freq of + # None instead of BDay(4) + + with ensure_clean_store(setup_path) as store: + # doc example part 2 + np.random.seed(1234) + index = date_range("1/1/2000", periods=8) + df_dc = DataFrame(np.random.randn(8, 3), index=index, columns=["A", "B", "C"]) + df_dc["string"] = "foo" + df_dc.loc[df_dc.index[4:6], "string"] = np.nan + df_dc.loc[df_dc.index[7:9], "string"] = "bar" + df_dc.loc[:, ["B", "C"]] = df_dc.loc[:, ["B", "C"]].abs() + df_dc["string2"] = "cool" + + # on-disk operations + store.append("df_dc", df_dc, data_columns=["B", "C", "string", "string2"]) + + result = store.select("df_dc", "B>0") + expected = df_dc[df_dc.B > 0] + tm.assert_frame_equal(result, expected) + + result = store.select("df_dc", ["B > 0", "C > 0", 'string == "foo"']) + expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == "foo")] + tm.assert_frame_equal(result, expected) + + +def test_append_hierarchical(setup_path): + index = MultiIndex( + levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["foo", "bar"], + ) + df = DataFrame(np.random.randn(10, 3), index=index, columns=["A", "B", "C"]) + + with ensure_clean_store(setup_path) as store: + store.append("mi", df) + result = store.select("mi") + tm.assert_frame_equal(result, df) + + # GH 3748 + result = store.select("mi", columns=["A", "B"]) + expected = df.reindex(columns=["A", "B"]) + tm.assert_frame_equal(result, expected) + + with ensure_clean_path("test.hdf") as path: + df.to_hdf(path, "df", format="table") + result = read_hdf(path, "df", columns=["A", "B"]) + expected = df.reindex(columns=["A", "B"]) + tm.assert_frame_equal(result, expected) + + +def test_append_misc(setup_path): + + with ensure_clean_store(setup_path) as store: + df = tm.makeDataFrame() + store.append("df", df, chunksize=1) + result = store.select("df") + tm.assert_frame_equal(result, df) + + store.append("df1", df, expectedrows=10) + result = store.select("df1") + tm.assert_frame_equal(result, df) + + # more chunksize in append tests + def check(obj, comparator): + for c in [10, 200, 1000]: + with ensure_clean_store(setup_path, mode="w") as store: + store.append("obj", obj, chunksize=c) + result = store.select("obj") + comparator(result, obj) + + df = tm.makeDataFrame() + df["string"] = "foo" + df["float322"] = 1.0 + df["float322"] = df["float322"].astype("float32") + df["bool"] = df["float322"] > 0 + df["time1"] = Timestamp("20130101") + df["time2"] = Timestamp("20130102") + check(df, tm.assert_frame_equal) + + # empty frame, GH4273 + with ensure_clean_store(setup_path) as store: + + # 0 len + df_empty = DataFrame(columns=list("ABC")) + store.append("df", df_empty) + with pytest.raises(KeyError, match="'No object named df in the file'"): + store.select("df") + + # repeated append of 0/non-zero frames + df = DataFrame(np.random.rand(10, 3), columns=list("ABC")) + store.append("df", df) + tm.assert_frame_equal(store.select("df"), df) + store.append("df", df_empty) + tm.assert_frame_equal(store.select("df"), df) + + # store + df = DataFrame(columns=list("ABC")) + store.put("df2", df) + tm.assert_frame_equal(store.select("df2"), df) + + +def test_append_raise(setup_path): + + with ensure_clean_store(setup_path) as store: + + # test append with invalid input to get good error messages + + # list in column + df = tm.makeDataFrame() + df["invalid"] = [["a"]] * len(df) + assert df.dtypes["invalid"] == np.object_ + msg = re.escape( + """Cannot serialize the column [invalid] +because its data contents are not [string] but [mixed] object dtype""" + ) + with pytest.raises(TypeError, match=msg): + store.append("df", df) + + # multiple invalid columns + df["invalid2"] = [["a"]] * len(df) + df["invalid3"] = [["a"]] * len(df) + with pytest.raises(TypeError, match=msg): + store.append("df", df) + + # datetime with embedded nans as object + df = tm.makeDataFrame() + s = Series(datetime.datetime(2001, 1, 2), index=df.index) + s = s.astype(object) + s[0:5] = np.nan + df["invalid"] = s + assert df.dtypes["invalid"] == np.object_ + msg = "too many timezones in this block, create separate data columns" + with pytest.raises(TypeError, match=msg): + store.append("df", df) + + # directly ndarray + msg = "value must be None, Series, or DataFrame" + with pytest.raises(TypeError, match=msg): + store.append("df", np.arange(10)) + + # series directly + msg = re.escape( + "cannot properly create the storer for: " + "[group->df,value-><class 'pandas.core.series.Series'>]" + ) + with pytest.raises(TypeError, match=msg): + store.append("df", Series(np.arange(10))) + + # appending an incompatible table + df = tm.makeDataFrame() + store.append("df", df) + + df["foo"] = "foo" + msg = re.escape( + "invalid combination of [non_index_axes] on appending data " + "[(1, ['A', 'B', 'C', 'D', 'foo'])] vs current table " + "[(1, ['A', 'B', 'C', 'D'])]" + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + +def test_append_with_timedelta(setup_path): + # GH 3577 + # append timedelta + + df = DataFrame( + { + "A": Timestamp("20130101"), + "B": [ + Timestamp("20130101") + timedelta(days=i, seconds=10) for i in range(10) + ], + } + ) + df["C"] = df["A"] - df["B"] + df.loc[3:5, "C"] = np.nan + + with ensure_clean_store(setup_path) as store: + + # table + _maybe_remove(store, "df") + store.append("df", df, data_columns=True) + result = store.select("df") + tm.assert_frame_equal(result, df) + + result = store.select("df", where="C<100000") + tm.assert_frame_equal(result, df) + + result = store.select("df", where="C<pd.Timedelta('-3D')") + tm.assert_frame_equal(result, df.iloc[3:]) + + result = store.select("df", "C<'-3D'") + tm.assert_frame_equal(result, df.iloc[3:]) + + # a bit hacky here as we don't really deal with the NaT properly + + result = store.select("df", "C<'-500000s'") + result = result.dropna(subset=["C"]) + tm.assert_frame_equal(result, df.iloc[6:]) + + result = store.select("df", "C<'-3.5D'") + result = result.iloc[1:] + tm.assert_frame_equal(result, df.iloc[4:]) + + # fixed + _maybe_remove(store, "df2") + store.put("df2", df) + result = store.select("df2") + tm.assert_frame_equal(result, df) + + +def test_append_to_multiple(setup_path): + df1 = tm.makeTimeDataFrame() + df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) + df2["foo"] = "bar" + df = concat([df1, df2], axis=1) + + with ensure_clean_store(setup_path) as store: + + # exceptions + msg = "append_to_multiple requires a selector that is in passed dict" + with pytest.raises(ValueError, match=msg): + store.append_to_multiple( + {"df1": ["A", "B"], "df2": None}, df, selector="df3" + ) + + with pytest.raises(ValueError, match=msg): + store.append_to_multiple({"df1": None, "df2": None}, df, selector="df3") + + msg = ( + "append_to_multiple must have a dictionary specified as the way to " + "split the value" + ) + with pytest.raises(ValueError, match=msg): + store.append_to_multiple("df1", df, "df1") + + # regular operation + store.append_to_multiple({"df1": ["A", "B"], "df2": None}, df, selector="df1") + result = store.select_as_multiple( + ["df1", "df2"], where=["A>0", "B>0"], selector="df1" + ) + expected = df[(df.A > 0) & (df.B > 0)] + tm.assert_frame_equal(result, expected) + + +def test_append_to_multiple_dropna(setup_path): + df1 = tm.makeTimeDataFrame() + df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) + df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan + df = concat([df1, df2], axis=1) + + with ensure_clean_store(setup_path) as store: + + # dropna=True should guarantee rows are synchronized + store.append_to_multiple( + {"df1": ["A", "B"], "df2": None}, df, selector="df1", dropna=True + ) + result = store.select_as_multiple(["df1", "df2"]) + expected = df.dropna() + tm.assert_frame_equal(result, expected) + tm.assert_index_equal(store.select("df1").index, store.select("df2").index) + + +@pytest.mark.xfail( + run=False, reason="append_to_multiple_dropna_false is not raising as failed" +) +def test_append_to_multiple_dropna_false(setup_path): + df1 = tm.makeTimeDataFrame() + df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) + df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan + df = concat([df1, df2], axis=1) + + with ensure_clean_store(setup_path) as store: + + # dropna=False shouldn't synchronize row indexes + store.append_to_multiple( + {"df1a": ["A", "B"], "df2a": None}, df, selector="df1a", dropna=False + ) + + # TODO Update error message to desired message for this case + msg = "Cannot select as multiple after appending with dropna=False" + with pytest.raises(ValueError, match=msg): + store.select_as_multiple(["df1a", "df2a"]) + + assert not store.select("df1a").index.equals(store.select("df2a").index) + + +def test_append_to_multiple_min_itemsize(setup_path): + # GH 11238 + df = DataFrame( + { + "IX": np.arange(1, 21), + "Num": np.arange(1, 21), + "BigNum": np.arange(1, 21) * 88, + "Str": ["a" for _ in range(20)], + "LongStr": ["abcde" for _ in range(20)], + } + ) + expected = df.iloc[[0]] + + with ensure_clean_store(setup_path) as store: + store.append_to_multiple( + { + "index": ["IX"], + "nums": ["Num", "BigNum"], + "strs": ["Str", "LongStr"], + }, + df.iloc[[0]], + "index", + min_itemsize={"Str": 10, "LongStr": 100, "Num": 2}, + ) + result = store.select_as_multiple(["index", "nums", "strs"]) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/pytables/test_categorical.py b/pandas/tests/io/pytables/test_categorical.py new file mode 100644 index 0000000000000..67209c2bc0d57 --- /dev/null +++ b/pandas/tests/io/pytables/test_categorical.py @@ -0,0 +1,186 @@ +import numpy as np +import pytest + +from pandas import Categorical, DataFrame, Series, _testing as tm, concat, read_hdf +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_path, + ensure_clean_store, +) + +pytestmark = pytest.mark.single + + +def test_categorical(setup_path): + + with ensure_clean_store(setup_path) as store: + + # Basic + _maybe_remove(store, "s") + s = Series( + Categorical( + ["a", "b", "b", "a", "a", "c"], + categories=["a", "b", "c", "d"], + ordered=False, + ) + ) + store.append("s", s, format="table") + result = store.select("s") + tm.assert_series_equal(s, result) + + _maybe_remove(store, "s_ordered") + s = Series( + Categorical( + ["a", "b", "b", "a", "a", "c"], + categories=["a", "b", "c", "d"], + ordered=True, + ) + ) + store.append("s_ordered", s, format="table") + result = store.select("s_ordered") + tm.assert_series_equal(s, result) + + _maybe_remove(store, "df") + df = DataFrame({"s": s, "vals": [1, 2, 3, 4, 5, 6]}) + store.append("df", df, format="table") + result = store.select("df") + tm.assert_frame_equal(result, df) + + # Dtypes + _maybe_remove(store, "si") + s = Series([1, 1, 2, 2, 3, 4, 5]).astype("category") + store.append("si", s) + result = store.select("si") + tm.assert_series_equal(result, s) + + _maybe_remove(store, "si2") + s = Series([1, 1, np.nan, 2, 3, 4, 5]).astype("category") + store.append("si2", s) + result = store.select("si2") + tm.assert_series_equal(result, s) + + # Multiple + _maybe_remove(store, "df2") + df2 = df.copy() + df2["s2"] = Series(list("abcdefg")).astype("category") + store.append("df2", df2) + result = store.select("df2") + tm.assert_frame_equal(result, df2) + + # Make sure the metadata is OK + info = store.info() + assert "/df2 " in info + # assert '/df2/meta/values_block_0/meta' in info + assert "/df2/meta/values_block_1/meta" in info + + # unordered + _maybe_remove(store, "s2") + s = Series( + Categorical( + ["a", "b", "b", "a", "a", "c"], + categories=["a", "b", "c", "d"], + ordered=False, + ) + ) + store.append("s2", s, format="table") + result = store.select("s2") + tm.assert_series_equal(result, s) + + # Query + _maybe_remove(store, "df3") + store.append("df3", df, data_columns=["s"]) + expected = df[df.s.isin(["b", "c"])] + result = store.select("df3", where=['s in ["b","c"]']) + tm.assert_frame_equal(result, expected) + + expected = df[df.s.isin(["b", "c"])] + result = store.select("df3", where=['s = ["b","c"]']) + tm.assert_frame_equal(result, expected) + + expected = df[df.s.isin(["d"])] + result = store.select("df3", where=['s in ["d"]']) + tm.assert_frame_equal(result, expected) + + expected = df[df.s.isin(["f"])] + result = store.select("df3", where=['s in ["f"]']) + tm.assert_frame_equal(result, expected) + + # Appending with same categories is ok + store.append("df3", df) + + df = concat([df, df]) + expected = df[df.s.isin(["b", "c"])] + result = store.select("df3", where=['s in ["b","c"]']) + tm.assert_frame_equal(result, expected) + + # Appending must have the same categories + df3 = df.copy() + df3["s"] = df3["s"].cat.remove_unused_categories() + + msg = "cannot append a categorical with different categories to the existing" + with pytest.raises(ValueError, match=msg): + store.append("df3", df3) + + # Remove, and make sure meta data is removed (its a recursive + # removal so should be). + result = store.select("df3/meta/s/meta") + assert result is not None + store.remove("df3") + + with pytest.raises( + KeyError, match="'No object named df3/meta/s/meta in the file'" + ): + store.select("df3/meta/s/meta") + + +def test_categorical_conversion(setup_path): + + # GH13322 + # Check that read_hdf with categorical columns doesn't return rows if + # where criteria isn't met. + obsids = ["ESP_012345_6789", "ESP_987654_3210"] + imgids = ["APF00006np", "APF0001imm"] + data = [4.3, 9.8] + + # Test without categories + df = DataFrame({"obsids": obsids, "imgids": imgids, "data": data}) + + # We are expecting an empty DataFrame matching types of df + expected = df.iloc[[], :] + with ensure_clean_path(setup_path) as path: + df.to_hdf(path, "df", format="table", data_columns=True) + result = read_hdf(path, "df", where="obsids=B") + tm.assert_frame_equal(result, expected) + + # Test with categories + df.obsids = df.obsids.astype("category") + df.imgids = df.imgids.astype("category") + + # We are expecting an empty DataFrame matching types of df + expected = df.iloc[[], :] + with ensure_clean_path(setup_path) as path: + df.to_hdf(path, "df", format="table", data_columns=True) + result = read_hdf(path, "df", where="obsids=B") + tm.assert_frame_equal(result, expected) + + +def test_categorical_nan_only_columns(setup_path): + # GH18413 + # Check that read_hdf with categorical columns with NaN-only values can + # be read back. + df = DataFrame( + { + "a": ["a", "b", "c", np.nan], + "b": [np.nan, np.nan, np.nan, np.nan], + "c": [1, 2, 3, 4], + "d": Series([None] * 4, dtype=object), + } + ) + df["a"] = df.a.astype("category") + df["b"] = df.b.astype("category") + df["d"] = df.b.astype("category") + expected = df + with ensure_clean_path(setup_path) as path: + df.to_hdf(path, "df", format="table", data_columns=True) + result = read_hdf(path, "df") + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/pytables/test_errors.py b/pandas/tests/io/pytables/test_errors.py new file mode 100644 index 0000000000000..24bd573341dc4 --- /dev/null +++ b/pandas/tests/io/pytables/test_errors.py @@ -0,0 +1,234 @@ +import datetime +from io import BytesIO +import re +from warnings import catch_warnings + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + CategoricalIndex, + DataFrame, + HDFStore, + MultiIndex, + _testing as tm, + date_range, + read_hdf, +) +from pandas.tests.io.pytables.common import ensure_clean_path, ensure_clean_store + +from pandas.io.pytables import Term, _maybe_adjust_name + +pytestmark = pytest.mark.single + + +def test_pass_spec_to_storer(setup_path): + + df = tm.makeDataFrame() + + with ensure_clean_store(setup_path) as store: + store.put("df", df) + msg = ( + "cannot pass a column specification when reading a Fixed format " + "store. this store must be selected in its entirety" + ) + with pytest.raises(TypeError, match=msg): + store.select("df", columns=["A"]) + msg = ( + "cannot pass a where specification when reading from a Fixed " + "format store. this store must be selected in its entirety" + ) + with pytest.raises(TypeError, match=msg): + store.select("df", where=[("columns=A")]) + + +def test_table_index_incompatible_dtypes(setup_path): + df1 = DataFrame({"a": [1, 2, 3]}) + df2 = DataFrame({"a": [4, 5, 6]}, index=date_range("1/1/2000", periods=3)) + + with ensure_clean_store(setup_path) as store: + store.put("frame", df1, format="table") + msg = re.escape("incompatible kind in col [integer - datetime64]") + with pytest.raises(TypeError, match=msg): + store.put("frame", df2, format="table", append=True) + + +def test_unimplemented_dtypes_table_columns(setup_path): + + with ensure_clean_store(setup_path) as store: + + dtypes = [("date", datetime.date(2001, 1, 2))] + + # currently not supported dtypes #### + for n, f in dtypes: + df = tm.makeDataFrame() + df[n] = f + msg = re.escape(f"[{n}] is not implemented as a table column") + with pytest.raises(TypeError, match=msg): + store.append(f"df1_{n}", df) + + # frame + df = tm.makeDataFrame() + df["obj1"] = "foo" + df["obj2"] = "bar" + df["datetime1"] = datetime.date(2001, 1, 2) + df = df._consolidate()._convert(datetime=True) + + with ensure_clean_store(setup_path) as store: + # this fails because we have a date in the object block...... + msg = re.escape( + """Cannot serialize the column [datetime1] +because its data contents are not [string] but [date] object dtype""" + ) + with pytest.raises(TypeError, match=msg): + store.append("df_unimplemented", df) + + +def test_invalid_terms(setup_path): + + with ensure_clean_store(setup_path) as store: + + with catch_warnings(record=True): + + df = tm.makeTimeDataFrame() + df["string"] = "foo" + df.loc[df.index[0:4], "string"] = "bar" + + store.put("df", df, format="table") + + # some invalid terms + msg = re.escape( + "__init__() missing 1 required positional argument: 'where'" + ) + with pytest.raises(TypeError, match=msg): + Term() + + # more invalid + msg = re.escape( + "cannot process expression [df.index[3]], " + "[2000-01-06 00:00:00] is not a valid condition" + ) + with pytest.raises(ValueError, match=msg): + store.select("df", "df.index[3]") + + msg = "invalid syntax" + with pytest.raises(SyntaxError, match=msg): + store.select("df", "index>") + + # from the docs + with ensure_clean_path(setup_path) as path: + dfq = DataFrame( + np.random.randn(10, 4), + columns=list("ABCD"), + index=date_range("20130101", periods=10), + ) + dfq.to_hdf(path, "dfq", format="table", data_columns=True) + + # check ok + read_hdf(path, "dfq", where="index>Timestamp('20130104') & columns=['A', 'B']") + read_hdf(path, "dfq", where="A>0 or C>0") + + # catch the invalid reference + with ensure_clean_path(setup_path) as path: + dfq = DataFrame( + np.random.randn(10, 4), + columns=list("ABCD"), + index=date_range("20130101", periods=10), + ) + dfq.to_hdf(path, "dfq", format="table") + + msg = ( + r"The passed where expression: A>0 or C>0\n\s*" + r"contains an invalid variable reference\n\s*" + r"all of the variable references must be a reference to\n\s*" + r"an axis \(e.g. 'index' or 'columns'\), or a data_column\n\s*" + r"The currently defined references are: index,columns\n" + ) + with pytest.raises(ValueError, match=msg): + read_hdf(path, "dfq", where="A>0 or C>0") + + +def test_append_with_diff_col_name_types_raises_value_error(setup_path): + df = DataFrame(np.random.randn(10, 1)) + df2 = DataFrame({"a": np.random.randn(10)}) + df3 = DataFrame({(1, 2): np.random.randn(10)}) + df4 = DataFrame({("1", 2): np.random.randn(10)}) + df5 = DataFrame({("1", 2, object): np.random.randn(10)}) + + with ensure_clean_store(setup_path) as store: + name = f"df_{tm.rands(10)}" + store.append(name, df) + + for d in (df2, df3, df4, df5): + msg = re.escape( + "cannot match existing table structure for [0] on appending data" + ) + with pytest.raises(ValueError, match=msg): + store.append(name, d) + + +def test_invalid_complib(setup_path): + df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) + with tm.ensure_clean(setup_path) as path: + msg = r"complib only supports \[.*\] compression." + with pytest.raises(ValueError, match=msg): + df.to_hdf(path, "df", complib="foolib") + + +@pytest.mark.parametrize( + "idx", + [ + date_range("2019", freq="D", periods=3, tz="UTC"), + CategoricalIndex(list("abc")), + ], +) +def test_to_hdf_multiindex_extension_dtype(idx, setup_path): + # GH 7775 + mi = MultiIndex.from_arrays([idx, idx]) + df = DataFrame(0, index=mi, columns=["a"]) + with ensure_clean_path(setup_path) as path: + with pytest.raises(NotImplementedError, match="Saving a MultiIndex"): + df.to_hdf(path, "df") + + +def test_unsuppored_hdf_file_error(datapath): + # GH 9539 + data_path = datapath("io", "data", "legacy_hdf/incompatible_dataset.h5") + message = ( + r"Dataset\(s\) incompatible with Pandas data types, " + "not table, or no datasets found in HDF5 file." + ) + + with pytest.raises(ValueError, match=message): + pd.read_hdf(data_path) + + +def test_read_hdf_errors(setup_path): + df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) + + with ensure_clean_path(setup_path) as path: + msg = r"File [\S]* does not exist" + with pytest.raises(IOError, match=msg): + read_hdf(path, "key") + + df.to_hdf(path, "df") + store = HDFStore(path, mode="r") + store.close() + + msg = "The HDFStore must be open for reading." + with pytest.raises(IOError, match=msg): + read_hdf(store, "df") + + +def test_read_hdf_generic_buffer_errors(): + msg = "Support for generic buffers has not been implemented." + with pytest.raises(NotImplementedError, match=msg): + read_hdf(BytesIO(b""), "df") + + +@pytest.mark.parametrize("bad_version", [(1, 2), (1,), [], "12", "123"]) +def test_maybe_adjust_name_bad_version_raises(bad_version): + msg = "Version is incorrect, expected sequence of 3 integers" + with pytest.raises(ValueError, match=msg): + _maybe_adjust_name("values_block_0", version=bad_version) diff --git a/pandas/tests/io/pytables/test_file_handling.py b/pandas/tests/io/pytables/test_file_handling.py new file mode 100644 index 0000000000000..e0e995e03064f --- /dev/null +++ b/pandas/tests/io/pytables/test_file_handling.py @@ -0,0 +1,445 @@ +import os + +import numpy as np +import pytest + +from pandas.compat import is_platform_little_endian + +import pandas as pd +from pandas import DataFrame, HDFStore, Series, _testing as tm, read_hdf +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_path, + ensure_clean_store, + tables, +) + +from pandas.io import pytables as pytables +from pandas.io.pytables import ClosedFileError, PossibleDataLossError, Term + +pytestmark = pytest.mark.single + + +def test_mode(setup_path): + + df = tm.makeTimeDataFrame() + + def check(mode): + + msg = r"[\S]* does not exist" + with ensure_clean_path(setup_path) as path: + + # constructor + if mode in ["r", "r+"]: + with pytest.raises(IOError, match=msg): + HDFStore(path, mode=mode) + + else: + store = HDFStore(path, mode=mode) + assert store._handle.mode == mode + store.close() + + with ensure_clean_path(setup_path) as path: + + # context + if mode in ["r", "r+"]: + with pytest.raises(IOError, match=msg): + with HDFStore(path, mode=mode) as store: + pass + else: + with HDFStore(path, mode=mode) as store: + assert store._handle.mode == mode + + with ensure_clean_path(setup_path) as path: + + # conv write + if mode in ["r", "r+"]: + with pytest.raises(IOError, match=msg): + df.to_hdf(path, "df", mode=mode) + df.to_hdf(path, "df", mode="w") + else: + df.to_hdf(path, "df", mode=mode) + + # conv read + if mode in ["w"]: + msg = ( + "mode w is not allowed while performing a read. " + r"Allowed modes are r, r\+ and a." + ) + with pytest.raises(ValueError, match=msg): + read_hdf(path, "df", mode=mode) + else: + result = read_hdf(path, "df", mode=mode) + tm.assert_frame_equal(result, df) + + def check_default_mode(): + + # read_hdf uses default mode + with ensure_clean_path(setup_path) as path: + df.to_hdf(path, "df", mode="w") + result = read_hdf(path, "df") + tm.assert_frame_equal(result, df) + + check("r") + check("r+") + check("a") + check("w") + check_default_mode() + + +def test_reopen_handle(setup_path): + + with ensure_clean_path(setup_path) as path: + + store = HDFStore(path, mode="a") + store["a"] = tm.makeTimeSeries() + + msg = ( + r"Re-opening the file \[[\S]*\] with mode \[a\] will delete the " + "current file!" + ) + # invalid mode change + with pytest.raises(PossibleDataLossError, match=msg): + store.open("w") + + store.close() + assert not store.is_open + + # truncation ok here + store.open("w") + assert store.is_open + assert len(store) == 0 + store.close() + assert not store.is_open + + store = HDFStore(path, mode="a") + store["a"] = tm.makeTimeSeries() + + # reopen as read + store.open("r") + assert store.is_open + assert len(store) == 1 + assert store._mode == "r" + store.close() + assert not store.is_open + + # reopen as append + store.open("a") + assert store.is_open + assert len(store) == 1 + assert store._mode == "a" + store.close() + assert not store.is_open + + # reopen as append (again) + store.open("a") + assert store.is_open + assert len(store) == 1 + assert store._mode == "a" + store.close() + assert not store.is_open + + +def test_open_args(setup_path): + + with tm.ensure_clean(setup_path) as path: + + df = tm.makeDataFrame() + + # create an in memory store + store = HDFStore( + path, mode="a", driver="H5FD_CORE", driver_core_backing_store=0 + ) + store["df"] = df + store.append("df2", df) + + tm.assert_frame_equal(store["df"], df) + tm.assert_frame_equal(store["df2"], df) + + store.close() + + # the file should not have actually been written + assert not os.path.exists(path) + + +def test_flush(setup_path): + + with ensure_clean_store(setup_path) as store: + store["a"] = tm.makeTimeSeries() + store.flush() + store.flush(fsync=True) + + +def test_complibs_default_settings(setup_path): + # GH15943 + df = tm.makeDataFrame() + + # Set complevel and check if complib is automatically set to + # default value + with ensure_clean_path(setup_path) as tmpfile: + df.to_hdf(tmpfile, "df", complevel=9) + result = pd.read_hdf(tmpfile, "df") + tm.assert_frame_equal(result, df) + + with tables.open_file(tmpfile, mode="r") as h5file: + for node in h5file.walk_nodes(where="/df", classname="Leaf"): + assert node.filters.complevel == 9 + assert node.filters.complib == "zlib" + + # Set complib and check to see if compression is disabled + with ensure_clean_path(setup_path) as tmpfile: + df.to_hdf(tmpfile, "df", complib="zlib") + result = pd.read_hdf(tmpfile, "df") + tm.assert_frame_equal(result, df) + + with tables.open_file(tmpfile, mode="r") as h5file: + for node in h5file.walk_nodes(where="/df", classname="Leaf"): + assert node.filters.complevel == 0 + assert node.filters.complib is None + + # Check if not setting complib or complevel results in no compression + with ensure_clean_path(setup_path) as tmpfile: + df.to_hdf(tmpfile, "df") + result = pd.read_hdf(tmpfile, "df") + tm.assert_frame_equal(result, df) + + with tables.open_file(tmpfile, mode="r") as h5file: + for node in h5file.walk_nodes(where="/df", classname="Leaf"): + assert node.filters.complevel == 0 + assert node.filters.complib is None + + # Check if file-defaults can be overridden on a per table basis + with ensure_clean_path(setup_path) as tmpfile: + store = HDFStore(tmpfile) + store.append("dfc", df, complevel=9, complib="blosc") + store.append("df", df) + store.close() + + with tables.open_file(tmpfile, mode="r") as h5file: + for node in h5file.walk_nodes(where="/df", classname="Leaf"): + assert node.filters.complevel == 0 + assert node.filters.complib is None + for node in h5file.walk_nodes(where="/dfc", classname="Leaf"): + assert node.filters.complevel == 9 + assert node.filters.complib == "blosc" + + +def test_complibs(setup_path): + # GH14478 + df = tm.makeDataFrame() + + # Building list of all complibs and complevels tuples + all_complibs = tables.filters.all_complibs + # Remove lzo if its not available on this platform + if not tables.which_lib_version("lzo"): + all_complibs.remove("lzo") + # Remove bzip2 if its not available on this platform + if not tables.which_lib_version("bzip2"): + all_complibs.remove("bzip2") + + all_levels = range(0, 10) + all_tests = [(lib, lvl) for lib in all_complibs for lvl in all_levels] + + for (lib, lvl) in all_tests: + with ensure_clean_path(setup_path) as tmpfile: + gname = "foo" + + # Write and read file to see if data is consistent + df.to_hdf(tmpfile, gname, complib=lib, complevel=lvl) + result = pd.read_hdf(tmpfile, gname) + tm.assert_frame_equal(result, df) + + # Open file and check metadata + # for correct amount of compression + h5table = tables.open_file(tmpfile, mode="r") + for node in h5table.walk_nodes(where="/" + gname, classname="Leaf"): + assert node.filters.complevel == lvl + if lvl == 0: + assert node.filters.complib is None + else: + assert node.filters.complib == lib + h5table.close() + + +@pytest.mark.skipif( + not is_platform_little_endian(), reason="reason platform is not little endian" +) +def test_encoding(setup_path): + + with ensure_clean_store(setup_path) as store: + df = DataFrame({"A": "foo", "B": "bar"}, index=range(5)) + df.loc[2, "A"] = np.nan + df.loc[3, "B"] = np.nan + _maybe_remove(store, "df") + store.append("df", df, encoding="ascii") + tm.assert_frame_equal(store["df"], df) + + expected = df.reindex(columns=["A"]) + result = store.select("df", Term("columns=A", encoding="ascii")) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "val", + [ + [b"E\xc9, 17", b"", b"a", b"b", b"c"], + [b"E\xc9, 17", b"a", b"b", b"c"], + [b"EE, 17", b"", b"a", b"b", b"c"], + [b"E\xc9, 17", b"\xf8\xfc", b"a", b"b", b"c"], + [b"", b"a", b"b", b"c"], + [b"\xf8\xfc", b"a", b"b", b"c"], + [b"A\xf8\xfc", b"", b"a", b"b", b"c"], + [np.nan, b"", b"b", b"c"], + [b"A\xf8\xfc", np.nan, b"", b"b", b"c"], + ], +) +@pytest.mark.parametrize("dtype", ["category", object]) +def test_latin_encoding(setup_path, dtype, val): + enc = "latin-1" + nan_rep = "" + key = "data" + + val = [x.decode(enc) if isinstance(x, bytes) else x for x in val] + ser = Series(val, dtype=dtype) + + with ensure_clean_path(setup_path) as store: + ser.to_hdf(store, key, format="table", encoding=enc, nan_rep=nan_rep) + retr = read_hdf(store, key) + + s_nan = ser.replace(nan_rep, np.nan) + + tm.assert_series_equal(s_nan, retr) + + +def test_multiple_open_close(setup_path): + # gh-4409: open & close multiple times + + with ensure_clean_path(setup_path) as path: + + df = tm.makeDataFrame() + df.to_hdf(path, "df", mode="w", format="table") + + # single + store = HDFStore(path) + assert "CLOSED" not in store.info() + assert store.is_open + + store.close() + assert "CLOSED" in store.info() + assert not store.is_open + + with ensure_clean_path(setup_path) as path: + + if pytables._table_file_open_policy_is_strict: + # multiples + store1 = HDFStore(path) + msg = ( + r"The file [\S]* is already opened\. Please close it before " + r"reopening in write mode\." + ) + with pytest.raises(ValueError, match=msg): + HDFStore(path) + + store1.close() + else: + + # multiples + store1 = HDFStore(path) + store2 = HDFStore(path) + + assert "CLOSED" not in store1.info() + assert "CLOSED" not in store2.info() + assert store1.is_open + assert store2.is_open + + store1.close() + assert "CLOSED" in store1.info() + assert not store1.is_open + assert "CLOSED" not in store2.info() + assert store2.is_open + + store2.close() + assert "CLOSED" in store1.info() + assert "CLOSED" in store2.info() + assert not store1.is_open + assert not store2.is_open + + # nested close + store = HDFStore(path, mode="w") + store.append("df", df) + + store2 = HDFStore(path) + store2.append("df2", df) + store2.close() + assert "CLOSED" in store2.info() + assert not store2.is_open + + store.close() + assert "CLOSED" in store.info() + assert not store.is_open + + # double closing + store = HDFStore(path, mode="w") + store.append("df", df) + + store2 = HDFStore(path) + store.close() + assert "CLOSED" in store.info() + assert not store.is_open + + store2.close() + assert "CLOSED" in store2.info() + assert not store2.is_open + + # ops on a closed store + with ensure_clean_path(setup_path) as path: + + df = tm.makeDataFrame() + df.to_hdf(path, "df", mode="w", format="table") + + store = HDFStore(path) + store.close() + + msg = r"[\S]* file is not open!" + with pytest.raises(ClosedFileError, match=msg): + store.keys() + + with pytest.raises(ClosedFileError, match=msg): + "df" in store + + with pytest.raises(ClosedFileError, match=msg): + len(store) + + with pytest.raises(ClosedFileError, match=msg): + store["df"] + + with pytest.raises(ClosedFileError, match=msg): + store.select("df") + + with pytest.raises(ClosedFileError, match=msg): + store.get("df") + + with pytest.raises(ClosedFileError, match=msg): + store.append("df2", df) + + with pytest.raises(ClosedFileError, match=msg): + store.put("df3", df) + + with pytest.raises(ClosedFileError, match=msg): + store.get_storer("df2") + + with pytest.raises(ClosedFileError, match=msg): + store.remove("df2") + + with pytest.raises(ClosedFileError, match=msg): + store.select("df") + + msg = "'HDFStore' object has no attribute 'df'" + with pytest.raises(AttributeError, match=msg): + store.df + + +def test_fspath(): + with tm.ensure_clean("foo.h5") as path: + with HDFStore(path) as store: + assert os.fspath(store) == str(path) diff --git a/pandas/tests/io/pytables/test_keys.py b/pandas/tests/io/pytables/test_keys.py new file mode 100644 index 0000000000000..4f939adeb4138 --- /dev/null +++ b/pandas/tests/io/pytables/test_keys.py @@ -0,0 +1,76 @@ +import pytest + +from pandas import DataFrame, HDFStore, _testing as tm +from pandas.tests.io.pytables.common import ( + ensure_clean_path, + ensure_clean_store, + tables, +) + +pytestmark = pytest.mark.single + + +def test_keys(setup_path): + + with ensure_clean_store(setup_path) as store: + store["a"] = tm.makeTimeSeries() + store["b"] = tm.makeStringSeries() + store["c"] = tm.makeDataFrame() + + assert len(store) == 3 + expected = {"/a", "/b", "/c"} + assert set(store.keys()) == expected + assert set(store) == expected + + +def test_non_pandas_keys(setup_path): + class Table1(tables.IsDescription): + value1 = tables.Float32Col() + + class Table2(tables.IsDescription): + value2 = tables.Float32Col() + + class Table3(tables.IsDescription): + value3 = tables.Float32Col() + + with ensure_clean_path(setup_path) as path: + with tables.open_file(path, mode="w") as h5file: + group = h5file.create_group("/", "group") + h5file.create_table(group, "table1", Table1, "Table 1") + h5file.create_table(group, "table2", Table2, "Table 2") + h5file.create_table(group, "table3", Table3, "Table 3") + with HDFStore(path) as store: + assert len(store.keys(include="native")) == 3 + expected = {"/group/table1", "/group/table2", "/group/table3"} + assert set(store.keys(include="native")) == expected + assert set(store.keys(include="pandas")) == set() + for name in expected: + df = store.get(name) + assert len(df.columns) == 1 + + +def test_keys_illegal_include_keyword_value(setup_path): + with ensure_clean_store(setup_path) as store: + with pytest.raises( + ValueError, + match="`include` should be either 'pandas' or 'native' but is 'illegal'", + ): + store.keys(include="illegal") + + +def test_keys_ignore_hdf_softlink(setup_path): + + # GH 20523 + # Puts a softlink into HDF file and rereads + + with ensure_clean_store(setup_path) as store: + + df = DataFrame({"A": range(5), "B": range(5)}) + store.put("df", df) + + assert store.keys() == ["/df"] + + store._handle.create_soft_link(store._handle.root, "symlink", "df") + + # Should ignore the softlink + assert store.keys() == ["/df"] diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py new file mode 100644 index 0000000000000..5f6a39d46df97 --- /dev/null +++ b/pandas/tests/io/pytables/test_put.py @@ -0,0 +1,375 @@ +import datetime +import re +from warnings import catch_warnings, simplefilter + +import numpy as np +import pytest + +from pandas._libs.tslibs import Timestamp + +import pandas as pd +from pandas import ( + DataFrame, + HDFStore, + Index, + Int64Index, + MultiIndex, + RangeIndex, + Series, + _testing as tm, + concat, +) +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_path, + ensure_clean_store, +) +from pandas.util import _test_decorators as td + +pytestmark = pytest.mark.single + + +def test_format_type(setup_path): + df = DataFrame({"A": [1, 2]}) + with ensure_clean_path(setup_path) as path: + with HDFStore(path) as store: + store.put("a", df, format="fixed") + store.put("b", df, format="table") + + assert store.get_storer("a").format_type == "fixed" + assert store.get_storer("b").format_type == "table" + + +def test_format_kwarg_in_constructor(setup_path): + # GH 13291 + + msg = "format is not a defined argument for HDFStore" + + with tm.ensure_clean(setup_path) as path: + with pytest.raises(ValueError, match=msg): + HDFStore(path, format="table") + + +def test_api_default_format(setup_path): + + # default_format option + with ensure_clean_store(setup_path) as store: + df = tm.makeDataFrame() + + pd.set_option("io.hdf.default_format", "fixed") + _maybe_remove(store, "df") + store.put("df", df) + assert not store.get_storer("df").is_table + + msg = "Can only append to Tables" + + with pytest.raises(ValueError, match=msg): + store.append("df2", df) + + pd.set_option("io.hdf.default_format", "table") + _maybe_remove(store, "df") + store.put("df", df) + assert store.get_storer("df").is_table + _maybe_remove(store, "df2") + store.append("df2", df) + assert store.get_storer("df").is_table + + pd.set_option("io.hdf.default_format", None) + + with ensure_clean_path(setup_path) as path: + + df = tm.makeDataFrame() + + pd.set_option("io.hdf.default_format", "fixed") + df.to_hdf(path, "df") + with HDFStore(path) as store: + assert not store.get_storer("df").is_table + with pytest.raises(ValueError, match=msg): + df.to_hdf(path, "df2", append=True) + + pd.set_option("io.hdf.default_format", "table") + df.to_hdf(path, "df3") + with HDFStore(path) as store: + assert store.get_storer("df3").is_table + df.to_hdf(path, "df4", append=True) + with HDFStore(path) as store: + assert store.get_storer("df4").is_table + + pd.set_option("io.hdf.default_format", None) + + +def test_put(setup_path): + + with ensure_clean_store(setup_path) as store: + + ts = tm.makeTimeSeries() + df = tm.makeTimeDataFrame() + store["a"] = ts + store["b"] = df[:10] + store["foo/bar/bah"] = df[:10] + store["foo"] = df[:10] + store["/foo"] = df[:10] + store.put("c", df[:10], format="table") + + # not OK, not a table + msg = "Can only append to Tables" + with pytest.raises(ValueError, match=msg): + store.put("b", df[10:], append=True) + + # node does not currently exist, test _is_table_type returns False + # in this case + _maybe_remove(store, "f") + with pytest.raises(ValueError, match=msg): + store.put("f", df[10:], append=True) + + # can't put to a table (use append instead) + with pytest.raises(ValueError, match=msg): + store.put("c", df[10:], append=True) + + # overwrite table + store.put("c", df[:10], format="table", append=False) + tm.assert_frame_equal(df[:10], store["c"]) + + +def test_put_string_index(setup_path): + + with ensure_clean_store(setup_path) as store: + + index = Index([f"I am a very long string index: {i}" for i in range(20)]) + s = Series(np.arange(20), index=index) + df = DataFrame({"A": s, "B": s}) + + store["a"] = s + tm.assert_series_equal(store["a"], s) + + store["b"] = df + tm.assert_frame_equal(store["b"], df) + + # mixed length + index = Index( + ["abcdefghijklmnopqrstuvwxyz1234567890"] + + [f"I am a very long string index: {i}" for i in range(20)] + ) + s = Series(np.arange(21), index=index) + df = DataFrame({"A": s, "B": s}) + store["a"] = s + tm.assert_series_equal(store["a"], s) + + store["b"] = df + tm.assert_frame_equal(store["b"], df) + + +def test_put_compression(setup_path): + + with ensure_clean_store(setup_path) as store: + df = tm.makeTimeDataFrame() + + store.put("c", df, format="table", complib="zlib") + tm.assert_frame_equal(store["c"], df) + + # can't compress if format='fixed' + msg = "Compression not supported on Fixed format stores" + with pytest.raises(ValueError, match=msg): + store.put("b", df, format="fixed", complib="zlib") + + +@td.skip_if_windows_python_3 +def test_put_compression_blosc(setup_path): + df = tm.makeTimeDataFrame() + + with ensure_clean_store(setup_path) as store: + + # can't compress if format='fixed' + msg = "Compression not supported on Fixed format stores" + with pytest.raises(ValueError, match=msg): + store.put("b", df, format="fixed", complib="blosc") + + store.put("c", df, format="table", complib="blosc") + tm.assert_frame_equal(store["c"], df) + + +def test_put_mixed_type(setup_path): + df = tm.makeTimeDataFrame() + df["obj1"] = "foo" + df["obj2"] = "bar" + df["bool1"] = df["A"] > 0 + df["bool2"] = df["B"] > 0 + df["bool3"] = True + df["int1"] = 1 + df["int2"] = 2 + df["timestamp1"] = Timestamp("20010102") + df["timestamp2"] = Timestamp("20010103") + df["datetime1"] = datetime.datetime(2001, 1, 2, 0, 0) + df["datetime2"] = datetime.datetime(2001, 1, 3, 0, 0) + df.loc[df.index[3:6], ["obj1"]] = np.nan + df = df._consolidate()._convert(datetime=True) + + with ensure_clean_store(setup_path) as store: + _maybe_remove(store, "df") + + # PerformanceWarning + with catch_warnings(record=True): + simplefilter("ignore", pd.errors.PerformanceWarning) + store.put("df", df) + + expected = store.get("df") + tm.assert_frame_equal(expected, df) + + +def test_store_index_types(setup_path): + # GH5386 + # test storing various index types + + with ensure_clean_store(setup_path) as store: + + def check(format, index): + df = DataFrame(np.random.randn(10, 2), columns=list("AB")) + df.index = index(len(df)) + + _maybe_remove(store, "df") + store.put("df", df, format=format) + tm.assert_frame_equal(df, store["df"]) + + for index in [ + tm.makeFloatIndex, + tm.makeStringIndex, + tm.makeIntIndex, + tm.makeDateIndex, + ]: + + check("table", index) + check("fixed", index) + + # period index currently broken for table + # seee GH7796 FIXME + check("fixed", tm.makePeriodIndex) + # check('table',tm.makePeriodIndex) + + # unicode + index = tm.makeUnicodeIndex + check("table", index) + check("fixed", index) + + +def test_column_multiindex(setup_path): + # GH 4710 + # recreate multi-indexes properly + + index = MultiIndex.from_tuples( + [("A", "a"), ("A", "b"), ("B", "a"), ("B", "b")], names=["first", "second"] + ) + df = DataFrame(np.arange(12).reshape(3, 4), columns=index) + expected = df.copy() + if isinstance(expected.index, RangeIndex): + expected.index = Int64Index(expected.index) + + with ensure_clean_store(setup_path) as store: + + store.put("df", df) + tm.assert_frame_equal( + store["df"], expected, check_index_type=True, check_column_type=True + ) + + store.put("df1", df, format="table") + tm.assert_frame_equal( + store["df1"], expected, check_index_type=True, check_column_type=True + ) + + msg = re.escape("cannot use a multi-index on axis [1] with data_columns ['A']") + with pytest.raises(ValueError, match=msg): + store.put("df2", df, format="table", data_columns=["A"]) + msg = re.escape("cannot use a multi-index on axis [1] with data_columns True") + with pytest.raises(ValueError, match=msg): + store.put("df3", df, format="table", data_columns=True) + + # appending multi-column on existing table (see GH 6167) + with ensure_clean_store(setup_path) as store: + store.append("df2", df) + store.append("df2", df) + + tm.assert_frame_equal(store["df2"], concat((df, df))) + + # non_index_axes name + df = DataFrame(np.arange(12).reshape(3, 4), columns=Index(list("ABCD"), name="foo")) + expected = df.copy() + if isinstance(expected.index, RangeIndex): + expected.index = Int64Index(expected.index) + + with ensure_clean_store(setup_path) as store: + + store.put("df1", df, format="table") + tm.assert_frame_equal( + store["df1"], expected, check_index_type=True, check_column_type=True + ) + + +def test_store_multiindex(setup_path): + + # validate multi-index names + # GH 5527 + with ensure_clean_store(setup_path) as store: + + def make_index(names=None): + return MultiIndex.from_tuples( + [ + (datetime.datetime(2013, 12, d), s, t) + for d in range(1, 3) + for s in range(2) + for t in range(3) + ], + names=names, + ) + + # no names + _maybe_remove(store, "df") + df = DataFrame(np.zeros((12, 2)), columns=["a", "b"], index=make_index()) + store.append("df", df) + tm.assert_frame_equal(store.select("df"), df) + + # partial names + _maybe_remove(store, "df") + df = DataFrame( + np.zeros((12, 2)), + columns=["a", "b"], + index=make_index(["date", None, None]), + ) + store.append("df", df) + tm.assert_frame_equal(store.select("df"), df) + + # series + _maybe_remove(store, "s") + s = Series(np.zeros(12), index=make_index(["date", None, None])) + store.append("s", s) + xp = Series(np.zeros(12), index=make_index(["date", "level_1", "level_2"])) + tm.assert_series_equal(store.select("s"), xp) + + # dup with column + _maybe_remove(store, "df") + df = DataFrame( + np.zeros((12, 2)), + columns=["a", "b"], + index=make_index(["date", "a", "t"]), + ) + msg = "duplicate names/columns in the multi-index when storing as a table" + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + # dup within level + _maybe_remove(store, "df") + df = DataFrame( + np.zeros((12, 2)), + columns=["a", "b"], + index=make_index(["date", "date", "date"]), + ) + with pytest.raises(ValueError, match=msg): + store.append("df", df) + + # fully names + _maybe_remove(store, "df") + df = DataFrame( + np.zeros((12, 2)), + columns=["a", "b"], + index=make_index(["date", "s", "t"]), + ) + store.append("df", df) + tm.assert_frame_equal(store.select("df"), df) diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py new file mode 100644 index 0000000000000..5ca8960ae5604 --- /dev/null +++ b/pandas/tests/io/pytables/test_read.py @@ -0,0 +1,338 @@ +from pathlib import Path +import re + +import numpy as np +import pytest + +from pandas._libs.tslibs import Timestamp +from pandas.compat import is_platform_windows + +import pandas as pd +from pandas import DataFrame, HDFStore, Index, Series, _testing as tm, read_hdf +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_path, + ensure_clean_store, +) +from pandas.util import _test_decorators as td + +from pandas.io.pytables import TableIterator + +pytestmark = pytest.mark.single + + +def test_read_missing_key_close_store(setup_path): + # GH 25766 + with ensure_clean_path(setup_path) as path: + df = DataFrame({"a": range(2), "b": range(2)}) + df.to_hdf(path, "k1") + + with pytest.raises(KeyError, match="'No object named k2 in the file'"): + pd.read_hdf(path, "k2") + + # smoke test to test that file is properly closed after + # read with KeyError before another write + df.to_hdf(path, "k2") + + +def test_read_missing_key_opened_store(setup_path): + # GH 28699 + with ensure_clean_path(setup_path) as path: + df = DataFrame({"a": range(2), "b": range(2)}) + df.to_hdf(path, "k1") + + with HDFStore(path, "r") as store: + + with pytest.raises(KeyError, match="'No object named k2 in the file'"): + pd.read_hdf(store, "k2") + + # Test that the file is still open after a KeyError and that we can + # still read from it. + pd.read_hdf(store, "k1") + + +def test_read_column(setup_path): + + df = tm.makeTimeDataFrame() + + with ensure_clean_store(setup_path) as store: + _maybe_remove(store, "df") + + # GH 17912 + # HDFStore.select_column should raise a KeyError + # exception if the key is not a valid store + with pytest.raises(KeyError, match="No object named df in the file"): + store.select_column("df", "index") + + store.append("df", df) + # error + with pytest.raises( + KeyError, match=re.escape("'column [foo] not found in the table'") + ): + store.select_column("df", "foo") + + msg = re.escape("select_column() got an unexpected keyword argument 'where'") + with pytest.raises(TypeError, match=msg): + store.select_column("df", "index", where=["index>5"]) + + # valid + result = store.select_column("df", "index") + tm.assert_almost_equal(result.values, Series(df.index).values) + assert isinstance(result, Series) + + # not a data indexable column + msg = re.escape( + "column [values_block_0] can not be extracted individually; " + "it is not data indexable" + ) + with pytest.raises(ValueError, match=msg): + store.select_column("df", "values_block_0") + + # a data column + df2 = df.copy() + df2["string"] = "foo" + store.append("df2", df2, data_columns=["string"]) + result = store.select_column("df2", "string") + tm.assert_almost_equal(result.values, df2["string"].values) + + # a data column with NaNs, result excludes the NaNs + df3 = df.copy() + df3["string"] = "foo" + df3.loc[df3.index[4:6], "string"] = np.nan + store.append("df3", df3, data_columns=["string"]) + result = store.select_column("df3", "string") + tm.assert_almost_equal(result.values, df3["string"].values) + + # start/stop + result = store.select_column("df3", "string", start=2) + tm.assert_almost_equal(result.values, df3["string"].values[2:]) + + result = store.select_column("df3", "string", start=-2) + tm.assert_almost_equal(result.values, df3["string"].values[-2:]) + + result = store.select_column("df3", "string", stop=2) + tm.assert_almost_equal(result.values, df3["string"].values[:2]) + + result = store.select_column("df3", "string", stop=-2) + tm.assert_almost_equal(result.values, df3["string"].values[:-2]) + + result = store.select_column("df3", "string", start=2, stop=-2) + tm.assert_almost_equal(result.values, df3["string"].values[2:-2]) + + result = store.select_column("df3", "string", start=-2, stop=2) + tm.assert_almost_equal(result.values, df3["string"].values[-2:2]) + + # GH 10392 - make sure column name is preserved + df4 = DataFrame({"A": np.random.randn(10), "B": "foo"}) + store.append("df4", df4, data_columns=True) + expected = df4["B"] + result = store.select_column("df4", "B") + tm.assert_series_equal(result, expected) + + +def test_pytables_native_read(datapath, setup_path): + with ensure_clean_store( + datapath("io", "data", "legacy_hdf/pytables_native.h5"), mode="r" + ) as store: + d2 = store["detector/readout"] + assert isinstance(d2, DataFrame) + + +@pytest.mark.skipif(is_platform_windows(), reason="native2 read fails oddly on windows") +def test_pytables_native2_read(datapath, setup_path): + with ensure_clean_store( + datapath("io", "data", "legacy_hdf", "pytables_native2.h5"), mode="r" + ) as store: + str(store) + d1 = store["detector"] + assert isinstance(d1, DataFrame) + + +def test_legacy_table_fixed_format_read_py2(datapath, setup_path): + # GH 24510 + # legacy table with fixed format written in Python 2 + with ensure_clean_store( + datapath("io", "data", "legacy_hdf", "legacy_table_fixed_py2.h5"), mode="r" + ) as store: + result = store.select("df") + expected = DataFrame( + [[1, 2, 3, "D"]], + columns=["A", "B", "C", "D"], + index=Index(["ABC"], name="INDEX_NAME"), + ) + tm.assert_frame_equal(expected, result) + + +def test_legacy_table_fixed_format_read_datetime_py2(datapath, setup_path): + # GH 31750 + # legacy table with fixed format and datetime64 column written in Python 2 + with ensure_clean_store( + datapath("io", "data", "legacy_hdf", "legacy_table_fixed_datetime_py2.h5"), + mode="r", + ) as store: + result = store.select("df") + expected = DataFrame( + [[Timestamp("2020-02-06T18:00")]], + columns=["A"], + index=Index(["date"]), + ) + tm.assert_frame_equal(expected, result) + + +def test_legacy_table_read_py2(datapath, setup_path): + # issue: 24925 + # legacy table written in Python 2 + with ensure_clean_store( + datapath("io", "data", "legacy_hdf", "legacy_table_py2.h5"), mode="r" + ) as store: + result = store.select("table") + + expected = DataFrame({"a": ["a", "b"], "b": [2, 3]}) + tm.assert_frame_equal(expected, result) + + +def test_read_hdf_open_store(setup_path): + # GH10330 + # No check for non-string path_or-buf, and no test of open store + df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) + df.index.name = "letters" + df = df.set_index(keys="E", append=True) + + with ensure_clean_path(setup_path) as path: + df.to_hdf(path, "df", mode="w") + direct = read_hdf(path, "df") + store = HDFStore(path, mode="r") + indirect = read_hdf(store, "df") + tm.assert_frame_equal(direct, indirect) + assert store.is_open + store.close() + + +def test_read_hdf_iterator(setup_path): + df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) + df.index.name = "letters" + df = df.set_index(keys="E", append=True) + + with ensure_clean_path(setup_path) as path: + df.to_hdf(path, "df", mode="w", format="t") + direct = read_hdf(path, "df") + iterator = read_hdf(path, "df", iterator=True) + assert isinstance(iterator, TableIterator) + indirect = next(iterator.__iter__()) + tm.assert_frame_equal(direct, indirect) + iterator.store.close() + + +def test_read_nokey(setup_path): + # GH10443 + df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) + + # Categorical dtype not supported for "fixed" format. So no need + # to test with that dtype in the dataframe here. + with ensure_clean_path(setup_path) as path: + df.to_hdf(path, "df", mode="a") + reread = read_hdf(path) + tm.assert_frame_equal(df, reread) + df.to_hdf(path, "df2", mode="a") + + msg = "key must be provided when HDF5 file contains multiple datasets." + with pytest.raises(ValueError, match=msg): + read_hdf(path) + + +def test_read_nokey_table(setup_path): + # GH13231 + df = DataFrame({"i": range(5), "c": Series(list("abacd"), dtype="category")}) + + with ensure_clean_path(setup_path) as path: + df.to_hdf(path, "df", mode="a", format="table") + reread = read_hdf(path) + tm.assert_frame_equal(df, reread) + df.to_hdf(path, "df2", mode="a", format="table") + + msg = "key must be provided when HDF5 file contains multiple datasets." + with pytest.raises(ValueError, match=msg): + read_hdf(path) + + +def test_read_nokey_empty(setup_path): + with ensure_clean_path(setup_path) as path: + store = HDFStore(path) + store.close() + msg = re.escape( + "Dataset(s) incompatible with Pandas data types, not table, or no " + "datasets found in HDF5 file." + ) + with pytest.raises(ValueError, match=msg): + read_hdf(path) + + +def test_read_from_pathlib_path(setup_path): + + # GH11773 + expected = DataFrame( + np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE") + ) + with ensure_clean_path(setup_path) as filename: + path_obj = Path(filename) + + expected.to_hdf(path_obj, "df", mode="a") + actual = read_hdf(path_obj, "df") + + tm.assert_frame_equal(expected, actual) + + +@td.skip_if_no("py.path") +def test_read_from_py_localpath(setup_path): + + # GH11773 + from py.path import local as LocalPath + + expected = DataFrame( + np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE") + ) + with ensure_clean_path(setup_path) as filename: + path_obj = LocalPath(filename) + + expected.to_hdf(path_obj, "df", mode="a") + actual = read_hdf(path_obj, "df") + + tm.assert_frame_equal(expected, actual) + + +@pytest.mark.parametrize("format", ["fixed", "table"]) +def test_read_hdf_series_mode_r(format, setup_path): + # GH 16583 + # Tests that reading a Series saved to an HDF file + # still works if a mode='r' argument is supplied + series = tm.makeFloatSeries() + with ensure_clean_path(setup_path) as path: + series.to_hdf(path, key="data", format=format) + result = pd.read_hdf(path, key="data", mode="r") + tm.assert_series_equal(result, series) + + +def test_read_py2_hdf_file_in_py3(datapath): + # GH 16781 + + # tests reading a PeriodIndex DataFrame written in Python2 in Python3 + + # the file was generated in Python 2.7 like so: + # + # df = DataFrame([1.,2,3], index=pd.PeriodIndex( + # ['2015-01-01', '2015-01-02', '2015-01-05'], freq='B')) + # df.to_hdf('periodindex_0.20.1_x86_64_darwin_2.7.13.h5', 'p') + + expected = DataFrame( + [1.0, 2, 3], + index=pd.PeriodIndex(["2015-01-01", "2015-01-02", "2015-01-05"], freq="B"), + ) + + with ensure_clean_store( + datapath( + "io", "data", "legacy_hdf", "periodindex_0.20.1_x86_64_darwin_2.7.13.h5" + ), + mode="r", + ) as store: + result = store["p"] + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/pytables/test_retain_attributes.py b/pandas/tests/io/pytables/test_retain_attributes.py new file mode 100644 index 0000000000000..d301835632431 --- /dev/null +++ b/pandas/tests/io/pytables/test_retain_attributes.py @@ -0,0 +1,111 @@ +from warnings import catch_warnings + +import pytest + +from pandas._libs.tslibs import Timestamp + +from pandas import DataFrame, Series, _testing as tm, date_range, read_hdf +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_path, + ensure_clean_store, +) + +pytestmark = pytest.mark.single + + +def test_retain_index_attributes(setup_path): + + # GH 3499, losing frequency info on index recreation + df = DataFrame( + {"A": Series(range(3), index=date_range("2000-1-1", periods=3, freq="H"))} + ) + + with ensure_clean_store(setup_path) as store: + _maybe_remove(store, "data") + store.put("data", df, format="table") + + result = store.get("data") + tm.assert_frame_equal(df, result) + + for attr in ["freq", "tz", "name"]: + for idx in ["index", "columns"]: + assert getattr(getattr(df, idx), attr, None) == getattr( + getattr(result, idx), attr, None + ) + + # try to append a table with a different frequency + with catch_warnings(record=True): + df2 = DataFrame( + { + "A": Series( + range(3), index=date_range("2002-1-1", periods=3, freq="D") + ) + } + ) + store.append("data", df2) + + assert store.get_storer("data").info["index"]["freq"] is None + + # this is ok + _maybe_remove(store, "df2") + df2 = DataFrame( + { + "A": Series( + range(3), + index=[ + Timestamp("20010101"), + Timestamp("20010102"), + Timestamp("20020101"), + ], + ) + } + ) + store.append("df2", df2) + df3 = DataFrame( + {"A": Series(range(3), index=date_range("2002-1-1", periods=3, freq="D"))} + ) + store.append("df2", df3) + + +@pytest.mark.filterwarnings( + "ignore:\\nthe :pandas.io.pytables.AttributeConflictWarning" +) +def test_retain_index_attributes2(setup_path): + with ensure_clean_path(setup_path) as path: + + with catch_warnings(record=True): + + df = DataFrame( + { + "A": Series( + range(3), index=date_range("2000-1-1", periods=3, freq="H") + ) + } + ) + df.to_hdf(path, "data", mode="w", append=True) + df2 = DataFrame( + { + "A": Series( + range(3), index=date_range("2002-1-1", periods=3, freq="D") + ) + } + ) + + df2.to_hdf(path, "data", append=True) + + idx = date_range("2000-1-1", periods=3, freq="H") + idx.name = "foo" + df = DataFrame({"A": Series(range(3), index=idx)}) + df.to_hdf(path, "data", mode="w", append=True) + + assert read_hdf(path, "data").index.name == "foo" + + with catch_warnings(record=True): + + idx2 = date_range("2001-1-1", periods=3, freq="H") + idx2.name = "bar" + df2 = DataFrame({"A": Series(range(3), index=idx2)}) + df2.to_hdf(path, "data", append=True) + + assert read_hdf(path, "data").index.name is None diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py new file mode 100644 index 0000000000000..403c3766fe6ed --- /dev/null +++ b/pandas/tests/io/pytables/test_round_trip.py @@ -0,0 +1,563 @@ +import datetime +import re +from warnings import catch_warnings, simplefilter + +import numpy as np +import pytest + +from pandas._libs.tslibs import Timestamp + +import pandas as pd +from pandas import ( + DataFrame, + Index, + MultiIndex, + Series, + _testing as tm, + bdate_range, + read_hdf, +) +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_path, + ensure_clean_store, +) +from pandas.util import _test_decorators as td + +_default_compressor = "blosc" + + +pytestmark = pytest.mark.single + + +def test_conv_read_write(setup_path): + with tm.ensure_clean() as path: + + def roundtrip(key, obj, **kwargs): + obj.to_hdf(path, key, **kwargs) + return read_hdf(path, key) + + o = tm.makeTimeSeries() + tm.assert_series_equal(o, roundtrip("series", o)) + + o = tm.makeStringSeries() + tm.assert_series_equal(o, roundtrip("string_series", o)) + + o = tm.makeDataFrame() + tm.assert_frame_equal(o, roundtrip("frame", o)) + + # table + df = DataFrame({"A": range(5), "B": range(5)}) + df.to_hdf(path, "table", append=True) + result = read_hdf(path, "table", where=["index>2"]) + tm.assert_frame_equal(df[df.index > 2], result) + + +def test_long_strings(setup_path): + + # GH6166 + df = DataFrame( + {"a": tm.rands_array(100, size=10)}, index=tm.rands_array(100, size=10) + ) + + with ensure_clean_store(setup_path) as store: + store.append("df", df, data_columns=["a"]) + + result = store.select("df") + tm.assert_frame_equal(df, result) + + +def test_api(setup_path): + + # GH4584 + # API issue when to_hdf doesn't accept append AND format args + with ensure_clean_path(setup_path) as path: + + df = tm.makeDataFrame() + df.iloc[:10].to_hdf(path, "df", append=True, format="table") + df.iloc[10:].to_hdf(path, "df", append=True, format="table") + tm.assert_frame_equal(read_hdf(path, "df"), df) + + # append to False + df.iloc[:10].to_hdf(path, "df", append=False, format="table") + df.iloc[10:].to_hdf(path, "df", append=True, format="table") + tm.assert_frame_equal(read_hdf(path, "df"), df) + + with ensure_clean_path(setup_path) as path: + + df = tm.makeDataFrame() + df.iloc[:10].to_hdf(path, "df", append=True) + df.iloc[10:].to_hdf(path, "df", append=True, format="table") + tm.assert_frame_equal(read_hdf(path, "df"), df) + + # append to False + df.iloc[:10].to_hdf(path, "df", append=False, format="table") + df.iloc[10:].to_hdf(path, "df", append=True) + tm.assert_frame_equal(read_hdf(path, "df"), df) + + with ensure_clean_path(setup_path) as path: + + df = tm.makeDataFrame() + df.to_hdf(path, "df", append=False, format="fixed") + tm.assert_frame_equal(read_hdf(path, "df"), df) + + df.to_hdf(path, "df", append=False, format="f") + tm.assert_frame_equal(read_hdf(path, "df"), df) + + df.to_hdf(path, "df", append=False) + tm.assert_frame_equal(read_hdf(path, "df"), df) + + df.to_hdf(path, "df") + tm.assert_frame_equal(read_hdf(path, "df"), df) + + with ensure_clean_store(setup_path) as store: + + df = tm.makeDataFrame() + + _maybe_remove(store, "df") + store.append("df", df.iloc[:10], append=True, format="table") + store.append("df", df.iloc[10:], append=True, format="table") + tm.assert_frame_equal(store.select("df"), df) + + # append to False + _maybe_remove(store, "df") + store.append("df", df.iloc[:10], append=False, format="table") + store.append("df", df.iloc[10:], append=True, format="table") + tm.assert_frame_equal(store.select("df"), df) + + # formats + _maybe_remove(store, "df") + store.append("df", df.iloc[:10], append=False, format="table") + store.append("df", df.iloc[10:], append=True, format="table") + tm.assert_frame_equal(store.select("df"), df) + + _maybe_remove(store, "df") + store.append("df", df.iloc[:10], append=False, format="table") + store.append("df", df.iloc[10:], append=True, format=None) + tm.assert_frame_equal(store.select("df"), df) + + with ensure_clean_path(setup_path) as path: + # Invalid. + df = tm.makeDataFrame() + + msg = "Can only append to Tables" + + with pytest.raises(ValueError, match=msg): + df.to_hdf(path, "df", append=True, format="f") + + with pytest.raises(ValueError, match=msg): + df.to_hdf(path, "df", append=True, format="fixed") + + msg = r"invalid HDFStore format specified \[foo\]" + + with pytest.raises(TypeError, match=msg): + df.to_hdf(path, "df", append=True, format="foo") + + with pytest.raises(TypeError, match=msg): + df.to_hdf(path, "df", append=False, format="foo") + + # File path doesn't exist + path = "" + msg = f"File {path} does not exist" + + with pytest.raises(FileNotFoundError, match=msg): + read_hdf(path, "df") + + +def test_get(setup_path): + + with ensure_clean_store(setup_path) as store: + store["a"] = tm.makeTimeSeries() + left = store.get("a") + right = store["a"] + tm.assert_series_equal(left, right) + + left = store.get("/a") + right = store["/a"] + tm.assert_series_equal(left, right) + + with pytest.raises(KeyError, match="'No object named b in the file'"): + store.get("b") + + +def test_put_integer(setup_path): + # non-date, non-string index + df = DataFrame(np.random.randn(50, 100)) + _check_roundtrip(df, tm.assert_frame_equal, setup_path) + + +def test_table_values_dtypes_roundtrip(setup_path): + + with ensure_clean_store(setup_path) as store: + df1 = DataFrame({"a": [1, 2, 3]}, dtype="f8") + store.append("df_f8", df1) + tm.assert_series_equal(df1.dtypes, store["df_f8"].dtypes) + + df2 = DataFrame({"a": [1, 2, 3]}, dtype="i8") + store.append("df_i8", df2) + tm.assert_series_equal(df2.dtypes, store["df_i8"].dtypes) + + # incompatible dtype + msg = re.escape( + "invalid combination of [values_axes] on appending data " + "[name->values_block_0,cname->values_block_0," + "dtype->float64,kind->float,shape->(1, 3)] vs " + "current table [name->values_block_0," + "cname->values_block_0,dtype->int64,kind->integer," + "shape->None]" + ) + with pytest.raises(ValueError, match=msg): + store.append("df_i8", df1) + + # check creation/storage/retrieval of float32 (a bit hacky to + # actually create them thought) + df1 = DataFrame(np.array([[1], [2], [3]], dtype="f4"), columns=["A"]) + store.append("df_f4", df1) + tm.assert_series_equal(df1.dtypes, store["df_f4"].dtypes) + assert df1.dtypes[0] == "float32" + + # check with mixed dtypes + df1 = DataFrame( + { + c: Series(np.random.randint(5), dtype=c) + for c in ["float32", "float64", "int32", "int64", "int16", "int8"] + } + ) + df1["string"] = "foo" + df1["float322"] = 1.0 + df1["float322"] = df1["float322"].astype("float32") + df1["bool"] = df1["float32"] > 0 + df1["time1"] = Timestamp("20130101") + df1["time2"] = Timestamp("20130102") + + store.append("df_mixed_dtypes1", df1) + result = store.select("df_mixed_dtypes1").dtypes.value_counts() + result.index = [str(i) for i in result.index] + expected = Series( + { + "float32": 2, + "float64": 1, + "int32": 1, + "bool": 1, + "int16": 1, + "int8": 1, + "int64": 1, + "object": 1, + "datetime64[ns]": 2, + } + ) + result = result.sort_index() + expected = expected.sort_index() + tm.assert_series_equal(result, expected) + + +def test_series(setup_path): + + s = tm.makeStringSeries() + _check_roundtrip(s, tm.assert_series_equal, path=setup_path) + + ts = tm.makeTimeSeries() + _check_roundtrip(ts, tm.assert_series_equal, path=setup_path) + + ts2 = Series(ts.index, Index(ts.index, dtype=object)) + _check_roundtrip(ts2, tm.assert_series_equal, path=setup_path) + + ts3 = Series(ts.values, Index(np.asarray(ts.index, dtype=object), dtype=object)) + _check_roundtrip( + ts3, tm.assert_series_equal, path=setup_path, check_index_type=False + ) + + +def test_float_index(setup_path): + + # GH #454 + index = np.random.randn(10) + s = Series(np.random.randn(10), index=index) + _check_roundtrip(s, tm.assert_series_equal, path=setup_path) + + +def test_tuple_index(setup_path): + + # GH #492 + col = np.arange(10) + idx = [(0.0, 1.0), (2.0, 3.0), (4.0, 5.0)] + data = np.random.randn(30).reshape((3, 10)) + DF = DataFrame(data, index=idx, columns=col) + + with catch_warnings(record=True): + simplefilter("ignore", pd.errors.PerformanceWarning) + _check_roundtrip(DF, tm.assert_frame_equal, path=setup_path) + + +@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") +def test_index_types(setup_path): + with catch_warnings(record=True): + values = np.random.randn(2) + + func = lambda l, r: tm.assert_series_equal(l, r, check_index_type=True) + + with catch_warnings(record=True): + ser = Series(values, [0, "y"]) + _check_roundtrip(ser, func, path=setup_path) + + with catch_warnings(record=True): + ser = Series(values, [datetime.datetime.today(), 0]) + _check_roundtrip(ser, func, path=setup_path) + + with catch_warnings(record=True): + ser = Series(values, ["y", 0]) + _check_roundtrip(ser, func, path=setup_path) + + with catch_warnings(record=True): + ser = Series(values, [datetime.date.today(), "a"]) + _check_roundtrip(ser, func, path=setup_path) + + with catch_warnings(record=True): + ser = Series(values, [0, "y"]) + _check_roundtrip(ser, func, path=setup_path) + + ser = Series(values, [datetime.datetime.today(), 0]) + _check_roundtrip(ser, func, path=setup_path) + + ser = Series(values, ["y", 0]) + _check_roundtrip(ser, func, path=setup_path) + + ser = Series(values, [datetime.date.today(), "a"]) + _check_roundtrip(ser, func, path=setup_path) + + ser = Series(values, [1.23, "b"]) + _check_roundtrip(ser, func, path=setup_path) + + ser = Series(values, [1, 1.53]) + _check_roundtrip(ser, func, path=setup_path) + + ser = Series(values, [1, 5]) + _check_roundtrip(ser, func, path=setup_path) + + ser = Series( + values, [datetime.datetime(2012, 1, 1), datetime.datetime(2012, 1, 2)] + ) + _check_roundtrip(ser, func, path=setup_path) + + +def test_timeseries_preepoch(setup_path): + + dr = bdate_range("1/1/1940", "1/1/1960") + ts = Series(np.random.randn(len(dr)), index=dr) + try: + _check_roundtrip(ts, tm.assert_series_equal, path=setup_path) + except OverflowError: + pytest.skip("known failer on some windows platforms") + + +@pytest.mark.parametrize( + "compression", [False, pytest.param(True, marks=td.skip_if_windows_python_3)] +) +def test_frame(compression, setup_path): + + df = tm.makeDataFrame() + + # put in some random NAs + df.values[0, 0] = np.nan + df.values[5, 3] = np.nan + + _check_roundtrip_table( + df, tm.assert_frame_equal, path=setup_path, compression=compression + ) + _check_roundtrip( + df, tm.assert_frame_equal, path=setup_path, compression=compression + ) + + tdf = tm.makeTimeDataFrame() + _check_roundtrip( + tdf, tm.assert_frame_equal, path=setup_path, compression=compression + ) + + with ensure_clean_store(setup_path) as store: + # not consolidated + df["foo"] = np.random.randn(len(df)) + store["df"] = df + recons = store["df"] + assert recons._mgr.is_consolidated() + + # empty + _check_roundtrip(df[:0], tm.assert_frame_equal, path=setup_path) + + +def test_empty_series_frame(setup_path): + s0 = Series(dtype=object) + s1 = Series(name="myseries", dtype=object) + df0 = DataFrame() + df1 = DataFrame(index=["a", "b", "c"]) + df2 = DataFrame(columns=["d", "e", "f"]) + + _check_roundtrip(s0, tm.assert_series_equal, path=setup_path) + _check_roundtrip(s1, tm.assert_series_equal, path=setup_path) + _check_roundtrip(df0, tm.assert_frame_equal, path=setup_path) + _check_roundtrip(df1, tm.assert_frame_equal, path=setup_path) + _check_roundtrip(df2, tm.assert_frame_equal, path=setup_path) + + +@pytest.mark.parametrize("dtype", [np.int64, np.float64, object, "m8[ns]", "M8[ns]"]) +def test_empty_series(dtype, setup_path): + s = Series(dtype=dtype) + _check_roundtrip(s, tm.assert_series_equal, path=setup_path) + + +def test_can_serialize_dates(setup_path): + + rng = [x.date() for x in bdate_range("1/1/2000", "1/30/2000")] + frame = DataFrame(np.random.randn(len(rng), 4), index=rng) + + _check_roundtrip(frame, tm.assert_frame_equal, path=setup_path) + + +def test_store_hierarchical(setup_path): + index = MultiIndex( + levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["foo", "bar"], + ) + frame = DataFrame(np.random.randn(10, 3), index=index, columns=["A", "B", "C"]) + + _check_roundtrip(frame, tm.assert_frame_equal, path=setup_path) + _check_roundtrip(frame.T, tm.assert_frame_equal, path=setup_path) + _check_roundtrip(frame["A"], tm.assert_series_equal, path=setup_path) + + # check that the names are stored + with ensure_clean_store(setup_path) as store: + store["frame"] = frame + recons = store["frame"] + tm.assert_frame_equal(recons, frame) + + +@pytest.mark.parametrize( + "compression", [False, pytest.param(True, marks=td.skip_if_windows_python_3)] +) +def test_store_mixed(compression, setup_path): + def _make_one(): + df = tm.makeDataFrame() + df["obj1"] = "foo" + df["obj2"] = "bar" + df["bool1"] = df["A"] > 0 + df["bool2"] = df["B"] > 0 + df["int1"] = 1 + df["int2"] = 2 + return df._consolidate() + + df1 = _make_one() + df2 = _make_one() + + _check_roundtrip(df1, tm.assert_frame_equal, path=setup_path) + _check_roundtrip(df2, tm.assert_frame_equal, path=setup_path) + + with ensure_clean_store(setup_path) as store: + store["obj"] = df1 + tm.assert_frame_equal(store["obj"], df1) + store["obj"] = df2 + tm.assert_frame_equal(store["obj"], df2) + + # check that can store Series of all of these types + _check_roundtrip( + df1["obj1"], + tm.assert_series_equal, + path=setup_path, + compression=compression, + ) + _check_roundtrip( + df1["bool1"], + tm.assert_series_equal, + path=setup_path, + compression=compression, + ) + _check_roundtrip( + df1["int1"], + tm.assert_series_equal, + path=setup_path, + compression=compression, + ) + + +def _check_roundtrip(obj, comparator, path, compression=False, **kwargs): + + options = {} + if compression: + options["complib"] = _default_compressor + + with ensure_clean_store(path, "w", **options) as store: + store["obj"] = obj + retrieved = store["obj"] + comparator(retrieved, obj, **kwargs) + + +def _check_double_roundtrip(self, obj, comparator, path, compression=False, **kwargs): + options = {} + if compression: + options["complib"] = compression or _default_compressor + + with ensure_clean_store(path, "w", **options) as store: + store["obj"] = obj + retrieved = store["obj"] + comparator(retrieved, obj, **kwargs) + store["obj"] = retrieved + again = store["obj"] + comparator(again, obj, **kwargs) + + +def _check_roundtrip_table(obj, comparator, path, compression=False): + options = {} + if compression: + options["complib"] = _default_compressor + + with ensure_clean_store(path, "w", **options) as store: + store.put("obj", obj, format="table") + retrieved = store["obj"] + + comparator(retrieved, obj) + + +def test_unicode_index(setup_path): + + unicode_values = ["\u03c3", "\u03c3\u03c3"] + + # PerformanceWarning + with catch_warnings(record=True): + simplefilter("ignore", pd.errors.PerformanceWarning) + s = Series(np.random.randn(len(unicode_values)), unicode_values) + _check_roundtrip(s, tm.assert_series_equal, path=setup_path) + + +def test_unicode_longer_encoded(setup_path): + # GH 11234 + char = "\u0394" + df = DataFrame({"A": [char]}) + with ensure_clean_store(setup_path) as store: + store.put("df", df, format="table", encoding="utf-8") + result = store.get("df") + tm.assert_frame_equal(result, df) + + df = DataFrame({"A": ["a", char], "B": ["b", "b"]}) + with ensure_clean_store(setup_path) as store: + store.put("df", df, format="table", encoding="utf-8") + result = store.get("df") + tm.assert_frame_equal(result, df) + + +def test_store_datetime_mixed(setup_path): + + df = DataFrame({"a": [1, 2, 3], "b": [1.0, 2.0, 3.0], "c": ["a", "b", "c"]}) + ts = tm.makeTimeSeries() + df["d"] = ts.index[:3] + _check_roundtrip(df, tm.assert_frame_equal, path=setup_path) + + +def test_round_trip_equals(setup_path): + # GH 9330 + df = DataFrame({"B": [1, 2], "A": ["x", "y"]}) + + with ensure_clean_path(setup_path) as path: + df.to_hdf(path, "df", format="table") + other = read_hdf(path, "df") + tm.assert_frame_equal(df, other) + assert df.equals(other) + assert other.equals(df) diff --git a/pandas/tests/io/pytables/test_select.py b/pandas/tests/io/pytables/test_select.py new file mode 100644 index 0000000000000..87d0728e2418e --- /dev/null +++ b/pandas/tests/io/pytables/test_select.py @@ -0,0 +1,981 @@ +from distutils.version import LooseVersion +from warnings import catch_warnings + +import numpy as np +import pytest + +from pandas._libs.tslibs import Timestamp + +import pandas as pd +from pandas import ( + DataFrame, + HDFStore, + Index, + MultiIndex, + Series, + _testing as tm, + bdate_range, + concat, + date_range, + isna, + read_hdf, +) +from pandas.tests.io.pytables.common import ( + _maybe_remove, + ensure_clean_path, + ensure_clean_store, + tables, +) + +from pandas.io.pytables import Term + +pytestmark = pytest.mark.single + + +def test_select_columns_in_where(setup_path): + + # GH 6169 + # recreate multi-indexes when columns is passed + # in the `where` argument + index = MultiIndex( + levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["foo_name", "bar_name"], + ) + + # With a DataFrame + df = DataFrame(np.random.randn(10, 3), index=index, columns=["A", "B", "C"]) + + with ensure_clean_store(setup_path) as store: + store.put("df", df, format="table") + expected = df[["A"]] + + tm.assert_frame_equal(store.select("df", columns=["A"]), expected) + + tm.assert_frame_equal(store.select("df", where="columns=['A']"), expected) + + # With a Series + s = Series(np.random.randn(10), index=index, name="A") + with ensure_clean_store(setup_path) as store: + store.put("s", s, format="table") + tm.assert_series_equal(store.select("s", where="columns=['A']"), s) + + +def test_select_with_dups(setup_path): + + # single dtypes + df = DataFrame(np.random.randn(10, 4), columns=["A", "A", "B", "B"]) + df.index = date_range("20130101 9:30", periods=10, freq="T") + + with ensure_clean_store(setup_path) as store: + store.append("df", df) + + result = store.select("df") + expected = df + tm.assert_frame_equal(result, expected, by_blocks=True) + + result = store.select("df", columns=df.columns) + expected = df + tm.assert_frame_equal(result, expected, by_blocks=True) + + result = store.select("df", columns=["A"]) + expected = df.loc[:, ["A"]] + tm.assert_frame_equal(result, expected) + + # dups across dtypes + df = concat( + [ + DataFrame(np.random.randn(10, 4), columns=["A", "A", "B", "B"]), + DataFrame( + np.random.randint(0, 10, size=20).reshape(10, 2), columns=["A", "C"] + ), + ], + axis=1, + ) + df.index = date_range("20130101 9:30", periods=10, freq="T") + + with ensure_clean_store(setup_path) as store: + store.append("df", df) + + result = store.select("df") + expected = df + tm.assert_frame_equal(result, expected, by_blocks=True) + + result = store.select("df", columns=df.columns) + expected = df + tm.assert_frame_equal(result, expected, by_blocks=True) + + expected = df.loc[:, ["A"]] + result = store.select("df", columns=["A"]) + tm.assert_frame_equal(result, expected, by_blocks=True) + + expected = df.loc[:, ["B", "A"]] + result = store.select("df", columns=["B", "A"]) + tm.assert_frame_equal(result, expected, by_blocks=True) + + # duplicates on both index and columns + with ensure_clean_store(setup_path) as store: + store.append("df", df) + store.append("df", df) + + expected = df.loc[:, ["B", "A"]] + expected = concat([expected, expected]) + result = store.select("df", columns=["B", "A"]) + tm.assert_frame_equal(result, expected, by_blocks=True) + + +def test_select(setup_path): + + with ensure_clean_store(setup_path) as store: + + with catch_warnings(record=True): + + # select with columns= + df = tm.makeTimeDataFrame() + _maybe_remove(store, "df") + store.append("df", df) + result = store.select("df", columns=["A", "B"]) + expected = df.reindex(columns=["A", "B"]) + tm.assert_frame_equal(expected, result) + + # equivalently + result = store.select("df", [("columns=['A', 'B']")]) + expected = df.reindex(columns=["A", "B"]) + tm.assert_frame_equal(expected, result) + + # with a data column + _maybe_remove(store, "df") + store.append("df", df, data_columns=["A"]) + result = store.select("df", ["A > 0"], columns=["A", "B"]) + expected = df[df.A > 0].reindex(columns=["A", "B"]) + tm.assert_frame_equal(expected, result) + + # all a data columns + _maybe_remove(store, "df") + store.append("df", df, data_columns=True) + result = store.select("df", ["A > 0"], columns=["A", "B"]) + expected = df[df.A > 0].reindex(columns=["A", "B"]) + tm.assert_frame_equal(expected, result) + + # with a data column, but different columns + _maybe_remove(store, "df") + store.append("df", df, data_columns=["A"]) + result = store.select("df", ["A > 0"], columns=["C", "D"]) + expected = df[df.A > 0].reindex(columns=["C", "D"]) + tm.assert_frame_equal(expected, result) + + +def test_select_dtypes(setup_path): + + with ensure_clean_store(setup_path) as store: + # with a Timestamp data column (GH #2637) + df = DataFrame( + { + "ts": bdate_range("2012-01-01", periods=300), + "A": np.random.randn(300), + } + ) + _maybe_remove(store, "df") + store.append("df", df, data_columns=["ts", "A"]) + + result = store.select("df", "ts>=Timestamp('2012-02-01')") + expected = df[df.ts >= Timestamp("2012-02-01")] + tm.assert_frame_equal(expected, result) + + # bool columns (GH #2849) + df = DataFrame(np.random.randn(5, 2), columns=["A", "B"]) + df["object"] = "foo" + df.loc[4:5, "object"] = "bar" + df["boolv"] = df["A"] > 0 + _maybe_remove(store, "df") + store.append("df", df, data_columns=True) + + expected = df[df.boolv == True].reindex(columns=["A", "boolv"]) # noqa + for v in [True, "true", 1]: + result = store.select("df", f"boolv == {v}", columns=["A", "boolv"]) + tm.assert_frame_equal(expected, result) + + expected = df[df.boolv == False].reindex(columns=["A", "boolv"]) # noqa + for v in [False, "false", 0]: + result = store.select("df", f"boolv == {v}", columns=["A", "boolv"]) + tm.assert_frame_equal(expected, result) + + # integer index + df = DataFrame({"A": np.random.rand(20), "B": np.random.rand(20)}) + _maybe_remove(store, "df_int") + store.append("df_int", df) + result = store.select("df_int", "index<10 and columns=['A']") + expected = df.reindex(index=list(df.index)[0:10], columns=["A"]) + tm.assert_frame_equal(expected, result) + + # float index + df = DataFrame( + { + "A": np.random.rand(20), + "B": np.random.rand(20), + "index": np.arange(20, dtype="f8"), + } + ) + _maybe_remove(store, "df_float") + store.append("df_float", df) + result = store.select("df_float", "index<10.0 and columns=['A']") + expected = df.reindex(index=list(df.index)[0:10], columns=["A"]) + tm.assert_frame_equal(expected, result) + + with ensure_clean_store(setup_path) as store: + + # floats w/o NaN + df = DataFrame({"cols": range(11), "values": range(11)}, dtype="float64") + df["cols"] = (df["cols"] + 10).apply(str) + + store.append("df1", df, data_columns=True) + result = store.select("df1", where="values>2.0") + expected = df[df["values"] > 2.0] + tm.assert_frame_equal(expected, result) + + # floats with NaN + df.iloc[0] = np.nan + expected = df[df["values"] > 2.0] + + store.append("df2", df, data_columns=True, index=False) + result = store.select("df2", where="values>2.0") + tm.assert_frame_equal(expected, result) + + # https://github.com/PyTables/PyTables/issues/282 + # bug in selection when 0th row has a np.nan and an index + # store.append('df3',df,data_columns=True) + # result = store.select( + # 'df3', where='values>2.0') + # tm.assert_frame_equal(expected, result) + + # not in first position float with NaN ok too + df = DataFrame({"cols": range(11), "values": range(11)}, dtype="float64") + df["cols"] = (df["cols"] + 10).apply(str) + + df.iloc[1] = np.nan + expected = df[df["values"] > 2.0] + + store.append("df4", df, data_columns=True) + result = store.select("df4", where="values>2.0") + tm.assert_frame_equal(expected, result) + + # test selection with comparison against numpy scalar + # GH 11283 + with ensure_clean_store(setup_path) as store: + df = tm.makeDataFrame() + + expected = df[df["A"] > 0] + + store.append("df", df, data_columns=True) + np_zero = np.float64(0) # noqa + result = store.select("df", where=["A>np_zero"]) + tm.assert_frame_equal(expected, result) + + +def test_select_with_many_inputs(setup_path): + + with ensure_clean_store(setup_path) as store: + + df = DataFrame( + { + "ts": bdate_range("2012-01-01", periods=300), + "A": np.random.randn(300), + "B": range(300), + "users": ["a"] * 50 + + ["b"] * 50 + + ["c"] * 100 + + [f"a{i:03d}" for i in range(100)], + } + ) + _maybe_remove(store, "df") + store.append("df", df, data_columns=["ts", "A", "B", "users"]) + + # regular select + result = store.select("df", "ts>=Timestamp('2012-02-01')") + expected = df[df.ts >= Timestamp("2012-02-01")] + tm.assert_frame_equal(expected, result) + + # small selector + result = store.select("df", "ts>=Timestamp('2012-02-01') & users=['a','b','c']") + expected = df[ + (df.ts >= Timestamp("2012-02-01")) & df.users.isin(["a", "b", "c"]) + ] + tm.assert_frame_equal(expected, result) + + # big selector along the columns + selector = ["a", "b", "c"] + [f"a{i:03d}" for i in range(60)] + result = store.select("df", "ts>=Timestamp('2012-02-01') and users=selector") + expected = df[(df.ts >= Timestamp("2012-02-01")) & df.users.isin(selector)] + tm.assert_frame_equal(expected, result) + + selector = range(100, 200) + result = store.select("df", "B=selector") + expected = df[df.B.isin(selector)] + tm.assert_frame_equal(expected, result) + assert len(result) == 100 + + # big selector along the index + selector = Index(df.ts[0:100].values) + result = store.select("df", "ts=selector") + expected = df[df.ts.isin(selector.values)] + tm.assert_frame_equal(expected, result) + assert len(result) == 100 + + +def test_select_iterator(setup_path): + + # single table + with ensure_clean_store(setup_path) as store: + + df = tm.makeTimeDataFrame(500) + _maybe_remove(store, "df") + store.append("df", df) + + expected = store.select("df") + + results = list(store.select("df", iterator=True)) + result = concat(results) + tm.assert_frame_equal(expected, result) + + results = list(store.select("df", chunksize=100)) + assert len(results) == 5 + result = concat(results) + tm.assert_frame_equal(expected, result) + + results = list(store.select("df", chunksize=150)) + result = concat(results) + tm.assert_frame_equal(result, expected) + + with ensure_clean_path(setup_path) as path: + + df = tm.makeTimeDataFrame(500) + df.to_hdf(path, "df_non_table") + + msg = "can only use an iterator or chunksize on a table" + with pytest.raises(TypeError, match=msg): + read_hdf(path, "df_non_table", chunksize=100) + + with pytest.raises(TypeError, match=msg): + read_hdf(path, "df_non_table", iterator=True) + + with ensure_clean_path(setup_path) as path: + + df = tm.makeTimeDataFrame(500) + df.to_hdf(path, "df", format="table") + + results = list(read_hdf(path, "df", chunksize=100)) + result = concat(results) + + assert len(results) == 5 + tm.assert_frame_equal(result, df) + tm.assert_frame_equal(result, read_hdf(path, "df")) + + # multiple + + with ensure_clean_store(setup_path) as store: + + df1 = tm.makeTimeDataFrame(500) + store.append("df1", df1, data_columns=True) + df2 = tm.makeTimeDataFrame(500).rename(columns="{}_2".format) + df2["foo"] = "bar" + store.append("df2", df2) + + df = concat([df1, df2], axis=1) + + # full selection + expected = store.select_as_multiple(["df1", "df2"], selector="df1") + results = list( + store.select_as_multiple(["df1", "df2"], selector="df1", chunksize=150) + ) + result = concat(results) + tm.assert_frame_equal(expected, result) + + +def test_select_iterator_complete_8014(setup_path): + + # GH 8014 + # using iterator and where clause + chunksize = 1e4 + + # no iterator + with ensure_clean_store(setup_path) as store: + + expected = tm.makeTimeDataFrame(100064, "S") + _maybe_remove(store, "df") + store.append("df", expected) + + beg_dt = expected.index[0] + end_dt = expected.index[-1] + + # select w/o iteration and no where clause works + result = store.select("df") + tm.assert_frame_equal(expected, result) + + # select w/o iterator and where clause, single term, begin + # of range, works + where = f"index >= '{beg_dt}'" + result = store.select("df", where=where) + tm.assert_frame_equal(expected, result) + + # select w/o iterator and where clause, single term, end + # of range, works + where = f"index <= '{end_dt}'" + result = store.select("df", where=where) + tm.assert_frame_equal(expected, result) + + # select w/o iterator and where clause, inclusive range, + # works + where = f"index >= '{beg_dt}' & index <= '{end_dt}'" + result = store.select("df", where=where) + tm.assert_frame_equal(expected, result) + + # with iterator, full range + with ensure_clean_store(setup_path) as store: + + expected = tm.makeTimeDataFrame(100064, "S") + _maybe_remove(store, "df") + store.append("df", expected) + + beg_dt = expected.index[0] + end_dt = expected.index[-1] + + # select w/iterator and no where clause works + results = list(store.select("df", chunksize=chunksize)) + result = concat(results) + tm.assert_frame_equal(expected, result) + + # select w/iterator and where clause, single term, begin of range + where = f"index >= '{beg_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + result = concat(results) + tm.assert_frame_equal(expected, result) + + # select w/iterator and where clause, single term, end of range + where = f"index <= '{end_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + result = concat(results) + tm.assert_frame_equal(expected, result) + + # select w/iterator and where clause, inclusive range + where = f"index >= '{beg_dt}' & index <= '{end_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + result = concat(results) + tm.assert_frame_equal(expected, result) + + +def test_select_iterator_non_complete_8014(setup_path): + + # GH 8014 + # using iterator and where clause + chunksize = 1e4 + + # with iterator, non complete range + with ensure_clean_store(setup_path) as store: + + expected = tm.makeTimeDataFrame(100064, "S") + _maybe_remove(store, "df") + store.append("df", expected) + + beg_dt = expected.index[1] + end_dt = expected.index[-2] + + # select w/iterator and where clause, single term, begin of range + where = f"index >= '{beg_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + result = concat(results) + rexpected = expected[expected.index >= beg_dt] + tm.assert_frame_equal(rexpected, result) + + # select w/iterator and where clause, single term, end of range + where = f"index <= '{end_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + result = concat(results) + rexpected = expected[expected.index <= end_dt] + tm.assert_frame_equal(rexpected, result) + + # select w/iterator and where clause, inclusive range + where = f"index >= '{beg_dt}' & index <= '{end_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + result = concat(results) + rexpected = expected[(expected.index >= beg_dt) & (expected.index <= end_dt)] + tm.assert_frame_equal(rexpected, result) + + # with iterator, empty where + with ensure_clean_store(setup_path) as store: + + expected = tm.makeTimeDataFrame(100064, "S") + _maybe_remove(store, "df") + store.append("df", expected) + + end_dt = expected.index[-1] + + # select w/iterator and where clause, single term, begin of range + where = f"index > '{end_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + assert 0 == len(results) + + +def test_select_iterator_many_empty_frames(setup_path): + + # GH 8014 + # using iterator and where clause can return many empty + # frames. + chunksize = 10_000 + + # with iterator, range limited to the first chunk + with ensure_clean_store(setup_path) as store: + + expected = tm.makeTimeDataFrame(100000, "S") + _maybe_remove(store, "df") + store.append("df", expected) + + beg_dt = expected.index[0] + end_dt = expected.index[chunksize - 1] + + # select w/iterator and where clause, single term, begin of range + where = f"index >= '{beg_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + result = concat(results) + rexpected = expected[expected.index >= beg_dt] + tm.assert_frame_equal(rexpected, result) + + # select w/iterator and where clause, single term, end of range + where = f"index <= '{end_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + + assert len(results) == 1 + result = concat(results) + rexpected = expected[expected.index <= end_dt] + tm.assert_frame_equal(rexpected, result) + + # select w/iterator and where clause, inclusive range + where = f"index >= '{beg_dt}' & index <= '{end_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + + # should be 1, is 10 + assert len(results) == 1 + result = concat(results) + rexpected = expected[(expected.index >= beg_dt) & (expected.index <= end_dt)] + tm.assert_frame_equal(rexpected, result) + + # select w/iterator and where clause which selects + # *nothing*. + # + # To be consistent with Python idiom I suggest this should + # return [] e.g. `for e in []: print True` never prints + # True. + + where = f"index <= '{beg_dt}' & index >= '{end_dt}'" + results = list(store.select("df", where=where, chunksize=chunksize)) + + # should be [] + assert len(results) == 0 + + +def test_frame_select(setup_path): + + df = tm.makeTimeDataFrame() + + with ensure_clean_store(setup_path) as store: + store.put("frame", df, format="table") + date = df.index[len(df) // 2] + + crit1 = Term("index>=date") + assert crit1.env.scope["date"] == date + + crit2 = "columns=['A', 'D']" + crit3 = "columns=A" + + result = store.select("frame", [crit1, crit2]) + expected = df.loc[date:, ["A", "D"]] + tm.assert_frame_equal(result, expected) + + result = store.select("frame", [crit3]) + expected = df.loc[:, ["A"]] + tm.assert_frame_equal(result, expected) + + # invalid terms + df = tm.makeTimeDataFrame() + store.append("df_time", df) + msg = "could not convert string to Timestamp" + with pytest.raises(ValueError, match=msg): + store.select("df_time", "index>0") + + # can't select if not written as table + # store['frame'] = df + # with pytest.raises(ValueError): + # store.select('frame', [crit1, crit2]) + + +def test_frame_select_complex(setup_path): + # select via complex criteria + + df = tm.makeTimeDataFrame() + df["string"] = "foo" + df.loc[df.index[0:4], "string"] = "bar" + + with ensure_clean_store(setup_path) as store: + store.put("df", df, format="table", data_columns=["string"]) + + # empty + result = store.select("df", 'index>df.index[3] & string="bar"') + expected = df.loc[(df.index > df.index[3]) & (df.string == "bar")] + tm.assert_frame_equal(result, expected) + + result = store.select("df", 'index>df.index[3] & string="foo"') + expected = df.loc[(df.index > df.index[3]) & (df.string == "foo")] + tm.assert_frame_equal(result, expected) + + # or + result = store.select("df", 'index>df.index[3] | string="bar"') + expected = df.loc[(df.index > df.index[3]) | (df.string == "bar")] + tm.assert_frame_equal(result, expected) + + result = store.select( + "df", '(index>df.index[3] & index<=df.index[6]) | string="bar"' + ) + expected = df.loc[ + ((df.index > df.index[3]) & (df.index <= df.index[6])) + | (df.string == "bar") + ] + tm.assert_frame_equal(result, expected) + + # invert + result = store.select("df", 'string!="bar"') + expected = df.loc[df.string != "bar"] + tm.assert_frame_equal(result, expected) + + # invert not implemented in numexpr :( + msg = "cannot use an invert condition when passing to numexpr" + with pytest.raises(NotImplementedError, match=msg): + store.select("df", '~(string="bar")') + + # invert ok for filters + result = store.select("df", "~(columns=['A','B'])") + expected = df.loc[:, df.columns.difference(["A", "B"])] + tm.assert_frame_equal(result, expected) + + # in + result = store.select("df", "index>df.index[3] & columns in ['A','B']") + expected = df.loc[df.index > df.index[3]].reindex(columns=["A", "B"]) + tm.assert_frame_equal(result, expected) + + +def test_frame_select_complex2(setup_path): + + with ensure_clean_path(["parms.hdf", "hist.hdf"]) as paths: + + pp, hh = paths + + # use non-trivial selection criteria + parms = DataFrame({"A": [1, 1, 2, 2, 3]}) + parms.to_hdf(pp, "df", mode="w", format="table", data_columns=["A"]) + + selection = read_hdf(pp, "df", where="A=[2,3]") + hist = DataFrame( + np.random.randn(25, 1), + columns=["data"], + index=MultiIndex.from_tuples( + [(i, j) for i in range(5) for j in range(5)], names=["l1", "l2"] + ), + ) + + hist.to_hdf(hh, "df", mode="w", format="table") + + expected = read_hdf(hh, "df", where="l1=[2, 3, 4]") + + # scope with list like + l = selection.index.tolist() # noqa + store = HDFStore(hh) + result = store.select("df", where="l1=l") + tm.assert_frame_equal(result, expected) + store.close() + + result = read_hdf(hh, "df", where="l1=l") + tm.assert_frame_equal(result, expected) + + # index + index = selection.index # noqa + result = read_hdf(hh, "df", where="l1=index") + tm.assert_frame_equal(result, expected) + + result = read_hdf(hh, "df", where="l1=selection.index") + tm.assert_frame_equal(result, expected) + + result = read_hdf(hh, "df", where="l1=selection.index.tolist()") + tm.assert_frame_equal(result, expected) + + result = read_hdf(hh, "df", where="l1=list(selection.index)") + tm.assert_frame_equal(result, expected) + + # scope with index + store = HDFStore(hh) + + result = store.select("df", where="l1=index") + tm.assert_frame_equal(result, expected) + + result = store.select("df", where="l1=selection.index") + tm.assert_frame_equal(result, expected) + + result = store.select("df", where="l1=selection.index.tolist()") + tm.assert_frame_equal(result, expected) + + result = store.select("df", where="l1=list(selection.index)") + tm.assert_frame_equal(result, expected) + + store.close() + + +def test_invalid_filtering(setup_path): + + # can't use more than one filter (atm) + + df = tm.makeTimeDataFrame() + + with ensure_clean_store(setup_path) as store: + store.put("df", df, format="table") + + msg = "unable to collapse Joint Filters" + # not implemented + with pytest.raises(NotImplementedError, match=msg): + store.select("df", "columns=['A'] | columns=['B']") + + # in theory we could deal with this + with pytest.raises(NotImplementedError, match=msg): + store.select("df", "columns=['A','B'] & columns=['C']") + + +def test_string_select(setup_path): + # GH 2973 + with ensure_clean_store(setup_path) as store: + + df = tm.makeTimeDataFrame() + + # test string ==/!= + df["x"] = "none" + df.loc[df.index[2:7], "x"] = "" + + store.append("df", df, data_columns=["x"]) + + result = store.select("df", "x=none") + expected = df[df.x == "none"] + tm.assert_frame_equal(result, expected) + + result = store.select("df", "x!=none") + expected = df[df.x != "none"] + tm.assert_frame_equal(result, expected) + + df2 = df.copy() + df2.loc[df2.x == "", "x"] = np.nan + + store.append("df2", df2, data_columns=["x"]) + result = store.select("df2", "x!=none") + expected = df2[isna(df2.x)] + tm.assert_frame_equal(result, expected) + + # int ==/!= + df["int"] = 1 + df.loc[df.index[2:7], "int"] = 2 + + store.append("df3", df, data_columns=["int"]) + + result = store.select("df3", "int=2") + expected = df[df.int == 2] + tm.assert_frame_equal(result, expected) + + result = store.select("df3", "int!=2") + expected = df[df.int != 2] + tm.assert_frame_equal(result, expected) + + +def test_select_as_multiple(setup_path): + + df1 = tm.makeTimeDataFrame() + df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) + df2["foo"] = "bar" + + with ensure_clean_store(setup_path) as store: + + msg = "keys must be a list/tuple" + # no tables stored + with pytest.raises(TypeError, match=msg): + store.select_as_multiple(None, where=["A>0", "B>0"], selector="df1") + + store.append("df1", df1, data_columns=["A", "B"]) + store.append("df2", df2) + + # exceptions + with pytest.raises(TypeError, match=msg): + store.select_as_multiple(None, where=["A>0", "B>0"], selector="df1") + + with pytest.raises(TypeError, match=msg): + store.select_as_multiple([None], where=["A>0", "B>0"], selector="df1") + + msg = "'No object named df3 in the file'" + with pytest.raises(KeyError, match=msg): + store.select_as_multiple( + ["df1", "df3"], where=["A>0", "B>0"], selector="df1" + ) + + with pytest.raises(KeyError, match=msg): + store.select_as_multiple(["df3"], where=["A>0", "B>0"], selector="df1") + + with pytest.raises(KeyError, match="'No object named df4 in the file'"): + store.select_as_multiple( + ["df1", "df2"], where=["A>0", "B>0"], selector="df4" + ) + + # default select + result = store.select("df1", ["A>0", "B>0"]) + expected = store.select_as_multiple( + ["df1"], where=["A>0", "B>0"], selector="df1" + ) + tm.assert_frame_equal(result, expected) + expected = store.select_as_multiple("df1", where=["A>0", "B>0"], selector="df1") + tm.assert_frame_equal(result, expected) + + # multiple + result = store.select_as_multiple( + ["df1", "df2"], where=["A>0", "B>0"], selector="df1" + ) + expected = concat([df1, df2], axis=1) + expected = expected[(expected.A > 0) & (expected.B > 0)] + tm.assert_frame_equal(result, expected) + + # multiple (diff selector) + result = store.select_as_multiple( + ["df1", "df2"], where="index>df2.index[4]", selector="df2" + ) + expected = concat([df1, df2], axis=1) + expected = expected[5:] + tm.assert_frame_equal(result, expected) + + # test exception for diff rows + store.append("df3", tm.makeTimeDataFrame(nper=50)) + msg = "all tables must have exactly the same nrows!" + with pytest.raises(ValueError, match=msg): + store.select_as_multiple( + ["df1", "df3"], where=["A>0", "B>0"], selector="df1" + ) + + +@pytest.mark.skipif( + LooseVersion(tables.__version__) < LooseVersion("3.1.0"), + reason=("tables version does not support fix for nan selection bug: GH 4858"), +) +def test_nan_selection_bug_4858(setup_path): + + with ensure_clean_store(setup_path) as store: + + df = DataFrame({"cols": range(6), "values": range(6)}, dtype="float64") + df["cols"] = (df["cols"] + 10).apply(str) + df.iloc[0] = np.nan + + expected = DataFrame( + {"cols": ["13.0", "14.0", "15.0"], "values": [3.0, 4.0, 5.0]}, + index=[3, 4, 5], + ) + + # write w/o the index on that particular column + store.append("df", df, data_columns=True, index=["cols"]) + result = store.select("df", where="values>2.0") + tm.assert_frame_equal(result, expected) + + +def test_query_with_nested_special_character(setup_path): + df = DataFrame( + { + "a": ["a", "a", "c", "b", "test & test", "c", "b", "e"], + "b": [1, 2, 3, 4, 5, 6, 7, 8], + } + ) + expected = df[df.a == "test & test"] + with ensure_clean_store(setup_path) as store: + store.append("test", df, format="table", data_columns=True) + result = store.select("test", 'a = "test & test"') + tm.assert_frame_equal(expected, result) + + +def test_query_long_float_literal(setup_path): + # GH 14241 + df = DataFrame({"A": [1000000000.0009, 1000000000.0011, 1000000000.0015]}) + + with ensure_clean_store(setup_path) as store: + store.append("test", df, format="table", data_columns=True) + + cutoff = 1000000000.0006 + result = store.select("test", f"A < {cutoff:.4f}") + assert result.empty + + cutoff = 1000000000.0010 + result = store.select("test", f"A > {cutoff:.4f}") + expected = df.loc[[1, 2], :] + tm.assert_frame_equal(expected, result) + + exact = 1000000000.0011 + result = store.select("test", f"A == {exact:.4f}") + expected = df.loc[[1], :] + tm.assert_frame_equal(expected, result) + + +def test_query_compare_column_type(setup_path): + # GH 15492 + df = DataFrame( + { + "date": ["2014-01-01", "2014-01-02"], + "real_date": date_range("2014-01-01", periods=2), + "float": [1.1, 1.2], + "int": [1, 2], + }, + columns=["date", "real_date", "float", "int"], + ) + + with ensure_clean_store(setup_path) as store: + store.append("test", df, format="table", data_columns=True) + + ts = Timestamp("2014-01-01") # noqa + result = store.select("test", where="real_date > ts") + expected = df.loc[[1], :] + tm.assert_frame_equal(expected, result) + + for op in ["<", ">", "=="]: + # non strings to string column always fail + for v in [2.1, True, Timestamp("2014-01-01"), pd.Timedelta(1, "s")]: + query = f"date {op} v" + msg = f"Cannot compare {v} of type {type(v)} to string column" + with pytest.raises(TypeError, match=msg): + store.select("test", where=query) + + # strings to other columns must be convertible to type + v = "a" + for col in ["int", "float", "real_date"]: + query = f"{col} {op} v" + msg = "could not convert string to " + with pytest.raises(ValueError, match=msg): + store.select("test", where=query) + + for v, col in zip( + ["1", "1.1", "2014-01-01"], ["int", "float", "real_date"] + ): + query = f"{col} {op} v" + result = store.select("test", where=query) + + if op == "==": + expected = df.loc[[0], :] + elif op == ">": + expected = df.loc[[1], :] + else: + expected = df.loc[[], :] + tm.assert_frame_equal(expected, result) + + +@pytest.mark.parametrize("where", ["", (), (None,), [], [None]]) +def test_select_empty_where(where): + # GH26610 + + df = DataFrame([1, 2, 3]) + with ensure_clean_path("empty_where.h5") as path: + with HDFStore(path) as store: + store.put("df", df, "t") + result = pd.read_hdf(store, "df", where=where) + tm.assert_frame_equal(result, df) diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 131711a32d114..819f8ed9bc07f 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -1,36 +1,24 @@ import datetime -from datetime import timedelta -from distutils.version import LooseVersion import hashlib -from io import BytesIO import os -from pathlib import Path -import re import time from warnings import catch_warnings, simplefilter import numpy as np 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 ( - Categorical, - CategoricalIndex, DataFrame, DatetimeIndex, Index, - Int64Index, MultiIndex, - RangeIndex, Series, Timestamp, - bdate_range, concat, date_range, - isna, timedelta_range, ) import pandas._testing as tm @@ -39,22 +27,8 @@ ensure_clean_path, ensure_clean_store, safe_close, - tables, ) -from pandas.io.pytables import ( - ClosedFileError, - HDFStore, - PossibleDataLossError, - Term, - _maybe_adjust_name, - read_hdf, -) - -from pandas.io import pytables as pytables # isort:skip -from pandas.io.pytables import TableIterator # isort:skip - - # TODO(ArrayManager) HDFStore relies on accessing the blocks pytestmark = td.skip_array_manager_not_yet_implemented @@ -64,4971 +38,972 @@ "ignore:object name:tables.exceptions.NaturalNameWarning" ) +from pandas.io.pytables import HDFStore, read_hdf -@pytest.mark.single -class TestHDFStore: - def test_format_type(self, setup_path): - df = DataFrame({"A": [1, 2]}) - with ensure_clean_path(setup_path) as path: - with HDFStore(path) as store: - store.put("a", df, format="fixed") - store.put("b", df, format="table") - - assert store.get_storer("a").format_type == "fixed" - assert store.get_storer("b").format_type == "table" - - def test_format_kwarg_in_constructor(self, setup_path): - # GH 13291 - - msg = "format is not a defined argument for HDFStore" +pytestmark = pytest.mark.single - with tm.ensure_clean(setup_path) as path: - with pytest.raises(ValueError, match=msg): - HDFStore(path, format="table") - def test_context(self, setup_path): - with tm.ensure_clean(setup_path) as path: - try: - with HDFStore(path) as tbl: - raise ValueError("blah") - except ValueError: - pass - with tm.ensure_clean(setup_path) as path: +def test_context(setup_path): + with tm.ensure_clean(setup_path) as path: + try: with HDFStore(path) as tbl: - tbl["a"] = tm.makeDataFrame() - assert len(tbl) == 1 - assert type(tbl["a"]) == DataFrame - - def test_conv_read_write(self, setup_path): - with tm.ensure_clean() as path: - - def roundtrip(key, obj, **kwargs): - obj.to_hdf(path, key, **kwargs) - return read_hdf(path, key) - - o = tm.makeTimeSeries() - tm.assert_series_equal(o, roundtrip("series", o)) - - o = tm.makeStringSeries() - tm.assert_series_equal(o, roundtrip("string_series", o)) - - o = tm.makeDataFrame() - tm.assert_frame_equal(o, roundtrip("frame", o)) - - # table - df = DataFrame({"A": range(5), "B": range(5)}) - df.to_hdf(path, "table", append=True) - result = read_hdf(path, "table", where=["index>2"]) - tm.assert_frame_equal(df[df.index > 2], result) - - def test_long_strings(self, setup_path): - - # GH6166 - df = DataFrame( - {"a": tm.rands_array(100, size=10)}, index=tm.rands_array(100, size=10) - ) - - with ensure_clean_store(setup_path) as store: - store.append("df", df, data_columns=["a"]) - - result = store.select("df") - tm.assert_frame_equal(df, result) + raise ValueError("blah") + except ValueError: + pass + with tm.ensure_clean(setup_path) as path: + with HDFStore(path) as tbl: + tbl["a"] = tm.makeDataFrame() + assert len(tbl) == 1 + assert type(tbl["a"]) == DataFrame + + +def test_no_track_times(setup_path): + + # GH 32682 + # enables to set track_times (see `pytables` `create_table` documentation) + + def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128): + h = hash_factory() + with open(filename, "rb") as f: + for chunk in iter(lambda: f.read(chunk_num_blocks * h.block_size), b""): + h.update(chunk) + return h.digest() + + def create_h5_and_return_checksum(track_times): + with ensure_clean_path(setup_path) as path: + df = DataFrame({"a": [1]}) + + with HDFStore(path, mode="w") as hdf: + hdf.put( + "table", + df, + format="table", + data_columns=True, + index=None, + track_times=track_times, + ) - def test_api(self, setup_path): + return checksum(path) - # GH4584 - # API issue when to_hdf doesn't accept append AND format args - with ensure_clean_path(setup_path) as path: + checksum_0_tt_false = create_h5_and_return_checksum(track_times=False) + checksum_0_tt_true = create_h5_and_return_checksum(track_times=True) - df = tm.makeDataFrame() - df.iloc[:10].to_hdf(path, "df", append=True, format="table") - df.iloc[10:].to_hdf(path, "df", append=True, format="table") - tm.assert_frame_equal(read_hdf(path, "df"), df) + # sleep is necessary to create h5 with different creation time + time.sleep(1) - # append to False - df.iloc[:10].to_hdf(path, "df", append=False, format="table") - df.iloc[10:].to_hdf(path, "df", append=True, format="table") - tm.assert_frame_equal(read_hdf(path, "df"), df) + checksum_1_tt_false = create_h5_and_return_checksum(track_times=False) + checksum_1_tt_true = create_h5_and_return_checksum(track_times=True) - with ensure_clean_path(setup_path) as path: + # checksums are the same if track_time = False + assert checksum_0_tt_false == checksum_1_tt_false - df = tm.makeDataFrame() - df.iloc[:10].to_hdf(path, "df", append=True) - df.iloc[10:].to_hdf(path, "df", append=True, format="table") - tm.assert_frame_equal(read_hdf(path, "df"), df) + # checksums are NOT same if track_time = True + assert checksum_0_tt_true != checksum_1_tt_true - # append to False - df.iloc[:10].to_hdf(path, "df", append=False, format="table") - df.iloc[10:].to_hdf(path, "df", append=True) - tm.assert_frame_equal(read_hdf(path, "df"), df) - with ensure_clean_path(setup_path) as path: +def test_iter_empty(setup_path): - df = tm.makeDataFrame() - df.to_hdf(path, "df", append=False, format="fixed") - tm.assert_frame_equal(read_hdf(path, "df"), df) + with ensure_clean_store(setup_path) as store: + # GH 12221 + assert list(store) == [] - df.to_hdf(path, "df", append=False, format="f") - tm.assert_frame_equal(read_hdf(path, "df"), df) - df.to_hdf(path, "df", append=False) - tm.assert_frame_equal(read_hdf(path, "df"), df) +def test_repr(setup_path): - df.to_hdf(path, "df") - tm.assert_frame_equal(read_hdf(path, "df"), df) + with ensure_clean_store(setup_path) as store: + repr(store) + store.info() + store["a"] = tm.makeTimeSeries() + store["b"] = tm.makeStringSeries() + store["c"] = tm.makeDataFrame() - with ensure_clean_store(setup_path) as store: + df = tm.makeDataFrame() + df["obj1"] = "foo" + df["obj2"] = "bar" + df["bool1"] = df["A"] > 0 + df["bool2"] = df["B"] > 0 + df["bool3"] = True + df["int1"] = 1 + df["int2"] = 2 + df["timestamp1"] = Timestamp("20010102") + df["timestamp2"] = Timestamp("20010103") + df["datetime1"] = datetime.datetime(2001, 1, 2, 0, 0) + df["datetime2"] = datetime.datetime(2001, 1, 3, 0, 0) + df.loc[df.index[3:6], ["obj1"]] = np.nan + df = df._consolidate()._convert(datetime=True) - path = store._path - df = tm.makeDataFrame() + with catch_warnings(record=True): + simplefilter("ignore", pd.errors.PerformanceWarning) + store["df"] = df - _maybe_remove(store, "df") - store.append("df", df.iloc[:10], append=True, format="table") - store.append("df", df.iloc[10:], append=True, format="table") - tm.assert_frame_equal(store.select("df"), df) + # make a random group in hdf space + store._handle.create_group(store._handle.root, "bah") - # append to False - _maybe_remove(store, "df") - store.append("df", df.iloc[:10], append=False, format="table") - store.append("df", df.iloc[10:], append=True, format="table") - tm.assert_frame_equal(store.select("df"), df) + assert store.filename in repr(store) + assert store.filename in str(store) + store.info() - # formats - _maybe_remove(store, "df") - store.append("df", df.iloc[:10], append=False, format="table") - store.append("df", df.iloc[10:], append=True, format="table") - tm.assert_frame_equal(store.select("df"), df) + # storers + with ensure_clean_store(setup_path) as store: - _maybe_remove(store, "df") - store.append("df", df.iloc[:10], append=False, format="table") - store.append("df", df.iloc[10:], append=True, format=None) - tm.assert_frame_equal(store.select("df"), df) + df = tm.makeDataFrame() + store.append("df", df) - with ensure_clean_path(setup_path) as path: - # Invalid. - df = tm.makeDataFrame() + s = store.get_storer("df") + repr(s) + str(s) - msg = "Can only append to Tables" - with pytest.raises(ValueError, match=msg): - df.to_hdf(path, "df", append=True, format="f") +@pytest.mark.filterwarnings("ignore:object name:tables.exceptions.NaturalNameWarning") +def test_contains(setup_path): - with pytest.raises(ValueError, match=msg): - df.to_hdf(path, "df", append=True, format="fixed") + with ensure_clean_store(setup_path) as store: + store["a"] = tm.makeTimeSeries() + store["b"] = tm.makeDataFrame() + store["foo/bar"] = tm.makeDataFrame() + assert "a" in store + assert "b" in store + assert "c" not in store + assert "foo/bar" in store + assert "/foo/bar" in store + assert "/foo/b" not in store + assert "bar" not in store - msg = r"invalid HDFStore format specified \[foo\]" + # gh-2694: tables.NaturalNameWarning + with catch_warnings(record=True): + store["node())"] = tm.makeDataFrame() + assert "node())" in store - with pytest.raises(TypeError, match=msg): - df.to_hdf(path, "df", append=True, format="foo") - with pytest.raises(TypeError, match=msg): - df.to_hdf(path, "df", append=False, format="foo") +def test_versioning(setup_path): - # File path doesn't exist - path = "" - msg = f"File {path} does not exist" + with ensure_clean_store(setup_path) as store: + store["a"] = tm.makeTimeSeries() + store["b"] = tm.makeDataFrame() + df = tm.makeTimeDataFrame() + _maybe_remove(store, "df1") + store.append("df1", df[:10]) + store.append("df1", df[10:]) + assert store.root.a._v_attrs.pandas_version == "0.15.2" + assert store.root.b._v_attrs.pandas_version == "0.15.2" + assert store.root.df1._v_attrs.pandas_version == "0.15.2" - with pytest.raises(FileNotFoundError, match=msg): - read_hdf(path, "df") + # write a file and wipe its versioning + _maybe_remove(store, "df2") + store.append("df2", df) - def test_api_default_format(self, setup_path): + # this is an error because its table_type is appendable, but no + # version info + store.get_node("df2")._v_attrs.pandas_version = None - # default_format option - with ensure_clean_store(setup_path) as store: - df = tm.makeDataFrame() + msg = "'NoneType' object has no attribute 'startswith'" - pd.set_option("io.hdf.default_format", "fixed") - _maybe_remove(store, "df") - store.put("df", df) - assert not store.get_storer("df").is_table + with pytest.raises(Exception, match=msg): + store.select("df2") - msg = "Can only append to Tables" - with pytest.raises(ValueError, match=msg): - store.append("df2", df) +@pytest.mark.parametrize( + "where, expected", + [ + ( + "/", + { + "": ({"first_group", "second_group"}, set()), + "/first_group": (set(), {"df1", "df2"}), + "/second_group": ({"third_group"}, {"df3", "s1"}), + "/second_group/third_group": (set(), {"df4"}), + }, + ), + ( + "/second_group", + { + "/second_group": ({"third_group"}, {"df3", "s1"}), + "/second_group/third_group": (set(), {"df4"}), + }, + ), + ], +) +def test_walk(where, expected, setup_path): + # GH10143 + objs = { + "df1": DataFrame([1, 2, 3]), + "df2": DataFrame([4, 5, 6]), + "df3": DataFrame([6, 7, 8]), + "df4": DataFrame([9, 10, 11]), + "s1": Series([10, 9, 8]), + # Next 3 items aren't pandas objects and should be ignored + "a1": np.array([[1, 2, 3], [4, 5, 6]]), + "tb1": np.array([(1, 2, 3), (4, 5, 6)], dtype="i,i,i"), + "tb2": np.array([(7, 8, 9), (10, 11, 12)], dtype="i,i,i"), + } + + with ensure_clean_store("walk_groups.hdf", mode="w") as store: + store.put("/first_group/df1", objs["df1"]) + store.put("/first_group/df2", objs["df2"]) + store.put("/second_group/df3", objs["df3"]) + store.put("/second_group/s1", objs["s1"]) + store.put("/second_group/third_group/df4", objs["df4"]) + # Create non-pandas objects + store._handle.create_array("/first_group", "a1", objs["a1"]) + store._handle.create_table("/first_group", "tb1", obj=objs["tb1"]) + store._handle.create_table("/second_group", "tb2", obj=objs["tb2"]) + + assert len(list(store.walk(where=where))) == len(expected) + for path, groups, leaves in store.walk(where=where): + assert path in expected + expected_groups, expected_frames = expected[path] + assert expected_groups == set(groups) + assert expected_frames == set(leaves) + for leaf in leaves: + frame_path = "/".join([path, leaf]) + obj = store.get(frame_path) + if "df" in leaf: + tm.assert_frame_equal(obj, objs[leaf]) + else: + tm.assert_series_equal(obj, objs[leaf]) - pd.set_option("io.hdf.default_format", "table") - _maybe_remove(store, "df") - store.put("df", df) - assert store.get_storer("df").is_table - _maybe_remove(store, "df2") - store.append("df2", df) - assert store.get_storer("df").is_table - pd.set_option("io.hdf.default_format", None) +def test_getattr(setup_path): - with ensure_clean_path(setup_path) as path: + with ensure_clean_store(setup_path) as store: - df = tm.makeDataFrame() + s = tm.makeTimeSeries() + store["a"] = s - pd.set_option("io.hdf.default_format", "fixed") - df.to_hdf(path, "df") - with HDFStore(path) as store: - assert not store.get_storer("df").is_table - with pytest.raises(ValueError, match=msg): - df.to_hdf(path, "df2", append=True) + # test attribute access + result = store.a + tm.assert_series_equal(result, s) + result = getattr(store, "a") + tm.assert_series_equal(result, s) - pd.set_option("io.hdf.default_format", "table") - df.to_hdf(path, "df3") - with HDFStore(path) as store: - assert store.get_storer("df3").is_table - df.to_hdf(path, "df4", append=True) - with HDFStore(path) as store: - assert store.get_storer("df4").is_table + df = tm.makeTimeDataFrame() + store["df"] = df + result = store.df + tm.assert_frame_equal(result, df) - pd.set_option("io.hdf.default_format", None) + # errors + for x in ["d", "mode", "path", "handle", "complib"]: + msg = f"'HDFStore' object has no attribute '{x}'" + with pytest.raises(AttributeError, match=msg): + getattr(store, x) - def test_keys(self, setup_path): + # not stores + for x in ["mode", "path", "handle", "complib"]: + getattr(store, f"_{x}") - with ensure_clean_store(setup_path) as store: - store["a"] = tm.makeTimeSeries() - store["b"] = tm.makeStringSeries() - store["c"] = tm.makeDataFrame() - assert len(store) == 3 - expected = {"/a", "/b", "/c"} - assert set(store.keys()) == expected - assert set(store) == expected +def test_store_dropna(setup_path): + df_with_missing = DataFrame( + {"col1": [0.0, np.nan, 2.0], "col2": [1.0, np.nan, np.nan]}, + index=list("abc"), + ) + df_without_missing = DataFrame( + {"col1": [0.0, 2.0], "col2": [1.0, np.nan]}, index=list("ac") + ) - def test_no_track_times(self, setup_path): + # # Test to make sure defaults are to not drop. + # # Corresponding to Issue 9382 + with ensure_clean_path(setup_path) as path: + df_with_missing.to_hdf(path, "df", format="table") + reloaded = read_hdf(path, "df") + tm.assert_frame_equal(df_with_missing, reloaded) - # GH 32682 - # enables to set track_times (see `pytables` `create_table` documentation) + with ensure_clean_path(setup_path) as path: + df_with_missing.to_hdf(path, "df", format="table", dropna=False) + reloaded = read_hdf(path, "df") + tm.assert_frame_equal(df_with_missing, reloaded) - def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128): - h = hash_factory() - with open(filename, "rb") as f: - for chunk in iter(lambda: f.read(chunk_num_blocks * h.block_size), b""): - h.update(chunk) - return h.digest() + with ensure_clean_path(setup_path) as path: + df_with_missing.to_hdf(path, "df", format="table", dropna=True) + reloaded = read_hdf(path, "df") + tm.assert_frame_equal(df_without_missing, reloaded) - def create_h5_and_return_checksum(track_times): - with ensure_clean_path(setup_path) as path: - df = DataFrame({"a": [1]}) - with HDFStore(path, mode="w") as hdf: - hdf.put( - "table", - df, - format="table", - data_columns=True, - index=None, - track_times=track_times, - ) +def test_to_hdf_with_min_itemsize(setup_path): - return checksum(path) + with ensure_clean_path(setup_path) as path: - checksum_0_tt_false = create_h5_and_return_checksum(track_times=False) - checksum_0_tt_true = create_h5_and_return_checksum(track_times=True) + # min_itemsize in index with to_hdf (GH 10381) + df = tm.makeMixedDataFrame().set_index("C") + df.to_hdf(path, "ss3", format="table", min_itemsize={"index": 6}) + # just make sure there is a longer string: + df2 = df.copy().reset_index().assign(C="longer").set_index("C") + df2.to_hdf(path, "ss3", append=True, format="table") + tm.assert_frame_equal(pd.read_hdf(path, "ss3"), pd.concat([df, df2])) - # sleep is necessary to create h5 with different creation time - time.sleep(1) + # same as above, with a Series + df["B"].to_hdf(path, "ss4", format="table", min_itemsize={"index": 6}) + df2["B"].to_hdf(path, "ss4", append=True, format="table") + tm.assert_series_equal(pd.read_hdf(path, "ss4"), pd.concat([df["B"], df2["B"]])) - checksum_1_tt_false = create_h5_and_return_checksum(track_times=False) - checksum_1_tt_true = create_h5_and_return_checksum(track_times=True) - # checksums are the same if track_time = False - assert checksum_0_tt_false == checksum_1_tt_false +@pytest.mark.parametrize("format", ["fixed", "table"]) +def test_to_hdf_errors(format, setup_path): - # checksums are NOT same if track_time = True - assert checksum_0_tt_true != checksum_1_tt_true + data = ["\ud800foo"] + ser = Series(data, index=Index(data)) + with ensure_clean_path(setup_path) as path: + # GH 20835 + ser.to_hdf(path, "table", format=format, errors="surrogatepass") - def test_non_pandas_keys(self, setup_path): - class Table1(tables.IsDescription): - value1 = tables.Float32Col() + result = pd.read_hdf(path, "table", errors="surrogatepass") + tm.assert_series_equal(result, ser) - class Table2(tables.IsDescription): - value2 = tables.Float32Col() - class Table3(tables.IsDescription): - value3 = tables.Float32Col() +def test_create_table_index(setup_path): - with ensure_clean_path(setup_path) as path: - with tables.open_file(path, mode="w") as h5file: - group = h5file.create_group("/", "group") - h5file.create_table(group, "table1", Table1, "Table 1") - h5file.create_table(group, "table2", Table2, "Table 2") - h5file.create_table(group, "table3", Table3, "Table 3") - with HDFStore(path) as store: - assert len(store.keys(include="native")) == 3 - expected = {"/group/table1", "/group/table2", "/group/table3"} - assert set(store.keys(include="native")) == expected - assert set(store.keys(include="pandas")) == set() - for name in expected: - df = store.get(name) - assert len(df.columns) == 1 - - def test_keys_illegal_include_keyword_value(self, setup_path): - with ensure_clean_store(setup_path) as store: - with pytest.raises( - ValueError, - match="`include` should be either 'pandas' or 'native' " - "but is 'illegal'", - ): - store.keys(include="illegal") - - def test_keys_ignore_hdf_softlink(self, setup_path): - - # GH 20523 - # Puts a softlink into HDF file and rereads - - with ensure_clean_store(setup_path) as store: - - df = DataFrame({"A": range(5), "B": range(5)}) - store.put("df", df) - - assert store.keys() == ["/df"] - - store._handle.create_soft_link(store._handle.root, "symlink", "df") - - # Should ignore the softlink - assert store.keys() == ["/df"] - - def test_iter_empty(self, setup_path): - - with ensure_clean_store(setup_path) as store: - # GH 12221 - assert list(store) == [] - - def test_repr(self, setup_path): - - with ensure_clean_store(setup_path) as store: - repr(store) - store.info() - store["a"] = tm.makeTimeSeries() - store["b"] = tm.makeStringSeries() - store["c"] = tm.makeDataFrame() - - df = tm.makeDataFrame() - df["obj1"] = "foo" - df["obj2"] = "bar" - df["bool1"] = df["A"] > 0 - df["bool2"] = df["B"] > 0 - df["bool3"] = True - df["int1"] = 1 - df["int2"] = 2 - df["timestamp1"] = Timestamp("20010102") - df["timestamp2"] = Timestamp("20010103") - df["datetime1"] = datetime.datetime(2001, 1, 2, 0, 0) - df["datetime2"] = datetime.datetime(2001, 1, 3, 0, 0) - df.loc[df.index[3:6], ["obj1"]] = np.nan - df = df._consolidate()._convert(datetime=True) + with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): - simplefilter("ignore", pd.errors.PerformanceWarning) - store["df"] = df - - # make a random group in hdf space - store._handle.create_group(store._handle.root, "bah") - - assert store.filename in repr(store) - assert store.filename in str(store) - store.info() - - # storers - with ensure_clean_store(setup_path) as store: - - df = tm.makeDataFrame() - store.append("df", df) - - s = store.get_storer("df") - repr(s) - str(s) - - @ignore_natural_naming_warning - def test_contains(self, setup_path): - - with ensure_clean_store(setup_path) as store: - store["a"] = tm.makeTimeSeries() - store["b"] = tm.makeDataFrame() - store["foo/bar"] = tm.makeDataFrame() - assert "a" in store - assert "b" in store - assert "c" not in store - assert "foo/bar" in store - assert "/foo/bar" in store - assert "/foo/b" not in store - assert "bar" not in store - - # gh-2694: tables.NaturalNameWarning - with catch_warnings(record=True): - store["node())"] = tm.makeDataFrame() - assert "node())" in store + with catch_warnings(record=True): - def test_versioning(self, setup_path): + def col(t, column): + return getattr(store.get_storer(t).table.cols, column) - with ensure_clean_store(setup_path) as store: - store["a"] = tm.makeTimeSeries() - store["b"] = tm.makeDataFrame() + # data columns df = tm.makeTimeDataFrame() - _maybe_remove(store, "df1") - store.append("df1", df[:10]) - store.append("df1", df[10:]) - assert store.root.a._v_attrs.pandas_version == "0.15.2" - assert store.root.b._v_attrs.pandas_version == "0.15.2" - assert store.root.df1._v_attrs.pandas_version == "0.15.2" - - # write a file and wipe its versioning - _maybe_remove(store, "df2") - store.append("df2", df) - - # this is an error because its table_type is appendable, but no - # version info - store.get_node("df2")._v_attrs.pandas_version = None - - msg = "'NoneType' object has no attribute 'startswith'" - - with pytest.raises(Exception, match=msg): - store.select("df2") - - def test_mode(self, setup_path): - - df = tm.makeTimeDataFrame() - - def check(mode): - - msg = r"[\S]* does not exist" - with ensure_clean_path(setup_path) as path: - - # constructor - if mode in ["r", "r+"]: - with pytest.raises(IOError, match=msg): - HDFStore(path, mode=mode) - - else: - store = HDFStore(path, mode=mode) - assert store._handle.mode == mode - store.close() - - with ensure_clean_path(setup_path) as path: - - # context - if mode in ["r", "r+"]: - with pytest.raises(IOError, match=msg): - with HDFStore(path, mode=mode) as store: - pass - else: - with HDFStore(path, mode=mode) as store: - assert store._handle.mode == mode - - with ensure_clean_path(setup_path) as path: - - # conv write - if mode in ["r", "r+"]: - with pytest.raises(IOError, match=msg): - df.to_hdf(path, "df", mode=mode) - df.to_hdf(path, "df", mode="w") - else: - df.to_hdf(path, "df", mode=mode) - - # conv read - if mode in ["w"]: - msg = ( - "mode w is not allowed while performing a read. " - r"Allowed modes are r, r\+ and a." - ) - with pytest.raises(ValueError, match=msg): - read_hdf(path, "df", mode=mode) - else: - result = read_hdf(path, "df", mode=mode) - tm.assert_frame_equal(result, df) - - def check_default_mode(): - - # read_hdf uses default mode - with ensure_clean_path(setup_path) as path: - df.to_hdf(path, "df", mode="w") - result = read_hdf(path, "df") - tm.assert_frame_equal(result, df) - - check("r") - check("r+") - check("a") - check("w") - check_default_mode() + df["string"] = "foo" + df["string2"] = "bar" + store.append("f", df, data_columns=["string", "string2"]) + assert col("f", "index").is_indexed is True + assert col("f", "string").is_indexed is True + assert col("f", "string2").is_indexed is True + + # specify index=columns + store.append("f2", df, index=["string"], data_columns=["string", "string2"]) + assert col("f2", "index").is_indexed is False + assert col("f2", "string").is_indexed is True + assert col("f2", "string2").is_indexed is False + + # try to index a non-table + _maybe_remove(store, "f2") + store.put("f2", df) + msg = "cannot create table index on a Fixed format store" + with pytest.raises(TypeError, match=msg): + store.create_table_index("f2") - def test_reopen_handle(self, setup_path): - with ensure_clean_path(setup_path) as path: +def test_create_table_index_data_columns_argument(setup_path): + # GH 28156 - store = HDFStore(path, mode="a") - store["a"] = tm.makeTimeSeries() + with ensure_clean_store(setup_path) as store: - msg = ( - r"Re-opening the file \[[\S]*\] with mode \[a\] will delete the " - "current file!" - ) - # invalid mode change - with pytest.raises(PossibleDataLossError, match=msg): - store.open("w") - - store.close() - assert not store.is_open - - # truncation ok here - store.open("w") - assert store.is_open - assert len(store) == 0 - store.close() - assert not store.is_open - - store = HDFStore(path, mode="a") - store["a"] = tm.makeTimeSeries() - - # reopen as read - store.open("r") - assert store.is_open - assert len(store) == 1 - assert store._mode == "r" - store.close() - assert not store.is_open - - # reopen as append - store.open("a") - assert store.is_open - assert len(store) == 1 - assert store._mode == "a" - store.close() - assert not store.is_open - - # reopen as append (again) - store.open("a") - assert store.is_open - assert len(store) == 1 - assert store._mode == "a" - store.close() - assert not store.is_open - - def test_open_args(self, setup_path): - - with tm.ensure_clean(setup_path) as path: - - df = tm.makeDataFrame() - - # create an in memory store - store = HDFStore( - path, mode="a", driver="H5FD_CORE", driver_core_backing_store=0 - ) - store["df"] = df - store.append("df2", df) - - tm.assert_frame_equal(store["df"], df) - tm.assert_frame_equal(store["df2"], df) - - store.close() - - # the file should not have actually been written - assert not os.path.exists(path) - - def test_flush(self, setup_path): - - with ensure_clean_store(setup_path) as store: - store["a"] = tm.makeTimeSeries() - store.flush() - store.flush(fsync=True) - - def test_get(self, setup_path): - - with ensure_clean_store(setup_path) as store: - store["a"] = tm.makeTimeSeries() - left = store.get("a") - right = store["a"] - tm.assert_series_equal(left, right) - - left = store.get("/a") - right = store["/a"] - tm.assert_series_equal(left, right) - - with pytest.raises(KeyError, match="'No object named b in the file'"): - store.get("b") - - @pytest.mark.parametrize( - "where, expected", - [ - ( - "/", - { - "": ({"first_group", "second_group"}, set()), - "/first_group": (set(), {"df1", "df2"}), - "/second_group": ({"third_group"}, {"df3", "s1"}), - "/second_group/third_group": (set(), {"df4"}), - }, - ), - ( - "/second_group", - { - "/second_group": ({"third_group"}, {"df3", "s1"}), - "/second_group/third_group": (set(), {"df4"}), - }, - ), - ], - ) - def test_walk(self, where, expected, setup_path): - # GH10143 - objs = { - "df1": DataFrame([1, 2, 3]), - "df2": DataFrame([4, 5, 6]), - "df3": DataFrame([6, 7, 8]), - "df4": DataFrame([9, 10, 11]), - "s1": Series([10, 9, 8]), - # Next 3 items aren't pandas objects and should be ignored - "a1": np.array([[1, 2, 3], [4, 5, 6]]), - "tb1": np.array([(1, 2, 3), (4, 5, 6)], dtype="i,i,i"), - "tb2": np.array([(7, 8, 9), (10, 11, 12)], dtype="i,i,i"), - } + with catch_warnings(record=True): - with ensure_clean_store("walk_groups.hdf", mode="w") as store: - store.put("/first_group/df1", objs["df1"]) - store.put("/first_group/df2", objs["df2"]) - store.put("/second_group/df3", objs["df3"]) - store.put("/second_group/s1", objs["s1"]) - store.put("/second_group/third_group/df4", objs["df4"]) - # Create non-pandas objects - store._handle.create_array("/first_group", "a1", objs["a1"]) - store._handle.create_table("/first_group", "tb1", obj=objs["tb1"]) - store._handle.create_table("/second_group", "tb2", obj=objs["tb2"]) - - assert len(list(store.walk(where=where))) == len(expected) - for path, groups, leaves in store.walk(where=where): - assert path in expected - expected_groups, expected_frames = expected[path] - assert expected_groups == set(groups) - assert expected_frames == set(leaves) - for leaf in leaves: - frame_path = "/".join([path, leaf]) - obj = store.get(frame_path) - if "df" in leaf: - tm.assert_frame_equal(obj, objs[leaf]) - else: - tm.assert_series_equal(obj, objs[leaf]) - - def test_getattr(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - s = tm.makeTimeSeries() - store["a"] = s - - # test attribute access - result = store.a - tm.assert_series_equal(result, s) - result = getattr(store, "a") - tm.assert_series_equal(result, s) + def col(t, column): + return getattr(store.get_storer(t).table.cols, column) + # data columns df = tm.makeTimeDataFrame() - store["df"] = df - result = store.df - tm.assert_frame_equal(result, df) - - # errors - for x in ["d", "mode", "path", "handle", "complib"]: - msg = f"'HDFStore' object has no attribute '{x}'" - with pytest.raises(AttributeError, match=msg): - getattr(store, x) - - # not stores - for x in ["mode", "path", "handle", "complib"]: - getattr(store, f"_{x}") - - def test_put(self, setup_path): + df["string"] = "foo" + df["string2"] = "bar" + store.append("f", df, data_columns=["string"]) + assert col("f", "index").is_indexed is True + assert col("f", "string").is_indexed is True - with ensure_clean_store(setup_path) as store: + msg = "'Cols' object has no attribute 'string2'" + with pytest.raises(AttributeError, match=msg): + col("f", "string2").is_indexed - ts = tm.makeTimeSeries() - df = tm.makeTimeDataFrame() - store["a"] = ts - store["b"] = df[:10] - store["foo/bar/bah"] = df[:10] - store["foo"] = df[:10] - store["/foo"] = df[:10] - store.put("c", df[:10], format="table") - - # not OK, not a table - msg = "Can only append to Tables" - with pytest.raises(ValueError, match=msg): - store.put("b", df[10:], append=True) - - # node does not currently exist, test _is_table_type returns False - # in this case - _maybe_remove(store, "f") - with pytest.raises(ValueError, match=msg): - store.put("f", df[10:], append=True) - - # can't put to a table (use append instead) - with pytest.raises(ValueError, match=msg): - store.put("c", df[10:], append=True) - - # overwrite table - store.put("c", df[:10], format="table", append=False) - tm.assert_frame_equal(df[:10], store["c"]) - - def test_put_string_index(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - index = Index([f"I am a very long string index: {i}" for i in range(20)]) - s = Series(np.arange(20), index=index) - df = DataFrame({"A": s, "B": s}) - - store["a"] = s - tm.assert_series_equal(store["a"], s) - - store["b"] = df - tm.assert_frame_equal(store["b"], df) - - # mixed length - index = Index( - ["abcdefghijklmnopqrstuvwxyz1234567890"] - + [f"I am a very long string index: {i}" for i in range(20)] + # try to index a col which isn't a data_column + msg = ( + "column string2 is not a data_column.\n" + "In order to read column string2 you must reload the dataframe \n" + "into HDFStore and include string2 with the data_columns argument." ) - s = Series(np.arange(21), index=index) - df = DataFrame({"A": s, "B": s}) - store["a"] = s - tm.assert_series_equal(store["a"], s) - - store["b"] = df - tm.assert_frame_equal(store["b"], df) + with pytest.raises(AttributeError, match=msg): + store.create_table_index("f", columns=["string2"]) - def test_put_compression(self, setup_path): - with ensure_clean_store(setup_path) as store: - df = tm.makeTimeDataFrame() +def test_mi_data_columns(setup_path): + # GH 14435 + idx = MultiIndex.from_arrays( + [date_range("2000-01-01", periods=5), range(5)], names=["date", "id"] + ) + df = DataFrame({"a": [1.1, 1.2, 1.3, 1.4, 1.5]}, index=idx) + + with ensure_clean_store(setup_path) as store: + store.append("df", df, data_columns=True) + + actual = store.select("df", where="id == 1") + expected = df.iloc[[1], :] + tm.assert_frame_equal(actual, expected) + + +def test_table_mixed_dtypes(setup_path): + + # frame + df = tm.makeDataFrame() + df["obj1"] = "foo" + df["obj2"] = "bar" + df["bool1"] = df["A"] > 0 + df["bool2"] = df["B"] > 0 + df["bool3"] = True + df["int1"] = 1 + df["int2"] = 2 + df["timestamp1"] = Timestamp("20010102") + df["timestamp2"] = Timestamp("20010103") + df["datetime1"] = datetime.datetime(2001, 1, 2, 0, 0) + df["datetime2"] = datetime.datetime(2001, 1, 3, 0, 0) + df.loc[df.index[3:6], ["obj1"]] = np.nan + df = df._consolidate()._convert(datetime=True) + + with ensure_clean_store(setup_path) as store: + store.append("df1_mixed", df) + tm.assert_frame_equal(store.select("df1_mixed"), df) + + +def test_calendar_roundtrip_issue(setup_path): + + # 8591 + # doc example from tseries holiday section + weekmask_egypt = "Sun Mon Tue Wed Thu" + holidays = [ + "2012-05-01", + datetime.datetime(2013, 5, 1), + np.datetime64("2014-05-01"), + ] + bday_egypt = pd.offsets.CustomBusinessDay( + holidays=holidays, weekmask=weekmask_egypt + ) + dt = datetime.datetime(2013, 4, 30) + dts = date_range(dt, periods=5, freq=bday_egypt) - store.put("c", df, format="table", complib="zlib") - tm.assert_frame_equal(store["c"], df) + s = Series(dts.weekday, dts).map(Series("Mon Tue Wed Thu Fri Sat Sun".split())) - # can't compress if format='fixed' - msg = "Compression not supported on Fixed format stores" - with pytest.raises(ValueError, match=msg): - store.put("b", df, format="fixed", complib="zlib") + with ensure_clean_store(setup_path) as store: - @td.skip_if_windows_python_3 - def test_put_compression_blosc(self, setup_path): - df = tm.makeTimeDataFrame() + store.put("fixed", s) + result = store.select("fixed") + tm.assert_series_equal(result, s) - with ensure_clean_store(setup_path) as store: + store.append("table", s) + result = store.select("table") + tm.assert_series_equal(result, s) - # can't compress if format='fixed' - msg = "Compression not supported on Fixed format stores" - with pytest.raises(ValueError, match=msg): - store.put("b", df, format="fixed", complib="blosc") - store.put("c", df, format="table", complib="blosc") - tm.assert_frame_equal(store["c"], df) +def test_remove(setup_path): - def test_complibs_default_settings(self, setup_path): - # GH15943 - df = tm.makeDataFrame() + with ensure_clean_store(setup_path) as store: - # Set complevel and check if complib is automatically set to - # default value - with ensure_clean_path(setup_path) as tmpfile: - df.to_hdf(tmpfile, "df", complevel=9) - result = pd.read_hdf(tmpfile, "df") - tm.assert_frame_equal(result, df) - - with tables.open_file(tmpfile, mode="r") as h5file: - for node in h5file.walk_nodes(where="/df", classname="Leaf"): - assert node.filters.complevel == 9 - assert node.filters.complib == "zlib" - - # Set complib and check to see if compression is disabled - with ensure_clean_path(setup_path) as tmpfile: - df.to_hdf(tmpfile, "df", complib="zlib") - result = pd.read_hdf(tmpfile, "df") - tm.assert_frame_equal(result, df) - - with tables.open_file(tmpfile, mode="r") as h5file: - for node in h5file.walk_nodes(where="/df", classname="Leaf"): - assert node.filters.complevel == 0 - assert node.filters.complib is None - - # Check if not setting complib or complevel results in no compression - with ensure_clean_path(setup_path) as tmpfile: - df.to_hdf(tmpfile, "df") - result = pd.read_hdf(tmpfile, "df") - tm.assert_frame_equal(result, df) - - with tables.open_file(tmpfile, mode="r") as h5file: - for node in h5file.walk_nodes(where="/df", classname="Leaf"): - assert node.filters.complevel == 0 - assert node.filters.complib is None - - # Check if file-defaults can be overridden on a per table basis - with ensure_clean_path(setup_path) as tmpfile: - store = HDFStore(tmpfile) - store.append("dfc", df, complevel=9, complib="blosc") - store.append("df", df) - store.close() - - with tables.open_file(tmpfile, mode="r") as h5file: - for node in h5file.walk_nodes(where="/df", classname="Leaf"): - assert node.filters.complevel == 0 - assert node.filters.complib is None - for node in h5file.walk_nodes(where="/dfc", classname="Leaf"): - assert node.filters.complevel == 9 - assert node.filters.complib == "blosc" - - def test_complibs(self, setup_path): - # GH14478 + ts = tm.makeTimeSeries() df = tm.makeDataFrame() + store["a"] = ts + store["b"] = df + _maybe_remove(store, "a") + assert len(store) == 1 + tm.assert_frame_equal(df, store["b"]) - # Building list of all complibs and complevels tuples - all_complibs = tables.filters.all_complibs - # Remove lzo if its not available on this platform - if not tables.which_lib_version("lzo"): - all_complibs.remove("lzo") - # Remove bzip2 if its not available on this platform - if not tables.which_lib_version("bzip2"): - all_complibs.remove("bzip2") - - all_levels = range(0, 10) - all_tests = [(lib, lvl) for lib in all_complibs for lvl in all_levels] - - for (lib, lvl) in all_tests: - with ensure_clean_path(setup_path) as tmpfile: - gname = "foo" - - # Write and read file to see if data is consistent - df.to_hdf(tmpfile, gname, complib=lib, complevel=lvl) - result = pd.read_hdf(tmpfile, gname) - tm.assert_frame_equal(result, df) - - # Open file and check metadata - # for correct amount of compression - h5table = tables.open_file(tmpfile, mode="r") - for node in h5table.walk_nodes(where="/" + gname, classname="Leaf"): - assert node.filters.complevel == lvl - if lvl == 0: - assert node.filters.complib is None - else: - assert node.filters.complib == lib - h5table.close() - - def test_put_integer(self, setup_path): - # non-date, non-string index - df = DataFrame(np.random.randn(50, 100)) - self._check_roundtrip(df, tm.assert_frame_equal, setup_path) - - def test_put_mixed_type(self, setup_path): - df = tm.makeTimeDataFrame() - df["obj1"] = "foo" - df["obj2"] = "bar" - df["bool1"] = df["A"] > 0 - df["bool2"] = df["B"] > 0 - df["bool3"] = True - df["int1"] = 1 - df["int2"] = 2 - df["timestamp1"] = Timestamp("20010102") - df["timestamp2"] = Timestamp("20010103") - df["datetime1"] = datetime.datetime(2001, 1, 2, 0, 0) - df["datetime2"] = datetime.datetime(2001, 1, 3, 0, 0) - df.loc[df.index[3:6], ["obj1"]] = np.nan - df = df._consolidate()._convert(datetime=True) - - with ensure_clean_store(setup_path) as store: - _maybe_remove(store, "df") - - # PerformanceWarning - with catch_warnings(record=True): - simplefilter("ignore", pd.errors.PerformanceWarning) - store.put("df", df) - - expected = store.get("df") - tm.assert_frame_equal(expected, df) + _maybe_remove(store, "b") + assert len(store) == 0 - @pytest.mark.filterwarnings( - "ignore:object name:tables.exceptions.NaturalNameWarning" - ) - def test_append(self, setup_path): + # nonexistence + with pytest.raises( + KeyError, match="'No object named a_nonexistent_store in the file'" + ): + store.remove("a_nonexistent_store") - with ensure_clean_store(setup_path) as store: + # pathing + store["a"] = ts + store["b/foo"] = df + _maybe_remove(store, "foo") + _maybe_remove(store, "b/foo") + assert len(store) == 1 - # this is allowed by almost always don't want to do it - # tables.NaturalNameWarning): - with catch_warnings(record=True): + store["a"] = ts + store["b/foo"] = df + _maybe_remove(store, "b") + assert len(store) == 1 - df = tm.makeTimeDataFrame() - _maybe_remove(store, "df1") - store.append("df1", df[:10]) - store.append("df1", df[10:]) - tm.assert_frame_equal(store["df1"], df) - - _maybe_remove(store, "df2") - store.put("df2", df[:10], format="table") - store.append("df2", df[10:]) - tm.assert_frame_equal(store["df2"], df) - - _maybe_remove(store, "df3") - store.append("/df3", df[:10]) - store.append("/df3", df[10:]) - tm.assert_frame_equal(store["df3"], df) - - # this is allowed by almost always don't want to do it - # tables.NaturalNameWarning - _maybe_remove(store, "/df3 foo") - store.append("/df3 foo", df[:10]) - store.append("/df3 foo", df[10:]) - tm.assert_frame_equal(store["df3 foo"], df) - - # dtype issues - mizxed type in a single object column - df = DataFrame(data=[[1, 2], [0, 1], [1, 2], [0, 0]]) - df["mixed_column"] = "testing" - df.loc[2, "mixed_column"] = np.nan - _maybe_remove(store, "df") - store.append("df", df) - tm.assert_frame_equal(store["df"], df) - - # uints - test storage of uints - uint_data = DataFrame( - { - "u08": Series( - np.random.randint(0, high=255, size=5), dtype=np.uint8 - ), - "u16": Series( - np.random.randint(0, high=65535, size=5), dtype=np.uint16 - ), - "u32": Series( - np.random.randint(0, high=2 ** 30, size=5), dtype=np.uint32 - ), - "u64": Series( - [2 ** 58, 2 ** 59, 2 ** 60, 2 ** 61, 2 ** 62], - dtype=np.uint64, - ), - }, - index=np.arange(5), - ) - _maybe_remove(store, "uints") - store.append("uints", uint_data) - tm.assert_frame_equal(store["uints"], uint_data) - - # uints - test storage of uints in indexable columns - _maybe_remove(store, "uints") - # 64-bit indices not yet supported - store.append("uints", uint_data, data_columns=["u08", "u16", "u32"]) - tm.assert_frame_equal(store["uints"], uint_data) - - def test_append_series(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - # basic - ss = tm.makeStringSeries() - ts = tm.makeTimeSeries() - ns = Series(np.arange(100)) - - store.append("ss", ss) - result = store["ss"] - tm.assert_series_equal(result, ss) - assert result.name is None - - store.append("ts", ts) - result = store["ts"] - tm.assert_series_equal(result, ts) - assert result.name is None - - ns.name = "foo" - store.append("ns", ns) - result = store["ns"] - tm.assert_series_equal(result, ns) - assert result.name == ns.name - - # select on the values - expected = ns[ns > 60] - result = store.select("ns", "foo>60") - tm.assert_series_equal(result, expected) - - # select on the index and values - expected = ns[(ns > 70) & (ns.index < 90)] - result = store.select("ns", "foo>70 and index<90") - tm.assert_series_equal(result, expected) - - # multi-index - mi = DataFrame(np.random.randn(5, 1), columns=["A"]) - mi["B"] = np.arange(len(mi)) - mi["C"] = "foo" - mi.loc[3:5, "C"] = "bar" - mi.set_index(["C", "B"], inplace=True) - s = mi.stack() - s.index = s.index.droplevel(2) - store.append("mi", s) - tm.assert_series_equal(store["mi"], s) - - def test_store_index_types(self, setup_path): - # GH5386 - # test storing various index types - - with ensure_clean_store(setup_path) as store: - - def check(format, index): - df = DataFrame(np.random.randn(10, 2), columns=list("AB")) - df.index = index(len(df)) - - _maybe_remove(store, "df") - store.put("df", df, format=format) - tm.assert_frame_equal(df, store["df"]) - - for index in [ - tm.makeFloatIndex, - tm.makeStringIndex, - tm.makeIntIndex, - tm.makeDateIndex, - ]: - - check("table", index) - check("fixed", index) - - # period index currently broken for table - # seee GH7796 FIXME - check("fixed", tm.makePeriodIndex) - # check('table',tm.makePeriodIndex) - - # unicode - index = tm.makeUnicodeIndex - check("table", index) - check("fixed", index) - - @pytest.mark.skipif( - not is_platform_little_endian(), reason="reason platform is not little endian" - ) - def test_encoding(self, setup_path): - - with ensure_clean_store(setup_path) as store: - df = DataFrame({"A": "foo", "B": "bar"}, index=range(5)) - df.loc[2, "A"] = np.nan - df.loc[3, "B"] = np.nan - _maybe_remove(store, "df") - store.append("df", df, encoding="ascii") - tm.assert_frame_equal(store["df"], df) - - expected = df.reindex(columns=["A"]) - result = store.select("df", Term("columns=A", encoding="ascii")) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "val", - [ - [b"E\xc9, 17", b"", b"a", b"b", b"c"], - [b"E\xc9, 17", b"a", b"b", b"c"], - [b"EE, 17", b"", b"a", b"b", b"c"], - [b"E\xc9, 17", b"\xf8\xfc", b"a", b"b", b"c"], - [b"", b"a", b"b", b"c"], - [b"\xf8\xfc", b"a", b"b", b"c"], - [b"A\xf8\xfc", b"", b"a", b"b", b"c"], - [np.nan, b"", b"b", b"c"], - [b"A\xf8\xfc", np.nan, b"", b"b", b"c"], - ], - ) - @pytest.mark.parametrize("dtype", ["category", object]) - def test_latin_encoding(self, setup_path, dtype, val): - enc = "latin-1" - nan_rep = "" - key = "data" - - val = [x.decode(enc) if isinstance(x, bytes) else x for x in val] - ser = Series(val, dtype=dtype) - - with ensure_clean_path(setup_path) as store: - ser.to_hdf(store, key, format="table", encoding=enc, nan_rep=nan_rep) - retr = read_hdf(store, key) - - s_nan = ser.replace(nan_rep, np.nan) - - tm.assert_series_equal(s_nan, retr) - - def test_append_some_nans(self, setup_path): - - with ensure_clean_store(setup_path) as store: - df = DataFrame( - { - "A": Series(np.random.randn(20)).astype("int32"), - "A1": np.random.randn(20), - "A2": np.random.randn(20), - "B": "foo", - "C": "bar", - "D": Timestamp("20010101"), - "E": datetime.datetime(2001, 1, 2, 0, 0), - }, - index=np.arange(20), - ) - # some nans - _maybe_remove(store, "df1") - df.loc[0:15, ["A1", "B", "D", "E"]] = np.nan - store.append("df1", df[:10]) - store.append("df1", df[10:]) - tm.assert_frame_equal(store["df1"], df) - - # first column - df1 = df.copy() - df1.loc[:, "A1"] = np.nan - _maybe_remove(store, "df1") - store.append("df1", df1[:10]) - store.append("df1", df1[10:]) - tm.assert_frame_equal(store["df1"], df1) - - # 2nd column - df2 = df.copy() - df2.loc[:, "A2"] = np.nan - _maybe_remove(store, "df2") - store.append("df2", df2[:10]) - store.append("df2", df2[10:]) - tm.assert_frame_equal(store["df2"], df2) - - # datetimes - df3 = df.copy() - df3.loc[:, "E"] = np.nan - _maybe_remove(store, "df3") - store.append("df3", df3[:10]) - store.append("df3", df3[10:]) - tm.assert_frame_equal(store["df3"], df3) - - def test_append_all_nans(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - df = DataFrame( - {"A1": np.random.randn(20), "A2": np.random.randn(20)}, - index=np.arange(20), - ) - df.loc[0:15, :] = np.nan - - # nan some entire rows (dropna=True) - _maybe_remove(store, "df") - store.append("df", df[:10], dropna=True) - store.append("df", df[10:], dropna=True) - tm.assert_frame_equal(store["df"], df[-4:]) - - # nan some entire rows (dropna=False) - _maybe_remove(store, "df2") - store.append("df2", df[:10], dropna=False) - store.append("df2", df[10:], dropna=False) - tm.assert_frame_equal(store["df2"], df) - - # tests the option io.hdf.dropna_table - pd.set_option("io.hdf.dropna_table", False) - _maybe_remove(store, "df3") - store.append("df3", df[:10]) - store.append("df3", df[10:]) - tm.assert_frame_equal(store["df3"], df) - - pd.set_option("io.hdf.dropna_table", True) - _maybe_remove(store, "df4") - store.append("df4", df[:10]) - store.append("df4", df[10:]) - tm.assert_frame_equal(store["df4"], df[-4:]) - - # nan some entire rows (string are still written!) - df = DataFrame( - { - "A1": np.random.randn(20), - "A2": np.random.randn(20), - "B": "foo", - "C": "bar", - }, - index=np.arange(20), - ) + # __delitem__ + store["a"] = ts + store["b"] = df + del store["a"] + del store["b"] + assert len(store) == 0 - df.loc[0:15, :] = np.nan - - _maybe_remove(store, "df") - store.append("df", df[:10], dropna=True) - store.append("df", df[10:], dropna=True) - tm.assert_frame_equal(store["df"], df) - - _maybe_remove(store, "df2") - store.append("df2", df[:10], dropna=False) - store.append("df2", df[10:], dropna=False) - tm.assert_frame_equal(store["df2"], df) - - # nan some entire rows (but since we have dates they are still - # written!) - df = DataFrame( - { - "A1": np.random.randn(20), - "A2": np.random.randn(20), - "B": "foo", - "C": "bar", - "D": Timestamp("20010101"), - "E": datetime.datetime(2001, 1, 2, 0, 0), - }, - index=np.arange(20), - ) - df.loc[0:15, :] = np.nan +def test_same_name_scoping(setup_path): - _maybe_remove(store, "df") - store.append("df", df[:10], dropna=True) - store.append("df", df[10:], dropna=True) - tm.assert_frame_equal(store["df"], df) + with ensure_clean_store(setup_path) as store: - _maybe_remove(store, "df2") - store.append("df2", df[:10], dropna=False) - store.append("df2", df[10:], dropna=False) - tm.assert_frame_equal(store["df2"], df) + import pandas as pd - def test_store_dropna(self, setup_path): - df_with_missing = DataFrame( - {"col1": [0.0, np.nan, 2.0], "col2": [1.0, np.nan, np.nan]}, - index=list("abc"), - ) - df_without_missing = DataFrame( - {"col1": [0.0, 2.0], "col2": [1.0, np.nan]}, index=list("ac") + df = DataFrame( + np.random.randn(20, 2), index=pd.date_range("20130101", periods=20) ) + store.put("df", df, format="table") + expected = df[df.index > Timestamp("20130105")] - # # Test to make sure defaults are to not drop. - # # Corresponding to Issue 9382 - with ensure_clean_path(setup_path) as path: - df_with_missing.to_hdf(path, "df", format="table") - reloaded = read_hdf(path, "df") - tm.assert_frame_equal(df_with_missing, reloaded) - - with ensure_clean_path(setup_path) as path: - df_with_missing.to_hdf(path, "df", format="table", dropna=False) - reloaded = read_hdf(path, "df") - tm.assert_frame_equal(df_with_missing, reloaded) - - with ensure_clean_path(setup_path) as path: - df_with_missing.to_hdf(path, "df", format="table", dropna=True) - reloaded = read_hdf(path, "df") - tm.assert_frame_equal(df_without_missing, reloaded) - - def test_read_missing_key_close_store(self, setup_path): - # GH 25766 - with ensure_clean_path(setup_path) as path: - df = DataFrame({"a": range(2), "b": range(2)}) - df.to_hdf(path, "k1") - - with pytest.raises(KeyError, match="'No object named k2 in the file'"): - pd.read_hdf(path, "k2") - - # smoke test to test that file is properly closed after - # read with KeyError before another write - df.to_hdf(path, "k2") - - def test_read_missing_key_opened_store(self, setup_path): - # GH 28699 - with ensure_clean_path(setup_path) as path: - df = DataFrame({"a": range(2), "b": range(2)}) - df.to_hdf(path, "k1") - - with HDFStore(path, "r") as store: + result = store.select("df", "index>datetime.datetime(2013,1,5)") + tm.assert_frame_equal(result, expected) - with pytest.raises(KeyError, match="'No object named k2 in the file'"): - pd.read_hdf(store, "k2") + from datetime import datetime # noqa - # Test that the file is still open after a KeyError and that we can - # still read from it. - pd.read_hdf(store, "k1") + # technically an error, but allow it + result = store.select("df", "index>datetime.datetime(2013,1,5)") + tm.assert_frame_equal(result, expected) - def test_append_frame_column_oriented(self, setup_path): - with ensure_clean_store(setup_path) as store: + result = store.select("df", "index>datetime(2013,1,5)") + tm.assert_frame_equal(result, expected) - # column oriented - df = tm.makeTimeDataFrame() - df.index = df.index._with_freq(None) # freq doesnt round-trip - - _maybe_remove(store, "df1") - store.append("df1", df.iloc[:, :2], axes=["columns"]) - store.append("df1", df.iloc[:, 2:]) - tm.assert_frame_equal(store["df1"], df) - - result = store.select("df1", "columns=A") - expected = df.reindex(columns=["A"]) - tm.assert_frame_equal(expected, result) - - # selection on the non-indexable - result = store.select("df1", ("columns=A", "index=df.index[0:4]")) - expected = df.reindex(columns=["A"], index=df.index[0:4]) - tm.assert_frame_equal(expected, result) - - # this isn't supported - msg = re.escape( - "passing a filterable condition to a non-table indexer " - "[Filter: Not Initialized]" - ) - with pytest.raises(TypeError, match=msg): - store.select("df1", "columns=A and index>df.index[4]") - def test_append_with_different_block_ordering(self, setup_path): +def test_store_index_name(setup_path): + df = tm.makeDataFrame() + df.index.name = "foo" - # GH 4096; using same frames, but different block orderings - with ensure_clean_store(setup_path) as store: + with ensure_clean_store(setup_path) as store: + store["frame"] = df + recons = store["frame"] + tm.assert_frame_equal(recons, df) - for i in range(10): - df = DataFrame(np.random.randn(10, 2), columns=list("AB")) - df["index"] = range(10) - df["index"] += i * 10 - df["int64"] = Series([1] * len(df), dtype="int64") - df["int16"] = Series([1] * len(df), dtype="int16") +@pytest.mark.parametrize("table_format", ["table", "fixed"]) +def test_store_index_name_numpy_str(table_format, setup_path): + # GH #13492 + idx = Index( + pd.to_datetime([datetime.date(2000, 1, 1), datetime.date(2000, 1, 2)]), + name="cols\u05d2", + ) + idx1 = Index( + pd.to_datetime([datetime.date(2010, 1, 1), datetime.date(2010, 1, 2)]), + name="rows\u05d0", + ) + df = DataFrame(np.arange(4).reshape(2, 2), columns=idx, index=idx1) - if i % 2 == 0: - del df["int64"] - df["int64"] = Series([1] * len(df), dtype="int64") - if i % 3 == 0: - a = df.pop("A") - df["A"] = a + # This used to fail, returning numpy strings instead of python strings. + with ensure_clean_path(setup_path) as path: + df.to_hdf(path, "df", format=table_format) + df2 = read_hdf(path, "df") - df.set_index("index", inplace=True) + tm.assert_frame_equal(df, df2, check_names=True) - store.append("df", df) + assert type(df2.index.name) == str + assert type(df2.columns.name) == str - # test a different ordering but with more fields (like invalid - # combinate) - with ensure_clean_store(setup_path) as store: - df = DataFrame(np.random.randn(10, 2), columns=list("AB"), dtype="float64") - df["int64"] = Series([1] * len(df), dtype="int64") - df["int16"] = Series([1] * len(df), dtype="int16") - store.append("df", df) +def test_store_series_name(setup_path): + df = tm.makeDataFrame() + series = df["A"] - # store additional fields in different blocks - df["int16_2"] = Series([1] * len(df), dtype="int16") - msg = re.escape( - "cannot match existing table structure for [int16] on appending data" - ) - with pytest.raises(ValueError, match=msg): - store.append("df", df) + with ensure_clean_store(setup_path) as store: + store["series"] = series + recons = store["series"] + tm.assert_series_equal(recons, series) - # store multiple additional fields in different blocks - df["float_3"] = Series([1.0] * len(df), dtype="float64") - msg = re.escape( - "cannot match existing table structure for [A,B] on appending data" - ) - with pytest.raises(ValueError, match=msg): - store.append("df", df) - def test_append_with_strings(self, setup_path): +@pytest.mark.filterwarnings("ignore:\\nduplicate:pandas.io.pytables.DuplicateWarning") +def test_overwrite_node(setup_path): - with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): + with ensure_clean_store(setup_path) as store: + store["a"] = tm.makeTimeDataFrame() + ts = tm.makeTimeSeries() + store["a"] = ts - def check_col(key, name, size): - assert ( - getattr(store.get_storer(key).table.description, name).itemsize - == size - ) - - # avoid truncation on elements - df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]]) - store.append("df_big", df) - tm.assert_frame_equal(store.select("df_big"), df) - check_col("df_big", "values_block_1", 15) - - # appending smaller string ok - df2 = DataFrame([[124, "asdqy"], [346, "dggnhefbdfb"]]) - store.append("df_big", df2) - expected = concat([df, df2]) - tm.assert_frame_equal(store.select("df_big"), expected) - check_col("df_big", "values_block_1", 15) - - # avoid truncation on elements - df = DataFrame([[123, "asdqwerty"], [345, "dggnhebbsdfbdfb"]]) - store.append("df_big2", df, min_itemsize={"values": 50}) - tm.assert_frame_equal(store.select("df_big2"), df) - check_col("df_big2", "values_block_1", 50) - - # bigger string on next append - store.append("df_new", df) - df_new = DataFrame( - [[124, "abcdefqhij"], [346, "abcdefghijklmnopqrtsuvwxyz"]] - ) - msg = ( - r"Trying to store a string with len \[26\] in " - r"\[values_block_1\] column but\n" - r"this column has a limit of \[15\]!\n" - "Consider using min_itemsize to preset the sizes on these " - "columns" - ) - with pytest.raises(ValueError, match=msg): - store.append("df_new", df_new) + tm.assert_series_equal(store["a"], ts) - # min_itemsize on Series index (GH 11412) - df = tm.makeMixedDataFrame().set_index("C") - store.append("ss", df["B"], min_itemsize={"index": 4}) - tm.assert_series_equal(store.select("ss"), df["B"]) - # same as above, with data_columns=True - store.append( - "ss2", df["B"], data_columns=True, min_itemsize={"index": 4} - ) - tm.assert_series_equal(store.select("ss2"), df["B"]) - - # min_itemsize in index without appending (GH 10381) - store.put("ss3", df, format="table", min_itemsize={"index": 6}) - # just make sure there is a longer string: - df2 = df.copy().reset_index().assign(C="longer").set_index("C") - store.append("ss3", df2) - tm.assert_frame_equal(store.select("ss3"), pd.concat([df, df2])) - - # same as above, with a Series - store.put("ss4", df["B"], format="table", min_itemsize={"index": 6}) - store.append("ss4", df2["B"]) - tm.assert_series_equal( - store.select("ss4"), pd.concat([df["B"], df2["B"]]) - ) +@pytest.mark.filterwarnings( + "ignore:\\nthe :pandas.io.pytables.AttributeConflictWarning" +) +def test_coordinates(setup_path): + df = tm.makeTimeDataFrame() + + with ensure_clean_store(setup_path) as store: + + _maybe_remove(store, "df") + store.append("df", df) + + # all + c = store.select_as_coordinates("df") + assert (c.values == np.arange(len(df.index))).all() + + # get coordinates back & test vs frame + _maybe_remove(store, "df") + + df = DataFrame({"A": range(5), "B": range(5)}) + store.append("df", df) + c = store.select_as_coordinates("df", ["index<3"]) + assert (c.values == np.arange(3)).all() + result = store.select("df", where=c) + expected = df.loc[0:2, :] + tm.assert_frame_equal(result, expected) + + c = store.select_as_coordinates("df", ["index>=3", "index<=4"]) + assert (c.values == np.arange(2) + 3).all() + result = store.select("df", where=c) + expected = df.loc[3:4, :] + tm.assert_frame_equal(result, expected) + assert isinstance(c, Index) + + # multiple tables + _maybe_remove(store, "df1") + _maybe_remove(store, "df2") + df1 = tm.makeTimeDataFrame() + df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) + store.append("df1", df1, data_columns=["A", "B"]) + store.append("df2", df2) - # with nans - _maybe_remove(store, "df") - df = tm.makeTimeDataFrame() - df["string"] = "foo" - df.loc[df.index[1:4], "string"] = np.nan - df["string2"] = "bar" - df.loc[df.index[4:8], "string2"] = np.nan - df["string3"] = "bah" - df.loc[df.index[1:], "string3"] = np.nan - store.append("df", df) - result = store.select("df") - tm.assert_frame_equal(result, df) - - with ensure_clean_store(setup_path) as store: - - def check_col(key, name, size): - assert getattr( - store.get_storer(key).table.description, name - ).itemsize, size - - df = DataFrame({"A": "foo", "B": "bar"}, index=range(10)) - - # a min_itemsize that creates a data_column - _maybe_remove(store, "df") - store.append("df", df, min_itemsize={"A": 200}) - check_col("df", "A", 200) - assert store.get_storer("df").data_columns == ["A"] - - # a min_itemsize that creates a data_column2 - _maybe_remove(store, "df") - store.append("df", df, data_columns=["B"], min_itemsize={"A": 200}) - check_col("df", "A", 200) - assert store.get_storer("df").data_columns == ["B", "A"] - - # a min_itemsize that creates a data_column2 - _maybe_remove(store, "df") - store.append("df", df, data_columns=["B"], min_itemsize={"values": 200}) - check_col("df", "B", 200) - check_col("df", "values_block_0", 200) - assert store.get_storer("df").data_columns == ["B"] - - # infer the .typ on subsequent appends - _maybe_remove(store, "df") - store.append("df", df[:5], min_itemsize=200) - store.append("df", df[5:], min_itemsize=200) - tm.assert_frame_equal(store["df"], df) - - # invalid min_itemsize keys - df = DataFrame(["foo", "foo", "foo", "barh", "barh", "barh"], columns=["A"]) - _maybe_remove(store, "df") - msg = re.escape( - "min_itemsize has the key [foo] which is not an axis or data_column" - ) - with pytest.raises(ValueError, match=msg): - store.append("df", df, min_itemsize={"foo": 20, "foobar": 20}) + c = store.select_as_coordinates("df1", ["A>0", "B>0"]) + df1_result = store.select("df1", c) + df2_result = store.select("df2", c) + result = concat([df1_result, df2_result], axis=1) - def test_append_with_empty_string(self, setup_path): + expected = concat([df1, df2], axis=1) + expected = expected[(expected.A > 0) & (expected.B > 0)] + tm.assert_frame_equal(result, expected) - with ensure_clean_store(setup_path) as store: + # pass array/mask as the coordinates + with ensure_clean_store(setup_path) as store: - # with all empty strings (GH 12242) - df = DataFrame({"x": ["a", "b", "c", "d", "e", "f", ""]}) - store.append("df", df[:-1], min_itemsize={"x": 1}) - store.append("df", df[-1:], min_itemsize={"x": 1}) - tm.assert_frame_equal(store.select("df"), df) + df = DataFrame( + np.random.randn(1000, 2), index=date_range("20000101", periods=1000) + ) + store.append("df", df) + c = store.select_column("df", "index") + where = c[DatetimeIndex(c).month == 5].index + expected = df.iloc[where] - def test_to_hdf_with_min_itemsize(self, setup_path): + # locations + result = store.select("df", where=where) + tm.assert_frame_equal(result, expected) - with ensure_clean_path(setup_path) as path: + # boolean + result = store.select("df", where=where) + tm.assert_frame_equal(result, expected) - # min_itemsize in index with to_hdf (GH 10381) - df = tm.makeMixedDataFrame().set_index("C") - df.to_hdf(path, "ss3", format="table", min_itemsize={"index": 6}) - # just make sure there is a longer string: - df2 = df.copy().reset_index().assign(C="longer").set_index("C") - df2.to_hdf(path, "ss3", append=True, format="table") - tm.assert_frame_equal(pd.read_hdf(path, "ss3"), pd.concat([df, df2])) - - # same as above, with a Series - df["B"].to_hdf(path, "ss4", format="table", min_itemsize={"index": 6}) - df2["B"].to_hdf(path, "ss4", append=True, format="table") - tm.assert_series_equal( - pd.read_hdf(path, "ss4"), pd.concat([df["B"], df2["B"]]) - ) + # invalid + msg = "cannot process expression" + with pytest.raises(ValueError, match=msg): + store.select("df", where=np.arange(len(df), dtype="float64")) - @pytest.mark.parametrize("format", ["fixed", "table"]) - def test_to_hdf_errors(self, format, setup_path): + with pytest.raises(ValueError, match=msg): + store.select("df", where=np.arange(len(df) + 1)) - data = ["\ud800foo"] - ser = Series(data, index=Index(data)) - with ensure_clean_path(setup_path) as path: - # GH 20835 - ser.to_hdf(path, "table", format=format, errors="surrogatepass") + with pytest.raises(ValueError, match=msg): + store.select("df", where=np.arange(len(df)), start=5) - result = pd.read_hdf(path, "table", errors="surrogatepass") - tm.assert_series_equal(result, ser) + with pytest.raises(ValueError, match=msg): + store.select("df", where=np.arange(len(df)), start=5, stop=10) - def test_append_with_data_columns(self, setup_path): + # selection with filter + selection = date_range("20000101", periods=500) + result = store.select("df", where="index in selection") + expected = df[df.index.isin(selection)] + tm.assert_frame_equal(result, expected) - with ensure_clean_store(setup_path) as store: - df = tm.makeTimeDataFrame() - df.iloc[0, df.columns.get_loc("B")] = 1.0 - _maybe_remove(store, "df") - store.append("df", df[:2], data_columns=["B"]) - store.append("df", df[2:]) - tm.assert_frame_equal(store["df"], df) - - # check that we have indices created - assert store._handle.root.df.table.cols.index.is_indexed is True - assert store._handle.root.df.table.cols.B.is_indexed is True - - # data column searching - result = store.select("df", "B>0") - expected = df[df.B > 0] - tm.assert_frame_equal(result, expected) - - # data column searching (with an indexable and a data_columns) - result = store.select("df", "B>0 and index>df.index[3]") - df_new = df.reindex(index=df.index[4:]) - expected = df_new[df_new.B > 0] - tm.assert_frame_equal(result, expected) - - # data column selection with a string data_column - df_new = df.copy() - df_new["string"] = "foo" - df_new.loc[df_new.index[1:4], "string"] = np.nan - df_new.loc[df_new.index[5:6], "string"] = "bar" - _maybe_remove(store, "df") - store.append("df", df_new, data_columns=["string"]) - result = store.select("df", "string='foo'") - expected = df_new[df_new.string == "foo"] - tm.assert_frame_equal(result, expected) - - # using min_itemsize and a data column - def check_col(key, name, size): - assert ( - getattr(store.get_storer(key).table.description, name).itemsize - == size - ) + # list + df = DataFrame(np.random.randn(10, 2)) + store.append("df2", df) + result = store.select("df2", where=[0, 3, 5]) + expected = df.iloc[[0, 3, 5]] + tm.assert_frame_equal(result, expected) - with ensure_clean_store(setup_path) as store: - _maybe_remove(store, "df") - store.append( - "df", df_new, data_columns=["string"], min_itemsize={"string": 30} - ) - check_col("df", "string", 30) - _maybe_remove(store, "df") - store.append("df", df_new, data_columns=["string"], min_itemsize=30) - check_col("df", "string", 30) - _maybe_remove(store, "df") - store.append( - "df", df_new, data_columns=["string"], min_itemsize={"values": 30} - ) - check_col("df", "string", 30) - - with ensure_clean_store(setup_path) as store: - df_new["string2"] = "foobarbah" - df_new["string_block1"] = "foobarbah1" - df_new["string_block2"] = "foobarbah2" - _maybe_remove(store, "df") - store.append( - "df", - df_new, - data_columns=["string", "string2"], - min_itemsize={"string": 30, "string2": 40, "values": 50}, - ) - check_col("df", "string", 30) - check_col("df", "string2", 40) - check_col("df", "values_block_1", 50) - - with ensure_clean_store(setup_path) as store: - # multiple data columns - df_new = df.copy() - df_new.iloc[0, df_new.columns.get_loc("A")] = 1.0 - df_new.iloc[0, df_new.columns.get_loc("B")] = -1.0 - df_new["string"] = "foo" - - sl = df_new.columns.get_loc("string") - df_new.iloc[1:4, sl] = np.nan - df_new.iloc[5:6, sl] = "bar" - - df_new["string2"] = "foo" - sl = df_new.columns.get_loc("string2") - df_new.iloc[2:5, sl] = np.nan - df_new.iloc[7:8, sl] = "bar" - _maybe_remove(store, "df") - store.append("df", df_new, data_columns=["A", "B", "string", "string2"]) - result = store.select( - "df", "string='foo' and string2='foo' and A>0 and B<0" - ) - expected = df_new[ - (df_new.string == "foo") - & (df_new.string2 == "foo") - & (df_new.A > 0) - & (df_new.B < 0) - ] - tm.assert_frame_equal(result, expected, check_freq=False) - # FIXME: 2020-05-07 freq check randomly fails in the CI - - # yield an empty frame - result = store.select("df", "string='foo' and string2='cool'") - expected = df_new[(df_new.string == "foo") & (df_new.string2 == "cool")] - tm.assert_frame_equal(result, expected) - - with ensure_clean_store(setup_path) as store: - # doc example - df_dc = df.copy() - df_dc["string"] = "foo" - df_dc.loc[df_dc.index[4:6], "string"] = np.nan - df_dc.loc[df_dc.index[7:9], "string"] = "bar" - df_dc["string2"] = "cool" - df_dc["datetime"] = Timestamp("20010102") - df_dc = df_dc._convert(datetime=True) - df_dc.loc[df_dc.index[3:5], ["A", "B", "datetime"]] = np.nan - - _maybe_remove(store, "df_dc") - store.append( - "df_dc", df_dc, data_columns=["B", "C", "string", "string2", "datetime"] - ) - result = store.select("df_dc", "B>0") - - expected = df_dc[df_dc.B > 0] - tm.assert_frame_equal(result, expected) - - result = store.select("df_dc", ["B > 0", "C > 0", "string == foo"]) - expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == "foo")] - tm.assert_frame_equal(result, expected, check_freq=False) - # FIXME: 2020-12-07 intermittent build failures here with freq of - # None instead of BDay(4) - - with ensure_clean_store(setup_path) as store: - # doc example part 2 - np.random.seed(1234) - index = date_range("1/1/2000", periods=8) - df_dc = DataFrame( - np.random.randn(8, 3), index=index, columns=["A", "B", "C"] - ) - df_dc["string"] = "foo" - df_dc.loc[df_dc.index[4:6], "string"] = np.nan - df_dc.loc[df_dc.index[7:9], "string"] = "bar" - df_dc.loc[:, ["B", "C"]] = df_dc.loc[:, ["B", "C"]].abs() - df_dc["string2"] = "cool" + # boolean + where = [True] * 10 + where[-2] = False + result = store.select("df2", where=where) + expected = df.loc[where] + tm.assert_frame_equal(result, expected) - # on-disk operations - store.append("df_dc", df_dc, data_columns=["B", "C", "string", "string2"]) + # start/stop + result = store.select("df2", start=5, stop=10) + expected = df[5:10] + tm.assert_frame_equal(result, expected) - result = store.select("df_dc", "B>0") - expected = df_dc[df_dc.B > 0] - tm.assert_frame_equal(result, expected) - result = store.select("df_dc", ["B > 0", "C > 0", 'string == "foo"']) - expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == "foo")] - tm.assert_frame_equal(result, expected) +def test_start_stop_table(setup_path): - def test_create_table_index(self, setup_path): + with ensure_clean_store(setup_path) as store: - with ensure_clean_store(setup_path) as store: + # table + df = DataFrame({"A": np.random.rand(20), "B": np.random.rand(20)}) + store.append("df", df) - with catch_warnings(record=True): + result = store.select("df", "columns=['A']", start=0, stop=5) + expected = df.loc[0:4, ["A"]] + tm.assert_frame_equal(result, expected) - def col(t, column): - return getattr(store.get_storer(t).table.cols, column) - - # data columns - df = tm.makeTimeDataFrame() - df["string"] = "foo" - df["string2"] = "bar" - store.append("f", df, data_columns=["string", "string2"]) - assert col("f", "index").is_indexed is True - assert col("f", "string").is_indexed is True - assert col("f", "string2").is_indexed is True - - # specify index=columns - store.append( - "f2", df, index=["string"], data_columns=["string", "string2"] - ) - assert col("f2", "index").is_indexed is False - assert col("f2", "string").is_indexed is True - assert col("f2", "string2").is_indexed is False + # out of range + result = store.select("df", "columns=['A']", start=30, stop=40) + assert len(result) == 0 + expected = df.loc[30:40, ["A"]] + tm.assert_frame_equal(result, expected) - # try to index a non-table - _maybe_remove(store, "f2") - store.put("f2", df) - msg = "cannot create table index on a Fixed format store" - with pytest.raises(TypeError, match=msg): - store.create_table_index("f2") - def test_create_table_index_data_columns_argument(self, setup_path): - # GH 28156 +def test_start_stop_multiple(setup_path): - with ensure_clean_store(setup_path) as store: + # GH 16209 + with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): + df = DataFrame({"foo": [1, 2], "bar": [1, 2]}) - def col(t, column): - return getattr(store.get_storer(t).table.cols, column) - - # data columns - df = tm.makeTimeDataFrame() - df["string"] = "foo" - df["string2"] = "bar" - store.append("f", df, data_columns=["string"]) - assert col("f", "index").is_indexed is True - assert col("f", "string").is_indexed is True - - msg = "'Cols' object has no attribute 'string2'" - with pytest.raises(AttributeError, match=msg): - col("f", "string2").is_indexed - - # try to index a col which isn't a data_column - msg = ( - "column string2 is not a data_column.\n" - "In order to read column string2 you must reload the dataframe \n" - "into HDFStore and include string2 with the data_columns argument." - ) - with pytest.raises(AttributeError, match=msg): - store.create_table_index("f", columns=["string2"]) - - def test_append_hierarchical(self, setup_path): - index = MultiIndex( - levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], - codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], - names=["foo", "bar"], + store.append_to_multiple( + {"selector": ["foo"], "data": None}, df, selector="selector" ) - df = DataFrame(np.random.randn(10, 3), index=index, columns=["A", "B", "C"]) - - with ensure_clean_store(setup_path) as store: - store.append("mi", df) - result = store.select("mi") - tm.assert_frame_equal(result, df) - - # GH 3748 - result = store.select("mi", columns=["A", "B"]) - expected = df.reindex(columns=["A", "B"]) - tm.assert_frame_equal(result, expected) - - with ensure_clean_path("test.hdf") as path: - df.to_hdf(path, "df", format="table") - result = read_hdf(path, "df", columns=["A", "B"]) - expected = df.reindex(columns=["A", "B"]) - tm.assert_frame_equal(result, expected) - - def test_column_multiindex(self, setup_path): - # GH 4710 - # recreate multi-indexes properly - - index = MultiIndex.from_tuples( - [("A", "a"), ("A", "b"), ("B", "a"), ("B", "b")], names=["first", "second"] + result = store.select_as_multiple( + ["selector", "data"], selector="selector", start=0, stop=1 ) - df = DataFrame(np.arange(12).reshape(3, 4), columns=index) - expected = df.copy() - if isinstance(expected.index, RangeIndex): - expected.index = Int64Index(expected.index) - - with ensure_clean_store(setup_path) as store: - - store.put("df", df) - tm.assert_frame_equal( - store["df"], expected, check_index_type=True, check_column_type=True - ) - - store.put("df1", df, format="table") - tm.assert_frame_equal( - store["df1"], expected, check_index_type=True, check_column_type=True - ) + expected = df.loc[[0], ["foo", "bar"]] + tm.assert_frame_equal(result, expected) - msg = re.escape( - "cannot use a multi-index on axis [1] with data_columns ['A']" - ) - with pytest.raises(ValueError, match=msg): - store.put("df2", df, format="table", data_columns=["A"]) - msg = re.escape( - "cannot use a multi-index on axis [1] with data_columns True" - ) - with pytest.raises(ValueError, match=msg): - store.put("df3", df, format="table", data_columns=True) - # appending multi-column on existing table (see GH 6167) - with ensure_clean_store(setup_path) as store: - store.append("df2", df) - store.append("df2", df) +def test_start_stop_fixed(setup_path): - tm.assert_frame_equal(store["df2"], concat((df, df))) + with ensure_clean_store(setup_path) as store: - # non_index_axes name + # fixed, GH 8287 df = DataFrame( - np.arange(12).reshape(3, 4), columns=Index(list("ABCD"), name="foo") + {"A": np.random.rand(20), "B": np.random.rand(20)}, + index=pd.date_range("20130101", periods=20), ) - expected = df.copy() - if isinstance(expected.index, RangeIndex): - expected.index = Int64Index(expected.index) + store.put("df", df) - with ensure_clean_store(setup_path) as store: + result = store.select("df", start=0, stop=5) + expected = df.iloc[0:5, :] + tm.assert_frame_equal(result, expected) - store.put("df1", df, format="table") - tm.assert_frame_equal( - store["df1"], expected, check_index_type=True, check_column_type=True - ) + result = store.select("df", start=5, stop=10) + expected = df.iloc[5:10, :] + tm.assert_frame_equal(result, expected) - def test_store_multiindex(self, setup_path): - - # validate multi-index names - # GH 5527 - with ensure_clean_store(setup_path) as store: - - def make_index(names=None): - return MultiIndex.from_tuples( - [ - (datetime.datetime(2013, 12, d), s, t) - for d in range(1, 3) - for s in range(2) - for t in range(3) - ], - names=names, - ) + # out of range + result = store.select("df", start=30, stop=40) + expected = df.iloc[30:40, :] + tm.assert_frame_equal(result, expected) - # no names - _maybe_remove(store, "df") - df = DataFrame(np.zeros((12, 2)), columns=["a", "b"], index=make_index()) - store.append("df", df) - tm.assert_frame_equal(store.select("df"), df) - - # partial names - _maybe_remove(store, "df") - df = DataFrame( - np.zeros((12, 2)), - columns=["a", "b"], - index=make_index(["date", None, None]), - ) - store.append("df", df) - tm.assert_frame_equal(store.select("df"), df) - - # series - _maybe_remove(store, "s") - s = Series(np.zeros(12), index=make_index(["date", None, None])) - store.append("s", s) - xp = Series(np.zeros(12), index=make_index(["date", "level_1", "level_2"])) - tm.assert_series_equal(store.select("s"), xp) - - # dup with column - _maybe_remove(store, "df") - df = DataFrame( - np.zeros((12, 2)), - columns=["a", "b"], - index=make_index(["date", "a", "t"]), - ) - msg = "duplicate names/columns in the multi-index when storing as a table" - with pytest.raises(ValueError, match=msg): - store.append("df", df) - - # dup within level - _maybe_remove(store, "df") - df = DataFrame( - np.zeros((12, 2)), - columns=["a", "b"], - index=make_index(["date", "date", "date"]), - ) - with pytest.raises(ValueError, match=msg): - store.append("df", df) - - # fully names - _maybe_remove(store, "df") - df = DataFrame( - np.zeros((12, 2)), - columns=["a", "b"], - index=make_index(["date", "s", "t"]), - ) - store.append("df", df) - tm.assert_frame_equal(store.select("df"), df) - - def test_select_columns_in_where(self, setup_path): - - # GH 6169 - # recreate multi-indexes when columns is passed - # in the `where` argument - index = MultiIndex( - levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], - codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], - names=["foo_name", "bar_name"], - ) + # series + s = df.A + store.put("s", s) + result = store.select("s", start=0, stop=5) + expected = s.iloc[0:5] + tm.assert_series_equal(result, expected) - # With a DataFrame - df = DataFrame(np.random.randn(10, 3), index=index, columns=["A", "B", "C"]) + result = store.select("s", start=5, stop=10) + expected = s.iloc[5:10] + tm.assert_series_equal(result, expected) - with ensure_clean_store(setup_path) as store: - store.put("df", df, format="table") - expected = df[["A"]] + # sparse; not implemented + df = tm.makeDataFrame() + df.iloc[3:5, 1:3] = np.nan + df.iloc[8:10, -2] = np.nan - tm.assert_frame_equal(store.select("df", columns=["A"]), expected) - tm.assert_frame_equal(store.select("df", where="columns=['A']"), expected) +def test_select_filter_corner(setup_path): - # With a Series - s = Series(np.random.randn(10), index=index, name="A") - with ensure_clean_store(setup_path) as store: - store.put("s", s, format="table") - tm.assert_series_equal(store.select("s", where="columns=['A']"), s) + df = DataFrame(np.random.randn(50, 100)) + df.index = [f"{c:3d}" for c in df.index] + df.columns = [f"{c:3d}" for c in df.columns] - def test_mi_data_columns(self, setup_path): - # GH 14435 - idx = MultiIndex.from_arrays( - [date_range("2000-01-01", periods=5), range(5)], names=["date", "id"] - ) - df = DataFrame({"a": [1.1, 1.2, 1.3, 1.4, 1.5]}, index=idx) + with ensure_clean_store(setup_path) as store: + store.put("frame", df, format="table") - with ensure_clean_store(setup_path) as store: - store.append("df", df, data_columns=True) + crit = "columns=df.columns[:75]" + result = store.select("frame", [crit]) + tm.assert_frame_equal(result, df.loc[:, df.columns[:75]]) - actual = store.select("df", where="id == 1") - expected = df.iloc[[1], :] - tm.assert_frame_equal(actual, expected) + crit = "columns=df.columns[:75:2]" + result = store.select("frame", [crit]) + tm.assert_frame_equal(result, df.loc[:, df.columns[:75:2]]) - def test_pass_spec_to_storer(self, setup_path): - df = tm.makeDataFrame() +def test_path_pathlib(setup_path): + df = tm.makeDataFrame() - with ensure_clean_store(setup_path) as store: - store.put("df", df) - msg = ( - "cannot pass a column specification when reading a Fixed format " - "store. this store must be selected in its entirety" - ) - with pytest.raises(TypeError, match=msg): - store.select("df", columns=["A"]) - msg = ( - "cannot pass a where specification when reading from a Fixed " - "format store. this store must be selected in its entirety" - ) - with pytest.raises(TypeError, match=msg): - store.select("df", where=[("columns=A")]) + result = tm.round_trip_pathlib( + lambda p: df.to_hdf(p, "df"), lambda p: pd.read_hdf(p, "df") + ) + tm.assert_frame_equal(df, result) - def test_append_misc(self, setup_path): - with ensure_clean_store(setup_path) as store: - df = tm.makeDataFrame() - store.append("df", df, chunksize=1) - result = store.select("df") - tm.assert_frame_equal(result, df) +@pytest.mark.parametrize("start, stop", [(0, 2), (1, 2), (None, None)]) +def test_contiguous_mixed_data_table(start, stop, setup_path): + # GH 17021 + df = DataFrame( + { + "a": Series([20111010, 20111011, 20111012]), + "b": Series(["ab", "cd", "ab"]), + } + ) - store.append("df1", df, expectedrows=10) - result = store.select("df1") - tm.assert_frame_equal(result, df) + with ensure_clean_store(setup_path) as store: + store.append("test_dataset", df) - # more chunksize in append tests - def check(obj, comparator): - for c in [10, 200, 1000]: - with ensure_clean_store(setup_path, mode="w") as store: - store.append("obj", obj, chunksize=c) - result = store.select("obj") - comparator(result, obj) + result = store.select("test_dataset", start=start, stop=stop) + tm.assert_frame_equal(df[start:stop], result) - df = tm.makeDataFrame() - df["string"] = "foo" - df["float322"] = 1.0 - df["float322"] = df["float322"].astype("float32") - df["bool"] = df["float322"] > 0 - df["time1"] = Timestamp("20130101") - df["time2"] = Timestamp("20130102") - check(df, tm.assert_frame_equal) - - # empty frame, GH4273 - with ensure_clean_store(setup_path) as store: - - # 0 len - df_empty = DataFrame(columns=list("ABC")) - store.append("df", df_empty) - with pytest.raises(KeyError, match="'No object named df in the file'"): - store.select("df") - - # repeated append of 0/non-zero frames - df = DataFrame(np.random.rand(10, 3), columns=list("ABC")) - store.append("df", df) - tm.assert_frame_equal(store.select("df"), df) - store.append("df", df_empty) - tm.assert_frame_equal(store.select("df"), df) - - # store - df = DataFrame(columns=list("ABC")) - store.put("df2", df) - tm.assert_frame_equal(store.select("df2"), df) - - def test_append_raise(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - # test append with invalid input to get good error messages - - # list in column - df = tm.makeDataFrame() - df["invalid"] = [["a"]] * len(df) - assert df.dtypes["invalid"] == np.object_ - msg = re.escape( - """Cannot serialize the column [invalid] -because its data contents are not [string] but [mixed] object dtype""" - ) - with pytest.raises(TypeError, match=msg): - store.append("df", df) - # multiple invalid columns - df["invalid2"] = [["a"]] * len(df) - df["invalid3"] = [["a"]] * len(df) - with pytest.raises(TypeError, match=msg): - store.append("df", df) - - # datetime with embedded nans as object - df = tm.makeDataFrame() - s = Series(datetime.datetime(2001, 1, 2), index=df.index) - s = s.astype(object) - s[0:5] = np.nan - df["invalid"] = s - assert df.dtypes["invalid"] == np.object_ - msg = "too many timezones in this block, create separate data columns" - with pytest.raises(TypeError, match=msg): - store.append("df", df) +def test_path_pathlib_hdfstore(setup_path): + df = tm.makeDataFrame() - # directly ndarray - msg = "value must be None, Series, or DataFrame" - with pytest.raises(TypeError, match=msg): - store.append("df", np.arange(10)) + def writer(path): + with HDFStore(path) as store: + df.to_hdf(store, "df") - # series directly - msg = re.escape( - "cannot properly create the storer for: " - "[group->df,value-><class 'pandas.core.series.Series'>]" - ) - with pytest.raises(TypeError, match=msg): - store.append("df", Series(np.arange(10))) + def reader(path): + with HDFStore(path) as store: + return pd.read_hdf(store, "df") - # appending an incompatible table - df = tm.makeDataFrame() - store.append("df", df) + result = tm.round_trip_pathlib(writer, reader) + tm.assert_frame_equal(df, result) - df["foo"] = "foo" - msg = re.escape( - "invalid combination of [non_index_axes] on appending data " - "[(1, ['A', 'B', 'C', 'D', 'foo'])] vs current table " - "[(1, ['A', 'B', 'C', 'D'])]" - ) - with pytest.raises(ValueError, match=msg): - store.append("df", df) - def test_table_index_incompatible_dtypes(self, setup_path): - df1 = DataFrame({"a": [1, 2, 3]}) - df2 = DataFrame({"a": [4, 5, 6]}, index=date_range("1/1/2000", periods=3)) +def test_pickle_path_localpath(setup_path): + df = tm.makeDataFrame() + result = tm.round_trip_pathlib( + lambda p: df.to_hdf(p, "df"), lambda p: pd.read_hdf(p, "df") + ) + tm.assert_frame_equal(df, result) - with ensure_clean_store(setup_path) as store: - store.put("frame", df1, format="table") - msg = re.escape("incompatible kind in col [integer - datetime64]") - with pytest.raises(TypeError, match=msg): - store.put("frame", df2, format="table", append=True) - - def test_table_values_dtypes_roundtrip(self, setup_path): - - with ensure_clean_store(setup_path) as store: - df1 = DataFrame({"a": [1, 2, 3]}, dtype="f8") - store.append("df_f8", df1) - tm.assert_series_equal(df1.dtypes, store["df_f8"].dtypes) - - df2 = DataFrame({"a": [1, 2, 3]}, dtype="i8") - store.append("df_i8", df2) - tm.assert_series_equal(df2.dtypes, store["df_i8"].dtypes) - - # incompatible dtype - msg = re.escape( - "invalid combination of [values_axes] on appending data " - "[name->values_block_0,cname->values_block_0," - "dtype->float64,kind->float,shape->(1, 3)] vs " - "current table [name->values_block_0," - "cname->values_block_0,dtype->int64,kind->integer," - "shape->None]" - ) - with pytest.raises(ValueError, match=msg): - store.append("df_i8", df1) - - # check creation/storage/retrieval of float32 (a bit hacky to - # actually create them thought) - df1 = DataFrame(np.array([[1], [2], [3]], dtype="f4"), columns=["A"]) - store.append("df_f4", df1) - tm.assert_series_equal(df1.dtypes, store["df_f4"].dtypes) - assert df1.dtypes[0] == "float32" - - # check with mixed dtypes - df1 = DataFrame( - { - c: Series(np.random.randint(5), dtype=c) - for c in ["float32", "float64", "int32", "int64", "int16", "int8"] - } - ) - df1["string"] = "foo" - df1["float322"] = 1.0 - df1["float322"] = df1["float322"].astype("float32") - df1["bool"] = df1["float32"] > 0 - df1["time1"] = Timestamp("20130101") - df1["time2"] = Timestamp("20130102") - - store.append("df_mixed_dtypes1", df1) - result = store.select("df_mixed_dtypes1").dtypes.value_counts() - result.index = [str(i) for i in result.index] - expected = Series( - { - "float32": 2, - "float64": 1, - "int32": 1, - "bool": 1, - "int16": 1, - "int8": 1, - "int64": 1, - "object": 1, - "datetime64[ns]": 2, - } - ) - result = result.sort_index() - expected = expected.sort_index() - tm.assert_series_equal(result, expected) - def test_table_mixed_dtypes(self, setup_path): +def test_path_localpath_hdfstore(setup_path): + df = tm.makeDataFrame() - # frame - df = tm.makeDataFrame() - df["obj1"] = "foo" - df["obj2"] = "bar" - df["bool1"] = df["A"] > 0 - df["bool2"] = df["B"] > 0 - df["bool3"] = True - df["int1"] = 1 - df["int2"] = 2 - df["timestamp1"] = Timestamp("20010102") - df["timestamp2"] = Timestamp("20010103") - df["datetime1"] = datetime.datetime(2001, 1, 2, 0, 0) - df["datetime2"] = datetime.datetime(2001, 1, 3, 0, 0) - df.loc[df.index[3:6], ["obj1"]] = np.nan - df = df._consolidate()._convert(datetime=True) + def writer(path): + with HDFStore(path) as store: + df.to_hdf(store, "df") - with ensure_clean_store(setup_path) as store: - store.append("df1_mixed", df) - tm.assert_frame_equal(store.select("df1_mixed"), df) + def reader(path): + with HDFStore(path) as store: + return pd.read_hdf(store, "df") - def test_unimplemented_dtypes_table_columns(self, setup_path): + result = tm.round_trip_localpath(writer, reader) + tm.assert_frame_equal(df, result) - with ensure_clean_store(setup_path) as store: - dtypes = [("date", datetime.date(2001, 1, 2))] +def test_copy(setup_path): - # currently not supported dtypes #### - for n, f in dtypes: - df = tm.makeDataFrame() - df[n] = f - msg = re.escape(f"[{n}] is not implemented as a table column") - with pytest.raises(TypeError, match=msg): - store.append(f"df1_{n}", df) + with catch_warnings(record=True): - # frame - df = tm.makeDataFrame() - df["obj1"] = "foo" - df["obj2"] = "bar" - df["datetime1"] = datetime.date(2001, 1, 2) - df = df._consolidate()._convert(datetime=True) + def do_copy(f, new_f=None, keys=None, propindexes=True, **kwargs): + try: + store = HDFStore(f, "r") - with ensure_clean_store(setup_path) as store: - # this fails because we have a date in the object block...... - msg = re.escape( - """Cannot serialize the column [datetime1] -because its data contents are not [string] but [date] object dtype""" - ) - with pytest.raises(TypeError, match=msg): - store.append("df_unimplemented", df) - - def test_calendar_roundtrip_issue(self, setup_path): - - # 8591 - # doc example from tseries holiday section - weekmask_egypt = "Sun Mon Tue Wed Thu" - holidays = [ - "2012-05-01", - datetime.datetime(2013, 5, 1), - np.datetime64("2014-05-01"), - ] - bday_egypt = pd.offsets.CustomBusinessDay( - holidays=holidays, weekmask=weekmask_egypt - ) - dt = datetime.datetime(2013, 4, 30) - dts = date_range(dt, periods=5, freq=bday_egypt) + if new_f is None: + import tempfile - s = Series(dts.weekday, dts).map(Series("Mon Tue Wed Thu Fri Sat Sun".split())) + fd, new_f = tempfile.mkstemp() + tstore = store.copy(new_f, keys=keys, propindexes=propindexes, **kwargs) - with ensure_clean_store(setup_path) as store: + # check keys + if keys is None: + keys = store.keys() + assert set(keys) == set(tstore.keys()) - store.put("fixed", s) - result = store.select("fixed") - tm.assert_series_equal(result, s) + # check indices & nrows + for k in tstore.keys(): + if tstore.get_storer(k).is_table: + new_t = tstore.get_storer(k) + orig_t = store.get_storer(k) - store.append("table", s) - result = store.select("table") - tm.assert_series_equal(result, s) + assert orig_t.nrows == new_t.nrows - def test_append_with_timedelta(self, setup_path): - # GH 3577 - # append timedelta + # check propindixes + if propindexes: + for a in orig_t.axes: + if a.is_indexed: + assert new_t[a.name].is_indexed - df = DataFrame( - { - "A": Timestamp("20130101"), - "B": [ - Timestamp("20130101") + timedelta(days=i, seconds=10) - for i in range(10) - ], - } - ) - df["C"] = df["A"] - df["B"] - df.loc[3:5, "C"] = np.nan + finally: + safe_close(store) + safe_close(tstore) + try: + os.close(fd) + except (OSError, ValueError): + pass + os.remove(new_f) - with ensure_clean_store(setup_path) as store: + # new table + df = tm.makeDataFrame() - # table - _maybe_remove(store, "df") - store.append("df", df, data_columns=True) - result = store.select("df") - tm.assert_frame_equal(result, df) + with tm.ensure_clean() as path: + st = HDFStore(path) + st.append("df", df, data_columns=["A"]) + st.close() + do_copy(f=path) + do_copy(f=path, propindexes=False) - result = store.select("df", where="C<100000") - tm.assert_frame_equal(result, df) - result = store.select("df", where="C<pd.Timedelta('-3D')") - tm.assert_frame_equal(result, df.iloc[3:]) +def test_duplicate_column_name(setup_path): + df = DataFrame(columns=["a", "a"], data=[[0, 0]]) - result = store.select("df", "C<'-3D'") - tm.assert_frame_equal(result, df.iloc[3:]) + with ensure_clean_path(setup_path) as path: + msg = "Columns index has to be unique for fixed format" + with pytest.raises(ValueError, match=msg): + df.to_hdf(path, "df", format="fixed") - # a bit hacky here as we don't really deal with the NaT properly + df.to_hdf(path, "df", format="table") + other = read_hdf(path, "df") - result = store.select("df", "C<'-500000s'") - result = result.dropna(subset=["C"]) - tm.assert_frame_equal(result, df.iloc[6:]) + tm.assert_frame_equal(df, other) + assert df.equals(other) + assert other.equals(df) - result = store.select("df", "C<'-3.5D'") - result = result.iloc[1:] - tm.assert_frame_equal(result, df.iloc[4:]) - # fixed - _maybe_remove(store, "df2") - store.put("df2", df) - result = store.select("df2") - tm.assert_frame_equal(result, df) +def test_preserve_timedeltaindex_type(setup_path): + # GH9635 + df = DataFrame(np.random.normal(size=(10, 5))) + df.index = timedelta_range(start="0s", periods=10, freq="1s", name="example") - def test_remove(self, setup_path): + with ensure_clean_store(setup_path) as store: - with ensure_clean_store(setup_path) as store: + store["df"] = df + tm.assert_frame_equal(store["df"], df) - ts = tm.makeTimeSeries() - df = tm.makeDataFrame() - store["a"] = ts - store["b"] = df - _maybe_remove(store, "a") - assert len(store) == 1 - tm.assert_frame_equal(df, store["b"]) - _maybe_remove(store, "b") - assert len(store) == 0 +def test_columns_multiindex_modified(setup_path): + # BUG: 7212 - # nonexistence - with pytest.raises( - KeyError, match="'No object named a_nonexistent_store in the file'" - ): - store.remove("a_nonexistent_store") + df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) + df.index.name = "letters" + df = df.set_index(keys="E", append=True) - # pathing - store["a"] = ts - store["b/foo"] = df - _maybe_remove(store, "foo") - _maybe_remove(store, "b/foo") - assert len(store) == 1 + data_columns = df.index.names + df.columns.tolist() + with ensure_clean_path(setup_path) as path: + df.to_hdf( + path, + "df", + mode="a", + append=True, + data_columns=data_columns, + index=False, + ) + cols2load = list("BCD") + cols2load_original = list(cols2load) + df_loaded = read_hdf(path, "df", columns=cols2load) # noqa + assert cols2load_original == cols2load - store["a"] = ts - store["b/foo"] = df - _maybe_remove(store, "b") - assert len(store) == 1 - # __delitem__ - store["a"] = ts - store["b"] = df - del store["a"] - del store["b"] - assert len(store) == 0 +pytest.mark.filterwarnings("ignore:object name:tables.exceptions.NaturalNameWarning") - def test_invalid_terms(self, setup_path): - with ensure_clean_store(setup_path) as store: +def test_to_hdf_with_object_column_names(setup_path): + # GH9057 - with catch_warnings(record=True): - - df = tm.makeTimeDataFrame() - df["string"] = "foo" - df.loc[df.index[0:4], "string"] = "bar" - - store.put("df", df, format="table") - - # some invalid terms - msg = re.escape( - "__init__() missing 1 required positional argument: 'where'" - ) - with pytest.raises(TypeError, match=msg): - Term() - - # more invalid - msg = re.escape( - "cannot process expression [df.index[3]], " - "[2000-01-06 00:00:00] is not a valid condition" - ) - with pytest.raises(ValueError, match=msg): - store.select("df", "df.index[3]") - - msg = "invalid syntax" - with pytest.raises(SyntaxError, match=msg): - store.select("df", "index>") - - # from the docs - with ensure_clean_path(setup_path) as path: - dfq = DataFrame( - np.random.randn(10, 4), - columns=list("ABCD"), - index=date_range("20130101", periods=10), - ) - dfq.to_hdf(path, "dfq", format="table", data_columns=True) - - # check ok - read_hdf( - path, "dfq", where="index>Timestamp('20130104') & columns=['A', 'B']" - ) - read_hdf(path, "dfq", where="A>0 or C>0") - - # catch the invalid reference - with ensure_clean_path(setup_path) as path: - dfq = DataFrame( - np.random.randn(10, 4), - columns=list("ABCD"), - index=date_range("20130101", periods=10), - ) - dfq.to_hdf(path, "dfq", format="table") - - msg = ( - r"The passed where expression: A>0 or C>0\n\s*" - r"contains an invalid variable reference\n\s*" - r"all of the variable references must be a reference to\n\s*" - r"an axis \(e.g. 'index' or 'columns'\), or a data_column\n\s*" - r"The currently defined references are: index,columns\n" - ) - with pytest.raises(ValueError, match=msg): - read_hdf(path, "dfq", where="A>0 or C>0") - - def test_same_name_scoping(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - import pandas as pd - - df = DataFrame( - np.random.randn(20, 2), index=pd.date_range("20130101", periods=20) - ) - store.put("df", df, format="table") - expected = df[df.index > Timestamp("20130105")] - - import datetime - - result = store.select("df", "index>datetime.datetime(2013,1,5)") - tm.assert_frame_equal(result, expected) - - from datetime import datetime # noqa - - # technically an error, but allow it - result = store.select("df", "index>datetime.datetime(2013,1,5)") - tm.assert_frame_equal(result, expected) - - result = store.select("df", "index>datetime(2013,1,5)") - tm.assert_frame_equal(result, expected) - - def test_series(self, setup_path): - - s = tm.makeStringSeries() - self._check_roundtrip(s, tm.assert_series_equal, path=setup_path) - - ts = tm.makeTimeSeries() - self._check_roundtrip(ts, tm.assert_series_equal, path=setup_path) - - ts2 = Series(ts.index, Index(ts.index, dtype=object)) - self._check_roundtrip(ts2, tm.assert_series_equal, path=setup_path) - - ts3 = Series(ts.values, Index(np.asarray(ts.index, dtype=object), dtype=object)) - self._check_roundtrip( - ts3, tm.assert_series_equal, path=setup_path, check_index_type=False - ) - - def test_float_index(self, setup_path): - - # GH #454 - index = np.random.randn(10) - s = Series(np.random.randn(10), index=index) - self._check_roundtrip(s, tm.assert_series_equal, path=setup_path) - - def test_tuple_index(self, setup_path): - - # GH #492 - col = np.arange(10) - idx = [(0.0, 1.0), (2.0, 3.0), (4.0, 5.0)] - data = np.random.randn(30).reshape((3, 10)) - DF = DataFrame(data, index=idx, columns=col) - - with catch_warnings(record=True): - simplefilter("ignore", pd.errors.PerformanceWarning) - self._check_roundtrip(DF, tm.assert_frame_equal, path=setup_path) - - @pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") - def test_index_types(self, setup_path): - - with catch_warnings(record=True): - values = np.random.randn(2) - - func = lambda l, r: tm.assert_series_equal(l, r, check_index_type=True) - - with catch_warnings(record=True): - ser = Series(values, [0, "y"]) - self._check_roundtrip(ser, func, path=setup_path) - - with catch_warnings(record=True): - ser = Series(values, [datetime.datetime.today(), 0]) - self._check_roundtrip(ser, func, path=setup_path) - - with catch_warnings(record=True): - ser = Series(values, ["y", 0]) - self._check_roundtrip(ser, func, path=setup_path) - - with catch_warnings(record=True): - ser = Series(values, [datetime.date.today(), "a"]) - self._check_roundtrip(ser, func, path=setup_path) - - with catch_warnings(record=True): - - ser = Series(values, [0, "y"]) - self._check_roundtrip(ser, func, path=setup_path) - - ser = Series(values, [datetime.datetime.today(), 0]) - self._check_roundtrip(ser, func, path=setup_path) - - ser = Series(values, ["y", 0]) - self._check_roundtrip(ser, func, path=setup_path) - - ser = Series(values, [datetime.date.today(), "a"]) - self._check_roundtrip(ser, func, path=setup_path) - - ser = Series(values, [1.23, "b"]) - self._check_roundtrip(ser, func, path=setup_path) - - ser = Series(values, [1, 1.53]) - self._check_roundtrip(ser, func, path=setup_path) - - ser = Series(values, [1, 5]) - self._check_roundtrip(ser, func, path=setup_path) - - ser = Series( - values, [datetime.datetime(2012, 1, 1), datetime.datetime(2012, 1, 2)] - ) - self._check_roundtrip(ser, func, path=setup_path) - - def test_timeseries_preepoch(self, setup_path): - - dr = bdate_range("1/1/1940", "1/1/1960") - ts = Series(np.random.randn(len(dr)), index=dr) - try: - self._check_roundtrip(ts, tm.assert_series_equal, path=setup_path) - except OverflowError: - pytest.skip("known failer on some windows platforms") - - @pytest.mark.parametrize( - "compression", [False, pytest.param(True, marks=td.skip_if_windows_python_3)] - ) - def test_frame(self, compression, setup_path): - - df = tm.makeDataFrame() - - # put in some random NAs - df.values[0, 0] = np.nan - df.values[5, 3] = np.nan - - self._check_roundtrip_table( - df, tm.assert_frame_equal, path=setup_path, compression=compression - ) - self._check_roundtrip( - df, tm.assert_frame_equal, path=setup_path, compression=compression - ) - - tdf = tm.makeTimeDataFrame() - self._check_roundtrip( - tdf, tm.assert_frame_equal, path=setup_path, compression=compression - ) - - with ensure_clean_store(setup_path) as store: - # not consolidated - df["foo"] = np.random.randn(len(df)) - store["df"] = df - recons = store["df"] - assert recons._mgr.is_consolidated() - - # empty - self._check_roundtrip(df[:0], tm.assert_frame_equal, path=setup_path) - - def test_empty_series_frame(self, setup_path): - s0 = Series(dtype=object) - s1 = Series(name="myseries", dtype=object) - df0 = DataFrame() - df1 = DataFrame(index=["a", "b", "c"]) - df2 = DataFrame(columns=["d", "e", "f"]) - - self._check_roundtrip(s0, tm.assert_series_equal, path=setup_path) - self._check_roundtrip(s1, tm.assert_series_equal, path=setup_path) - self._check_roundtrip(df0, tm.assert_frame_equal, path=setup_path) - self._check_roundtrip(df1, tm.assert_frame_equal, path=setup_path) - self._check_roundtrip(df2, tm.assert_frame_equal, path=setup_path) - - @pytest.mark.parametrize( - "dtype", [np.int64, np.float64, object, "m8[ns]", "M8[ns]"] - ) - def test_empty_series(self, dtype, setup_path): - s = Series(dtype=dtype) - self._check_roundtrip(s, tm.assert_series_equal, path=setup_path) - - def test_can_serialize_dates(self, setup_path): - - rng = [x.date() for x in bdate_range("1/1/2000", "1/30/2000")] - frame = DataFrame(np.random.randn(len(rng), 4), index=rng) - - self._check_roundtrip(frame, tm.assert_frame_equal, path=setup_path) - - def test_store_hierarchical(self, setup_path): - index = MultiIndex( - levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], - codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], - names=["foo", "bar"], - ) - frame = DataFrame(np.random.randn(10, 3), index=index, columns=["A", "B", "C"]) - - self._check_roundtrip(frame, tm.assert_frame_equal, path=setup_path) - self._check_roundtrip(frame.T, tm.assert_frame_equal, path=setup_path) - self._check_roundtrip(frame["A"], tm.assert_series_equal, path=setup_path) - - # check that the names are stored - with ensure_clean_store(setup_path) as store: - store["frame"] = frame - recons = store["frame"] - tm.assert_frame_equal(recons, frame) - - def test_store_index_name(self, setup_path): - df = tm.makeDataFrame() - df.index.name = "foo" - - with ensure_clean_store(setup_path) as store: - store["frame"] = df - recons = store["frame"] - tm.assert_frame_equal(recons, df) - - @pytest.mark.parametrize("table_format", ["table", "fixed"]) - def test_store_index_name_numpy_str(self, table_format, setup_path): - # GH #13492 - idx = Index( - pd.to_datetime([datetime.date(2000, 1, 1), datetime.date(2000, 1, 2)]), - name="cols\u05d2", - ) - idx1 = Index( - pd.to_datetime([datetime.date(2010, 1, 1), datetime.date(2010, 1, 2)]), - name="rows\u05d0", - ) - df = DataFrame(np.arange(4).reshape(2, 2), columns=idx, index=idx1) - - # This used to fail, returning numpy strings instead of python strings. - with ensure_clean_path(setup_path) as path: - df.to_hdf(path, "df", format=table_format) - df2 = read_hdf(path, "df") - - tm.assert_frame_equal(df, df2, check_names=True) - - assert type(df2.index.name) == str - assert type(df2.columns.name) == str - - def test_store_series_name(self, setup_path): - df = tm.makeDataFrame() - series = df["A"] - - with ensure_clean_store(setup_path) as store: - store["series"] = series - recons = store["series"] - tm.assert_series_equal(recons, series) - - @pytest.mark.parametrize( - "compression", [False, pytest.param(True, marks=td.skip_if_windows_python_3)] - ) - def test_store_mixed(self, compression, setup_path): - def _make_one(): - df = tm.makeDataFrame() - df["obj1"] = "foo" - df["obj2"] = "bar" - df["bool1"] = df["A"] > 0 - df["bool2"] = df["B"] > 0 - df["int1"] = 1 - df["int2"] = 2 - return df._consolidate() - - df1 = _make_one() - df2 = _make_one() - - self._check_roundtrip(df1, tm.assert_frame_equal, path=setup_path) - self._check_roundtrip(df2, tm.assert_frame_equal, path=setup_path) - - with ensure_clean_store(setup_path) as store: - store["obj"] = df1 - tm.assert_frame_equal(store["obj"], df1) - store["obj"] = df2 - tm.assert_frame_equal(store["obj"], df2) - - # check that can store Series of all of these types - self._check_roundtrip( - df1["obj1"], - tm.assert_series_equal, - path=setup_path, - compression=compression, - ) - self._check_roundtrip( - df1["bool1"], - tm.assert_series_equal, - path=setup_path, - compression=compression, - ) - self._check_roundtrip( - df1["int1"], - tm.assert_series_equal, - path=setup_path, - compression=compression, - ) - - @pytest.mark.filterwarnings( - "ignore:\\nduplicate:pandas.io.pytables.DuplicateWarning" - ) - def test_select_with_dups(self, setup_path): - - # single dtypes - df = DataFrame(np.random.randn(10, 4), columns=["A", "A", "B", "B"]) - df.index = date_range("20130101 9:30", periods=10, freq="T") - - with ensure_clean_store(setup_path) as store: - store.append("df", df) - - result = store.select("df") - expected = df - tm.assert_frame_equal(result, expected, by_blocks=True) - - result = store.select("df", columns=df.columns) - expected = df - tm.assert_frame_equal(result, expected, by_blocks=True) - - result = store.select("df", columns=["A"]) - expected = df.loc[:, ["A"]] - tm.assert_frame_equal(result, expected) - - # dups across dtypes - df = concat( - [ - DataFrame(np.random.randn(10, 4), columns=["A", "A", "B", "B"]), - DataFrame( - np.random.randint(0, 10, size=20).reshape(10, 2), columns=["A", "C"] - ), - ], - axis=1, - ) - df.index = date_range("20130101 9:30", periods=10, freq="T") - - with ensure_clean_store(setup_path) as store: - store.append("df", df) - - result = store.select("df") - expected = df - tm.assert_frame_equal(result, expected, by_blocks=True) - - result = store.select("df", columns=df.columns) - expected = df - tm.assert_frame_equal(result, expected, by_blocks=True) - - expected = df.loc[:, ["A"]] - result = store.select("df", columns=["A"]) - tm.assert_frame_equal(result, expected, by_blocks=True) - - expected = df.loc[:, ["B", "A"]] - result = store.select("df", columns=["B", "A"]) - tm.assert_frame_equal(result, expected, by_blocks=True) - - # duplicates on both index and columns - with ensure_clean_store(setup_path) as store: - store.append("df", df) - store.append("df", df) - - expected = df.loc[:, ["B", "A"]] - expected = concat([expected, expected]) - result = store.select("df", columns=["B", "A"]) - tm.assert_frame_equal(result, expected, by_blocks=True) - - def test_overwrite_node(self, setup_path): - - with ensure_clean_store(setup_path) as store: - store["a"] = tm.makeTimeDataFrame() - ts = tm.makeTimeSeries() - store["a"] = ts - - tm.assert_series_equal(store["a"], ts) - - def test_select(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - with catch_warnings(record=True): - - # select with columns= - df = tm.makeTimeDataFrame() - _maybe_remove(store, "df") - store.append("df", df) - result = store.select("df", columns=["A", "B"]) - expected = df.reindex(columns=["A", "B"]) - tm.assert_frame_equal(expected, result) - - # equivalently - result = store.select("df", [("columns=['A', 'B']")]) - expected = df.reindex(columns=["A", "B"]) - tm.assert_frame_equal(expected, result) - - # with a data column - _maybe_remove(store, "df") - store.append("df", df, data_columns=["A"]) - result = store.select("df", ["A > 0"], columns=["A", "B"]) - expected = df[df.A > 0].reindex(columns=["A", "B"]) - tm.assert_frame_equal(expected, result) - - # all a data columns - _maybe_remove(store, "df") - store.append("df", df, data_columns=True) - result = store.select("df", ["A > 0"], columns=["A", "B"]) - expected = df[df.A > 0].reindex(columns=["A", "B"]) - tm.assert_frame_equal(expected, result) - - # with a data column, but different columns - _maybe_remove(store, "df") - store.append("df", df, data_columns=["A"]) - result = store.select("df", ["A > 0"], columns=["C", "D"]) - expected = df[df.A > 0].reindex(columns=["C", "D"]) - tm.assert_frame_equal(expected, result) - - def test_select_dtypes(self, setup_path): - - with ensure_clean_store(setup_path) as store: - # with a Timestamp data column (GH #2637) - df = DataFrame( - { - "ts": bdate_range("2012-01-01", periods=300), - "A": np.random.randn(300), - } - ) - _maybe_remove(store, "df") - store.append("df", df, data_columns=["ts", "A"]) - - result = store.select("df", "ts>=Timestamp('2012-02-01')") - expected = df[df.ts >= Timestamp("2012-02-01")] - tm.assert_frame_equal(expected, result) - - # bool columns (GH #2849) - df = DataFrame(np.random.randn(5, 2), columns=["A", "B"]) - df["object"] = "foo" - df.loc[4:5, "object"] = "bar" - df["boolv"] = df["A"] > 0 - _maybe_remove(store, "df") - store.append("df", df, data_columns=True) - - expected = df[df.boolv == True].reindex(columns=["A", "boolv"]) # noqa - for v in [True, "true", 1]: - result = store.select("df", f"boolv == {v}", columns=["A", "boolv"]) - tm.assert_frame_equal(expected, result) - - expected = df[df.boolv == False].reindex(columns=["A", "boolv"]) # noqa - for v in [False, "false", 0]: - result = store.select("df", f"boolv == {v}", columns=["A", "boolv"]) - tm.assert_frame_equal(expected, result) - - # integer index - df = DataFrame({"A": np.random.rand(20), "B": np.random.rand(20)}) - _maybe_remove(store, "df_int") - store.append("df_int", df) - result = store.select("df_int", "index<10 and columns=['A']") - expected = df.reindex(index=list(df.index)[0:10], columns=["A"]) - tm.assert_frame_equal(expected, result) - - # float index - df = DataFrame( - { - "A": np.random.rand(20), - "B": np.random.rand(20), - "index": np.arange(20, dtype="f8"), - } - ) - _maybe_remove(store, "df_float") - store.append("df_float", df) - result = store.select("df_float", "index<10.0 and columns=['A']") - expected = df.reindex(index=list(df.index)[0:10], columns=["A"]) - tm.assert_frame_equal(expected, result) - - with ensure_clean_store(setup_path) as store: - - # floats w/o NaN - df = DataFrame({"cols": range(11), "values": range(11)}, dtype="float64") - df["cols"] = (df["cols"] + 10).apply(str) - - store.append("df1", df, data_columns=True) - result = store.select("df1", where="values>2.0") - expected = df[df["values"] > 2.0] - tm.assert_frame_equal(expected, result) - - # floats with NaN - df.iloc[0] = np.nan - expected = df[df["values"] > 2.0] - - store.append("df2", df, data_columns=True, index=False) - result = store.select("df2", where="values>2.0") - tm.assert_frame_equal(expected, result) - - # https://github.com/PyTables/PyTables/issues/282 - # bug in selection when 0th row has a np.nan and an index - # store.append('df3',df,data_columns=True) - # result = store.select( - # 'df3', where='values>2.0') - # tm.assert_frame_equal(expected, result) - - # not in first position float with NaN ok too - df = DataFrame({"cols": range(11), "values": range(11)}, dtype="float64") - df["cols"] = (df["cols"] + 10).apply(str) - - df.iloc[1] = np.nan - expected = df[df["values"] > 2.0] - - store.append("df4", df, data_columns=True) - result = store.select("df4", where="values>2.0") - tm.assert_frame_equal(expected, result) - - # test selection with comparison against numpy scalar - # GH 11283 - with ensure_clean_store(setup_path) as store: - df = tm.makeDataFrame() - - expected = df[df["A"] > 0] - - store.append("df", df, data_columns=True) - np_zero = np.float64(0) # noqa - result = store.select("df", where=["A>np_zero"]) - tm.assert_frame_equal(expected, result) - - def test_select_with_many_inputs(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - df = DataFrame( - { - "ts": bdate_range("2012-01-01", periods=300), - "A": np.random.randn(300), - "B": range(300), - "users": ["a"] * 50 - + ["b"] * 50 - + ["c"] * 100 - + [f"a{i:03d}" for i in range(100)], - } - ) - _maybe_remove(store, "df") - store.append("df", df, data_columns=["ts", "A", "B", "users"]) - - # regular select - result = store.select("df", "ts>=Timestamp('2012-02-01')") - expected = df[df.ts >= Timestamp("2012-02-01")] - tm.assert_frame_equal(expected, result) - - # small selector - result = store.select( - "df", "ts>=Timestamp('2012-02-01') & users=['a','b','c']" - ) - expected = df[ - (df.ts >= Timestamp("2012-02-01")) & df.users.isin(["a", "b", "c"]) - ] - tm.assert_frame_equal(expected, result) - - # big selector along the columns - selector = ["a", "b", "c"] + [f"a{i:03d}" for i in range(60)] - result = store.select( - "df", "ts>=Timestamp('2012-02-01') and users=selector" - ) - expected = df[(df.ts >= Timestamp("2012-02-01")) & df.users.isin(selector)] - tm.assert_frame_equal(expected, result) - - selector = range(100, 200) - result = store.select("df", "B=selector") - expected = df[df.B.isin(selector)] - tm.assert_frame_equal(expected, result) - assert len(result) == 100 - - # big selector along the index - selector = Index(df.ts[0:100].values) - result = store.select("df", "ts=selector") - expected = df[df.ts.isin(selector.values)] - tm.assert_frame_equal(expected, result) - assert len(result) == 100 - - def test_select_iterator(self, setup_path): - - # single table - with ensure_clean_store(setup_path) as store: - - df = tm.makeTimeDataFrame(500) - _maybe_remove(store, "df") - store.append("df", df) - - expected = store.select("df") - - results = list(store.select("df", iterator=True)) - result = concat(results) - tm.assert_frame_equal(expected, result) - - results = list(store.select("df", chunksize=100)) - assert len(results) == 5 - result = concat(results) - tm.assert_frame_equal(expected, result) - - results = list(store.select("df", chunksize=150)) - result = concat(results) - tm.assert_frame_equal(result, expected) - - with ensure_clean_path(setup_path) as path: - - df = tm.makeTimeDataFrame(500) - df.to_hdf(path, "df_non_table") - - msg = "can only use an iterator or chunksize on a table" - with pytest.raises(TypeError, match=msg): - read_hdf(path, "df_non_table", chunksize=100) - - with pytest.raises(TypeError, match=msg): - read_hdf(path, "df_non_table", iterator=True) - - with ensure_clean_path(setup_path) as path: - - df = tm.makeTimeDataFrame(500) - df.to_hdf(path, "df", format="table") - - results = list(read_hdf(path, "df", chunksize=100)) - result = concat(results) - - assert len(results) == 5 - tm.assert_frame_equal(result, df) - tm.assert_frame_equal(result, read_hdf(path, "df")) - - # multiple - - with ensure_clean_store(setup_path) as store: - - df1 = tm.makeTimeDataFrame(500) - store.append("df1", df1, data_columns=True) - df2 = tm.makeTimeDataFrame(500).rename(columns="{}_2".format) - df2["foo"] = "bar" - store.append("df2", df2) - - df = concat([df1, df2], axis=1) - - # full selection - expected = store.select_as_multiple(["df1", "df2"], selector="df1") - results = list( - store.select_as_multiple(["df1", "df2"], selector="df1", chunksize=150) - ) - result = concat(results) - tm.assert_frame_equal(expected, result) - - def test_select_iterator_complete_8014(self, setup_path): - - # GH 8014 - # using iterator and where clause - chunksize = 1e4 - - # no iterator - with ensure_clean_store(setup_path) as store: - - expected = tm.makeTimeDataFrame(100064, "S") - _maybe_remove(store, "df") - store.append("df", expected) - - beg_dt = expected.index[0] - end_dt = expected.index[-1] - - # select w/o iteration and no where clause works - result = store.select("df") - tm.assert_frame_equal(expected, result) - - # select w/o iterator and where clause, single term, begin - # of range, works - where = f"index >= '{beg_dt}'" - result = store.select("df", where=where) - tm.assert_frame_equal(expected, result) - - # select w/o iterator and where clause, single term, end - # of range, works - where = f"index <= '{end_dt}'" - result = store.select("df", where=where) - tm.assert_frame_equal(expected, result) - - # select w/o iterator and where clause, inclusive range, - # works - where = f"index >= '{beg_dt}' & index <= '{end_dt}'" - result = store.select("df", where=where) - tm.assert_frame_equal(expected, result) - - # with iterator, full range - with ensure_clean_store(setup_path) as store: - - expected = tm.makeTimeDataFrame(100064, "S") - _maybe_remove(store, "df") - store.append("df", expected) - - beg_dt = expected.index[0] - end_dt = expected.index[-1] - - # select w/iterator and no where clause works - results = list(store.select("df", chunksize=chunksize)) - result = concat(results) - tm.assert_frame_equal(expected, result) - - # select w/iterator and where clause, single term, begin of range - where = f"index >= '{beg_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - result = concat(results) - tm.assert_frame_equal(expected, result) - - # select w/iterator and where clause, single term, end of range - where = f"index <= '{end_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - result = concat(results) - tm.assert_frame_equal(expected, result) - - # select w/iterator and where clause, inclusive range - where = f"index >= '{beg_dt}' & index <= '{end_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - result = concat(results) - tm.assert_frame_equal(expected, result) - - def test_select_iterator_non_complete_8014(self, setup_path): - - # GH 8014 - # using iterator and where clause - chunksize = 1e4 - - # with iterator, non complete range - with ensure_clean_store(setup_path) as store: - - expected = tm.makeTimeDataFrame(100064, "S") - _maybe_remove(store, "df") - store.append("df", expected) - - beg_dt = expected.index[1] - end_dt = expected.index[-2] - - # select w/iterator and where clause, single term, begin of range - where = f"index >= '{beg_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - result = concat(results) - rexpected = expected[expected.index >= beg_dt] - tm.assert_frame_equal(rexpected, result) - - # select w/iterator and where clause, single term, end of range - where = f"index <= '{end_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - result = concat(results) - rexpected = expected[expected.index <= end_dt] - tm.assert_frame_equal(rexpected, result) - - # select w/iterator and where clause, inclusive range - where = f"index >= '{beg_dt}' & index <= '{end_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - result = concat(results) - rexpected = expected[ - (expected.index >= beg_dt) & (expected.index <= end_dt) - ] - tm.assert_frame_equal(rexpected, result) - - # with iterator, empty where - with ensure_clean_store(setup_path) as store: - - expected = tm.makeTimeDataFrame(100064, "S") - _maybe_remove(store, "df") - store.append("df", expected) - - end_dt = expected.index[-1] - - # select w/iterator and where clause, single term, begin of range - where = f"index > '{end_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - assert 0 == len(results) - - def test_select_iterator_many_empty_frames(self, setup_path): - - # GH 8014 - # using iterator and where clause can return many empty - # frames. - chunksize = 10_000 - - # with iterator, range limited to the first chunk - with ensure_clean_store(setup_path) as store: - - expected = tm.makeTimeDataFrame(100000, "S") - _maybe_remove(store, "df") - store.append("df", expected) - - beg_dt = expected.index[0] - end_dt = expected.index[chunksize - 1] - - # select w/iterator and where clause, single term, begin of range - where = f"index >= '{beg_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - result = concat(results) - rexpected = expected[expected.index >= beg_dt] - tm.assert_frame_equal(rexpected, result) - - # select w/iterator and where clause, single term, end of range - where = f"index <= '{end_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - - assert len(results) == 1 - result = concat(results) - rexpected = expected[expected.index <= end_dt] - tm.assert_frame_equal(rexpected, result) - - # select w/iterator and where clause, inclusive range - where = f"index >= '{beg_dt}' & index <= '{end_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - - # should be 1, is 10 - assert len(results) == 1 - result = concat(results) - rexpected = expected[ - (expected.index >= beg_dt) & (expected.index <= end_dt) - ] - tm.assert_frame_equal(rexpected, result) - - # select w/iterator and where clause which selects - # *nothing*. - # - # To be consistent with Python idiom I suggest this should - # return [] e.g. `for e in []: print True` never prints - # True. - - where = f"index <= '{beg_dt}' & index >= '{end_dt}'" - results = list(store.select("df", where=where, chunksize=chunksize)) - - # should be [] - assert len(results) == 0 - - @pytest.mark.filterwarnings( - "ignore:\\nthe :pandas.io.pytables.AttributeConflictWarning" - ) - def test_retain_index_attributes(self, setup_path): - - # GH 3499, losing frequency info on index recreation - df = DataFrame( - {"A": Series(range(3), index=date_range("2000-1-1", periods=3, freq="H"))} - ) - - with ensure_clean_store(setup_path) as store: - _maybe_remove(store, "data") - store.put("data", df, format="table") - - result = store.get("data") - tm.assert_frame_equal(df, result) - - for attr in ["freq", "tz", "name"]: - for idx in ["index", "columns"]: - assert getattr(getattr(df, idx), attr, None) == getattr( - getattr(result, idx), attr, None - ) - - # try to append a table with a different frequency - with catch_warnings(record=True): - df2 = DataFrame( - { - "A": Series( - range(3), index=date_range("2002-1-1", periods=3, freq="D") - ) - } - ) - store.append("data", df2) - - assert store.get_storer("data").info["index"]["freq"] is None - - # this is ok - _maybe_remove(store, "df2") - df2 = DataFrame( - { - "A": Series( - range(3), - index=[ - Timestamp("20010101"), - Timestamp("20010102"), - Timestamp("20020101"), - ], - ) - } - ) - store.append("df2", df2) - df3 = DataFrame( - { - "A": Series( - range(3), index=date_range("2002-1-1", periods=3, freq="D") - ) - } - ) - store.append("df2", df3) - - @pytest.mark.filterwarnings( - "ignore:\\nthe :pandas.io.pytables.AttributeConflictWarning" - ) - def test_retain_index_attributes2(self, setup_path): - with ensure_clean_path(setup_path) as path: - - with catch_warnings(record=True): - - df = DataFrame( - { - "A": Series( - range(3), index=date_range("2000-1-1", periods=3, freq="H") - ) - } - ) - df.to_hdf(path, "data", mode="w", append=True) - df2 = DataFrame( - { - "A": Series( - range(3), index=date_range("2002-1-1", periods=3, freq="D") - ) - } - ) - - df2.to_hdf(path, "data", append=True) - - idx = date_range("2000-1-1", periods=3, freq="H") - idx.name = "foo" - df = DataFrame({"A": Series(range(3), index=idx)}) - df.to_hdf(path, "data", mode="w", append=True) - - assert read_hdf(path, "data").index.name == "foo" - - with catch_warnings(record=True): - - idx2 = date_range("2001-1-1", periods=3, freq="H") - idx2.name = "bar" - df2 = DataFrame({"A": Series(range(3), index=idx2)}) - df2.to_hdf(path, "data", append=True) - - assert read_hdf(path, "data").index.name is None - - def test_frame_select(self, setup_path): - - df = tm.makeTimeDataFrame() - - with ensure_clean_store(setup_path) as store: - store.put("frame", df, format="table") - date = df.index[len(df) // 2] - - crit1 = Term("index>=date") - assert crit1.env.scope["date"] == date - - crit2 = "columns=['A', 'D']" - crit3 = "columns=A" - - result = store.select("frame", [crit1, crit2]) - expected = df.loc[date:, ["A", "D"]] - tm.assert_frame_equal(result, expected) - - result = store.select("frame", [crit3]) - expected = df.loc[:, ["A"]] - tm.assert_frame_equal(result, expected) - - # invalid terms - df = tm.makeTimeDataFrame() - store.append("df_time", df) - msg = "could not convert string to Timestamp" - with pytest.raises(ValueError, match=msg): - store.select("df_time", "index>0") - - # can't select if not written as table - # store['frame'] = df - # with pytest.raises(ValueError): - # store.select('frame', [crit1, crit2]) - - def test_frame_select_complex(self, setup_path): - # select via complex criteria - - df = tm.makeTimeDataFrame() - df["string"] = "foo" - df.loc[df.index[0:4], "string"] = "bar" - - with ensure_clean_store(setup_path) as store: - store.put("df", df, format="table", data_columns=["string"]) - - # empty - result = store.select("df", 'index>df.index[3] & string="bar"') - expected = df.loc[(df.index > df.index[3]) & (df.string == "bar")] - tm.assert_frame_equal(result, expected) - - result = store.select("df", 'index>df.index[3] & string="foo"') - expected = df.loc[(df.index > df.index[3]) & (df.string == "foo")] - tm.assert_frame_equal(result, expected) - - # or - result = store.select("df", 'index>df.index[3] | string="bar"') - expected = df.loc[(df.index > df.index[3]) | (df.string == "bar")] - tm.assert_frame_equal(result, expected) - - result = store.select( - "df", '(index>df.index[3] & index<=df.index[6]) | string="bar"' - ) - expected = df.loc[ - ((df.index > df.index[3]) & (df.index <= df.index[6])) - | (df.string == "bar") - ] - tm.assert_frame_equal(result, expected) - - # invert - result = store.select("df", 'string!="bar"') - expected = df.loc[df.string != "bar"] - tm.assert_frame_equal(result, expected) - - # invert not implemented in numexpr :( - msg = "cannot use an invert condition when passing to numexpr" - with pytest.raises(NotImplementedError, match=msg): - store.select("df", '~(string="bar")') - - # invert ok for filters - result = store.select("df", "~(columns=['A','B'])") - expected = df.loc[:, df.columns.difference(["A", "B"])] - tm.assert_frame_equal(result, expected) - - # in - result = store.select("df", "index>df.index[3] & columns in ['A','B']") - expected = df.loc[df.index > df.index[3]].reindex(columns=["A", "B"]) - tm.assert_frame_equal(result, expected) - - def test_frame_select_complex2(self, setup_path): - - with ensure_clean_path(["parms.hdf", "hist.hdf"]) as paths: - - pp, hh = paths - - # use non-trivial selection criteria - parms = DataFrame({"A": [1, 1, 2, 2, 3]}) - parms.to_hdf(pp, "df", mode="w", format="table", data_columns=["A"]) - - selection = read_hdf(pp, "df", where="A=[2,3]") - hist = DataFrame( - np.random.randn(25, 1), - columns=["data"], - index=MultiIndex.from_tuples( - [(i, j) for i in range(5) for j in range(5)], names=["l1", "l2"] - ), - ) - - hist.to_hdf(hh, "df", mode="w", format="table") - - expected = read_hdf(hh, "df", where="l1=[2, 3, 4]") - - # scope with list like - l = selection.index.tolist() # noqa - store = HDFStore(hh) - result = store.select("df", where="l1=l") - tm.assert_frame_equal(result, expected) - store.close() - - result = read_hdf(hh, "df", where="l1=l") - tm.assert_frame_equal(result, expected) - - # index - index = selection.index # noqa - result = read_hdf(hh, "df", where="l1=index") - tm.assert_frame_equal(result, expected) - - result = read_hdf(hh, "df", where="l1=selection.index") - tm.assert_frame_equal(result, expected) - - result = read_hdf(hh, "df", where="l1=selection.index.tolist()") - tm.assert_frame_equal(result, expected) - - result = read_hdf(hh, "df", where="l1=list(selection.index)") - tm.assert_frame_equal(result, expected) - - # scope with index - store = HDFStore(hh) - - result = store.select("df", where="l1=index") - tm.assert_frame_equal(result, expected) - - result = store.select("df", where="l1=selection.index") - tm.assert_frame_equal(result, expected) - - result = store.select("df", where="l1=selection.index.tolist()") - tm.assert_frame_equal(result, expected) - - result = store.select("df", where="l1=list(selection.index)") - tm.assert_frame_equal(result, expected) - - store.close() - - def test_invalid_filtering(self, setup_path): - - # can't use more than one filter (atm) - - df = tm.makeTimeDataFrame() - - with ensure_clean_store(setup_path) as store: - store.put("df", df, format="table") - - msg = "unable to collapse Joint Filters" - # not implemented - with pytest.raises(NotImplementedError, match=msg): - store.select("df", "columns=['A'] | columns=['B']") - - # in theory we could deal with this - with pytest.raises(NotImplementedError, match=msg): - store.select("df", "columns=['A','B'] & columns=['C']") - - def test_string_select(self, setup_path): - # GH 2973 - with ensure_clean_store(setup_path) as store: - - df = tm.makeTimeDataFrame() - - # test string ==/!= - df["x"] = "none" - df.loc[df.index[2:7], "x"] = "" - - store.append("df", df, data_columns=["x"]) - - result = store.select("df", "x=none") - expected = df[df.x == "none"] - tm.assert_frame_equal(result, expected) - - result = store.select("df", "x!=none") - expected = df[df.x != "none"] - tm.assert_frame_equal(result, expected) - - df2 = df.copy() - df2.loc[df2.x == "", "x"] = np.nan - - store.append("df2", df2, data_columns=["x"]) - result = store.select("df2", "x!=none") - expected = df2[isna(df2.x)] - tm.assert_frame_equal(result, expected) - - # int ==/!= - df["int"] = 1 - df.loc[df.index[2:7], "int"] = 2 - - store.append("df3", df, data_columns=["int"]) - - result = store.select("df3", "int=2") - expected = df[df.int == 2] - tm.assert_frame_equal(result, expected) - - result = store.select("df3", "int!=2") - expected = df[df.int != 2] - tm.assert_frame_equal(result, expected) - - def test_read_column(self, setup_path): - - df = tm.makeTimeDataFrame() - - with ensure_clean_store(setup_path) as store: - _maybe_remove(store, "df") - - # GH 17912 - # HDFStore.select_column should raise a KeyError - # exception if the key is not a valid store - with pytest.raises(KeyError, match="No object named df in the file"): - store.select_column("df", "index") - - store.append("df", df) - # error - with pytest.raises( - KeyError, match=re.escape("'column [foo] not found in the table'") - ): - store.select_column("df", "foo") - - msg = re.escape( - "select_column() got an unexpected keyword argument 'where'" - ) - with pytest.raises(TypeError, match=msg): - store.select_column("df", "index", where=["index>5"]) - - # valid - result = store.select_column("df", "index") - tm.assert_almost_equal(result.values, Series(df.index).values) - assert isinstance(result, Series) - - # not a data indexable column - msg = re.escape( - "column [values_block_0] can not be extracted individually; " - "it is not data indexable" - ) - with pytest.raises(ValueError, match=msg): - store.select_column("df", "values_block_0") - - # a data column - df2 = df.copy() - df2["string"] = "foo" - store.append("df2", df2, data_columns=["string"]) - result = store.select_column("df2", "string") - tm.assert_almost_equal(result.values, df2["string"].values) - - # a data column with NaNs, result excludes the NaNs - df3 = df.copy() - df3["string"] = "foo" - df3.loc[df3.index[4:6], "string"] = np.nan - store.append("df3", df3, data_columns=["string"]) - result = store.select_column("df3", "string") - tm.assert_almost_equal(result.values, df3["string"].values) - - # start/stop - result = store.select_column("df3", "string", start=2) - tm.assert_almost_equal(result.values, df3["string"].values[2:]) - - result = store.select_column("df3", "string", start=-2) - tm.assert_almost_equal(result.values, df3["string"].values[-2:]) - - result = store.select_column("df3", "string", stop=2) - tm.assert_almost_equal(result.values, df3["string"].values[:2]) - - result = store.select_column("df3", "string", stop=-2) - tm.assert_almost_equal(result.values, df3["string"].values[:-2]) - - result = store.select_column("df3", "string", start=2, stop=-2) - tm.assert_almost_equal(result.values, df3["string"].values[2:-2]) - - result = store.select_column("df3", "string", start=-2, stop=2) - tm.assert_almost_equal(result.values, df3["string"].values[-2:2]) - - # GH 10392 - make sure column name is preserved - df4 = DataFrame({"A": np.random.randn(10), "B": "foo"}) - store.append("df4", df4, data_columns=True) - expected = df4["B"] - result = store.select_column("df4", "B") - tm.assert_series_equal(result, expected) - - def test_coordinates(self, setup_path): - df = tm.makeTimeDataFrame() - - with ensure_clean_store(setup_path) as store: - - _maybe_remove(store, "df") - store.append("df", df) - - # all - c = store.select_as_coordinates("df") - assert (c.values == np.arange(len(df.index))).all() - - # get coordinates back & test vs frame - _maybe_remove(store, "df") - - df = DataFrame({"A": range(5), "B": range(5)}) - store.append("df", df) - c = store.select_as_coordinates("df", ["index<3"]) - assert (c.values == np.arange(3)).all() - result = store.select("df", where=c) - expected = df.loc[0:2, :] - tm.assert_frame_equal(result, expected) - - c = store.select_as_coordinates("df", ["index>=3", "index<=4"]) - assert (c.values == np.arange(2) + 3).all() - result = store.select("df", where=c) - expected = df.loc[3:4, :] - tm.assert_frame_equal(result, expected) - assert isinstance(c, Index) - - # multiple tables - _maybe_remove(store, "df1") - _maybe_remove(store, "df2") - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) - store.append("df1", df1, data_columns=["A", "B"]) - store.append("df2", df2) - - c = store.select_as_coordinates("df1", ["A>0", "B>0"]) - df1_result = store.select("df1", c) - df2_result = store.select("df2", c) - result = concat([df1_result, df2_result], axis=1) - - expected = concat([df1, df2], axis=1) - expected = expected[(expected.A > 0) & (expected.B > 0)] - tm.assert_frame_equal(result, expected) - - # pass array/mask as the coordinates - with ensure_clean_store(setup_path) as store: - - df = DataFrame( - np.random.randn(1000, 2), index=date_range("20000101", periods=1000) - ) - store.append("df", df) - c = store.select_column("df", "index") - where = c[DatetimeIndex(c).month == 5].index - expected = df.iloc[where] - - # locations - result = store.select("df", where=where) - tm.assert_frame_equal(result, expected) - - # boolean - result = store.select("df", where=where) - tm.assert_frame_equal(result, expected) - - # invalid - msg = "cannot process expression" - with pytest.raises(ValueError, match=msg): - store.select("df", where=np.arange(len(df), dtype="float64")) - - with pytest.raises(ValueError, match=msg): - store.select("df", where=np.arange(len(df) + 1)) - - with pytest.raises(ValueError, match=msg): - store.select("df", where=np.arange(len(df)), start=5) - - with pytest.raises(ValueError, match=msg): - store.select("df", where=np.arange(len(df)), start=5, stop=10) - - # selection with filter - selection = date_range("20000101", periods=500) - result = store.select("df", where="index in selection") - expected = df[df.index.isin(selection)] - tm.assert_frame_equal(result, expected) - - # list - df = DataFrame(np.random.randn(10, 2)) - store.append("df2", df) - result = store.select("df2", where=[0, 3, 5]) - expected = df.iloc[[0, 3, 5]] - tm.assert_frame_equal(result, expected) - - # boolean - where = [True] * 10 - where[-2] = False - result = store.select("df2", where=where) - expected = df.loc[where] - tm.assert_frame_equal(result, expected) - - # start/stop - result = store.select("df2", start=5, stop=10) - expected = df[5:10] - tm.assert_frame_equal(result, expected) - - def test_append_to_multiple(self, setup_path): - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) - df2["foo"] = "bar" - df = concat([df1, df2], axis=1) - - with ensure_clean_store(setup_path) as store: - - # exceptions - msg = "append_to_multiple requires a selector that is in passed dict" - with pytest.raises(ValueError, match=msg): - store.append_to_multiple( - {"df1": ["A", "B"], "df2": None}, df, selector="df3" - ) - - with pytest.raises(ValueError, match=msg): - store.append_to_multiple({"df1": None, "df2": None}, df, selector="df3") - - msg = ( - "append_to_multiple must have a dictionary specified as the way to " - "split the value" - ) - with pytest.raises(ValueError, match=msg): - store.append_to_multiple("df1", df, "df1") - - # regular operation - store.append_to_multiple( - {"df1": ["A", "B"], "df2": None}, df, selector="df1" - ) - result = store.select_as_multiple( - ["df1", "df2"], where=["A>0", "B>0"], selector="df1" - ) - expected = df[(df.A > 0) & (df.B > 0)] - tm.assert_frame_equal(result, expected) - - def test_append_to_multiple_dropna(self, setup_path): - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) - df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan - df = concat([df1, df2], axis=1) - - with ensure_clean_store(setup_path) as store: - - # dropna=True should guarantee rows are synchronized - store.append_to_multiple( - {"df1": ["A", "B"], "df2": None}, df, selector="df1", dropna=True - ) - result = store.select_as_multiple(["df1", "df2"]) - expected = df.dropna() - tm.assert_frame_equal(result, expected) - tm.assert_index_equal(store.select("df1").index, store.select("df2").index) - - @pytest.mark.xfail( - run=False, reason="append_to_multiple_dropna_false is not raising as failed" - ) - def test_append_to_multiple_dropna_false(self, setup_path): - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) - df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan - df = concat([df1, df2], axis=1) - - with ensure_clean_store(setup_path) as store: - - # dropna=False shouldn't synchronize row indexes - store.append_to_multiple( - {"df1a": ["A", "B"], "df2a": None}, df, selector="df1a", dropna=False - ) - - # TODO Update error message to desired message for this case - msg = "Cannot select as multiple after appending with dropna=False" - with pytest.raises(ValueError, match=msg): - store.select_as_multiple(["df1a", "df2a"]) - - assert not store.select("df1a").index.equals(store.select("df2a").index) - - def test_append_to_multiple_min_itemsize(self, setup_path): - # GH 11238 - df = DataFrame( - { - "IX": np.arange(1, 21), - "Num": np.arange(1, 21), - "BigNum": np.arange(1, 21) * 88, - "Str": ["a" for _ in range(20)], - "LongStr": ["abcde" for _ in range(20)], - } - ) - expected = df.iloc[[0]] - - with ensure_clean_store(setup_path) as store: - store.append_to_multiple( - { - "index": ["IX"], - "nums": ["Num", "BigNum"], - "strs": ["Str", "LongStr"], - }, - df.iloc[[0]], - "index", - min_itemsize={"Str": 10, "LongStr": 100, "Num": 2}, - ) - result = store.select_as_multiple(["index", "nums", "strs"]) - tm.assert_frame_equal(result, expected) - - def test_select_as_multiple(self, setup_path): - - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) - df2["foo"] = "bar" - - with ensure_clean_store(setup_path) as store: - - msg = "keys must be a list/tuple" - # no tables stored - with pytest.raises(TypeError, match=msg): - store.select_as_multiple(None, where=["A>0", "B>0"], selector="df1") - - store.append("df1", df1, data_columns=["A", "B"]) - store.append("df2", df2) - - # exceptions - with pytest.raises(TypeError, match=msg): - store.select_as_multiple(None, where=["A>0", "B>0"], selector="df1") - - with pytest.raises(TypeError, match=msg): - store.select_as_multiple([None], where=["A>0", "B>0"], selector="df1") - - msg = "'No object named df3 in the file'" - with pytest.raises(KeyError, match=msg): - store.select_as_multiple( - ["df1", "df3"], where=["A>0", "B>0"], selector="df1" - ) - - with pytest.raises(KeyError, match=msg): - store.select_as_multiple(["df3"], where=["A>0", "B>0"], selector="df1") - - with pytest.raises(KeyError, match="'No object named df4 in the file'"): - store.select_as_multiple( - ["df1", "df2"], where=["A>0", "B>0"], selector="df4" - ) - - # default select - result = store.select("df1", ["A>0", "B>0"]) - expected = store.select_as_multiple( - ["df1"], where=["A>0", "B>0"], selector="df1" - ) - tm.assert_frame_equal(result, expected) - expected = store.select_as_multiple( - "df1", where=["A>0", "B>0"], selector="df1" - ) - tm.assert_frame_equal(result, expected) - - # multiple - result = store.select_as_multiple( - ["df1", "df2"], where=["A>0", "B>0"], selector="df1" - ) - expected = concat([df1, df2], axis=1) - expected = expected[(expected.A > 0) & (expected.B > 0)] - tm.assert_frame_equal(result, expected) - - # multiple (diff selector) - result = store.select_as_multiple( - ["df1", "df2"], where="index>df2.index[4]", selector="df2" - ) - expected = concat([df1, df2], axis=1) - expected = expected[5:] - tm.assert_frame_equal(result, expected) - - # test exception for diff rows - store.append("df3", tm.makeTimeDataFrame(nper=50)) - msg = "all tables must have exactly the same nrows!" - with pytest.raises(ValueError, match=msg): - store.select_as_multiple( - ["df1", "df3"], where=["A>0", "B>0"], selector="df1" - ) - - @pytest.mark.skipif( - LooseVersion(tables.__version__) < LooseVersion("3.1.0"), - reason=("tables version does not support fix for nan selection bug: GH 4858"), - ) - def test_nan_selection_bug_4858(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - df = DataFrame({"cols": range(6), "values": range(6)}, dtype="float64") - df["cols"] = (df["cols"] + 10).apply(str) - df.iloc[0] = np.nan - - expected = DataFrame( - {"cols": ["13.0", "14.0", "15.0"], "values": [3.0, 4.0, 5.0]}, - index=[3, 4, 5], - ) - - # write w/o the index on that particular column - store.append("df", df, data_columns=True, index=["cols"]) - result = store.select("df", where="values>2.0") - tm.assert_frame_equal(result, expected) - - def test_start_stop_table(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - # table - df = DataFrame({"A": np.random.rand(20), "B": np.random.rand(20)}) - store.append("df", df) - - result = store.select("df", "columns=['A']", start=0, stop=5) - expected = df.loc[0:4, ["A"]] - tm.assert_frame_equal(result, expected) - - # out of range - result = store.select("df", "columns=['A']", start=30, stop=40) - assert len(result) == 0 - expected = df.loc[30:40, ["A"]] - tm.assert_frame_equal(result, expected) - - def test_start_stop_multiple(self, setup_path): - - # GH 16209 - with ensure_clean_store(setup_path) as store: - - df = DataFrame({"foo": [1, 2], "bar": [1, 2]}) - - store.append_to_multiple( - {"selector": ["foo"], "data": None}, df, selector="selector" - ) - result = store.select_as_multiple( - ["selector", "data"], selector="selector", start=0, stop=1 - ) - expected = df.loc[[0], ["foo", "bar"]] - tm.assert_frame_equal(result, expected) + types_should_fail = [ + tm.makeIntIndex, + tm.makeFloatIndex, + tm.makeDateIndex, + tm.makeTimedeltaIndex, + tm.makePeriodIndex, + ] + types_should_run = [ + tm.makeStringIndex, + tm.makeCategoricalIndex, + tm.makeUnicodeIndex, + ] - def test_start_stop_fixed(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - # fixed, GH 8287 - df = DataFrame( - {"A": np.random.rand(20), "B": np.random.rand(20)}, - index=pd.date_range("20130101", periods=20), - ) - store.put("df", df) - - result = store.select("df", start=0, stop=5) - expected = df.iloc[0:5, :] - tm.assert_frame_equal(result, expected) - - result = store.select("df", start=5, stop=10) - expected = df.iloc[5:10, :] - tm.assert_frame_equal(result, expected) - - # out of range - result = store.select("df", start=30, stop=40) - expected = df.iloc[30:40, :] - tm.assert_frame_equal(result, expected) - - # series - s = df.A - store.put("s", s) - result = store.select("s", start=0, stop=5) - expected = s.iloc[0:5] - tm.assert_series_equal(result, expected) - - result = store.select("s", start=5, stop=10) - expected = s.iloc[5:10] - tm.assert_series_equal(result, expected) - - # sparse; not implemented - df = tm.makeDataFrame() - df.iloc[3:5, 1:3] = np.nan - df.iloc[8:10, -2] = np.nan - - def test_select_filter_corner(self, setup_path): - - df = DataFrame(np.random.randn(50, 100)) - df.index = [f"{c:3d}" for c in df.index] - df.columns = [f"{c:3d}" for c in df.columns] - - with ensure_clean_store(setup_path) as store: - store.put("frame", df, format="table") - - crit = "columns=df.columns[:75]" - result = store.select("frame", [crit]) - tm.assert_frame_equal(result, df.loc[:, df.columns[:75]]) - - crit = "columns=df.columns[:75:2]" - result = store.select("frame", [crit]) - tm.assert_frame_equal(result, df.loc[:, df.columns[:75:2]]) - - def test_path_pathlib(self, setup_path): - df = tm.makeDataFrame() - - result = tm.round_trip_pathlib( - lambda p: df.to_hdf(p, "df"), lambda p: pd.read_hdf(p, "df") - ) - tm.assert_frame_equal(df, result) - - @pytest.mark.parametrize("start, stop", [(0, 2), (1, 2), (None, None)]) - def test_contiguous_mixed_data_table(self, start, stop, setup_path): - # GH 17021 - # ValueError when reading a contiguous mixed-data table ft. VLArray - df = DataFrame( - { - "a": Series([20111010, 20111011, 20111012]), - "b": Series(["ab", "cd", "ab"]), - } - ) - - with ensure_clean_store(setup_path) as store: - store.append("test_dataset", df) - - result = store.select("test_dataset", start=start, stop=stop) - tm.assert_frame_equal(df[start:stop], result) - - def test_path_pathlib_hdfstore(self, setup_path): - df = tm.makeDataFrame() - - def writer(path): - with HDFStore(path) as store: - df.to_hdf(store, "df") - - def reader(path): - with HDFStore(path) as store: - return pd.read_hdf(store, "df") - - result = tm.round_trip_pathlib(writer, reader) - tm.assert_frame_equal(df, result) - - def test_pickle_path_localpath(self, setup_path): - df = tm.makeDataFrame() - result = tm.round_trip_pathlib( - lambda p: df.to_hdf(p, "df"), lambda p: pd.read_hdf(p, "df") - ) - tm.assert_frame_equal(df, result) - - def test_path_localpath_hdfstore(self, setup_path): - df = tm.makeDataFrame() - - def writer(path): - with HDFStore(path) as store: - df.to_hdf(store, "df") - - def reader(path): - with HDFStore(path) as store: - return pd.read_hdf(store, "df") - - result = tm.round_trip_localpath(writer, reader) - tm.assert_frame_equal(df, result) - - def _check_roundtrip(self, obj, comparator, path, compression=False, **kwargs): - - options = {} - if compression: - options["complib"] = _default_compressor - - with ensure_clean_store(path, "w", **options) as store: - store["obj"] = obj - retrieved = store["obj"] - comparator(retrieved, obj, **kwargs) - - def _check_double_roundtrip( - self, obj, comparator, path, compression=False, **kwargs - ): - options = {} - if compression: - options["complib"] = compression or _default_compressor - - with ensure_clean_store(path, "w", **options) as store: - store["obj"] = obj - retrieved = store["obj"] - comparator(retrieved, obj, **kwargs) - store["obj"] = retrieved - again = store["obj"] - comparator(again, obj, **kwargs) - - def _check_roundtrip_table(self, obj, comparator, path, compression=False): - options = {} - if compression: - options["complib"] = _default_compressor - - with ensure_clean_store(path, "w", **options) as store: - store.put("obj", obj, format="table") - retrieved = store["obj"] - - comparator(retrieved, obj) - - def test_multiple_open_close(self, setup_path): - # gh-4409: open & close multiple times - - with ensure_clean_path(setup_path) as path: - - df = tm.makeDataFrame() - df.to_hdf(path, "df", mode="w", format="table") - - # single - store = HDFStore(path) - assert "CLOSED" not in store.info() - assert store.is_open - - store.close() - assert "CLOSED" in store.info() - assert not store.is_open - - with ensure_clean_path(setup_path) as path: - - if pytables._table_file_open_policy_is_strict: - # multiples - store1 = HDFStore(path) - msg = ( - r"The file [\S]* is already opened\. Please close it before " - r"reopening in write mode\." - ) - with pytest.raises(ValueError, match=msg): - HDFStore(path) - - store1.close() - else: - - # multiples - store1 = HDFStore(path) - store2 = HDFStore(path) - - assert "CLOSED" not in store1.info() - assert "CLOSED" not in store2.info() - assert store1.is_open - assert store2.is_open - - store1.close() - assert "CLOSED" in store1.info() - assert not store1.is_open - assert "CLOSED" not in store2.info() - assert store2.is_open - - store2.close() - assert "CLOSED" in store1.info() - assert "CLOSED" in store2.info() - assert not store1.is_open - assert not store2.is_open - - # nested close - store = HDFStore(path, mode="w") - store.append("df", df) - - store2 = HDFStore(path) - store2.append("df2", df) - store2.close() - assert "CLOSED" in store2.info() - assert not store2.is_open - - store.close() - assert "CLOSED" in store.info() - assert not store.is_open - - # double closing - store = HDFStore(path, mode="w") - store.append("df", df) - - store2 = HDFStore(path) - store.close() - assert "CLOSED" in store.info() - assert not store.is_open - - store2.close() - assert "CLOSED" in store2.info() - assert not store2.is_open - - # ops on a closed store + for index in types_should_fail: + df = DataFrame(np.random.randn(10, 2), columns=index(2)) with ensure_clean_path(setup_path) as path: - - df = tm.makeDataFrame() - df.to_hdf(path, "df", mode="w", format="table") - - store = HDFStore(path) - store.close() - - msg = r"[\S]* file is not open!" - with pytest.raises(ClosedFileError, match=msg): - store.keys() - - with pytest.raises(ClosedFileError, match=msg): - "df" in store - - with pytest.raises(ClosedFileError, match=msg): - len(store) - - with pytest.raises(ClosedFileError, match=msg): - store["df"] - - with pytest.raises(ClosedFileError, match=msg): - store.select("df") - - with pytest.raises(ClosedFileError, match=msg): - store.get("df") - - with pytest.raises(ClosedFileError, match=msg): - store.append("df2", df) - - with pytest.raises(ClosedFileError, match=msg): - store.put("df3", df) - - with pytest.raises(ClosedFileError, match=msg): - store.get_storer("df2") - - with pytest.raises(ClosedFileError, match=msg): - store.remove("df2") - - with pytest.raises(ClosedFileError, match=msg): - store.select("df") - - msg = "'HDFStore' object has no attribute 'df'" - with pytest.raises(AttributeError, match=msg): - store.df - - def test_pytables_native_read(self, datapath, setup_path): - with ensure_clean_store( - datapath("io", "data", "legacy_hdf/pytables_native.h5"), mode="r" - ) as store: - d2 = store["detector/readout"] - assert isinstance(d2, DataFrame) - - @pytest.mark.skipif( - is_platform_windows(), reason="native2 read fails oddly on windows" - ) - def test_pytables_native2_read(self, datapath, setup_path): - with ensure_clean_store( - datapath("io", "data", "legacy_hdf", "pytables_native2.h5"), mode="r" - ) as store: - str(store) - d1 = store["detector"] - assert isinstance(d1, DataFrame) - - def test_legacy_table_fixed_format_read_py2(self, datapath, setup_path): - # GH 24510 - # legacy table with fixed format written in Python 2 - with ensure_clean_store( - datapath("io", "data", "legacy_hdf", "legacy_table_fixed_py2.h5"), mode="r" - ) as store: - result = store.select("df") - expected = DataFrame( - [[1, 2, 3, "D"]], - columns=["A", "B", "C", "D"], - index=Index(["ABC"], name="INDEX_NAME"), - ) - tm.assert_frame_equal(expected, result) - - def test_legacy_table_fixed_format_read_datetime_py2(self, datapath, setup_path): - # GH 31750 - # legacy table with fixed format and datetime64 column written in Python 2 - with ensure_clean_store( - datapath("io", "data", "legacy_hdf", "legacy_table_fixed_datetime_py2.h5"), - mode="r", - ) as store: - result = store.select("df") - expected = DataFrame( - [[Timestamp("2020-02-06T18:00")]], - columns=["A"], - index=Index(["date"]), - ) - tm.assert_frame_equal(expected, result) - - def test_legacy_table_read_py2(self, datapath, setup_path): - # issue: 24925 - # legacy table written in Python 2 - with ensure_clean_store( - datapath("io", "data", "legacy_hdf", "legacy_table_py2.h5"), mode="r" - ) as store: - result = store.select("table") - - expected = DataFrame({"a": ["a", "b"], "b": [2, 3]}) - tm.assert_frame_equal(expected, result) - - def test_copy(self, setup_path): - - with catch_warnings(record=True): - - def do_copy(f, new_f=None, keys=None, propindexes=True, **kwargs): - try: - store = HDFStore(f, "r") - - if new_f is None: - import tempfile - - fd, new_f = tempfile.mkstemp() - tstore = store.copy( - new_f, keys=keys, propindexes=propindexes, **kwargs - ) - - # check keys - if keys is None: - keys = store.keys() - assert set(keys) == set(tstore.keys()) - - # check indices & nrows - for k in tstore.keys(): - if tstore.get_storer(k).is_table: - new_t = tstore.get_storer(k) - orig_t = store.get_storer(k) - - assert orig_t.nrows == new_t.nrows - - # check propindixes - if propindexes: - for a in orig_t.axes: - if a.is_indexed: - assert new_t[a.name].is_indexed - - finally: - safe_close(store) - safe_close(tstore) - try: - os.close(fd) - except (OSError, ValueError): - pass - os.remove(new_f) - - # new table - df = tm.makeDataFrame() - - with tm.ensure_clean() as path: - st = HDFStore(path) - st.append("df", df, data_columns=["A"]) - st.close() - do_copy(f=path) - do_copy(f=path, propindexes=False) - - def test_store_datetime_fractional_secs(self, setup_path): - - with ensure_clean_store(setup_path) as store: - dt = datetime.datetime(2012, 1, 2, 3, 4, 5, 123456) - series = Series([0], [dt]) - store["a"] = series - assert store["a"].index[0] == dt - - def test_tseries_indices_series(self, setup_path): - - with ensure_clean_store(setup_path) as store: - idx = tm.makeDateIndex(10) - ser = Series(np.random.randn(len(idx)), idx) - store["a"] = ser - result = store["a"] - - tm.assert_series_equal(result, ser) - assert result.index.freq == ser.index.freq - tm.assert_class_equal(result.index, ser.index, obj="series index") - - idx = tm.makePeriodIndex(10) - ser = Series(np.random.randn(len(idx)), idx) - store["a"] = ser - result = store["a"] - - tm.assert_series_equal(result, ser) - assert result.index.freq == ser.index.freq - tm.assert_class_equal(result.index, ser.index, obj="series index") - - def test_tseries_indices_frame(self, setup_path): - - with ensure_clean_store(setup_path) as store: - idx = tm.makeDateIndex(10) - df = DataFrame(np.random.randn(len(idx), 3), index=idx) - store["a"] = df - result = store["a"] - - tm.assert_frame_equal(result, df) - assert result.index.freq == df.index.freq - tm.assert_class_equal(result.index, df.index, obj="dataframe index") - - idx = tm.makePeriodIndex(10) - df = DataFrame(np.random.randn(len(idx), 3), idx) - store["a"] = df - result = store["a"] - - tm.assert_frame_equal(result, df) - assert result.index.freq == df.index.freq - tm.assert_class_equal(result.index, df.index, obj="dataframe index") - - def test_unicode_index(self, setup_path): - - unicode_values = ["\u03c3", "\u03c3\u03c3"] - - # PerformanceWarning - with catch_warnings(record=True): - simplefilter("ignore", pd.errors.PerformanceWarning) - s = Series(np.random.randn(len(unicode_values)), unicode_values) - self._check_roundtrip(s, tm.assert_series_equal, path=setup_path) - - def test_unicode_longer_encoded(self, setup_path): - # GH 11234 - char = "\u0394" - df = DataFrame({"A": [char]}) - with ensure_clean_store(setup_path) as store: - store.put("df", df, format="table", encoding="utf-8") - result = store.get("df") - tm.assert_frame_equal(result, df) - - df = DataFrame({"A": ["a", char], "B": ["b", "b"]}) - with ensure_clean_store(setup_path) as store: - store.put("df", df, format="table", encoding="utf-8") - result = store.get("df") - tm.assert_frame_equal(result, df) - - def test_store_datetime_mixed(self, setup_path): - - df = DataFrame({"a": [1, 2, 3], "b": [1.0, 2.0, 3.0], "c": ["a", "b", "c"]}) - ts = tm.makeTimeSeries() - df["d"] = ts.index[:3] - self._check_roundtrip(df, tm.assert_frame_equal, path=setup_path) - - # FIXME: don't leave commented-out code - # def test_cant_write_multiindex_table(self): - # # for now, #1848 - # df = DataFrame(np.random.randn(10, 4), - # index=[np.arange(5).repeat(2), - # np.tile(np.arange(2), 5)]) - # - # with pytest.raises(Exception): - # store.put('foo', df, format='table') - - def test_append_with_diff_col_name_types_raises_value_error(self, setup_path): - df = DataFrame(np.random.randn(10, 1)) - df2 = DataFrame({"a": np.random.randn(10)}) - df3 = DataFrame({(1, 2): np.random.randn(10)}) - df4 = DataFrame({("1", 2): np.random.randn(10)}) - df5 = DataFrame({("1", 2, object): np.random.randn(10)}) - - with ensure_clean_store(setup_path) as store: - name = f"df_{tm.rands(10)}" - store.append(name, df) - - for d in (df2, df3, df4, df5): - msg = re.escape( - "cannot match existing table structure for [0] on appending data" - ) + with catch_warnings(record=True): + msg = "cannot have non-object label DataIndexableCol" with pytest.raises(ValueError, match=msg): - store.append(name, d) - - def test_query_with_nested_special_character(self, setup_path): - df = DataFrame( - { - "a": ["a", "a", "c", "b", "test & test", "c", "b", "e"], - "b": [1, 2, 3, 4, 5, 6, 7, 8], - } - ) - expected = df[df.a == "test & test"] - with ensure_clean_store(setup_path) as store: - store.append("test", df, format="table", data_columns=True) - result = store.select("test", 'a = "test & test"') - tm.assert_frame_equal(expected, result) - - def test_categorical(self, setup_path): - - with ensure_clean_store(setup_path) as store: - - # Basic - _maybe_remove(store, "s") - s = Series( - Categorical( - ["a", "b", "b", "a", "a", "c"], - categories=["a", "b", "c", "d"], - ordered=False, - ) - ) - store.append("s", s, format="table") - result = store.select("s") - tm.assert_series_equal(s, result) - - _maybe_remove(store, "s_ordered") - s = Series( - Categorical( - ["a", "b", "b", "a", "a", "c"], - categories=["a", "b", "c", "d"], - ordered=True, - ) - ) - store.append("s_ordered", s, format="table") - result = store.select("s_ordered") - tm.assert_series_equal(s, result) - - _maybe_remove(store, "df") - df = DataFrame({"s": s, "vals": [1, 2, 3, 4, 5, 6]}) - store.append("df", df, format="table") - result = store.select("df") - tm.assert_frame_equal(result, df) - - # Dtypes - _maybe_remove(store, "si") - s = Series([1, 1, 2, 2, 3, 4, 5]).astype("category") - store.append("si", s) - result = store.select("si") - tm.assert_series_equal(result, s) - - _maybe_remove(store, "si2") - s = Series([1, 1, np.nan, 2, 3, 4, 5]).astype("category") - store.append("si2", s) - result = store.select("si2") - tm.assert_series_equal(result, s) - - # Multiple - _maybe_remove(store, "df2") - df2 = df.copy() - df2["s2"] = Series(list("abcdefg")).astype("category") - store.append("df2", df2) - result = store.select("df2") - tm.assert_frame_equal(result, df2) - - # Make sure the metadata is OK - info = store.info() - assert "/df2 " in info - # assert '/df2/meta/values_block_0/meta' in info - assert "/df2/meta/values_block_1/meta" in info - - # unordered - _maybe_remove(store, "s2") - s = Series( - Categorical( - ["a", "b", "b", "a", "a", "c"], - categories=["a", "b", "c", "d"], - ordered=False, - ) - ) - store.append("s2", s, format="table") - result = store.select("s2") - tm.assert_series_equal(result, s) - - # Query - _maybe_remove(store, "df3") - store.append("df3", df, data_columns=["s"]) - expected = df[df.s.isin(["b", "c"])] - result = store.select("df3", where=['s in ["b","c"]']) - tm.assert_frame_equal(result, expected) - - expected = df[df.s.isin(["b", "c"])] - result = store.select("df3", where=['s = ["b","c"]']) - tm.assert_frame_equal(result, expected) - - expected = df[df.s.isin(["d"])] - result = store.select("df3", where=['s in ["d"]']) - tm.assert_frame_equal(result, expected) - - expected = df[df.s.isin(["f"])] - result = store.select("df3", where=['s in ["f"]']) - tm.assert_frame_equal(result, expected) - - # Appending with same categories is ok - store.append("df3", df) - - df = concat([df, df]) - expected = df[df.s.isin(["b", "c"])] - result = store.select("df3", where=['s in ["b","c"]']) - tm.assert_frame_equal(result, expected) - - # Appending must have the same categories - df3 = df.copy() - df3["s"] = df3["s"].cat.remove_unused_categories() - - msg = ( - "cannot append a categorical with different categories to the existing" - ) - with pytest.raises(ValueError, match=msg): - store.append("df3", df3) - - # Remove, and make sure meta data is removed (its a recursive - # removal so should be). - result = store.select("df3/meta/s/meta") - assert result is not None - store.remove("df3") - - with pytest.raises( - KeyError, match="'No object named df3/meta/s/meta in the file'" - ): - store.select("df3/meta/s/meta") - - def test_categorical_conversion(self, setup_path): - - # GH13322 - # Check that read_hdf with categorical columns doesn't return rows if - # where criteria isn't met. - obsids = ["ESP_012345_6789", "ESP_987654_3210"] - imgids = ["APF00006np", "APF0001imm"] - data = [4.3, 9.8] - - # Test without categories - df = DataFrame({"obsids": obsids, "imgids": imgids, "data": data}) - - # We are expecting an empty DataFrame matching types of df - expected = df.iloc[[], :] - with ensure_clean_path(setup_path) as path: - df.to_hdf(path, "df", format="table", data_columns=True) - result = read_hdf(path, "df", where="obsids=B") - tm.assert_frame_equal(result, expected) - - # Test with categories - df.obsids = df.obsids.astype("category") - df.imgids = df.imgids.astype("category") - - # We are expecting an empty DataFrame matching types of df - expected = df.iloc[[], :] - with ensure_clean_path(setup_path) as path: - df.to_hdf(path, "df", format="table", data_columns=True) - result = read_hdf(path, "df", where="obsids=B") - tm.assert_frame_equal(result, expected) - - def test_categorical_nan_only_columns(self, setup_path): - # GH18413 - # Check that read_hdf with categorical columns with NaN-only values can - # be read back. - df = DataFrame( - { - "a": ["a", "b", "c", np.nan], - "b": [np.nan, np.nan, np.nan, np.nan], - "c": [1, 2, 3, 4], - "d": Series([None] * 4, dtype=object), - } - ) - df["a"] = df.a.astype("category") - df["b"] = df.b.astype("category") - df["d"] = df.b.astype("category") - expected = df - with ensure_clean_path(setup_path) as path: - df.to_hdf(path, "df", format="table", data_columns=True) - result = read_hdf(path, "df") - tm.assert_frame_equal(result, expected) - - def test_duplicate_column_name(self, setup_path): - df = DataFrame(columns=["a", "a"], data=[[0, 0]]) - - with ensure_clean_path(setup_path) as path: - msg = "Columns index has to be unique for fixed format" - with pytest.raises(ValueError, match=msg): - df.to_hdf(path, "df", format="fixed") - - df.to_hdf(path, "df", format="table") - other = read_hdf(path, "df") - - tm.assert_frame_equal(df, other) - assert df.equals(other) - assert other.equals(df) - - def test_round_trip_equals(self, setup_path): - # GH 9330 - df = DataFrame({"B": [1, 2], "A": ["x", "y"]}) - - with ensure_clean_path(setup_path) as path: - df.to_hdf(path, "df", format="table") - other = read_hdf(path, "df") - tm.assert_frame_equal(df, other) - assert df.equals(other) - assert other.equals(df) - - def test_preserve_timedeltaindex_type(self, setup_path): - # GH9635 - # Storing TimedeltaIndexed DataFrames in fixed stores did not preserve - # the type of the index. - df = DataFrame(np.random.normal(size=(10, 5))) - df.index = timedelta_range(start="0s", periods=10, freq="1s", name="example") - - with ensure_clean_store(setup_path) as store: - - store["df"] = df - tm.assert_frame_equal(store["df"], df) - - def test_columns_multiindex_modified(self, setup_path): - # BUG: 7212 - # read_hdf store.select modified the passed columns parameters - # when multi-indexed. - - df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) - df.index.name = "letters" - df = df.set_index(keys="E", append=True) - - data_columns = df.index.names + df.columns.tolist() - with ensure_clean_path(setup_path) as path: - df.to_hdf( - path, - "df", - mode="a", - append=True, - data_columns=data_columns, - index=False, - ) - cols2load = list("BCD") - cols2load_original = list(cols2load) - df_loaded = read_hdf(path, "df", columns=cols2load) # noqa - assert cols2load_original == cols2load - - @ignore_natural_naming_warning - def test_to_hdf_with_object_column_names(self, setup_path): - # GH9057 - # Writing HDF5 table format should only work for string-like - # column types - - types_should_fail = [ - tm.makeIntIndex, - tm.makeFloatIndex, - tm.makeDateIndex, - tm.makeTimedeltaIndex, - tm.makePeriodIndex, - ] - types_should_run = [ - tm.makeStringIndex, - tm.makeCategoricalIndex, - tm.makeUnicodeIndex, - ] - - for index in types_should_fail: - df = DataFrame(np.random.randn(10, 2), columns=index(2)) - with ensure_clean_path(setup_path) as path: - with catch_warnings(record=True): - msg = "cannot have non-object label DataIndexableCol" - with pytest.raises(ValueError, match=msg): - df.to_hdf(path, "df", format="table", data_columns=True) - - for index in types_should_run: - df = DataFrame(np.random.randn(10, 2), columns=index(2)) - with ensure_clean_path(setup_path) as path: - with catch_warnings(record=True): df.to_hdf(path, "df", format="table", data_columns=True) - result = pd.read_hdf(path, "df", where=f"index = [{df.index[0]}]") - assert len(result) - - def test_read_hdf_open_store(self, setup_path): - # GH10330 - # No check for non-string path_or-buf, and no test of open store - df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) - df.index.name = "letters" - df = df.set_index(keys="E", append=True) - - with ensure_clean_path(setup_path) as path: - df.to_hdf(path, "df", mode="w") - direct = read_hdf(path, "df") - store = HDFStore(path, mode="r") - indirect = read_hdf(store, "df") - tm.assert_frame_equal(direct, indirect) - assert store.is_open - store.close() - - def test_read_hdf_iterator(self, setup_path): - df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) - df.index.name = "letters" - df = df.set_index(keys="E", append=True) - - with ensure_clean_path(setup_path) as path: - df.to_hdf(path, "df", mode="w", format="t") - direct = read_hdf(path, "df") - iterator = read_hdf(path, "df", iterator=True) - assert isinstance(iterator, TableIterator) - indirect = next(iterator.__iter__()) - tm.assert_frame_equal(direct, indirect) - iterator.store.close() - - def test_read_hdf_errors(self, setup_path): - df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) - - with ensure_clean_path(setup_path) as path: - msg = r"File [\S]* does not exist" - with pytest.raises(IOError, match=msg): - read_hdf(path, "key") - - df.to_hdf(path, "df") - store = HDFStore(path, mode="r") - store.close() - - msg = "The HDFStore must be open for reading." - with pytest.raises(IOError, match=msg): - read_hdf(store, "df") - - def test_read_hdf_generic_buffer_errors(self): - msg = "Support for generic buffers has not been implemented." - with pytest.raises(NotImplementedError, match=msg): - read_hdf(BytesIO(b""), "df") - - def test_invalid_complib(self, setup_path): - df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) - with tm.ensure_clean(setup_path) as path: - msg = r"complib only supports \[.*\] compression." - with pytest.raises(ValueError, match=msg): - df.to_hdf(path, "df", complib="foolib") - - # GH10443 - - def test_read_nokey(self, setup_path): - df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) - - # Categorical dtype not supported for "fixed" format. So no need - # to test with that dtype in the dataframe here. - with ensure_clean_path(setup_path) as path: - df.to_hdf(path, "df", mode="a") - reread = read_hdf(path) - tm.assert_frame_equal(df, reread) - df.to_hdf(path, "df2", mode="a") - - msg = "key must be provided when HDF5 file contains multiple datasets." - with pytest.raises(ValueError, match=msg): - read_hdf(path) - - def test_read_nokey_table(self, setup_path): - # GH13231 - df = DataFrame({"i": range(5), "c": Series(list("abacd"), dtype="category")}) - - with ensure_clean_path(setup_path) as path: - df.to_hdf(path, "df", mode="a", format="table") - reread = read_hdf(path) - tm.assert_frame_equal(df, reread) - df.to_hdf(path, "df2", mode="a", format="table") - - msg = "key must be provided when HDF5 file contains multiple datasets." - with pytest.raises(ValueError, match=msg): - read_hdf(path) - - def test_read_nokey_empty(self, setup_path): - with ensure_clean_path(setup_path) as path: - store = HDFStore(path) - store.close() - msg = re.escape( - "Dataset(s) incompatible with Pandas data types, not table, or no " - "datasets found in HDF5 file." - ) - with pytest.raises(ValueError, match=msg): - read_hdf(path) - - def test_read_from_pathlib_path(self, setup_path): - - # GH11773 - expected = DataFrame( - np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE") - ) - with ensure_clean_path(setup_path) as filename: - path_obj = Path(filename) - expected.to_hdf(path_obj, "df", mode="a") - actual = read_hdf(path_obj, "df") - - tm.assert_frame_equal(expected, actual) - - @td.skip_if_no("py.path") - def test_read_from_py_localpath(self, setup_path): - - # GH11773 - from py.path import local as LocalPath - - expected = DataFrame( - np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE") - ) - with ensure_clean_path(setup_path) as filename: - path_obj = LocalPath(filename) - - expected.to_hdf(path_obj, "df", mode="a") - actual = read_hdf(path_obj, "df") - - tm.assert_frame_equal(expected, actual) - - def test_query_long_float_literal(self, setup_path): - # GH 14241 - df = DataFrame({"A": [1000000000.0009, 1000000000.0011, 1000000000.0015]}) - - with ensure_clean_store(setup_path) as store: - store.append("test", df, format="table", data_columns=True) - - cutoff = 1000000000.0006 - result = store.select("test", f"A < {cutoff:.4f}") - assert result.empty - - cutoff = 1000000000.0010 - result = store.select("test", f"A > {cutoff:.4f}") - expected = df.loc[[1, 2], :] - tm.assert_frame_equal(expected, result) - - exact = 1000000000.0011 - result = store.select("test", f"A == {exact:.4f}") - expected = df.loc[[1], :] - tm.assert_frame_equal(expected, result) - - def test_query_compare_column_type(self, setup_path): - # GH 15492 - df = DataFrame( - { - "date": ["2014-01-01", "2014-01-02"], - "real_date": date_range("2014-01-01", periods=2), - "float": [1.1, 1.2], - "int": [1, 2], - }, - columns=["date", "real_date", "float", "int"], - ) - - with ensure_clean_store(setup_path) as store: - store.append("test", df, format="table", data_columns=True) - - ts = Timestamp("2014-01-01") # noqa - result = store.select("test", where="real_date > ts") - expected = df.loc[[1], :] - tm.assert_frame_equal(expected, result) - - for op in ["<", ">", "=="]: - # non strings to string column always fail - for v in [2.1, True, Timestamp("2014-01-01"), pd.Timedelta(1, "s")]: - query = f"date {op} v" - msg = f"Cannot compare {v} of type {type(v)} to string column" - with pytest.raises(TypeError, match=msg): - store.select("test", where=query) - - # strings to other columns must be convertible to type - v = "a" - for col in ["int", "float", "real_date"]: - query = f"{col} {op} v" - msg = "could not convert string to " - with pytest.raises(ValueError, match=msg): - store.select("test", where=query) - - for v, col in zip( - ["1", "1.1", "2014-01-01"], ["int", "float", "real_date"] - ): - query = f"{col} {op} v" - result = store.select("test", where=query) - - if op == "==": - expected = df.loc[[0], :] - elif op == ">": - expected = df.loc[[1], :] - else: - expected = df.loc[[], :] - tm.assert_frame_equal(expected, result) - - @pytest.mark.parametrize("format", ["fixed", "table"]) - def test_read_hdf_series_mode_r(self, format, setup_path): - # GH 16583 - # Tests that reading a Series saved to an HDF file - # still works if a mode='r' argument is supplied - series = tm.makeFloatSeries() - with ensure_clean_path(setup_path) as path: - series.to_hdf(path, key="data", format=format) - result = pd.read_hdf(path, key="data", mode="r") - tm.assert_series_equal(result, series) - - def test_fspath(self): - with tm.ensure_clean("foo.h5") as path: - with HDFStore(path) as store: - assert os.fspath(store) == str(path) - - def test_read_py2_hdf_file_in_py3(self, datapath): - # GH 16781 - - # tests reading a PeriodIndex DataFrame written in Python2 in Python3 - - # the file was generated in Python 2.7 like so: - # - # df = DataFrame([1.,2,3], index=pd.PeriodIndex( - # ['2015-01-01', '2015-01-02', '2015-01-05'], freq='B')) - # df.to_hdf('periodindex_0.20.1_x86_64_darwin_2.7.13.h5', 'p') - - expected = DataFrame( - [1.0, 2, 3], - index=pd.PeriodIndex(["2015-01-01", "2015-01-02", "2015-01-05"], freq="B"), - ) - - with ensure_clean_store( - datapath( - "io", "data", "legacy_hdf", "periodindex_0.20.1_x86_64_darwin_2.7.13.h5" - ), - mode="r", - ) as store: - result = store["p"] - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("where", ["", (), (None,), [], [None]]) - def test_select_empty_where(self, where): - # GH26610 - - # Using keyword `where` as '' or (), or [None], etc - # while reading from HDF store raises - # "SyntaxError: only a single expression is allowed" - - df = DataFrame([1, 2, 3]) - with ensure_clean_path("empty_where.h5") as path: - with HDFStore(path) as store: - store.put("df", df, "t") - result = pd.read_hdf(store, "df", where=where) - tm.assert_frame_equal(result, df) - - @pytest.mark.parametrize( - "idx", - [ - date_range("2019", freq="D", periods=3, tz="UTC"), - CategoricalIndex(list("abc")), - ], - ) - def test_to_hdf_multiindex_extension_dtype(self, idx, setup_path): - # GH 7775 - mi = MultiIndex.from_arrays([idx, idx]) - df = DataFrame(0, index=mi, columns=["a"]) + for index in types_should_run: + df = DataFrame(np.random.randn(10, 2), columns=index(2)) with ensure_clean_path(setup_path) as path: - with pytest.raises(NotImplementedError, match="Saving a MultiIndex"): - df.to_hdf(path, "df") - - def test_unsuppored_hdf_file_error(self, datapath): - # GH 9539 - data_path = datapath("io", "data", "legacy_hdf/incompatible_dataset.h5") - message = ( - r"Dataset\(s\) incompatible with Pandas data types, " - "not table, or no datasets found in HDF5 file." - ) - - with pytest.raises(ValueError, match=message): - pd.read_hdf(data_path) - - -@pytest.mark.parametrize("bad_version", [(1, 2), (1,), [], "12", "123"]) -def test_maybe_adjust_name_bad_version_raises(bad_version): - msg = "Version is incorrect, expected sequence of 3 integers" - with pytest.raises(ValueError, match=msg): - _maybe_adjust_name("values_block_0", version=bad_version) + with catch_warnings(record=True): + df.to_hdf(path, "df", format="table", data_columns=True) + result = pd.read_hdf(path, "df", where=f"index = [{df.index[0]}]") + assert len(result) diff --git a/pandas/tests/io/pytables/test_time_series.py b/pandas/tests/io/pytables/test_time_series.py new file mode 100644 index 0000000000000..d98ae7c599c52 --- /dev/null +++ b/pandas/tests/io/pytables/test_time_series.py @@ -0,0 +1,62 @@ +import datetime + +import numpy as np +import pytest + +from pandas import DataFrame, Series, _testing as tm +from pandas.tests.io.pytables.common import ensure_clean_store + +pytestmark = pytest.mark.single + + +def test_store_datetime_fractional_secs(setup_path): + + with ensure_clean_store(setup_path) as store: + dt = datetime.datetime(2012, 1, 2, 3, 4, 5, 123456) + series = Series([0], [dt]) + store["a"] = series + assert store["a"].index[0] == dt + + +def test_tseries_indices_series(setup_path): + + with ensure_clean_store(setup_path) as store: + idx = tm.makeDateIndex(10) + ser = Series(np.random.randn(len(idx)), idx) + store["a"] = ser + result = store["a"] + + tm.assert_series_equal(result, ser) + assert result.index.freq == ser.index.freq + tm.assert_class_equal(result.index, ser.index, obj="series index") + + idx = tm.makePeriodIndex(10) + ser = Series(np.random.randn(len(idx)), idx) + store["a"] = ser + result = store["a"] + + tm.assert_series_equal(result, ser) + assert result.index.freq == ser.index.freq + tm.assert_class_equal(result.index, ser.index, obj="series index") + + +def test_tseries_indices_frame(setup_path): + + with ensure_clean_store(setup_path) as store: + idx = tm.makeDateIndex(10) + df = DataFrame(np.random.randn(len(idx), 3), index=idx) + store["a"] = df + result = store["a"] + + tm.assert_frame_equal(result, df) + assert result.index.freq == df.index.freq + tm.assert_class_equal(result.index, df.index, obj="dataframe index") + + idx = tm.makePeriodIndex(10) + df = DataFrame(np.random.randn(len(idx), 3), idx) + store["a"] = df + result = store["a"] + + tm.assert_frame_equal(result, df) + assert result.index.freq == df.index.freq + tm.assert_class_equal(result.index, df.index, obj="dataframe index")
This PR addresses xref #26807 for pandas/tests/io/pytables/test_store.py, which was more than 5000 lines before this attempt. I made a new directory pandas/tests/io/pytables/store/ to put all the new modules in. I tried to 1) get all the new modules below 1000 lines and 2) break it up in a somewhat logical way, but let's see if I succeeded in the opinion of the reviewer. There were 194 tests in pandas/tests/io/pytables/test_store.py, and now there are 194 tests in pandas/tests/io/pytables/store so I haven't gained or lost any. One is skipped on my dev machine. - [ ] closes #xxxx - [ ] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39072
2021-01-09T21:17:33Z
2021-01-13T18:04:33Z
2021-01-13T18:04:33Z
2021-01-13T18:04:39Z
Regression in loc.setitem raising ValueError with unordered MultiIndex columns and scalar indexer
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 31bff510e9c59..e26405c3a332a 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -22,6 +22,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.any` and :meth:`DataFrame.all` not returning a result for tz-aware ``datetime64`` columns (:issue:`38723`) - Fixed regression in :meth:`DataFrame.__setitem__` raising ``ValueError`` when expanding :class:`DataFrame` and new column is from type ``"0 - name"`` (:issue:`39010`) - Fixed regression in :meth:`.GroupBy.sem` where the presence of non-numeric columns would cause an error instead of being dropped (:issue:`38774`) +- Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``ValueError`` when :class:`DataFrame` has unsorted :class:`MultiIndex` columns and indexer is a scalar (:issue:`38601`) - Fixed regression in :func:`read_excel` with non-rawbyte file handles (:issue:`38788`) - Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) - Fixed regression in :meth:`Rolling.skew` and :meth:`Rolling.kurt` modifying the object inplace (:issue:`38908`) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 12694c19b2173..a1b06f3c9d6a1 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -15,6 +15,7 @@ from pandas.core.dtypes.common import ( is_array_like, + is_bool_dtype, is_hashable, is_integer, is_iterator, @@ -1933,12 +1934,14 @@ def _ensure_iterable_column_indexer(self, column_indexer): """ Ensure that our column indexer is something that can be iterated over. """ - # Ensure we have something we can iterate over if is_integer(column_indexer): ilocs = [column_indexer] elif isinstance(column_indexer, slice): - ri = Index(range(len(self.obj.columns))) - ilocs = ri[column_indexer] + ilocs = np.arange(len(self.obj.columns))[column_indexer] + elif isinstance(column_indexer, np.ndarray) and is_bool_dtype( + column_indexer.dtype + ): + ilocs = np.arange(len(column_indexer))[column_indexer] else: ilocs = column_indexer return ilocs diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 4cbdf61ff8dae..6808ffe65e561 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1685,6 +1685,21 @@ def test_getitem_interval_index_partial_indexing(self): res = df.loc[:, 0.5] tm.assert_series_equal(res, expected) + @pytest.mark.parametrize("indexer", ["A", ["A"], ("A", slice(None))]) + def test_setitem_unsorted_multiindex_columns(self, indexer): + # GH#38601 + mi = MultiIndex.from_tuples([("A", 4), ("B", "3"), ("A", "2")]) + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=mi) + obj = df.copy() + obj.loc[:, indexer] = np.zeros((2, 2), dtype=int) + expected = DataFrame([[0, 2, 0], [0, 5, 0]], columns=mi) + tm.assert_frame_equal(obj, expected) + + df = df.sort_index(1) + df.loc[:, indexer] = np.zeros((2, 2), dtype=int) + expected = expected.sort_index(1) + tm.assert_frame_equal(df, expected) + class TestDataFrameIndexingUInt64: def test_setitem(self, uint64_frame):
- [x] closes #38601 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry @jbrockmendel Would it be faster to use arange too in the line above of my fix instead of Index?
https://api.github.com/repos/pandas-dev/pandas/pulls/39071
2021-01-09T21:13:36Z
2021-01-10T03:59:07Z
2021-01-10T03:59:06Z
2021-01-11T17:06:34Z
TYP: PeriodArray._unbox_scalar
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 96a075dd21bf9..235bd2753742f 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -272,7 +272,7 @@ def _generate_range(cls, start, end, periods, freq, fields): def _unbox_scalar( self, value: Union[Period, NaTType], setitem: bool = False - ) -> int: + ) -> np.int64: if value is NaT: return np.int64(value.value) elif isinstance(value, self._scalar_type):
mypy errors with numpy 1.20 pandas/core/arrays/period.py:273: error: Return type "int" of "_unbox_scalar" incompatible with return type "Union[signedinteger[_64Bit], datetime64, timedelta64]" in supertype "DatetimeLikeArrayMixin" [override] pandas/core/arrays/period.py:277: error: Incompatible return value type (got "signedinteger[_64Bit]", expected "int") [return-value] pandas/core/arrays/period.py:280: error: Incompatible return value type (got "signedinteger[_64Bit]", expected "int") [return-value]
https://api.github.com/repos/pandas-dev/pandas/pulls/39070
2021-01-09T21:02:08Z
2021-01-09T22:06:02Z
2021-01-09T22:06:02Z
2021-01-10T09:32:13Z
REGR: diff_2d raising for int8, int16
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 28d84c380956c..31bff510e9c59 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -27,6 +27,7 @@ Fixed regressions - Fixed regression in :meth:`Rolling.skew` and :meth:`Rolling.kurt` modifying the object inplace (:issue:`38908`) - Fixed regression in :meth:`read_csv` and other read functions were the encoding error policy (``errors``) did not default to ``"replace"`` when no encoding was specified (:issue:`38989`) - Fixed regression in :meth:`DataFrame.replace` raising ValueError when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) +- Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 1291fc25fc21d..085ad5e6a0dcf 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -1991,7 +1991,13 @@ def diff(arr, n: int, axis: int = 0, stacklevel=3): elif is_integer_dtype(dtype): # We have to cast in order to be able to hold np.nan - dtype = np.float64 + + # int8, int16 are incompatible with float64, + # see https://github.com/cython/cython/issues/2646 + if arr.dtype.name in ["int8", "int16"]: + dtype = np.float32 + else: + dtype = np.float64 orig_ndim = arr.ndim if orig_ndim == 1: diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 5735f895e33b6..dd836591d5965 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1698,64 +1698,6 @@ def test_sort(x): g.apply(test_sort) -def test_group_shift_with_null_key(): - # This test is designed to replicate the segfault in issue #13813. - n_rows = 1200 - - # Generate a moderately large dataframe with occasional missing - # values in column `B`, and then group by [`A`, `B`]. This should - # force `-1` in `labels` array of `g.grouper.group_info` exactly - # at those places, where the group-by key is partially missing. - df = DataFrame( - [(i % 12, i % 3 if i % 3 else np.nan, i) for i in range(n_rows)], - dtype=float, - columns=["A", "B", "Z"], - index=None, - ) - g = df.groupby(["A", "B"]) - - expected = DataFrame( - [(i + 12 if i % 3 and i < n_rows - 12 else np.nan) for i in range(n_rows)], - dtype=float, - columns=["Z"], - index=None, - ) - result = g.shift(-1) - - tm.assert_frame_equal(result, expected) - - -def test_group_shift_with_fill_value(): - # GH #24128 - n_rows = 24 - df = DataFrame( - [(i % 12, i % 3, i) for i in range(n_rows)], - dtype=float, - columns=["A", "B", "Z"], - index=None, - ) - g = df.groupby(["A", "B"]) - - expected = DataFrame( - [(i + 12 if i < n_rows - 12 else 0) for i in range(n_rows)], - dtype=float, - columns=["Z"], - index=None, - ) - result = g.shift(-1, fill_value=0)[["Z"]] - - tm.assert_frame_equal(result, expected) - - -def test_group_shift_lose_timezone(): - # GH 30134 - now_dt = Timestamp.utcnow() - df = DataFrame({"a": [1, 1], "date": now_dt}) - result = df.groupby("a").shift(0).iloc[0] - expected = Series({"date": now_dt}, name=result.name) - tm.assert_series_equal(result, expected) - - def test_pivot_table_values_key_error(): # This test is designed to replicate the error in issue #14938 df = DataFrame( diff --git a/pandas/tests/groupby/test_groupby_shift_diff.py b/pandas/tests/groupby/test_groupby_shift_diff.py new file mode 100644 index 0000000000000..1410038274152 --- /dev/null +++ b/pandas/tests/groupby/test_groupby_shift_diff.py @@ -0,0 +1,106 @@ +import numpy as np +import pytest + +from pandas import DataFrame, NaT, Series, Timedelta, Timestamp +import pandas._testing as tm + + +def test_group_shift_with_null_key(): + # This test is designed to replicate the segfault in issue #13813. + n_rows = 1200 + + # Generate a moderately large dataframe with occasional missing + # values in column `B`, and then group by [`A`, `B`]. This should + # force `-1` in `labels` array of `g.grouper.group_info` exactly + # at those places, where the group-by key is partially missing. + df = DataFrame( + [(i % 12, i % 3 if i % 3 else np.nan, i) for i in range(n_rows)], + dtype=float, + columns=["A", "B", "Z"], + index=None, + ) + g = df.groupby(["A", "B"]) + + expected = DataFrame( + [(i + 12 if i % 3 and i < n_rows - 12 else np.nan) for i in range(n_rows)], + dtype=float, + columns=["Z"], + index=None, + ) + result = g.shift(-1) + + tm.assert_frame_equal(result, expected) + + +def test_group_shift_with_fill_value(): + # GH #24128 + n_rows = 24 + df = DataFrame( + [(i % 12, i % 3, i) for i in range(n_rows)], + dtype=float, + columns=["A", "B", "Z"], + index=None, + ) + g = df.groupby(["A", "B"]) + + expected = DataFrame( + [(i + 12 if i < n_rows - 12 else 0) for i in range(n_rows)], + dtype=float, + columns=["Z"], + index=None, + ) + result = g.shift(-1, fill_value=0)[["Z"]] + + tm.assert_frame_equal(result, expected) + + +def test_group_shift_lose_timezone(): + # GH 30134 + now_dt = Timestamp.utcnow() + df = DataFrame({"a": [1, 1], "date": now_dt}) + result = df.groupby("a").shift(0).iloc[0] + expected = Series({"date": now_dt}, name=result.name) + tm.assert_series_equal(result, expected) + + +def test_group_diff_real(any_real_dtype): + df = DataFrame({"a": [1, 2, 3, 3, 2], "b": [1, 2, 3, 4, 5]}, dtype=any_real_dtype) + result = df.groupby("a")["b"].diff() + exp_dtype = "float" + if any_real_dtype in ["int8", "int16", "float32"]: + exp_dtype = "float32" + expected = Series([np.nan, np.nan, np.nan, 1.0, 3.0], dtype=exp_dtype, name="b") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "data", + [ + [ + Timestamp("2013-01-01"), + Timestamp("2013-01-02"), + Timestamp("2013-01-03"), + ], + [Timedelta("5 days"), Timedelta("6 days"), Timedelta("7 days")], + ], +) +def test_group_diff_datetimelike(data): + df = DataFrame({"a": [1, 2, 2], "b": data}) + result = df.groupby("a")["b"].diff() + expected = Series([NaT, NaT, Timedelta("1 days")], name="b") + tm.assert_series_equal(result, expected) + + +def test_group_diff_bool(): + df = DataFrame({"a": [1, 2, 3, 3, 2], "b": [True, True, False, False, True]}) + result = df.groupby("a")["b"].diff() + expected = Series([np.nan, np.nan, np.nan, False, False], name="b") + tm.assert_series_equal(result, expected) + + +def test_group_diff_object_raises(object_dtype): + df = DataFrame( + {"a": ["foo", "bar", "bar"], "b": ["baz", "foo", "foo"]}, dtype=object_dtype + ) + with pytest.raises(TypeError, match=r"unsupported operand type\(s\) for -"): + df.groupby("a")["b"].diff() diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index a5c71b9ea3286..93900fa223966 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -2409,3 +2409,10 @@ def test_diff_ea_axis(self): msg = "cannot diff DatetimeArray on axis=1" with pytest.raises(ValueError, match=msg): algos.diff(dta, 1, axis=1) + + @pytest.mark.parametrize("dtype", ["int8", "int16"]) + def test_diff_low_precision_int(self, dtype): + arr = np.array([0, 1, 1, 0, 0], dtype=dtype) + result = algos.diff(arr, 1) + expected = np.array([np.nan, 1, 0, -1, 0], dtype="float32") + tm.assert_numpy_array_equal(result, expected)
- [x] closes #39050 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39069
2021-01-09T20:32:57Z
2021-01-10T00:42:30Z
2021-01-10T00:42:30Z
2021-01-11T13:44:50Z
BUG/API: DTI/TDI/PI.insert cast to object on failure
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index cbbba84da6ae6..06a583fe381d0 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -286,6 +286,7 @@ Indexing - Bug in :meth:`DataFrame.loc` dropping levels of :class:`MultiIndex` when :class:`DataFrame` used as input has only one row (:issue:`10521`) - Bug in setting ``timedelta64`` values into numeric :class:`Series` failing to cast to object dtype (:issue:`39086`) - Bug in setting :class:`Interval` values into a :class:`Series` or :class:`DataFrame` with mismatched :class:`IntervalDtype` incorrectly casting the new values to the existing dtype (:issue:`39120`) +- Bug in incorrectly raising in :meth:`Index.insert`, when setting a new column that cannot be held in the existing ``frame.columns``, or in :meth:`Series.reset_index` or :meth:`DataFrame.reset_index` instead of casting to a compatible dtype (:issue:`39068`) Missing ^^^^^^^ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index aa1a05aac9ad1..f38b49a15c120 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -5717,6 +5717,7 @@ def insert(self, loc: int, item): """ # Note: this method is overridden by all ExtensionIndex subclasses, # so self is never backed by an EA. + item = lib.item_from_zerodim(item) try: item = self._validate_fill_value(item) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 02a3548ec304e..268474446d6f6 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -600,7 +600,11 @@ def delete(self, loc): @doc(NDArrayBackedExtensionIndex.insert) def insert(self, loc: int, item): - result = super().insert(loc, item) + try: + result = super().insert(loc, item) + except (ValueError, TypeError): + # i.e. self._data._validate_scalar raised + return self.astype(object).insert(loc, item) result._data._freq = self._get_insert_freq(loc, item) return result @@ -865,15 +869,3 @@ def join( def _maybe_utc_convert(self: _T, other: Index) -> Tuple[_T, Index]: # Overridden by DatetimeIndex return self, other - - # -------------------------------------------------------------------- - # List-Like Methods - - @Appender(DatetimeIndexOpsMixin.insert.__doc__) - def insert(self, loc, item): - if isinstance(item, str): - # TODO: Why are strings special? - # TODO: Should we attempt _scalar_from_string? - return self.astype(object).insert(loc, item) - - return DatetimeIndexOpsMixin.insert(self, loc, item) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 48488fd867da7..2eda9f9ba41ac 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -422,12 +422,6 @@ def inferred_type(self) -> str: # indexing return "period" - def insert(self, loc: int, item): - if not isinstance(item, Period) or self.freq != item.freq: - return self.astype(object).insert(loc, item) - - return DatetimeIndexOpsMixin.insert(self, loc, item) - # ------------------------------------------------------------------------ # Indexing Methods diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index e43eb3fb47b7e..8644f56e4f253 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -314,18 +314,45 @@ def test_reset_index_multiindex_nan(self): rs = df.set_index(["A", "B"]).reset_index() tm.assert_frame_equal(rs, df) - def test_reset_index_with_datetimeindex_cols(self): + @pytest.mark.parametrize( + "name", + [ + None, + "foo", + 2, + 3.0, + pd.Timedelta(6), + Timestamp("2012-12-30", tz="UTC"), + "2012-12-31", + ], + ) + def test_reset_index_with_datetimeindex_cols(self, name): # GH#5818 + warn = None + if isinstance(name, Timestamp) and name.tz is not None: + # _deprecate_mismatched_indexing + warn = FutureWarning + df = DataFrame( [[1, 2], [3, 4]], columns=date_range("1/1/2013", "1/2/2013"), index=["A", "B"], ) + df.index.name = name + + with tm.assert_produces_warning(warn, check_stacklevel=False): + result = df.reset_index() + + item = name if name is not None else "index" + columns = Index([item, datetime(2013, 1, 1), datetime(2013, 1, 2)]) + if isinstance(item, str) and item == "2012-12-31": + columns = columns.astype("datetime64[ns]") + else: + assert columns.dtype == object - result = df.reset_index() expected = DataFrame( [["A", 1, 2], ["B", 3, 4]], - columns=["index", datetime(2013, 1, 1), datetime(2013, 1, 2)], + columns=columns, ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_insert.py b/pandas/tests/indexes/datetimes/test_insert.py index d2c999f61b4bb..684c6b813b48f 100644 --- a/pandas/tests/indexes/datetimes/test_insert.py +++ b/pandas/tests/indexes/datetimes/test_insert.py @@ -21,9 +21,11 @@ def test_insert_nat(self, tz, null): @pytest.mark.parametrize("tz", [None, "UTC", "US/Eastern"]) def test_insert_invalid_na(self, tz): idx = DatetimeIndex(["2017-01-01"], tz=tz) - msg = "value should be a 'Timestamp' or 'NaT'. Got 'timedelta64' instead." - with pytest.raises(TypeError, match=msg): - idx.insert(0, np.timedelta64("NaT")) + + item = np.timedelta64("NaT") + result = idx.insert(0, item) + expected = Index([item] + list(idx), dtype=object) + tm.assert_index_equal(result, expected) def test_insert_empty_preserves_freq(self, tz_naive_fixture): # GH#33573 @@ -114,17 +116,6 @@ def test_insert(self): assert result.name == expected.name assert result.freq is None - # see gh-7299 - idx = date_range("1/1/2000", periods=3, freq="D", tz="Asia/Tokyo", name="idx") - with pytest.raises(TypeError, match="Cannot compare tz-naive and tz-aware"): - idx.insert(3, Timestamp("2000-01-04")) - with pytest.raises(TypeError, match="Cannot compare tz-naive and tz-aware"): - idx.insert(3, datetime(2000, 1, 4)) - with pytest.raises(ValueError, match="Timezones don't match"): - idx.insert(3, Timestamp("2000-01-04", tz="US/Eastern")) - with pytest.raises(ValueError, match="Timezones don't match"): - idx.insert(3, datetime(2000, 1, 4, tzinfo=pytz.timezone("US/Eastern"))) - for tz in ["US/Pacific", "Asia/Singapore"]: idx = date_range("1/1/2000 09:00", periods=6, freq="H", tz=tz, name="idx") # preserve freq @@ -167,6 +158,48 @@ def test_insert(self): assert result.tz == expected.tz assert result.freq is None + # TODO: also changes DataFrame.__setitem__ with expansion + def test_insert_mismatched_tzawareness(self): + # see GH#7299 + idx = date_range("1/1/2000", periods=3, freq="D", tz="Asia/Tokyo", name="idx") + + # mismatched tz-awareness + item = Timestamp("2000-01-04") + result = idx.insert(3, item) + expected = Index( + list(idx[:3]) + [item] + list(idx[3:]), dtype=object, name="idx" + ) + tm.assert_index_equal(result, expected) + + # mismatched tz-awareness + item = datetime(2000, 1, 4) + result = idx.insert(3, item) + expected = Index( + list(idx[:3]) + [item] + list(idx[3:]), dtype=object, name="idx" + ) + tm.assert_index_equal(result, expected) + + # TODO: also changes DataFrame.__setitem__ with expansion + def test_insert_mismatched_tz(self): + # see GH#7299 + idx = date_range("1/1/2000", periods=3, freq="D", tz="Asia/Tokyo", name="idx") + + # mismatched tz -> cast to object (could reasonably cast to same tz or UTC) + item = Timestamp("2000-01-04", tz="US/Eastern") + result = idx.insert(3, item) + expected = Index( + list(idx[:3]) + [item] + list(idx[3:]), dtype=object, name="idx" + ) + tm.assert_index_equal(result, expected) + + # mismatched tz -> cast to object (could reasonably cast to same tz) + item = datetime(2000, 1, 4, tzinfo=pytz.timezone("US/Eastern")) + result = idx.insert(3, item) + expected = Index( + list(idx[:3]) + [item] + list(idx[3:]), dtype=object, name="idx" + ) + tm.assert_index_equal(result, expected) + @pytest.mark.parametrize( "item", [0, np.int64(0), np.float64(0), np.array(0), np.timedelta64(456)] ) @@ -175,17 +208,36 @@ def test_insert_mismatched_types_raises(self, tz_aware_fixture, item): tz = tz_aware_fixture dti = date_range("2019-11-04", periods=9, freq="-1D", name=9, tz=tz) - msg = "value should be a 'Timestamp' or 'NaT'. Got '.*' instead" - with pytest.raises(TypeError, match=msg): - dti.insert(1, item) + result = dti.insert(1, item) + + if isinstance(item, np.ndarray): + # FIXME: without doing .item() here this segfaults + assert item.item() == 0 + expected = Index([dti[0], 0] + list(dti[1:]), dtype=object, name=9) + else: + expected = Index([dti[0], item] + list(dti[1:]), dtype=object, name=9) + + tm.assert_index_equal(result, expected) - def test_insert_object_casting(self, tz_aware_fixture): + def test_insert_castable_str(self, tz_aware_fixture): # GH#33703 tz = tz_aware_fixture dti = date_range("2019-11-04", periods=3, freq="-1D", name=9, tz=tz) - # ATM we treat this as a string, but we could plausibly wrap it in Timestamp value = "2019-11-05" result = dti.insert(0, value) - expected = Index(["2019-11-05"] + list(dti), dtype=object, name=9) + + ts = Timestamp(value).tz_localize(tz) + expected = DatetimeIndex([ts] + list(dti), dtype=dti.dtype, name=9) + tm.assert_index_equal(result, expected) + + def test_insert_non_castable_str(self, tz_aware_fixture): + # GH#33703 + tz = tz_aware_fixture + dti = date_range("2019-11-04", periods=3, freq="-1D", name=9, tz=tz) + + value = "foo" + result = dti.insert(0, value) + + expected = Index(["foo"] + list(dti), dtype=object, name=9) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/timedeltas/test_insert.py b/pandas/tests/indexes/timedeltas/test_insert.py index 66fec2310e50c..d501f81fd9dce 100644 --- a/pandas/tests/indexes/timedeltas/test_insert.py +++ b/pandas/tests/indexes/timedeltas/test_insert.py @@ -3,6 +3,8 @@ import numpy as np import pytest +from pandas._libs import lib + import pandas as pd from pandas import Index, Timedelta, TimedeltaIndex, timedelta_range import pandas._testing as tm @@ -79,9 +81,14 @@ def test_insert_nat(self, null): def test_insert_invalid_na(self): idx = TimedeltaIndex(["4day", "1day", "2day"], name="idx") - msg = r"value should be a 'Timedelta' or 'NaT'\. Got 'datetime64' instead\." - with pytest.raises(TypeError, match=msg): - idx.insert(0, np.datetime64("NaT")) + + # FIXME: assert_index_equal fails if we pass a different + # instance of np.datetime64("NaT") + item = np.datetime64("NaT") + result = idx.insert(0, item) + + expected = Index([item] + list(idx), dtype=object, name="idx") + tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "item", [0, np.int64(0), np.float64(0), np.array(0), np.datetime64(456, "us")] @@ -90,18 +97,30 @@ def test_insert_mismatched_types_raises(self, item): # GH#33703 dont cast these to td64 tdi = TimedeltaIndex(["4day", "1day", "2day"], name="idx") - msg = r"value should be a 'Timedelta' or 'NaT'\. Got '.*' instead\." - with pytest.raises(TypeError, match=msg): - tdi.insert(1, item) + result = tdi.insert(1, item) + + expected = Index( + [tdi[0], lib.item_from_zerodim(item)] + list(tdi[1:]), + dtype=object, + name="idx", + ) + tm.assert_index_equal(result, expected) - def test_insert_dont_cast_strings(self): - # To match DatetimeIndex and PeriodIndex behavior, dont try to - # parse strings to Timedelta + def test_insert_castable_str(self): idx = timedelta_range("1day", "3day") result = idx.insert(0, "1 Day") - assert result.dtype == object - assert result[0] == "1 Day" + + expected = TimedeltaIndex([idx[0]] + list(idx)) + tm.assert_index_equal(result, expected) + + def test_insert_non_castable_str(self): + idx = timedelta_range("1day", "3day") + + result = idx.insert(0, "foo") + + expected = Index(["foo"] + list(idx), dtype=object) + tm.assert_index_equal(result, expected) def test_insert_empty(self): # Corner case inserting with length zero doesnt raise IndexError diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index ac2e300f9f8d6..b342942cd9f5f 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -441,14 +441,6 @@ def test_insert_index_float64(self, insert, coerced_val, coerced_dtype): [pd.Timestamp("2012-01-01"), pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), 1], ) def test_insert_index_datetimes(self, request, fill_val, exp_dtype, insert_value): - if not hasattr(insert_value, "tz"): - request.node.add_marker( - pytest.mark.xfail(reason="ToDo: must coerce to object") - ) - elif fill_val.tz != insert_value.tz: - request.node.add_marker( - pytest.mark.xfail(reason="GH 37605 - require tz equality?") - ) obj = pd.DatetimeIndex( ["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"], tz=fill_val.tz @@ -461,7 +453,36 @@ def test_insert_index_datetimes(self, request, fill_val, exp_dtype, insert_value ) self._assert_insert_conversion(obj, fill_val, exp, exp_dtype) - obj.insert(1, insert_value) + if fill_val.tz: + + # mismatched tzawareness + ts = pd.Timestamp("2012-01-01") + result = obj.insert(1, ts) + expected = obj.astype(object).insert(1, ts) + assert expected.dtype == object + tm.assert_index_equal(result, expected) + + # mismatched tz --> cast to object (could reasonably cast to commom tz) + ts = pd.Timestamp("2012-01-01", tz="Asia/Tokyo") + result = obj.insert(1, ts) + expected = obj.astype(object).insert(1, ts) + assert expected.dtype == object + tm.assert_index_equal(result, expected) + + else: + # mismatched tzawareness + ts = pd.Timestamp("2012-01-01", tz="Asia/Tokyo") + result = obj.insert(1, ts) + expected = obj.astype(object).insert(1, ts) + assert expected.dtype == object + tm.assert_index_equal(result, expected) + + item = 1 + result = obj.insert(1, item) + expected = obj.astype(object).insert(1, item) + assert expected[1] == item + assert expected.dtype == object + tm.assert_index_equal(result, expected) def test_insert_index_timedelta64(self): obj = pd.TimedeltaIndex(["1 day", "2 day", "3 day", "4 day"]) @@ -473,15 +494,11 @@ def test_insert_index_timedelta64(self): obj, pd.Timedelta("10 day"), exp, "timedelta64[ns]" ) - # ToDo: must coerce to object - msg = "value should be a 'Timedelta' or 'NaT'. Got 'Timestamp' instead." - with pytest.raises(TypeError, match=msg): - obj.insert(1, pd.Timestamp("2012-01-01")) - - # ToDo: must coerce to object - msg = "value should be a 'Timedelta' or 'NaT'. Got 'int' instead." - with pytest.raises(TypeError, match=msg): - obj.insert(1, 1) + for item in [pd.Timestamp("2012-01-01"), 1]: + result = obj.insert(1, item) + expected = obj.astype(object).insert(1, item) + assert expected.dtype == object + tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "insert, coerced_val, coerced_dtype", @@ -506,7 +523,23 @@ def test_insert_index_period(self, insert, coerced_val, coerced_dtype): if isinstance(insert, pd.Period): exp = pd.PeriodIndex(data, freq="M") self._assert_insert_conversion(obj, insert, exp, coerced_dtype) + + # string that can be parsed to appropriate PeriodDtype + self._assert_insert_conversion(obj, str(insert), exp, coerced_dtype) + else: + result = obj.insert(0, insert) + expected = obj.astype(object).insert(0, insert) + tm.assert_index_equal(result, expected) + + # TODO: ATM inserting '2012-01-01 00:00:00' when we have obj.freq=="M" + # casts that string to Period[M], not clear that is desirable + if not isinstance(insert, pd.Timestamp): + # non-castable string + result = obj.insert(0, str(insert)) + expected = obj.astype(object).insert(0, str(insert)) + tm.assert_index_equal(result, expected) + msg = r"Unexpected keyword arguments {'freq'}" with pytest.raises(TypeError, match=msg): with tm.assert_produces_warning(FutureWarning): diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 0251fb4a0ebd6..ad2d7250d9d6c 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -326,22 +326,24 @@ def test_series_partial_set_with_name(self): result = ser.iloc[[1, 1, 0, 0]] tm.assert_series_equal(result, expected, check_index_type=True) + @pytest.mark.parametrize("key", [100, 100.0]) + def test_setitem_with_expansion_numeric_into_datetimeindex(self, key): + # GH#4940 inserting non-strings + orig = tm.makeTimeDataFrame() + df = orig.copy() + + df.loc[key, :] = df.iloc[0] + ex_index = Index(list(orig.index) + [key], dtype=object, name=orig.index.name) + ex_data = np.concatenate([orig.values, df.iloc[[0]].values], axis=0) + expected = DataFrame(ex_data, index=ex_index, columns=orig.columns) + tm.assert_frame_equal(df, expected) + def test_partial_set_invalid(self): # GH 4940 # allow only setting of 'valid' values orig = tm.makeTimeDataFrame() - df = orig.copy() - - # don't allow not string inserts - msg = r"value should be a 'Timestamp' or 'NaT'\. Got '.*' instead\." - - with pytest.raises(TypeError, match=msg): - df.loc[100.0, :] = df.iloc[0] - - with pytest.raises(TypeError, match=msg): - df.loc[100, :] = df.iloc[0] # allow object conversion here df = orig.copy()
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry ATM DTI/TDI/PI/insert are pretty idiosyncratic. This changes them to match the base Index.insert by a) always trying _validate_fill_value (this changes the behavior for strings that can be parsed to datetime/timedelta/period) and b) always fall back to object in cases where this validation fails (this changes behavior for non-strings where the validation fails). AFAICT the current behavior was implemented in #5819 and the only discussion I see about castable strings or non-castable non-strings is this [comment](https://github.com/pandas-dev/pandas/pull/5819#issuecomment-31454545), which I don't think is relevant any longer. One corner case is mismatched tzs, which raise in master. In the PR they cast to object. They could also reasonably cast to the index's tz (xref #37605) cc @rhshadrach IIRC you had a question about the insert tests in test_coercion. I think this addresses what you were asking about. Let me know if I missed something.
https://api.github.com/repos/pandas-dev/pandas/pulls/39068
2021-01-09T20:31:41Z
2021-01-21T23:58:35Z
2021-01-21T23:58:35Z
2021-01-22T00:07:29Z
TYP: ALL_NUMPY_DTYPES mypy errors with numpy-1.20
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index c51ceb750c338..415dfd80d38e6 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -108,9 +108,9 @@ DATETIME64_DTYPES: List[Dtype] = ["datetime64[ns]", "M8[ns]"] TIMEDELTA64_DTYPES: List[Dtype] = ["timedelta64[ns]", "m8[ns]"] -BOOL_DTYPES = [bool, "bool"] -BYTES_DTYPES = [bytes, "bytes"] -OBJECT_DTYPES = [object, "object"] +BOOL_DTYPES: List[Dtype] = [bool, "bool"] +BYTES_DTYPES: List[Dtype] = [bytes, "bytes"] +OBJECT_DTYPES: List[Dtype] = [object, "object"] ALL_REAL_DTYPES = FLOAT_DTYPES + ALL_INT_DTYPES ALL_NUMPY_DTYPES = (
prevents mypy errors pandas/_testing/__init__.py:122: error: Unsupported operand types for + ("List[Union[ExtensionDtype, Union[str, dtype[Any]], Type[str], Type[float], Type[int], Type[complex], Type[bool], Type[object]]]" and "List[object]") [operator] pandas/_testing/__init__.py:123: error: Unsupported operand types for + ("List[Union[ExtensionDtype, Union[str, dtype[Any]], Type[str], Type[float], Type[int], Type[complex], Type[bool], Type[object]]]" and "List[object]") [operator] pandas/_testing/__init__.py:124: error: Unsupported operand types for + ("List[Union[ExtensionDtype, Union[str, dtype[Any]], Type[str], Type[float], Type[int], Type[complex], Type[bool], Type[object]]]" and "List[object]") [operator]
https://api.github.com/repos/pandas-dev/pandas/pulls/39066
2021-01-09T20:03:59Z
2021-01-09T21:34:55Z
2021-01-09T21:34:55Z
2021-01-10T09:23:31Z
Regression in replace raising ValueError for bytes object
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index 4b7a4180ee9f9..28d84c380956c 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -26,6 +26,7 @@ Fixed regressions - Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) - Fixed regression in :meth:`Rolling.skew` and :meth:`Rolling.kurt` modifying the object inplace (:issue:`38908`) - Fixed regression in :meth:`read_csv` and other read functions were the encoding error policy (``errors``) did not default to ``"replace"`` when no encoding was specified (:issue:`38989`) +- Fixed regression in :meth:`DataFrame.replace` raising ValueError when :class:`DataFrame` has dtype ``bytes`` (:issue:`38900`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 94c7d325d0bc8..a2a337413d707 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2293,7 +2293,7 @@ class ObjectBlock(Block): _can_hold_na = True def _maybe_coerce_values(self, values): - if issubclass(values.dtype.type, str): + if issubclass(values.dtype.type, (str, bytes)): values = np.array(values, dtype=object) return values diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index ab750bca7e069..1b570028964df 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -1636,3 +1636,10 @@ def test_replace_unicode(self): result = df1.replace(columns_values_map) expected = DataFrame({"positive": np.ones(3)}) tm.assert_frame_equal(result, expected) + + def test_replace_bytes(self, frame_or_series): + # GH#38900 + obj = frame_or_series(["o"]).astype("|S") + expected = obj.copy() + obj = obj.replace({None: np.nan}) + tm.assert_equal(obj, expected)
- [x] closes #38900 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39065
2021-01-09T19:42:51Z
2021-01-09T22:05:14Z
2021-01-09T22:05:13Z
2021-01-09T22:23:17Z
Added docs for the change of behavior of isin
diff --git a/pandas/core/series.py b/pandas/core/series.py index b248899a171ff..3888194305d76 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4599,6 +4599,15 @@ def isin(self, values) -> Series: 4 True 5 False Name: animal, dtype: bool + + Strings and integers are distinct and are therefore not comparable: + + >>> pd.Series([1]).isin(['1']) + 0 False + dtype: bool + >>> pd.Series([1.1]).isin(['1.1']) + 0 False + dtype: bool """ result = algorithms.isin(self._values, values) return self._constructor(result, index=self.index).__finalize__(
This is to close issue #38781, I added documentation to explain the change of behavior of the isin function. - [x] closes #38781 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39064
2021-01-09T18:35:05Z
2021-01-17T15:36:02Z
2021-01-17T15:36:01Z
2021-01-17T15:37:27Z
TST: skips in extension.test_categorical
diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index 472e783c977f0..7e7f1f1a6e025 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -394,7 +394,7 @@ def test_hash_pandas_object_works(self, data, as_frame): def test_searchsorted(self, data_for_sorting, as_series): b, c, a = data_for_sorting - arr = type(data_for_sorting)._from_sequence([a, b, c]) + arr = data_for_sorting.take([2, 0, 1]) # to get [a, b, c] if as_series: arr = pd.Series(arr) diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index e38de67071f15..9cea274a118c0 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -175,10 +175,6 @@ def test_combine_add(self, data_repeated): def test_fillna_length_mismatch(self, data_missing): super().test_fillna_length_mismatch(data_missing) - def test_searchsorted(self, data_for_sorting): - if not data_for_sorting.ordered: - raise pytest.skip(reason="searchsorted requires ordered data.") - class TestCasting(base.BaseCastingTests): @pytest.mark.parametrize("cls", [Categorical, CategoricalIndex]) @@ -229,21 +225,26 @@ def test_consistent_casting(self, dtype, expected): class TestArithmeticOps(base.BaseArithmeticOpsTests): - def test_arith_frame_with_scalar(self, data, all_arithmetic_operators): + def test_arith_frame_with_scalar(self, data, all_arithmetic_operators, request): # frame & scalar op_name = all_arithmetic_operators - if op_name != "__rmod__": - super().test_arith_frame_with_scalar(data, all_arithmetic_operators) - else: - pytest.skip("rmod never called when string is first argument") - - def test_arith_series_with_scalar(self, data, all_arithmetic_operators): - + if op_name == "__rmod__": + request.node.add_marker( + pytest.mark.xfail( + reason="rmod never called when string is first argument" + ) + ) + super().test_arith_frame_with_scalar(data, op_name) + + def test_arith_series_with_scalar(self, data, all_arithmetic_operators, request): op_name = all_arithmetic_operators - if op_name != "__rmod__": - super().test_arith_series_with_scalar(data, op_name) - else: - pytest.skip("rmod never called when string is first argument") + if op_name == "__rmod__": + request.node.add_marker( + pytest.mark.xfail( + reason="rmod never called when string is first argument" + ) + ) + super().test_arith_series_with_scalar(data, op_name) def test_add_series_with_extension_array(self, data): ser = pd.Series(data)
- [x] closes #38904 - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them cc @simonjayhawkins For the searchsorted test, the categorical data starts off ordered as "C" < "A" < "B" but then gets reordered in the test by these lines: > b, c, a = data_for_sorting arr = type(data_for_sorting)._from_sequence([a, b, c]) so the ordering becomes "A" < "B" < "C". This causes failure when "C" is said to be inserted at index 3 (new order) to preserve order rather than the expected 0 (original order).
https://api.github.com/repos/pandas-dev/pandas/pulls/39062
2021-01-09T16:25:36Z
2021-01-12T01:17:22Z
2021-01-12T01:17:22Z
2021-01-12T01:28:00Z
REF: Move Series.apply/agg into apply
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 6c503eefed54b..874b40f224a26 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -8,6 +8,7 @@ from pandas._config import option_context +from pandas._libs import lib from pandas._typing import ( AggFuncType, AggFuncTypeBase, @@ -26,7 +27,10 @@ from pandas.core.dtypes.generic import ABCSeries from pandas.core.aggregation import agg_dict_like, agg_list_like -from pandas.core.construction import create_series_with_explicit_dtype +from pandas.core.construction import ( + array as pd_array, + create_series_with_explicit_dtype, +) if TYPE_CHECKING: from pandas import DataFrame, Index, Series @@ -63,12 +67,30 @@ def frame_apply( ) +def series_apply( + obj: Series, + how: str, + func: AggFuncType, + convert_dtype: bool = True, + args=None, + kwds=None, +) -> SeriesApply: + return SeriesApply( + obj, + how, + func, + convert_dtype, + args, + kwds, + ) + + class Apply(metaclass=abc.ABCMeta): axis: int def __init__( self, - obj: DataFrame, + obj: FrameOrSeriesUnion, how: str, func, raw: bool, @@ -110,12 +132,62 @@ def f(x): def index(self) -> Index: return self.obj.index - @abc.abstractmethod def get_result(self): + if self.how == "apply": + return self.apply() + else: + return self.agg() + + @abc.abstractmethod + def apply(self) -> FrameOrSeriesUnion: pass + def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]: + """ + Provide an implementation for the aggregators. + + Returns + ------- + tuple of result, how. + + Notes + ----- + how can be a string describe the required post-processing, or + None if not required. + """ + obj = self.obj + arg = self.f + args = self.args + kwargs = self.kwds + + _axis = kwargs.pop("_axis", None) + if _axis is None: + _axis = getattr(obj, "axis", 0) + + if isinstance(arg, str): + return obj._try_aggregate_string_function(arg, *args, **kwargs), None + elif is_dict_like(arg): + arg = cast(AggFuncTypeDict, arg) + return agg_dict_like(obj, arg, _axis), True + elif is_list_like(arg): + # we require a list, but not a 'str' + arg = cast(List[AggFuncTypeBase], arg) + return agg_list_like(obj, arg, _axis=_axis), None + else: + result = None + + if callable(arg): + f = obj._get_cython_func(arg) + if f and not args and not kwargs: + return getattr(obj, f)(), None + + # caller can react + return result, True + class FrameApply(Apply): + obj: DataFrame + # --------------------------------------------------------------- # Abstract Methods @@ -168,48 +240,6 @@ def get_result(self): else: return self.agg() - def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]: - """ - Provide an implementation for the aggregators. - - Returns - ------- - tuple of result, how. - - Notes - ----- - how can be a string describe the required post-processing, or - None if not required. - """ - obj = self.obj - arg = self.f - args = self.args - kwargs = self.kwds - - _axis = kwargs.pop("_axis", None) - if _axis is None: - _axis = getattr(obj, "axis", 0) - - if isinstance(arg, str): - return obj._try_aggregate_string_function(arg, *args, **kwargs), None - elif is_dict_like(arg): - arg = cast(AggFuncTypeDict, arg) - return agg_dict_like(obj, arg, _axis), True - elif is_list_like(arg): - # we require a list, but not a 'str' - arg = cast(List[AggFuncTypeBase], arg) - return agg_list_like(obj, arg, _axis=_axis), None - else: - result = None - - if callable(arg): - f = obj._get_cython_func(arg) - if f and not args and not kwargs: - return getattr(obj, f)(), None - - # caller can react - return result, True - def apply(self) -> FrameOrSeriesUnion: """ compute the results """ # dispatch to agg @@ -531,3 +561,79 @@ def infer_to_same_shape(self, results: ResType, res_index: Index) -> DataFrame: result = result.infer_objects() return result + + +class SeriesApply(Apply): + obj: Series + axis = 0 + + def __init__( + self, + obj: Series, + how: str, + func: AggFuncType, + convert_dtype: bool, + args, + kwds, + ): + self.convert_dtype = convert_dtype + + super().__init__( + obj, + how, + func, + raw=False, + result_type=None, + args=args, + kwds=kwds, + ) + + def apply(self) -> FrameOrSeriesUnion: + obj = self.obj + func = self.f + args = self.args + kwds = self.kwds + + if len(obj) == 0: + return self.apply_empty_result() + + # dispatch to agg + if isinstance(func, (list, dict)): + return obj.aggregate(func, *args, **kwds) + + # if we are a string, try to dispatch + if isinstance(func, str): + return obj._try_aggregate_string_function(func, *args, **kwds) + + return self.apply_standard() + + def apply_empty_result(self) -> Series: + obj = self.obj + return obj._constructor(dtype=obj.dtype, index=obj.index).__finalize__( + obj, method="apply" + ) + + def apply_standard(self) -> FrameOrSeriesUnion: + f = self.f + obj = self.obj + + with np.errstate(all="ignore"): + if isinstance(f, np.ufunc): + return f(obj) + + # row-wise access + if is_extension_array_dtype(obj.dtype) and hasattr(obj._values, "map"): + # GH#23179 some EAs do not have `map` + mapped = obj._values.map(f) + else: + values = obj.astype(object)._values + mapped = lib.map_infer(values, f, convert=self.convert_dtype) + + if len(mapped) and isinstance(mapped[0], ABCSeries): + # GH 25959 use pd.array instead of tolist + # so extension arrays can be used + return obj._constructor_expanddim(pd_array(mapped), index=obj.index) + else: + return obj._constructor(mapped, index=obj.index).__finalize__( + obj, method="apply" + ) diff --git a/pandas/core/series.py b/pandas/core/series.py index 668cad4f64ac3..6586ac8b01840 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -71,13 +71,13 @@ from pandas.core import algorithms, base, generic, missing, nanops, ops from pandas.core.accessor import CachedAccessor -from pandas.core.aggregation import aggregate, transform +from pandas.core.aggregation import transform +from pandas.core.apply import series_apply 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 ( - array as pd_array, create_series_with_explicit_dtype, extract_array, is_empty_data, @@ -3944,7 +3944,8 @@ def aggregate(self, func=None, axis=0, *args, **kwargs): if func is None: func = dict(kwargs.items()) - result, how = aggregate(self, func, *args, **kwargs) + op = series_apply(self, "agg", func, args=args, kwds=kwargs) + result, how = op.get_result() if result is None: # we can be called from an inner function which @@ -4076,48 +4077,8 @@ def apply(self, func, convert_dtype=True, args=(), **kwds): Helsinki 2.484907 dtype: float64 """ - if len(self) == 0: - return self._constructor(dtype=self.dtype, index=self.index).__finalize__( - self, method="apply" - ) - - # dispatch to agg - if isinstance(func, (list, dict)): - return self.aggregate(func, *args, **kwds) - - # if we are a string, try to dispatch - if isinstance(func, str): - return self._try_aggregate_string_function(func, *args, **kwds) - - # handle ufuncs and lambdas - if kwds or args and not isinstance(func, np.ufunc): - - def f(x): - return func(x, *args, **kwds) - - else: - f = func - - with np.errstate(all="ignore"): - if isinstance(f, np.ufunc): - return f(self) - - # row-wise access - if is_extension_array_dtype(self.dtype) and hasattr(self._values, "map"): - # GH#23179 some EAs do not have `map` - mapped = self._values.map(f) - else: - values = self.astype(object)._values - mapped = lib.map_infer(values, f, convert=convert_dtype) - - if len(mapped) and isinstance(mapped[0], Series): - # GH 25959 use pd.array instead of tolist - # so extension arrays can be used - return self._constructor_expanddim(pd_array(mapped), index=self.index) - else: - return self._constructor(mapped, index=self.index).__finalize__( - self, method="apply" - ) + op = series_apply(self, "apply", func, convert_dtype, args, kwds) + return op.get_result() def _reduce( self,
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them Will do follow up to share list/dict/str code in Apply for how=apply; they are essentially identical.
https://api.github.com/repos/pandas-dev/pandas/pulls/39061
2021-01-09T15:22:44Z
2021-01-09T21:24:43Z
2021-01-09T21:24:43Z
2021-01-09T21:25:23Z
TYP: series apply method adds type hints
diff --git a/pandas/core/series.py b/pandas/core/series.py index 6586ac8b01840..897e7c65466ae 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3980,7 +3980,13 @@ def transform( ) -> FrameOrSeriesUnion: return transform(self, func, axis, *args, **kwargs) - def apply(self, func, convert_dtype=True, args=(), **kwds): + def apply( + self, + func: AggFuncType, + convert_dtype: bool = True, + args: Tuple[Any, ...] = (), + **kwds, + ) -> FrameOrSeriesUnion: """ Invoke function on values of Series. diff --git a/pandas/io/sas/sas7bdat.py b/pandas/io/sas/sas7bdat.py index 7c2b801ee0ea8..fe06f103e6c5e 100644 --- a/pandas/io/sas/sas7bdat.py +++ b/pandas/io/sas/sas7bdat.py @@ -52,13 +52,17 @@ def _convert_datetimes(sas_datetimes: pd.Series, unit: str) -> pd.Series: return pd.to_datetime(sas_datetimes, unit=unit, origin="1960-01-01") except OutOfBoundsDatetime: if unit == "s": - return sas_datetimes.apply( + s_series = sas_datetimes.apply( lambda sas_float: datetime(1960, 1, 1) + timedelta(seconds=sas_float) ) + s_series = cast(pd.Series, s_series) + return s_series elif unit == "d": - return sas_datetimes.apply( + d_series = sas_datetimes.apply( lambda sas_float: datetime(1960, 1, 1) + timedelta(days=sas_float) ) + d_series = cast(pd.Series, d_series) + return d_series else: raise ValueError("unit must be 'd' or 's'")
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/39058
2021-01-09T14:13:02Z
2021-01-11T12:21:21Z
2021-01-11T12:21:20Z
2021-01-11T12:21:21Z
TYP: remove ignore from makeCustomIndex
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index c51ceb750c338..e00cb487ed4f4 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -1,11 +1,11 @@ -from collections import Counter +import collections from datetime import datetime from functools import wraps import operator import os import re import string -from typing import Callable, ContextManager, List, Type +from typing import Callable, ContextManager, Counter, List, Type import warnings import numpy as np @@ -568,7 +568,7 @@ def makeCustomIndex( assert all(x > 0 for x in ndupe_l) - tuples = [] + list_of_lists = [] for i in range(nlevels): def keyfunc(x): @@ -579,16 +579,18 @@ def keyfunc(x): # build a list of lists to create the index from div_factor = nentries // ndupe_l[i] + 1 - # pandas\_testing.py:2148: error: Need type annotation for 'cnt' - cnt = Counter() # type: ignore[var-annotated] + + # Deprecated since version 3.9: collections.Counter now supports []. See PEP 585 + # and Generic Alias Type. + cnt: Counter[str] = collections.Counter() for j in range(div_factor): label = f"{prefix}_l{i}_g{j}" cnt[label] = ndupe_l[i] # cute Counter trick result = sorted(cnt.elements(), key=keyfunc)[:nentries] - tuples.append(result) + list_of_lists.append(result) - tuples = list(zip(*tuples)) + tuples = list(zip(*list_of_lists)) # convert tuples to index if nentries == 1:
xref #37715
https://api.github.com/repos/pandas-dev/pandas/pulls/39057
2021-01-09T14:04:45Z
2021-01-09T21:16:56Z
2021-01-09T21:16:56Z
2021-01-10T09:25:27Z
TYP: remove ignore from makeMissingDataframe
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index c51ceb750c338..d254e8ec99435 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -468,7 +468,7 @@ def makeTimeDataFrame(nper=None, freq="B"): return DataFrame(data) -def makeDataFrame(): +def makeDataFrame() -> DataFrame: data = getSeriesData() return DataFrame(data) @@ -738,14 +738,7 @@ def _gen_unique_rand(rng, _extra_size): def makeMissingDataframe(density=0.9, random_state=None): df = makeDataFrame() - # pandas\_testing.py:2306: error: "_create_missing_idx" gets multiple - # values for keyword argument "density" [misc] - - # pandas\_testing.py:2306: error: "_create_missing_idx" gets multiple - # values for keyword argument "random_state" [misc] - i, j = _create_missing_idx( # type: ignore[misc] - *df.shape, density=density, random_state=random_state - ) + i, j = _create_missing_idx(*df.shape, density=density, random_state=random_state) df.values[i, j] = np.nan return df
xref #37715
https://api.github.com/repos/pandas-dev/pandas/pulls/39056
2021-01-09T14:01:40Z
2021-01-09T21:18:17Z
2021-01-09T21:18:17Z
2021-01-10T09:24:15Z
TYP: remove ignore from all_timeseries_index_generator
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 3df1999ce7dce..b36e790f8023b 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import collections from datetime import datetime from functools import wraps @@ -5,7 +7,15 @@ import os import re import string -from typing import Callable, ContextManager, Counter, List, Type +from typing import ( + TYPE_CHECKING, + Callable, + ContextManager, + Counter, + Iterable, + List, + Type, +) import warnings import numpy as np @@ -90,6 +100,9 @@ ) from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray, period_array +if TYPE_CHECKING: + from pandas import PeriodIndex, TimedeltaIndex + _N = 30 _K = 4 @@ -281,17 +294,17 @@ def makeFloatIndex(k=10, name=None): return Index(values * (10 ** np.random.randint(0, 9)), name=name) -def makeDateIndex(k=10, freq="B", name=None, **kwargs): +def makeDateIndex(k: int = 10, freq="B", name=None, **kwargs) -> DatetimeIndex: dt = datetime(2000, 1, 1) dr = bdate_range(dt, periods=k, freq=freq, name=name) return DatetimeIndex(dr, name=name, **kwargs) -def makeTimedeltaIndex(k=10, freq="D", name=None, **kwargs): +def makeTimedeltaIndex(k: int = 10, freq="D", name=None, **kwargs) -> TimedeltaIndex: return pd.timedelta_range(start="1 day", periods=k, freq=freq, name=name, **kwargs) -def makePeriodIndex(k=10, name=None, **kwargs): +def makePeriodIndex(k: int = 10, name=None, **kwargs) -> PeriodIndex: dt = datetime(2000, 1, 1) return pd.period_range(start=dt, periods=k, freq="B", name=name, **kwargs) @@ -394,7 +407,7 @@ def index_subclass_makers_generator(): yield from make_index_funcs -def all_timeseries_index_generator(k=10): +def all_timeseries_index_generator(k: int = 10) -> Iterable[Index]: """ Generator which can be iterated over to get instances of all the classes which represent time-series. @@ -403,10 +416,13 @@ def all_timeseries_index_generator(k=10): ---------- k: length of each of the index instances """ - make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex] + make_index_funcs: List[Callable[..., Index]] = [ + makeDateIndex, + makePeriodIndex, + makeTimedeltaIndex, + ] for make_index_func in make_index_funcs: - # pandas\_testing.py:1986: error: Cannot call function of unknown type - yield make_index_func(k=k) # type: ignore[operator] + yield make_index_func(k=k) # make series diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 8609c61065327..b7f93295837e0 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1089,7 +1089,7 @@ def date_range( def bdate_range( start=None, end=None, - periods=None, + periods: Optional[int] = None, freq="B", tz=None, normalize=True, diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index fe9560a1f2f3f..d5dc68b77df61 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -649,7 +649,7 @@ def memory_usage(self, deep: bool = False) -> int: def period_range( - start=None, end=None, periods=None, freq=None, name=None + start=None, end=None, periods: Optional[int] = None, freq=None, name=None ) -> PeriodIndex: """ Return a fixed frequency PeriodIndex. diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 5cf1def014450..e80fde87ffdee 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -2,7 +2,7 @@ from pandas._libs import index as libindex, lib from pandas._libs.tslibs import Timedelta, to_offset -from pandas._typing import DtypeObj +from pandas._typing import DtypeObj, Optional from pandas.errors import InvalidIndexError from pandas.core.dtypes.common import TD64NS_DTYPE, is_scalar, is_timedelta64_dtype @@ -212,7 +212,12 @@ def inferred_type(self) -> str: def timedelta_range( - start=None, end=None, periods=None, freq=None, name=None, closed=None + start=None, + end=None, + periods: Optional[int] = None, + freq=None, + name=None, + closed=None, ) -> TimedeltaIndex: """ Return a fixed frequency TimedeltaIndex, with day as the default @@ -236,7 +241,7 @@ def timedelta_range( Returns ------- - rng : TimedeltaIndex + TimedeltaIndex Notes -----
xref #37715
https://api.github.com/repos/pandas-dev/pandas/pulls/39054
2021-01-09T13:06:04Z
2021-01-10T12:34:13Z
2021-01-10T12:34:13Z
2021-01-10T12:34:34Z
TYP: remove ignores from set_testing_mode and reset_testing_mode
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index c51ceb750c338..3274d75128917 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -136,24 +136,16 @@ def set_testing_mode(): # set the testing mode filters testing_mode = os.environ.get("PANDAS_TESTING_MODE", "None") if "deprecate" in testing_mode: - # pandas\_testing.py:119: error: Argument 2 to "simplefilter" has - # incompatible type "Tuple[Type[DeprecationWarning], - # Type[ResourceWarning]]"; expected "Type[Warning]" - warnings.simplefilter( - "always", _testing_mode_warnings # type: ignore[arg-type] - ) + for category in _testing_mode_warnings: + warnings.simplefilter("always", category) def reset_testing_mode(): # reset the testing mode filters testing_mode = os.environ.get("PANDAS_TESTING_MODE", "None") if "deprecate" in testing_mode: - # pandas\_testing.py:126: error: Argument 2 to "simplefilter" has - # incompatible type "Tuple[Type[DeprecationWarning], - # Type[ResourceWarning]]"; expected "Type[Warning]" - warnings.simplefilter( - "ignore", _testing_mode_warnings # type: ignore[arg-type] - ) + for category in _testing_mode_warnings: + warnings.simplefilter("ignore", category) set_testing_mode() diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 8fe92ed757401..fe9560a1f2f3f 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -164,18 +164,21 @@ def to_timestamp(self, freq=None, how="start") -> DatetimeIndex: arr = self._data.to_timestamp(freq, how) return DatetimeIndex._simple_new(arr, name=self.name) + # https://github.com/python/mypy/issues/1362 # error: Decorated property not supported [misc] @property # type:ignore[misc] @doc(PeriodArray.hour.fget) def hour(self) -> Int64Index: return Int64Index(self._data.hour, name=self.name) + # https://github.com/python/mypy/issues/1362 # error: Decorated property not supported [misc] @property # type:ignore[misc] @doc(PeriodArray.minute.fget) def minute(self) -> Int64Index: return Int64Index(self._data.minute, name=self.name) + # https://github.com/python/mypy/issues/1362 # error: Decorated property not supported [misc] @property # type:ignore[misc] @doc(PeriodArray.second.fget)
xref #37715 The error message is self-explanatory although the original code passing a tuple seemed to work also, although not documented.
https://api.github.com/repos/pandas-dev/pandas/pulls/39052
2021-01-09T11:29:12Z
2021-01-09T21:17:46Z
2021-01-09T21:17:46Z
2021-01-10T09:26:01Z
ENH: try to preserve the dtype on combine_first for the case where the two DataFrame objects have the same columns
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index cb97fdeccd579..557663d10accf 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -65,6 +65,36 @@ Notable bug fixes These are bug fixes that might have notable behavior changes. +Preserve dtypes in :meth:`~pandas.DataFrame.combine_first` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:meth:`~pandas.DataFrame.combine_first` will now preserve dtypes (:issue:`7509`) + +.. ipython:: python + + df1 = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=[0, 1, 2]) + df1 + df2 = pd.DataFrame({"B": [4, 5, 6], "C": [1, 2, 3]}, index=[2, 3, 4]) + df2 + combined = df1.combine_first(df2) + +*pandas 1.2.x* + +.. code-block:: ipython + + In [1]: combined.dtypes + Out[2]: + A float64 + B float64 + C float64 + dtype: object + +*pandas 1.3.0* + +.. ipython:: python + + combined.dtypes + .. _whatsnew_130.api_breaking.deps: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e65e9302dd4d5..897ff7e12cc9e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6482,7 +6482,18 @@ def combiner(x, y): return expressions.where(mask, y_values, x_values) - return self.combine(other, combiner, overwrite=False) + combined = self.combine(other, combiner, overwrite=False) + + dtypes = { + col: find_common_type([self.dtypes[col], other.dtypes[col]]) + for col in self.columns.intersection(other.columns) + if not is_dtype_equal(combined.dtypes[col], self.dtypes[col]) + } + + if dtypes: + combined = combined.astype(dtypes) + + return combined def update( self, diff --git a/pandas/tests/frame/methods/test_combine_first.py b/pandas/tests/frame/methods/test_combine_first.py index 934ad9eb8213a..1325bfbda24c6 100644 --- a/pandas/tests/frame/methods/test_combine_first.py +++ b/pandas/tests/frame/methods/test_combine_first.py @@ -3,6 +3,8 @@ import numpy as np import pytest +from pandas.core.dtypes.cast import find_common_type, is_dtype_equal + import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series import pandas._testing as tm @@ -18,9 +20,7 @@ def test_combine_first_mixed(self): b = Series(range(2), index=range(5, 7)) g = DataFrame({"A": a, "B": b}) - exp = DataFrame( - {"A": list("abab"), "B": [0.0, 1.0, 0.0, 1.0]}, index=[0, 1, 5, 6] - ) + exp = DataFrame({"A": list("abab"), "B": [0, 1, 0, 1]}, index=[0, 1, 5, 6]) combined = f.combine_first(g) tm.assert_frame_equal(combined, exp) @@ -144,7 +144,7 @@ def test_combine_first_return_obj_type_with_bools(self): ) df2 = DataFrame([[-42.6, np.nan, True], [-5.0, 1.6, False]], index=[1, 2]) - expected = Series([True, True, False], name=2, dtype=object) + expected = Series([True, True, False], name=2, dtype=bool) result_12 = df1.combine_first(df2)[2] tm.assert_series_equal(result_12, expected) @@ -157,22 +157,22 @@ def test_combine_first_return_obj_type_with_bools(self): ( ( [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], - [None, None, None], + [pd.NaT, pd.NaT, pd.NaT], [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], ), ( - [None, None, None], + [pd.NaT, pd.NaT, pd.NaT], [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], ), ( - [datetime(2000, 1, 2), None, None], + [datetime(2000, 1, 2), pd.NaT, pd.NaT], [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], [datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 3)], ), ( [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], - [datetime(2000, 1, 2), None, None], + [datetime(2000, 1, 2), pd.NaT, pd.NaT], [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], ), ), @@ -196,13 +196,13 @@ def test_combine_first_align_nan(self): res = dfa.combine_first(dfb) exp = DataFrame( - {"a": [pd.Timestamp("2011-01-01"), pd.NaT], "b": [2.0, 5.0]}, + {"a": [pd.Timestamp("2011-01-01"), pd.NaT], "b": [2, 5]}, columns=["a", "b"], ) tm.assert_frame_equal(res, exp) assert res["a"].dtype == "datetime64[ns]" # ToDo: this must be int64 - assert res["b"].dtype == "float64" + assert res["b"].dtype == "int64" res = dfa.iloc[:0].combine_first(dfb) exp = DataFrame({"a": [np.nan, np.nan], "b": [4, 5]}, columns=["a", "b"]) @@ -219,14 +219,12 @@ def test_combine_first_timezone(self): columns=["UTCdatetime", "abc"], data=data1, index=pd.date_range("20140627", periods=1), - dtype="object", ) data2 = pd.to_datetime("20121212 12:12").tz_localize("UTC") df2 = DataFrame( columns=["UTCdatetime", "xyz"], data=data2, index=pd.date_range("20140628", periods=1), - dtype="object", ) res = df2[["UTCdatetime"]].combine_first(df1) exp = DataFrame( @@ -239,13 +237,10 @@ def test_combine_first_timezone(self): }, columns=["UTCdatetime", "abc"], index=pd.date_range("20140627", periods=2, freq="D"), - dtype="object", ) assert res["UTCdatetime"].dtype == "datetime64[ns, UTC]" assert res["abc"].dtype == "datetime64[ns, UTC]" - # Need to cast all to "obejct" because combine_first does not retain dtypes: - # GH Issue 7509 - res = res.astype("object") + tm.assert_frame_equal(res, exp) # see gh-10567 @@ -360,12 +355,11 @@ def test_combine_first_int(self): df2 = DataFrame({"a": [1, 4]}, dtype="int64") result_12 = df1.combine_first(df2) - expected_12 = DataFrame({"a": [0, 1, 3, 5]}, dtype="float64") + expected_12 = DataFrame({"a": [0, 1, 3, 5]}) tm.assert_frame_equal(result_12, expected_12) result_21 = df2.combine_first(df1) - expected_21 = DataFrame({"a": [1, 4, 3, 5]}, dtype="float64") - + expected_21 = DataFrame({"a": [1, 4, 3, 5]}) tm.assert_frame_equal(result_21, expected_21) @pytest.mark.parametrize("val", [1, 1.0]) @@ -404,11 +398,38 @@ def test_combine_first_string_dtype_only_na(self): def test_combine_first_timestamp_bug(scalar1, scalar2, nulls_fixture): # GH28481 na_value = nulls_fixture + frame = DataFrame([[na_value, na_value]], columns=["a", "b"]) other = DataFrame([[scalar1, scalar2]], columns=["b", "c"]) + common_dtype = find_common_type([frame.dtypes["b"], other.dtypes["b"]]) + + if is_dtype_equal(common_dtype, "object") or frame.dtypes["b"] == other.dtypes["b"]: + val = scalar1 + else: + val = na_value + + result = frame.combine_first(other) + + expected = DataFrame([[na_value, val, scalar2]], columns=["a", "b", "c"]) + + expected["b"] = expected["b"].astype(common_dtype) + + tm.assert_frame_equal(result, expected) + + +def test_combine_first_timestamp_bug_NaT(): + # GH28481 + frame = DataFrame([[pd.NaT, pd.NaT]], columns=["a", "b"]) + other = DataFrame( + [[datetime(2020, 1, 1), datetime(2020, 1, 2)]], columns=["b", "c"] + ) + result = frame.combine_first(other) - expected = DataFrame([[na_value, scalar1, scalar2]], columns=["a", "b", "c"]) + expected = DataFrame( + [[pd.NaT, datetime(2020, 1, 1), datetime(2020, 1, 2)]], columns=["a", "b", "c"] + ) + tm.assert_frame_equal(result, expected) @@ -439,3 +460,25 @@ def test_combine_first_with_nan_multiindex(): index=mi_expected, ) tm.assert_frame_equal(res, expected) + + +def test_combine_preserve_dtypes(): + # GH7509 + a_column = Series(["a", "b"], index=range(2)) + b_column = Series(range(2), index=range(2)) + df1 = DataFrame({"A": a_column, "B": b_column}) + + c_column = Series(["a", "b"], index=range(5, 7)) + b_column = Series(range(-1, 1), index=range(5, 7)) + df2 = DataFrame({"B": b_column, "C": c_column}) + + expected = DataFrame( + { + "A": ["a", "b", np.nan, np.nan], + "B": [0, 1, -1, 0], + "C": [np.nan, np.nan, "a", "b"], + }, + index=[0, 1, 5, 6], + ) + combined = df1.combine_first(df2) + tm.assert_frame_equal(combined, expected)
…e two DataFrame objects have the same columns - [ ] closes #7509 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39051
2021-01-09T08:27:59Z
2021-01-15T16:30:23Z
2021-01-15T16:30:22Z
2021-01-15T16:30:28Z
BUG: pd.to_numeric does not copy _mask for ExtensionArrays
diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py index d8a5855d05dfd..3807fdd47b54f 100644 --- a/pandas/core/tools/numeric.py +++ b/pandas/core/tools/numeric.py @@ -221,7 +221,7 @@ def to_numeric(arg, errors="raise", downcast=None): from pandas.core.arrays import FloatingArray, IntegerArray klass = IntegerArray if is_integer_dtype(data.dtype) else FloatingArray - values = klass(data, mask) + values = klass(data, mask.copy()) if is_series: return arg._constructor(values, index=arg.index, name=arg.name) diff --git a/pandas/tests/tools/test_to_numeric.py b/pandas/tests/tools/test_to_numeric.py index 80446e464985c..d5b4bda35ca2b 100644 --- a/pandas/tests/tools/test_to_numeric.py +++ b/pandas/tests/tools/test_to_numeric.py @@ -764,3 +764,16 @@ def test_downcast_nullable_numeric(data, input_dtype, downcast, expected_dtype): result = pd.to_numeric(arr, downcast=downcast) expected = pd.array(data, dtype=expected_dtype) tm.assert_extension_array_equal(result, expected) + + +def test_downcast_nullable_mask_is_copied(): + # GH38974 + + arr = pd.array([1, 2, pd.NA], dtype="Int64") + + result = pd.to_numeric(arr, downcast="integer") + expected = pd.array([1, 2, pd.NA], dtype="Int8") + tm.assert_extension_array_equal(result, expected) + + arr[1] = pd.NA # should not modify result + tm.assert_extension_array_equal(result, expected)
- [x] closes #38974 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry (not needed as bug on master only) Fixing a bug I introduced in #38746
https://api.github.com/repos/pandas-dev/pandas/pulls/39049
2021-01-09T04:42:40Z
2021-01-09T21:22:56Z
2021-01-09T21:22:55Z
2021-01-09T21:22:59Z
BUG: reindexing empty CategoricalIndex would fail if target had duplicates
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 1d76c9d296255..d90ccd57be16a 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -192,6 +192,7 @@ Categorical - Bug in ``CategoricalIndex.reindex`` failed when ``Index`` passed with elements all in category (:issue:`28690`) - Bug where constructing a :class:`Categorical` from an object-dtype array of ``date`` objects did not round-trip correctly with ``astype`` (:issue:`38552`) - Bug in constructing a :class:`DataFrame` from an ``ndarray`` and a :class:`CategoricalDtype` (:issue:`38857`) +- Bug in :meth:`DataFrame.reindex` was throwing ``IndexError`` when new index contained duplicates and old index was :class:`CategoricalIndex` (:issue:`38906`) Datetimelike ^^^^^^^^^^^^ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 92a4d0a125195..a2e9737f305ba 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3730,8 +3730,13 @@ def _reindex_non_unique(self, target): new_labels[cur_indexer] = cur_labels new_labels[missing_indexer] = missing_labels + # GH#38906 + if not len(self): + + new_indexer = np.arange(0) + # a unique indexer - if target.is_unique: + elif target.is_unique: # see GH5553, make sure we use the right indexer new_indexer = np.arange(len(indexer)) diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 4cbdf61ff8dae..2b80e06861a00 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1717,6 +1717,34 @@ def test_setitem(self, uint64_frame): ) +@pytest.mark.parametrize( + "src_idx", + [ + Index([]), + pd.CategoricalIndex([]), + ], +) +@pytest.mark.parametrize( + "cat_idx", + [ + # No duplicates + Index([]), + pd.CategoricalIndex([]), + Index(["A", "B"]), + pd.CategoricalIndex(["A", "B"]), + # Duplicates: GH#38906 + Index(["A", "A"]), + pd.CategoricalIndex(["A", "A"]), + ], +) +def test_reindex_empty(src_idx, cat_idx): + df = DataFrame(columns=src_idx, index=["K"], dtype="f8") + + result = df.reindex(columns=cat_idx) + expected = DataFrame(index=["K"], columns=cat_idx, dtype="f8") + tm.assert_frame_equal(result, expected) + + def test_object_casting_indexing_wraps_datetimelike(): # GH#31649, check the indexing methods all the way down the stack df = DataFrame(
- [x] closes #38906 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39046
2021-01-08T23:44:42Z
2021-01-10T02:39:54Z
2021-01-10T02:39:53Z
2021-01-10T02:39:57Z
Update awkward phrasing
diff --git a/doc/source/getting_started/intro_tutorials/04_plotting.rst b/doc/source/getting_started/intro_tutorials/04_plotting.rst index 615b944fd395f..a6d8142e68073 100644 --- a/doc/source/getting_started/intro_tutorials/04_plotting.rst +++ b/doc/source/getting_started/intro_tutorials/04_plotting.rst @@ -151,7 +151,7 @@ I want each of the columns in a separate subplot. Separate subplots for each of the data columns are supported by the ``subplots`` argument of the ``plot`` functions. The builtin options available in each of the pandas plot -functions that are worthwhile to have a look. +functions are worth reviewing. .. raw:: html
Docs: change "The builtin options available in each of the pandas plot functions that are worthwhile to have a look." to "The builtin options available in each of the pandas plot functions are worth reviewing."
https://api.github.com/repos/pandas-dev/pandas/pulls/39045
2021-01-08T23:10:20Z
2021-01-09T21:21:50Z
2021-01-09T21:21:50Z
2021-01-09T21:21:54Z
CI: use conda incubator in benchmarks
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 516d37a483ce4..b551e7ded0178 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,7 @@ name: CI on: push: - branches: master + branches: [master] pull_request: branches: - master @@ -10,16 +10,17 @@ on: env: ENV_FILE: environment.yml + PANDAS_CI: 1 jobs: checks: name: Checks runs-on: ubuntu-latest - steps: - - - name: Setting conda path - run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH + defaults: + run: + shell: bash -l {0} + steps: - name: Checkout uses: actions/checkout@v1 @@ -27,49 +28,55 @@ jobs: run: ci/code_checks.sh patterns if: always() - - name: Setup environment and build pandas - run: ci/setup_env.sh - if: always() + - name: Cache conda + uses: actions/cache@v2 + with: + path: ~/conda_pkgs_dir + key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }} - - name: Linting + - uses: conda-incubator/setup-miniconda@v2 + with: + activate-environment: pandas-dev + channel-priority: strict + environment-file: ${{ env.ENV_FILE }} + use-only-tar-bz2: true + + - name: Environment Detail run: | - source activate pandas-dev - ci/code_checks.sh lint + conda info + conda list + + - name: Build Pandas + run: | + python setup.py build_ext -j 2 + python -m pip install -e . --no-build-isolation --no-use-pep517 + + - name: Linting + run: ci/code_checks.sh lint if: always() - name: Checks on imported code - run: | - source activate pandas-dev - ci/code_checks.sh code + run: ci/code_checks.sh code if: always() - name: Running doctests - run: | - source activate pandas-dev - ci/code_checks.sh doctests + run: ci/code_checks.sh doctests if: always() - name: Docstring validation - run: | - source activate pandas-dev - ci/code_checks.sh docstrings + run: ci/code_checks.sh docstrings if: always() - name: Typing validation - run: | - source activate pandas-dev - ci/code_checks.sh typing + run: ci/code_checks.sh typing if: always() - name: Testing docstring validation script - run: | - source activate pandas-dev - pytest --capture=no --strict-markers scripts + run: pytest --capture=no --strict-markers scripts if: always() - name: Running benchmarks run: | - source activate pandas-dev cd asv_bench asv check -E existing git remote add upstream https://github.com/pandas-dev/pandas.git @@ -106,7 +113,6 @@ jobs: run: | source activate pandas-dev python web/pandas_web.py web/pandas --target-path=web/build - - name: Build documentation run: | source activate pandas-dev diff --git a/doc/source/user_guide/enhancingperf.rst b/doc/source/user_guide/enhancingperf.rst index 42621c032416d..49bb923dbec39 100644 --- a/doc/source/user_guide/enhancingperf.rst +++ b/doc/source/user_guide/enhancingperf.rst @@ -247,7 +247,7 @@ We've gotten another big improvement. Let's check again where the time is spent: .. ipython:: python - %%prun -l 4 apply_integrate_f(df["a"].to_numpy(), df["b"].to_numpy(), df["N"].to_numpy()) + %prun -l 4 apply_integrate_f(df["a"].to_numpy(), df["b"].to_numpy(), df["N"].to_numpy()) As one might expect, the majority of the time is now spent in ``apply_integrate_f``, so if we wanted to make anymore efficiencies we must continue to concentrate our diff --git a/doc/source/whatsnew/v0.8.0.rst b/doc/source/whatsnew/v0.8.0.rst index 781054fc4de7c..490175914cef1 100644 --- a/doc/source/whatsnew/v0.8.0.rst +++ b/doc/source/whatsnew/v0.8.0.rst @@ -176,7 +176,7 @@ New plotting methods Vytautas Jancauskas, the 2012 GSOC participant, has added many new plot types. For example, ``'kde'`` is a new option: -.. ipython:: python +.. code-block:: python s = pd.Series( np.concatenate((np.random.randn(1000), np.random.randn(1000) * 0.5 + 3))
The benchmark ci currently has the longest runtime. Using conda incubator would save about 6-8 min.
https://api.github.com/repos/pandas-dev/pandas/pulls/39043
2021-01-08T22:17:36Z
2021-01-14T19:14:50Z
2021-01-14T19:14:50Z
2021-03-18T16:37:14Z
REF: Prep for moving Series.apply into apply
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index ac98f3736be6d..6c503eefed54b 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -43,7 +43,7 @@ def frame_apply( result_type: Optional[str] = None, args=None, kwds=None, -): +) -> FrameApply: """ construct and return a row or column based frame apply object """ axis = obj._get_axis_number(axis) klass: Type[FrameApply] @@ -63,35 +63,9 @@ def frame_apply( ) -class FrameApply(metaclass=abc.ABCMeta): - - # --------------------------------------------------------------- - # Abstract Methods +class Apply(metaclass=abc.ABCMeta): axis: int - @property - @abc.abstractmethod - def result_index(self) -> Index: - pass - - @property - @abc.abstractmethod - def result_columns(self) -> Index: - pass - - @property - @abc.abstractmethod - def series_generator(self) -> Iterator[Series]: - pass - - @abc.abstractmethod - def wrap_results_for_axis( - self, results: ResType, res_index: Index - ) -> FrameOrSeriesUnion: - pass - - # --------------------------------------------------------------- - def __init__( self, obj: DataFrame, @@ -132,6 +106,42 @@ def f(x): self.f: AggFuncType = f + @property + def index(self) -> Index: + return self.obj.index + + @abc.abstractmethod + def get_result(self): + pass + + +class FrameApply(Apply): + # --------------------------------------------------------------- + # Abstract Methods + + @property + @abc.abstractmethod + def result_index(self) -> Index: + pass + + @property + @abc.abstractmethod + def result_columns(self) -> Index: + pass + + @property + @abc.abstractmethod + def series_generator(self) -> Iterator[Series]: + pass + + @abc.abstractmethod + def wrap_results_for_axis( + self, results: ResType, res_index: Index + ) -> FrameOrSeriesUnion: + pass + + # --------------------------------------------------------------- + @property def res_columns(self) -> Index: return self.result_columns @@ -140,10 +150,6 @@ def res_columns(self) -> Index: def columns(self) -> Index: return self.obj.columns - @property - def index(self) -> Index: - return self.obj.index - @cache_readonly def values(self): return self.obj.values
- [ ] closes #xxxx - [ ] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Will be moving Series.apply into apply next. The plan is to have a base class Apply which is parent to both FrameApply and SeriesApply.
https://api.github.com/repos/pandas-dev/pandas/pulls/39042
2021-01-08T21:31:27Z
2021-01-08T23:08:21Z
2021-01-08T23:08:21Z
2021-01-09T01:57:25Z
BUG: DataFrame.iloc.__setitem__ with IntegerArray values
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 94c7d325d0bc8..e4bb28c34dbe8 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -984,6 +984,14 @@ def setitem(self, indexer, value): values = values.astype(arr_value.dtype, copy=False) + elif is_ea_value: + # GH#38952 + if values.ndim == 1: + values[indexer] = value + else: + # TODO(EA2D): special case not needed with 2D EA + values[indexer] = value.to_numpy(values.dtype).reshape(-1, 1) + # set else: values[indexer] = value diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 24721a370241f..7dcb30efb8184 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -14,6 +14,7 @@ Index, NaT, Series, + array as pd_array, concat, date_range, isna, @@ -64,6 +65,24 @@ def test_iloc_getitem_list_int(self): class TestiLocBaseIndependent: """Tests Independent Of Base Class""" + @pytest.mark.parametrize("box", [pd_array, Series]) + def test_iloc_setitem_ea_inplace(self, frame_or_series, box): + # GH#38952 Case with not setting a full column + # IntegerArray without NAs + arr = pd_array([1, 2, 3, 4]) + obj = frame_or_series(arr.to_numpy("i8")) + values = obj.values + + obj.iloc[:2] = box(arr[2:]) + expected = frame_or_series(np.array([3, 4, 3, 4], dtype="i8")) + tm.assert_equal(obj, expected) + + # Check that we are actually in-place + if frame_or_series is Series: + assert obj.values is values + else: + assert obj.values.base is values.base and values.base is not None + def test_is_scalar_access(self): # GH#32085 index with duplicates doesnt matter for _is_scalar_access index = Index([1, 2, 1])
- [x] closes #38952 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39040
2021-01-08T19:23:03Z
2021-01-09T22:26:22Z
2021-01-09T22:26:22Z
2021-01-09T23:27:40Z
CLN, TYP use from __future__ import annotations
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index aeae39094ba7c..e65e9302dd4d5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3220,7 +3220,7 @@ def _setitem_frame(self, key, value): self._check_setitem_copy() self._where(-key, value, inplace=True) - def _set_item_frame_value(self, key, value: "DataFrame") -> None: + def _set_item_frame_value(self, key, value: DataFrame) -> None: self._ensure_valid_index(value) # align right-hand-side columns if self.columns diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 60b526426d413..12694c19b2173 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from contextlib import suppress from typing import TYPE_CHECKING, Any, Hashable, List, Sequence, Tuple, Union import warnings @@ -1742,7 +1744,7 @@ def _setitem_with_indexer_2d_value(self, indexer, value): # setting with a list, re-coerces self._setitem_single_column(loc, value[:, i].tolist(), pi) - def _setitem_with_indexer_frame_value(self, indexer, value: "DataFrame", name: str): + def _setitem_with_indexer_frame_value(self, indexer, value: DataFrame, name: str): ilocs = self._ensure_iterable_column_indexer(indexer[1]) sub_indexer = list(indexer) @@ -2032,7 +2034,7 @@ def ravel(i): raise ValueError("Incompatible indexer with Series") - def _align_frame(self, indexer, df: "DataFrame"): + def _align_frame(self, indexer, df: DataFrame): is_frame = self.ndim == 2 if isinstance(indexer, tuple): @@ -2204,7 +2206,7 @@ def _tuplify(ndim: int, loc: Hashable) -> Tuple[Union[Hashable, slice], ...]: return tuple(_tup) -def convert_to_index_sliceable(obj: "DataFrame", key): +def convert_to_index_sliceable(obj: DataFrame, key): """ If we are index sliceable, then return my slicer, otherwise return None. """ diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 7b14a5c636abe..cea8cc1ff28b4 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -3,6 +3,8 @@ This is not a public API. """ +from __future__ import annotations + import operator from typing import TYPE_CHECKING, Optional, Set import warnings @@ -293,7 +295,7 @@ def to_series(right): def should_reindex_frame_op( - left: "DataFrame", right, op, axis, default_axis, fill_value, level + left: DataFrame, right, op, axis, default_axis, fill_value, level ) -> bool: """ Check if this is an operation between DataFrames that will need to reindex. @@ -322,7 +324,7 @@ def should_reindex_frame_op( def frame_arith_method_with_reindex( - left: "DataFrame", right: "DataFrame", op + left: DataFrame, right: DataFrame, op ) -> "DataFrame": """ For DataFrame-with-DataFrame operations that require reindexing, @@ -367,7 +369,7 @@ def frame_arith_method_with_reindex( return result -def _maybe_align_series_as_frame(frame: "DataFrame", series: "Series", axis: int): +def _maybe_align_series_as_frame(frame: DataFrame, series: "Series", axis: int): """ If the Series operand is not EA-dtype, we can broadcast to 2D and operate blockwise. diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index f49aaee8bbc00..e58e27438ad33 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import re from typing import TYPE_CHECKING, List, cast import warnings @@ -24,7 +26,7 @@ @Appender(_shared_docs["melt"] % {"caller": "pd.melt(df, ", "other": "DataFrame.melt"}) def melt( - frame: "DataFrame", + frame: DataFrame, id_vars=None, value_vars=None, var_name=None, @@ -139,7 +141,7 @@ def melt( @deprecate_kwarg(old_arg_name="label", new_arg_name=None) -def lreshape(data: "DataFrame", groups, dropna: bool = True, label=None) -> "DataFrame": +def lreshape(data: DataFrame, groups, dropna: bool = True, label=None) -> "DataFrame": """ Reshape wide-format data to long. Generalized inverse of DataFrame.pivot. @@ -234,7 +236,7 @@ def lreshape(data: "DataFrame", groups, dropna: bool = True, label=None) -> "Dat def wide_to_long( - df: "DataFrame", stubnames, i, j, sep: str = "", suffix: str = r"\d+" + df: DataFrame, stubnames, i, j, sep: str = "", suffix: str = r"\d+" ) -> "DataFrame": r""" Wide panel to long format. Less flexible but more user-friendly than melt. diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 1caf1a2a023da..cf5fd58748bb0 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1,6 +1,7 @@ """ SQL-style merge routines """ +from __future__ import annotations import copy import datetime @@ -99,7 +100,7 @@ def merge( merge.__doc__ = _merge_doc % "\nleft : DataFrame" -def _groupby_and_merge(by, on, left: "DataFrame", right: "DataFrame", merge_pieces): +def _groupby_and_merge(by, on, left: DataFrame, right: DataFrame, merge_pieces): """ groupby & merge; we are always performing a left-by type operation @@ -157,8 +158,8 @@ def _groupby_and_merge(by, on, left: "DataFrame", right: "DataFrame", merge_piec def merge_ordered( - left: "DataFrame", - right: "DataFrame", + left: DataFrame, + right: DataFrame, on: Optional[IndexLabel] = None, left_on: Optional[IndexLabel] = None, right_on: Optional[IndexLabel] = None, @@ -300,8 +301,8 @@ def _merger(x, y): def merge_asof( - left: "DataFrame", - right: "DataFrame", + left: DataFrame, + right: DataFrame, on: Optional[IndexLabel] = None, left_on: Optional[IndexLabel] = None, right_on: Optional[IndexLabel] = None, @@ -717,12 +718,12 @@ def get_result(self): return result.__finalize__(self, method="merge") - def _maybe_drop_cross_column(self, result: "DataFrame", cross_col: Optional[str]): + def _maybe_drop_cross_column(self, result: DataFrame, cross_col: Optional[str]): if cross_col is not None: result.drop(columns=cross_col, inplace=True) def _indicator_pre_merge( - self, left: "DataFrame", right: "DataFrame" + self, left: DataFrame, right: DataFrame ) -> Tuple["DataFrame", "DataFrame"]: columns = left.columns.union(right.columns) @@ -1230,7 +1231,7 @@ def _maybe_coerce_merge_keys(self): self.right = self.right.assign(**{name: self.right[name].astype(typ)}) def _create_cross_configuration( - self, left: "DataFrame", right: "DataFrame" + self, left: DataFrame, right: DataFrame ) -> Tuple["DataFrame", "DataFrame", str, str]: """ Creates the configuration to dispatch the cross operation to inner join, @@ -1546,8 +1547,8 @@ class _OrderedMerge(_MergeOperation): def __init__( self, - left: "DataFrame", - right: "DataFrame", + left: DataFrame, + right: DataFrame, on: Optional[IndexLabel] = None, left_on: Optional[IndexLabel] = None, right_on: Optional[IndexLabel] = None, @@ -1640,8 +1641,8 @@ class _AsOfMerge(_OrderedMerge): def __init__( self, - left: "DataFrame", - right: "DataFrame", + left: DataFrame, + right: DataFrame, on: Optional[IndexLabel] = None, left_on: Optional[IndexLabel] = None, right_on: Optional[IndexLabel] = None, diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 8e4b000a56a3d..bdbd8c7b8dff6 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from typing import ( TYPE_CHECKING, Callable, @@ -367,7 +369,7 @@ def _all_key(key): def _generate_marginal_results_without_values( - table: "DataFrame", data, rows, cols, aggfunc, observed, margins_name: str = "All" + table: DataFrame, data, rows, cols, aggfunc, observed, margins_name: str = "All" ): if len(cols) > 0: # need to "interleave" the margins @@ -421,7 +423,7 @@ def _convert_by(by): @Substitution("\ndata : DataFrame") @Appender(_shared_docs["pivot"], indents=1) def pivot( - data: "DataFrame", + data: DataFrame, index: Optional[Union[Label, Sequence[Label]]] = None, columns: Optional[Union[Label, Sequence[Label]]] = None, values: Optional[Union[Label, Sequence[Label]]] = None, diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 393c517a63660..29e7050639a2d 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -2,6 +2,8 @@ Provide a generic structure to support window functions, similar to how we have a Groupby object. """ +from __future__ import annotations + from datetime import timedelta from functools import partial import inspect @@ -314,7 +316,7 @@ def _prep_values(self, values: Optional[np.ndarray] = None) -> np.ndarray: return values - def _insert_on_column(self, result: "DataFrame", obj: "DataFrame"): + def _insert_on_column(self, result: DataFrame, obj: DataFrame): # if we have an 'on' column we want to put it back into # the results in the same location from pandas import Series diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 8265d5ef8f94b..6426f9e780eef 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -2,6 +2,7 @@ Internal module for formatting output data in csv, html, and latex files. This module also applies to display formatting. """ +from __future__ import annotations from contextlib import contextmanager from csv import QUOTE_NONE, QUOTE_NONNUMERIC @@ -462,7 +463,7 @@ class DataFrameFormatter: def __init__( self, - frame: "DataFrame", + frame: DataFrame, columns: Optional[Sequence[str]] = None, col_space: Optional[ColspaceArgType] = None, header: Union[bool, Sequence[str]] = True, @@ -813,7 +814,7 @@ def _get_formatter(self, i: Union[str, int]) -> Optional[Callable]: i = self.columns[i] return self.formatters.get(i, None) - def _get_formatted_column_labels(self, frame: "DataFrame") -> List[List[str]]: + def _get_formatted_column_labels(self, frame: DataFrame) -> List[List[str]]: from pandas.core.indexes.multi import sparsify_labels columns = frame.columns @@ -854,7 +855,7 @@ def space_format(x, y): # self.str_columns = str_columns return str_columns - def _get_formatted_index(self, frame: "DataFrame") -> List[str]: + def _get_formatted_index(self, frame: DataFrame) -> List[str]: # Note: this is only used by to_string() and to_latex(), not by # to_html(). so safe to cast col_space here. col_space = {k: cast(int, v) for k, v in self.col_space.items()} diff --git a/pandas/io/formats/info.py b/pandas/io/formats/info.py index 98bd159c567b1..c4575bc07c149 100644 --- a/pandas/io/formats/info.py +++ b/pandas/io/formats/info.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from abc import ABC, abstractmethod import sys from typing import ( @@ -227,10 +229,10 @@ class DataFrameInfo(BaseInfo): def __init__( self, - data: "DataFrame", + data: DataFrame, memory_usage: Optional[Union[bool, str]] = None, ): - self.data: "DataFrame" = data + self.data: DataFrame = data self.memory_usage = _initialize_memory_usage(memory_usage) @property @@ -679,7 +681,7 @@ def _gen_columns(self) -> Iterator[str]: yield pprint_thing(col) -def _get_dataframe_dtype_counts(df: "DataFrame") -> Mapping[str, int]: +def _get_dataframe_dtype_counts(df: DataFrame) -> Mapping[str, int]: """ Create mapping between datatypes and their number of occurences. """ diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py index afe1234f9fa96..39f25750aa774 100644 --- a/pandas/io/gbq.py +++ b/pandas/io/gbq.py @@ -1,4 +1,6 @@ """ Google BigQuery support """ +from __future__ import annotations + from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union from pandas.compat._optional import import_optional_dependency @@ -195,7 +197,7 @@ def read_gbq( def to_gbq( - dataframe: "DataFrame", + dataframe: DataFrame, destination_table: str, project_id: Optional[str] = None, chunksize: Optional[int] = None, diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 795239ab78c6e..ab8f94596ff1a 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import importlib from typing import TYPE_CHECKING, Optional, Sequence, Tuple, Union @@ -99,7 +101,7 @@ def hist_series( def hist_frame( - data: "DataFrame", + data: DataFrame, column: Union[Label, Sequence[Label]] = None, by=None, grid: bool = True, diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index c564e6ed39f7d..64078abfd9220 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import random from typing import TYPE_CHECKING, Dict, List, Optional, Set @@ -21,7 +23,7 @@ def scatter_matrix( - frame: "DataFrame", + frame: DataFrame, alpha=0.5, figsize=None, ax=None, @@ -124,7 +126,7 @@ def _get_marker_compat(marker): def radviz( - frame: "DataFrame", + frame: DataFrame, class_column, ax: Optional["Axes"] = None, color=None, @@ -212,7 +214,7 @@ def normalize(series): def andrews_curves( - frame: "DataFrame", + frame: DataFrame, class_column, ax: Optional["Axes"] = None, samples: int = 200, @@ -334,7 +336,7 @@ def bootstrap_plot( def parallel_coordinates( - frame: "DataFrame", + frame: DataFrame, class_column, cols=None, ax: Optional["Axes"] = None,
Seeing as pandas is Python3.7+ we can clean up some annotations. Not yet figured out how to write a good automated check for this, but here's a start
https://api.github.com/repos/pandas-dev/pandas/pulls/39036
2021-01-08T12:30:21Z
2021-01-08T13:23:38Z
2021-01-08T13:23:38Z
2021-01-10T13:59:02Z
API: concatting DataFrames does not skip empty objects
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 9e557a0020f1e..c2372b0e6b9a1 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -312,8 +312,8 @@ Reshaping - Bug in :func:`merge` raising error when performing an inner join with partial index and ``right_index`` when no overlap between indices (:issue:`33814`) - Bug in :meth:`DataFrame.unstack` with missing levels led to incorrect index names (:issue:`37510`) - Bug in :func:`join` over :class:`MultiIndex` returned wrong result, when one of both indexes had only one level (:issue:`36909`) -- Bug in :func:`concat` incorrectly casting to ``object`` dtype in some cases when one or more of the operands is empty (:issue:`38843`, :issue:`38907`) - :meth:`merge_asof` raises ``ValueError`` instead of cryptic ``TypeError`` in case of non-numerical merge columns (:issue:`29130`) +- Sparse ^^^^^^ diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index d768f83e4d36b..624e71a5cf760 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -127,7 +127,7 @@ def is_nonempty(x) -> bool: # marginal given that it would still require shape & dtype calculation and # np.concatenate which has them both implemented is compiled. non_empties = [x for x in to_concat if is_nonempty(x)] - if non_empties: + if non_empties and axis == 0: to_concat = non_empties typs = _get_dtype_kinds(to_concat) diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 5e587dd9f9472..f97077954f8bf 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -318,12 +318,6 @@ def _concatenate_join_units( # Concatenating join units along ax0 is handled in _merge_blocks. raise AssertionError("Concatenating join units along axis0") - nonempties = [ - x for x in join_units if x.block is None or x.block.shape[concat_axis] > 0 - ] - if nonempties: - join_units = nonempties - empty_dtype, upcasted_na = _get_empty_dtype_and_na(join_units) to_concat = [ diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index f2d628c70ae62..0251fb4a0ebd6 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -154,8 +154,7 @@ def test_partial_setting_mixed_dtype(self): # columns will align df = DataFrame(columns=["A", "B"]) df.loc[0] = Series(1, index=range(4)) - expected = DataFrame(columns=["A", "B"], index=[0], dtype=int) - tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(df, DataFrame(columns=["A", "B"], index=[0])) # columns will align df = DataFrame(columns=["A", "B"]) @@ -171,21 +170,11 @@ def test_partial_setting_mixed_dtype(self): with pytest.raises(ValueError, match=msg): df.loc[0] = [1, 2, 3] - @pytest.mark.parametrize("dtype", [None, "int64", "Int64"]) - def test_loc_setitem_expanding_empty(self, dtype): + # TODO: #15657, these are left as object and not coerced df = DataFrame(columns=["A", "B"]) + df.loc[3] = [6, 7] - value = [6, 7] - if dtype == "int64": - value = np.array(value, dtype=dtype) - elif dtype == "Int64": - value = pd.array(value, dtype=dtype) - - df.loc[3] = value - - exp = DataFrame([[6, 7]], index=[3], columns=["A", "B"], dtype=dtype) - if dtype is not None: - exp = exp.astype(dtype) + exp = DataFrame([[6, 7]], index=[3], columns=["A", "B"], dtype="object") tm.assert_frame_equal(df, exp) def test_series_partial_set(self): diff --git a/pandas/tests/reshape/concat/test_append.py b/pandas/tests/reshape/concat/test_append.py index 1a895aee98f0a..ffeda703cd890 100644 --- a/pandas/tests/reshape/concat/test_append.py +++ b/pandas/tests/reshape/concat/test_append.py @@ -82,7 +82,6 @@ def test_append_length0_frame(self, sort): df5 = df.append(df3, sort=sort) expected = DataFrame(index=[0, 1], columns=["A", "B", "C"]) - expected["C"] = expected["C"].astype(np.float64) tm.assert_frame_equal(df5, expected) def test_append_records(self): @@ -341,11 +340,16 @@ def test_append_empty_frame_to_series_with_dateutil_tz(self): expected = DataFrame( [[np.nan, np.nan, 1.0, 2.0, date]], columns=["c", "d", "a", "b", "date"] ) + # These columns get cast to object after append + expected["c"] = expected["c"].astype(object) + expected["d"] = expected["d"].astype(object) tm.assert_frame_equal(result_a, expected) expected = DataFrame( [[np.nan, np.nan, 1.0, 2.0, date]] * 2, columns=["c", "d", "a", "b", "date"] ) + expected["c"] = expected["c"].astype(object) + expected["d"] = expected["d"].astype(object) result_b = result_a.append(s, ignore_index=True) tm.assert_frame_equal(result_b, expected) diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index 4750f9b0c40a3..16c4e9456aa05 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -474,12 +474,11 @@ def test_concat_will_upcast(dt, pdt): assert x.values.dtype == "float64" -@pytest.mark.parametrize("dtype", ["int64", "Int64"]) -def test_concat_empty_and_non_empty_frame_regression(dtype): +def test_concat_empty_and_non_empty_frame_regression(): # GH 18178 regression test - df1 = DataFrame({"foo": [1]}).astype(dtype) + df1 = DataFrame({"foo": [1]}) df2 = DataFrame({"foo": []}) - expected = df1 + expected = DataFrame({"foo": [1.0]}) result = pd.concat([df1, df2]) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/concat/test_empty.py b/pandas/tests/reshape/concat/test_empty.py index 075785120677a..a97e9265b4f99 100644 --- a/pandas/tests/reshape/concat/test_empty.py +++ b/pandas/tests/reshape/concat/test_empty.py @@ -202,14 +202,12 @@ def test_concat_empty_series_dtypes_sparse(self): expected = pd.SparseDtype("object") assert result.dtype == expected - @pytest.mark.parametrize("dtype", ["int64", "Int64"]) - def test_concat_empty_df_object_dtype(self, dtype): + def test_concat_empty_df_object_dtype(self): # GH 9149 df_1 = DataFrame({"Row": [0, 1, 1], "EmptyCol": np.nan, "NumberCol": [1, 2, 3]}) - df_1["Row"] = df_1["Row"].astype(dtype) df_2 = DataFrame(columns=df_1.columns) result = pd.concat([df_1, df_2], axis=0) - expected = df_1.copy() + expected = df_1.astype(object) tm.assert_frame_equal(result, expected) def test_concat_empty_dataframe_dtypes(self):
See discussion in https://github.com/pandas-dev/pandas/pull/38843 To repeat the main argument: when not skipping empty objects, the resulting dtype of a concat-operation only depends on the input *dtypes*, and not on the exact content (the exact values, how many values (shape)). In general we want to get rid of value-dependent behaviour. In the past we discussed this in the context of the certain values (eg presence of NaNs or not), but I think also the shape should not matter (eg when slicing dataframes before contatting, you can get empties or not depending on *values*). This starts with reverting the change for DataFrame. If we opt for this behaviour, in addition we should also discuss how to change the Series behaviour. cc @jbrockmendel
https://api.github.com/repos/pandas-dev/pandas/pulls/39035
2021-01-08T09:28:29Z
2021-01-08T15:58:27Z
2021-01-08T15:58:27Z
2021-01-12T08:36:34Z
CLN/INT: remove Index as a sub-class of NDArray
diff --git a/doc/source/api.rst b/doc/source/api.rst index 88aab0ced8420..9d443254ae25a 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -1104,6 +1104,8 @@ Modifying and Computations Index.order Index.reindex Index.repeat + Index.take + Index.putmask Index.set_names Index.unique Index.nunique diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index 39635cb0e612f..8ec61496c538a 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -52,6 +52,12 @@ indexing. should be avoided. See :ref:`Returning a View versus Copy <indexing.view_versus_copy>` +.. warning:: + + In 0.15.0 ``Index`` has internally been refactored to no longer sub-class ``ndarray`` + but instead subclass ``PandasObject``, similarly to the rest of the pandas objects. This should be + a transparent change with only very limited API implications (See the :ref:`Internal Refactoring <whatsnew_0150.refactoring>`) + See the :ref:`cookbook<cookbook.selection>` for some advanced strategies Different Choices for Indexing (``loc``, ``iloc``, and ``ix``) @@ -2175,7 +2181,7 @@ you can specify ``inplace=True`` to have the data change in place. .. versionadded:: 0.15.0 -``set_names``, ``set_levels``, and ``set_labels`` also take an optional +``set_names``, ``set_levels``, and ``set_labels`` also take an optional `level`` argument .. ipython:: python diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index 7623bf287bcd3..bb039b4484c7d 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -10,6 +10,7 @@ users upgrade to this version. - Highlights include: - The ``Categorical`` type was integrated as a first-class pandas type, see :ref:`here <whatsnew_0150.cat>` + - Internal refactoring of the ``Index`` class to no longer sub-class ``ndarray``, see :ref:`Internal Refactoring <whatsnew_0150.refactoring>` - :ref:`Other Enhancements <whatsnew_0150.enhancements>` @@ -25,6 +26,12 @@ users upgrade to this version. - :ref:`Bug Fixes <whatsnew_0150.bug_fixes>` +.. warning:: + + In 0.15.0 ``Index`` has internally been refactored to no longer sub-class ``ndarray`` + but instead subclass ``PandasObject``, similarly to the rest of the pandas objects. This change allows very easy sub-classing and creation of new index types. This should be + a transparent change with only very limited API implications (See the :ref:`Internal Refactoring <whatsnew_0150.refactoring>`) + .. _whatsnew_0150.api: API changes @@ -155,6 +162,18 @@ previously results in ``Exception`` or ``TypeError`` (:issue:`7812`) didx didx.tz_localize(None) +.. _whatsnew_0150.refactoring: + +Internal Refactoring +~~~~~~~~~~~~~~~~~~~~ + +In 0.15.0 ``Index`` has internally been refactored to no longer sub-class ``ndarray`` +but instead subclass ``PandasObject``, similarly to the rest of the pandas objects. This change allows very easy sub-classing and creation of new index types. This should be +a transparent change with only very limited API implications (:issue:`5080`,:issue:`7439`,:issue:`7796`) + +- you may need to unpickle pandas version < 0.15.0 pickles using ``pd.read_pickle`` rather than ``pickle.load``. See :ref:`pickle docs <io.pickle>` +- when plotting with a ``PeriodIndex``. The ``matplotlib`` internal axes will now be arrays of ``Period`` rather than a ``PeriodIndex``. (this is similar to how a ``DatetimeIndex`` passess arrays of ``datetimes`` now) + .. _whatsnew_0150.cat: Categoricals in Series/DataFrame @@ -278,7 +297,7 @@ Performance ~~~~~~~~~~~ - Performance improvements in ``DatetimeIndex.__iter__`` to allow faster iteration (:issue:`7683`) - +- Performance improvements in ``Period`` creation (and ``PeriodIndex`` setitem) (:issue:`5155`) @@ -386,7 +405,7 @@ Bug Fixes - Bug in ``GroupBy.filter()`` where fast path vs. slow path made the filter return a non scalar value that appeared valid but wasn't (:issue:`7870`). - Bug in ``date_range()``/``DatetimeIndex()`` when the timezone was inferred from input dates yet incorrect - times were returned when crossing DST boundaries (:issue:`7835`, :issue:`7901`). + times were returned when crossing DST boundaries (:issue:`7835`, :issue:`7901`). diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py index 03b45336833d3..e794725574119 100644 --- a/pandas/compat/pickle_compat.py +++ b/pandas/compat/pickle_compat.py @@ -5,29 +5,32 @@ import pandas import copy import pickle as pkl -from pandas import compat +from pandas import compat, Index from pandas.compat import u, string_types -from pandas.core.series import Series, TimeSeries -from pandas.sparse.series import SparseSeries, SparseTimeSeries - def load_reduce(self): stack = self.stack args = stack.pop() func = stack[-1] + if type(args[0]) is type: n = args[0].__name__ - if n == u('DeprecatedSeries') or n == u('DeprecatedTimeSeries'): - stack[-1] = object.__new__(Series) - return - elif (n == u('DeprecatedSparseSeries') or - n == u('DeprecatedSparseTimeSeries')): - stack[-1] = object.__new__(SparseSeries) - return try: - value = func(*args) - except: + stack[-1] = func(*args) + return + except Exception as e: + + # if we have a deprecated function + # try to replace and try again + + if '_reconstruct: First argument must be a sub-type of ndarray' in str(e): + try: + cls = args[0] + stack[-1] = object.__new__(cls) + return + except: + pass # try to reencode the arguments if getattr(self,'encoding',None) is not None: @@ -57,6 +60,35 @@ class Unpickler(pkl.Unpickler): Unpickler.dispatch = copy.copy(Unpickler.dispatch) Unpickler.dispatch[pkl.REDUCE[0]] = load_reduce +def load_newobj(self): + args = self.stack.pop() + cls = self.stack[-1] + + # compat + if issubclass(cls, Index): + obj = object.__new__(cls) + else: + obj = cls.__new__(cls, *args) + + self.stack[-1] = obj +Unpickler.dispatch[pkl.NEWOBJ[0]] = load_newobj + +# py3 compat +def load_newobj_ex(self): + kwargs = self.stack.pop() + args = self.stack.pop() + cls = self.stack.pop() + + # compat + if issubclass(cls, Index): + obj = object.__new__(cls) + else: + obj = cls.__new__(cls, *args, **kwargs) + self.append(obj) +try: + Unpickler.dispatch[pkl.NEWOBJ_EX[0]] = load_newobj_ex +except: + pass def load(fh, encoding=None, compat=False, is_verbose=False): """load a pickle, with a provided encoding @@ -74,11 +106,6 @@ def load(fh, encoding=None, compat=False, is_verbose=False): """ try: - if compat: - pandas.core.series.Series = DeprecatedSeries - pandas.core.series.TimeSeries = DeprecatedTimeSeries - pandas.sparse.series.SparseSeries = DeprecatedSparseSeries - pandas.sparse.series.SparseTimeSeries = DeprecatedSparseTimeSeries fh.seek(0) if encoding is not None: up = Unpickler(fh, encoding=encoding) @@ -89,25 +116,3 @@ def load(fh, encoding=None, compat=False, is_verbose=False): return up.load() except: raise - finally: - if compat: - pandas.core.series.Series = Series - pandas.core.series.Series = TimeSeries - pandas.sparse.series.SparseSeries = SparseSeries - pandas.sparse.series.SparseTimeSeries = SparseTimeSeries - - -class DeprecatedSeries(np.ndarray, Series): - pass - - -class DeprecatedTimeSeries(DeprecatedSeries): - pass - - -class DeprecatedSparseSeries(DeprecatedSeries): - pass - - -class DeprecatedSparseTimeSeries(DeprecatedSparseSeries): - pass diff --git a/pandas/core/base.py b/pandas/core/base.py index beffbfb2923db..f685edd477b8c 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -8,7 +8,7 @@ from pandas.core import common as com import pandas.core.nanops as nanops import pandas.tslib as tslib -from pandas.util.decorators import cache_readonly +from pandas.util.decorators import Appender, cache_readonly class StringMixin(object): @@ -205,6 +205,19 @@ def __unicode__(self): quote_strings=True) return "%s(%s, dtype='%s')" % (type(self).__name__, prepr, self.dtype) +def _unbox(func): + @Appender(func.__doc__) + def f(self, *args, **kwargs): + result = func(self.values, *args, **kwargs) + from pandas.core.index import Index + if isinstance(result, (np.ndarray, com.ABCSeries, Index)) and result.ndim == 0: + # return NumPy type + return result.dtype.type(result.item()) + else: # pragma: no cover + return result + f.__name__ = func.__name__ + return f + class IndexOpsMixin(object): """ common ops mixin to support a unified inteface / docs for Series / Index """ @@ -238,6 +251,64 @@ def _wrap_access_object(self, obj): return obj + # ndarray compatibility + __array_priority__ = 1000 + + def transpose(self): + """ return the transpose, which is by definition self """ + return self + + T = property(transpose, doc="return the transpose, which is by definition self") + + @property + def shape(self): + """ return a tuple of the shape of the underlying data """ + return self._data.shape + + @property + def ndim(self): + """ return the number of dimensions of the underlying data, by definition 1 """ + return 1 + + def item(self): + """ return the first element of the underlying data as a python scalar """ + return self.values.item() + + @property + def data(self): + """ return the data pointer of the underlying data """ + return self.values.data + + @property + def itemsize(self): + """ return the size of the dtype of the item of the underlying data """ + return self.values.itemsize + + @property + def nbytes(self): + """ return the number of bytes in the underlying data """ + return self.values.nbytes + + @property + def strides(self): + """ return the strides of the underlying data """ + return self.values.strides + + @property + def size(self): + """ return the number of elements in the underlying data """ + return self.values.size + + @property + def flags(self): + """ return the ndarray.flags for the underlying data """ + return self.values.flags + + @property + def base(self): + """ return the base object if the memory of the underlying data is shared """ + return self.values.base + def max(self): """ The maximum value of the object """ return nanops.nanmax(self.values) @@ -340,6 +411,20 @@ def factorize(self, sort=False, na_sentinel=-1): from pandas.core.algorithms import factorize return factorize(self, sort=sort, na_sentinel=na_sentinel) + def searchsorted(self, key, side='left'): + """ np.ndarray searchsorted compat """ + + ### FIXME in GH7447 + #### needs coercion on the key (DatetimeIndex does alreay) + #### needs tests/doc-string + return self.values.searchsorted(key, side=side) + + #---------------------------------------------------------------------- + # unbox reductions + + all = _unbox(np.ndarray.all) + any = _unbox(np.ndarray.any) + # facilitate the properties on the wrapped ops def _field_accessor(name, docstring=None): op_accessor = '_{0}'.format(name) @@ -431,13 +516,17 @@ def asobject(self): def tolist(self): """ - See ndarray.tolist + return a list of the underlying data """ return list(self.asobject) def min(self, axis=None): """ - Overridden ndarray.min to return an object + return the minimum value of the Index + + See also + -------- + numpy.ndarray.min """ try: i8 = self.asi8 @@ -456,9 +545,30 @@ def min(self, axis=None): except ValueError: return self._na_value + def argmin(self, axis=None): + """ + return a ndarray of the minimum argument indexer + + See also + -------- + numpy.ndarray.argmin + """ + + ##### FIXME: need some tests (what do do if all NaT?) + i8 = self.asi8 + if self.hasnans: + mask = i8 == tslib.iNaT + i8 = i8.copy() + i8[mask] = np.iinfo('int64').max + return i8.argmin() + def max(self, axis=None): """ - Overridden ndarray.max to return an object + return the maximum value of the Index + + See also + -------- + numpy.ndarray.max """ try: i8 = self.asi8 @@ -477,6 +587,23 @@ def max(self, axis=None): except ValueError: return self._na_value + def argmax(self, axis=None): + """ + return a ndarray of the maximum argument indexer + + See also + -------- + numpy.ndarray.argmax + """ + + #### FIXME: need some tests (what do do if all NaT?) + i8 = self.asi8 + if self.hasnans: + mask = i8 == tslib.iNaT + i8 = i8.copy() + i8[mask] = 0 + return i8.argmax() + @property def _formatter_func(self): """ diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index f9ed6c2fecc3c..c9674aea4a715 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -939,6 +939,6 @@ def _get_codes_for_values(values, levels): levels = com._ensure_object(levels) (hash_klass, vec_klass), vals = _get_data_algo(values, _hashtables) t = hash_klass(len(levels)) - t.map_locations(levels) + t.map_locations(com._values_from_object(levels)) return com._ensure_platform_int(t.lookup(values)) diff --git a/pandas/core/common.py b/pandas/core/common.py index 04c5140d6a59b..d8314977742a4 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -205,7 +205,7 @@ def _isnull_new(obj): # hack (for now) because MI registers as ndarray elif isinstance(obj, pd.MultiIndex): raise NotImplementedError("isnull is not defined for MultiIndex") - elif isinstance(obj, (ABCSeries, np.ndarray)): + elif isinstance(obj, (ABCSeries, np.ndarray, pd.Index)): return _isnull_ndarraylike(obj) elif isinstance(obj, ABCGeneric): return obj._constructor(obj._data.isnull(func=isnull)) @@ -231,7 +231,7 @@ def _isnull_old(obj): # hack (for now) because MI registers as ndarray elif isinstance(obj, pd.MultiIndex): raise NotImplementedError("isnull is not defined for MultiIndex") - elif isinstance(obj, (ABCSeries, np.ndarray)): + elif isinstance(obj, (ABCSeries, np.ndarray, pd.Index)): return _isnull_ndarraylike_old(obj) elif isinstance(obj, ABCGeneric): return obj._constructor(obj._data.isnull(func=_isnull_old)) @@ -2024,8 +2024,7 @@ def _is_bool_indexer(key): def _default_index(n): from pandas.core.index import Int64Index values = np.arange(n, dtype=np.int64) - result = values.view(Int64Index) - result.name = None + result = Int64Index(values,name=None) result.is_unique = True return result diff --git a/pandas/core/format.py b/pandas/core/format.py index be4074bdb0ae7..8f749d07296a7 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -1186,7 +1186,7 @@ def _helper_csv(self, writer, na_rep=None, cols=None, if cols is None: cols = self.columns - has_aliases = isinstance(header, (tuple, list, np.ndarray)) + has_aliases = isinstance(header, (tuple, list, np.ndarray, Index)) if has_aliases or header: if index: # should write something for index label @@ -1205,7 +1205,7 @@ def _helper_csv(self, writer, na_rep=None, cols=None, else: index_label = [index_label] elif not isinstance(index_label, - (list, tuple, np.ndarray)): + (list, tuple, np.ndarray, Index)): # given a string for a DF with Index index_label = [index_label] @@ -1327,7 +1327,7 @@ def _save_header(self): header = self.header encoded_labels = [] - has_aliases = isinstance(header, (tuple, list, np.ndarray)) + has_aliases = isinstance(header, (tuple, list, np.ndarray, Index)) if not (has_aliases or self.header): return if has_aliases: @@ -1355,7 +1355,7 @@ def _save_header(self): index_label = [''] else: index_label = [index_label] - elif not isinstance(index_label, (list, tuple, np.ndarray)): + elif not isinstance(index_label, (list, tuple, np.ndarray, Index)): # given a string for a DF with Index index_label = [index_label] @@ -1520,7 +1520,7 @@ def _format_value(self, val): return val def _format_header_mi(self): - has_aliases = isinstance(self.header, (tuple, list, np.ndarray)) + has_aliases = isinstance(self.header, (tuple, list, np.ndarray, Index)) if not(has_aliases or self.header): return @@ -1566,7 +1566,7 @@ def _format_header_mi(self): self.rowcounter = lnum def _format_header_regular(self): - has_aliases = isinstance(self.header, (tuple, list, np.ndarray)) + has_aliases = isinstance(self.header, (tuple, list, np.ndarray, Index)) if has_aliases or self.header: coloffset = 0 @@ -1611,7 +1611,7 @@ def _format_body(self): return self._format_regular_rows() def _format_regular_rows(self): - has_aliases = isinstance(self.header, (tuple, list, np.ndarray)) + has_aliases = isinstance(self.header, (tuple, list, np.ndarray, Index)) if has_aliases or self.header: self.rowcounter += 1 @@ -1621,7 +1621,7 @@ def _format_regular_rows(self): # chek aliases # if list only take first as this is not a MultiIndex if self.index_label and isinstance(self.index_label, - (list, tuple, np.ndarray)): + (list, tuple, np.ndarray, Index)): index_label = self.index_label[0] # if string good to go elif self.index_label and isinstance(self.index_label, str): @@ -1661,7 +1661,7 @@ def _format_regular_rows(self): yield ExcelCell(self.rowcounter + i, colidx + coloffset, val) def _format_hierarchical_rows(self): - has_aliases = isinstance(self.header, (tuple, list, np.ndarray)) + has_aliases = isinstance(self.header, (tuple, list, np.ndarray, Index)) if has_aliases or self.header: self.rowcounter += 1 @@ -1671,7 +1671,7 @@ def _format_hierarchical_rows(self): index_labels = self.df.index.names # check for aliases if self.index_label and isinstance(self.index_label, - (list, tuple, np.ndarray)): + (list, tuple, np.ndarray, Index)): index_labels = self.index_label # if index labels are not empty go ahead and dump diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 516d87bb25f5d..3979ae76f14c3 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -220,7 +220,7 @@ def __init__(self, data=None, index=None, columns=None, dtype=None, mgr = self._init_ndarray(data, index, columns, dtype=dtype, copy=copy) - elif isinstance(data, (np.ndarray, Series)): + elif isinstance(data, (np.ndarray, Series, Index)): if data.dtype.names: data_columns = list(data.dtype.names) data = dict((k, data[k]) for k in data_columns) @@ -593,7 +593,7 @@ def dot(self, other): columns=other.columns) elif isinstance(other, Series): return Series(np.dot(lvals, rvals), index=left.index) - elif isinstance(rvals, np.ndarray): + elif isinstance(rvals, (np.ndarray, Index)): result = np.dot(lvals, rvals) if result.ndim == 2: return self._constructor(result, index=left.index) @@ -1668,7 +1668,7 @@ def __getitem__(self, key): if indexer is not None: return self._getitem_slice(indexer) - if isinstance(key, (Series, np.ndarray, list)): + if isinstance(key, (Series, np.ndarray, Index, list)): # either boolean or fancy integer index return self._getitem_array(key) elif isinstance(key, DataFrame): @@ -1719,7 +1719,7 @@ def _getitem_array(self, key): def _getitem_multilevel(self, key): loc = self.columns.get_loc(key) - if isinstance(loc, (slice, Series, np.ndarray)): + if isinstance(loc, (slice, Series, np.ndarray, Index)): new_columns = self.columns[loc] result_columns = _maybe_droplevels(new_columns, key) if self._is_mixed_type: @@ -1999,7 +1999,7 @@ def __setitem__(self, key, value): if indexer is not None: return self._setitem_slice(indexer, value) - if isinstance(key, (Series, np.ndarray, list)): + if isinstance(key, (Series, np.ndarray, list, Index)): self._setitem_array(key, value) elif isinstance(key, DataFrame): self._setitem_frame(key, value) @@ -2371,7 +2371,7 @@ def set_index(self, keys, drop=True, append=False, inplace=False, elif isinstance(col, Index): level = col names.append(col.name) - elif isinstance(col, (list, np.ndarray)): + elif isinstance(col, (list, np.ndarray, Index)): level = col names.append(None) else: @@ -2436,7 +2436,7 @@ def reset_index(self, level=None, drop=False, inplace=False, col_level=0, def _maybe_casted_values(index, labels=None): if isinstance(index, PeriodIndex): - values = index.asobject + values = index.asobject.values elif (isinstance(index, DatetimeIndex) and index.tz is not None): values = index.asobject @@ -3020,7 +3020,7 @@ def _compare_frame(self, other, func, str_rep): def _flex_compare_frame(self, other, func, str_rep, level): if not self._indexed_same(other): - self, other = self.align(other, 'outer', level=level) + self, other = self.align(other, 'outer', level=level, copy=False) return self._compare_frame_evaluate(other, func, str_rep) def combine(self, other, func, fill_value=None, overwrite=True): @@ -4622,7 +4622,7 @@ def extract_index(data): def _prep_ndarray(values, copy=True): - if not isinstance(values, (np.ndarray, Series)): + if not isinstance(values, (np.ndarray, Series, Index)): if len(values) == 0: return np.empty((0, 0), dtype=object) @@ -4685,7 +4685,7 @@ def _to_arrays(data, columns, coerce_float=False, dtype=None): return _list_of_series_to_arrays(data, columns, coerce_float=coerce_float, dtype=dtype) - elif (isinstance(data, (np.ndarray, Series)) + elif (isinstance(data, (np.ndarray, Series, Index)) and data.dtype.names is not None): columns = list(data.dtype.names) @@ -4865,9 +4865,9 @@ def _homogenize(data, index, dtype=None): oindex = index.astype('O') if type(v) == dict: # fast cython method - v = lib.fast_multiget(v, oindex, default=NA) + v = lib.fast_multiget(v, oindex.values, default=NA) else: - v = lib.map_infer(oindex, v.get) + v = lib.map_infer(oindex.values, v.get) v = _sanitize_array(v, index, dtype=dtype, copy=False, raise_cast_failure=False) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index cef18c5ad3c2b..2815f05ce313b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1505,7 +1505,7 @@ def drop(self, labels, axis=0, level=None, inplace=False, **kwargs): if level is not None: if not isinstance(axis, MultiIndex): raise AssertionError('axis must be a MultiIndex') - indexer = ~lib.ismember(axis.get_level_values(level), + indexer = ~lib.ismember(axis.get_level_values(level).values, set(labels)) else: indexer = ~axis.isin(labels) @@ -2135,16 +2135,14 @@ def copy(self, deep=True): Parameters ---------- - deep : boolean, default True + deep : boolean or string, default True Make a deep copy, i.e. also copy data Returns ------- copy : type of caller """ - data = self._data - if deep: - data = data.copy() + data = self._data.copy(deep=deep) return self._constructor(data).__finalize__(self) def convert_objects(self, convert_dates=True, convert_numeric=False, diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 8cfa0e25b789f..212e5086ee543 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -24,7 +24,7 @@ from pandas.core.common import(_possibly_downcast_to_dtype, isnull, notnull, _DATELIKE_DTYPES, is_numeric_dtype, is_timedelta64_dtype, is_datetime64_dtype, - is_categorical_dtype) + is_categorical_dtype, _values_from_object) from pandas.core.config import option_context from pandas import _np_version_under1p7 import pandas.lib as lib @@ -453,7 +453,7 @@ def name(self): @property def _selection_list(self): - if not isinstance(self._selection, (list, tuple, Series, np.ndarray)): + if not isinstance(self._selection, (list, tuple, Series, Index, np.ndarray)): return [self._selection] return self._selection @@ -1254,7 +1254,7 @@ def indices(self): return self.groupings[0].indices else: label_list = [ping.labels for ping in self.groupings] - keys = [ping.group_index for ping in self.groupings] + keys = [_values_from_object(ping.group_index) for ping in self.groupings] return _get_indices_dict(label_list, keys) @property @@ -1552,7 +1552,7 @@ def _aggregate_series_pure_python(self, obj, func): for label, group in splitter: res = func(group) if result is None: - if (isinstance(res, (Series, np.ndarray)) or + if (isinstance(res, (Series, Index, np.ndarray)) or isinstance(res, list)): raise ValueError('Function does not reduce') result = np.empty(ngroups, dtype='O') @@ -1894,7 +1894,7 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None, self.name = grouper.name # no level passed - if not isinstance(self.grouper, (Series, np.ndarray)): + if not isinstance(self.grouper, (Series, Index, np.ndarray)): self.grouper = self.index.map(self.grouper) if not (hasattr(self.grouper, "__len__") and len(self.grouper) == len(self.index)): @@ -2014,7 +2014,7 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True): # what are we after, exactly? match_axis_length = len(keys) == len(group_axis) any_callable = any(callable(g) or isinstance(g, dict) for g in keys) - any_arraylike = any(isinstance(g, (list, tuple, Series, np.ndarray)) + any_arraylike = any(isinstance(g, (list, tuple, Series, Index, np.ndarray)) for g in keys) try: @@ -2080,7 +2080,7 @@ def _convert_grouper(axis, grouper): return grouper.values else: return grouper.reindex(axis).values - elif isinstance(grouper, (list, Series, np.ndarray)): + elif isinstance(grouper, (list, Series, Index, np.ndarray)): if len(grouper) != len(axis): raise AssertionError('Grouper and axis must be same length') return grouper @@ -2246,7 +2246,7 @@ def _aggregate_named(self, func, *args, **kwargs): for name, group in self: group.name = name output = func(group, *args, **kwargs) - if isinstance(output, (Series, np.ndarray)): + if isinstance(output, (Series, Index, np.ndarray)): raise Exception('Must produce aggregated value') result[name] = self._try_cast(output, group) @@ -2678,7 +2678,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False): v = values[0] - if isinstance(v, (np.ndarray, Series)): + if isinstance(v, (np.ndarray, Index, Series)): if isinstance(v, Series): applied_index = self._selected_obj._get_axis(self.axis) all_indexed_same = _all_indexes_same([ @@ -2984,7 +2984,7 @@ def __getitem__(self, key): if self._selection is not None: raise Exception('Column(s) %s already selected' % self._selection) - if isinstance(key, (list, tuple, Series, np.ndarray)): + if isinstance(key, (list, tuple, Series, Index, np.ndarray)): if len(self.obj.columns.intersection(key)) != len(key): bad_keys = list(set(key).difference(self.obj.columns)) raise KeyError("Columns not found: %s" @@ -3579,7 +3579,7 @@ def _intercept_cython(func): def _groupby_indices(values): - return _algos.groupby_indices(com._ensure_object(values)) + return _algos.groupby_indices(_values_from_object(com._ensure_object(values))) def numpy_groupby(data, labels, axis=0): diff --git a/pandas/core/index.py b/pandas/core/index.py index 94bc48d0f4342..c7b1c60a9ddc4 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1,6 +1,7 @@ # pylint: disable=E1101,E1103,W0232 import datetime import warnings +import operator from functools import partial from pandas.compat import range, zip, lrange, lzip, u, reduce from pandas import compat @@ -11,12 +12,12 @@ import pandas.algos as _algos import pandas.index as _index from pandas.lib import Timestamp, is_datetime_array -from pandas.core.base import FrozenList, FrozenNDArray, IndexOpsMixin -from pandas.util.decorators import cache_readonly, deprecate, Appender +from pandas.core.base import PandasObject, FrozenList, FrozenNDArray, IndexOpsMixin +from pandas.util.decorators import Appender, cache_readonly, deprecate from pandas.core.common import isnull, array_equivalent import pandas.core.common as com from pandas.core.common import (_values_from_object, is_float, is_integer, - ABCSeries) + ABCSeries, _ensure_object) from pandas.core.config import get_option # simplify @@ -44,10 +45,15 @@ def _indexOp(opname): """ def wrapper(self, other): - func = getattr(self.view(np.ndarray), opname) - result = func(other) + func = getattr(self._data.view(np.ndarray), opname) + result = func(np.asarray(other)) + + # technically we could support bool dtyped Index + # for now just return the indexing array directly + if com.is_bool_dtype(result): + return result try: - return result.view(np.ndarray) + return Index(result) except: # pragma: no cover return result return wrapper @@ -56,19 +62,15 @@ def wrapper(self, other): class InvalidIndexError(Exception): pass - _o_dtype = np.dtype(object) - - -def _shouldbe_timestamp(obj): - return (tslib.is_datetime_array(obj) - or tslib.is_datetime64_array(obj) - or tslib.is_timestamp_array(obj)) - _Identity = object +def _new_Index(cls, d): + """ This is called upon unpickling, rather than the default which doesn't have arguments + and breaks __new__ """ + return cls.__new__(cls, **d) -class Index(IndexOpsMixin, FrozenNDArray): +class Index(IndexOpsMixin, PandasObject): """ Immutable ndarray implementing an ordered, sliceable set. The basic object @@ -102,16 +104,21 @@ class Index(IndexOpsMixin, FrozenNDArray): _box_scalars = False + _typ = 'index' + _data = None + _id = None name = None asi8 = None _comparables = ['name'] + _attributes = ['name'] _allow_index_ops = True _allow_datetime_index_ops = False _allow_period_index_ops = False + _is_numeric_dtype = False _engine_type = _index.ObjectEngine - def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, + def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False, tupleize_cols=True, **kwargs): # no class inference! @@ -119,7 +126,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, return cls._simple_new(data, name) from pandas.tseries.period import PeriodIndex - if isinstance(data, (np.ndarray, ABCSeries)): + if isinstance(data, (np.ndarray, Index, ABCSeries)): if issubclass(data.dtype.type, np.datetime64): from pandas.tseries.index import DatetimeIndex result = DatetimeIndex(data, copy=copy, name=name, **kwargs) @@ -143,7 +150,10 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, if issubclass(data.dtype.type, np.floating): return Float64Index(data, copy=copy, dtype=dtype, name=name) - subarr = com._asarray_tuplesafe(data, dtype=object) + if com.is_bool_dtype(data): + subarr = data + else: + subarr = com._asarray_tuplesafe(data, dtype=object) # _asarray_tuplesafe does not always copy underlying data, # so need to make sure that this happens @@ -153,7 +163,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, elif hasattr(data, '__array__'): return Index(np.asarray(data), dtype=dtype, copy=copy, name=name, **kwargs) - elif np.isscalar(data): + elif data is None or np.isscalar(data): cls._scalar_data_error(data) else: if tupleize_cols and isinstance(data, list) and data: @@ -177,6 +187,9 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, return Int64Index(subarr.astype('i8'), copy=copy, name=name) elif inferred in ['floating', 'mixed-integer-float']: return Float64Index(subarr, copy=copy, name=name) + elif inferred == 'boolean': + # don't support boolean explicity ATM + pass elif inferred != 'string': if (inferred.startswith('datetime') or tslib.is_timestamp_array(subarr)): @@ -185,15 +198,16 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, elif inferred == 'period': return PeriodIndex(subarr, name=name, **kwargs) - subarr = subarr.view(cls) - # could also have a _set_name, but I don't think it's really necessary - subarr._set_names([name]) - return subarr + return cls._simple_new(subarr, name) @classmethod - def _simple_new(cls, values, name, **kwargs): - result = values.view(cls) + def _simple_new(cls, values, name=None, **kwargs): + result = object.__new__(cls) + result._data = values result.name = name + for k, v in compat.iteritems(kwargs): + setattr(result,k,v) + result._reset_identity() return result def is_(self, other): @@ -219,11 +233,66 @@ def _reset_identity(self): """Initializes or resets ``_id`` attribute with new object""" self._id = _Identity() - def view(self, *args, **kwargs): - result = super(Index, self).view(*args, **kwargs) - if isinstance(result, Index): - result._id = self._id - return result + # ndarray compat + def __len__(self): + """ + return the length of the Index + """ + return len(self._data) + + def __array__(self, result=None): + """ the array interface, return my values """ + return self._data.view(np.ndarray) + + def __array_wrap__(self, result, context=None): + """ + Gets called after a ufunc + """ + return self._shallow_copy(result) + + @cache_readonly + def dtype(self): + """ return the dtype object of the underlying data """ + return self._data.dtype + + @property + def values(self): + """ return the underlying data as an ndarray """ + return self._data.view(np.ndarray) + + def get_values(self): + """ return the underlying data as an ndarray """ + return self.values + + def _array_values(self): + return self._data + + # ops compat + def tolist(self): + """ + return a list of the Index values + """ + return list(self.values) + + def repeat(self, n): + """ + return a new Index of the values repeated n times + + See also + -------- + numpy.ndarray.repeat + """ + return self._shallow_copy(self.values.repeat(n)) + + def ravel(self, order='C'): + """ + return an ndarray of the flattened values of the underlying data + + See also + -------- + numpy.ndarray.ravel + """ + return self.values.ravel(order=order) # construction helpers @classmethod @@ -243,8 +312,8 @@ def _coerce_to_ndarray(cls, data): """coerces data to ndarray, raises on scalar data. Converts other iterables to list first and then to array. Does not touch ndarrays.""" - if not isinstance(data, np.ndarray): - if np.isscalar(data): + if not isinstance(data, (np.ndarray, Index)): + if data is None or np.isscalar(data): cls._scalar_data_error(data) # other iterable of some kind @@ -253,16 +322,27 @@ def _coerce_to_ndarray(cls, data): data = np.asarray(data) return data - def __array_finalize__(self, obj): - self._reset_identity() - if not isinstance(obj, type(self)): - # Only relevant if array being created from an Index instance - return + def _get_attributes_dict(self): + """ return an attributes dict for my class """ + return dict([ (k,getattr(self,k,None)) for k in self._attributes]) - self.name = getattr(obj, 'name', None) + def view(self, cls=None): + if cls is not None and not issubclass(cls, Index): + result = self._data.view(cls) + else: + result = self._shallow_copy() + if isinstance(result, Index): + result._id = self._id + return result - def _shallow_copy(self): - return self.view() + def _shallow_copy(self, values=None, **kwargs): + """ create a new Index, don't copy the data, use the same object attributes + with passed in attributes taking precedence """ + if values is None: + values = self.values + attributes = self._get_attributes_dict() + attributes.update(kwargs) + return self.__class__._simple_new(values,**attributes) def copy(self, names=None, name=None, dtype=None, deep=False): """ @@ -287,10 +367,11 @@ def copy(self, names=None, name=None, dtype=None, deep=False): raise TypeError("Can only provide one of `names` and `name`") if deep: from copy import deepcopy - new_index = np.ndarray.__deepcopy__(self, {}).view(self.__class__) + new_index = self._shallow_copy(self._data.copy()) name = name or deepcopy(self.name) else: - new_index = super(Index, self).copy() + new_index = self._shallow_copy() + name = self.name if name is not None: names = [name] if names: @@ -299,6 +380,19 @@ def copy(self, names=None, name=None, dtype=None, deep=False): new_index = new_index.astype(dtype) return new_index + __copy__ = copy + + def __unicode__(self): + """ + Return a string representation for this object. + + Invoked by unicode(df) in py2 only. Yields a Unicode String in both + py2/py3. + """ + prepr = com.pprint_thing(self, escape_chars=('\t', '\r', '\n'), + quote_strings=True) + return "%s(%s, dtype='%s')" % (type(self).__name__, prepr, self.dtype) + def to_series(self, keep_tz=False): """ Create a Series with both index and values equal to the index keys @@ -343,22 +437,10 @@ def to_datetime(self, dayfirst=False): def _assert_can_do_setop(self, other): return True - def tolist(self): - """ - Overridden version of ndarray.tolist - """ - return list(self.values) - - @cache_readonly - def dtype(self): - return self.values.dtype - @property def nlevels(self): return 1 - # for compat with multindex code - def _get_names(self): return FrozenList((self.name,)) @@ -395,7 +477,7 @@ def set_names(self, names, level=None, inplace=False): >>> Index([1, 2, 3, 4]).set_names(['foo']) Int64Index([1, 2, 3, 4], dtype='int64') >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), - (2, u'one'), (2, u'two')], + (2, u'one'), (2, u'two')], names=['foo', 'bar']) >>> idx.set_names(['baz', 'quz']) MultiIndex(levels=[[1, 2], [u'one', u'two']], @@ -473,13 +555,6 @@ def _mpl_repr(self): # how to represent ourselves to matplotlib return self.values - @property - def values(self): - return np.asarray(self) - - def get_values(self): - return self.values - _na_value = np.nan """The expected NA value to use with this index.""" @@ -720,26 +795,42 @@ def is_type_compatible(self, typ): @cache_readonly def is_all_dates(self): - return is_datetime_array(self.values) + if self._data is None: + return False + return is_datetime_array(_ensure_object(self.values)) def __iter__(self): return iter(self.values) def __reduce__(self): - """Necessary for making this object picklable""" - object_state = list(np.ndarray.__reduce__(self)) - subclass_state = self.name, - object_state[2] = (object_state[2], subclass_state) - return tuple(object_state) + d = dict(data=self._data) + d.update(self._get_attributes_dict()) + return _new_Index, (self.__class__, d), None def __setstate__(self, state): """Necessary for making this object picklable""" - if len(state) == 2: - nd_state, own_state = state - np.ndarray.__setstate__(self, nd_state) - self.name = own_state[0] - else: # pragma: no cover - np.ndarray.__setstate__(self, state) + + if isinstance(state, dict): + self._data = state.pop('data') + for k, v in compat.iteritems(state): + setattr(self, k, v) + + elif isinstance(state, tuple): + + if len(state) == 2: + nd_state, own_state = state + data = np.empty(nd_state[1], dtype=nd_state[2]) + np.ndarray.__setstate__(data, nd_state) + self.name = own_state[0] + + else: # pragma: no cover + data = np.empty(state) + np.ndarray.__setstate__(data, state) + + self._data = data + else: + raise Exception("invalid pickle state") + _unpickle_compat = __setstate__ def __deepcopy__(self, memo={}): return self.copy(deep=True) @@ -755,6 +846,9 @@ def __contains__(self, key): def __hash__(self): raise TypeError("unhashable type: %r" % type(self).__name__) + def __setitem__(self, key, value): + raise TypeError("Indexes does not support mutable operations") + def __getitem__(self, key): """ Override numpy.ndarray's __getitem__ method to work as desired. @@ -768,21 +862,24 @@ def __getitem__(self, key): """ # There's no custom logic to be implemented in __getslice__, so it's # not overloaded intentionally. - __getitem__ = super(Index, self).__getitem__ + getitem = self._data.__getitem__ + promote = self._shallow_copy + if np.isscalar(key): - return __getitem__(key) + return getitem(key) if isinstance(key, slice): # This case is separated from the conditional above to avoid # pessimization of basic indexing. - return __getitem__(key) + return promote(getitem(key)) if com._is_bool_indexer(key): - return __getitem__(np.asarray(key)) + key = np.asarray(key) - result = __getitem__(key) - if result.ndim > 1: - return result.view(np.ndarray) + key = _values_from_object(key) + result = getitem(key) + if not np.isscalar(result): + return promote(result) else: return result @@ -831,12 +928,30 @@ def _ensure_compat_concat(indexes): def take(self, indexer, axis=0): """ - Analogous to ndarray.take + return a new Index of the values selected by the indexer + + See also + -------- + numpy.ndarray.take """ + indexer = com._ensure_platform_int(indexer) - taken = self.view(np.ndarray).take(indexer) - return self._simple_new(taken, name=self.name, freq=None, - tz=getattr(self, 'tz', None)) + taken = np.array(self).take(indexer) + + # by definition cannot propogate freq + return self._shallow_copy(taken, freq=None) + + def putmask(self, mask, value): + """ + return a new Index of the values set with the mask + + See also + -------- + numpy.ndarray.putmask + """ + values = self.values.copy() + np.putmask(values, mask, value) + return self._shallow_copy(values) def format(self, name=False, formatter=None, **kwargs): """ @@ -985,18 +1100,22 @@ def shift(self, periods=1, freq=None): def argsort(self, *args, **kwargs): """ - See docstring for ndarray.argsort + return an ndarray indexer of the underlying data + + See also + -------- + numpy.ndarray.argsort """ result = self.asi8 if result is None: - result = self.view(np.ndarray) + result = np.array(self) return result.argsort(*args, **kwargs) def __add__(self, other): if isinstance(other, Index): return self.union(other) else: - return Index(self.view(np.ndarray) + other) + return Index(np.array(self) + other) __iadd__ = __add__ __eq__ = _indexOp('__eq__') @@ -1048,7 +1167,7 @@ def union(self, other): if self.is_monotonic and other.is_monotonic: try: - result = self._outer_indexer(self, other.values)[0] + result = self._outer_indexer(self.values, other.values)[0] except TypeError: # incomparable objects result = list(self.values) @@ -1122,7 +1241,7 @@ def intersection(self, other): if self.is_monotonic and other.is_monotonic: try: - result = self._inner_indexer(self, other.values)[0] + result = self._inner_indexer(self.values, other.values)[0] return self._wrap_union_result(other, result) except TypeError: pass @@ -1381,7 +1500,7 @@ def _possibly_promote(self, other): return self, other def groupby(self, to_groupby): - return self._groupby(self.values, to_groupby) + return self._groupby(self.values, _values_from_object(to_groupby)) def map(self, mapper): return self._arrmap(self.values, mapper) @@ -1416,9 +1535,6 @@ def isin(self, values, level=None): self._validate_index_level(level) return lib.ismember(self._array_values(), value_set) - def _array_values(self): - return self - def _get_method(self, method): if method: method = method.lower() @@ -1778,7 +1894,7 @@ def slice_indexer(self, start=None, end=None, step=None): return slice(start_slice, end_slice, step) # loc indexers - return Index(start_slice) & Index(end_slice) + return (Index(start_slice) & Index(end_slice)).values def slice_locs(self, start=None, end=None): """ @@ -1814,7 +1930,7 @@ def _get_slice(starting_value, offset, search_side, slice_property, # get_loc will return a boolean array for non_uniques # if we are not monotonic - if isinstance(slc, np.ndarray): + if isinstance(slc, (np.ndarray, Index)): raise KeyError("cannot peform a slice operation " "on a non-unique non-monotonic index") @@ -1853,7 +1969,7 @@ def delete(self, loc): ------- new_index : Index """ - return np.delete(self, loc) + return Index(np.delete(self._data, loc), name=self.name) def insert(self, loc, item): """ @@ -1894,8 +2010,75 @@ def drop(self, labels): raise ValueError('labels %s not contained in axis' % labels[mask]) return self.delete(indexer) + @classmethod + def _add_numeric_methods_disabled(cls): + """ add in numeric methods to disable """ + + def _make_invalid_op(opstr): + + def _invalid_op(self, other): + raise TypeError("cannot perform {opstr} with this index type: {typ}".format(opstr=opstr, + typ=type(self))) + return _invalid_op + + cls.__mul__ = cls.__rmul__ = _make_invalid_op('multiplication') + cls.__floordiv__ = cls.__rfloordiv__ = _make_invalid_op('floor division') + cls.__truediv__ = cls.__rtruediv__ = _make_invalid_op('true division') + if not compat.PY3: + cls.__div__ = cls.__rdiv__ = _make_invalid_op('division') + + @classmethod + def _add_numeric_methods(cls): + """ add in numeric methods """ + + def _make_evaluate_binop(op, opstr): + + def _evaluate_numeric_binop(self, other): + + # if we are an inheritor of numeric, but not actually numeric (e.g. DatetimeIndex/PeriodInde) + if not self._is_numeric_dtype: + raise TypeError("cannot evaluate a numeric op {opstr} for type: {typ}".format(opstr=opstr, + typ=type(self))) + + if isinstance(other, Index): + if not other._is_numeric_dtype: + raise TypeError("cannot evaluate a numeric op {opstr} with type: {typ}".format(opstr=type(self), + typ=type(other))) + elif isinstance(other, np.ndarray) and not other.ndim: + other = other.item() + + if isinstance(other, (Index, ABCSeries, np.ndarray)): + if len(self) != len(other): + raise ValueError("cannot evaluate a numeric op with unequal lengths") + other = _values_from_object(other) + if other.dtype.kind not in ['f','i']: + raise TypeError("cannot evaluate a numeric op with a non-numeric dtype") + else: + if not (com.is_float(other) or com.is_integer(other)): + raise TypeError("can only perform ops with scalar values") + return self._shallow_copy(op(self.values, other)) + + return _evaluate_numeric_binop + + + cls.__mul__ = cls.__rmul__ = _make_evaluate_binop(operator.mul,'multiplication') + cls.__floordiv__ = cls.__rfloordiv__ = _make_evaluate_binop(operator.floordiv,'floor division') + cls.__truediv__ = cls.__rtruediv__ = _make_evaluate_binop(operator.truediv,'true division') + if not compat.PY3: + cls.__div__ = cls.__rdiv__ = _make_evaluate_binop(operator.div,'division') +Index._add_numeric_methods_disabled() + +class NumericIndex(Index): + """ + Provide numeric type operations -class Int64Index(Index): + This is an abstract class + + """ + _is_numeric_dtype = True + + +class Int64Index(NumericIndex): """ Immutable ndarray implementing an ordered, sliceable set. The basic object @@ -1918,6 +2101,7 @@ class Int64Index(Index): An Index instance can **only** contain hashable objects """ + _typ = 'int64index' _groupby = _algos.groupby_int64 _arrmap = _algos.arrmap_int64 _left_indexer_unique = _algos.left_join_indexer_unique_int64 @@ -1927,12 +2111,10 @@ class Int64Index(Index): _engine_type = _index.Int64Engine - def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False): + def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False, **kwargs): if fastpath: - subarr = data.view(cls) - subarr.name = name - return subarr + return cls._simple_new(data, name=name) # isscalar, generators handled in coerce_to_ndarray data = cls._coerce_to_ndarray(data) @@ -1955,9 +2137,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False): raise TypeError('Unsafe NumPy casting to integer, you must' ' explicitly cast') - subarr = subarr.view(cls) - subarr.name = name - return subarr + return cls._simple_new(subarr, name=name) @property def inferred_type(self): @@ -1994,9 +2174,9 @@ def equals(self, other): def _wrap_joined_index(self, joined, other): name = self.name if self.name == other.name else None return Int64Index(joined, name=name) +Int64Index._add_numeric_methods() - -class Float64Index(Index): +class Float64Index(NumericIndex): """ Immutable ndarray implementing an ordered, sliceable set. The basic object @@ -2017,7 +2197,7 @@ class Float64Index(Index): An Float64Index instance can **only** contain hashable objects """ - # when this is not longer object dtype this can be changed + _typ = 'float64index' _engine_type = _index.Float64Engine _groupby = _algos.groupby_float64 _arrmap = _algos.arrmap_float64 @@ -2026,12 +2206,10 @@ class Float64Index(Index): _inner_indexer = _algos.inner_join_indexer_float64 _outer_indexer = _algos.outer_join_indexer_float64 - def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False): + def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False, **kwargs): if fastpath: - subarr = data.view(cls) - subarr.name = name - return subarr + return cls._simple_new(data, name) data = cls._coerce_to_ndarray(data) @@ -2051,9 +2229,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False): if subarr.dtype != np.float64: subarr = subarr.astype(np.float64) - subarr = subarr.view(cls) - subarr.name = name - return subarr + return cls._simple_new(subarr, name) @property def inferred_type(self): @@ -2186,6 +2362,7 @@ def isin(self, values, level=None): self._validate_index_level(level) return lib.ismember_nans(self._array_values(), value_set, isnull(list(value_set)).any()) +Float64Index._add_numeric_methods() class MultiIndex(Index): @@ -2205,8 +2382,14 @@ class MultiIndex(Index): level) names : optional sequence of objects Names for each of the index levels. + copy : boolean, default False + Copy the meta-data + verify_integrity : boolean, default True + Check that the levels/labels are consistent and valid """ + # initialize to zero-length tuples to make everything work + _typ = 'multiindex' _names = FrozenList() _levels = FrozenList() _labels = FrozenList() @@ -2214,7 +2397,8 @@ class MultiIndex(Index): rename = Index.set_names def __new__(cls, levels=None, labels=None, sortorder=None, names=None, - copy=False, verify_integrity=True): + copy=False, verify_integrity=True, _set_identity=True, **kwargs): + if levels is None or labels is None: raise TypeError("Must pass both levels and labels") if len(levels) != len(labels): @@ -2226,28 +2410,29 @@ def __new__(cls, levels=None, labels=None, sortorder=None, names=None, name = names[0] else: name = None - return Index(levels[0], name=name, copy=True).take(labels[0]) - # v3, 0.8.0 - subarr = np.empty(0, dtype=object).view(cls) + result = object.__new__(MultiIndex) + # we've already validated levels and labels, so shortcut here - subarr._set_levels(levels, copy=copy, validate=False) - subarr._set_labels(labels, copy=copy, validate=False) + result._set_levels(levels, copy=copy, validate=False) + result._set_labels(labels, copy=copy, validate=False) if names is not None: # handles name validation - subarr._set_names(names) + result._set_names(names) if sortorder is not None: - subarr.sortorder = int(sortorder) + result.sortorder = int(sortorder) else: - subarr.sortorder = sortorder + result.sortorder = sortorder if verify_integrity: - subarr._verify_integrity() + result._verify_integrity() + if _set_identity: + result._reset_identity() - return subarr + return result def _verify_integrity(self): """Raises ValueError if length of levels and labels don't match or any @@ -2329,7 +2514,7 @@ def set_levels(self, levels, level=None, inplace=False, verify_integrity=True): Examples -------- >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), - (2, u'one'), (2, u'two')], + (2, u'one'), (2, u'two')], names=['foo', 'bar']) >>> idx.set_levels([['a','b'], [1,2]]) MultiIndex(levels=[[u'a', u'b'], [1, 2]], @@ -2381,7 +2566,7 @@ def _get_labels(self): def _set_labels(self, labels, level=None, copy=False, validate=True, verify_integrity=False): - + if validate and level is None and len(labels) != self.nlevels: raise ValueError("Length of labels must match number of levels") if validate and level is not None and len(labels) != len(level): @@ -2427,7 +2612,7 @@ def set_labels(self, labels, level=None, inplace=False, verify_integrity=True): Examples -------- >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), - (2, u'one'), (2, u'two')], + (2, u'one'), (2, u'two')], names=['foo', 'bar']) >>> idx.set_labels([[1,0,1,0], [0,0,1,1]]) MultiIndex(levels=[[1, 2], [u'one', u'two']], @@ -2474,7 +2659,7 @@ def set_labels(self, labels, level=None, inplace=False, verify_integrity=True): labels = property(fget=_get_labels, fset=__set_labels) def copy(self, names=None, dtype=None, levels=None, labels=None, - deep=False): + deep=False, _set_identity=False): """ Make a copy of this object. Names, dtype, levels and labels can be passed and will be set on new copy. @@ -2496,39 +2681,33 @@ def copy(self, names=None, dtype=None, levels=None, labels=None, ``deep``, but if ``deep`` is passed it will attempt to deepcopy. This could be potentially expensive on large MultiIndex objects. """ - new_index = np.ndarray.copy(self) if deep: from copy import deepcopy levels = levels if levels is not None else deepcopy(self.levels) labels = labels if labels is not None else deepcopy(self.labels) names = names if names is not None else deepcopy(self.names) - if levels is not None: - new_index = new_index.set_levels(levels) - if labels is not None: - new_index = new_index.set_labels(labels) - if names is not None: - new_index = new_index.set_names(names) - if dtype: - new_index = new_index.astype(dtype) - return new_index + else: + levels = self.levels + labels = self.labels + names = self.names + return MultiIndex(levels=levels, + labels=labels, + names=names, + sortorder=self.sortorder, + verify_integrity=False, + _set_identity=_set_identity) + + def __array__(self, result=None): + """ the array interface, return my values """ + return self.values - def __array_finalize__(self, obj): - """ - Update custom MultiIndex attributes when a new array is created by - numpy, e.g. when calling ndarray.view() - """ - # overriden if a view - self._reset_identity() - if not isinstance(obj, type(self)): - # Only relevant if this array is being created from an Index - # instance. - return + def view(self, cls=None): + """ this is defined as a copy with the same identity """ + result = self.copy() + result._id = self._id + return result - # skip the validation on first, rest will catch the errors - self._set_levels(getattr(obj, 'levels', []), validate=False) - self._set_labels(getattr(obj, 'labels', [])) - self._set_names(getattr(obj, 'names', [])) - self.sortorder = getattr(obj, 'sortorder', None) + _shallow_copy = view def _array_values(self): # hack for various methods @@ -2628,12 +2807,7 @@ def inferred_type(self): @staticmethod def _from_elements(values, labels=None, levels=None, names=None, sortorder=None): - index = values.view(MultiIndex) - index._set_levels(levels) - index._set_labels(labels) - index._set_names(names) - index.sortorder = sortorder - return index + return MultiIndex(levels, labels, names, sortorder=sortorder) def _get_level_number(self, level): try: @@ -2663,33 +2837,28 @@ def _get_level_number(self, level): @property def values(self): - if self._is_v2: - return self.view(np.ndarray) - else: - if self._tuples is not None: - return self._tuples + if self._tuples is not None: + return self._tuples - values = [] - for lev, lab in zip(self.levels, self.labels): - taken = com.take_1d(lev.values, lab) - # Need to box timestamps, etc. - if hasattr(lev, '_box_values'): - taken = lev._box_values(taken) - values.append(taken) + values = [] + for lev, lab in zip(self.levels, self.labels): + taken = com.take_1d(lev.values, lab) + # Need to box timestamps, etc. + if hasattr(lev, '_box_values'): + taken = lev._box_values(taken) + values.append(taken) - self._tuples = lib.fast_zip(values) - return self._tuples + self._tuples = lib.fast_zip(values) + return self._tuples # fml @property def _is_v1(self): - contents = self.view(np.ndarray) - return len(contents) > 0 and not isinstance(contents[0], tuple) + return False @property def _is_v2(self): - contents = self.view(np.ndarray) - return len(contents) > 0 and isinstance(contents[0], tuple) + return False @property def _has_complex_internals(self): @@ -3000,7 +3169,7 @@ def from_tuples(cls, tuples, sortorder=None, names=None): # I think this is right? Not quite sure... raise TypeError('Cannot infer number of levels from empty list') - if isinstance(tuples, np.ndarray): + if isinstance(tuples, (np.ndarray, Index)): if isinstance(tuples, Index): tuples = tuples.values @@ -3075,18 +3244,25 @@ def __contains__(self, key): def __reduce__(self): """Necessary for making this object picklable""" - object_state = list(np.ndarray.__reduce__(self)) - subclass_state = ([lev.view(np.ndarray) for lev in self.levels], - [label.view(np.ndarray) for label in self.labels], - self.sortorder, list(self.names)) - object_state[2] = (object_state[2], subclass_state) - return tuple(object_state) + d = dict(levels = [lev.view(np.ndarray) for lev in self.levels], + labels = [label.view(np.ndarray) for label in self.labels], + sortorder = self.sortorder, + names = list(self.names)) + return _new_Index, (self.__class__, d), None def __setstate__(self, state): """Necessary for making this object picklable""" - nd_state, own_state = state - np.ndarray.__setstate__(self, nd_state) - levels, labels, sortorder, names = own_state + + if isinstance(state, dict): + levels = state.get('levels') + labels = state.get('labels') + sortorder = state.get('sortorder') + names = state.get('names') + + elif isinstance(state, tuple): + + nd_state, own_state = state + levels, labels, sortorder, names = own_state self._set_levels([Index(x) for x in levels], validate=False) self._set_labels(labels) @@ -3112,21 +3288,15 @@ def __getitem__(self, key): # cannot be sure whether the result will be sorted sortorder = None - result = np.empty(0, dtype=object).view(type(self)) new_labels = [lab[key] for lab in self.labels] - # an optimization - result._set_levels(self.levels, validate=False) - result._set_labels(new_labels) - result.sortorder = sortorder - result._set_names(self.names) - - return result + return MultiIndex(levels=self.levels, + labels=new_labels, + names=self.names, + sortorder=sortorder, + verify_integrity=False) def take(self, indexer, axis=None): - """ - Analogous to ndarray.take - """ indexer = com._ensure_platform_int(indexer) new_labels = [lab.take(indexer) for lab in self.labels] return MultiIndex(levels=self.levels, labels=new_labels, @@ -3167,6 +3337,13 @@ def append(self, other): def argsort(self, *args, **kwargs): return self.values.argsort() + def repeat(self, n): + return MultiIndex(levels=self.levels, + labels=[label.view(np.ndarray).repeat(n) for label in self.labels], + names=self.names, + sortorder=self.sortorder, + verify_integrity=False) + def drop(self, labels, level=None): """ Make new MultiIndex with passed list of labels deleted @@ -3185,7 +3362,7 @@ def drop(self, labels, level=None): return self._drop_from_level(labels, level) try: - if not isinstance(labels, np.ndarray): + if not isinstance(labels, (np.ndarray, Index)): labels = com._index_labels_to_array(labels) indexer = self.get_indexer(labels) mask = indexer == -1 @@ -3254,7 +3431,7 @@ def droplevel(self, level=0): mask = new_labels[0] == -1 result = new_levels[0].take(new_labels[0]) if mask.any(): - np.putmask(result, mask, np.nan) + result = result.putmask(mask, np.nan) result.name = new_names[0] return result @@ -3414,16 +3591,16 @@ def get_indexer(self, target, method=None, limit=None): if not self.is_unique or not self.is_monotonic: raise AssertionError(('Must be unique and monotonic to ' 'use forward fill getting the indexer')) - indexer = self_index._engine.get_pad_indexer(target_index, + indexer = self_index._engine.get_pad_indexer(target_index.values, limit=limit) elif method == 'backfill': if not self.is_unique or not self.is_monotonic: raise AssertionError(('Must be unique and monotonic to ' 'use backward fill getting the indexer')) - indexer = self_index._engine.get_backfill_indexer(target_index, + indexer = self_index._engine.get_backfill_indexer(target_index.values, limit=limit) else: - indexer = self_index._engine.get_indexer(target_index) + indexer = self_index._engine.get_indexer(target_index.values) return com._ensure_platform_int(indexer) @@ -4087,6 +4264,7 @@ def isin(self, values, level=None): return np.zeros(len(labs), dtype=np.bool_) else: return np.lib.arraysetops.in1d(labs, sought_labels) +MultiIndex._add_numeric_methods_disabled() # For utility purposes @@ -4192,6 +4370,12 @@ def _union_indexes(indexes): return result indexes, kind = _sanitize_and_check(indexes) + def _unique_indices(inds): + def conv(i): + if isinstance(i, Index): + i = i.tolist() + return i + return Index(lib.fast_unique_multiple_list([ conv(i) for i in inds ])) if kind == 'special': result = indexes[0] @@ -4206,11 +4390,11 @@ def _union_indexes(indexes): index = indexes[0] for other in indexes[1:]: if not index.equals(other): - return Index(lib.fast_unique_multiple(indexes)) + return _unique_indices(indexes) return index else: - return Index(lib.fast_unique_multiple_list(indexes)) + return _unique_indices(indexes) def _trim_front(strings): diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index b02fe523df998..91008f9b22aed 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -7,7 +7,8 @@ import pandas.core.common as com from pandas.core.common import (_is_bool_indexer, is_integer_dtype, _asarray_tuplesafe, is_list_like, isnull, - ABCSeries, ABCDataFrame, ABCPanel, is_float) + ABCSeries, ABCDataFrame, ABCPanel, is_float, + _values_from_object) import pandas.lib as lib import numpy as np @@ -1086,7 +1087,7 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False): return {'key': obj} raise KeyError('%s not in index' % objarr[mask]) - return indexer + return _values_from_object(indexer) else: try: @@ -1512,7 +1513,7 @@ def _length_of_indexer(indexer, target=None): elif step < 0: step = abs(step) return (stop - start) / step - elif isinstance(indexer, (ABCSeries, np.ndarray, list)): + elif isinstance(indexer, (ABCSeries, Index, np.ndarray, list)): return len(indexer) elif not is_list_like(indexer): return 1 diff --git a/pandas/core/internals.py b/pandas/core/internals.py index f5cb48fd94022..da36d95a3ad9e 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -2617,15 +2617,22 @@ def copy(self, deep=True): Parameters ---------- - deep : boolean, default True + deep : boolean o rstring, default True If False, return shallow copy (do not copy data) + If 'all', copy data and a deep copy of the index Returns ------- copy : BlockManager """ + + # this preserves the notion of view copying of axes if deep: - new_axes = [ax.view() for ax in self.axes] + if deep == 'all': + copy = lambda ax: ax.copy(deep=True) + else: + copy = lambda ax: ax.view() + new_axes = [ copy(ax) for ax in self.axes] else: new_axes = list(self.axes) return self.apply('copy', axes=new_axes, deep=deep, diff --git a/pandas/core/ops.py b/pandas/core/ops.py index abe1974705243..9f29570af6f4f 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -247,7 +247,7 @@ def __init__(self, left, right, name): # need to make sure that we are aligning the data if isinstance(left, pd.Series) and isinstance(right, pd.Series): - left, right = left.align(right) + left, right = left.align(right,copy=False) self.left = left self.right = right @@ -331,12 +331,12 @@ def _convert_to_array(self, values, name=None, other=None): values = np.empty(values.shape, dtype=other.dtype) values[:] = tslib.iNaT - # a datetlike + # a datelike + elif isinstance(values, pd.DatetimeIndex): + values = values.to_series() elif not (isinstance(values, (pa.Array, pd.Series)) and com.is_datetime64_dtype(values)): values = tslib.array_to_datetime(values) - elif isinstance(values, pd.DatetimeIndex): - values = values.to_series() elif inferred_type in ('timedelta', 'timedelta64'): # have a timedelta, convert to to ns here values = _possibly_cast_to_timedelta(values, coerce=coerce, dtype='timedelta64[ns]') @@ -451,11 +451,11 @@ def na_op(x, y): result = expressions.evaluate(op, str_rep, x, y, raise_on_error=True, **eval_kwargs) except TypeError: - if isinstance(y, (pa.Array, pd.Series)): + if isinstance(y, (pa.Array, pd.Series, pd.Index)): dtype = np.find_common_type([x.dtype, y.dtype], []) result = np.empty(x.size, dtype=dtype) mask = notnull(x) & notnull(y) - result[mask] = op(x[mask], y[mask]) + result[mask] = op(x[mask], _values_from_object(y[mask])) elif isinstance(x, pa.Array): result = pa.empty(len(x), dtype=x.dtype) mask = notnull(x) @@ -555,7 +555,7 @@ def wrapper(self, other): index=self.index, name=name) elif isinstance(other, pd.DataFrame): # pragma: no cover return NotImplemented - elif isinstance(other, (pa.Array, pd.Series)): + elif isinstance(other, (pa.Array, pd.Series, pd.Index)): if len(self) != len(other): raise ValueError('Lengths must match to compare') return self._constructor(na_op(self.values, np.asarray(other)), @@ -565,7 +565,7 @@ def wrapper(self, other): mask = isnull(self) values = self.get_values() - other = _index.convert_scalar(values, other) + other = _index.convert_scalar(values,_values_from_object(other)) if issubclass(values.dtype.type, np.datetime64): values = values.view('i8') diff --git a/pandas/core/series.py b/pandas/core/series.py index d1f861b7f7fd7..22284df337d97 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -70,18 +70,6 @@ def wrapper(self): return wrapper -def _unbox(func): - @Appender(func.__doc__) - def f(self, *args, **kwargs): - result = func(self.values, *args, **kwargs) - if isinstance(result, (pa.Array, Series)) and result.ndim == 0: - # return NumPy type - return result.dtype.type(result.item()) - else: # pragma: no cover - return result - f.__name__ = func.__name__ - return f - #---------------------------------------------------------------------- # Series class @@ -290,76 +278,87 @@ def _set_subtyp(self, is_all_dates): object.__setattr__(self, '_subtyp', 'series') # ndarray compatibility - def item(self): - return self._data.values.item() - - @property - def data(self): - return self._data.values.data - - @property - def strides(self): - return self._data.values.strides - - @property - def size(self): - return self._data.values.size - - @property - def flags(self): - return self._data.values.flags - @property def dtype(self): + """ return the dtype object of the underlying data """ return self._data.dtype @property def dtypes(self): - """ for compat """ + """ return the dtype object of the underlying data """ return self._data.dtype @property def ftype(self): + """ return if the data is sparse|dense """ return self._data.ftype @property def ftypes(self): - """ for compat """ + """ return if the data is sparse|dense """ return self._data.ftype @property - def shape(self): - return self._data.shape + def values(self): + """ + Return Series as ndarray - @property - def ndim(self): - return 1 + Returns + ------- + arr : numpy.ndarray + """ + return self._data.values - @property - def base(self): - return self.values.base + def get_values(self): + """ same as values (but handles sparseness conversions); is a view """ + return self._data.get_values() + + # ops def ravel(self, order='C'): + """ + Return the flattened underlying data as an ndarray + + See also + -------- + numpy.ndarray.ravel + """ return self.values.ravel(order=order) def compress(self, condition, axis=0, out=None, **kwargs): - # 1-d compat with numpy - return self[condition] - - def transpose(self): - """ support for compatiblity """ - return self + """ + Return selected slices of an array along given axis as a Series - T = property(transpose) + See also + -------- + numpy.ndarray.compress + """ + return self[condition] def nonzero(self): - """ numpy like, returns same as nonzero """ + """ + return the a boolean array of the underlying data is nonzero + + See also + -------- + numpy.ndarray.nonzero + """ return self.values.nonzero() def put(self, *args, **kwargs): + """ + return a ndarray with the values put + + See also + -------- + numpy.ndarray.put + """ self.values.put(*args, **kwargs) def __len__(self): + """ + return the length of the Series + """ return len(self._data) def view(self, dtype=None): @@ -442,7 +441,7 @@ def _unpickle_series_compat(self, state): # recreate self._data = SingleBlockManager(data, index, fastpath=True) - self.index = index + self._index = index self.name = name else: @@ -549,7 +548,7 @@ def _get_with(self, key): raise # pragma: no cover - if not isinstance(key, (list, pa.Array, Series)): + if not isinstance(key, (list, pa.Array, Series, Index)): key = list(key) if isinstance(key, Index): @@ -716,7 +715,11 @@ def _set_values(self, key, value): def repeat(self, reps): """ - See ndarray.repeat + return a new Series with the values repeated reps times + + See also + -------- + numpy.ndarray.repeat """ new_index = self.index.repeat(reps) new_values = self.values.repeat(reps) @@ -725,7 +728,13 @@ def repeat(self, reps): def reshape(self, *args, **kwargs): """ - See numpy.ndarray.reshape + return an ndarray with the values shape + if the specified shape matches exactly the current shape, then + return self (for compat) + + See also + -------- + numpy.ndarray.take """ if len(args) == 1 and hasattr(args[0], '__iter__'): shape = args[0] @@ -989,12 +998,6 @@ def iteritems(self): if compat.PY3: # pragma: no cover items = iteritems - #---------------------------------------------------------------------- - # unbox reductions - - all = _unbox(pa.Array.all) - any = _unbox(pa.Array.any) - #---------------------------------------------------------------------- # Misc public methods @@ -1002,21 +1005,6 @@ def keys(self): "Alias for index" return self.index - @property - def values(self): - """ - Return Series as ndarray - - Returns - ------- - arr : numpy.ndarray - """ - return self._data.values - - def get_values(self): - """ same as values (but handles sparseness conversions); is a view """ - return self._data.get_values() - def tolist(self): """ Convert Series to a nested list """ return list(self) @@ -1191,6 +1179,7 @@ def idxmin(self, axis=None, out=None, skipna=True): See Also -------- DataFrame.idxmin + numpy.ndarray.argmin """ i = nanops.nanargmin(_values_from_object(self), skipna=skipna) if i == -1: @@ -1217,6 +1206,7 @@ def idxmax(self, axis=None, out=None, skipna=True): See Also -------- DataFrame.idxmax + numpy.ndarray.argmax """ i = nanops.nanargmax(_values_from_object(self), skipna=skipna) if i == -1: @@ -1334,7 +1324,7 @@ def cov(self, other, min_periods=None): Normalized by N-1 (unbiased estimator). """ - this, other = self.align(other, join='inner') + this, other = self.align(other, join='inner', copy=False) if len(this) == 0: return pa.NA return nanops.nancov(this.values, other.values, @@ -1460,7 +1450,7 @@ def _binop(self, other, func, level=None, fill_value=None): this = self if not self.index.equals(other.index): - this, other = self.align(other, level=level, join='outer') + this, other = self.align(other, level=level, join='outer', copy=False) new_index = this.index this_vals = this.values @@ -1599,6 +1589,9 @@ def argsort(self, axis=0, kind='quicksort', order=None): ------- argsorted : Series, with -1 indicated where nan values are present + See also + -------- + numpy.ndarray.argsort """ values = self.values mask = isnull(values) @@ -2072,8 +2065,7 @@ def reindex_axis(self, labels, axis=0, **kwargs): def take(self, indices, axis=0, convert=True, is_copy=False): """ - Analogous to ndarray.take, return Series corresponding to requested - indices + return Series corresponding to requested indices Parameters ---------- @@ -2083,6 +2075,10 @@ def take(self, indices, axis=0, convert=True, is_copy=False): Returns ------- taken : Series + + See also + -------- + numpy.ndarray.take """ # check/convert indicies here if convert: @@ -2483,7 +2479,7 @@ def _try_cast(arr, take_fast_path): return subarr # GH #846 - if isinstance(data, (pa.Array, Series)): + if isinstance(data, (pa.Array, Index, Series)): subarr = np.array(data, copy=False) if dtype is not None: diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py index e80bfec9c8dba..52a9ef0370e9e 100644 --- a/pandas/io/pickle.py +++ b/pandas/io/pickle.py @@ -1,6 +1,5 @@ from pandas.compat import cPickle as pkl, pickle_compat as pc, PY3 - def to_pickle(obj, path): """ Pickle (serialize) object to input file path @@ -45,7 +44,7 @@ def try_read(path, encoding=None): try: with open(path, 'rb') as fh: return pkl.load(fh) - except: + except (Exception) as e: # reg/patched pickle try: diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index b95c1ed0b77e9..78e7c43de678f 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3564,7 +3564,7 @@ def read(self, where=None, columns=None, **kwargs): # need a better algorithm tuple_index = long_index._tuple_index - unique_tuples = lib.fast_unique(tuple_index) + unique_tuples = lib.fast_unique(tuple_index.values) unique_tuples = _asarray_tuplesafe(unique_tuples) indexer = match(unique_tuples, tuple_index) diff --git a/pandas/io/tests/test_pickle.py b/pandas/io/tests/test_pickle.py index 07d576ac1c8ae..aea7fb42b7d36 100644 --- a/pandas/io/tests/test_pickle.py +++ b/pandas/io/tests/test_pickle.py @@ -18,11 +18,6 @@ from pandas.util.misc import is_little_endian import pandas -def _read_pickle(vf, encoding=None, compat=False): - from pandas.compat import pickle_compat as pc - with open(vf,'rb') as fh: - pc.load(fh, encoding=encoding, compat=compat) - class TestPickle(tm.TestCase): _multiprocess_can_split_ = True @@ -97,16 +92,54 @@ def test_read_pickles_0_14_0(self): self.read_pickles('0.14.0') def test_round_trip_current(self): - for typ, dv in self.data.items(): + try: + import cPickle as c_pickle + def c_pickler(obj,path): + with open(path,'wb') as fh: + c_pickle.dump(obj,fh,protocol=-1) + + def c_unpickler(path): + with open(path,'rb') as fh: + fh.seek(0) + return c_pickle.load(fh) + except: + c_pickler = None + c_unpickler = None + + import pickle as python_pickle + + def python_pickler(obj,path): + with open(path,'wb') as fh: + python_pickle.dump(obj,fh,protocol=-1) + + def python_unpickler(path): + with open(path,'rb') as fh: + fh.seek(0) + return python_pickle.load(fh) + + for typ, dv in self.data.items(): for dt, expected in dv.items(): - with tm.ensure_clean(self.path) as path: + for writer in [pd.to_pickle, c_pickler, python_pickler ]: + if writer is None: + continue + + with tm.ensure_clean(self.path) as path: + + # test writing with each pickler + writer(expected,path) + + # test reading with each unpickler + result = pd.read_pickle(path) + self.compare_element(typ, result, expected) - pd.to_pickle(expected,path) + if c_unpickler is not None: + result = c_unpickler(path) + self.compare_element(typ, result, expected) - result = pd.read_pickle(path) - self.compare_element(typ, result, expected) + result = python_unpickler(path) + self.compare_element(typ, result, expected) def _validate_timeseries(self, pickled, current): # GH 7748 diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 024415409cdca..4f76f72b8eb66 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -857,11 +857,16 @@ def check(format,index): assert_frame_equal(df,store['df']) for index in [ tm.makeFloatIndex, tm.makeStringIndex, tm.makeIntIndex, - tm.makeDateIndex, tm.makePeriodIndex ]: + tm.makeDateIndex ]: check('table',index) check('fixed',index) + # period index currently broken for table + # seee GH7796 FIXME + check('fixed',tm.makePeriodIndex) + #check('table',tm.makePeriodIndex) + # unicode index = tm.makeUnicodeIndex if compat.PY3: @@ -2285,7 +2290,7 @@ def test_remove_where(self): # deleted number (entire table) n = store.remove('wp', []) - assert(n == 120) + self.assertTrue(n == 120) # non - empty where _maybe_remove(store, 'wp') @@ -2379,7 +2384,8 @@ def test_remove_crit(self): crit4 = Term('major_axis=date4') store.put('wp3', wp, format='t') n = store.remove('wp3', where=[crit4]) - assert(n == 36) + self.assertTrue(n == 36) + result = store.select('wp3') expected = wp.reindex(major_axis=wp.major_axis - date4) assert_panel_equal(result, expected) @@ -2392,11 +2398,10 @@ def test_remove_crit(self): crit1 = Term('major_axis>date') crit2 = Term("minor_axis=['A', 'D']") n = store.remove('wp', where=[crit1]) - - assert(n == 56) + self.assertTrue(n == 56) n = store.remove('wp', where=[crit2]) - assert(n == 32) + self.assertTrue(n == 32) result = store['wp'] expected = wp.truncate(after=date).reindex(minor=['B', 'C']) diff --git a/pandas/lib.pyx b/pandas/lib.pyx index 373320393bff2..7ffc59f6ab50d 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -813,7 +813,7 @@ def clean_index_list(list obj): for i in range(n): v = obj[i] - if not (PyList_Check(v) or np.PyArray_Check(v)): + if not (PyList_Check(v) or np.PyArray_Check(v) or hasattr(v,'_data')): all_arrays = 0 break @@ -823,7 +823,7 @@ def clean_index_list(list obj): converted = np.empty(n, dtype=object) for i in range(n): v = obj[i] - if PyList_Check(v) or np.PyArray_Check(v): + if PyList_Check(v) or np.PyArray_Check(v) or hasattr(v,'_data'): converted[i] = tuple(v) else: converted[i] = v diff --git a/pandas/sparse/tests/test_array.py b/pandas/sparse/tests/test_array.py index a12d1dfe70513..5227bb23ad616 100644 --- a/pandas/sparse/tests/test_array.py +++ b/pandas/sparse/tests/test_array.py @@ -4,7 +4,6 @@ import numpy as np import operator -import pickle from pandas.core.series import Series from pandas.core.common import notnull @@ -169,8 +168,7 @@ def _check_inplace_op(op): def test_pickle(self): def _check_roundtrip(obj): - pickled = pickle.dumps(obj) - unpickled = pickle.loads(pickled) + unpickled = self.round_trip_pickle(obj) assert_sp_array_equal(unpickled, obj) _check_roundtrip(self.arr) diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py index 475b8f93c10ef..105f661f08b10 100644 --- a/pandas/sparse/tests/test_sparse.py +++ b/pandas/sparse/tests/test_sparse.py @@ -21,7 +21,7 @@ import pandas.core.datetools as datetools from pandas.core.common import isnull import pandas.util.testing as tm -from pandas.compat import range, lrange, cPickle as pickle, StringIO, lrange +from pandas.compat import range, lrange, StringIO, lrange from pandas import compat import pandas.sparse.frame as spf @@ -315,8 +315,7 @@ def test_kind(self): def test_pickle(self): def _test_roundtrip(series): - pickled = pickle.dumps(series, protocol=pickle.HIGHEST_PROTOCOL) - unpickled = pickle.loads(pickled) + unpickled = self.round_trip_pickle(series) assert_sp_series_equal(series, unpickled) assert_series_equal(series.to_dense(), unpickled.to_dense()) @@ -793,7 +792,10 @@ def test_copy(self): cp = self.frame.copy() tm.assert_isinstance(cp, SparseDataFrame) assert_sp_frame_equal(cp, self.frame) - self.assertTrue(cp.index.is_(self.frame.index)) + + # as of v0.15.0 + # this is now identical (but not is_a ) + self.assertTrue(cp.index.identical(self.frame.index)) def test_constructor(self): for col, series in compat.iteritems(self.frame): @@ -918,9 +920,8 @@ def test_array_interface(self): def test_pickle(self): def _test_roundtrip(frame): - pickled = pickle.dumps(frame, protocol=pickle.HIGHEST_PROTOCOL) - unpickled = pickle.loads(pickled) - assert_sp_frame_equal(frame, unpickled) + result = self.round_trip_pickle(frame) + assert_sp_frame_equal(frame, result) _test_roundtrip(SparseDataFrame()) self._check_all(_test_roundtrip) @@ -1608,12 +1609,11 @@ def test_from_dict(self): def test_pickle(self): def _test_roundtrip(panel): - pickled = pickle.dumps(panel, protocol=pickle.HIGHEST_PROTOCOL) - unpickled = pickle.loads(pickled) - tm.assert_isinstance(unpickled.items, Index) - tm.assert_isinstance(unpickled.major_axis, Index) - tm.assert_isinstance(unpickled.minor_axis, Index) - assert_sp_panel_equal(panel, unpickled) + result = self.round_trip_pickle(panel) + tm.assert_isinstance(result.items, Index) + tm.assert_isinstance(result.major_axis, Index) + tm.assert_isinstance(result.minor_axis, Index) + assert_sp_panel_equal(panel, result) _test_roundtrip(self.panel) diff --git a/pandas/src/generate_code.py b/pandas/src/generate_code.py index 842be5a1645bf..f7aede92d635d 100644 --- a/pandas/src/generate_code.py +++ b/pandas/src/generate_code.py @@ -55,6 +55,17 @@ else: return np.array(arr, dtype=np.int_) +cpdef ensure_object(object arr): + if util.is_array(arr): + if (<ndarray> arr).descr.type_num == NPY_OBJECT: + return arr + else: + return arr.astype(np.object_) + elif hasattr(arr,'asobject'): + return arr.asobject + else: + return np.array(arr, dtype=np.object_) + """ @@ -2189,7 +2200,7 @@ def outer_join_indexer_%(name)s(ndarray[%(c_type)s] left, ('int32', 'INT32', 'int32'), ('int64', 'INT64', 'int64'), # ('platform_int', 'INT', 'int_'), - ('object', 'OBJECT', 'object_'), + #('object', 'OBJECT', 'object_'), ] def generate_ensure_dtypes(): diff --git a/pandas/src/generated.pyx b/pandas/src/generated.pyx index 97a34582d2ef2..50eefa5e783cf 100644 --- a/pandas/src/generated.pyx +++ b/pandas/src/generated.pyx @@ -49,6 +49,17 @@ cpdef ensure_platform_int(object arr): else: return np.array(arr, dtype=np.int_) +cpdef ensure_object(object arr): + if util.is_array(arr): + if (<ndarray> arr).descr.type_num == NPY_OBJECT: + return arr + else: + return arr.astype(np.object_) + elif hasattr(arr,'asobject'): + return arr.asobject + else: + return np.array(arr, dtype=np.object_) + cpdef ensure_float64(object arr): @@ -111,16 +122,6 @@ cpdef ensure_int64(object arr): return np.array(arr, dtype=np.int64) -cpdef ensure_object(object arr): - if util.is_array(arr): - if (<ndarray> arr).descr.type_num == NPY_OBJECT: - return arr - else: - return arr.astype(np.object_) - else: - return np.array(arr, dtype=np.object_) - - @cython.wraparound(False) @cython.boundscheck(False) cpdef map_indices_float64(ndarray[float64_t] index): @@ -5932,7 +5933,7 @@ def group_mean_bin_float64(ndarray[float64_t, ndim=2] out, for i in range(ngroups): for j in range(K): count = nobs[i, j] - if nobs[i, j] == 0: + if count == 0: out[i, j] = nan else: out[i, j] = sumx[i, j] / count @@ -5985,7 +5986,7 @@ def group_mean_bin_float32(ndarray[float32_t, ndim=2] out, for i in range(ngroups): for j in range(K): count = nobs[i, j] - if nobs[i, j] == 0: + if count == 0: out[i, j] = nan else: out[i, j] = sumx[i, j] / count diff --git a/pandas/src/reduce.pyx b/pandas/src/reduce.pyx index a22e7e636d7e4..add9a03642bed 100644 --- a/pandas/src/reduce.pyx +++ b/pandas/src/reduce.pyx @@ -13,7 +13,7 @@ cdef class Reducer: ''' cdef: Py_ssize_t increment, chunksize, nresults - object arr, dummy, f, labels, typ, index + object arr, dummy, f, labels, typ, ityp, index def __init__(self, object arr, object f, axis=1, dummy=None, labels=None): @@ -37,38 +37,34 @@ cdef class Reducer: self.f = f self.arr = arr - self.typ = None self.labels = labels - self.dummy, index = self._check_dummy(dummy=dummy) - - self.labels = labels - self.index = index + self.dummy, self.typ, self.index, self.ityp = self._check_dummy(dummy=dummy) def _check_dummy(self, dummy=None): - cdef object index + cdef object index=None, typ=None, ityp=None if dummy is None: dummy = np.empty(self.chunksize, dtype=self.arr.dtype) - index = None # our ref is stolen later since we are creating this array # in cython, so increment first Py_INCREF(dummy) + else: + # we passed a series-like if hasattr(dummy,'values'): - self.typ = type(dummy) + typ = type(dummy) index = getattr(dummy,'index',None) dummy = dummy.values if dummy.dtype != self.arr.dtype: raise ValueError('Dummy array must be same dtype') if len(dummy) != self.chunksize: - raise ValueError('Dummy array must be length %d' % - self.chunksize) + raise ValueError('Dummy array must be length %d' % self.chunksize) - return dummy, index + return dummy, typ, index, ityp def get_result(self): cdef: @@ -76,21 +72,23 @@ cdef class Reducer: ndarray arr, result, chunk Py_ssize_t i, incr flatiter it + bint has_labels object res, name, labels, index - object cached_typ = None + object cached_typ=None arr = self.arr chunk = self.dummy dummy_buf = chunk.data chunk.data = arr.data labels = self.labels - index = self.index + has_labels = labels is not None + has_index = self.index is not None incr = self.increment try: for i in range(self.nresults): - if labels is not None: + if has_labels: name = util.get_value_at(labels, i) else: name = None @@ -102,9 +100,9 @@ cdef class Reducer: if self.typ is not None: # recreate with the index if supplied - if index is not None: + if has_index: - cached_typ = self.typ(chunk, index=index, name=name) + cached_typ = self.typ(chunk, index=self.index, name=name) else: @@ -113,6 +111,10 @@ cdef class Reducer: # use the cached_typ if possible if cached_typ is not None: + + if has_index: + object.__setattr__(cached_typ, 'index', self.index) + object.__setattr__(cached_typ._data._block, 'values', chunk) object.__setattr__(cached_typ, 'name', name) res = self.f(cached_typ) @@ -121,7 +123,6 @@ cdef class Reducer: if hasattr(res,'values'): res = res.values - if i == 0: result = self._get_result_array(res) it = <flatiter> PyArray_IterNew(result) @@ -163,7 +164,7 @@ cdef class SeriesBinGrouper: bint passed_dummy cdef public: - object arr, index, dummy_arr, dummy_index, values, f, bins, typ, name + object arr, index, dummy_arr, dummy_index, values, f, bins, typ, ityp, name def __init__(self, object series, object f, object bins, object dummy): n = len(series) @@ -175,8 +176,9 @@ cdef class SeriesBinGrouper: if not values.flags.c_contiguous: values = values.copy('C') self.arr = values - self.index = series.index self.typ = type(series) + self.ityp = type(series.index) + self.index = series.index.values self.name = getattr(series,'name',None) self.dummy_arr, self.dummy_index = self._check_dummy(dummy) @@ -189,6 +191,8 @@ cdef class SeriesBinGrouper: self.ngroups = len(bins) + 1 def _check_dummy(self, dummy=None): + # both values and index must be an ndarray! + if dummy is None: values = np.empty(0, dtype=self.arr.dtype) index = None @@ -198,7 +202,9 @@ cdef class SeriesBinGrouper: raise ValueError('Dummy array must be same dtype') if not values.flags.contiguous: values = values.copy() - index = dummy.index + index = dummy.index.values + if not index.flags.contiguous: + index = index.copy() return values, index @@ -210,8 +216,7 @@ cdef class SeriesBinGrouper: object res bint initialized = 0 Slider vslider, islider - object gin, typ, name - object cached_typ = None + object name, cached_typ=None, cached_ityp=None counts = np.zeros(self.ngroups, dtype=np.int64) @@ -230,8 +235,6 @@ cdef class SeriesBinGrouper: vslider = Slider(self.arr, self.dummy_arr) islider = Slider(self.index, self.dummy_index) - gin = self.dummy_index._engine - try: for i in range(self.ngroups): group_size = counts[i] @@ -240,13 +243,17 @@ cdef class SeriesBinGrouper: vslider.set_length(group_size) if cached_typ is None: - cached_typ = self.typ(vslider.buf, index=islider.buf, + cached_ityp = self.ityp(islider.buf) + cached_typ = self.typ(vslider.buf, index=cached_ityp, name=name) else: + object.__setattr__(cached_ityp, '_data', islider.buf) + cached_ityp._engine.clear_mapping() object.__setattr__(cached_typ._data._block, 'values', vslider.buf) - object.__setattr__(cached_typ, '_index', islider.buf) + object.__setattr__(cached_typ, '_index', cached_ityp) object.__setattr__(cached_typ, 'name', name) + cached_ityp._engine.clear_mapping() res = self.f(cached_typ) res = _extract_result(res) if not initialized: @@ -258,7 +265,6 @@ cdef class SeriesBinGrouper: islider.advance(group_size) vslider.advance(group_size) - gin.clear_mapping() except: raise finally: @@ -292,7 +298,7 @@ cdef class SeriesGrouper: bint passed_dummy cdef public: - object arr, index, dummy_arr, dummy_index, f, labels, values, typ, name + object arr, index, dummy_arr, dummy_index, f, labels, values, typ, ityp, name def __init__(self, object series, object f, object labels, Py_ssize_t ngroups, object dummy): @@ -305,8 +311,9 @@ cdef class SeriesGrouper: if not values.flags.c_contiguous: values = values.copy('C') self.arr = values - self.index = series.index self.typ = type(series) + self.ityp = type(series.index) + self.index = series.index.values self.name = getattr(series,'name',None) self.dummy_arr, self.dummy_index = self._check_dummy(dummy) @@ -314,6 +321,8 @@ cdef class SeriesGrouper: self.ngroups = ngroups def _check_dummy(self, dummy=None): + # both values and index must be an ndarray! + if dummy is None: values = np.empty(0, dtype=self.arr.dtype) index = None @@ -323,7 +332,9 @@ cdef class SeriesGrouper: raise ValueError('Dummy array must be same dtype') if not values.flags.contiguous: values = values.copy() - index = dummy.index + index = dummy.index.values + if not index.flags.contiguous: + index = index.copy() return values, index @@ -335,8 +346,7 @@ cdef class SeriesGrouper: object res bint initialized = 0 Slider vslider, islider - object gin, typ, name - object cached_typ = None + object name, cached_typ=None, cached_ityp=None labels = self.labels counts = np.zeros(self.ngroups, dtype=np.int64) @@ -347,8 +357,6 @@ cdef class SeriesGrouper: vslider = Slider(self.arr, self.dummy_arr) islider = Slider(self.index, self.dummy_index) - gin = self.dummy_index._engine - try: for i in range(n): group_size += 1 @@ -366,13 +374,17 @@ cdef class SeriesGrouper: vslider.set_length(group_size) if cached_typ is None: - cached_typ = self.typ(vslider.buf, index=islider.buf, + cached_ityp = self.ityp(islider.buf) + cached_typ = self.typ(vslider.buf, index=cached_ityp, name=name) else: + object.__setattr__(cached_ityp, '_data', islider.buf) + cached_ityp._engine.clear_mapping() object.__setattr__(cached_typ._data._block, 'values', vslider.buf) - object.__setattr__(cached_typ, '_index', islider.buf) + object.__setattr__(cached_typ, '_index', cached_ityp) object.__setattr__(cached_typ, 'name', name) + cached_ityp._engine.clear_mapping() res = self.f(cached_typ) res = _extract_result(res) if not initialized: @@ -386,8 +398,6 @@ cdef class SeriesGrouper: group_size = 0 - gin.clear_mapping() - except: raise finally: @@ -434,6 +444,7 @@ cdef class Slider: def __init__(self, object values, object buf): assert(values.ndim == 1) + if not values.flags.contiguous: values = values.copy() @@ -463,11 +474,11 @@ cdef class Slider: self.buf.shape[0] = length cpdef reset(self): + self.buf.shape[0] = self.orig_len self.buf.data = self.orig_data self.buf.strides[0] = self.orig_stride - class InvalidApply(Exception): pass @@ -488,7 +499,7 @@ def apply_frame_axis0(object frame, object f, object names, # Need to infer if our low-level mucking is going to cause a segfault if n > 0: - chunk = frame[starts[0]:ends[0]] + chunk = frame.iloc[starts[0]:ends[0]] shape_before = chunk.shape try: result = f(chunk) @@ -497,17 +508,16 @@ def apply_frame_axis0(object frame, object f, object names, except: raise InvalidApply('Let this error raise above us') + slider = BlockSlider(frame) mutated = False item_cache = slider.dummy._item_cache - gin = slider.dummy.index._engine # f7u12 try: for i in range(n): slider.move(starts[i], ends[i]) item_cache.clear() # ugh - gin.clear_mapping() object.__setattr__(slider.dummy, 'name', names[i]) piece = f(slider.dummy) @@ -515,11 +525,12 @@ def apply_frame_axis0(object frame, object f, object names, # I'm paying the price for index-sharing, ugh try: if piece.index is slider.dummy.index: - piece = piece.copy() + piece = piece.copy(deep='all') else: mutated = True except AttributeError: pass + results.append(piece) finally: slider.reset() @@ -532,7 +543,7 @@ cdef class BlockSlider: ''' cdef public: - object frame, dummy + object frame, dummy, index int nblocks Slider idx_slider list blocks @@ -543,6 +554,7 @@ cdef class BlockSlider: def __init__(self, frame): self.frame = frame self.dummy = frame[:0] + self.index = self.dummy.index self.blocks = [b.values for b in self.dummy._data.blocks] @@ -550,7 +562,7 @@ cdef class BlockSlider: util.set_array_not_contiguous(x) self.nblocks = len(self.blocks) - self.idx_slider = Slider(self.frame.index, self.dummy.index) + self.idx_slider = Slider(self.frame.index.values, self.dummy.index.values) self.base_ptrs = <char**> malloc(sizeof(char*) * len(self.blocks)) for i, block in enumerate(self.blocks): @@ -562,6 +574,7 @@ cdef class BlockSlider: cpdef move(self, int start, int end): cdef: ndarray arr + object index # move blocks for i in range(self.nblocks): @@ -571,13 +584,16 @@ cdef class BlockSlider: arr.data = self.base_ptrs[i] + arr.strides[1] * start arr.shape[1] = end - start + # move and set the index self.idx_slider.move(start, end) + object.__setattr__(self.index,'_data',self.idx_slider.buf) + self.index._engine.clear_mapping() cdef reset(self): cdef: ndarray arr - # move blocks + # reset blocks for i in range(self.nblocks): arr = self.blocks[i] @@ -585,12 +601,25 @@ cdef class BlockSlider: arr.data = self.base_ptrs[i] arr.shape[1] = 0 - self.idx_slider.reset() - - def reduce(arr, f, axis=0, dummy=None, labels=None): - if labels._has_complex_internals: - raise Exception('Cannot use shortcut') + """ + + Paramaters + ----------- + arr : NDFrame object + f : function + axis : integer axis + dummy : type of reduced output (series) + labels : Index or None + """ + + if labels is not None: + if labels._has_complex_internals: + raise Exception('Cannot use shortcut') + + # pass as an ndarray + if hasattr(labels,'values'): + labels = labels.values reducer = Reducer(arr, f, axis=axis, dummy=dummy, labels=labels) return reducer.get_result() diff --git a/pandas/src/ujson/python/objToJSON.c b/pandas/src/ujson/python/objToJSON.c index f6cb5b9803e25..c1e9f8edcf423 100644 --- a/pandas/src/ujson/python/objToJSON.c +++ b/pandas/src/ujson/python/objToJSON.c @@ -1537,7 +1537,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) PRINTMARK(); tc->type = JT_OBJECT; pc->columnLabelsLen = PyArray_DIM(pc->newObj, 0); - pc->columnLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(obj, "index"), (JSONObjectEncoder*) enc, pc->columnLabelsLen); + pc->columnLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(PyObject_GetAttrString(obj, "index"), "values"), (JSONObjectEncoder*) enc, pc->columnLabelsLen); if (!pc->columnLabels) { goto INVALID; @@ -1614,7 +1614,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) PRINTMARK(); tc->type = JT_ARRAY; pc->columnLabelsLen = PyArray_DIM(pc->newObj, 1); - pc->columnLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(obj, "columns"), (JSONObjectEncoder*) enc, pc->columnLabelsLen); + pc->columnLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(PyObject_GetAttrString(obj, "columns"), "values"), (JSONObjectEncoder*) enc, pc->columnLabelsLen); if (!pc->columnLabels) { goto INVALID; @@ -1632,7 +1632,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) goto INVALID; } pc->columnLabelsLen = PyArray_DIM(pc->newObj, 1); - pc->columnLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(obj, "columns"), (JSONObjectEncoder*) enc, pc->columnLabelsLen); + pc->columnLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(PyObject_GetAttrString(obj, "columns"), "values"), (JSONObjectEncoder*) enc, pc->columnLabelsLen); if (!pc->columnLabels) { NpyArr_freeLabels(pc->rowLabels, pc->rowLabelsLen); @@ -1645,7 +1645,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) PRINTMARK(); tc->type = JT_OBJECT; pc->rowLabelsLen = PyArray_DIM(pc->newObj, 1); - pc->rowLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(obj, "columns"), (JSONObjectEncoder*) enc, pc->rowLabelsLen); + pc->rowLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(PyObject_GetAttrString(obj, "columns"), "values"), (JSONObjectEncoder*) enc, pc->rowLabelsLen); if (!pc->rowLabels) { goto INVALID; diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 6353ad53a88ef..fe070cff2e0ea 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -187,16 +187,17 @@ def test_object_refcount_bug(self): len(algos.unique(lst)) def test_on_index_object(self): + mindex = pd.MultiIndex.from_arrays([np.arange(5).repeat(5), np.tile(np.arange(5), 5)]) + expected = mindex.values + expected.sort() + mindex = mindex.repeat(2) result = pd.unique(mindex) result.sort() - expected = mindex.values - expected.sort() - tm.assert_almost_equal(result, expected) class TestValueCounts(tm.TestCase): diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 9acb1804a7ef0..90a36228e816a 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -197,6 +197,32 @@ def setUp(self): self.is_valid_objs = [ o for o in self.objs if o._allow_index_ops ] self.not_valid_objs = [ o for o in self.objs if not o._allow_index_ops ] + def test_ndarray_compat_properties(self): + + for o in self.objs: + + # check that we work + for p in ['shape','dtype','base','flags','T', + 'strides','itemsize','nbytes']: + self.assertIsNotNone(getattr(o,p,None)) + + # if we have a datetimelike dtype then needs a view to work + # but the user is responsible for that + try: + self.assertIsNotNone(o.data) + except (ValueError): + pass + + # len > 1 + self.assertRaises(ValueError, lambda : o.item()) + + self.assertTrue(o.ndim == 1) + + self.assertTrue(o.size == len(o)) + + self.assertTrue(Index([1]).item() == 1) + self.assertTrue(Series([1]).item() == 1) + def test_ops(self): tm._skip_if_not_numpy17_friendly() for op in ['max','min']: @@ -243,11 +269,13 @@ def test_value_counts_unique_nunique(self): # create repeated values, 'n'th element is repeated by n+1 times if isinstance(o, PeriodIndex): # freq must be specified because repeat makes freq ambiguous + expected_index = o[::-1] o = klass(np.repeat(values, range(1, len(o) + 1)), freq=o.freq) else: + expected_index = values[::-1] o = klass(np.repeat(values, range(1, len(o) + 1))) - expected_s = Series(range(10, 0, -1), index=values[::-1], dtype='int64') + expected_s = Series(range(10, 0, -1), index=expected_index, dtype='int64') tm.assert_series_equal(o.value_counts(), expected_s) result = o.unique() @@ -278,12 +306,14 @@ def test_value_counts_unique_nunique(self): # create repeated values, 'n'th element is repeated by n+1 times if isinstance(o, PeriodIndex): + expected_index = o o = klass(np.repeat(values, range(1, len(o) + 1)), freq=o.freq) else: + expected_index = values o = klass(np.repeat(values, range(1, len(o) + 1))) - expected_s_na = Series(list(range(10, 2, -1)) +[3], index=values[9:0:-1], dtype='int64') - expected_s = Series(list(range(10, 2, -1)), index=values[9:1:-1], dtype='int64') + expected_s_na = Series(list(range(10, 2, -1)) +[3], index=expected_index[9:0:-1], dtype='int64') + expected_s = Series(list(range(10, 2, -1)), index=expected_index[9:1:-1], dtype='int64') tm.assert_series_equal(o.value_counts(dropna=False), expected_s_na) tm.assert_series_equal(o.value_counts(), expected_s) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 88a86da27daf9..6a31f573951cd 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -16,7 +16,7 @@ from pandas.compat import( map, zip, range, long, lrange, lmap, lzip, - OrderedDict, cPickle as pickle, u, StringIO + OrderedDict, u, StringIO ) from pandas import compat @@ -3620,6 +3620,7 @@ def test_constructor_with_datetimes(self): df = DataFrame() df['a'] = i assert_frame_equal(df, expected) + df = DataFrame( {'a' : i } ) assert_frame_equal(df, expected) @@ -3925,14 +3926,14 @@ def test_array_interface(self): assert_frame_equal(result, self.frame.apply(np.sqrt)) def test_pickle(self): - unpickled = pickle.loads(pickle.dumps(self.mixed_frame)) + unpickled = self.round_trip_pickle(self.mixed_frame) assert_frame_equal(self.mixed_frame, unpickled) # buglet self.mixed_frame._data.ndim # empty - unpickled = pickle.loads(pickle.dumps(self.empty)) + unpickled = self.round_trip_pickle(self.empty) repr(unpickled) def test_to_dict(self): @@ -12578,6 +12579,7 @@ def test_empty_nonzero(self): self.assertTrue(df.T.empty) def test_any_all(self): + self._check_bool_op('any', np.any, has_skipna=True, has_bool_only=True) self._check_bool_op('all', np.all, has_skipna=True, has_bool_only=True) diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 5d9b43e48e3c1..8dbcb8c542fb3 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -1000,7 +1000,8 @@ def test_xcompat(self): pd.plot_params['x_compat'] = False ax = df.plot() lines = ax.get_lines() - tm.assert_isinstance(lines[0].get_xdata(), PeriodIndex) + self.assertNotIsInstance(lines[0].get_xdata(), PeriodIndex) + self.assertIsInstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex) tm.close() # useful if you're plotting a bunch together @@ -1012,7 +1013,8 @@ def test_xcompat(self): tm.close() ax = df.plot() lines = ax.get_lines() - tm.assert_isinstance(lines[0].get_xdata(), PeriodIndex) + self.assertNotIsInstance(lines[0].get_xdata(), PeriodIndex) + self.assertIsInstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex) def test_unsorted_index(self): df = DataFrame({'y': np.arange(100)}, diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index f958d5481ad33..8e9503b4fe1a3 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -2152,6 +2152,10 @@ def test_non_cython_api(self): result = g.idxmax() assert_frame_equal(result,expected) + def test_cython_api2(self): + + # this takes the fast apply path + # cumsum (GH5614) df = DataFrame([[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=['A', 'B', 'C']) expected = DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=['B', 'C']) @@ -2425,6 +2429,31 @@ def convert_force_pure(x): self.assertEqual(result.dtype, np.object_) tm.assert_isinstance(result[0], Decimal) + def test_fast_apply(self): + # make sure that fast apply is correctly called + # rather than raising any kind of error + # otherwise the python path will be callsed + # which slows things down + N = 1000 + labels = np.random.randint(0, 2000, size=N) + labels2 = np.random.randint(0, 3, size=N) + df = DataFrame({'key': labels, + 'key2': labels2, + 'value1': np.random.randn(N), + 'value2': ['foo', 'bar', 'baz', 'qux'] * (N // 4)}) + def f(g): + return 1 + + g = df.groupby(['key', 'key2']) + + grouper = g.grouper + + splitter = grouper._get_splitter(g._selected_obj, axis=g.axis) + group_keys = grouper._get_group_keys() + + values, mutated = splitter.fast_apply(f, group_keys) + self.assertFalse(mutated) + def test_apply_with_mixed_dtype(self): # GH3480, apply with mixed dtype on axis=1 breaks in 0.11 df = DataFrame({'foo1' : ['one', 'two', 'two', 'three', 'one', 'two'], diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index c32c7ddc55ced..5affdbe1c99aa 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -3,7 +3,6 @@ from datetime import datetime, timedelta from pandas.compat import range, lrange, lzip, u, zip import operator -import pickle import re import nose import warnings @@ -12,9 +11,12 @@ import numpy as np from numpy.testing import assert_array_equal +from pandas import period_range, date_range + from pandas.core.index import (Index, Float64Index, Int64Index, MultiIndex, - InvalidIndexError) + InvalidIndexError, NumericIndex) from pandas.tseries.index import DatetimeIndex +from pandas.tseries.period import PeriodIndex from pandas.core.series import Series from pandas.util.testing import (assert_almost_equal, assertRaisesRegexp, assert_copy) @@ -32,7 +34,48 @@ from pandas import _np_version_under1p7 -class TestIndex(tm.TestCase): +class Base(object): + """ base class for index sub-class tests """ + _holder = None + + def verify_pickle(self,index): + unpickled = self.round_trip_pickle(index) + self.assertTrue(index.equals(unpickled)) + + def test_pickle_compat_construction(self): + # this is testing for pickle compat + if self._holder is None: + return + + # need an object to create with + self.assertRaises(TypeError, self._holder) + + def test_numeric_compat(self): + + idx = self.create_index() + tm.assertRaisesRegexp(TypeError, + "cannot perform multiplication", + lambda : idx * 1) + tm.assertRaisesRegexp(TypeError, + "cannot perform multiplication", + lambda : 1 * idx) + + div_err = "cannot perform true division" if compat.PY3 else "cannot perform division" + tm.assertRaisesRegexp(TypeError, + div_err, + lambda : idx / 1) + tm.assertRaisesRegexp(TypeError, + div_err, + lambda : 1 / idx) + tm.assertRaisesRegexp(TypeError, + "cannot perform floor division", + lambda : idx // 1) + tm.assertRaisesRegexp(TypeError, + "cannot perform floor division", + lambda : 1 // idx) + +class TestIndex(Base, tm.TestCase): + _holder = Index _multiprocess_can_split_ = True def setUp(self): @@ -49,6 +92,9 @@ def setUp(self): for name, ind in self.indices.items(): setattr(self, name, ind) + def create_index(self): + return Index(list('abcde')) + def test_wrong_number_names(self): def testit(ind): ind.names = ["apple", "banana", "carrot"] @@ -123,7 +169,7 @@ def test_constructor(self): # casting arr = np.array(self.strIndex) - index = arr.view(Index) + index = Index(arr) tm.assert_contains_all(arr, index) self.assert_numpy_array_equal(self.strIndex, index) @@ -181,13 +227,12 @@ def __array__(self, dtype=None): for array in [np.arange(5), np.array(['a', 'b', 'c']), - pd.date_range('2000-01-01', periods=3).values]: + date_range('2000-01-01', periods=3).values]: expected = pd.Index(array) result = pd.Index(ArrayLike(array)) self.assertTrue(result.equals(expected)) def test_index_ctor_infer_periodindex(self): - from pandas import period_range, PeriodIndex xp = period_range('2012-1-1', freq='M', periods=3) rs = Index(xp) assert_array_equal(rs, xp) @@ -312,8 +357,9 @@ def test_is_(self): self.assertFalse(ind.is_(ind[:])) self.assertFalse(ind.is_(ind.view(np.ndarray).view(Index))) self.assertFalse(ind.is_(np.array(range(10)))) + # quasi-implementation dependent - self.assertTrue(ind.is_(ind.view().base)) + self.assertTrue(ind.is_(ind.view())) ind2 = ind.view() ind2.name = 'bob' self.assertTrue(ind.is_(ind2)) @@ -366,8 +412,7 @@ def _check(op): arr_result = op(arr, element) index_result = op(index, element) - tm.assert_isinstance(index_result, np.ndarray) - self.assertNotIsInstance(index_result, Index) + self.assertIsInstance(index_result, np.ndarray) self.assert_numpy_array_equal(arr_result, index_result) _check(operator.eq) @@ -617,6 +662,7 @@ def test_symmetric_diff(self): idx2 = Index([0, 1, np.nan]) result = idx1.sym_diff(idx2) # expected = Index([0.0, np.nan, 2.0, 3.0, np.nan]) + nans = pd.isnull(result) self.assertEqual(nans.sum(), 2) self.assertEqual((~nans).sum(), 3) @@ -639,21 +685,11 @@ def test_symmetric_diff(self): idx1 - 1 def test_pickle(self): - def testit(index): - pickled = pickle.dumps(index) - unpickled = pickle.loads(pickled) - - tm.assert_isinstance(unpickled, Index) - self.assert_numpy_array_equal(unpickled, index) - self.assertEqual(unpickled.name, index.name) - - # tm.assert_dict_equal(unpickled.indexMap, index.indexMap) - testit(self.strIndex) + self.verify_pickle(self.strIndex) self.strIndex.name = 'foo' - testit(self.strIndex) - - testit(self.dateIndex) + self.verify_pickle(self.strIndex) + self.verify_pickle(self.dateIndex) def test_is_numeric(self): self.assertFalse(self.dateIndex.is_numeric()) @@ -902,9 +938,7 @@ def test_boolean_cmp(self): idx = Index(values) res = (idx == values) - self.assertTrue(res.all()) - self.assertEqual(res.dtype, 'bool') - self.assertNotIsInstance(res, Index) + self.assert_numpy_array_equal(res,np.array([True,True,True,True],dtype=bool)) def test_get_level_values(self): result = self.strIndex.get_level_values(0) @@ -951,13 +985,64 @@ def test_nan_first_take_datetime(self): tm.assert_index_equal(res, exp) -class TestFloat64Index(tm.TestCase): +class Numeric(Base): + + def test_numeric_compat(self): + + idx = self._holder(np.arange(5,dtype='int64')) + didx = self._holder(np.arange(5,dtype='int64')**2 + ) + result = idx * 1 + tm.assert_index_equal(result, idx) + + result = 1 * idx + tm.assert_index_equal(result, idx) + + result = idx * idx + tm.assert_index_equal(result, didx) + + result = idx / 1 + tm.assert_index_equal(result, idx) + + result = idx // 1 + tm.assert_index_equal(result, idx) + + result = idx * np.array(5,dtype='int64') + tm.assert_index_equal(result, self._holder(np.arange(5,dtype='int64')*5)) + + result = idx * np.arange(5,dtype='int64') + tm.assert_index_equal(result, didx) + + result = idx * Series(np.arange(5,dtype='int64')) + tm.assert_index_equal(result, didx) + + result = idx * Series(np.arange(5,dtype='float64')+0.1) + tm.assert_index_equal(result, + Float64Index(np.arange(5,dtype='float64')*(np.arange(5,dtype='float64')+0.1))) + + + # invalid + self.assertRaises(TypeError, lambda : idx * date_range('20130101',periods=5)) + self.assertRaises(ValueError, lambda : idx * self._holder(np.arange(3))) + self.assertRaises(ValueError, lambda : idx * np.array([1,2])) + + def test_ufunc_compat(self): + idx = self._holder(np.arange(5,dtype='int64')) + result = np.sin(idx) + expected = Float64Index(np.sin(np.arange(5,dtype='int64'))) + tm.assert_index_equal(result, expected) + +class TestFloat64Index(Numeric, tm.TestCase): + _holder = Float64Index _multiprocess_can_split_ = True def setUp(self): self.mixed = Float64Index([1.5, 2, 3, 4, 5]) self.float = Float64Index(np.arange(5) * 2.5) + def create_index(self): + return Float64Index(np.arange(5,dtype='float64')) + def test_hash_error(self): with tm.assertRaisesRegexp(TypeError, "unhashable type: %r" % @@ -1095,12 +1180,16 @@ def test_astype_from_object(self): tm.assert_index_equal(result, expected) -class TestInt64Index(tm.TestCase): +class TestInt64Index(Numeric, tm.TestCase): + _holder = Int64Index _multiprocess_can_split_ = True def setUp(self): self.index = Int64Index(np.arange(0, 20, 2)) + def create_index(self): + return Int64Index(np.arange(5,dtype='int64')) + def test_too_many_names(self): def testit(): self.index.names = ["roger", "harold"] @@ -1519,8 +1608,38 @@ def test_slice_keep_name(self): idx = Int64Index([1, 2], name='asdf') self.assertEqual(idx.name, idx[1:].name) +class TestDatetimeIndex(Base, tm.TestCase): + _holder = DatetimeIndex + _multiprocess_can_split_ = True + + def create_index(self): + return date_range('20130101',periods=5) + + def test_pickle_compat_construction(self): + pass + + def test_numeric_compat(self): + super(TestDatetimeIndex, self).test_numeric_compat() + + if not (_np_version_under1p7 or compat.PY3_2): + for f in [lambda : np.timedelta64(1, 'D').astype('m8[ns]') * pd.date_range('2000-01-01', periods=3), + lambda : pd.date_range('2000-01-01', periods=3) * np.timedelta64(1, 'D').astype('m8[ns]') ]: + tm.assertRaisesRegexp(TypeError, + "cannot perform multiplication with this index type", + f) -class TestMultiIndex(tm.TestCase): +class TestPeriodIndex(Base, tm.TestCase): + _holder = PeriodIndex + _multiprocess_can_split_ = True + + def create_index(self): + return period_range('20130101',periods=5,freq='D') + + def test_pickle_compat_construction(self): + pass + +class TestMultiIndex(Base, tm.TestCase): + _holder = MultiIndex _multiprocess_can_split_ = True def setUp(self): @@ -1534,6 +1653,9 @@ def setUp(self): labels=[major_labels, minor_labels], names=self.index_names, verify_integrity=False) + def create_index(self): + return self.index + def test_hash_error(self): with tm.assertRaisesRegexp(TypeError, "unhashable type: %r" % @@ -1574,6 +1696,7 @@ def test_set_names_and_rename(self): def test_set_levels(self): + # side note - you probably wouldn't want to use levels and labels # directly like this - but it is possible. levels, labels = self.index.levels, self.index.labels @@ -1966,6 +2089,7 @@ def check_level_names(self, index, names): self.assertEqual([level.name for level in index.levels], list(names)) def test_changing_names(self): + # names should be applied to levels level_names = [level.name for level in self.index.levels] self.check_level_names(self.index, self.index.names) @@ -2015,6 +2139,7 @@ def test_from_arrays(self): self.assertTrue(result.levels[1].equals(Index(['a','b']))) def test_from_product(self): + first = ['foo', 'bar', 'buz'] second = ['a', 'b', 'c'] names = ['first', 'second'] @@ -2029,7 +2154,7 @@ def test_from_product(self): self.assertEqual(result.names, names) def test_from_product_datetimeindex(self): - dt_index = pd.date_range('2000-01-01', periods=2) + dt_index = date_range('2000-01-01', periods=2) mi = pd.MultiIndex.from_product([[1, 2], dt_index]) etalon = pd.lib.list_to_object_array([(1, pd.Timestamp('2000-01-01')), (1, pd.Timestamp('2000-01-02')), @@ -2108,23 +2233,12 @@ def test_iter(self): ('baz', 'two'), ('qux', 'one'), ('qux', 'two')] self.assertEqual(result, expected) - def test_pickle(self): - pickled = pickle.dumps(self.index) - unpickled = pickle.loads(pickled) - self.assertTrue(self.index.equals(unpickled)) - def test_legacy_pickle(self): if compat.PY3: - raise nose.SkipTest("doesn't work on Python 3") - - def curpath(): - pth, _ = os.path.split(os.path.abspath(__file__)) - return pth + raise nose.SkipTest("testing for legacy pickles not support on py3") - ppath = os.path.join(curpath(), 'data/multiindex_v1.pickle') - obj = pickle.load(open(ppath, 'r')) - - self.assertTrue(obj._is_v1) + path = tm.get_data_path('multiindex_v1.pickle') + obj = pd.read_pickle(path) obj2 = MultiIndex.from_tuples(obj.values) self.assertTrue(obj.equals(obj2)) @@ -2140,11 +2254,10 @@ def curpath(): assert_almost_equal(exp, exp2) def test_legacy_v2_unpickle(self): - # 0.7.3 -> 0.8.0 format manage - pth, _ = os.path.split(os.path.abspath(__file__)) - filepath = os.path.join(pth, 'data', 'mindex_073.pickle') - obj = pd.read_pickle(filepath) + # 0.7.3 -> 0.8.0 format manage + path = tm.get_data_path('mindex_073.pickle') + obj = pd.read_pickle(path) obj2 = MultiIndex.from_tuples(obj.values) self.assertTrue(obj.equals(obj2)) @@ -2562,6 +2675,7 @@ def test_identical(self): self.assertTrue(mi.equals(mi4)) def test_is_(self): + mi = MultiIndex.from_tuples(lzip(range(10), range(10))) self.assertTrue(mi.is_(mi)) self.assertTrue(mi.is_(mi.view())) @@ -2571,6 +2685,7 @@ def test_is_(self): mi2.names = ["A", "B"] self.assertTrue(mi2.is_(mi)) self.assertTrue(mi.is_(mi2)) + self.assertTrue(mi.is_(mi.set_names(["C", "D"]))) mi2 = mi.view() mi2.set_names(["E", "F"], inplace=True) diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index 36dbced6eda8c..a523df4cc2461 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -9,7 +9,7 @@ from pandas.core.internals import * import pandas.core.internals as internals import pandas.util.testing as tm - +import pandas as pd from pandas.util.testing import ( assert_almost_equal, assert_frame_equal, randn) from pandas.compat import zip, u @@ -182,12 +182,9 @@ def test_constructor(self): self.assertEqual(int32block.dtype, np.int32) def test_pickle(self): - import pickle def _check(blk): - pickled = pickle.dumps(blk) - unpickled = pickle.loads(pickled) - assert_block_equal(blk, unpickled) + assert_block_equal(self.round_trip_pickle(blk), blk) _check(self.fblock) _check(self.cblock) @@ -341,12 +338,8 @@ def test_contains(self): self.assertNotIn('baz', self.mgr) def test_pickle(self): - import pickle - - pickled = pickle.dumps(self.mgr) - mgr2 = pickle.loads(pickled) - # same result + mgr2 = self.round_trip_pickle(self.mgr) assert_frame_equal(DataFrame(self.mgr), DataFrame(mgr2)) # share ref_items @@ -361,13 +354,13 @@ def test_pickle(self): self.assertFalse(mgr2._known_consolidated) def test_non_unique_pickle(self): - import pickle + mgr = create_mgr('a,a,a:f8') - mgr2 = pickle.loads(pickle.dumps(mgr)) + mgr2 = self.round_trip_pickle(mgr) assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) mgr = create_mgr('a: f8; a: i8') - mgr2 = pickle.loads(pickle.dumps(mgr)) + mgr2 = self.round_trip_pickle(mgr) assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) def test_get_scalar(self): diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 6d0d7aaf37b02..ed078ae5749de 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -14,7 +14,7 @@ assertRaisesRegexp) import pandas.core.common as com import pandas.util.testing as tm -from pandas.compat import (range, lrange, StringIO, lzip, u, cPickle, +from pandas.compat import (range, lrange, StringIO, lzip, u, product as cart_product, zip) import pandas as pd @@ -181,8 +181,7 @@ def _check_op(opname): def test_pickle(self): def _test_roundtrip(frame): - pickled = cPickle.dumps(frame) - unpickled = cPickle.loads(pickled) + unpickled = self.round_trip_pickle(frame) assert_frame_equal(frame, unpickled) _test_roundtrip(self.frame) @@ -445,6 +444,7 @@ def test_xs(self): ] df = DataFrame(acc, columns=['a1','a2','cnt']).set_index(['a1','a2']) expected = DataFrame({ 'cnt' : [24,26,25,26] }, index=Index(['xbcde',np.nan,'zbcde','ybcde'],name='a2')) + result = df.xs('z',level='a1') assert_frame_equal(result, expected) @@ -2106,13 +2106,13 @@ def test_reset_index_datetime(self): idx1 = pd.date_range('1/1/2011', periods=5, freq='D', tz=tz, name='idx1') idx2 = pd.Index(range(5), name='idx2',dtype='int64') idx = pd.MultiIndex.from_arrays([idx1, idx2]) - df = pd.DataFrame({'a': np.arange(5,dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx) + df = pd.DataFrame({'a': np.arange(5,dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx) expected = pd.DataFrame({'idx1': [datetime.datetime(2011, 1, 1), datetime.datetime(2011, 1, 2), datetime.datetime(2011, 1, 3), datetime.datetime(2011, 1, 4), - datetime.datetime(2011, 1, 5)], + datetime.datetime(2011, 1, 5)], 'idx2': np.arange(5,dtype='int64'), 'a': np.arange(5,dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, columns=['idx1', 'idx2', 'a', 'b']) @@ -2122,19 +2122,19 @@ def test_reset_index_datetime(self): idx3 = pd.date_range('1/1/2012', periods=5, freq='MS', tz='Europe/Paris', name='idx3') idx = pd.MultiIndex.from_arrays([idx1, idx2, idx3]) - df = pd.DataFrame({'a': np.arange(5,dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx) + df = pd.DataFrame({'a': np.arange(5,dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx) expected = pd.DataFrame({'idx1': [datetime.datetime(2011, 1, 1), datetime.datetime(2011, 1, 2), datetime.datetime(2011, 1, 3), datetime.datetime(2011, 1, 4), - datetime.datetime(2011, 1, 5)], + datetime.datetime(2011, 1, 5)], 'idx2': np.arange(5,dtype='int64'), 'idx3': [datetime.datetime(2012, 1, 1), datetime.datetime(2012, 2, 1), datetime.datetime(2012, 3, 1), datetime.datetime(2012, 4, 1), - datetime.datetime(2012, 5, 1)], + datetime.datetime(2012, 5, 1)], 'a': np.arange(5,dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, columns=['idx1', 'idx2', 'idx3', 'a', 'b']) expected['idx1'] = expected['idx1'].apply(lambda d: pd.Timestamp(d, tz=tz)) @@ -2148,7 +2148,7 @@ def test_reset_index_datetime(self): expected = pd.DataFrame({'level_0': 'a a a b b b'.split(), 'level_1': [datetime.datetime(2013, 1, 1), datetime.datetime(2013, 1, 2), - datetime.datetime(2013, 1, 3)] * 2, + datetime.datetime(2013, 1, 3)] * 2, 'a': np.arange(6, dtype='int64')}, columns=['level_0', 'level_1', 'a']) expected['level_1'] = expected['level_1'].apply(lambda d: pd.Timestamp(d, offset='D', tz=tz)) diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index f8798e794d22c..fb1f1c1693fdd 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -12,7 +12,7 @@ from pandas.core.series import remove_na import pandas.core.common as com from pandas import compat -from pandas.compat import range, lrange, StringIO, cPickle, OrderedDict +from pandas.compat import range, lrange, StringIO, OrderedDict from pandas.util.testing import (assert_panel_equal, assert_frame_equal, @@ -31,8 +31,7 @@ class PanelTests(object): panel = None def test_pickle(self): - pickled = cPickle.dumps(self.panel) - unpickled = cPickle.loads(pickled) + unpickled = self.round_trip_pickle(self.panel) assert_frame_equal(unpickled['ItemA'], self.panel['ItemA']) def test_cumsum(self): diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index fcd4b89377176..01e9e15585fc0 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -27,7 +27,7 @@ import pandas.core.datetools as datetools import pandas.core.nanops as nanops -from pandas.compat import StringIO, lrange, range, zip, u, OrderedDict, long +from pandas.compat import StringIO, lrange, range, zip, u, OrderedDict, long, PY3_2 from pandas import compat from pandas.util.testing import (assert_series_equal, assert_almost_equal, @@ -61,6 +61,7 @@ def test_copy_index_name_checking(self): self.ts.index.name = None self.assertIsNone(self.ts.index.name) self.assertIs(self.ts, self.ts) + cp = self.ts.copy() cp.index.name = 'foo' com.pprint_thing(self.ts.index.name) @@ -1867,7 +1868,7 @@ def test_timeseries_periodindex(self): from pandas import period_range prng = period_range('1/1/2011', '1/1/2012', freq='M') ts = Series(np.random.randn(len(prng)), prng) - new_ts = pickle.loads(pickle.dumps(ts)) + new_ts = self.round_trip_pickle(ts) self.assertEqual(new_ts.index.freq, 'M') def test_iter(self): @@ -5232,9 +5233,15 @@ def test_align_sameindex(self): # self.assertIsNot(b.index, self.ts.index) def test_reindex(self): + identity = self.series.reindex(self.series.index) - self.assertTrue(np.may_share_memory(self.series.index, identity.index)) + + # the older numpies / 3.2 call __array_inteface__ which we don't define + if not _np_version_under1p7 and not PY3_2: + self.assertTrue(np.may_share_memory(self.series.index, identity.index)) + self.assertTrue(identity.index.is_(self.series.index)) + self.assertTrue(identity.index.identical(self.series.index)) subIndex = self.series.index[10:20] subSeries = self.series.reindex(subIndex) @@ -6083,7 +6090,7 @@ def test_unique_data_ownership(self): # it works! #1807 Series(Series(["a", "c", "b"]).unique()).sort() - if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False) + diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py index d5f7a536f9fe8..5c26fce2b111e 100644 --- a/pandas/tests/test_tseries.py +++ b/pandas/tests/test_tseries.py @@ -32,7 +32,7 @@ def test_backfill(self): old = Index([1, 5, 10]) new = Index(lrange(12)) - filler = algos.backfill_int64(old, new) + filler = algos.backfill_int64(old.values, new.values) expect_filler = [0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, -1] self.assert_numpy_array_equal(filler, expect_filler) @@ -40,7 +40,7 @@ def test_backfill(self): # corner case old = Index([1, 4]) new = Index(lrange(5, 10)) - filler = algos.backfill_int64(old, new) + filler = algos.backfill_int64(old.values, new.values) expect_filler = [-1, -1, -1, -1, -1] self.assert_numpy_array_equal(filler, expect_filler) @@ -49,7 +49,7 @@ def test_pad(self): old = Index([1, 5, 10]) new = Index(lrange(12)) - filler = algos.pad_int64(old, new) + filler = algos.pad_int64(old.values, new.values) expect_filler = [-1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2] self.assert_numpy_array_equal(filler, expect_filler) @@ -57,7 +57,7 @@ def test_pad(self): # corner case old = Index([5, 10]) new = Index(lrange(5)) - filler = algos.pad_int64(old, new) + filler = algos.pad_int64(old.values, new.values) expect_filler = [-1, -1, -1, -1, -1] self.assert_numpy_array_equal(filler, expect_filler) @@ -165,7 +165,7 @@ def test_left_join_indexer2(): idx = Index([1, 1, 2, 5]) idx2 = Index([1, 2, 5, 7, 9]) - res, lidx, ridx = algos.left_join_indexer_int64(idx2, idx) + res, lidx, ridx = algos.left_join_indexer_int64(idx2.values, idx.values) exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64) assert_almost_equal(res, exp_res) @@ -181,7 +181,7 @@ def test_outer_join_indexer2(): idx = Index([1, 1, 2, 5]) idx2 = Index([1, 2, 5, 7, 9]) - res, lidx, ridx = algos.outer_join_indexer_int64(idx2, idx) + res, lidx, ridx = algos.outer_join_indexer_int64(idx2.values, idx.values) exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64) assert_almost_equal(res, exp_res) @@ -197,7 +197,7 @@ def test_inner_join_indexer2(): idx = Index([1, 1, 2, 5]) idx2 = Index([1, 2, 5, 7, 9]) - res, lidx, ridx = algos.inner_join_indexer_int64(idx2, idx) + res, lidx, ridx = algos.inner_join_indexer_int64(idx2.values, idx.values) exp_res = np.array([1, 1, 2, 5], dtype=np.int64) assert_almost_equal(res, exp_res) @@ -690,6 +690,10 @@ def test_int_index(self): expected = arr.sum(1) assert_almost_equal(result, expected) + result = lib.reduce(arr, np.sum, axis=1, + dummy=dummy, labels=Index(np.arange(100))) + assert_almost_equal(result, expected) + class TestTsUtil(tm.TestCase): def test_min_valid(self): diff --git a/pandas/tools/pivot.py b/pandas/tools/pivot.py index ada13d6f4bccb..83df908d8033f 100644 --- a/pandas/tools/pivot.py +++ b/pandas/tools/pivot.py @@ -3,7 +3,7 @@ import warnings from pandas import Series, DataFrame -from pandas.core.index import MultiIndex +from pandas.core.index import MultiIndex, Index from pandas.core.groupby import Grouper from pandas.tools.merge import concat from pandas.tools.util import cartesian_product @@ -307,7 +307,7 @@ def _all_key(): def _convert_by(by): if by is None: by = [] - elif (np.isscalar(by) or isinstance(by, (np.ndarray, Series, Grouper)) + elif (np.isscalar(by) or isinstance(by, (np.ndarray, Index, Series, Grouper)) or hasattr(by, '__call__')): by = [by] else: diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index 8f79f14cd551a..5d85b68234f96 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -12,7 +12,7 @@ from pandas.util.decorators import cache_readonly, deprecate_kwarg import pandas.core.common as com from pandas.core.generic import _shared_docs, _shared_doc_kwargs -from pandas.core.index import MultiIndex +from pandas.core.index import Index, MultiIndex from pandas.core.series import Series, remove_na from pandas.tseries.index import DatetimeIndex from pandas.tseries.period import PeriodIndex, Period @@ -821,7 +821,7 @@ def __init__(self, data, kind=None, by=None, subplots=False, sharex=True, for kw, err in zip(['xerr', 'yerr'], [xerr, yerr]): self.errors[kw] = self._parse_errorbars(kw, err) - if not isinstance(secondary_y, (bool, tuple, list, np.ndarray)): + if not isinstance(secondary_y, (bool, tuple, list, np.ndarray, Index)): secondary_y = [secondary_y] self.secondary_y = secondary_y @@ -872,7 +872,7 @@ def _iter_data(self, data=None, keep_index=False): data = self.data from pandas.core.frame import DataFrame - if isinstance(data, (Series, np.ndarray)): + if isinstance(data, (Series, np.ndarray, Index)): if keep_index is True: yield self.label, data else: @@ -1223,7 +1223,7 @@ def on_right(self, i): return self.secondary_y if (isinstance(self.data, DataFrame) and - isinstance(self.secondary_y, (tuple, list, np.ndarray))): + isinstance(self.secondary_y, (tuple, list, np.ndarray, Index))): return self.data.columns[i] in self.secondary_y def _get_style(self, i, col_name): @@ -2485,7 +2485,7 @@ def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, return axes if column is not None: - if not isinstance(column, (list, np.ndarray)): + if not isinstance(column, (list, np.ndarray, Index)): column = [column] data = data[column] data = data._get_numeric_data() @@ -2962,7 +2962,7 @@ def _subplots(nrows=1, ncols=1, naxes=None, sharex=False, sharey=False, squeeze= axarr[i] = ax if nplots > 1: - + if sharex and nrows > 1: for ax in axarr[:naxes][:-ncols]: # only bottom row for label in ax.get_xticklabels(): @@ -3015,7 +3015,7 @@ def _subplots(nrows=1, ncols=1, naxes=None, sharex=False, sharey=False, squeeze= def _flatten(axes): if not com.is_list_like(axes): axes = [axes] - elif isinstance(axes, np.ndarray): + elif isinstance(axes, (np.ndarray, Index)): axes = axes.ravel() return axes diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py index a16df00351d76..7e52c8c333dbf 100644 --- a/pandas/tools/tests/test_pivot.py +++ b/pandas/tools/tests/test_pivot.py @@ -517,10 +517,10 @@ def test_pivot_datetime_tz(self): exp_col3 = pd.DatetimeIndex(['2013-01-01 15:00:00', '2013-02-01 15:00:00'] * 4, tz='Asia/Tokyo', name='dt2') exp_col = MultiIndex.from_arrays([exp_col1, exp_col2, exp_col3]) - expected = DataFrame(np.array([[0, 3, 1, 2, 0, 3, 1, 2], + expected = DataFrame(np.array([[0, 3, 1, 2, 0, 3, 1, 2], [1, 4, 2, 1, 1, 4, 2, 1], - [2, 5, 1, 2, 2, 5, 1, 2]], dtype='int64'), - index=exp_idx, + [2, 5, 1, 2, 2, 5, 1, 2]], dtype='int64'), + index=exp_idx, columns=exp_col) result = pivot_table(df, index=['dt1'], columns=['dt2'], values=['value1', 'value2'], diff --git a/pandas/tseries/converter.py b/pandas/tseries/converter.py index 80ac97ee60617..b014e718d5411 100644 --- a/pandas/tseries/converter.py +++ b/pandas/tseries/converter.py @@ -59,7 +59,7 @@ def convert(value, unit, axis): return time2num(value) if isinstance(value, Index): return value.map(time2num) - if isinstance(value, (list, tuple, np.ndarray)): + if isinstance(value, (list, tuple, np.ndarray, Index)): return [time2num(x) for x in value] return value @@ -116,8 +116,8 @@ def convert(values, units, axis): return values.asfreq(axis.freq).values if isinstance(values, Index): return values.map(lambda x: get_datevalue(x, axis.freq)) - if isinstance(values, (list, tuple, np.ndarray)): - return [get_datevalue(x, axis.freq) for x in values] + if isinstance(values, (list, tuple, np.ndarray, Index)): + return PeriodIndex(values, freq=axis.freq).values return values @@ -127,7 +127,7 @@ def get_datevalue(date, freq): elif isinstance(date, (str, datetime, pydt.date, pydt.time)): return Period(date, freq).ordinal elif (com.is_integer(date) or com.is_float(date) or - (isinstance(date, np.ndarray) and (date.size == 1))): + (isinstance(date, (np.ndarray, Index)) and (date.size == 1))): return date elif date is None: return None @@ -145,7 +145,7 @@ def _dt_to_float_ordinal(dt): preserving hours, minutes, seconds and microseconds. Return value is a :func:`float`. """ - if isinstance(dt, (np.ndarray, Series)) and com.is_datetime64_ns_dtype(dt): + if isinstance(dt, (np.ndarray, Index, Series)) and com.is_datetime64_ns_dtype(dt): base = dates.epoch2num(dt.asi8 / 1.0E9) else: base = dates.date2num(dt) @@ -171,7 +171,9 @@ def try_parse(values): return values elif isinstance(values, compat.string_types): return try_parse(values) - elif isinstance(values, (list, tuple, np.ndarray)): + elif isinstance(values, (list, tuple, np.ndarray, Index)): + if isinstance(values, Index): + values = values.values if not isinstance(values, np.ndarray): values = com._asarray_tuplesafe(values) diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index fb87e1b570985..3ada26a7e5779 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -59,10 +59,10 @@ def f(self): def _join_i8_wrapper(joinf, with_indexers=True): @staticmethod def wrapper(left, right): - if isinstance(left, (np.ndarray, ABCSeries)): - left = left.view('i8', type=np.ndarray) - if isinstance(right, (np.ndarray, ABCSeries)): - right = right.view('i8', type=np.ndarray) + if isinstance(left, (np.ndarray, Index, ABCSeries)): + left = left.view('i8') + if isinstance(right, (np.ndarray, Index, ABCSeries)): + right = right.view('i8') results = joinf(left, right) if with_indexers: join_index, left_indexer, right_indexer = results @@ -86,9 +86,10 @@ def wrapper(self, other): else: if isinstance(other, list): other = DatetimeIndex(other) - elif not isinstance(other, (np.ndarray, ABCSeries)): + elif not isinstance(other, (np.ndarray, Index, ABCSeries)): other = _ensure_datetime64(other) result = func(other) + result = _values_from_object(result) if isinstance(other, Index): o_mask = other.values.view('i8') == tslib.iNaT @@ -101,7 +102,11 @@ def wrapper(self, other): mask = self.asi8 == tslib.iNaT if mask.any(): result[mask] = nat_result - return result.view(np.ndarray) + + # support of bool dtype indexers + if com.is_bool_dtype(result): + return result + return Index(result) return wrapper @@ -143,8 +148,9 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index): name : object Name to be stored in the index """ - _join_precedence = 10 + _typ = 'datetimeindex' + _join_precedence = 10 _inner_indexer = _join_i8_wrapper(_algos.inner_join_indexer_int64) _outer_indexer = _join_i8_wrapper(_algos.outer_join_indexer_int64) _left_indexer = _join_i8_wrapper(_algos.left_join_indexer_int64) @@ -167,17 +173,19 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index): tz = None offset = None _comparables = ['name','freqstr','tz'] + _attributes = ['name','freq','tz'] _allow_datetime_index_ops = True + _is_numeric_dtype = False def __new__(cls, data=None, freq=None, start=None, end=None, periods=None, copy=False, name=None, tz=None, verify_integrity=True, normalize=False, - closed=None, **kwds): + closed=None, **kwargs): - dayfirst = kwds.pop('dayfirst', None) - yearfirst = kwds.pop('yearfirst', None) - infer_dst = kwds.pop('infer_dst', False) + dayfirst = kwargs.pop('dayfirst', None) + yearfirst = kwargs.pop('yearfirst', None) + infer_dst = kwargs.pop('infer_dst', False) freq_infer = False if not isinstance(freq, DateOffset): @@ -205,7 +213,7 @@ def __new__(cls, data=None, tz=tz, normalize=normalize, closed=closed, infer_dst=infer_dst) - if not isinstance(data, (np.ndarray, ABCSeries)): + if not isinstance(data, (np.ndarray, Index, ABCSeries)): if np.isscalar(data): raise ValueError('DatetimeIndex() must be called with a ' 'collection of some kind, %s was passed' @@ -262,7 +270,7 @@ def __new__(cls, data=None, else: subarr = data.view(_NS_DTYPE) else: - if isinstance(data, ABCSeries): + if isinstance(data, (ABCSeries, Index)): values = data.values else: values = data @@ -302,10 +310,7 @@ def __new__(cls, data=None, subarr = subarr.view(_NS_DTYPE) - subarr = subarr.view(cls) - subarr.name = name - subarr.offset = freq - subarr.tz = tz + subarr = cls._simple_new(subarr, name=name, freq=freq, tz=tz) if verify_integrity and len(subarr) > 0: if freq is not None and not freq_infer: @@ -442,10 +447,7 @@ def _generate(cls, start, end, periods, name, offset, infer_dst=infer_dst) index = index.view(_NS_DTYPE) - index = index.view(cls) - index.name = name - index.offset = offset - index.tz = tz + index = cls._simple_new(index, name=name, freq=offset, tz=tz) if not left_closed: index = index[1:] @@ -474,15 +476,18 @@ def _local_timestamps(self): return result.take(reverse) @classmethod - def _simple_new(cls, values, name, freq=None, tz=None): + def _simple_new(cls, values, name=None, freq=None, tz=None): + if not getattr(values,'dtype',None): + values = np.array(values,copy=False) if values.dtype != _NS_DTYPE: values = com._ensure_int64(values).view(_NS_DTYPE) - result = values.view(cls) + result = object.__new__(cls) + result._data = values result.name = name result.offset = freq result.tz = tslib.maybe_get_tz(tz) - + result._reset_identity() return result @property @@ -517,7 +522,7 @@ def _cached_range(cls, start=None, end=None, periods=None, offset=None, arr = tools.to_datetime(list(xdr), box=False) - cachedRange = arr.view(DatetimeIndex) + cachedRange = DatetimeIndex._simple_new(arr) cachedRange.offset = offset cachedRange.tz = None cachedRange.name = None @@ -575,29 +580,37 @@ def _formatter_func(self): formatter = _get_format_datetime64(is_dates_only=self._is_dates_only) return lambda x: formatter(x, tz=self.tz) - def __reduce__(self): - """Necessary for making this object picklable""" - object_state = list(np.ndarray.__reduce__(self)) - subclass_state = self.name, self.offset, self.tz - object_state[2] = (object_state[2], subclass_state) - return tuple(object_state) - def __setstate__(self, state): """Necessary for making this object picklable""" - if len(state) == 2: - nd_state, own_state = state - self.name = own_state[0] - self.offset = own_state[1] - self.tz = own_state[2] - np.ndarray.__setstate__(self, nd_state) - - # provide numpy < 1.7 compat - if nd_state[2] == 'M8[us]': - new_state = np.ndarray.__reduce__(self.values.astype('M8[ns]')) - np.ndarray.__setstate__(self, new_state[2]) + if isinstance(state, dict): + super(DatetimeIndex, self).__setstate__(state) - else: # pragma: no cover - np.ndarray.__setstate__(self, state) + elif isinstance(state, tuple): + + # < 0.15 compat + if len(state) == 2: + nd_state, own_state = state + data = np.empty(nd_state[1], dtype=nd_state[2]) + np.ndarray.__setstate__(data, nd_state) + + self.name = own_state[0] + self.offset = own_state[1] + self.tz = own_state[2] + + # provide numpy < 1.7 compat + if nd_state[2] == 'M8[us]': + new_state = np.ndarray.__reduce__(data.astype('M8[ns]')) + np.ndarray.__setstate__(data, new_state[2]) + + else: # pragma: no cover + data = np.empty(state) + np.ndarray.__setstate__(data, state) + + self._data = data + + else: + raise Exception("invalid pickle state") + _unpickle_compat = __setstate__ def _add_delta(self, delta): if isinstance(delta, (Tick, timedelta)): @@ -662,7 +675,7 @@ def to_datetime(self, dayfirst=False): return self.copy() def groupby(self, f): - objs = self.asobject + objs = self.asobject.values return _algos.groupby_object(objs, f) def summary(self, name=None): @@ -982,7 +995,7 @@ def _wrap_joined_index(self, joined, other): if (isinstance(other, DatetimeIndex) and self.offset == other.offset and self._can_fast_union(other)): - joined = self._view_like(joined) + joined = self._shallow_copy(joined) joined.name = name return joined else: @@ -1044,7 +1057,7 @@ def _fast_union(self, other): loc = right.searchsorted(left_end, side='right') right_chunk = right.values[loc:] dates = com._concat_compat((left.values, right_chunk)) - return self._view_like(dates) + return self._shallow_copy(dates) else: return left else: @@ -1140,7 +1153,7 @@ def intersection(self, other): else: lslice = slice(*left.slice_locs(start, end)) left_chunk = left.values[lslice] - return self._view_like(left_chunk) + return self._shallow_copy(left_chunk) def _partial_date_slice(self, reso, parsed, use_lhs=True, use_rhs=True): @@ -1357,10 +1370,9 @@ def slice_locs(self, start=None, end=None): return Index.slice_locs(self, start, end) def __getitem__(self, key): - """Override numpy.ndarray's __getitem__ method to work as desired""" - arr_idx = self.view(np.ndarray) + getitem = self._data.__getitem__ if np.isscalar(key): - val = arr_idx[key] + val = getitem(key) return Timestamp(val, offset=self.offset, tz=self.tz) else: if com._is_bool_indexer(key): @@ -1377,7 +1389,7 @@ def __getitem__(self, key): else: new_offset = self.offset - result = arr_idx[key] + result = getitem(key) if result.ndim > 1: return result @@ -1388,18 +1400,20 @@ def __getitem__(self, key): def map(self, f): try: result = f(self) - if not isinstance(result, np.ndarray): + if not isinstance(result, (np.ndarray, Index)): raise TypeError return result except Exception: - return _algos.arrmap_object(self.asobject, f) + return _algos.arrmap_object(self.asobject.values, f) # alias to offset - @property - def freq(self): - """ return the frequency object if its set, otherwise None """ + def _get_freq(self): return self.offset + def _set_freq(self, value): + self.offset = value + freq = property(fget=_get_freq, fset=_set_freq, doc="get/set the frequncy of the Index") + @cache_readonly def inferred_freq(self): try: @@ -1443,14 +1457,14 @@ def _time(self): """ # can't call self.map() which tries to treat func as ufunc # and causes recursion warnings on python 2.6 - return _algos.arrmap_object(self.asobject, lambda x: x.time()) + return _algos.arrmap_object(self.asobject.values, lambda x: x.time()) @property def _date(self): """ Returns numpy array of datetime.date. The date part of the Timestamps. """ - return _algos.arrmap_object(self.asobject, lambda x: x.date()) + return _algos.arrmap_object(self.asobject.values, lambda x: x.date()) def normalize(self): @@ -1466,7 +1480,7 @@ def normalize(self): tz=self.tz) def searchsorted(self, key, side='left'): - if isinstance(key, np.ndarray): + if isinstance(key, (np.ndarray, Index)): key = np.array(key, dtype=_NS_DTYPE, copy=False) else: key = _to_m8(key, tz=self.tz) @@ -1609,13 +1623,6 @@ def delete(self, loc): new_dates = tslib.tz_convert(new_dates, 'UTC', self.tz) return DatetimeIndex(new_dates, name=self.name, freq=freq, tz=self.tz) - def _view_like(self, ndarray): - result = ndarray.view(type(self)) - result.offset = self.offset - result.tz = self.tz - result.name = self.name - return result - def tz_convert(self, tz): """ Convert tz-aware DatetimeIndex from one time zone to another (using pytz/dateutil) @@ -1639,7 +1646,7 @@ def tz_convert(self, tz): 'tz_localize to localize') # No conversion since timestamps are all UTC to begin with - return self._simple_new(self.values, self.name, self.offset, tz) + return self._shallow_copy(tz=tz) def tz_localize(self, tz, infer_dst=False): """ @@ -1669,7 +1676,7 @@ def tz_localize(self, tz, infer_dst=False): # Convert to UTC new_dates = tslib.tz_localize_to_utc(self.asi8, tz, infer_dst=infer_dst) new_dates = new_dates.view(_NS_DTYPE) - return self._simple_new(new_dates, self.name, self.offset, tz) + return self._shallow_copy(new_dates, tz=tz) def indexer_at_time(self, time, asof=False): """ @@ -1782,7 +1789,7 @@ def to_julian_date(self): self.microsecond/3600.0/1e+6 + self.nanosecond/3600.0/1e+9 )/24.0) - +DatetimeIndex._add_numeric_methods_disabled() def _generate_regular_range(start, end, periods, offset): if isinstance(offset, Tick): diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py index 7f865fd9aefa8..ddd1ee34f0798 100644 --- a/pandas/tseries/period.py +++ b/pandas/tseries/period.py @@ -60,12 +60,22 @@ class Period(PandasObject): minute : int, default 0 second : int, default 0 """ + _typ = 'periodindex' __slots__ = ['freq', 'ordinal'] _comparables = ['name','freqstr'] + @classmethod + def _from_ordinal(cls, ordinal, freq): + """ fast creation from an ordinal and freq that are already validated! """ + self = object.__new__(cls) + self.ordinal = ordinal + self.freq = freq + return self + def __init__(self, value=None, freq=None, ordinal=None, year=None, month=1, quarter=None, day=1, hour=0, minute=0, second=0): + # freq points to a tuple (base, mult); base is one of the defined # periods such as A, Q, etc. Every five minutes would be, e.g., # ('T', 5) but may be passed in as a string like '5T' @@ -563,6 +573,8 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): """ _box_scalars = True _allow_period_index_ops = True + _attributes = ['name','freq'] + _is_numeric_dtype = False __eq__ = _period_index_cmp('__eq__') __ne__ = _period_index_cmp('__ne__', nat_result=True) @@ -572,9 +584,7 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): __ge__ = _period_index_cmp('__ge__') def __new__(cls, data=None, ordinal=None, freq=None, start=None, end=None, - periods=None, copy=False, name=None, year=None, month=None, - quarter=None, day=None, hour=None, minute=None, second=None, - tz=None): + periods=None, copy=False, name=None, tz=None, **kwargs): freq = frequencies.get_standard_freq(freq) @@ -589,32 +599,24 @@ def __new__(cls, data=None, ordinal=None, freq=None, start=None, end=None, if ordinal is not None: data = np.asarray(ordinal, dtype=np.int64) else: - fields = [year, month, quarter, day, hour, minute, second] data, freq = cls._generate_range(start, end, periods, - freq, fields) + freq, kwargs) else: ordinal, freq = cls._from_arraylike(data, freq, tz) data = np.array(ordinal, dtype=np.int64, copy=False) - subarr = data.view(cls) - subarr.name = name - subarr.freq = freq - - return subarr + return cls._simple_new(data, name=name, freq=freq) @classmethod def _generate_range(cls, start, end, periods, freq, fields): - field_count = com._count_not_none(*fields) + field_count = len(fields) if com._count_not_none(start, end) > 0: if field_count > 0: raise ValueError('Can either instantiate from fields ' 'or endpoints, but not both') subarr, freq = _get_ordinal_range(start, end, periods, freq) elif field_count > 0: - y, mth, q, d, h, minute, s = fields - subarr, freq = _range_from_fields(year=y, month=mth, quarter=q, - day=d, hour=h, minute=minute, - second=s, freq=freq) + subarr, freq = _range_from_fields(freq=freq, **fields) else: raise ValueError('Not enough parameters to construct ' 'Period range') @@ -623,7 +625,8 @@ def _generate_range(cls, start, end, periods, freq, fields): @classmethod def _from_arraylike(cls, data, freq, tz): - if not isinstance(data, np.ndarray): + + if not isinstance(data, (np.ndarray, PeriodIndex, DatetimeIndex, Int64Index)): if np.isscalar(data) or isinstance(data, Period): raise ValueError('PeriodIndex() must be called with a ' 'collection of some kind, %s was passed' @@ -681,10 +684,12 @@ def _from_arraylike(cls, data, freq, tz): return data, freq @classmethod - def _simple_new(cls, values, name, freq=None, **kwargs): - result = values.view(cls) + def _simple_new(cls, values, name=None, freq=None, **kwargs): + result = object.__new__(cls) + result._data = values result.name = name result.freq = freq + result._reset_identity() return result @property @@ -704,7 +709,7 @@ def __contains__(self, key): @property def _box_func(self): - return lambda x: Period(ordinal=x, freq=self.freq) + return lambda x: Period._from_ordinal(ordinal=x, freq=self.freq) def asof_locs(self, where, mask): """ @@ -800,17 +805,15 @@ def to_datetime(self, dayfirst=False): def map(self, f): try: result = f(self) - if not isinstance(result, np.ndarray): + if not isinstance(result, (np.ndarray, Index)): raise TypeError return result except Exception: - return _algos.arrmap_object(self.asobject, f) + return _algos.arrmap_object(self.asobject.values, f) def _get_object_array(self): freq = self.freq - boxfunc = lambda x: Period(ordinal=x, freq=freq) - boxer = np.frompyfunc(boxfunc, 1, 1) - return boxer(self.values) + return np.array([ Period._from_ordinal(ordinal=x, freq=freq) for x in self.values], copy=False) def _mpl_repr(self): # how to represent ourselves to matplotlib @@ -823,6 +826,13 @@ def equals(self, other): if self.is_(other): return True + if (not hasattr(other, 'inferred_type') or + other.inferred_type != 'int64'): + try: + other = PeriodIndex(other) + except: + return False + return np.array_equal(self.asi8, other.asi8) def to_timestamp(self, freq=None, how='start'): @@ -1042,21 +1052,19 @@ def _wrap_union_result(self, other, result): def _apply_meta(self, rawarr): if not isinstance(rawarr, PeriodIndex): - rawarr = rawarr.view(PeriodIndex) - rawarr.freq = self.freq + rawarr = PeriodIndex(rawarr, freq=self.freq) return rawarr def __getitem__(self, key): - """Override numpy.ndarray's __getitem__ method to work as desired""" - arr_idx = self.view(np.ndarray) + getitem = self._data.__getitem__ if np.isscalar(key): - val = arr_idx[key] + val = getitem(key) return Period(ordinal=val, freq=self.freq) else: if com._is_bool_indexer(key): key = np.asarray(key) - result = arr_idx[key] + result = getitem(key) if result.ndim > 1: # MPL kludge # values = np.asarray(list(values), dtype=object) @@ -1129,7 +1137,7 @@ def append(self, other): if isinstance(to_concat[0], PeriodIndex): if len(set([x.freq for x in to_concat])) > 1: # box - to_concat = [x.asobject for x in to_concat] + to_concat = [x.asobject.values for x in to_concat] else: cat_values = np.concatenate([x.values for x in to_concat]) return PeriodIndex(cat_values, freq=self.freq, name=name) @@ -1138,26 +1146,35 @@ def append(self, other): for x in to_concat] return Index(com._concat_compat(to_concat), name=name) - def __reduce__(self): - """Necessary for making this object picklable""" - object_state = list(np.ndarray.__reduce__(self)) - subclass_state = (self.name, self.freq) - object_state[2] = (object_state[2], subclass_state) - return tuple(object_state) - def __setstate__(self, state): """Necessary for making this object picklable""" - if len(state) == 2: - nd_state, own_state = state - np.ndarray.__setstate__(self, nd_state) - self.name = own_state[0] - try: # backcompat - self.freq = own_state[1] - except: - pass - else: # pragma: no cover - np.ndarray.__setstate__(self, state) + if isinstance(state, dict): + super(PeriodIndex, self).__setstate__(state) + + elif isinstance(state, tuple): + + # < 0.15 compat + if len(state) == 2: + nd_state, own_state = state + data = np.empty(nd_state[1], dtype=nd_state[2]) + np.ndarray.__setstate__(data, nd_state) + + try: # backcompat + self.freq = own_state[1] + except: + pass + + else: # pragma: no cover + data = np.empty(state) + np.ndarray.__setstate__(self, state) + + self._data = data + + else: + raise Exception("invalid pickle state") + _unpickle_compat = __setstate__ +PeriodIndex._add_numeric_methods_disabled() def _get_ordinal_range(start, end, periods, freq): if com._count_not_none(start, end, periods) < 2: diff --git a/pandas/tseries/plotting.py b/pandas/tseries/plotting.py index b95553f87ec6b..899d2bfdc9c76 100644 --- a/pandas/tseries/plotting.py +++ b/pandas/tseries/plotting.py @@ -61,7 +61,7 @@ def tsplot(series, plotf, **kwargs): if not hasattr(ax, '_plot_data'): ax._plot_data = [] ax._plot_data.append((series, plotf, kwargs)) - lines = plotf(ax, series.index, series.values, **kwargs) + lines = plotf(ax, series.index._mpl_repr(), series.values, **kwargs) # set date formatter, locators and rescale limits format_dateaxis(ax, ax.freq) @@ -152,7 +152,7 @@ def _replot_ax(ax, freq, kwargs): idx = series.index.asfreq(freq, how='S') series.index = idx ax._plot_data.append(series) - lines.append(plotf(ax, series.index, series.values, **kwds)[0]) + lines.append(plotf(ax, series.index._mpl_repr(), series.values, **kwds)[0]) labels.append(com.pprint_thing(series.name)) return lines, labels diff --git a/pandas/tseries/tests/test_converter.py b/pandas/tseries/tests/test_converter.py index 902b9cb549e32..a1b873e1c0bea 100644 --- a/pandas/tseries/tests/test_converter.py +++ b/pandas/tseries/tests/test_converter.py @@ -84,8 +84,8 @@ def _assert_less(ts1, ts2): if not val1 < val2: raise AssertionError('{0} is not less than {1}.'.format(val1, val2)) - # Matplotlib's time representation using floats cannot distinguish intervals smaller - # than ~10 microsecond in the common range of years. + # Matplotlib's time representation using floats cannot distinguish intervals smaller + # than ~10 microsecond in the common range of years. ts = Timestamp('2012-1-1') _assert_less(ts, ts + Second()) _assert_less(ts, ts + Milli()) diff --git a/pandas/tseries/tests/test_daterange.py b/pandas/tseries/tests/test_daterange.py index 7b0bfa98690e2..b109f6585092a 100644 --- a/pandas/tseries/tests/test_daterange.py +++ b/pandas/tseries/tests/test_daterange.py @@ -1,6 +1,5 @@ from datetime import datetime from pandas.compat import range -import pickle import nose import sys import numpy as np @@ -168,9 +167,7 @@ def test_shift(self): self.assertEqual(shifted[0], rng[0] + datetools.bday) def test_pickle_unpickle(self): - pickled = pickle.dumps(self.rng) - unpickled = pickle.loads(pickled) - + unpickled = self.round_trip_pickle(self.rng) self.assertIsNotNone(unpickled.offset) def test_union(self): @@ -561,9 +558,7 @@ def test_shift(self): self.assertEqual(shifted[0], rng[0] + datetools.cday) def test_pickle_unpickle(self): - pickled = pickle.dumps(self.rng) - unpickled = pickle.loads(pickled) - + unpickled = self.round_trip_pickle(self.rng) self.assertIsNotNone(unpickled.offset) def test_union(self): diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py index b9d4dd80438ef..b7abedbafa7b0 100644 --- a/pandas/tseries/tests/test_period.py +++ b/pandas/tseries/tests/test_period.py @@ -2052,7 +2052,7 @@ def test_range_slice_outofbounds(self): for idx in [didx, pidx]: df = DataFrame(dict(units=[100 + i for i in range(10)]), index=idx) - empty = DataFrame(index=DatetimeIndex([], freq='D'), columns=['units']) + empty = DataFrame(index=idx.__class__([], freq='D'), columns=['units']) tm.assert_frame_equal(df['2013/09/01':'2013/09/30'], empty) tm.assert_frame_equal(df['2013/09/30':'2013/10/02'], df.iloc[:2]) @@ -2408,7 +2408,7 @@ def test_pickle_freq(self): # GH2891 import pickle prng = period_range('1/1/2011', '1/1/2012', freq='M') - new_prng = pickle.loads(pickle.dumps(prng)) + new_prng = self.round_trip_pickle(prng) self.assertEqual(new_prng.freq,'M') def test_slice_keep_name(self): diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py index b52dca76f2c77..6b34ae0eb9384 100644 --- a/pandas/tseries/tests/test_plotting.py +++ b/pandas/tseries/tests/test_plotting.py @@ -298,7 +298,7 @@ def test_dataframe(self): bts = DataFrame({'a': tm.makeTimeSeries()}) ax = bts.plot() idx = ax.get_lines()[0].get_xdata() - assert_array_equal(bts.index.to_period(), idx) + assert_array_equal(bts.index.to_period(), PeriodIndex(idx)) @slow def test_axis_limits(self): @@ -605,8 +605,8 @@ def test_mixed_freq_regular_first(self): ax = s1.plot() ax2 = s2.plot(style='g') lines = ax2.get_lines() - idx1 = lines[0].get_xdata() - idx2 = lines[1].get_xdata() + idx1 = PeriodIndex(lines[0].get_xdata()) + idx2 = PeriodIndex(lines[1].get_xdata()) self.assertTrue(idx1.equals(s1.index.to_period('B'))) self.assertTrue(idx2.equals(s2.index.to_period('B'))) left, right = ax2.get_xlim() @@ -881,9 +881,9 @@ def test_secondary_upsample(self): low.plot() ax = high.plot(secondary_y=True) for l in ax.get_lines(): - self.assertEqual(l.get_xdata().freq, 'D') + self.assertEqual(PeriodIndex(l.get_xdata()).freq, 'D') for l in ax.right_ax.get_lines(): - self.assertEqual(l.get_xdata().freq, 'D') + self.assertEqual(PeriodIndex(l.get_xdata()).freq, 'D') @slow def test_secondary_legend(self): diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 6dbf095189d36..9487949adf23a 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -27,7 +27,7 @@ import pandas.index as _index -from pandas.compat import range, long, StringIO, lrange, lmap, zip, product +from pandas.compat import range, long, StringIO, lrange, lmap, zip, product, PY3_2 from numpy.random import rand from numpy.testing import assert_array_equal from pandas.util.testing import assert_frame_equal @@ -871,11 +871,11 @@ def test_string_na_nat_conversion(self): result2 = to_datetime(strings) tm.assert_isinstance(result2, DatetimeIndex) - assert_almost_equal(result, result2) + self.assert_numpy_array_equal(result, result2) malformed = np.array(['1/100/2000', np.nan], dtype=object) result = to_datetime(malformed) - assert_almost_equal(result, malformed) + self.assert_numpy_array_equal(result, malformed) self.assertRaises(ValueError, to_datetime, malformed, errors='raise') @@ -2058,18 +2058,15 @@ def test_period_resample_with_local_timezone_dateutil(self): def test_pickle(self): #GH4606 - from pandas.compat import cPickle - import pickle - for pick in [pickle, cPickle]: - p = pick.loads(pick.dumps(NaT)) - self.assertTrue(p is NaT) + p = self.round_trip_pickle(NaT) + self.assertTrue(p is NaT) - idx = pd.to_datetime(['2013-01-01', NaT, '2014-01-06']) - idx_p = pick.loads(pick.dumps(idx)) - self.assertTrue(idx_p[0] == idx[0]) - self.assertTrue(idx_p[1] is NaT) - self.assertTrue(idx_p[2] == idx[2]) + idx = pd.to_datetime(['2013-01-01', NaT, '2014-01-06']) + idx_p = self.round_trip_pickle(idx) + self.assertTrue(idx_p[0] == idx[0]) + self.assertTrue(idx_p[1] is NaT) + self.assertTrue(idx_p[2] == idx[2]) def _simple_ts(start, end, freq='D'): @@ -2212,6 +2209,9 @@ def test_comparisons_coverage(self): self.assert_numpy_array_equal(result, exp) def test_comparisons_nat(self): + if PY3_2: + raise nose.SkipTest('nat comparisons on 3.2 broken') + fidx1 = pd.Index([1.0, np.nan, 3.0, np.nan, 5.0, 7.0]) fidx2 = pd.Index([2.0, 3.0, np.nan, np.nan, 6.0, 7.0]) @@ -2233,9 +2233,11 @@ def test_comparisons_nat(self): # Check pd.NaT is handles as the same as np.nan for idx1, idx2 in cases: + result = idx1 < idx2 expected = np.array([True, False, False, False, True, False]) self.assert_numpy_array_equal(result, expected) + result = idx2 > idx1 expected = np.array([True, False, False, False, True, False]) self.assert_numpy_array_equal(result, expected) @@ -2243,6 +2245,7 @@ def test_comparisons_nat(self): result = idx1 <= idx2 expected = np.array([True, False, False, False, True, True]) self.assert_numpy_array_equal(result, expected) + result = idx2 >= idx1 expected = np.array([True, False, False, False, True, True]) self.assert_numpy_array_equal(result, expected) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 13f432d5cea2a..42048ec9877fa 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -98,6 +98,13 @@ def assert_numpy_array_equal(self, np_array, assert_equal): return raise AssertionError('{0} is not equal to {1}.'.format(np_array, assert_equal)) + def round_trip_pickle(self, obj, path=None): + if path is None: + path = u('__%s__.pickle' % rands(10)) + with ensure_clean(path) as path: + pd.to_pickle(obj, path) + return pd.read_pickle(path) + def assert_numpy_array_equivalent(self, np_array, assert_equal): """Checks that 'np_array' is equivalent to 'assert_equal'
make `Index` now subclass `PandasObject/IndexOpsMixin` rather than `ndarray` should allow much easier new Index classes (e.g. #7640) This doesn't change the public API at all, and provides compat closes #5080 back compat for pickles is now way simpler ToDo: - docs - [x] release note - [x] warnings in io.rst about this change - [x] fixes `.repeat` on MultiIndex (broken in master) - [x] minor API compat issue with comparisons of `DatetimeIndex` with `NaT` vs ndarrays - [x] merge with searchsorted issues/PR ( #6712, #7447, #6469) - [x] tests fixed (FIXMES), just a few left - [x] perf - [x] json completely broken ATM - [x] #7796 FIXME (PeriodIndex not supported in HDF), not really a big deal - [x] #7439 since `Index` now doesn't have implicit ops (aside from `__sub__/__add__`, these need to be added in (e.g. `__mul__,__div__,__truediv__`). - [x] bool(Index/MultiIndex) : https://github.com/pydata/pandas/issues/7897 (will address this later) closes #5155 (perf fix for Period creation), slight increase on the plotting because of the the plottling routines holding array of Periods (rather than PeriodIndex). ``` ------------------------------------------------------------------------------- Test name | head[ms] | base[ms] | ratio | ------------------------------------------------------------------------------- period_setitem | 16.2210 | 122.9340 | 0.1319 | timeseries_iter_periodindex | 1197.7839 | 6906.1464 | 0.1734 | timeseries_iter_periodindex_preexit | 12.4850 | 69.8563 | 0.1787 | timeseries_period_downsample_mean | 11.2850 | 11.1457 | 1.0125 | plot_timeseries_period | 107.6056 | 86.5277 | 1.2436 | ```
https://api.github.com/repos/pandas-dev/pandas/pulls/7891
2014-07-31T17:15:09Z
2014-08-07T11:34:54Z
2014-08-07T11:34:54Z
2014-08-07T12:10:59Z
PERF: groupby / frame apply optimization
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 9659d4c3bd6e0..eabe1b43004df 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -635,11 +635,11 @@ def apply(self, func, *args, **kwargs): @wraps(func) def f(g): - # ignore SettingWithCopy here in case the user mutates - with option_context('mode.chained_assignment',None): - return func(g, *args, **kwargs) + return func(g, *args, **kwargs) - return self._python_apply_general(f) + # ignore SettingWithCopy here in case the user mutates + with option_context('mode.chained_assignment',None): + return self._python_apply_general(f) def _python_apply_general(self, f): keys, values, mutated = self.grouper.apply(f, self._selected_obj, diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index 15ebeba941ccd..e798961ea7bf9 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -445,7 +445,10 @@ def test_fred(self): end = datetime(2013, 1, 27) received = web.DataReader("GDP", "fred", start, end)['GDP'].tail(1)[0] - self.assertEqual(int(received), 16535) + + # < 7/30/14 16535 was returned + #self.assertEqual(int(received), 16535) + self.assertEqual(int(received), 16502) self.assertRaises(Exception, web.DataReader, "NON EXISTENT SERIES", 'fred', start, end)
``` ------------------------------------------------------------------------------- Test name | head[ms] | base[ms] | ratio | ------------------------------------------------------------------------------- groupby_frame_apply_overhead | 9.1400 | 70.3743 | 0.1299 | groupby_frame_apply | 43.5640 | 186.6427 | 0.2334 | groupby_apply_dict_return | 39.6016 | 80.1926 | 0.4938 | ```
https://api.github.com/repos/pandas-dev/pandas/pulls/7881
2014-07-30T16:50:51Z
2014-07-30T17:56:01Z
2014-07-30T17:56:01Z
2014-07-30T17:56:01Z
ENH add level argument to set_names, set_levels and set_labels (GH7792)
diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index 837e3b386f3d0..023c200e271ab 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -2162,6 +2162,17 @@ you can specify ``inplace=True`` to have the data change in place. ind.name = "bob" ind +.. versionadded:: 0.15.0 + +``set_names``, ``set_levels``, and ``set_labels`` also take an optional +`level`` argument + +.. ipython:: python + + index + index.levels[1] + index.set_levels(["a", "b"], level=1) + Adding an index to an existing DataFrame ---------------------------------------- diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index 9279d8b0288c4..2e5ec8e2f4193 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -35,6 +35,16 @@ API changes levels aren't all level names or all level numbers. See :ref:`Reshaping by stacking and unstacking <reshaping.stack_multiple>`. +- :func:`set_names`, :func:`set_labels`, and :func:`set_levels` methods now take an optional ``level`` keyword argument to all modification of specific level(s) of a MultiIndex. Additionally :func:`set_names` now accepts a scalar string value when operating on an ``Index`` or on a specific level of a ``MultiIndex`` (:issue:`7792`) + + .. ipython:: python + + idx = pandas.MultiIndex.from_product([['a'], range(3), list("pqr")], names=['foo', 'bar', 'baz']) + idx.set_names('qux', level=0) + idx.set_names(['qux','baz'], level=[0,1]) + idx.set_levels(['a','b','c'], level='bar') + idx.set_levels([['a','b','c'],[1,2,3]], level=[1,2]) + - Raise a ``ValueError`` in ``df.to_hdf`` with 'fixed' format, if ``df`` has non-unique columns as the resulting file will be broken (:issue:`7761`) - :func:`rolling_min`, :func:`rolling_max`, :func:`rolling_cov`, and :func:`rolling_corr` diff --git a/pandas/core/index.py b/pandas/core/index.py index 81602d5240a08..8c43511866e9a 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -362,7 +362,7 @@ def nlevels(self): def _get_names(self): return FrozenList((self.name,)) - def _set_names(self, values): + def _set_names(self, values, level=None): if len(values) != 1: raise ValueError('Length of new names must be 1, got %d' % len(values)) @@ -370,28 +370,61 @@ def _set_names(self, values): names = property(fset=_set_names, fget=_get_names) - def set_names(self, names, inplace=False): + def set_names(self, names, level=None, inplace=False): """ Set new names on index. Defaults to returning new index. Parameters ---------- - names : sequence - names to set + names : str or sequence + name(s) to set + level : int or level name, or sequence of int / level names (default None) + If the index is a MultiIndex (hierarchical), level(s) to set (None for all levels) + Otherwise level must be None inplace : bool if True, mutates in place Returns ------- new index (of same type and class...etc) [if inplace, returns None] + + Examples + -------- + >>> Index([1, 2, 3, 4]).set_names('foo') + Int64Index([1, 2, 3, 4], dtype='int64') + >>> Index([1, 2, 3, 4]).set_names(['foo']) + Int64Index([1, 2, 3, 4], dtype='int64') + >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), + (2, u'one'), (2, u'two')], + names=['foo', 'bar']) + >>> idx.set_names(['baz', 'quz']) + MultiIndex(levels=[[1, 2], [u'one', u'two']], + labels=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=[u'baz', u'quz']) + >>> idx.set_names('baz', level=0) + MultiIndex(levels=[[1, 2], [u'one', u'two']], + labels=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=[u'baz', u'bar']) """ - if not com.is_list_like(names): + if level is not None and self.nlevels == 1: + raise ValueError('Level must be None for non-MultiIndex') + + if level is not None and not com.is_list_like(level) and com.is_list_like(names): + raise TypeError("Names must be a string") + + if not com.is_list_like(names) and level is None and self.nlevels > 1: raise TypeError("Must pass list-like as `names`.") + + if not com.is_list_like(names): + names = [names] + if level is not None and not com.is_list_like(level): + level = [level] + if inplace: idx = self else: idx = self._shallow_copy() - idx._set_names(names) + idx._set_names(names, level=level) if not inplace: return idx @@ -2218,19 +2251,30 @@ def _verify_integrity(self): def _get_levels(self): return self._levels - def _set_levels(self, levels, copy=False, validate=True, + def _set_levels(self, levels, level=None, copy=False, validate=True, verify_integrity=False): # This is NOT part of the levels property because it should be # externally not allowed to set levels. User beware if you change # _levels directly if validate and len(levels) == 0: raise ValueError('Must set non-zero number of levels.') - if validate and len(levels) != len(self._labels): - raise ValueError('Length of levels must match length of labels.') - levels = FrozenList(_ensure_index(lev, copy=copy)._shallow_copy() - for lev in levels) + if validate and level is None and len(levels) != self.nlevels: + raise ValueError('Length of levels must match number of levels.') + if validate and level is not None and len(levels) != len(level): + raise ValueError('Length of levels must match length of level.') + + if level is None: + new_levels = FrozenList(_ensure_index(lev, copy=copy)._shallow_copy() + for lev in levels) + else: + level = [self._get_level_number(l) for l in level] + new_levels = list(self._levels) + for l, v in zip(level, levels): + new_levels[l] = _ensure_index(v, copy=copy)._shallow_copy() + new_levels = FrozenList(new_levels) + names = self.names - self._levels = levels + self._levels = new_levels if any(names): self._set_names(names) @@ -2240,15 +2284,17 @@ def _set_levels(self, levels, copy=False, validate=True, if verify_integrity: self._verify_integrity() - def set_levels(self, levels, inplace=False, verify_integrity=True): + def set_levels(self, levels, level=None, inplace=False, verify_integrity=True): """ Set new levels on MultiIndex. Defaults to returning new index. Parameters ---------- - levels : sequence - new levels to apply + levels : sequence or list of sequence + new level(s) to apply + level : int or level name, or sequence of int / level names (default None) + level(s) to set (None for all levels) inplace : bool if True, mutates in place verify_integrity : bool (default True) @@ -2257,15 +2303,47 @@ def set_levels(self, levels, inplace=False, verify_integrity=True): Returns ------- new index (of same type and class...etc) - """ - if not com.is_list_like(levels) or not com.is_list_like(levels[0]): - raise TypeError("Levels must be list of lists-like") + + + Examples + -------- + >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), + (2, u'one'), (2, u'two')], + names=['foo', 'bar']) + >>> idx.set_levels([['a','b'], [1,2]]) + MultiIndex(levels=[[u'a', u'b'], [1, 2]], + labels=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=[u'foo', u'bar']) + >>> idx.set_levels(['a','b'], level=0) + MultiIndex(levels=[[u'a', u'b'], [u'one', u'two']], + labels=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=[u'foo', u'bar']) + >>> idx.set_levels(['a','b'], level='bar') + MultiIndex(levels=[[1, 2], [u'a', u'b']], + labels=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=[u'foo', u'bar']) + >>> idx.set_levels([['a','b'], [1,2]], level=[0,1]) + MultiIndex(levels=[[u'a', u'b'], [1, 2]], + labels=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=[u'foo', u'bar']) + """ + if level is not None and not com.is_list_like(level): + if not com.is_list_like(levels): + raise TypeError("Levels must be list-like") + if com.is_list_like(levels[0]): + raise TypeError("Levels must be list-like") + level = [level] + levels = [levels] + elif level is None or com.is_list_like(level): + if not com.is_list_like(levels) or not com.is_list_like(levels[0]): + raise TypeError("Levels must be list of lists-like") + if inplace: idx = self else: idx = self._shallow_copy() idx._reset_identity() - idx._set_levels(levels, validate=True, + idx._set_levels(levels, level=level, validate=True, verify_integrity=verify_integrity) if not inplace: return idx @@ -2280,27 +2358,42 @@ def set_levels(self, levels, inplace=False, verify_integrity=True): def _get_labels(self): return self._labels - def _set_labels(self, labels, copy=False, validate=True, + def _set_labels(self, labels, level=None, copy=False, validate=True, verify_integrity=False): - if validate and len(labels) != self.nlevels: - raise ValueError("Length of labels must match length of levels") - self._labels = FrozenList( - _ensure_frozen(labs, copy=copy)._shallow_copy() for labs in labels) + + if validate and level is None and len(labels) != self.nlevels: + raise ValueError("Length of labels must match number of levels") + if validate and level is not None and len(labels) != len(level): + raise ValueError('Length of labels must match length of levels.') + + if level is None: + new_labels = FrozenList(_ensure_frozen(v, copy=copy)._shallow_copy() + for v in labels) + else: + level = [self._get_level_number(l) for l in level] + new_labels = list(self._labels) + for l, v in zip(level, labels): + new_labels[l] = _ensure_frozen(v, copy=copy)._shallow_copy() + new_labels = FrozenList(new_labels) + + self._labels = new_labels self._tuples = None self._reset_cache() if verify_integrity: self._verify_integrity() - def set_labels(self, labels, inplace=False, verify_integrity=True): + def set_labels(self, labels, level=None, inplace=False, verify_integrity=True): """ Set new labels on MultiIndex. Defaults to returning new index. Parameters ---------- - labels : sequence of arrays + labels : sequence or list of sequence new labels to apply + level : int or level name, or sequence of int / level names (default None) + level(s) to set (None for all levels) inplace : bool if True, mutates in place verify_integrity : bool (default True) @@ -2309,15 +2402,46 @@ def set_labels(self, labels, inplace=False, verify_integrity=True): Returns ------- new index (of same type and class...etc) - """ - if not com.is_list_like(labels) or not com.is_list_like(labels[0]): - raise TypeError("Labels must be list of lists-like") + + Examples + -------- + >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), + (2, u'one'), (2, u'two')], + names=['foo', 'bar']) + >>> idx.set_labels([[1,0,1,0], [0,0,1,1]]) + MultiIndex(levels=[[1, 2], [u'one', u'two']], + labels=[[1, 0, 1, 0], [0, 0, 1, 1]], + names=[u'foo', u'bar']) + >>> idx.set_labels([1,0,1,0], level=0) + MultiIndex(levels=[[1, 2], [u'one', u'two']], + labels=[[1, 0, 1, 0], [0, 1, 0, 1]], + names=[u'foo', u'bar']) + >>> idx.set_labels([0,0,1,1], level='bar') + MultiIndex(levels=[[1, 2], [u'one', u'two']], + labels=[[0, 0, 1, 1], [0, 0, 1, 1]], + names=[u'foo', u'bar']) + >>> idx.set_labels([[1,0,1,0], [0,0,1,1]], level=[0,1]) + MultiIndex(levels=[[1, 2], [u'one', u'two']], + labels=[[1, 0, 1, 0], [0, 0, 1, 1]], + names=[u'foo', u'bar']) + """ + if level is not None and not com.is_list_like(level): + if not com.is_list_like(labels): + raise TypeError("Labels must be list-like") + if com.is_list_like(labels[0]): + raise TypeError("Labels must be list-like") + level = [level] + labels = [labels] + elif level is None or com.is_list_like(level): + if not com.is_list_like(labels) or not com.is_list_like(labels[0]): + raise TypeError("Labels must be list of lists-like") + if inplace: idx = self else: idx = self._shallow_copy() idx._reset_identity() - idx._set_labels(labels, verify_integrity=verify_integrity) + idx._set_labels(labels, level=level, verify_integrity=verify_integrity) if not inplace: return idx @@ -2434,18 +2558,30 @@ def __len__(self): def _get_names(self): return FrozenList(level.name for level in self.levels) - def _set_names(self, values, validate=True): + def _set_names(self, names, level=None, validate=True): """ sets names on levels. WARNING: mutates! Note that you generally want to set this *after* changing levels, so - that it only acts on copies""" - values = list(values) - if validate and len(values) != self.nlevels: - raise ValueError('Length of names must match length of levels') + that it only acts on copies + """ + + names = list(names) + + if validate and level is not None and len(names) != len(level): + raise ValueError('Length of names must match length of level.') + if validate and level is None and len(names) != self.nlevels: + raise ValueError( + 'Length of names must match number of levels in MultiIndex.') + + if level is None: + level = range(self.nlevels) + else: + level = [self._get_level_number(l) for l in level] + # set the name - for name, level in zip(values, self.levels): - level.rename(name, inplace=True) + for l, name in zip(level, names): + self.levels[l].rename(name, inplace=True) names = property( fset=_set_names, fget=_get_names, doc="Names of levels in MultiIndex") diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index a8486beb57042..8b1f6ce3e7f45 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -70,9 +70,11 @@ def test_set_name_methods(self): self.assertIsNone(res) self.assertEqual(ind.name, new_name) self.assertEqual(ind.names, [new_name]) - with assertRaisesRegexp(TypeError, "list-like"): - # should still fail even if it would be the right length - ind.set_names("a") + #with assertRaisesRegexp(TypeError, "list-like"): + # # should still fail even if it would be the right length + # ind.set_names("a") + with assertRaisesRegexp(ValueError, "Level must be None"): + ind.set_names("a", level=0) # rename in place just leaves tuples and other containers alone name = ('A', 'B') ind = self.intIndex @@ -1509,15 +1511,30 @@ def test_set_names_and_rename(self): self.assertIsNone(res) self.assertEqual(ind.names, new_names2) - def test_set_levels_and_set_labels(self): + # set names for specific level (# GH7792) + ind = self.index.set_names(new_names[0], level=0) + self.assertEqual(self.index.names, self.index_names) + self.assertEqual(ind.names, [new_names[0], self.index_names[1]]) + + res = ind.set_names(new_names2[0], level=0, inplace=True) + self.assertIsNone(res) + self.assertEqual(ind.names, [new_names2[0], self.index_names[1]]) + + # set names for multiple levels + ind = self.index.set_names(new_names, level=[0, 1]) + self.assertEqual(self.index.names, self.index_names) + self.assertEqual(ind.names, new_names) + + res = ind.set_names(new_names2, level=[0, 1], inplace=True) + self.assertIsNone(res) + self.assertEqual(ind.names, new_names2) + + + def test_set_levels(self): # side note - you probably wouldn't want to use levels and labels # directly like this - but it is possible. levels, labels = self.index.levels, self.index.labels new_levels = [[lev + 'a' for lev in level] for level in levels] - major_labels, minor_labels = labels - major_labels = [(x + 1) % 3 for x in major_labels] - minor_labels = [(x + 1) % 1 for x in minor_labels] - new_labels = [major_labels, minor_labels] def assert_matching(actual, expected): # avoid specifying internal representation @@ -1539,6 +1556,58 @@ def assert_matching(actual, expected): self.assertIsNone(inplace_return) assert_matching(ind2.levels, new_levels) + # level changing specific level [w/o mutation] + ind2 = self.index.set_levels(new_levels[0], level=0) + assert_matching(ind2.levels, [new_levels[0], levels[1]]) + assert_matching(self.index.levels, levels) + + ind2 = self.index.set_levels(new_levels[1], level=1) + assert_matching(ind2.levels, [levels[0], new_levels[1]]) + assert_matching(self.index.levels, levels) + + # level changing multiple levels [w/o mutation] + ind2 = self.index.set_levels(new_levels, level=[0, 1]) + assert_matching(ind2.levels, new_levels) + assert_matching(self.index.levels, levels) + + # level changing specific level [w/ mutation] + ind2 = self.index.copy() + inplace_return = ind2.set_levels(new_levels[0], level=0, inplace=True) + self.assertIsNone(inplace_return) + assert_matching(ind2.levels, [new_levels[0], levels[1]]) + assert_matching(self.index.levels, levels) + + ind2 = self.index.copy() + inplace_return = ind2.set_levels(new_levels[1], level=1, inplace=True) + self.assertIsNone(inplace_return) + assert_matching(ind2.levels, [levels[0], new_levels[1]]) + assert_matching(self.index.levels, levels) + + # level changing multiple levels [w/ mutation] + ind2 = self.index.copy() + inplace_return = ind2.set_levels(new_levels, level=[0, 1], inplace=True) + self.assertIsNone(inplace_return) + assert_matching(ind2.levels, new_levels) + assert_matching(self.index.levels, levels) + + def test_set_labels(self): + # side note - you probably wouldn't want to use levels and labels + # directly like this - but it is possible. + levels, labels = self.index.levels, self.index.labels + major_labels, minor_labels = labels + major_labels = [(x + 1) % 3 for x in major_labels] + minor_labels = [(x + 1) % 1 for x in minor_labels] + new_labels = [major_labels, minor_labels] + + def assert_matching(actual, expected): + # avoid specifying internal representation + # as much as possible + self.assertEqual(len(actual), len(expected)) + for act, exp in zip(actual, expected): + act = np.asarray(act) + exp = np.asarray(exp) + assert_almost_equal(act, exp) + # label changing [w/o mutation] ind2 = self.index.set_labels(new_labels) assert_matching(ind2.labels, new_labels) @@ -1550,6 +1619,40 @@ def assert_matching(actual, expected): self.assertIsNone(inplace_return) assert_matching(ind2.labels, new_labels) + # label changing specific level [w/o mutation] + ind2 = self.index.set_labels(new_labels[0], level=0) + assert_matching(ind2.labels, [new_labels[0], labels[1]]) + assert_matching(self.index.labels, labels) + + ind2 = self.index.set_labels(new_labels[1], level=1) + assert_matching(ind2.labels, [labels[0], new_labels[1]]) + assert_matching(self.index.labels, labels) + + # label changing multiple levels [w/o mutation] + ind2 = self.index.set_labels(new_labels, level=[0, 1]) + assert_matching(ind2.labels, new_labels) + assert_matching(self.index.labels, labels) + + # label changing specific level [w/ mutation] + ind2 = self.index.copy() + inplace_return = ind2.set_labels(new_labels[0], level=0, inplace=True) + self.assertIsNone(inplace_return) + assert_matching(ind2.labels, [new_labels[0], labels[1]]) + assert_matching(self.index.labels, labels) + + ind2 = self.index.copy() + inplace_return = ind2.set_labels(new_labels[1], level=1, inplace=True) + self.assertIsNone(inplace_return) + assert_matching(ind2.labels, [labels[0], new_labels[1]]) + assert_matching(self.index.labels, labels) + + # label changing multiple levels [w/ mutation] + ind2 = self.index.copy() + inplace_return = ind2.set_labels(new_labels, level=[0, 1], inplace=True) + self.assertIsNone(inplace_return) + assert_matching(ind2.labels, new_labels) + assert_matching(self.index.labels, labels) + def test_set_levels_labels_names_bad_input(self): levels, labels = self.index.levels, self.index.labels names = self.index.names @@ -1575,6 +1678,27 @@ def test_set_levels_labels_names_bad_input(self): with tm.assertRaisesRegexp(TypeError, 'list-like'): self.index.set_names(names[0]) + # should have equal lengths + with tm.assertRaisesRegexp(TypeError, 'list of lists-like'): + self.index.set_levels(levels[0], level=[0, 1]) + + with tm.assertRaisesRegexp(TypeError, 'list-like'): + self.index.set_levels(levels, level=0) + + # should have equal lengths + with tm.assertRaisesRegexp(TypeError, 'list of lists-like'): + self.index.set_labels(labels[0], level=[0, 1]) + + with tm.assertRaisesRegexp(TypeError, 'list-like'): + self.index.set_labels(labels, level=0) + + # should have equal lengths + with tm.assertRaisesRegexp(ValueError, 'Length of names'): + self.index.set_names(names[0], level=[0, 1]) + + with tm.assertRaisesRegexp(TypeError, 'string'): + self.index.set_names(names, level=0) + def test_metadata_immutable(self): levels, labels = self.index.levels, self.index.labels # shouldn't be able to set at either the top level or base level
Closes #7792 New `level` argument: ``` set_names(self, names, level=None, inplace=False) set_levels(self, levels, level=None, inplace=False, verify_integrity=True) set_labels(self, labels, level=None, inplace=False, verify_integrity=True) ``` e.g. set_names('foo',level=1) set_names(['foo','bar'],level=[1,2]) set_levels(['a','b','c'],level=1) set_levels([['a','b','c'],[1,2,3]],level=[1,2])
https://api.github.com/repos/pandas-dev/pandas/pulls/7874
2014-07-29T21:07:09Z
2014-07-30T22:13:57Z
2014-07-30T22:13:57Z
2014-07-30T22:38:48Z
BUG/FIX: groupby should raise on multi-valued filter
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index 9279d8b0288c4..523939b39c580 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -336,7 +336,8 @@ Bug Fixes - +- Bug in ``GroupBy.filter()`` where fast path vs. slow path made the filter + return a non scalar value that appeared valid but wasnt' (:issue:`7870`). diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index eabe1b43004df..93be135e9ff40 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -2945,48 +2945,34 @@ def filter(self, func, dropna=True, *args, **kwargs): >>> grouped = df.groupby(lambda x: mapping[x]) >>> grouped.filter(lambda x: x['A'].sum() + x['B'].sum() > 0) """ - from pandas.tools.merge import concat indices = [] obj = self._selected_obj gen = self.grouper.get_iterator(obj, axis=self.axis) - fast_path, slow_path = self._define_paths(func, *args, **kwargs) - - path = None for name, group in gen: object.__setattr__(group, 'name', name) - if path is None: - # Try slow path and fast path. - try: - path, res = self._choose_path(fast_path, slow_path, group) - except Exception: # pragma: no cover - res = fast_path(group) - path = fast_path - else: - res = path(group) + res = func(group) - def add_indices(): - indices.append(self._get_index(name)) + try: + res = res.squeeze() + except AttributeError: # allow e.g., scalars and frames to pass + pass # interpret the result of the filter - if isinstance(res, (bool, np.bool_)): - if res: - add_indices() + if (isinstance(res, (bool, np.bool_)) or + np.isscalar(res) and isnull(res)): + if res and notnull(res): + indices.append(self._get_index(name)) else: - if getattr(res, 'ndim', None) == 1: - val = res.ravel()[0] - if val and notnull(val): - add_indices() - else: - - # in theory you could do .all() on the boolean result ? - raise TypeError("the filter must return a boolean result") + # non scalars aren't allowed + raise TypeError("filter function returned a %s, " + "but expected a scalar bool" % + type(res).__name__) - filtered = self._apply_filter(indices, dropna) - return filtered + return self._apply_filter(indices, dropna) class DataFrameGroupBy(NDFrameGroupBy): diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 5adaacbeb9d29..f958d5481ad33 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -3968,6 +3968,32 @@ def test_filter_has_access_to_grouped_cols(self): filt = g.filter(lambda x: x['A'].sum() == 2) assert_frame_equal(filt, df.iloc[[0, 1]]) + def test_filter_enforces_scalarness(self): + df = pd.DataFrame([ + ['best', 'a', 'x'], + ['worst', 'b', 'y'], + ['best', 'c', 'x'], + ['best','d', 'y'], + ['worst','d', 'y'], + ['worst','d', 'y'], + ['best','d', 'z'], + ], columns=['a', 'b', 'c']) + with tm.assertRaisesRegexp(TypeError, 'filter function returned a.*'): + df.groupby('c').filter(lambda g: g['a'] == 'best') + + def test_filter_non_bool_raises(self): + df = pd.DataFrame([ + ['best', 'a', 1], + ['worst', 'b', 1], + ['best', 'c', 1], + ['best','d', 1], + ['worst','d', 1], + ['worst','d', 1], + ['best','d', 1], + ], columns=['a', 'b', 'c']) + with tm.assertRaisesRegexp(TypeError, 'filter function returned a.*'): + df.groupby('a').filter(lambda g: g.c.mean()) + def test_index_label_overlaps_location(self): # checking we don't have any label/location confusion in the # the wake of GH5375
closes #7870
https://api.github.com/repos/pandas-dev/pandas/pulls/7871
2014-07-29T17:43:20Z
2014-07-30T23:15:10Z
2014-07-30T23:15:10Z
2014-07-30T23:15:11Z
BUG: Bug in multi-index slicing with missing indexers (GH7866)
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index b0267c3dc5163..fe5ad52397ee8 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -274,7 +274,7 @@ Bug Fixes - Bug in ``DatetimeIndex`` and ``PeriodIndex`` in-place addition and subtraction cause different result from normal one (:issue:`6527`) - Bug in adding and subtracting ``PeriodIndex`` with ``PeriodIndex`` raise ``TypeError`` (:issue:`7741`) - Bug in ``combine_first`` with ``PeriodIndex`` data raises ``TypeError`` (:issue:`3367`) - +- Bug in multi-index slicing with missing indexers (:issue:`7866`) - Bug in pickles contains ``DateOffset`` may raise ``AttributeError`` when ``normalize`` attribute is reffered internally (:issue:`7748`) diff --git a/pandas/core/index.py b/pandas/core/index.py index 81602d5240a08..cfac0a42eaa75 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -3638,9 +3638,17 @@ def _convert_indexer(r): ranges.append(k) elif com.is_list_like(k): # a collection of labels to include from this level (these are or'd) - ranges.append(reduce( - np.logical_or,[ _convert_indexer(self._get_level_indexer(x, level=i) - ) for x in k ])) + indexers = [] + for x in k: + try: + indexers.append(_convert_indexer(self._get_level_indexer(x, level=i))) + except (KeyError): + + # ignore not founds + continue + + ranges.append(reduce(np.logical_or,indexers)) + elif _is_null_slice(k): # empty slice pass diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 64e9d18d0aa2f..6a5a433ce3e35 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1941,6 +1941,39 @@ def f(): df.val['X'] self.assertRaises(KeyError, f) + + # GH 7866 + # multi-index slicing with missing indexers + s = pd.Series(np.arange(9), + index=pd.MultiIndex.from_product([['A','B','C'],['foo','bar','baz']], + names=['one','two']) + ).sortlevel() + + expected = pd.Series(np.arange(3), + index=pd.MultiIndex.from_product([['A'],['foo','bar','baz']], + names=['one','two']) + ).sortlevel() + + result = s.loc[['A']] + assert_series_equal(result,expected) + result = s.loc[['A','D']] + assert_series_equal(result,expected) + + # empty series + result = s.loc[['D']] + expected = s.loc[[]] + assert_series_equal(result,expected) + + idx = pd.IndexSlice + expected = pd.Series([0,3,6], + index=pd.MultiIndex.from_product([['A','B','C'],['foo']], + names=['one','two']) + ).sortlevel() + result = s.loc[idx[:,['foo']]] + assert_series_equal(result,expected) + result = s.loc[idx[:,['foo','bah']]] + assert_series_equal(result,expected) + def test_setitem_dtype_upcast(self): # GH3216
closes #7866
https://api.github.com/repos/pandas-dev/pandas/pulls/7867
2014-07-29T11:55:44Z
2014-07-30T23:48:47Z
2014-07-30T23:48:47Z
2014-07-31T11:25:56Z
BUG: Fixed incorrect string length calculation when writing strings in Stata
diff --git a/doc/source/io.rst b/doc/source/io.rst index 91ffb5091e927..32af1924aee70 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3529,6 +3529,13 @@ outside of this range, the data is cast to ``int16``. Conversion from ``int64`` to ``float64`` may result in a loss of precision if ``int64`` values are larger than 2**53. +.. warning:: + :class:`~pandas.io.stata.StataWriter`` and + :func:`~pandas.core.frame.DataFrame.to_stata` only support fixed width + strings containing up to 244 characters, a limitation imposed by the version + 115 dta file format. Attempting to write *Stata* dta files with strings + longer than 244 characters raises a ``ValueError``. + .. _io.stata_reader: diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index dbdae6ed7144e..e5ba8efd25b02 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -119,6 +119,11 @@ API changes - The ``infer_types`` argument to :func:`~pandas.io.html.read_html` now has no effect (:issue:`7762`, :issue:`7032`). +- ``DataFrame.to_stata`` and ``StataWriter`` check string length for + compatibility with limitations imposed in dta files where fixed-width + strings must contain 244 or fewer characters. Attempting to write Stata + dta files with strings longer than 244 characters raises a ``ValueError``. (:issue:`7858`) + .. _whatsnew_0150.cat: @@ -312,7 +317,7 @@ Bug Fixes - Bug in ``DataFrame.plot`` with ``subplots=True`` may draw unnecessary minor xticks and yticks (:issue:`7801`) - Bug in ``StataReader`` which did not read variable labels in 117 files due to difference between Stata documentation and implementation (:issue:`7816`) - +- Bug in ``StataReader`` where strings were always converted to 244 characters-fixed width irrespective of underlying string size (:issue:`7858`) - Bug in ``expanding_cov``, ``expanding_corr``, ``rolling_cov``, ``rolling_cov``, ``ewmcov``, and ``ewmcorr`` returning results with columns sorted by name and producing an error for non-unique columns; now handles non-unique columns and returns columns in original order diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 3458a95ac096d..5b5ce3e59e16e 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -23,6 +23,7 @@ from pandas.compat import long, lrange, lmap, lzip, text_type, string_types from pandas import isnull from pandas.io.common import get_filepath_or_buffer +from pandas.lib import max_len_string_array, is_string_array from pandas.tslib import NaT def read_stata(filepath_or_buffer, convert_dates=True, @@ -181,6 +182,11 @@ def _datetime_to_stata_elapsed(date, fmt): raise ValueError("fmt %s not understood" % fmt) +excessive_string_length_error = """ +Fixed width strings in Stata .dta files are limited to 244 (or fewer) characters. +Column '%s' does not satisfy this restriction. +""" + class PossiblePrecisionLoss(Warning): pass @@ -1040,12 +1046,14 @@ def _dtype_to_stata_type(dtype): "Please report an error to the developers." % dtype) -def _dtype_to_default_stata_fmt(dtype): +def _dtype_to_default_stata_fmt(dtype, column): """ Maps numpy dtype to stata's default format for this type. Not terribly important since users can change this in Stata. Semantics are string -> "%DDs" where DD is the length of the string + object -> "%DDs" where DD is the length of the string, if a string, or 244 + for anything that cannot be converted to a string. float64 -> "%10.0g" float32 -> "%9.0g" int64 -> "%9.0g" @@ -1055,9 +1063,21 @@ def _dtype_to_default_stata_fmt(dtype): """ #TODO: expand this to handle a default datetime format? if dtype.type == np.string_: + if max_len_string_array(column.values) > 244: + raise ValueError(excessive_string_length_error % column.name) + return "%" + str(dtype.itemsize) + "s" elif dtype.type == np.object_: - return "%244s" + try: + # Try to use optimal size if available + itemsize = max_len_string_array(column.values) + except: + # Default size + itemsize = 244 + if itemsize > 244: + raise ValueError(excessive_string_length_error % column.name) + + return "%" + str(itemsize) + "s" elif dtype == np.float64: return "%10.0g" elif dtype == np.float32: @@ -1264,7 +1284,9 @@ def __iter__(self): ) dtypes[key] = np.dtype(new_type) self.typlist = [_dtype_to_stata_type(dt) for dt in dtypes] - self.fmtlist = [_dtype_to_default_stata_fmt(dt) for dt in dtypes] + self.fmtlist = [] + for col, dtype in dtypes.iteritems(): + self.fmtlist.append(_dtype_to_default_stata_fmt(dtype, data[col])) # set the given format for the datetime cols if self._convert_dates is not None: for key in self._convert_dates: diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py index 5271604235922..459a1fe6c0e89 100644 --- a/pandas/io/tests/test_stata.py +++ b/pandas/io/tests/test_stata.py @@ -565,6 +565,30 @@ def test_variable_labels(self): self.assertTrue(k in keys) self.assertTrue(v in labels) + def test_minimal_size_col(self): + str_lens = (1, 100, 244) + s = {} + for str_len in str_lens: + s['s' + str(str_len)] = Series(['a' * str_len, 'b' * str_len, 'c' * str_len]) + original = DataFrame(s) + with tm.ensure_clean() as path: + original.to_stata(path, write_index=False) + sr = StataReader(path) + variables = sr.varlist + formats = sr.fmtlist + for variable, fmt in zip(variables, formats): + self.assertTrue(int(variable[1:]) == int(fmt[1:-1])) + + def test_excessively_long_string(self): + str_lens = (1, 244, 500) + s = {} + for str_len in str_lens: + s['s' + str(str_len)] = Series(['a' * str_len, 'b' * str_len, 'c' * str_len]) + original = DataFrame(s) + with tm.assertRaises(ValueError): + with tm.ensure_clean() as path: + original.to_stata(path) + if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
Strings were incorrectly written using 244 character irrespective of the actual length of the underlying due to changes in pandas where the underlying NumPy datatype of strings is always np.object_, and never np.string_. Closes #7858
https://api.github.com/repos/pandas-dev/pandas/pulls/7862
2014-07-29T06:19:15Z
2014-08-01T13:30:09Z
2014-08-01T13:30:09Z
2014-08-20T15:32:49Z
CLN: Clean tslib, frequencies import
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index ea7f963f79f28..c40ff67789b45 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -16,7 +16,7 @@ from pandas.core.series import Series, remove_na from pandas.tseries.index import DatetimeIndex from pandas.tseries.period import PeriodIndex, Period -from pandas.tseries.frequencies import get_period_alias, get_base_alias +import pandas.tseries.frequencies as frequencies from pandas.tseries.offsets import DateOffset from pandas.compat import range, lrange, lmap, map, zip, string_types import pandas.compat as compat @@ -1504,8 +1504,8 @@ def _is_dynamic_freq(self, freq): if isinstance(freq, DateOffset): freq = freq.rule_code else: - freq = get_base_alias(freq) - freq = get_period_alias(freq) + freq = frequencies.get_base_alias(freq) + freq = frequencies.get_period_alias(freq) return freq is not None and self._no_base(freq) def _no_base(self, freq): @@ -1513,10 +1513,9 @@ def _no_base(self, freq): from pandas.core.frame import DataFrame if (isinstance(self.data, (Series, DataFrame)) and isinstance(self.data.index, DatetimeIndex)): - import pandas.tseries.frequencies as freqmod - base = freqmod.get_freq(freq) + base = frequencies.get_freq(freq) x = self.data.index - if (base <= freqmod.FreqGroup.FR_DAY): + if (base <= frequencies.FreqGroup.FR_DAY): return x[:1].is_normalized return Period(x[0], freq).to_timestamp(tz=x.tz) == x[0] @@ -1632,8 +1631,8 @@ def _maybe_convert_index(self, data): freq = getattr(data.index, 'inferred_freq', None) if isinstance(freq, DateOffset): freq = freq.rule_code - freq = get_base_alias(freq) - freq = get_period_alias(freq) + freq = frequencies.get_base_alias(freq) + freq = frequencies.get_period_alias(freq) if freq is None: ax = self._get_ax(0) diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 4aa424ea08031..518bb4180ec89 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -14,7 +14,7 @@ from pandas.compat import u from pandas.tseries.frequencies import ( infer_freq, to_offset, get_period_alias, - Resolution, get_reso_string, _tz_convert_with_transitions) + Resolution, _tz_convert_with_transitions) from pandas.core.base import DatetimeIndexOpsMixin from pandas.tseries.offsets import DateOffset, generate_range, Tick, CDay from pandas.tseries.tools import parse_time_string, normalize_date @@ -291,7 +291,7 @@ def __new__(cls, data=None, tz = subarr.tz else: if tz is not None: - tz = tools._maybe_get_tz(tz) + tz = tslib.maybe_get_tz(tz) if (not isinstance(data, DatetimeIndex) or getattr(data, 'tz', None) is None): @@ -361,10 +361,14 @@ def _generate(cls, start, end, periods, name, offset, raise ValueError('Start and end cannot both be tz-aware with ' 'different timezones') - inferred_tz = tools._maybe_get_tz(inferred_tz) + inferred_tz = tslib.maybe_get_tz(inferred_tz) # these may need to be localized - tz = tools._maybe_get_tz(tz, start or end) + tz = tslib.maybe_get_tz(tz) + if tz is not None: + date = start or end + if date.tzinfo is not None and hasattr(tz, 'localize'): + tz = tz.localize(date.replace(tzinfo=None)).tzinfo if tz is not None and inferred_tz is not None: if not inferred_tz == tz: @@ -477,7 +481,7 @@ def _simple_new(cls, values, name, freq=None, tz=None): result = values.view(cls) result.name = name result.offset = freq - result.tz = tools._maybe_get_tz(tz) + result.tz = tslib.maybe_get_tz(tz) return result @@ -1620,7 +1624,7 @@ def tz_convert(self, tz): ------- normalized : DatetimeIndex """ - tz = tools._maybe_get_tz(tz) + tz = tslib.maybe_get_tz(tz) if self.tz is None: # tz naive, use tz_localize @@ -1648,7 +1652,7 @@ def tz_localize(self, tz, infer_dst=False): """ if self.tz is not None: raise TypeError("Already tz-aware, use tz_convert to convert.") - tz = tools._maybe_get_tz(tz) + tz = tslib.maybe_get_tz(tz) # Convert to UTC new_dates = tslib.tz_localize_to_utc(self.asi8, tz, infer_dst=infer_dst) diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py index 887bf806dd4e4..7f865fd9aefa8 100644 --- a/pandas/tseries/period.py +++ b/pandas/tseries/period.py @@ -5,12 +5,11 @@ import numpy as np from pandas.core.base import PandasObject -from pandas.tseries.frequencies import (get_freq_code as _gfc, - _month_numbers, FreqGroup) +import pandas.tseries.frequencies as frequencies +from pandas.tseries.frequencies import get_freq_code as _gfc from pandas.tseries.index import DatetimeIndex, Int64Index, Index from pandas.core.base import DatetimeIndexOpsMixin from pandas.tseries.tools import parse_time_string -import pandas.tseries.frequencies as _freq_mod import pandas.core.common as com from pandas.core.common import (isnull, _INT64_DTYPE, _maybe_box, @@ -116,7 +115,7 @@ def __init__(self, value=None, freq=None, ordinal=None, dt, _, reso = parse_time_string(value, freq) if freq is None: try: - freq = _freq_mod.Resolution.get_freq(reso) + freq = frequencies.Resolution.get_freq(reso) except KeyError: raise ValueError("Invalid frequency or could not infer: %s" % reso) @@ -142,7 +141,7 @@ def __init__(self, value=None, freq=None, ordinal=None, dt.hour, dt.minute, dt.second, dt.microsecond, 0, base) - self.freq = _freq_mod._get_freq_str(base) + self.freq = frequencies._get_freq_str(base) def __eq__(self, other): if isinstance(other, Period): @@ -267,7 +266,7 @@ def to_timestamp(self, freq=None, how='start', tz=None): if freq is None: base, mult = _gfc(self.freq) - freq = _freq_mod.get_to_timestamp_base(base) + freq = frequencies.get_to_timestamp_base(base) base, mult = _gfc(freq) val = self.asfreq(freq, how) @@ -296,7 +295,7 @@ def now(cls, freq=None): def __repr__(self): base, mult = _gfc(self.freq) formatted = tslib.period_format(self.ordinal, base) - freqstr = _freq_mod._reverse_period_code_map[base] + freqstr = frequencies._reverse_period_code_map[base] if not compat.PY3: encoding = com.get_option("display.encoding") @@ -577,7 +576,7 @@ def __new__(cls, data=None, ordinal=None, freq=None, start=None, end=None, quarter=None, day=None, hour=None, minute=None, second=None, tz=None): - freq = _freq_mod.get_standard_freq(freq) + freq = frequencies.get_standard_freq(freq) if periods is not None: if com.is_float(periods): @@ -767,7 +766,7 @@ def freqstr(self): def asfreq(self, freq=None, how='E'): how = _validate_end_alias(how) - freq = _freq_mod.get_standard_freq(freq) + freq = frequencies.get_standard_freq(freq) base1, mult1 = _gfc(self.freq) base2, mult2 = _gfc(freq) @@ -845,7 +844,7 @@ def to_timestamp(self, freq=None, how='start'): if freq is None: base, mult = _gfc(self.freq) - freq = _freq_mod.get_to_timestamp_base(base) + freq = frequencies.get_to_timestamp_base(base) base, mult = _gfc(freq) new_data = self.asfreq(freq, how) @@ -889,8 +888,8 @@ def get_value(self, series, key): except (KeyError, IndexError): try: asdt, parsed, reso = parse_time_string(key, self.freq) - grp = _freq_mod._infer_period_group(reso) - freqn = _freq_mod._period_group(self.freq) + grp = frequencies._infer_period_group(reso) + freqn = frequencies._period_group(self.freq) vals = self.values @@ -978,8 +977,8 @@ def _get_string_slice(self, key): key, parsed, reso = parse_time_string(key, self.freq) - grp = _freq_mod._infer_period_group(reso) - freqn = _freq_mod._period_group(self.freq) + grp = frequencies._infer_period_group(reso) + freqn = frequencies._period_group(self.freq) if reso == 'year': t1 = Period(year=parsed.year, freq='A') @@ -1216,12 +1215,12 @@ def _range_from_fields(year=None, month=None, quarter=None, day=None, if quarter is not None: if freq is None: freq = 'Q' - base = FreqGroup.FR_QTR + base = frequencies.FreqGroup.FR_QTR else: base, mult = _gfc(freq) if mult != 1: raise ValueError('Only mult == 1 supported') - if base != FreqGroup.FR_QTR: + if base != frequencies.FreqGroup.FR_QTR: raise AssertionError("base must equal FR_QTR") year, quarter = _make_field_arrays(year, quarter) @@ -1273,7 +1272,7 @@ def _quarter_to_myear(year, quarter, freq): if quarter <= 0 or quarter > 4: raise ValueError('Quarter must be 1 <= q <= 4') - mnum = _month_numbers[_freq_mod._get_rule_month(freq)] + 1 + mnum = frequencies._month_numbers[frequencies._get_rule_month(freq)] + 1 month = (mnum + (quarter - 1) * 3) % 12 + 1 if month > mnum: year -= 1 diff --git a/pandas/tseries/tests/test_frequencies.py b/pandas/tseries/tests/test_frequencies.py index 10a8286f4bec9..24deb8a298688 100644 --- a/pandas/tseries/tests/test_frequencies.py +++ b/pandas/tseries/tests/test_frequencies.py @@ -9,9 +9,9 @@ from pandas import Index, DatetimeIndex, Timestamp, Series, date_range, period_range -from pandas.tseries.frequencies import to_offset, infer_freq +import pandas.tseries.frequencies as frequencies from pandas.tseries.tools import to_datetime -import pandas.tseries.frequencies as fmod + import pandas.tseries.offsets as offsets from pandas.tseries.period import PeriodIndex import pandas.compat as compat @@ -23,40 +23,40 @@ def test_to_offset_multiple(): freqstr = '2h30min' freqstr2 = '2h 30min' - result = to_offset(freqstr) - assert(result == to_offset(freqstr2)) + result = frequencies.to_offset(freqstr) + assert(result == frequencies.to_offset(freqstr2)) expected = offsets.Minute(150) assert(result == expected) freqstr = '2h30min15s' - result = to_offset(freqstr) + result = frequencies.to_offset(freqstr) expected = offsets.Second(150 * 60 + 15) assert(result == expected) freqstr = '2h 60min' - result = to_offset(freqstr) + result = frequencies.to_offset(freqstr) expected = offsets.Hour(3) assert(result == expected) freqstr = '15l500u' - result = to_offset(freqstr) + result = frequencies.to_offset(freqstr) expected = offsets.Micro(15500) assert(result == expected) freqstr = '10s75L' - result = to_offset(freqstr) + result = frequencies.to_offset(freqstr) expected = offsets.Milli(10075) assert(result == expected) if not _np_version_under1p7: freqstr = '2800N' - result = to_offset(freqstr) + result = frequencies.to_offset(freqstr) expected = offsets.Nano(2800) assert(result == expected) # malformed try: - to_offset('2h20m') + frequencies.to_offset('2h20m') except ValueError: pass else: @@ -65,31 +65,31 @@ def test_to_offset_multiple(): def test_to_offset_negative(): freqstr = '-1S' - result = to_offset(freqstr) + result = frequencies.to_offset(freqstr) assert(result.n == -1) freqstr = '-5min10s' - result = to_offset(freqstr) + result = frequencies.to_offset(freqstr) assert(result.n == -310) def test_to_offset_leading_zero(): freqstr = '00H 00T 01S' - result = to_offset(freqstr) + result = frequencies.to_offset(freqstr) assert(result.n == 1) freqstr = '-00H 03T 14S' - result = to_offset(freqstr) + result = frequencies.to_offset(freqstr) assert(result.n == -194) def test_anchored_shortcuts(): - result = to_offset('W') - expected = to_offset('W-SUN') + result = frequencies.to_offset('W') + expected = frequencies.to_offset('W-SUN') assert(result == expected) - result = to_offset('Q') - expected = to_offset('Q-DEC') + result = frequencies.to_offset('Q') + expected = frequencies.to_offset('Q-DEC') assert(result == expected) @@ -100,26 +100,26 @@ class TestFrequencyInference(tm.TestCase): def test_raise_if_period_index(self): index = PeriodIndex(start="1/1/1990", periods=20, freq="M") - self.assertRaises(TypeError, infer_freq, index) + self.assertRaises(TypeError, frequencies.infer_freq, index) def test_raise_if_too_few(self): index = _dti(['12/31/1998', '1/3/1999']) - self.assertRaises(ValueError, infer_freq, index) + self.assertRaises(ValueError, frequencies.infer_freq, index) def test_business_daily(self): index = _dti(['12/31/1998', '1/3/1999', '1/4/1999']) - self.assertEqual(infer_freq(index), 'B') + self.assertEqual(frequencies.infer_freq(index), 'B') def test_day(self): self._check_tick(timedelta(1), 'D') def test_day_corner(self): index = _dti(['1/1/2000', '1/2/2000', '1/3/2000']) - self.assertEqual(infer_freq(index), 'D') + self.assertEqual(frequencies.infer_freq(index), 'D') def test_non_datetimeindex(self): dates = to_datetime(['1/1/2000', '1/2/2000', '1/3/2000']) - self.assertEqual(infer_freq(dates), 'D') + self.assertEqual(frequencies.infer_freq(dates), 'D') def test_hour(self): self._check_tick(timedelta(hours=1), 'H') @@ -149,15 +149,15 @@ def _check_tick(self, base_delta, code): exp_freq = '%d%s' % (i, code) else: exp_freq = code - self.assertEqual(infer_freq(index), exp_freq) + self.assertEqual(frequencies.infer_freq(index), exp_freq) index = _dti([b + base_delta * 7] + [b + base_delta * j for j in range(3)]) - self.assertIsNone(infer_freq(index)) + self.assertIsNone(frequencies.infer_freq(index)) index = _dti([b + base_delta * j for j in range(3)] + [b + base_delta * 7]) - self.assertIsNone(infer_freq(index)) + self.assertIsNone(frequencies.infer_freq(index)) def test_weekly(self): days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'] @@ -175,7 +175,7 @@ def test_week_of_month(self): def test_week_of_month_fake(self): #All of these dates are on same day of week and are 4 or 5 weeks apart index = DatetimeIndex(["2013-08-27","2013-10-01","2013-10-29","2013-11-26"]) - assert infer_freq(index) != 'WOM-4TUE' + assert frequencies.infer_freq(index) != 'WOM-4TUE' def test_monthly(self): self._check_generated_range('1/1/2000', 'M') @@ -212,9 +212,9 @@ def _check_generated_range(self, start, freq): gen = date_range(start, periods=7, freq=freq) index = _dti(gen.values) if not freq.startswith('Q-'): - self.assertEqual(infer_freq(index), gen.freqstr) + self.assertEqual(frequencies.infer_freq(index), gen.freqstr) else: - inf_freq = infer_freq(index) + inf_freq = frequencies.infer_freq(index) self.assertTrue((inf_freq == 'Q-DEC' and gen.freqstr in ('Q', 'Q-DEC', 'Q-SEP', 'Q-JUN', 'Q-MAR')) @@ -228,9 +228,9 @@ def _check_generated_range(self, start, freq): gen = date_range(start, periods=5, freq=freq) index = _dti(gen.values) if not freq.startswith('Q-'): - self.assertEqual(infer_freq(index), gen.freqstr) + self.assertEqual(frequencies.infer_freq(index), gen.freqstr) else: - inf_freq = infer_freq(index) + inf_freq = frequencies.infer_freq(index) self.assertTrue((inf_freq == 'Q-DEC' and gen.freqstr in ('Q', 'Q-DEC', 'Q-SEP', 'Q-JUN', 'Q-MAR')) @@ -281,7 +281,7 @@ def test_non_datetimeindex(self): vals = rng.to_pydatetime() - result = infer_freq(vals) + result = frequencies.infer_freq(vals) self.assertEqual(result, rng.inferred_freq) def test_invalid_index_types(self): @@ -290,17 +290,17 @@ def test_invalid_index_types(self): for i in [ tm.makeIntIndex(10), tm.makeFloatIndex(10), tm.makePeriodIndex(10) ]: - self.assertRaises(TypeError, lambda : infer_freq(i)) + self.assertRaises(TypeError, lambda : frequencies.infer_freq(i)) for i in [ tm.makeStringIndex(10), tm.makeUnicodeIndex(10) ]: - self.assertRaises(ValueError, lambda : infer_freq(i)) + self.assertRaises(ValueError, lambda : frequencies.infer_freq(i)) def test_string_datetimelike_compat(self): # GH 6463 - expected = infer_freq(['2004-01', '2004-02', '2004-03', '2004-04']) - result = infer_freq(Index(['2004-01', '2004-02', '2004-03', '2004-04'])) + expected = frequencies.infer_freq(['2004-01', '2004-02', '2004-03', '2004-04']) + result = frequencies.infer_freq(Index(['2004-01', '2004-02', '2004-03', '2004-04'])) self.assertEqual(result,expected) def test_series(self): @@ -311,24 +311,24 @@ def test_series(self): # invalid type of Series for s in [ Series(np.arange(10)), Series(np.arange(10.))]: - self.assertRaises(TypeError, lambda : infer_freq(s)) + self.assertRaises(TypeError, lambda : frequencies.infer_freq(s)) # a non-convertible string - self.assertRaises(ValueError, lambda : infer_freq(Series(['foo','bar']))) + self.assertRaises(ValueError, lambda : frequencies.infer_freq(Series(['foo','bar']))) # cannot infer on PeriodIndex for freq in [None, 'L', 'Y']: s = Series(period_range('2013',periods=10,freq=freq)) - self.assertRaises(TypeError, lambda : infer_freq(s)) + self.assertRaises(TypeError, lambda : frequencies.infer_freq(s)) # DateTimeIndex for freq in ['M', 'L', 'S']: s = Series(date_range('20130101',periods=10,freq=freq)) - inferred = infer_freq(s) + inferred = frequencies.infer_freq(s) self.assertEqual(inferred,freq) s = Series(date_range('20130101','20130110')) - inferred = infer_freq(s) + inferred = frequencies.infer_freq(s) self.assertEqual(inferred,'D') MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', @@ -336,20 +336,20 @@ def test_series(self): def test_is_superperiod_subperiod(): - assert(fmod.is_superperiod(offsets.YearEnd(), offsets.MonthEnd())) - assert(fmod.is_subperiod(offsets.MonthEnd(), offsets.YearEnd())) + assert(frequencies.is_superperiod(offsets.YearEnd(), offsets.MonthEnd())) + assert(frequencies.is_subperiod(offsets.MonthEnd(), offsets.YearEnd())) - assert(fmod.is_superperiod(offsets.Hour(), offsets.Minute())) - assert(fmod.is_subperiod(offsets.Minute(), offsets.Hour())) + assert(frequencies.is_superperiod(offsets.Hour(), offsets.Minute())) + assert(frequencies.is_subperiod(offsets.Minute(), offsets.Hour())) - assert(fmod.is_superperiod(offsets.Second(), offsets.Milli())) - assert(fmod.is_subperiod(offsets.Milli(), offsets.Second())) + assert(frequencies.is_superperiod(offsets.Second(), offsets.Milli())) + assert(frequencies.is_subperiod(offsets.Milli(), offsets.Second())) - assert(fmod.is_superperiod(offsets.Milli(), offsets.Micro())) - assert(fmod.is_subperiod(offsets.Micro(), offsets.Milli())) + assert(frequencies.is_superperiod(offsets.Milli(), offsets.Micro())) + assert(frequencies.is_subperiod(offsets.Micro(), offsets.Milli())) - assert(fmod.is_superperiod(offsets.Micro(), offsets.Nano())) - assert(fmod.is_subperiod(offsets.Nano(), offsets.Micro())) + assert(frequencies.is_superperiod(offsets.Micro(), offsets.Nano())) + assert(frequencies.is_subperiod(offsets.Nano(), offsets.Micro())) if __name__ == '__main__': diff --git a/pandas/tseries/tests/test_offsets.py b/pandas/tseries/tests/test_offsets.py index d99cfb254cc48..065aa9236e539 100644 --- a/pandas/tseries/tests/test_offsets.py +++ b/pandas/tseries/tests/test_offsets.py @@ -19,7 +19,7 @@ from pandas.tseries.frequencies import _offset_map from pandas.tseries.index import _to_m8, DatetimeIndex, _daterange_cache, date_range -from pandas.tseries.tools import parse_time_string, _maybe_get_tz +from pandas.tseries.tools import parse_time_string import pandas.tseries.offsets as offsets from pandas.tslib import NaT, Timestamp @@ -243,7 +243,7 @@ def _check_offsetfunc_works(self, offset, funcname, dt, expected, for tz in self.timezones: expected_localize = expected.tz_localize(tz) - tz_obj = _maybe_get_tz(tz) + tz_obj = tslib.maybe_get_tz(tz) dt_tz = tslib._localize_pydatetime(dt, tz_obj) result = func(dt_tz) diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py index f5f66a49c29d4..b9d4dd80438ef 100644 --- a/pandas/tseries/tests/test_period.py +++ b/pandas/tseries/tests/test_period.py @@ -15,7 +15,7 @@ from pandas.tseries.period import Period, PeriodIndex, period_range from pandas.tseries.index import DatetimeIndex, date_range, Index from pandas.tseries.tools import to_datetime -import pandas.tseries.period as pmod +import pandas.tseries.period as period import pandas.core.datetools as datetools import pandas as pd @@ -508,7 +508,7 @@ def test_properties_nat(self): def test_pnow(self): dt = datetime.now() - val = pmod.pnow('D') + val = period.pnow('D') exp = Period(dt, freq='D') self.assertEqual(val, exp) diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index f2bc66f156c75..9d5f45735feb5 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -15,7 +15,7 @@ import pandas.core.datetools as datetools import pandas.tseries.offsets as offsets import pandas.tseries.tools as tools -import pandas.tseries.frequencies as fmod +import pandas.tseries.frequencies as frequencies import pandas as pd from pandas.util.testing import assert_series_equal, assert_almost_equal @@ -28,7 +28,6 @@ import pandas.index as _index from pandas.compat import range, long, StringIO, lrange, lmap, zip, product -import pandas.core.datetools as dt from numpy.random import rand from numpy.testing import assert_array_equal from pandas.util.testing import assert_frame_equal @@ -2961,7 +2960,7 @@ def test_datetimeindex_constructor(self): edate = datetime(2000, 1, 1) idx = DatetimeIndex(start=sdate, freq='1B', periods=20) self.assertEqual(len(idx), 20) - self.assertEqual(idx[0], sdate + 0 * dt.bday) + self.assertEqual(idx[0], sdate + 0 * datetools.bday) self.assertEqual(idx.freq, 'B') idx = DatetimeIndex(end=edate, freq=('D', 5), periods=20) @@ -2971,19 +2970,19 @@ def test_datetimeindex_constructor(self): idx1 = DatetimeIndex(start=sdate, end=edate, freq='W-SUN') idx2 = DatetimeIndex(start=sdate, end=edate, - freq=dt.Week(weekday=6)) + freq=datetools.Week(weekday=6)) self.assertEqual(len(idx1), len(idx2)) self.assertEqual(idx1.offset, idx2.offset) idx1 = DatetimeIndex(start=sdate, end=edate, freq='QS') idx2 = DatetimeIndex(start=sdate, end=edate, - freq=dt.QuarterBegin(startingMonth=1)) + freq=datetools.QuarterBegin(startingMonth=1)) self.assertEqual(len(idx1), len(idx2)) self.assertEqual(idx1.offset, idx2.offset) idx1 = DatetimeIndex(start=sdate, end=edate, freq='BQ') idx2 = DatetimeIndex(start=sdate, end=edate, - freq=dt.BQuarterEnd(startingMonth=12)) + freq=datetools.BQuarterEnd(startingMonth=12)) self.assertEqual(len(idx1), len(idx2)) self.assertEqual(idx1.offset, idx2.offset) @@ -3474,31 +3473,31 @@ def test_delta_preserve_nanos(self): self.assertEqual(result.nanosecond, val.nanosecond) def test_frequency_misc(self): - self.assertEqual(fmod.get_freq_group('T'), - fmod.FreqGroup.FR_MIN) + self.assertEqual(frequencies.get_freq_group('T'), + frequencies.FreqGroup.FR_MIN) - code, stride = fmod.get_freq_code(offsets.Hour()) - self.assertEqual(code, fmod.FreqGroup.FR_HR) + code, stride = frequencies.get_freq_code(offsets.Hour()) + self.assertEqual(code, frequencies.FreqGroup.FR_HR) - code, stride = fmod.get_freq_code((5, 'T')) - self.assertEqual(code, fmod.FreqGroup.FR_MIN) + code, stride = frequencies.get_freq_code((5, 'T')) + self.assertEqual(code, frequencies.FreqGroup.FR_MIN) self.assertEqual(stride, 5) offset = offsets.Hour() - result = fmod.to_offset(offset) + result = frequencies.to_offset(offset) self.assertEqual(result, offset) - result = fmod.to_offset((5, 'T')) + result = frequencies.to_offset((5, 'T')) expected = offsets.Minute(5) self.assertEqual(result, expected) - self.assertRaises(ValueError, fmod.get_freq_code, (5, 'baz')) + self.assertRaises(ValueError, frequencies.get_freq_code, (5, 'baz')) - self.assertRaises(ValueError, fmod.to_offset, '100foo') + self.assertRaises(ValueError, frequencies.to_offset, '100foo') - self.assertRaises(ValueError, fmod.to_offset, ('', '')) + self.assertRaises(ValueError, frequencies.to_offset, ('', '')) - result = fmod.get_standard_freq(offsets.Hour()) + result = frequencies.get_standard_freq(offsets.Hour()) self.assertEqual(result, 'H') def test_hash_equivalent(self): @@ -3936,7 +3935,7 @@ def test_to_datetime_format_microsecond(self): val = '01-Apr-2011 00:00:01.978' format = '%d-%b-%Y %H:%M:%S.%f' result = to_datetime(val, format=format) - exp = dt.datetime.strptime(val, format) + exp = datetime.strptime(val, format) self.assertEqual(result, exp) def test_to_datetime_format_time(self): diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py index b4ab813d3debe..457a95deb16d9 100644 --- a/pandas/tseries/tools.py +++ b/pandas/tseries/tools.py @@ -56,20 +56,6 @@ def _infer(a, b): return tz -def _maybe_get_tz(tz, date=None): - tz = tslib.maybe_get_tz(tz) - if com.is_integer(tz): - import pytz - tz = pytz.FixedOffset(tz / 60) - - # localize and get the tz - if date is not None and tz is not None: - if date.tzinfo is not None and hasattr(tz,'localize'): - tz = tz.localize(date.replace(tzinfo=None)).tzinfo - - return tz - - def _guess_datetime_format(dt_str, dayfirst=False, dt_str_parse=compat.parse_date, dt_str_split=_DATEUTIL_LEXER_SPLIT): diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 655b92cfe70f3..dc9f3fa258985 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -1121,9 +1121,10 @@ cpdef inline object maybe_get_tz(object tz): tz._filename = zone else: tz = pytz.timezone(tz) - return tz - else: - return tz + elif util.is_integer_object(tz): + tz = pytz.FixedOffset(tz / 60) + return tz + class OutOfBoundsDatetime(ValueError): @@ -2223,7 +2224,7 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, bint infer_dst=False): result_b.fill(NPY_NAT) # left side - idx_shifted = _ensure_int64( + idx_shifted = ensure_int64( np.maximum(0, trans.searchsorted(vals - DAY_NS, side='right') - 1)) for i in range(n): @@ -2235,7 +2236,7 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, bint infer_dst=False): result_a[i] = v # right side - idx_shifted = _ensure_int64( + idx_shifted = ensure_int64( np.maximum(0, trans.searchsorted(vals + DAY_NS, side='right') - 1)) for i in range(n): @@ -2313,14 +2314,8 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, bint infer_dst=False): return result -cdef _ensure_int64(object arr): - if util.is_array(arr): - if (<ndarray> arr).descr.type_num == NPY_INT64: - return arr - else: - return arr.astype(np.int64) - else: - return np.array(arr, dtype=np.int64) +import pandas.algos as algos +ensure_int64 = algos.ensure_int64 cdef inline bisect_right_i8(int64_t *data, int64_t val, Py_ssize_t n):
Fixed: - Some modules are imported different aliases - Merge duplicated functions (`maybe_get_tz` and `ensure_int64`)
https://api.github.com/repos/pandas-dev/pandas/pulls/7854
2014-07-27T13:22:43Z
2014-07-28T14:57:03Z
2014-07-28T14:57:03Z
2014-08-04T13:18:06Z
ENH: tz_localize(None) allows to reset tz
diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst index c672a3d030bb9..1bc9cca17aeec 100644 --- a/doc/source/timeseries.rst +++ b/doc/source/timeseries.rst @@ -1454,6 +1454,19 @@ to determine the right offset. rng_hourly_eastern = rng_hourly.tz_localize('US/Eastern', infer_dst=True) rng_hourly_eastern.values + +To remove timezone from tz-aware ``DatetimeIndex``, use ``tz_localize(None)`` or ``tz_convert(None)``. ``tz_localize(None)`` will remove timezone holding local time representations. ``tz_convert(None)`` will remove timezone after converting to UTC time. + +.. ipython:: python + + didx = DatetimeIndex(start='2014-08-01 09:00', freq='H', periods=10, tz='US/Eastern') + didx + didx.tz_localize(None) + didx.tz_convert(None) + + # tz_convert(None) is identical with tz_convert('UTC').tz_localize(None) + didx.tz_convert('UCT').tz_localize(None) + .. _timeseries.timedeltas: Time Deltas diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index ef2b91d044d86..31947e3107708 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -142,6 +142,18 @@ API changes In [3]: idx.isin(['a', 'c', 'e'], level=1) Out[3]: array([ True, False, True, True, False, True], dtype=bool) +- ``tz_localize(None)`` for tz-aware ``Timestamp`` and ``DatetimeIndex`` now removes timezone holding local time, +previously results in ``Exception`` or ``TypeError`` (:issue:`7812`) + + .. ipython:: python + + ts = Timestamp('2014-08-01 09:00', tz='US/Eastern') + ts + ts.tz_localize(None) + + didx = DatetimeIndex(start='2014-08-01 09:00', freq='H', periods=10, tz='US/Eastern') + didx + didx.tz_localize(None) .. _whatsnew_0150.cat: diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 5f7c93d38653a..7ad913e8f5671 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -1618,7 +1618,14 @@ def _view_like(self, ndarray): def tz_convert(self, tz): """ - Convert DatetimeIndex from one time zone to another (using pytz/dateutil) + Convert tz-aware DatetimeIndex from one time zone to another (using pytz/dateutil) + + Parameters + ---------- + tz : string, pytz.timezone, dateutil.tz.tzfile or None + Time zone for time. Corresponding timestamps would be converted to + time zone of the TimeSeries. + None will remove timezone holding UTC time. Returns ------- @@ -1636,13 +1643,15 @@ def tz_convert(self, tz): def tz_localize(self, tz, infer_dst=False): """ - Localize tz-naive DatetimeIndex to given time zone (using pytz/dateutil) + Localize tz-naive DatetimeIndex to given time zone (using pytz/dateutil), + or remove timezone from tz-aware DatetimeIndex Parameters ---------- - tz : string or pytz.timezone or dateutil.tz.tzfile + tz : string, pytz.timezone, dateutil.tz.tzfile or None Time zone for time. Corresponding timestamps would be converted to - time zone of the TimeSeries + time zone of the TimeSeries. + None will remove timezone holding local time. infer_dst : boolean, default False Attempt to infer fall dst-transition hours based on order @@ -1651,13 +1660,15 @@ def tz_localize(self, tz, infer_dst=False): localized : DatetimeIndex """ if self.tz is not None: - raise TypeError("Already tz-aware, use tz_convert to convert.") - tz = tslib.maybe_get_tz(tz) - - # Convert to UTC - new_dates = tslib.tz_localize_to_utc(self.asi8, tz, infer_dst=infer_dst) + if tz is None: + new_dates = tslib.tz_convert(self.asi8, 'UTC', self.tz) + else: + raise TypeError("Already tz-aware, use tz_convert to convert.") + else: + tz = tslib.maybe_get_tz(tz) + # Convert to UTC + new_dates = tslib.tz_localize_to_utc(self.asi8, tz, infer_dst=infer_dst) new_dates = new_dates.view(_NS_DTYPE) - return self._simple_new(new_dates, self.name, self.offset, tz) def indexer_at_time(self, time, asof=False): diff --git a/pandas/tseries/tests/test_timezones.py b/pandas/tseries/tests/test_timezones.py index ab969f13289ac..bcfb2357b668d 100644 --- a/pandas/tseries/tests/test_timezones.py +++ b/pandas/tseries/tests/test_timezones.py @@ -863,6 +863,7 @@ def test_cache_keys_are_distinct_for_pytz_vs_dateutil(self): class TestTimeZones(tm.TestCase): _multiprocess_can_split_ = True + timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/US/Pacific'] def setUp(self): tm._skip_if_no_pytz() @@ -882,6 +883,24 @@ def test_tz_localize_naive(self): self.assertTrue(conv.equals(exp)) + def test_tz_localize_roundtrip(self): + for tz in self.timezones: + idx1 = date_range(start='2014-01-01', end='2014-12-31', freq='M') + idx2 = date_range(start='2014-01-01', end='2014-12-31', freq='D') + idx3 = date_range(start='2014-01-01', end='2014-03-01', freq='H') + idx4 = date_range(start='2014-08-01', end='2014-10-31', freq='T') + for idx in [idx1, idx2, idx3, idx4]: + localized = idx.tz_localize(tz) + expected = date_range(start=idx[0], end=idx[-1], freq=idx.freq, tz=tz) + tm.assert_index_equal(localized, expected) + + with tm.assertRaises(TypeError): + localized.tz_localize(tz) + + reset = localized.tz_localize(None) + tm.assert_index_equal(reset, idx) + self.assertTrue(reset.tzinfo is None) + def test_series_frame_tz_localize(self): rng = date_range('1/1/2011', periods=100, freq='H') @@ -930,6 +949,29 @@ def test_series_frame_tz_convert(self): ts = Series(1, index=rng) tm.assertRaisesRegexp(TypeError, "Cannot convert tz-naive", ts.tz_convert, 'US/Eastern') + def test_tz_convert_roundtrip(self): + for tz in self.timezones: + idx1 = date_range(start='2014-01-01', end='2014-12-31', freq='M', tz='UTC') + exp1 = date_range(start='2014-01-01', end='2014-12-31', freq='M') + + idx2 = date_range(start='2014-01-01', end='2014-12-31', freq='D', tz='UTC') + exp2 = date_range(start='2014-01-01', end='2014-12-31', freq='D') + + idx3 = date_range(start='2014-01-01', end='2014-03-01', freq='H', tz='UTC') + exp3 = date_range(start='2014-01-01', end='2014-03-01', freq='H') + + idx4 = date_range(start='2014-08-01', end='2014-10-31', freq='T', tz='UTC') + exp4 = date_range(start='2014-08-01', end='2014-10-31', freq='T') + + + for idx, expected in [(idx1, exp1), (idx2, exp2), (idx3, exp3), (idx4, exp4)]: + converted = idx.tz_convert(tz) + reset = converted.tz_convert(None) + tm.assert_index_equal(reset, expected) + self.assertTrue(reset.tzinfo is None) + tm.assert_index_equal(reset, converted.tz_convert('UTC').tz_localize(None)) + + def test_join_utc_convert(self): rng = date_range('1/1/2011', periods=100, freq='H', tz='utc') diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py index 79eaa97d50322..563ab74ad975a 100644 --- a/pandas/tseries/tests/test_tslib.py +++ b/pandas/tseries/tests/test_tslib.py @@ -97,6 +97,33 @@ def test_tz(self): self.assertEqual(conv.nanosecond, 5) self.assertEqual(conv.hour, 19) + def test_tz_localize_roundtrip(self): + for tz in ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/US/Pacific']: + for t in ['2014-02-01 09:00', '2014-07-08 09:00', '2014-11-01 17:00', + '2014-11-05 00:00']: + ts = Timestamp(t) + localized = ts.tz_localize(tz) + self.assertEqual(localized, Timestamp(t, tz=tz)) + + with tm.assertRaises(Exception): + localized.tz_localize(tz) + + reset = localized.tz_localize(None) + self.assertEqual(reset, ts) + self.assertTrue(reset.tzinfo is None) + + def test_tz_convert_roundtrip(self): + for tz in ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/US/Pacific']: + for t in ['2014-02-01 09:00', '2014-07-08 09:00', '2014-11-01 17:00', + '2014-11-05 00:00']: + ts = Timestamp(t, tz='UTC') + converted = ts.tz_convert(tz) + + reset = converted.tz_convert(None) + self.assertEqual(reset, Timestamp(t)) + self.assertTrue(reset.tzinfo is None) + self.assertEqual(reset, converted.tz_convert('UTC').tz_localize(None)) + def test_barely_oob_dts(self): one_us = np.timedelta64(1).astype('timedelta64[us]') diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index b8342baae16bd..3b1a969e17a18 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -373,11 +373,14 @@ class Timestamp(_Timestamp): def tz_localize(self, tz, infer_dst=False): """ - Convert naive Timestamp to local time zone + Convert naive Timestamp to local time zone, or remove + timezone from tz-aware Timestamp. Parameters ---------- - tz : pytz.timezone or dateutil.tz.tzfile + tz : string, pytz.timezone, dateutil.tz.tzfile or None + Time zone for time which Timestamp will be converted to. + None will remove timezone holding local time. infer_dst : boolean, default False Attempt to infer fall dst-transition hours based on order @@ -392,8 +395,13 @@ class Timestamp(_Timestamp): infer_dst=infer_dst)[0] return Timestamp(value, tz=tz) else: - raise Exception('Cannot localize tz-aware Timestamp, use ' - 'tz_convert for conversions') + if tz is None: + # reset tz + value = tz_convert_single(self.value, 'UTC', self.tz) + return Timestamp(value, tz=None) + else: + raise Exception('Cannot localize tz-aware Timestamp, use ' + 'tz_convert for conversions') def tz_convert(self, tz): """ @@ -402,7 +410,9 @@ class Timestamp(_Timestamp): Parameters ---------- - tz : pytz.timezone or dateutil.tz.tzfile + tz : string, pytz.timezone, dateutil.tz.tzfile or None + Time zone for time which Timestamp will be converted to. + None will remove timezone holding UTC time. Returns -------
Closes #7812. Allow `tz_localize(None)` for tz-aware `Timestamp` and `DatetimeIndex` to reset tz. CC @rockg, @nehalecky ``` t = pd.Timestamp('2014-01-01 09:00', tz='Asia/Tokyo') # tz_localize resets tz holding current tz representation t.tz_localize(None) #2014-01-01 09:00:00 # tz_convert reset tz using UTC representation (no changes by this PR) t.tz_convert(None) #2014-01-01 00:00:00 idx = pd.date_range(start='2011-01-01 09:00', freq='H', periods=10, tz='Asia/Tokyo') idx.tz_localize(None) # <class 'pandas.tseries.index.DatetimeIndex' # [2011-01-01 09:00:00, ..., 2011-01-01 18:00:00] # Length: 10, Freq: H, Timezone: None # (no changes by this PR) idx.tz_convert(None) # <class 'pandas.tseries.index.DatetimeIndex'> # [2011-01-01 00:00:00, ..., 2011-01-01 09:00:00] # Length: 10, Freq: H, Timezone: None ```
https://api.github.com/repos/pandas-dev/pandas/pulls/7852
2014-07-26T14:52:42Z
2014-08-05T14:49:29Z
2014-08-05T14:49:29Z
2014-08-07T22:13:11Z
BUG: fix greedy date parsing in read_html
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index a30400322716c..aa6f1ce28a90d 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -106,6 +106,9 @@ API changes See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy +- The ``infer_types`` argument to :func:`~pandas.io.html.read_html` now has no + effect (:issue:`7762`, :issue:`7032`). + .. _whatsnew_0150.cat: @@ -320,6 +323,8 @@ Bug Fixes +- Bug in ``read_html`` where the ``infer_types`` argument forced coercion of + date-likes incorrectly (:issue:`7762`, :issue:`7032`). diff --git a/pandas/io/html.py b/pandas/io/html.py index 5ea6ca36ac764..d9c980b5e88db 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -607,11 +607,6 @@ def _data_to_frame(data, header, index_col, skiprows, infer_types, parse_dates=parse_dates, tupleize_cols=tupleize_cols, thousands=thousands) df = tp.read() - - if infer_types: # TODO: rm this code so infer_types has no effect in 0.14 - df = df.convert_objects(convert_dates='coerce') - else: - df = df.applymap(text_type) return df @@ -757,9 +752,8 @@ def read_html(io, match='.+', flavor=None, header=None, index_col=None, that sequence. Note that a single element sequence means 'skip the nth row' whereas an integer means 'skip n rows'. - infer_types : bool, optional - This option is deprecated in 0.13, an will have no effect in 0.14. It - defaults to ``True``. + infer_types : None, optional + This has no effect since 0.15.0. It is here for backwards compatibility. attrs : dict or None, optional This is a dictionary of attributes that you can pass to use to identify @@ -838,9 +832,7 @@ def read_html(io, match='.+', flavor=None, header=None, index_col=None, pandas.io.parsers.read_csv """ if infer_types is not None: - warnings.warn("infer_types will have no effect in 0.14", FutureWarning) - else: - infer_types = True # TODO: remove effect of this in 0.14 + warnings.warn("infer_types has no effect since 0.15", FutureWarning) # Type check here. We don't want to parse only to fail because of an # invalid value of an integer skiprows. diff --git a/pandas/io/tests/data/wikipedia_states.html b/pandas/io/tests/data/wikipedia_states.html new file mode 100644 index 0000000000000..6765954dd13d1 --- /dev/null +++ b/pandas/io/tests/data/wikipedia_states.html @@ -0,0 +1,1757 @@ +<!DOCTYPE html> +<html lang="en" dir="ltr" class="client-nojs"> +<head> +<meta charset="UTF-8" /> +<title>List of U.S. states and territories by area - Wikipedia, the free encyclopedia</title> +<meta name="generator" content="MediaWiki 1.24wmf14" /> +<link rel="alternate" href="android-app://org.wikipedia/http/en.m.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_area" /> +<link rel="alternate" type="application/x-wiki" title="Edit this page" href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=edit" /> +<link rel="edit" title="Edit this page" href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=edit" /> +<link rel="apple-touch-icon" href="//bits.wikimedia.org/apple-touch/wikipedia.png" /> +<link rel="shortcut icon" href="//bits.wikimedia.org/favicon/wikipedia.ico" /> +<link rel="search" type="application/opensearchdescription+xml" href="/w/opensearch_desc.php" title="Wikipedia (en)" /> +<link rel="EditURI" type="application/rsd+xml" href="//en.wikipedia.org/w/api.php?action=rsd" /> +<link rel="copyright" href="//creativecommons.org/licenses/by-sa/3.0/" /> +<link rel="alternate" type="application/atom+xml" title="Wikipedia Atom feed" href="/w/index.php?title=Special:RecentChanges&amp;feed=atom" /> +<link rel="canonical" href="http://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_area" /> +<link rel="stylesheet" href="//bits.wikimedia.org/en.wikipedia.org/load.php?debug=false&amp;lang=en&amp;modules=ext.gadget.DRN-wizard%2CReferenceTooltips%2Ccharinsert%2CrefToolbar%2Cteahouse%7Cext.rtlcite%2Cwikihiero%7Cext.uls.nojs%7Cext.visualEditor.viewPageTarget.noscript%7Cmediawiki.legacy.commonPrint%2Cshared%7Cmediawiki.skinning.interface%7Cmediawiki.ui.button%7Cskins.vector.styles%7Cwikibase.client.init&amp;only=styles&amp;skin=vector&amp;*" /> +<meta name="ResourceLoaderDynamicStyles" content="" /> +<link rel="stylesheet" href="//bits.wikimedia.org/en.wikipedia.org/load.php?debug=false&amp;lang=en&amp;modules=site&amp;only=styles&amp;skin=vector&amp;*" /> +<style>a:lang(ar),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none} +/* cache key: enwiki:resourceloader:filter:minify-css:7:3904d24a08aa08f6a68dc338f9be277e */</style> +<script src="//bits.wikimedia.org/en.wikipedia.org/load.php?debug=false&amp;lang=en&amp;modules=startup&amp;only=scripts&amp;skin=vector&amp;*"></script> +<script>if(window.mw){ +mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"List_of_U.S._states_and_territories_by_area","wgTitle":"List of U.S. states and territories by area","wgCurRevisionId":614847271,"wgRevisionId":614847271,"wgArticleId":87513,"wgIsArticle":true,"wgIsRedirect":false,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":["Geography of the United States","Lists of states of the United States"],"wgBreakFrames":false,"wgPageContentLanguage":"en","wgPageContentModel":"wikitext","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"dmy","wgMonthNames":["","January","February","March","April","May","June","July","August","September","October","November","December"],"wgMonthNamesShort":["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"wgRelevantPageName":"List_of_U.S._states_and_territories_by_area","wgIsProbablyEditable":true,"wgRestrictionEdit":[],"wgRestrictionMove":[],"wgWikiEditorEnabledModules":{"toolbar":true,"dialogs":true,"hidesig":true,"preview":false,"previewDialog":false,"publish":false},"wgBetaFeaturesFeatures":[],"wgMediaViewerOnClick":true,"wgVisualEditor":{"isPageWatched":false,"magnifyClipIconURL":"//bits.wikimedia.org/static-1.24wmf14/skins/common/images/magnify-clip.png","pageLanguageCode":"en","pageLanguageDir":"ltr","svgMaxSize":2048,"namespacesWithSubpages":{"6":0,"8":0,"1":true,"2":true,"3":true,"4":true,"5":true,"7":true,"9":true,"10":true,"11":true,"12":true,"13":true,"14":true,"15":true,"100":true,"101":true,"102":true,"103":true,"104":true,"105":true,"106":true,"107":true,"108":true,"109":true,"110":true,"111":true,"447":true,"2600":false,"828":true,"829":true}},"wikilove-recipient":"","wikilove-anon":0,"wgGuidedTourHelpGuiderUrl":"Help:Guided tours/guider","wgULSAcceptLanguageList":["en-us"],"wgULSCurrentAutonym":"English","wgFlaggedRevsParams":{"tags":{"status":{"levels":1,"quality":2,"pristine":3}}},"wgStableRevisionId":null,"wgCategoryTreePageCategoryOptions":"{\"mode\":0,\"hideprefix\":20,\"showcount\":true,\"namespaces\":false}","wgNoticeProject":"wikipedia","wgWikibaseItemId":"Q150340"}); +}</script><script>if(window.mw){ +mw.loader.implement("user.options",function($,jQuery){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"editfont":"default","editondblclick":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"math":0,"minordefault":0,"newpageshidepatrolled":0,"nickname":"","norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"rcdays":7,"rclimit":50,"rows":25,"showhiddencats":false,"shownumberswatching":1,"showtoolbar":1,"skin":"vector","stubthreshold":0,"thumbsize":4,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":1,"watchdefault":0,"watchdeletion":0,"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250, +"useeditwarning":1,"prefershttps":1,"flaggedrevssimpleui":1,"flaggedrevsstable":0,"flaggedrevseditdiffs":true,"flaggedrevsviewdiffs":false,"usebetatoolbar":1,"usebetatoolbar-cgd":1,"multimediaviewer-enable":true,"visualeditor-enable":0,"visualeditor-betatempdisable":0,"visualeditor-enable-experimental":0,"visualeditor-enable-language":0,"visualeditor-hidebetawelcome":0,"wikilove-enabled":1,"mathJax":false,"echo-subscriptions-web-page-review":true,"echo-subscriptions-email-page-review":false,"ep_showtoplink":false,"ep_bulkdelorgs":false,"ep_bulkdelcourses":true,"ep_showdyk":true,"echo-subscriptions-web-education-program":true,"echo-subscriptions-email-education-program":false,"echo-notify-show-link":true,"echo-show-alert":true,"echo-email-frequency":0,"echo-email-format":"html","echo-subscriptions-email-system":true,"echo-subscriptions-web-system":true,"echo-subscriptions-email-user-rights":true,"echo-subscriptions-web-user-rights":true,"echo-subscriptions-email-other":false, +"echo-subscriptions-web-other":true,"echo-subscriptions-email-edit-user-talk":false,"echo-subscriptions-web-edit-user-talk":true,"echo-subscriptions-email-reverted":false,"echo-subscriptions-web-reverted":true,"echo-subscriptions-email-article-linked":false,"echo-subscriptions-web-article-linked":false,"echo-subscriptions-email-mention":false,"echo-subscriptions-web-mention":true,"echo-subscriptions-web-edit-thank":true,"echo-subscriptions-email-edit-thank":false,"echo-subscriptions-web-flow-discussion":true,"echo-subscriptions-email-flow-discussion":false,"gettingstarted-task-toolbar-show-intro":true,"uls-preferences":"","language":"en","variant-gan":"gan","variant-iu":"iu","variant-kk":"kk","variant-ku":"ku","variant-shi":"shi","variant-sr":"sr","variant-tg":"tg","variant-uz":"uz","variant-zh":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false, +"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"searchNs100":false,"searchNs101":false,"searchNs108":false,"searchNs109":false,"searchNs118":false,"searchNs119":false,"searchNs446":false,"searchNs447":false,"searchNs710":false,"searchNs711":false,"searchNs828":false,"searchNs829":false,"searchNs2600":false,"gadget-teahouse":1,"gadget-ReferenceTooltips":1,"gadget-DRN-wizard":1,"gadget-charinsert":1,"gadget-refToolbar":1,"gadget-mySandbox":1,"variant":"en"});},{},{});mw.loader.implement("user.tokens",function($,jQuery){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});},{},{}); +/* cache key: enwiki:resourceloader:filter:minify-js:7:ffff827f827051d73171f6b2dc70d368 */ +}</script> +<script>if(window.mw){ +mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax","ext.centralauth.centralautologin","mmv.head","ext.visualEditor.viewPageTarget.init","ext.uls.init","ext.uls.interface","ext.centralNotice.bannerController","skins.vector.js"]); +}</script> +<link rel="dns-prefetch" href="//meta.wikimedia.org" /> +<!--[if lt IE 7]><style type="text/css">body{behavior:url("/w/static-1.24wmf14/skins/Vector/csshover.min.htc")}</style><![endif]--> +</head> +<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-List_of_U_S_states_and_territories_by_area skin-vector action-view vector-animateLayout"> + <div id="mw-page-base" class="noprint"></div> + <div id="mw-head-base" class="noprint"></div> + <div id="content" class="mw-body" role="main"> + <a id="top"></a> + + <div id="mw-js-message" style="display:none;"></div> + <div id="siteNotice"><!-- CentralNotice --></div> + <h1 id="firstHeading" class="firstHeading" lang="en"><span dir="auto">List of U.S. states and territories by area</span></h1> + <div id="bodyContent" class="mw-body-content"> + <div id="siteSub">From Wikipedia, the free encyclopedia</div> + <div id="contentSub"></div> + <div id="jump-to-nav" class="mw-jump"> + Jump to: <a href="#mw-navigation">navigation</a>, <a href="#p-search">search</a> + </div> + <div id="mw-content-text" lang="en" dir="ltr" class="mw-content-ltr"><div class="thumb tright"> +<div class="thumbinner" style="width:222px;"><a href="/wiki/File:Image_shows_the_50_states_by_area-_Check_the_legend_for_more_details-_2014-06-29_05-36.jpg" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/2/28/Image_shows_the_50_states_by_area-_Check_the_legend_for_more_details-_2014-06-29_05-36.jpg/220px-Image_shows_the_50_states_by_area-_Check_the_legend_for_more_details-_2014-06-29_05-36.jpg" width="220" height="126" class="thumbimage" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/2/28/Image_shows_the_50_states_by_area-_Check_the_legend_for_more_details-_2014-06-29_05-36.jpg/330px-Image_shows_the_50_states_by_area-_Check_the_legend_for_more_details-_2014-06-29_05-36.jpg 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/2/28/Image_shows_the_50_states_by_area-_Check_the_legend_for_more_details-_2014-06-29_05-36.jpg/440px-Image_shows_the_50_states_by_area-_Check_the_legend_for_more_details-_2014-06-29_05-36.jpg 2x" data-file-width="1015" data-file-height="580" /></a> +<div class="thumbcaption"> +<div class="magnify"><a href="/wiki/File:Image_shows_the_50_states_by_area-_Check_the_legend_for_more_details-_2014-06-29_05-36.jpg" class="internal" title="Enlarge"><img src="//bits.wikimedia.org/static-1.24wmf14/skins/common/images/magnify-clip.png" width="15" height="11" alt="" /></a></div> +Image shows the 50 states by area. Check the legend for more details.</div> +</div> +</div> +<p>This is a complete <b>list of the <a href="/wiki/U.S._state" title="U.S. state">states of the United States</a> and its major <a href="/wiki/Territories_of_the_United_States" title="Territories of the United States">territories</a></b> ordered by <i>total area</i>, <i>land area</i>, and <i>water area</i>. The water area figures include inland, coastal, <a href="/wiki/Great_Lakes" title="Great Lakes">Great Lakes</a>, and <a href="/wiki/Territorial_waters" title="Territorial waters">territorial waters</a>. Glaciers and intermittent water features are counted as land area.<sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span>[</span>1<span>]</span></a></sup></p> +<p></p> +<div id="toc" class="toc"> +<div id="toctitle"> +<h2>Contents</h2> +</div> +<ul> +<li class="toclevel-1 tocsection-1"><a href="#Area_by_state.2Fterritory"><span class="tocnumber">1</span> <span class="toctext">Area by state/territory</span></a></li> +<li class="toclevel-1 tocsection-2"><a href="#Area_by_division"><span class="tocnumber">2</span> <span class="toctext">Area by division</span></a></li> +<li class="toclevel-1 tocsection-3"><a href="#Area_by_region"><span class="tocnumber">3</span> <span class="toctext">Area by region</span></a></li> +<li class="toclevel-1 tocsection-4"><a href="#See_also"><span class="tocnumber">4</span> <span class="toctext">See also</span></a></li> +<li class="toclevel-1 tocsection-5"><a href="#Notes"><span class="tocnumber">5</span> <span class="toctext">Notes</span></a></li> +<li class="toclevel-1 tocsection-6"><a href="#References"><span class="tocnumber">6</span> <span class="toctext">References</span></a></li> +<li class="toclevel-1 tocsection-7"><a href="#External_links"><span class="tocnumber">7</span> <span class="toctext">External links</span></a></li> +</ul> +</div> +<p></p> +<div style="clear:both;"></div> +<h2><span class="mw-headline" id="Area_by_state.2Fterritory">Area by state/territory</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=edit&amp;section=1" title="Edit section: Area by state/territory">edit</a><span class="mw-editsection-bracket">]</span></span></h2> +<table class="wikitable sortable"> +<tr> +<th></th> +<th colspan="3">Total area<sup id="cite_ref-2010census_2-0" class="reference"><a href="#cite_note-2010census-2"><span>[</span>2<span>]</span></a></sup></th> +<th colspan="4">Land area<sup id="cite_ref-2010census_2-1" class="reference"><a href="#cite_note-2010census-2"><span>[</span>2<span>]</span></a></sup></th> +<th colspan="4">Water<sup id="cite_ref-2010census_2-2" class="reference"><a href="#cite_note-2010census-2"><span>[</span>2<span>]</span></a></sup></th> +</tr> +<tr> +<th>State/territory</th> +<th>Rank</th> +<th>sq mi</th> +<th>km²</th> +<th>Rank</th> +<th>sq mi</th> +<th>km²</th> +<th>&#160;% land</th> +<th>sq mi</th> +<th>km²</th> +<th>&#160;% water</th> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Flag_of_Alaska.svg/21px-Flag_of_Alaska.svg.png" width="21" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Flag_of_Alaska.svg/33px-Flag_of_Alaska.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Flag_of_Alaska.svg/43px-Flag_of_Alaska.svg.png 2x" data-file-width="1416" data-file-height="1000" />&#160;</span><a href="/wiki/Alaska" title="Alaska">Alaska</a></td> +<td align="center"><span style="" class="sortkey">!C&#160;</span>1</td> +<td align="right">665,384.04</td> +<td align="right">1,723,337</td> +<td align="center"><span style="" class="sortkey">!C&#160;</span>1</td> +<td align="right">570,640.95</td> +<td align="right">1,477,953</td> +<td align="right"><span style="display:none" class="sortkey">7001857600000000000</span>85.76%</td> +<td align="right">94,743.10</td> +<td align="right">245,384</td> +<td align="right"><span style="display:none" class="sortkey">7001142400000000000</span>14.24%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Flag_of_Texas.svg/23px-Flag_of_Texas.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Flag_of_Texas.svg/35px-Flag_of_Texas.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Flag_of_Texas.svg/45px-Flag_of_Texas.svg.png 2x" data-file-width="1080" data-file-height="720" />&#160;</span><a href="/wiki/Texas" title="Texas">Texas</a></td> +<td align="center"><span style="" class="sortkey">!B9993068528194&#160;</span>2</td> +<td align="right">268,596.46</td> +<td align="right">695,662</td> +<td align="center"><span style="" class="sortkey">!B9993068528194&#160;</span>2</td> +<td align="right">261,231.71</td> +<td align="right">676,587</td> +<td align="right"><span style="display:none" class="sortkey">7001972600000000000</span>97.26%</td> +<td align="right">7,364.75</td> +<td align="right">19,075</td> +<td align="right"><span style="display:none" class="sortkey">7000274000000000000</span>2.74%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/0/01/Flag_of_California.svg/23px-Flag_of_California.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/0/01/Flag_of_California.svg/35px-Flag_of_California.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/0/01/Flag_of_California.svg/45px-Flag_of_California.svg.png 2x" data-file-width="900" data-file-height="600" />&#160;</span><a href="/wiki/California" title="California">California</a></td> +<td align="center"><span style="" class="sortkey">!B9989013877113&#160;</span>3</td> +<td align="right">163,694.74</td> +<td align="right">423,967</td> +<td align="center"><span style="" class="sortkey">!B9989013877113&#160;</span>3</td> +<td align="right">155,779.22</td> +<td align="right">403,466</td> +<td align="right"><span style="display:none" class="sortkey">7001951600000000000</span>95.16%</td> +<td align="right">7,915.52</td> +<td align="right">20,501</td> +<td align="right"><span style="display:none" class="sortkey">7000484000000000000</span>4.84%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/c/cb/Flag_of_Montana.svg/23px-Flag_of_Montana.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/c/cb/Flag_of_Montana.svg/35px-Flag_of_Montana.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/c/cb/Flag_of_Montana.svg/45px-Flag_of_Montana.svg.png 2x" data-file-width="615" data-file-height="410" />&#160;</span><a href="/wiki/Montana" title="Montana">Montana</a></td> +<td align="center"><span style="" class="sortkey">!B9986137056388&#160;</span>4</td> +<td align="right">147,039.71</td> +<td align="right">380,831</td> +<td align="center"><span style="" class="sortkey">!B9986137056388&#160;</span>4</td> +<td align="right">145,545.80</td> +<td align="right">376,962</td> +<td align="right"><span style="display:none" class="sortkey">7001989800000000000</span>98.98%</td> +<td align="right">1,493.91</td> +<td align="right">3,869</td> +<td align="right"><span style="display:none" class="sortkey">7000102000000000000</span>1.02%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Flag_of_New_Mexico.svg/23px-Flag_of_New_Mexico.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Flag_of_New_Mexico.svg/35px-Flag_of_New_Mexico.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Flag_of_New_Mexico.svg/45px-Flag_of_New_Mexico.svg.png 2x" data-file-width="1200" data-file-height="800" />&#160;</span><a href="/wiki/New_Mexico" title="New Mexico">New Mexico</a></td> +<td align="center"><span style="" class="sortkey">!B9983905620875&#160;</span>5</td> +<td align="right">121,590.30</td> +<td align="right">314,917</td> +<td align="center"><span style="" class="sortkey">!B9983905620875&#160;</span>5</td> +<td align="right">121,298.15</td> +<td align="right">314,161</td> +<td align="right"><span style="display:none" class="sortkey">7001997600000000000</span>99.76%</td> +<td align="right">292.15</td> +<td align="right">757</td> +<td align="right"><span style="display:none" class="sortkey">6999240000000000000</span>0.24%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Flag_of_Arizona.svg/23px-Flag_of_Arizona.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Flag_of_Arizona.svg/35px-Flag_of_Arizona.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Flag_of_Arizona.svg/45px-Flag_of_Arizona.svg.png 2x" data-file-width="900" data-file-height="600" />&#160;</span><a href="/wiki/Arizona" title="Arizona">Arizona</a></td> +<td align="center"><span style="" class="sortkey">!B9982082405307&#160;</span>6</td> +<td align="right">113,990.30</td> +<td align="right">295,234</td> +<td align="center"><span style="" class="sortkey">!B9982082405307&#160;</span>6</td> +<td align="right">113,594.08</td> +<td align="right">294,207</td> +<td align="right"><span style="display:none" class="sortkey">7001996500000000000</span>99.65%</td> +<td align="right">396.22</td> +<td align="right">1,026</td> +<td align="right"><span style="display:none" class="sortkey">6999350000000000000</span>0.35%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Flag_of_Nevada.svg/23px-Flag_of_Nevada.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Flag_of_Nevada.svg/35px-Flag_of_Nevada.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Flag_of_Nevada.svg/45px-Flag_of_Nevada.svg.png 2x" data-file-width="750" data-file-height="500" />&#160;</span><a href="/wiki/Nevada" title="Nevada">Nevada</a></td> +<td align="center"><span style="" class="sortkey">!B9980540898509&#160;</span>7</td> +<td align="right">110,571.82</td> +<td align="right">286,380</td> +<td align="center"><span style="" class="sortkey">!B9980540898509&#160;</span>7</td> +<td align="right">109,781.18</td> +<td align="right">284,332</td> +<td align="right"><span style="display:none" class="sortkey">7001992800000000000</span>99.28%</td> +<td align="right">790.65</td> +<td align="right">2,048</td> +<td align="right"><span style="display:none" class="sortkey">6999720000000000000</span>0.72%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/4/46/Flag_of_Colorado.svg/23px-Flag_of_Colorado.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/4/46/Flag_of_Colorado.svg/35px-Flag_of_Colorado.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/4/46/Flag_of_Colorado.svg/45px-Flag_of_Colorado.svg.png 2x" data-file-width="1800" data-file-height="1200" />&#160;</span><a href="/wiki/Colorado" title="Colorado">Colorado</a></td> +<td align="center"><span style="" class="sortkey">!B9979205584583&#160;</span>8</td> +<td align="right">104,093.67</td> +<td align="right">269,601</td> +<td align="center"><span style="" class="sortkey">!B9979205584583&#160;</span>8</td> +<td align="right">103,641.89</td> +<td align="right">268,431</td> +<td align="right"><span style="display:none" class="sortkey">7001995700000099999</span>99.57%</td> +<td align="right">451.78</td> +<td align="right">1,170</td> +<td align="right"><span style="display:none" class="sortkey">6999430000000000000</span>0.43%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/b/b9/Flag_of_Oregon.svg/23px-Flag_of_Oregon.svg.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/b/b9/Flag_of_Oregon.svg/35px-Flag_of_Oregon.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/b/b9/Flag_of_Oregon.svg/46px-Flag_of_Oregon.svg.png 2x" data-file-width="750" data-file-height="450" />&#160;</span><a href="/wiki/Oregon" title="Oregon">Oregon</a></td> +<td align="center"><span style="" class="sortkey">!B9978027754226&#160;</span>9</td> +<td align="right">98,378.54</td> +<td align="right">254,799</td> +<td align="center"><span style="" class="sortkey">!B9976974149070&#160;</span>10</td> +<td align="right">95,988.01</td> +<td align="right">248,608</td> +<td align="right"><span style="display:none" class="sortkey">7001975700000099999</span>97.57%</td> +<td align="right">2,390.53</td> +<td align="right">6,191</td> +<td align="right"><span style="display:none" class="sortkey">7000243000000000000</span>2.43%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyoming.svg/22px-Flag_of_Wyoming.svg.png" width="22" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyoming.svg/33px-Flag_of_Wyoming.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Flag_of_Wyoming.svg/43px-Flag_of_Wyoming.svg.png 2x" data-file-width="1000" data-file-height="700" />&#160;</span><a href="/wiki/Wyoming" title="Wyoming">Wyoming</a></td> +<td align="center"><span style="" class="sortkey">!B9976974149070&#160;</span>10</td> +<td align="right">97,813.01</td> +<td align="right">253,335</td> +<td align="center"><span style="" class="sortkey">!B9978027754226&#160;</span>9</td> +<td align="right">97,093.14</td> +<td align="right">251,470</td> +<td align="right"><span style="display:none" class="sortkey">7001992600000000000</span>99.26%</td> +<td align="right">719.87</td> +<td align="right">1,864</td> +<td align="right"><span style="display:none" class="sortkey">6999740000000000000</span>0.74%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Flag_of_Michigan.svg/23px-Flag_of_Michigan.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Flag_of_Michigan.svg/35px-Flag_of_Michigan.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Flag_of_Michigan.svg/45px-Flag_of_Michigan.svg.png 2x" data-file-width="685" data-file-height="457" />&#160;</span><a href="/wiki/Michigan" title="Michigan">Michigan</a></td> +<td align="center"><span style="" class="sortkey">!B9976021047272&#160;</span>11</td> +<td align="right">96,713.51</td> +<td align="right">250,487</td> +<td align="center"><span style="" class="sortkey">!B9969089575466&#160;</span>22</td> +<td align="right">56,538.90</td> +<td align="right">146,435</td> +<td align="right"><span style="display:none" class="sortkey">7001584600000000000</span>58.46%</td> +<td align="right">40,174.61</td> +<td align="right">104,052</td> +<td align="right"><span style="display:none" class="sortkey">7001415400000000000</span>41.54%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/b/b9/Flag_of_Minnesota.svg/23px-Flag_of_Minnesota.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/b/b9/Flag_of_Minnesota.svg/35px-Flag_of_Minnesota.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/b/b9/Flag_of_Minnesota.svg/46px-Flag_of_Minnesota.svg.png 2x" data-file-width="500" data-file-height="318" />&#160;</span><a href="/wiki/Minnesota" title="Minnesota">Minnesota</a></td> +<td align="center"><span style="" class="sortkey">!B9975150933502&#160;</span>12</td> +<td align="right">86,935.83</td> +<td align="right">225,163</td> +<td align="center"><span style="" class="sortkey">!B9973609426703&#160;</span>14</td> +<td align="right">79,626.74</td> +<td align="right">206,232</td> +<td align="right"><span style="display:none" class="sortkey">7001915900000000000</span>91.59%</td> +<td align="right">7,309.09</td> +<td align="right">18,930</td> +<td align="right"><span style="display:none" class="sortkey">7000841000000000000</span>8.41%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/7/7f/Flag_of_Utah.png/23px-Flag_of_Utah.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/7/7f/Flag_of_Utah.png/35px-Flag_of_Utah.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/7/7f/Flag_of_Utah.png/46px-Flag_of_Utah.png 2x" data-file-width="2875" data-file-height="1725" />&#160;</span><a href="/wiki/Utah" title="Utah">Utah</a></td> +<td align="center"><span style="" class="sortkey">!B9974350506425&#160;</span>13</td> +<td align="right">84,896.88</td> +<td align="right">219,882</td> +<td align="center"><span style="" class="sortkey">!B9975150933502&#160;</span>12</td> +<td align="right">82,169.62</td> +<td align="right">212,818</td> +<td align="right"><span style="display:none" class="sortkey">7001967900000000000</span>96.79%</td> +<td align="right">2,727.26</td> +<td align="right">7,064</td> +<td align="right"><span style="display:none" class="sortkey">7000321000000000000</span>3.21%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Flag_of_Idaho.svg/19px-Flag_of_Idaho.svg.png" width="19" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Flag_of_Idaho.svg/29px-Flag_of_Idaho.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Flag_of_Idaho.svg/38px-Flag_of_Idaho.svg.png 2x" data-file-width="660" data-file-height="520" />&#160;</span><a href="/wiki/Idaho" title="Idaho">Idaho</a></td> +<td align="center"><span style="" class="sortkey">!B9973609426703&#160;</span>14</td> +<td align="right">83,568.95</td> +<td align="right">216,443</td> +<td align="center"><span style="" class="sortkey">!B9976021047272&#160;</span>11</td> +<td align="right">82,643.12</td> +<td align="right">214,045</td> +<td align="right"><span style="display:none" class="sortkey">7001988900000000000</span>98.89%</td> +<td align="right">925.83</td> +<td align="right">2,398</td> +<td align="right"><span style="display:none" class="sortkey">7000111000000000000</span>1.11%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/d/da/Flag_of_Kansas.svg/23px-Flag_of_Kansas.svg.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/d/da/Flag_of_Kansas.svg/35px-Flag_of_Kansas.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/d/da/Flag_of_Kansas.svg/46px-Flag_of_Kansas.svg.png 2x" data-file-width="5400" data-file-height="3240" />&#160;</span><a href="/wiki/Kansas" title="Kansas">Kansas</a></td> +<td align="center"><span style="" class="sortkey">!B9972919497988&#160;</span>15</td> +<td align="right">82,278.36</td> +<td align="right">213,100</td> +<td align="center"><span style="" class="sortkey">!B9974350506425&#160;</span>13</td> +<td align="right">81,758.72</td> +<td align="right">211,754</td> +<td align="right"><span style="display:none" class="sortkey">7001993700000000000</span>99.37%</td> +<td align="right">519.64</td> +<td align="right">1,346</td> +<td align="right"><span style="display:none" class="sortkey">6999630000000000000</span>0.63%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/4/4d/Flag_of_Nebraska.svg/23px-Flag_of_Nebraska.svg.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/4/4d/Flag_of_Nebraska.svg/35px-Flag_of_Nebraska.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/4/4d/Flag_of_Nebraska.svg/46px-Flag_of_Nebraska.svg.png 2x" data-file-width="750" data-file-height="450" />&#160;</span><a href="/wiki/Nebraska" title="Nebraska">Nebraska</a></td> +<td align="center"><span style="" class="sortkey">!B9972274112777&#160;</span>16</td> +<td align="right">77,347.81</td> +<td align="right">200,330</td> +<td align="center"><span style="" class="sortkey">!B9972919497988&#160;</span>15</td> +<td align="right">76,824.17</td> +<td align="right">198,974</td> +<td align="right"><span style="display:none" class="sortkey">7001993200000099999</span>99.32%</td> +<td align="right">523.64</td> +<td align="right">1,356</td> +<td align="right"><span style="display:none" class="sortkey">6999680000000000000</span>0.68%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Flag_of_South_Dakota.svg/23px-Flag_of_South_Dakota.svg.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Flag_of_South_Dakota.svg/35px-Flag_of_South_Dakota.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Flag_of_South_Dakota.svg/46px-Flag_of_South_Dakota.svg.png 2x" data-file-width="720" data-file-height="450" />&#160;</span><a href="/wiki/South_Dakota" title="South Dakota">South Dakota</a></td> +<td align="center"><span style="" class="sortkey">!B9971667866559&#160;</span>17</td> +<td align="right">77,115.68</td> +<td align="right">199,729</td> +<td align="center"><span style="" class="sortkey">!B9972274112777&#160;</span>16</td> +<td align="right">75,811.00</td> +<td align="right">196,350</td> +<td align="right"><span style="display:none" class="sortkey">7001983100000000000</span>98.31%</td> +<td align="right">1,304.68</td> +<td align="right">3,379</td> +<td align="right"><span style="display:none" class="sortkey">7000169000000000000</span>1.69%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/5/54/Flag_of_Washington.svg/23px-Flag_of_Washington.svg.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/5/54/Flag_of_Washington.svg/35px-Flag_of_Washington.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/5/54/Flag_of_Washington.svg/46px-Flag_of_Washington.svg.png 2x" data-file-width="1106" data-file-height="658" />&#160;</span><a href="/wiki/Washington_(state)" title="Washington (state)">Washington</a></td> +<td align="center"><span style="" class="sortkey">!B9971096282421&#160;</span>18</td> +<td align="right">71,297.95</td> +<td align="right">184,661</td> +<td align="center"><span style="" class="sortkey">!B9970042677264&#160;</span>20</td> +<td align="right">66,455.52</td> +<td align="right">172,119</td> +<td align="right"><span style="display:none" class="sortkey">7001932100000099999</span>93.21%</td> +<td align="right">4,842.43</td> +<td align="right">12,542</td> +<td align="right"><span style="display:none" class="sortkey">7000679000000000000</span>6.79%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/e/ee/Flag_of_North_Dakota.svg/20px-Flag_of_North_Dakota.svg.png" width="20" height="16" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/e/ee/Flag_of_North_Dakota.svg/30px-Flag_of_North_Dakota.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/e/ee/Flag_of_North_Dakota.svg/40px-Flag_of_North_Dakota.svg.png 2x" data-file-width="575" data-file-height="450" />&#160;</span><a href="/wiki/North_Dakota" title="North Dakota">North Dakota</a></td> +<td align="center"><span style="" class="sortkey">!B9970555610208&#160;</span>19</td> +<td align="right">70,698.32</td> +<td align="right">183,108</td> +<td align="center"><span style="" class="sortkey">!B9971667866559&#160;</span>17</td> +<td align="right">69,000.80</td> +<td align="right">178,711</td> +<td align="right"><span style="display:none" class="sortkey">7001976000000000000</span>97.60%</td> +<td align="right">1,697.52</td> +<td align="right">4,397</td> +<td align="right"><span style="display:none" class="sortkey">7000240000000000000</span>2.40%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Flag_of_Oklahoma.svg/23px-Flag_of_Oklahoma.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Flag_of_Oklahoma.svg/35px-Flag_of_Oklahoma.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Flag_of_Oklahoma.svg/45px-Flag_of_Oklahoma.svg.png 2x" data-file-width="675" data-file-height="450" />&#160;</span><a href="/wiki/Oklahoma" title="Oklahoma">Oklahoma</a></td> +<td align="center"><span style="" class="sortkey">!B9970042677264&#160;</span>20</td> +<td align="right">69,898.87</td> +<td align="right">181,037</td> +<td align="center"><span style="" class="sortkey">!B9970555610208&#160;</span>19</td> +<td align="right">68,594.92</td> +<td align="right">177,660</td> +<td align="right"><span style="display:none" class="sortkey">7001981300000000000</span>98.13%</td> +<td align="right">1,303.95</td> +<td align="right">3,377</td> +<td align="right"><span style="display:none" class="sortkey">7000187000000000000</span>1.87%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Flag_of_Missouri.svg/23px-Flag_of_Missouri.svg.png" width="23" height="13" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Flag_of_Missouri.svg/35px-Flag_of_Missouri.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Flag_of_Missouri.svg/46px-Flag_of_Missouri.svg.png 2x" data-file-width="2400" data-file-height="1400" />&#160;</span><a href="/wiki/Missouri" title="Missouri">Missouri</a></td> +<td align="center"><span style="" class="sortkey">!B9969554775622&#160;</span>21</td> +<td align="right">69,706.99</td> +<td align="right">180,540</td> +<td align="center"><span style="" class="sortkey">!B9971096282421&#160;</span>18</td> +<td align="right">68,741.52</td> +<td align="right">178,040</td> +<td align="right"><span style="display:none" class="sortkey">7001986100000000000</span>98.61%</td> +<td align="right">965.47</td> +<td align="right">2,501</td> +<td align="right"><span style="display:none" class="sortkey">7000138990000099999</span>1.39%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Flag_of_Florida.svg/23px-Flag_of_Florida.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Flag_of_Florida.svg/35px-Flag_of_Florida.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Flag_of_Florida.svg/45px-Flag_of_Florida.svg.png 2x" data-file-width="750" data-file-height="500" />&#160;</span><a href="/wiki/Florida" title="Florida">Florida</a></td> +<td align="center"><span style="" class="sortkey">!B9969089575466&#160;</span>22</td> +<td align="right">65,757.70</td> +<td align="right">170,312</td> +<td align="center"><span style="" class="sortkey">!B9967419034619&#160;</span>26</td> +<td align="right">53,624.76</td> +<td align="right">138,887</td> +<td align="right"><span style="display:none" class="sortkey">7001815500000000000</span>81.55%</td> +<td align="right">12,132.94</td> +<td align="right">31,424</td> +<td align="right"><span style="display:none" class="sortkey">7001184500000000000</span>18.45%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/2/22/Flag_of_Wisconsin.svg/23px-Flag_of_Wisconsin.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/2/22/Flag_of_Wisconsin.svg/35px-Flag_of_Wisconsin.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/2/22/Flag_of_Wisconsin.svg/45px-Flag_of_Wisconsin.svg.png 2x" data-file-width="675" data-file-height="450" />&#160;</span><a href="/wiki/Wisconsin" title="Wisconsin">Wisconsin</a></td> +<td align="center"><span style="" class="sortkey">!B9968645057840&#160;</span>23</td> +<td align="right">65,496.38</td> +<td align="right">169,635</td> +<td align="center"><span style="" class="sortkey">!B9967811241751&#160;</span>25</td> +<td align="right">54,157.80</td> +<td align="right">140,268</td> +<td align="right"><span style="display:none" class="sortkey">7001826900000000000</span>82.69%</td> +<td align="right">11,338.57</td> +<td align="right">29,367</td> +<td align="right"><span style="display:none" class="sortkey">7001173109999900000</span>17.31%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/5/54/Flag_of_Georgia_%28U.S._state%29.svg/23px-Flag_of_Georgia_%28U.S._state%29.svg.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/5/54/Flag_of_Georgia_%28U.S._state%29.svg/35px-Flag_of_Georgia_%28U.S._state%29.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/5/54/Flag_of_Georgia_%28U.S._state%29.svg/46px-Flag_of_Georgia_%28U.S._state%29.svg.png 2x" data-file-width="6912" data-file-height="4320" />&#160;</span><a href="/wiki/Georgia_(U.S._state)" title="Georgia (U.S. state)">Georgia</a></td> +<td align="center"><span style="" class="sortkey">!B9968219461696&#160;</span>24</td> +<td align="right">59,425.15</td> +<td align="right">153,910</td> +<td align="center"><span style="" class="sortkey">!B9969554775622&#160;</span>21</td> +<td align="right">57,513.49</td> +<td align="right">148,959</td> +<td align="right"><span style="display:none" class="sortkey">7001967800000000000</span>96.78%</td> +<td align="right">1,911.66</td> +<td align="right">4,951</td> +<td align="right"><span style="display:none" class="sortkey">7000322000000000000</span>3.22%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/0/01/Flag_of_Illinois.svg/23px-Flag_of_Illinois.svg.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/0/01/Flag_of_Illinois.svg/35px-Flag_of_Illinois.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/0/01/Flag_of_Illinois.svg/46px-Flag_of_Illinois.svg.png 2x" data-file-width="778" data-file-height="460" />&#160;</span><a href="/wiki/Illinois" title="Illinois">Illinois</a></td> +<td align="center"><span style="" class="sortkey">!B9967811241751&#160;</span>25</td> +<td align="right">57,913.55</td> +<td align="right">149,995</td> +<td align="center"><span style="" class="sortkey">!B9968219461696&#160;</span>24</td> +<td align="right">55,518.93</td> +<td align="right">143,793</td> +<td align="right"><span style="display:none" class="sortkey">7001958700000000000</span>95.87%</td> +<td align="right">2,394.62</td> +<td align="right">6,202</td> +<td align="right"><span style="display:none" class="sortkey">7000413000000000000</span>4.13%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Flag_of_Iowa.svg/22px-Flag_of_Iowa.svg.png" width="22" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Flag_of_Iowa.svg/34px-Flag_of_Iowa.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Flag_of_Iowa.svg/44px-Flag_of_Iowa.svg.png 2x" data-file-width="670" data-file-height="459" />&#160;</span><a href="/wiki/Iowa" title="Iowa">Iowa</a></td> +<td align="center"><span style="" class="sortkey">!B9967419034619&#160;</span>26</td> +<td align="right">56,272.81</td> +<td align="right">145,746</td> +<td align="center"><span style="" class="sortkey">!B9968645057840&#160;</span>23</td> +<td align="right">55,857.13</td> +<td align="right">144,669</td> +<td align="right"><span style="display:none" class="sortkey">7001992600000000000</span>99.26%</td> +<td align="right">415.68</td> +<td align="right">1,077</td> +<td align="right"><span style="display:none" class="sortkey">6999740000000000000</span>0.74%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Flag_of_New_York.svg/23px-Flag_of_New_York.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Flag_of_New_York.svg/35px-Flag_of_New_York.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Flag_of_New_York.svg/46px-Flag_of_New_York.svg.png 2x" data-file-width="900" data-file-height="450" />&#160;</span><a href="/wiki/New_York" title="New York">New York</a></td> +<td align="center"><span style="" class="sortkey">!B9967041631339&#160;</span>27</td> +<td align="right">54,554.98</td> +<td align="right">141,297</td> +<td align="center"><span style="" class="sortkey">!B9965988026183&#160;</span>30</td> +<td align="right">47,126.40</td> +<td align="right">122,057</td> +<td align="right"><span style="display:none" class="sortkey">7001863800000000000</span>86.38%</td> +<td align="right">7,428.58</td> +<td align="right">19,240</td> +<td align="right"><span style="display:none" class="sortkey">7001136200000099999</span>13.62%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Flag_of_North_Carolina.svg/23px-Flag_of_North_Carolina.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Flag_of_North_Carolina.svg/35px-Flag_of_North_Carolina.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Flag_of_North_Carolina.svg/45px-Flag_of_North_Carolina.svg.png 2x" data-file-width="750" data-file-height="500" />&#160;</span><a href="/wiki/North_Carolina" title="North Carolina">North Carolina</a></td> +<td align="center"><span style="" class="sortkey">!B9966677954898&#160;</span>28</td> +<td align="right">53,819.16</td> +<td align="right">139,391</td> +<td align="center"><span style="" class="sortkey">!B9966327041700&#160;</span>29</td> +<td align="right">48,617.91</td> +<td align="right">125,920</td> +<td align="right"><span style="display:none" class="sortkey">7001903400000000000</span>90.34%</td> +<td align="right">5,201.25</td> +<td align="right">13,471</td> +<td align="right"><span style="display:none" class="sortkey">7000966000000000000</span>9.66%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Flag_of_Arkansas.svg/23px-Flag_of_Arkansas.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Flag_of_Arkansas.svg/35px-Flag_of_Arkansas.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Flag_of_Arkansas.svg/45px-Flag_of_Arkansas.svg.png 2x" data-file-width="450" data-file-height="300" />&#160;</span><a href="/wiki/Arkansas" title="Arkansas">Arkansas</a></td> +<td align="center"><span style="" class="sortkey">!B9966327041700&#160;</span>29</td> +<td align="right">53,178.55</td> +<td align="right">137,732</td> +<td align="center"><span style="" class="sortkey">!B9967041631339&#160;</span>27</td> +<td align="right">52,035.48</td> +<td align="right">134,771</td> +<td align="right"><span style="display:none" class="sortkey">7001978500000000000</span>97.85%</td> +<td align="right">1,143.07</td> +<td align="right">2,961</td> +<td align="right"><span style="display:none" class="sortkey">7000215000000000000</span>2.15%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/5/5c/Flag_of_Alabama.svg/23px-Flag_of_Alabama.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/5/5c/Flag_of_Alabama.svg/35px-Flag_of_Alabama.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/5/5c/Flag_of_Alabama.svg/45px-Flag_of_Alabama.svg.png 2x" data-file-width="600" data-file-height="400" />&#160;</span><a href="/wiki/Alabama" title="Alabama">Alabama</a></td> +<td align="center"><span style="" class="sortkey">!B9965988026183&#160;</span>30</td> +<td align="right">52,420.07</td> +<td align="right">135,767</td> +<td align="center"><span style="" class="sortkey">!B9966677954898&#160;</span>28</td> +<td align="right">50,645.33</td> +<td align="right">131,171</td> +<td align="right"><span style="display:none" class="sortkey">7001966100000000000</span>96.61%</td> +<td align="right">1,774.74</td> +<td align="right">4,597</td> +<td align="right"><span style="display:none" class="sortkey">7000339000000000000</span>3.39%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Flag_of_Louisiana.svg/23px-Flag_of_Louisiana.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Flag_of_Louisiana.svg/35px-Flag_of_Louisiana.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Flag_of_Louisiana.svg/46px-Flag_of_Louisiana.svg.png 2x" data-file-width="990" data-file-height="630" />&#160;</span><a href="/wiki/Louisiana" title="Louisiana">Louisiana</a></td> +<td align="center"><span style="" class="sortkey">!B9965660127955&#160;</span>31</td> +<td align="right">52,378.13</td> +<td align="right">135,659</td> +<td align="center"><span style="" class="sortkey">!B9965034924385&#160;</span>33</td> +<td align="right">43,203.90</td> +<td align="right">111,898</td> +<td align="right"><span style="display:none" class="sortkey">7001824800000000000</span>82.48%</td> +<td align="right">9,174.23</td> +<td align="right">23,761</td> +<td align="right"><span style="display:none" class="sortkey">7001175200000000000</span>17.52%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/4/42/Flag_of_Mississippi.svg/23px-Flag_of_Mississippi.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/4/42/Flag_of_Mississippi.svg/35px-Flag_of_Mississippi.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/4/42/Flag_of_Mississippi.svg/45px-Flag_of_Mississippi.svg.png 2x" data-file-width="900" data-file-height="600" />&#160;</span><a href="/wiki/Mississippi" title="Mississippi">Mississippi</a></td> +<td align="center"><span style="" class="sortkey">!B9965342640972&#160;</span>32</td> +<td align="right">48,431.78</td> +<td align="right">125,438</td> +<td align="center"><span style="" class="sortkey">!B9965660127955&#160;</span>31</td> +<td align="right">46,923.27</td> +<td align="right">121,531</td> +<td align="right"><span style="display:none" class="sortkey">7001968900000000000</span>96.89%</td> +<td align="right">1,508.51</td> +<td align="right">3,907</td> +<td align="right"><span style="display:none" class="sortkey">7000311000000000000</span>3.11%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Flag_of_Pennsylvania.svg/23px-Flag_of_Pennsylvania.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Flag_of_Pennsylvania.svg/35px-Flag_of_Pennsylvania.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Flag_of_Pennsylvania.svg/45px-Flag_of_Pennsylvania.svg.png 2x" data-file-width="675" data-file-height="450" />&#160;</span><a href="/wiki/Pennsylvania" title="Pennsylvania">Pennsylvania</a></td> +<td align="center"><span style="" class="sortkey">!B9965034924385&#160;</span>33</td> +<td align="right">46,054.35</td> +<td align="right">119,280</td> +<td align="center"><span style="" class="sortkey">!B9965342640972&#160;</span>32</td> +<td align="right">44,742.70</td> +<td align="right">115,883</td> +<td align="right"><span style="display:none" class="sortkey">7001971500000000000</span>97.15%</td> +<td align="right">1,311.64</td> +<td align="right">3,397</td> +<td align="right"><span style="display:none" class="sortkey">7000285000000000000</span>2.85%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Flag_of_Ohio.svg/23px-Flag_of_Ohio.svg.png" width="23" height="14" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Flag_of_Ohio.svg/35px-Flag_of_Ohio.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Flag_of_Ohio.svg/46px-Flag_of_Ohio.svg.png 2x" data-file-width="520" data-file-height="320" />&#160;</span><a href="/wiki/Ohio" title="Ohio">Ohio</a></td> +<td align="center"><span style="" class="sortkey">!B9964736394753&#160;</span>34</td> +<td align="right">44,825.58</td> +<td align="right">116,098</td> +<td align="center"><span style="" class="sortkey">!B9964446519385&#160;</span>35</td> +<td align="right">40,860.69</td> +<td align="right">105,829</td> +<td align="right"><span style="display:none" class="sortkey">7001911500000000000</span>91.15%</td> +<td align="right">3,964.89</td> +<td align="right">10,269</td> +<td align="right"><span style="display:none" class="sortkey">7000885000000000000</span>8.85%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/4/47/Flag_of_Virginia.svg/22px-Flag_of_Virginia.svg.png" width="22" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/4/47/Flag_of_Virginia.svg/34px-Flag_of_Virginia.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/4/47/Flag_of_Virginia.svg/44px-Flag_of_Virginia.svg.png 2x" data-file-width="670" data-file-height="460" />&#160;</span><a href="/wiki/Virginia" title="Virginia">Virginia</a></td> +<td align="center"><span style="" class="sortkey">!B9964446519385&#160;</span>35</td> +<td align="right">42,774.93</td> +<td align="right">110,787</td> +<td align="center"><span style="" class="sortkey">!B9964164810615&#160;</span>36</td> +<td align="right">39,490.09</td> +<td align="right">102,279</td> +<td align="right"><span style="display:none" class="sortkey">7001923200000099999</span>92.32%</td> +<td align="right">3,284.84</td> +<td align="right">8,508</td> +<td align="right"><span style="display:none" class="sortkey">7000768000000000000</span>7.68%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Flag_of_Tennessee.svg/23px-Flag_of_Tennessee.svg.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Flag_of_Tennessee.svg/35px-Flag_of_Tennessee.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Flag_of_Tennessee.svg/46px-Flag_of_Tennessee.svg.png 2x" data-file-width="500" data-file-height="300" />&#160;</span><a href="/wiki/Tennessee" title="Tennessee">Tennessee</a></td> +<td align="center"><span style="" class="sortkey">!B9964164810615&#160;</span>36</td> +<td align="right">42,144.25</td> +<td align="right">109,153</td> +<td align="center"><span style="" class="sortkey">!B9964736394753&#160;</span>34</td> +<td align="right">41,234.90</td> +<td align="right">106,798</td> +<td align="right"><span style="display:none" class="sortkey">7001978400000000000</span>97.84%</td> +<td align="right">909.36</td> +<td align="right">2,355</td> +<td align="right"><span style="display:none" class="sortkey">7000216000000000000</span>2.16%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Flag_of_Kentucky.svg/23px-Flag_of_Kentucky.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Flag_of_Kentucky.svg/35px-Flag_of_Kentucky.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Flag_of_Kentucky.svg/46px-Flag_of_Kentucky.svg.png 2x" data-file-width="950" data-file-height="500" />&#160;</span><a href="/wiki/Kentucky" title="Kentucky">Kentucky</a></td> +<td align="center"><span style="" class="sortkey">!B9963890820873&#160;</span>37</td> +<td align="right">40,407.80</td> +<td align="right">104,656</td> +<td align="center"><span style="" class="sortkey">!B9963890820873&#160;</span>37</td> +<td align="right">39,486.34</td> +<td align="right">102,269</td> +<td align="right"><span style="display:none" class="sortkey">7001977200000000000</span>97.72%</td> +<td align="right">921.46</td> +<td align="right">2,387</td> +<td align="right"><span style="display:none" class="sortkey">7000227990000099999</span>2.28%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Flag_of_Indiana.svg/23px-Flag_of_Indiana.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Flag_of_Indiana.svg/35px-Flag_of_Indiana.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Flag_of_Indiana.svg/45px-Flag_of_Indiana.svg.png 2x" data-file-width="750" data-file-height="500" />&#160;</span><a href="/wiki/Indiana" title="Indiana">Indiana</a></td> +<td align="center"><span style="" class="sortkey">!B9963624138402&#160;</span>38</td> +<td align="right">36,419.55</td> +<td align="right">94,326</td> +<td align="center"><span style="" class="sortkey">!B9963624138402&#160;</span>38</td> +<td align="right">35,826.11</td> +<td align="right">92,789</td> +<td align="right"><span style="display:none" class="sortkey">7001983700000000000</span>98.37%</td> +<td align="right">593.44</td> +<td align="right">1,537</td> +<td align="right"><span style="display:none" class="sortkey">7000162990000000000</span>1.63%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/3/35/Flag_of_Maine.svg/23px-Flag_of_Maine.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/3/35/Flag_of_Maine.svg/35px-Flag_of_Maine.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/3/35/Flag_of_Maine.svg/45px-Flag_of_Maine.svg.png 2x" data-file-width="687" data-file-height="458" />&#160;</span><a href="/wiki/Maine" title="Maine">Maine</a></td> +<td align="center"><span style="" class="sortkey">!B9963364383538&#160;</span>39</td> +<td align="right">35,379.74</td> +<td align="right">91,633</td> +<td align="center"><span style="" class="sortkey">!B9963364383538&#160;</span>39</td> +<td align="right">30,842.92</td> +<td align="right">79,883</td> +<td align="right"><span style="display:none" class="sortkey">7001871800000000000</span>87.18%</td> +<td align="right">4,536.82</td> +<td align="right">11,750</td> +<td align="right"><span style="display:none" class="sortkey">7001128200000000000</span>12.82%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/6/69/Flag_of_South_Carolina.svg/23px-Flag_of_South_Carolina.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/6/69/Flag_of_South_Carolina.svg/35px-Flag_of_South_Carolina.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/6/69/Flag_of_South_Carolina.svg/45px-Flag_of_South_Carolina.svg.png 2x" data-file-width="750" data-file-height="500" />&#160;</span><a href="/wiki/South_Carolina" title="South Carolina">South Carolina</a></td> +<td align="center"><span style="" class="sortkey">!B9963111205458&#160;</span>40</td> +<td align="right">32,020.49</td> +<td align="right">82,933</td> +<td align="center"><span style="" class="sortkey">!B9963111205458&#160;</span>40</td> +<td align="right">30,060.70</td> +<td align="right">77,857</td> +<td align="right"><span style="display:none" class="sortkey">7001938800000000000</span>93.88%</td> +<td align="right">1,959.79</td> +<td align="right">5,076</td> +<td align="right"><span style="display:none" class="sortkey">7000612000000000000</span>6.12%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/2/22/Flag_of_West_Virginia.svg/23px-Flag_of_West_Virginia.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/2/22/Flag_of_West_Virginia.svg/35px-Flag_of_West_Virginia.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/2/22/Flag_of_West_Virginia.svg/46px-Flag_of_West_Virginia.svg.png 2x" data-file-width="760" data-file-height="400" />&#160;</span><a href="/wiki/West_Virginia" title="West Virginia">West Virginia</a></td> +<td align="center"><span style="" class="sortkey">!B9962864279332&#160;</span>41</td> +<td align="right">24,230.04</td> +<td align="right">62,756</td> +<td align="center"><span style="" class="sortkey">!B9962864279332&#160;</span>41</td> +<td align="right">24,038.21</td> +<td align="right">62,259</td> +<td align="right"><span style="display:none" class="sortkey">7001992100000099999</span>99.21%</td> +<td align="right">191.83</td> +<td align="right">497</td> +<td align="right"><span style="display:none" class="sortkey">6999790000000000000</span>0.79%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Flag_of_Maryland.svg/23px-Flag_of_Maryland.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Flag_of_Maryland.svg/35px-Flag_of_Maryland.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Flag_of_Maryland.svg/45px-Flag_of_Maryland.svg.png 2x" data-file-width="750" data-file-height="500" />&#160;</span><a href="/wiki/Maryland" title="Maryland">Maryland</a></td> +<td align="center"><span style="" class="sortkey">!B9962623303817&#160;</span>42</td> +<td align="right">12,405.93</td> +<td align="right">32,131</td> +<td align="center"><span style="" class="sortkey">!B9962623303817&#160;</span>42</td> +<td align="right">9,707.24</td> +<td align="right">25,142</td> +<td align="right"><span style="display:none" class="sortkey">7001782500000000000</span>78.25%</td> +<td align="right">2,698.69</td> +<td align="right">6,990</td> +<td align="right"><span style="display:none" class="sortkey">7001217500000000000</span>21.75%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Flag_of_Hawaii.svg/23px-Flag_of_Hawaii.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Flag_of_Hawaii.svg/35px-Flag_of_Hawaii.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Flag_of_Hawaii.svg/46px-Flag_of_Hawaii.svg.png 2x" data-file-width="1200" data-file-height="600" />&#160;</span><a href="/wiki/Hawaii" title="Hawaii">Hawaii</a></td> +<td align="center"><span style="" class="sortkey">!B9962387998843&#160;</span>43</td> +<td align="right">10,931.72</td> +<td align="right">28,313</td> +<td align="center"><span style="" class="sortkey">!B9961498523982&#160;</span>47</td> +<td align="right">6,422.63</td> +<td align="right">16,635</td> +<td align="right"><span style="display:none" class="sortkey">7001587500000000000</span>58.75%</td> +<td align="right">4,509.09</td> +<td align="right">11,678</td> +<td align="right"><span style="display:none" class="sortkey">7001412500000000000</span>41.25%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/f2/Flag_of_Massachusetts.svg/23px-Flag_of_Massachusetts.svg.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/f2/Flag_of_Massachusetts.svg/35px-Flag_of_Massachusetts.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/f2/Flag_of_Massachusetts.svg/46px-Flag_of_Massachusetts.svg.png 2x" data-file-width="1500" data-file-height="900" />&#160;</span><a href="/wiki/Massachusetts" title="Massachusetts">Massachusetts</a></td> +<td align="center"><span style="" class="sortkey">!B9962158103660&#160;</span>44</td> +<td align="right">10,554.39</td> +<td align="right">27,336</td> +<td align="center"><span style="" class="sortkey">!B9961933375102&#160;</span>45</td> +<td align="right">7,800.06</td> +<td align="right">20,202</td> +<td align="right"><span style="display:none" class="sortkey">7001739000000000000</span>73.90%</td> +<td align="right">2,754.33</td> +<td align="right">7,134</td> +<td align="right"><span style="display:none" class="sortkey">7001261000000000000</span>26.10%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/4/49/Flag_of_Vermont.svg/23px-Flag_of_Vermont.svg.png" width="23" height="14" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/4/49/Flag_of_Vermont.svg/35px-Flag_of_Vermont.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/4/49/Flag_of_Vermont.svg/46px-Flag_of_Vermont.svg.png 2x" data-file-width="750" data-file-height="450" />&#160;</span><a href="/wiki/Vermont" title="Vermont">Vermont</a></td> +<td align="center"><span style="" class="sortkey">!B9961933375102&#160;</span>45</td> +<td align="right">9,616.36</td> +<td align="right">24,906</td> +<td align="center"><span style="" class="sortkey">!B9962387998843&#160;</span>43</td> +<td align="right">9,216.66</td> +<td align="right">23,871</td> +<td align="right"><span style="display:none" class="sortkey">7001958400000000000</span>95.84%</td> +<td align="right">399.71</td> +<td align="right">1,035</td> +<td align="right"><span style="display:none" class="sortkey">7000416000000000000</span>4.16%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/2/28/Flag_of_New_Hampshire.svg/23px-Flag_of_New_Hampshire.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/2/28/Flag_of_New_Hampshire.svg/35px-Flag_of_New_Hampshire.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/2/28/Flag_of_New_Hampshire.svg/45px-Flag_of_New_Hampshire.svg.png 2x" data-file-width="660" data-file-height="440" />&#160;</span><a href="/wiki/New_Hampshire" title="New Hampshire">New Hampshire</a></td> +<td align="center"><span style="" class="sortkey">!B9961713586035&#160;</span>46</td> +<td align="right">9,349.16</td> +<td align="right">24,214</td> +<td align="center"><span style="" class="sortkey">!B9962158103660&#160;</span>44</td> +<td align="right">8,952.65</td> +<td align="right">23,187</td> +<td align="right"><span style="display:none" class="sortkey">7001957600000000000</span>95.76%</td> +<td align="right">396.51</td> +<td align="right">1,027</td> +<td align="right"><span style="display:none" class="sortkey">7000424000000000000</span>4.24%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/9/92/Flag_of_New_Jersey.svg/23px-Flag_of_New_Jersey.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/9/92/Flag_of_New_Jersey.svg/35px-Flag_of_New_Jersey.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/9/92/Flag_of_New_Jersey.svg/45px-Flag_of_New_Jersey.svg.png 2x" data-file-width="750" data-file-height="500" />&#160;</span><a href="/wiki/New_Jersey" title="New Jersey">New Jersey</a></td> +<td align="center"><span style="" class="sortkey">!B9961498523982&#160;</span>47</td> +<td align="right">8,722.58</td> +<td align="right">22,591</td> +<td align="center"><span style="" class="sortkey">!B9961713586035&#160;</span>46</td> +<td align="right">7,354.22</td> +<td align="right">19,047</td> +<td align="right"><span style="display:none" class="sortkey">7001843100000000000</span>84.31%</td> +<td align="right">1,368.36</td> +<td align="right">3,544</td> +<td align="right"><span style="display:none" class="sortkey">7001156900000000000</span>15.69%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/9/96/Flag_of_Connecticut.svg/20px-Flag_of_Connecticut.svg.png" width="20" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/9/96/Flag_of_Connecticut.svg/30px-Flag_of_Connecticut.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/9/96/Flag_of_Connecticut.svg/40px-Flag_of_Connecticut.svg.png 2x" data-file-width="594" data-file-height="459" />&#160;</span><a href="/wiki/Connecticut" title="Connecticut">Connecticut</a></td> +<td align="center"><span style="" class="sortkey">!B9961287989890&#160;</span>48</td> +<td align="right">5,543.41</td> +<td align="right">14,357</td> +<td align="center"><span style="" class="sortkey">!B9961287989890&#160;</span>48</td> +<td align="right">4,842.36</td> +<td align="right">12,542</td> +<td align="right"><span style="display:none" class="sortkey">7001873500000000000</span>87.35%</td> +<td align="right">701.06</td> +<td align="right">1,816</td> +<td align="right"><span style="display:none" class="sortkey">7001126500000000000</span>12.65%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/c/c6/Flag_of_Delaware.svg/23px-Flag_of_Delaware.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/c/c6/Flag_of_Delaware.svg/35px-Flag_of_Delaware.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/c/c6/Flag_of_Delaware.svg/45px-Flag_of_Delaware.svg.png 2x" data-file-width="600" data-file-height="400" />&#160;</span><a href="/wiki/Delaware" title="Delaware">Delaware</a></td> +<td align="center"><span style="" class="sortkey">!B9961081797018&#160;</span>49</td> +<td align="right">2,488.72</td> +<td align="right">6,446</td> +<td align="center"><span style="" class="sortkey">!B9961081797018&#160;</span>49</td> +<td align="right">1,948.54</td> +<td align="right">5,047</td> +<td align="right"><span style="display:none" class="sortkey">7001782900000000000</span>78.29%</td> +<td align="right">540.18</td> +<td align="right">1,399</td> +<td align="right"><span style="display:none" class="sortkey">7001217100000000000</span>21.71%</td> +</tr> +<tr valign="top"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Flag_of_Rhode_Island.svg/18px-Flag_of_Rhode_Island.svg.png" width="18" height="17" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Flag_of_Rhode_Island.svg/28px-Flag_of_Rhode_Island.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Flag_of_Rhode_Island.svg/36px-Flag_of_Rhode_Island.svg.png 2x" data-file-width="531" data-file-height="496" />&#160;</span><a href="/wiki/Rhode_Island" title="Rhode Island">Rhode Island</a></td> +<td align="center"><span style="" class="sortkey">!B9960879769945&#160;</span>50</td> +<td align="right">1,544.89</td> +<td align="right">4,001</td> +<td align="center"><span style="" class="sortkey">!B9960879769945&#160;</span>50</td> +<td align="right">1,033.81</td> +<td align="right">2,678</td> +<td align="right"><span style="display:none" class="sortkey">7001669200000000000</span>66.92%</td> +<td align="right">511.07</td> +<td align="right">1,324</td> +<td align="right"><span style="display:none" class="sortkey">7001330800000000000</span>33.08%</td> +</tr> +<tr valign="top" style="background:lightgreen"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Flag_of_Washington%2C_D.C..svg/23px-Flag_of_Washington%2C_D.C..svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Flag_of_Washington%2C_D.C..svg/35px-Flag_of_Washington%2C_D.C..svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Flag_of_Washington%2C_D.C..svg/46px-Flag_of_Washington%2C_D.C..svg.png 2x" data-file-width="800" data-file-height="400" />&#160;</span><a href="/wiki/Washington,_D.C." title="Washington, D.C.">District of Columbia</a></td> +<td align="center"></td> +<td align="right">68.34</td> +<td align="right">177</td> +<td align="center"></td> +<td align="right">61.05</td> +<td align="right">158</td> +<td align="right"><span style="display:none" class="sortkey">7001893300000000000</span>89.33%</td> +<td align="right">7.29</td> +<td align="right">19</td> +<td align="right"><span style="display:none" class="sortkey">7001106700000000000</span>10.67%</td> +</tr> +<tr valign="top" style="background:beige"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/2/28/Flag_of_Puerto_Rico.svg/23px-Flag_of_Puerto_Rico.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/2/28/Flag_of_Puerto_Rico.svg/35px-Flag_of_Puerto_Rico.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/2/28/Flag_of_Puerto_Rico.svg/45px-Flag_of_Puerto_Rico.svg.png 2x" data-file-width="900" data-file-height="600" />&#160;</span><a href="/wiki/Puerto_Rico" title="Puerto Rico">Puerto Rico</a></td> +<td align="center"></td> +<td align="right">5,324.84</td> +<td align="right">13,791</td> +<td align="center"></td> +<td align="right">3,423.78</td> +<td align="right">8,868</td> +<td align="right"><span style="display:none" class="sortkey">7001643000000000000</span>64.30%</td> +<td align="right">1,901.07</td> +<td align="right">4,924</td> +<td align="right"><span style="display:none" class="sortkey">7001357000000000000</span>35.70%</td> +</tr> +<tr valign="top" style="background:beige"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Flag_of_the_Northern_Mariana_Islands.svg/23px-Flag_of_the_Northern_Mariana_Islands.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Flag_of_the_Northern_Mariana_Islands.svg/35px-Flag_of_the_Northern_Mariana_Islands.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Flag_of_the_Northern_Mariana_Islands.svg/46px-Flag_of_the_Northern_Mariana_Islands.svg.png 2x" data-file-width="1000" data-file-height="500" />&#160;</span><a href="/wiki/Northern_Mariana_Islands" title="Northern Mariana Islands">Northern Mariana Islands</a></td> +<td align="center"></td> +<td align="right">1,975.57</td> +<td align="right">5,117</td> +<td align="center"></td> +<td align="right">182.33</td> +<td align="right">472</td> +<td align="right"><span style="display:none" class="sortkey">7000923000000000000</span>9.23%</td> +<td align="right">1,793.24</td> +<td align="right">4,644</td> +<td align="right"><span style="display:none" class="sortkey">7001907700000000000</span>90.77%</td> +</tr> +<tr valign="top" style="background:beige"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Flag_of_the_United_States_Virgin_Islands.svg/23px-Flag_of_the_United_States_Virgin_Islands.svg.png" width="23" height="15" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Flag_of_the_United_States_Virgin_Islands.svg/35px-Flag_of_the_United_States_Virgin_Islands.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Flag_of_the_United_States_Virgin_Islands.svg/45px-Flag_of_the_United_States_Virgin_Islands.svg.png 2x" data-file-width="744" data-file-height="496" />&#160;</span><a href="/wiki/United_States_Virgin_Islands" title="United States Virgin Islands">United States Virgin Islands</a></td> +<td align="center"></td> +<td align="right">732.93</td> +<td align="right">1,898</td> +<td align="center"></td> +<td align="right">134.32</td> +<td align="right">348</td> +<td align="right"><span style="display:none" class="sortkey">7001183309999999999</span>18.33%</td> +<td align="right">598.61</td> +<td align="right">1,550</td> +<td align="right"><span style="display:none" class="sortkey">7001816700000000000</span>81.67%</td> +</tr> +<tr valign="top" style="background:beige"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/8/87/Flag_of_American_Samoa.svg/23px-Flag_of_American_Samoa.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/8/87/Flag_of_American_Samoa.svg/35px-Flag_of_American_Samoa.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/8/87/Flag_of_American_Samoa.svg/46px-Flag_of_American_Samoa.svg.png 2x" data-file-width="1000" data-file-height="500" />&#160;</span><a href="/wiki/American_Samoa" title="American Samoa">American Samoa</a></td> +<td align="center"></td> +<td align="right">581.05</td> +<td align="right">1,505</td> +<td align="center"></td> +<td align="right">76.46</td> +<td align="right">198</td> +<td align="right"><span style="display:none" class="sortkey">7001131600000000000</span>13.16%</td> +<td align="right">504.60</td> +<td align="right">1,307</td> +<td align="right"><span style="display:none" class="sortkey">7001868400000000000</span>86.84%</td> +</tr> +<tr valign="top" style="background:beige"> +<td><span class="flagicon"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/0/07/Flag_of_Guam.svg/23px-Flag_of_Guam.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/0/07/Flag_of_Guam.svg/35px-Flag_of_Guam.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/0/07/Flag_of_Guam.svg/46px-Flag_of_Guam.svg.png 2x" data-file-width="820" data-file-height="440" />&#160;</span><a href="/wiki/Guam" title="Guam">Guam</a></td> +<td align="center"></td> +<td align="right">570.62</td> +<td align="right">1,478</td> +<td align="center"></td> +<td align="right">209.80</td> +<td align="right">543</td> +<td align="right"><span style="display:none" class="sortkey">7001367700000000000</span>36.77%</td> +<td align="right">360.82</td> +<td align="right">935</td> +<td align="right"><span style="display:none" class="sortkey">7001632300000000000</span>63.23%</td> +</tr> +<tr valign="top" style="background:beige"> +<td><span class="flagicon"><a href="/wiki/United_States" title="United States"><img alt="United States" src="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/23px-Flag_of_the_United_States.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/35px-Flag_of_the_United_States.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/46px-Flag_of_the_United_States.svg.png 2x" data-file-width="1235" data-file-height="650" /></a></span> <i><a href="/wiki/United_States_Minor_Outlying_Islands" title="United States Minor Outlying Islands">Minor Outlying Islands</a></i><sup id="cite_ref-2000census_3-0" class="reference"><a href="#cite_note-2000census-3"><span>[</span>3<span>]</span></a></sup><sup id="cite_ref-4" class="reference"><a href="#cite_note-4"><span>[</span>a<span>]</span></a></sup></td> +<td align="center"></td> +<td align="right">16.0</td> +<td align="right">41</td> +<td align="center"></td> +<td align="right">16.0</td> +<td align="right">41</td> +<td align="center">—</td> +<td align="center">—</td> +<td align="center">—</td> +<td align="center">—</td> +</tr> +<tr class="sortbottom" valign="top" style="background: #D0E6FF;"> +<td><span class="flagicon"><a href="/wiki/United_States" title="United States"><img alt="United States" src="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/23px-Flag_of_the_United_States.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/35px-Flag_of_the_United_States.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/46px-Flag_of_the_United_States.svg.png 2x" data-file-width="1235" data-file-height="650" /></a></span> <b><a href="/wiki/Contiguous_United_States" title="Contiguous United States">Contiguous United States</a></b></td> +<td align="center"><b>Total</b></td> +<td align="right">3,120,426.47</td> +<td align="right">8,081,867</td> +<td align="center"></td> +<td align="right">2,954,841.42</td> +<td align="right">7,653,004</td> +<td align="right"><span style="display:none" class="sortkey">7001946900000000000</span>94.69%</td> +<td align="right">165,584.6</td> +<td align="right">428,862</td> +<td align="right"><span style="display:none" class="sortkey">7000530990000099999</span>5.31%</td> +</tr> +<tr class="sortbottom" valign="top" style="background: #D0E6FF;"> +<td><span class="flagicon"><a href="/wiki/United_States" title="United States"><img alt="United States" src="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/23px-Flag_of_the_United_States.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/35px-Flag_of_the_United_States.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/46px-Flag_of_the_United_States.svg.png 2x" data-file-width="1235" data-file-height="650" /></a></span> <b>50 states and D.C.</b></td> +<td align="center"><b>Total</b></td> +<td align="right">3,796,742.23</td> +<td align="right">9,833,517</td> +<td align="center"></td> +<td align="right">3,531,905.43</td> +<td align="right">9,147,593</td> +<td align="right"><span style="display:none" class="sortkey">7001930200000000000</span>93.02%</td> +<td align="right">264,836.79</td> +<td align="right">685,924</td> +<td align="right"><span style="display:none" class="sortkey">7000698000000000000</span>6.98%</td> +</tr> +<tr class="sortbottom" valign="top" style="background: #D0E6FF;"> +<td><span class="flagicon"><a href="/wiki/United_States" title="United States"><img alt="United States" src="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/23px-Flag_of_the_United_States.svg.png" width="23" height="12" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/35px-Flag_of_the_United_States.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/46px-Flag_of_the_United_States.svg.png 2x" data-file-width="1235" data-file-height="650" /></a></span> <b>All U.S. territory</b></td> +<td align="center"><b>Total</b></td> +<td align="right">3,805,943.26</td> +<td align="right">9,857,348</td> +<td align="center"></td> +<td align="right">3,535,948.12</td> +<td align="right">9,158,064</td> +<td align="right"><span style="display:none" class="sortkey">7001929100000000000</span>92.91%</td> +<td align="right">269,995.13</td> +<td align="right">699,284</td> +<td align="right"><span style="display:none" class="sortkey">7000709000000000000</span>7.09%</td> +</tr> +</table> +<h2><span class="mw-headline" id="Area_by_division">Area by division</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=edit&amp;section=2" title="Edit section: Area by division">edit</a><span class="mw-editsection-bracket">]</span></span></h2> +<table class="wikitable sortable"> +<tr> +<th></th> +<th colspan="3">Total area<sup id="cite_ref-2010census_2-4" class="reference"><a href="#cite_note-2010census-2"><span>[</span>2<span>]</span></a></sup></th> +<th colspan="4">Land area<sup id="cite_ref-2010census_2-5" class="reference"><a href="#cite_note-2010census-2"><span>[</span>2<span>]</span></a></sup></th> +<th colspan="4">Water<sup id="cite_ref-2010census_2-6" class="reference"><a href="#cite_note-2010census-2"><span>[</span>2<span>]</span></a></sup></th> +</tr> +<tr> +<th>Division</th> +<th>Rank</th> +<th>sq mi</th> +<th>km²</th> +<th>Rank</th> +<th>sq mi</th> +<th>km²</th> +<th>&#160;% land</th> +<th>Rank</th> +<th>sq mi</th> +<th>km²</th> +<th>&#160;% water</th> +</tr> +<tr> +<td><a href="/wiki/East_North_Central_States" title="East North Central States">East North Central</a></td> +<td align="center"><span style="" class="sortkey">!B9983905620875&#160;</span>5</td> +<td align="right">301,368.57</td> +<td align="right">780,541</td> +<td align="center"><span style="" class="sortkey">!B9982082405307&#160;</span>6</td> +<td align="right">242,902.44</td> +<td align="right">629,114</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9993068528194&#160;</span>2</td> +<td align="right">58,466.13</td> +<td align="right">151,427</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/East_South_Central_States" title="East South Central States">East South Central</a></td> +<td align="center"><span style="" class="sortkey">!B9980540898509&#160;</span>7</td> +<td align="right">183,403.89</td> +<td align="right">475,014</td> +<td align="center"><span style="" class="sortkey">!B9980540898509&#160;</span>7</td> +<td align="right">178,289.83</td> +<td align="right">461,769</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9978027754226&#160;</span>9</td> +<td align="right">5,114.60</td> +<td align="right">13,247</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/Mid-Atlantic_States" title="Mid-Atlantic States" class="mw-redirect">Middle Atlantic</a></td> +<td align="center"><span style="" class="sortkey">!B9979205584583&#160;</span>8</td> +<td align="right">109,331.89</td> +<td align="right">283,168</td> +<td align="center"><span style="" class="sortkey">!B9979205584583&#160;</span>8</td> +<td align="right">99,223.32</td> +<td align="right">256,987</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9982082405307&#160;</span>6</td> +<td align="right">10,108.57</td> +<td align="right">26,181</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/Mountain_States" title="Mountain States">Mountain</a></td> +<td align="center"><span style="" class="sortkey">!B9993068528194&#160;</span>2</td> +<td align="right">863,564.63</td> +<td align="right">2,236,622</td> +<td align="center"><span style="" class="sortkey">!B9993068528194&#160;</span>2</td> +<td align="right">855,766.98</td> +<td align="right">2,216,426</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9979205584583&#160;</span>8</td> +<td align="right">7,797.65</td> +<td align="right">20,196</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/New_England" title="New England">New England</a></td> +<td align="center"><span style="" class="sortkey">!B9978027754226&#160;</span>9</td> +<td align="right">71,987.96</td> +<td align="right">186,448</td> +<td align="center"><span style="" class="sortkey">!B9978027754226&#160;</span>9</td> +<td align="right">62,668.46</td> +<td align="right">162,311</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9980540898509&#160;</span>7</td> +<td align="right">9,299.50</td> +<td align="right">24,086</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/Pacific_States" title="Pacific States">Pacific</a></td> +<td align="center"><span style="" class="sortkey">!C&#160;</span>1</td> +<td align="right">1,009,687.00</td> +<td align="right">2,615,077</td> +<td align="center"><span style="" class="sortkey">!C&#160;</span>1</td> +<td align="right">895,286.33</td> +<td align="right">2,318,781</td> +<td></td> +<td align="center"><span style="" class="sortkey">!C&#160;</span>1</td> +<td align="right">114,400.67</td> +<td align="right">296,296</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/South_Atlantic_States" title="South Atlantic States">South Atlantic</a></td> +<td align="center"><span style="" class="sortkey">!B9982082405307&#160;</span>6</td> +<td align="right">292,990.46</td> +<td align="right">758,842</td> +<td align="center"><span style="" class="sortkey">!B9983905620875&#160;</span>5</td> +<td align="right">265,061.97</td> +<td align="right">686,507</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9989013877113&#160;</span>3</td> +<td align="right">27,928.49</td> +<td align="right">72,334</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/West_North_Central_States" title="West North Central States">West North Central</a></td> +<td align="center"><span style="" class="sortkey">!B9989013877113&#160;</span>3</td> +<td align="right">520,355.80</td> +<td align="right">1,347,715</td> +<td align="center"><span style="" class="sortkey">!B9989013877113&#160;</span>3</td> +<td align="right">507,620.08</td> +<td align="right">1,314,730</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9983905620875&#160;</span>5</td> +<td align="right">12,735.72</td> +<td align="right">32,985</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/West_South_Central_States" title="West South Central States">West South Central</a></td> +<td align="center"><span style="" class="sortkey">!B9986137056388&#160;</span>4</td> +<td align="right">444,052.01</td> +<td align="right">1,150,089</td> +<td align="center"><span style="" class="sortkey">!B9986137056388&#160;</span>4</td> +<td align="right">425,066.01</td> +<td align="right">1,100,916</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9986137056388&#160;</span>4</td> +<td align="right">18,986.00</td> +<td align="right">49,174</td> +<td></td> +</tr> +</table> +<h2><span class="mw-headline" id="Area_by_region">Area by region</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=edit&amp;section=3" title="Edit section: Area by region">edit</a><span class="mw-editsection-bracket">]</span></span></h2> +<table class="wikitable sortable"> +<tr> +<th></th> +<th colspan="3">Total area<sup id="cite_ref-2010census_2-7" class="reference"><a href="#cite_note-2010census-2"><span>[</span>2<span>]</span></a></sup></th> +<th colspan="4">Land area<sup id="cite_ref-2010census_2-8" class="reference"><a href="#cite_note-2010census-2"><span>[</span>2<span>]</span></a></sup></th> +<th colspan="4">Water<sup id="cite_ref-2010census_2-9" class="reference"><a href="#cite_note-2010census-2"><span>[</span>2<span>]</span></a></sup></th> +</tr> +<tr> +<th>Region</th> +<th>Rank</th> +<th>sq mi</th> +<th>km²</th> +<th>Rank</th> +<th>sq mi</th> +<th>km²</th> +<th>&#160;% land</th> +<th>Rank</th> +<th>sq mi</th> +<th>km²</th> +<th>&#160;% water</th> +</tr> +<tr> +<td><a href="/wiki/Midwestern_United_States" title="Midwestern United States">Midwest</a></td> +<td align="center"><span style="" class="sortkey">!B9989013877113&#160;</span>3</td> +<td align="right">821,724.38</td> +<td align="right">2,128,256</td> +<td align="center"><span style="" class="sortkey">!B9989013877113&#160;</span>3</td> +<td align="right">750,522.52</td> +<td align="right">1,943,844</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9993068528194&#160;</span>2</td> +<td align="right">71,201.86</td> +<td align="right">184,412</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/Northeastern_United_States" title="Northeastern United States">Northeast</a></td> +<td align="center"><span style="" class="sortkey">!B9986137056388&#160;</span>4</td> +<td align="right">181,319.85</td> +<td align="right">469,616</td> +<td align="center"><span style="" class="sortkey">!B9986137056388&#160;</span>4</td> +<td align="right">161,911.78</td> +<td align="right">419,350</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9986137056388&#160;</span>4</td> +<td align="right">19,408.07</td> +<td align="right">50,267</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/Southern_United_States" title="Southern United States">South</a></td> +<td align="center"><span style="" class="sortkey">!B9993068528194&#160;</span>2</td> +<td align="right">920,446.37</td> +<td align="right">2,383,945</td> +<td align="center"><span style="" class="sortkey">!B9993068528194&#160;</span>2</td> +<td align="right">868,417.82</td> +<td align="right">2,249,192</td> +<td></td> +<td align="center"><span style="" class="sortkey">!B9989013877113&#160;</span>3</td> +<td align="right">52,028.55</td> +<td align="right">134,753</td> +<td></td> +</tr> +<tr> +<td><a href="/wiki/Western_United_States" title="Western United States">West</a></td> +<td align="center"><span style="" class="sortkey">!C&#160;</span>1</td> +<td align="right">1,873,251.63</td> +<td align="right">4,851,699</td> +<td align="center"><span style="" class="sortkey">!C&#160;</span>1</td> +<td align="right">1,751,053.31</td> +<td align="right">4,535,207</td> +<td></td> +<td align="center"><span style="" class="sortkey">!C&#160;</span>1</td> +<td align="right">122,198.32</td> +<td align="right">316,492</td> +<td></td> +</tr> +</table> +<ul class="gallery mw-gallery-traditional"> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:28.5px auto;"><a href="/wiki/File:US_States_by_Total_Area.svg" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/b/bb/US_States_by_Total_Area.svg/120px-US_States_by_Total_Area.svg.png" width="120" height="93" data-file-width="932" data-file-height="723" /></a></div> +</div> +<div class="gallerytext"> +<p>U.S. states by total area</p> +</div> +</div> +</li> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:28.5px auto;"><a href="/wiki/File:US_States_by_Total_Land_Area.svg" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/5/5b/US_States_by_Total_Land_Area.svg/120px-US_States_by_Total_Land_Area.svg.png" width="120" height="93" data-file-width="932" data-file-height="723" /></a></div> +</div> +<div class="gallerytext"> +<p>U.S. states by land area</p> +</div> +</div> +</li> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:27.5px auto;"><a href="/wiki/File:US_States_by_Water_Area.svg" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/7/70/US_States_by_Water_Area.svg/120px-US_States_by_Water_Area.svg.png" width="120" height="95" data-file-width="966" data-file-height="764" /></a></div> +</div> +<div class="gallerytext"> +<p>U.S. states by water area</p> +</div> +</div> +</li> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:27.5px auto;"><a href="/wiki/File:US_States_by_Water_Percentage.svg" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/2/2d/US_States_by_Water_Percentage.svg/120px-US_States_by_Water_Percentage.svg.png" width="120" height="95" data-file-width="966" data-file-height="764" /></a></div> +</div> +<div class="gallerytext"> +<p>U.S. states by water percentage</p> +</div> +</div> +</li> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:36px auto;"><a href="/wiki/File:Map_of_USA_AK_full.png" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Map_of_USA_AK_full.png/120px-Map_of_USA_AK_full.png" width="120" height="78" data-file-width="284" data-file-height="184" /></a></div> +</div> +<div class="gallerytext"> +<p>Alaska is the largest state by total area, land area, and water area</p> +</div> +</div> +</li> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:37px auto;"><a href="/wiki/File:Alaska-Size.png" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/4/4e/Alaska-Size.png/120px-Alaska-Size.png" width="120" height="76" data-file-width="764" data-file-height="485" /></a></div> +</div> +<div class="gallerytext"> +<p>The area of <a href="/wiki/Alaska" title="Alaska">Alaska</a> is <span style="display:none" class="sortkey">7001180000000000000</span>18% of the area of the <a href="/wiki/United_States" title="United States">United States</a> and <span style="display:none" class="sortkey">7001210000000000000</span>21% of the area of the <a href="/wiki/Contiguous_United_States" title="Contiguous United States">contiguous United States</a></p> +</div> +</div> +</li> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:36px auto;"><a href="/wiki/File:Map_of_USA_TX.svg" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/c/cc/Map_of_USA_TX.svg/120px-Map_of_USA_TX.svg.png" width="120" height="78" data-file-width="286" data-file-height="186" /></a></div> +</div> +<div class="gallerytext"> +<p>The second largest state, Texas, is only <span style="display:none" class="sortkey">7001400000000000000</span>40% of the total area of the largest state, Alaska</p> +</div> +</div> +</li> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:36px auto;"><a href="/wiki/File:Map_of_USA_highlighting_Rhode_Island.png" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/9/91/Map_of_USA_highlighting_Rhode_Island.png/120px-Map_of_USA_highlighting_Rhode_Island.png" width="120" height="78" data-file-width="280" data-file-height="183" /></a></div> +</div> +<div class="gallerytext"> +<p>Rhode Island is the smallest state by total area and land area</p> +</div> +</div> +</li> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:15px auto;"><a href="/wiki/File:Map_of_California_highlighting_San_Bernardino_County.svg" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/7/77/Map_of_California_highlighting_San_Bernardino_County.svg/104px-Map_of_California_highlighting_San_Bernardino_County.svg.png" width="104" height="120" data-file-width="9164" data-file-height="10536" /></a></div> +</div> +<div class="gallerytext"> +<p><a href="/wiki/San_Bernardino_County" title="San Bernardino County" class="mw-redirect">San Bernardino County</a> is the largest <a href="/wiki/County" title="County">county</a> in the U.S. and is larger than each of the nine smallest states, including larger than the four smallest states combined. (Although some of Alaska's boroughs and census areas are larger, they are not true counties.)</p> +</div> +</div> +</li> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:25.5px auto;"><a href="/wiki/File:Michigan.svg" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/9/93/Michigan.svg/120px-Michigan.svg.png" width="120" height="99" data-file-width="741" data-file-height="612" /></a></div> +</div> +<div class="gallerytext"> +<p>Michigan is second (after Alaska) in water area, and first in water percentage</p> +</div> +</div> +</li> +<li class="gallerybox" style="width: 155px"> +<div style="width: 155px"> +<div class="thumb" style="width: 150px;"> +<div style="margin:22.5px auto;"><a href="/wiki/File:STS-95_Florida_From_Space.jpg" class="image"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/2/2e/STS-95_Florida_From_Space.jpg/120px-STS-95_Florida_From_Space.jpg" width="120" height="105" data-file-width="3000" data-file-height="2624" /></a></div> +</div> +<div class="gallerytext"> +<p>Florida is mostly a peninsula, and has the third largest water area and seventh largest water area percentage</p> +</div> +</div> +</li> +</ul> +<h2><span class="mw-headline" id="See_also">See also</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=edit&amp;section=4" title="Edit section: See also">edit</a><span class="mw-editsection-bracket">]</span></span></h2> +<div class="noprint tright portal" style="border:solid #aaa 1px;margin:0.5em 0 0.5em 1em;"> +<table style="background:#f9f9f9;font-size:85%;line-height:110%;max-width:175px;"> +<tr valign="middle"> +<td style="text-align:center;"><a href="/wiki/File:Flag_of_the_United_States.svg" class="image"><img alt="Portal icon" src="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/32px-Flag_of_the_United_States.svg.png" width="32" height="17" class="thumbborder" srcset="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/48px-Flag_of_the_United_States.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/64px-Flag_of_the_United_States.svg.png 2x" data-file-width="1235" data-file-height="650" /></a></td> +<td style="padding:0 0.2em;vertical-align:middle;font-style:italic;font-weight:bold;"><a href="/wiki/Portal:United_States" title="Portal:United States">United States portal</a></td> +</tr> +</table> +</div> +<ul> +<li><a href="/wiki/List_of_the_largest_country_subdivisions_by_area" title="List of the largest country subdivisions by area" class="mw-redirect">List of the largest country subdivisions by area</a></li> +<li><a href="/wiki/List_of_political_and_geographic_subdivisions_by_total_area" title="List of political and geographic subdivisions by total area">List of political and geographic subdivisions by total area</a></li> +</ul> +<h2><span class="mw-headline" id="Notes">Notes</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=edit&amp;section=5" title="Edit section: Notes">edit</a><span class="mw-editsection-bracket">]</span></span></h2> +<div class="reflist columns references-column-width" style="-moz-column-width: 30em; -webkit-column-width: 30em; column-width: 30em; list-style-type: lower-alpha;"> +<ol class="references"> +<li id="cite_note-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-4">^</a></b></span> <span class="reference-text">Areas were not published in the 2010 census, unlike previous years, as the U.S. Census Bureau no longer collects data on the Minor Outlying Islands.<sup id="cite_ref-2010census_2-3" class="reference"><a href="#cite_note-2010census-2"><span>[</span>2<span>]</span></a></sup></span></li> +</ol> +</div> +<h2><span class="mw-headline" id="References">References</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=edit&amp;section=6" title="Edit section: References">edit</a><span class="mw-editsection-bracket">]</span></span></h2> +<div class="reflist columns references-column-width" style="-moz-column-width: 30em; -webkit-column-width: 30em; column-width: 30em; list-style-type: decimal;"> +<ol class="references"> +<li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://www.census.gov/geo/www/tiger/glossry2.pdf">Census 2000 Geographic Terms and Concepts</a>, Census 2000 Geography Glossary, U.S. Census Bureau. Accessed 2007-07-10</span></li> +<li id="cite_note-2010census-2"><span class="mw-cite-backlink">^ <a href="#cite_ref-2010census_2-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-2010census_2-1"><sup><i><b>b</b></i></sup></a> <a href="#cite_ref-2010census_2-2"><sup><i><b>c</b></i></sup></a> <a href="#cite_ref-2010census_2-3"><sup><i><b>d</b></i></sup></a> <a href="#cite_ref-2010census_2-4"><sup><i><b>e</b></i></sup></a> <a href="#cite_ref-2010census_2-5"><sup><i><b>f</b></i></sup></a> <a href="#cite_ref-2010census_2-6"><sup><i><b>g</b></i></sup></a> <a href="#cite_ref-2010census_2-7"><sup><i><b>h</b></i></sup></a> <a href="#cite_ref-2010census_2-8"><sup><i><b>i</b></i></sup></a> <a href="#cite_ref-2010census_2-9"><sup><i><b>j</b></i></sup></a></span> <span class="reference-text"><span class="citation web"><a rel="nofollow" class="external text" href="http://www.census.gov/prod/cen2010/cph-2-1.pdf">"United States Summary: 2010, Population and Housing Unit Counts, 2010 Census of Population and Housing"</a> (PDF). <a href="/wiki/United_States_Census_Bureau" title="United States Census Bureau">United States Census Bureau</a>. September 2012. pp.&#160;V–2, 1 &amp; 41 (Tables 1 &amp; 18)<span class="reference-accessdate">. Retrieved February 7, 2014</span>.</span><span title="ctx_ver=Z39.88-2004&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AList+of+U.S.+states+and+territories+by+area&amp;rft.btitle=United+States+Summary%3A+2010%2C+Population+and+Housing+Unit+Counts%2C+2010+Census+of+Population+and+Housing&amp;rft.date=September+2012&amp;rft.genre=book&amp;rft_id=http%3A%2F%2Fwww.census.gov%2Fprod%2Fcen2010%2Fcph-2-1.pdf&amp;rft.pages=V-2%2C+1+%26+41+%28Tables+1+%26+18%29&amp;rft.pub=United+States+Census+Bureau&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook" class="Z3988"><span style="display:none;">&#160;</span></span></span></li> +<li id="cite_note-2000census-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-2000census_3-0">^</a></b></span> <span class="reference-text"><span class="citation web"><a rel="nofollow" class="external text" href="http://www.census.gov/prod/cen2000/phc3-us-pt1.pdf">"United States Summary: 2010, Population and Housing Unit Counts, 2000 Census of Population and Housing"</a> (PDF). United States Census Bureau. April 2004. p.&#160;1 (Table 1)<span class="reference-accessdate">. Retrieved February 10, 2014</span>.</span><span title="ctx_ver=Z39.88-2004&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AList+of+U.S.+states+and+territories+by+area&amp;rft.btitle=United+States+Summary%3A+2010%2C+Population+and+Housing+Unit+Counts%2C+2000+Census+of+Population+and+Housing&amp;rft.date=April+2004&amp;rft.genre=book&amp;rft_id=http%3A%2F%2Fwww.census.gov%2Fprod%2Fcen2000%2Fphc3-us-pt1.pdf&amp;rft.pages=1+%28Table+1%29&amp;rft.pub=United+States+Census+Bureau&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook" class="Z3988"><span style="display:none;">&#160;</span></span></span></li> +</ol> +</div> +<h2><span class="mw-headline" id="External_links">External links</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=edit&amp;section=7" title="Edit section: External links">edit</a><span class="mw-editsection-bracket">]</span></span></h2> +<table class="metadata plainlinks mbox-small" style="padding:0.25em 0.5em 0.5em 0.75em;border:1px solid #aaa;background:#f9f9f9;"> +<tr style="height:25px;"> +<td colspan="2" style="padding-bottom:0.5em;border-bottom:1px solid #aaa;margin:auto;text-align:center;">Find more about <b>area</b> at Wikipedia's <a href="/wiki/Wikipedia:Wikimedia_sister_projects" title="Wikipedia:Wikimedia sister projects">sister projects</a></td> +</tr> +<tr style="height:25px;"> +<td style="padding-top:0.75em;"><a href="//en.wiktionary.org/wiki/Special:Search/area" title="Search Wiktionary"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Wiktionary-logo-en.svg/23px-Wiktionary-logo-en.svg.png" width="23" height="25" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Wiktionary-logo-en.svg/35px-Wiktionary-logo-en.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Wiktionary-logo-en.svg/46px-Wiktionary-logo-en.svg.png 2x" data-file-width="1000" data-file-height="1089" /></a></td> +<td style="padding-top:0.75em;"><a href="//en.wiktionary.org/wiki/Special:Search/area" class="extiw" title="wikt:Special:Search/area">Definitions and translations</a> from Wiktionary</td> +</tr> +<tr style="height:25px;"> +<td><a href="//commons.wikimedia.org/wiki/Special:Search/area" title="Search Commons"><img alt="" src="//upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/18px-Commons-logo.svg.png" width="18" height="25" srcset="//upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/28px-Commons-logo.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/37px-Commons-logo.svg.png 2x" data-file-width="1024" data-file-height="1376" /></a></td> +<td><a href="//commons.wikimedia.org/wiki/Special:Search/area" class="extiw" title="commons:Special:Search/area">Media</a> from Commons</td> +</tr> +<tr style="height:25px;"> +<td><a href="//en.wikiquote.org/wiki/Special:Search/area" title="Search Wikiquote"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Wikiquote-logo.svg/21px-Wikiquote-logo.svg.png" width="21" height="25" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Wikiquote-logo.svg/32px-Wikiquote-logo.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Wikiquote-logo.svg/42px-Wikiquote-logo.svg.png 2x" data-file-width="300" data-file-height="355" /></a></td> +<td><a href="//en.wikiquote.org/wiki/Special:Search/area" class="extiw" title="q:Special:Search/area">Quotations</a> from Wikiquote</td> +</tr> +<tr style="height:25px;"> +<td><a href="//en.wikisource.org/wiki/Special:Search/area" title="Search Wikisource"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Wikisource-logo.svg/24px-Wikisource-logo.svg.png" width="24" height="25" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Wikisource-logo.svg/36px-Wikisource-logo.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Wikisource-logo.svg/48px-Wikisource-logo.svg.png 2x" data-file-width="410" data-file-height="430" /></a></td> +<td><a href="//en.wikisource.org/wiki/Special:Search/area" class="extiw" title="s:Special:Search/area">Source texts</a> from Wikisource</td> +</tr> +<tr style="height:25px;"> +<td><a href="//en.wikibooks.org/wiki/Special:Search/area" title="Search Wikibooks"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Wikibooks-logo.svg/25px-Wikibooks-logo.svg.png" width="25" height="25" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Wikibooks-logo.svg/38px-Wikibooks-logo.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Wikibooks-logo.svg/50px-Wikibooks-logo.svg.png 2x" data-file-width="300" data-file-height="300" /></a></td> +<td><a href="//en.wikibooks.org/wiki/Special:Search/area" class="extiw" title="b:Special:Search/area">Textbooks</a> from Wikibooks</td> +</tr> +<tr style="height:25px;"> +<td><a href="//en.wikiversity.org/wiki/Special:Search/area" title="Search Wikiversity"><img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Wikiversity-logo-en.svg/25px-Wikiversity-logo-en.svg.png" width="25" height="23" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Wikiversity-logo-en.svg/38px-Wikiversity-logo-en.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Wikiversity-logo-en.svg/50px-Wikiversity-logo-en.svg.png 2x" data-file-width="1000" data-file-height="900" /></a></td> +<td><a href="//en.wikiversity.org/wiki/Special:Search/area" class="extiw" title="v:Special:Search/area">Learning resources</a> from Wikiversity</td> +</tr> +</table> +<table cellspacing="0" class="navbox" style="border-spacing:0;"> +<tr> +<td style="padding:2px;"> +<table cellspacing="0" class="nowraplinks collapsible autocollapse navbox-inner" style="border-spacing:0;background:transparent;color:inherit;"> +<tr> +<th scope="col" class="navbox-title" colspan="2"> +<div class="plainlinks hlist navbar mini"> +<ul> +<li class="nv-view"><a href="/wiki/Template:USStateLists" title="Template:USStateLists"><span title="View this template" style=";;background:none transparent;border:none;;">v</span></a></li> +<li class="nv-talk"><a href="/wiki/Template_talk:USStateLists" title="Template talk:USStateLists"><span title="Discuss this template" style=";;background:none transparent;border:none;;">t</span></a></li> +<li class="nv-edit"><a class="external text" href="//en.wikipedia.org/w/index.php?title=Template:USStateLists&amp;action=edit"><span title="Edit this template" style=";;background:none transparent;border:none;;">e</span></a></li> +</ul> +</div> +<div style="font-size:110%;"><a href="/wiki/List_of_U.S._state_lists" title="List of U.S. state lists" class="mw-redirect">United States state-related lists</a></div> +</th> +</tr> +<tr style="height:2px;"> +<td colspan="2"></td> +</tr> +<tr> +<td class="navbox-abovebelow" colspan="2"> +<div><a href="/wiki/List_of_states_and_territories_of_the_United_States" title="List of states and territories of the United States">List of states and territories of the United States</a></div> +</td> +</tr> +<tr style="height:2px;"> +<td colspan="2"></td> +</tr> +<tr> +<th scope="row" class="navbox-group">Demographics</th> +<td class="navbox-list navbox-odd hlist" style="text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px;"> +<div style="padding:0em 0.25em;"> +<ul> +<li><a href="/wiki/List_of_U.S._states_by_educational_attainment" title="List of U.S. states by educational attainment">Educational attainment</a></li> +<li><a href="/wiki/Irreligion_in_the_United_States#Demographics" title="Irreligion in the United States">Irreligion</a></li> +<li><a href="/wiki/List_of_U.S._states%27_largest_cities_by_population" title="List of U.S. states' largest cities by population">Five most populous cities</a></li> +<li><a href="/wiki/List_of_the_most_populous_counties_by_U.S._state" title="List of the most populous counties by U.S. state">Most populous county</a></li> +<li><a href="/wiki/List_of_U.S._states_and_territories_by_population#States_and_territories" title="List of U.S. states and territories by population">Population</a> +<ul> +<li><a href="/wiki/List_of_U.S._states_by_population_density" title="List of U.S. states by population density">Density</a></li> +<li><a href="/wiki/List_of_U.S._states_by_population_growth_rate" title="List of U.S. states by population growth rate">Growth rate</a></li> +<li><a href="/wiki/List_of_U.S._states_by_historical_population" title="List of U.S. states by historical population">Historical</a></li> +<li><a href="/wiki/List_of_U.S._states_by_African-American_population" title="List of U.S. states by African-American population">African American</a></li> +<li><a href="/wiki/List_of_U.S._states_by_Amish_population" title="List of U.S. states by Amish population">Amish</a></li> +<li><a href="/wiki/List_of_U.S._states_by_Hispanic_and_Latino_population" title="List of U.S. states by Hispanic and Latino population">Hispanic and Latino</a></li> +<li><a href="/wiki/Spanish_language_in_the_United_States#Geographic_distribution" title="Spanish language in the United States">Spanish-speaking</a></li> +</ul> +</li> +</ul> +</div> +</td> +</tr> +<tr style="height:2px;"> +<td colspan="2"></td> +</tr> +<tr> +<th scope="row" class="navbox-group">Economy</th> +<td class="navbox-list navbox-even hlist" style="text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px;"> +<div style="padding:0em 0.25em;"> +<ul> +<li><a href="/wiki/List_of_U.S._states_by_the_number_of_billionaires" title="List of U.S. states by the number of billionaires">Billionaires</a></li> +<li><a href="/wiki/List_of_U.S._state_budgets" title="List of U.S. state budgets">Budgets</a></li> +<li><a href="/wiki/Federal_tax_revenue_by_state" title="Federal tax revenue by state">Federal tax revenue</a></li> +<li><a href="/wiki/Federal_taxation_and_spending_by_state" title="Federal taxation and spending by state">Federal net taxation less spending</a></li> +<li><a href="/wiki/List_of_U.S._states_by_GDP" title="List of U.S. states by GDP">Gross domestic product</a> +<ul> +<li><a href="/wiki/List_of_U.S._states_by_economic_growth_rate" title="List of U.S. states by economic growth rate">Growth rate</a></li> +<li><a href="/wiki/List_of_U.S._states_by_GDP_per_capita" title="List of U.S. states by GDP per capita">Per capita</a></li> +</ul> +</li> +<li><a href="/wiki/List_of_U.S._states_by_income" title="List of U.S. states by income">Income</a> +<ul> +<li><a href="/wiki/List_of_U.S._states_by_income#States_ranked_by_median_household_income" title="List of U.S. states by income">Household</a></li> +<li><a href="/wiki/List_of_U.S._states_by_income#States_ranked_by_per_capita_income" title="List of U.S. states by income">Per capita</a></li> +<li><a href="/wiki/List_of_U.S._states_by_Gini_coefficient" title="List of U.S. states by Gini coefficient">Inequality</a></li> +</ul> +</li> +<li><a href="/wiki/Union_affiliation_by_U.S._state" title="Union affiliation by U.S. state">Labor affiliation</a></li> +<li><a href="/wiki/List_of_U.S._state_minimum_wages" title="List of U.S. state minimum wages" class="mw-redirect">Minimum wages</a></li> +<li><a href="/wiki/List_of_U.S._states_by_poverty_rate" title="List of U.S. states by poverty rate">Poverty rates</a></li> +<li><a href="/wiki/Sales_taxes_in_the_United_States#By_jurisdiction" title="Sales taxes in the United States">Sales taxes</a></li> +<li><a href="/wiki/State_tax_levels_in_the_United_States" title="State tax levels in the United States">State income taxes</a> +<ul> +<li><a href="/wiki/State_income_tax#U.S._States_with_a_flat_rate_individual_income_tax" title="State income tax">Flat rate</a></li> +<li><a href="/wiki/State_income_tax#U.S._States_with_no_individual_income_tax" title="State income tax">None</a></li> +</ul> +</li> +<li><a href="/wiki/List_of_U.S._states_by_unemployment_rate" title="List of U.S. states by unemployment rate">Unemployment rates</a></li> +</ul> +</div> +</td> +</tr> +<tr style="height:2px;"> +<td colspan="2"></td> +</tr> +<tr> +<th scope="row" class="navbox-group">Environment</th> +<td class="navbox-list navbox-odd hlist" style="text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px;"> +<div style="padding:0em 0.25em;"> +<ul> +<li><a href="/wiki/List_of_U.S._states_by_carbon_dioxide_emissions" title="List of U.S. states by carbon dioxide emissions">Carbon dioxide emissions</a></li> +<li><a href="/wiki/List_of_U.S._state_parks" title="List of U.S. state parks">Parks</a></li> +<li><a href="/wiki/List_of_U.S._states_by_electricity_production_from_renewable_sources" title="List of U.S. states by electricity production from renewable sources">Renewable energy</a></li> +<li><a href="/wiki/List_of_Superfund_sites_in_the_United_States" title="List of Superfund sites in the United States">Superfund sites</a></li> +<li><a href="/wiki/List_of_U.S._state_and_tribal_wilderness_areas" title="List of U.S. state and tribal wilderness areas">Wildernesses</a></li> +</ul> +</div> +</td> +</tr> +<tr style="height:2px;"> +<td colspan="2"></td> +</tr> +<tr> +<th scope="row" class="navbox-group">Geography</th> +<td class="navbox-list navbox-even hlist" style="text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px;"> +<div style="padding:0em 0.25em;"> +<ul> +<li><strong class="selflink">Area</strong></li> +<li><a href="/wiki/List_of_U.S._states_by_coastline" title="List of U.S. states by coastline">Coastline</a></li> +<li><a href="/wiki/List_of_U.S._states_by_elevation" title="List of U.S. states by elevation">Elevations</a></li> +</ul> +</div> +</td> +</tr> +<tr style="height:2px;"> +<td colspan="2"></td> +</tr> +<tr> +<th scope="row" class="navbox-group">Government</th> +<td class="navbox-list navbox-odd hlist" style="text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px;"> +<div style="padding:0em 0.25em;"> +<ul> +<li><a href="/wiki/Wikipedia:List_of_U.S._state_portals" title="Wikipedia:List of U.S. state portals">Agencies</a></li> +<li><a href="/wiki/State_attorney_general" title="State attorney general">Attorneys general</a></li> +<li><a href="/wiki/List_of_capitals_in_the_United_States" title="List of capitals in the United States">Capitals</a> +<ul> +<li><a href="/wiki/List_of_capitals_in_the_United_States#Historical_state_capitals" title="List of capitals in the United States">Historical</a></li> +</ul> +</li> +<li><a href="/wiki/List_of_state_capitols_in_the_United_States" title="List of state capitols in the United States">Capitol buildings</a></li> +<li><a href="/wiki/Comparison_of_U.S._state_governments" title="Comparison of U.S. state governments">Comparison</a></li> +<li><a href="/wiki/List_of_counties_by_U.S._state" title="List of counties by U.S. state">Counties</a> +<ul> +<li><a href="/wiki/Index_of_U.S._counties" title="Index of U.S. counties">Alphabetical</a></li> +<li><a href="/wiki/County_(United_States)#Number_of_county_equivalents_per_state" title="County (United States)">Number</a></li> +</ul> +</li> +<li><a href="/wiki/List_of_current_United_States_governors" title="List of current United States governors">Governors</a></li> +<li><a href="/wiki/List_of_United_States_state_legislatures" title="List of United States state legislatures">Legislatures</a></li> +<li><a href="/wiki/List_of_U.S._state_libraries_and_archives" title="List of U.S. state libraries and archives">Libraries and archives</a></li> +<li><a href="/wiki/Languages_of_the_United_States#Official_language_status" title="Languages of the United States">Official languages</a></li> +<li><a href="/wiki/List_of_U.S._states%27_Poets_Laureate" title="List of U.S. states' Poets Laureate">Poets laureate</a></li> +<li><a href="/wiki/State_supreme_court" title="State supreme court">State supreme courts</a></li> +<li><a href="/wiki/State_treasurer" title="State treasurer">State treasurers</a></li> +</ul> +</div> +</td> +</tr> +<tr style="height:2px;"> +<td colspan="2"></td> +</tr> +<tr> +<th scope="row" class="navbox-group">Health</th> +<td class="navbox-list navbox-even hlist" style="text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px;"> +<div style="padding:0em 0.25em;"> +<ul> +<li><a href="/wiki/List_of_hospitals_in_the_United_States" title="List of hospitals in the United States">Hospitals</a></li> +<li><a href="/wiki/List_of_U.S._states_by_American_Human_Development_Index" title="List of U.S. states by American Human Development Index">American HDI</a></li> +<li><a href="/wiki/List_of_U.S._states_by_life_expectancy" title="List of U.S. states by life expectancy">Life expectancy</a></li> +<li><a href="/wiki/Obesity_in_the_United_States#Prevalence_by_state" title="Obesity in the United States">Obesity rates</a></li> +<li><a href="/wiki/List_of_U.S._states_and_territories_by_fertility_rate" title="List of U.S. states and territories by fertility rate">Total fertility rates</a></li> +</ul> +</div> +</td> +</tr> +<tr style="height:2px;"> +<td colspan="2"></td> +</tr> +<tr> +<th scope="row" class="navbox-group">History</th> +<td class="navbox-list navbox-odd hlist" style="text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px;"> +<div style="padding:0em 0.25em;"> +<ul> +<li><a href="/wiki/Historic_regions_of_the_United_States" title="Historic regions of the United States">Historic regions of the United States</a></li> +<li><a href="/wiki/List_of_U.S._states_by_date_of_statehood" title="List of U.S. states by date of statehood">Date of statehood</a></li> +<li><a href="/wiki/List_of_U.S._state_name_etymologies" title="List of U.S. state name etymologies">Etymologies</a></li> +<li><a href="/wiki/List_of_capitals_in_the_United_States#Historical_state_capitals" title="List of capitals in the United States">Historical capitals</a></li> +<li><a href="/wiki/List_of_U.S._states_by_historical_population" title="List of U.S. states by historical population">Historical population</a></li> +<li><a href="/wiki/List_of_U.S._state_historical_societies_and_museums" title="List of U.S. state historical societies and museums">Historical societies and museums</a></li> +<li><a href="/wiki/List_of_U.S._National_Historic_Landmarks_by_state" title="List of U.S. National Historic Landmarks by state">National Historic Landmarks</a></li> +<li><a href="/wiki/List_of_U.S._states_that_were_never_U.S._territories" title="List of U.S. states that were never U.S. territories">Never territories</a></li> +<li><a href="/wiki/List_of_U.S._state_partition_proposals" title="List of U.S. state partition proposals">Partition proposals</a></li> +<li><a href="/wiki/List_of_U.S._states_by_date_of_statehood#Table" title="List of U.S. states by date of statehood">Preceding entities</a></li> +</ul> +</div> +</td> +</tr> +<tr style="height:2px;"> +<td colspan="2"></td> +</tr> +<tr> +<th scope="row" class="navbox-group">Law</th> +<td class="navbox-list navbox-even hlist" style="text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px;"> +<div style="padding:0em 0.25em;"> +<ul> +<li><a href="/wiki/Abortion_in_the_United_States_by_state#State_table" title="Abortion in the United States by state">Abortion</a></li> +<li><a href="/wiki/Ages_of_consent_in_North_America#United_States" title="Ages of consent in North America">Age of consent</a></li> +<li><a href="/wiki/Alcohol_laws_of_the_United_States" title="Alcohol laws of the United States">Alcohol</a></li> +<li><a href="/wiki/List_of_U.S._states_by_Alford_plea_usage#U.S._states" title="List of U.S. states by Alford plea usage">Alford plea</a></li> +<li><a href="/wiki/Restrictions_on_cell_phone_use_while_driving_in_the_United_States" title="Restrictions on cell phone use while driving in the United States">Cell phones and driving laws</a></li> +<li><a href="/wiki/List_of_U.S._state_constitutions" title="List of U.S. state constitutions" class="mw-redirect">Constitutions</a></li> +<li><a href="/wiki/Gun_laws_in_the_United_States_by_state" title="Gun laws in the United States by state">Firearms</a> +<ul> +<li><a href="/wiki/Gun_violence_in_the_United_States_by_state" title="Gun violence in the United States by state">Homicide</a></li> +</ul> +</li> +<li><a href="/wiki/List_of_United_States_state_and_local_law_enforcement_agencies" title="List of United States state and local law enforcement agencies">Law enforcement agencies</a></li> +<li><a href="/wiki/List_of_U.S._state_legal_codes" title="List of U.S. state legal codes">Legal codes</a></li> +<li><a href="/wiki/Legality_of_cannabis_by_US_state" title="Legality of cannabis by US state" class="mw-redirect">Legality of cannabis</a></li> +<li><a href="/wiki/United_States_Peace_Index" title="United States Peace Index">Peace Index</a></li> +<li><a href="/wiki/List_of_United_States_state_prisons" title="List of United States state prisons">Prisons</a> +<ul> +<li><a href="/wiki/List_of_U.S._states_by_incarceration_rate" title="List of U.S. states by incarceration rate">Incarceration rate</a></li> +</ul> +</li> +<li><a href="/wiki/Same-sex_marriage_status_in_the_United_States_by_state" title="Same-sex marriage status in the United States by state" class="mw-redirect">Same-sex marriage</a> +<ul> +<li><a href="/wiki/List_of_U.S._state_constitutional_amendments_banning_same-sex_unions_by_type" title="List of U.S. state constitutional amendments banning same-sex unions by type">Constitutional bans</a></li> +<li><a href="/wiki/Same-sex_marriage_law_in_the_United_States_by_state" title="Same-sex marriage law in the United States by state">Law</a></li> +</ul> +</li> +<li><a href="/wiki/Seat_belt_legislation_in_the_United_States#The_laws_by_state" title="Seat belt legislation in the United States">Seat belt laws</a></li> +<li><a href="/wiki/List_of_U.S._state_constitutional_provisions_allowing_self-representation_in_state_courts" title="List of U.S. state constitutional provisions allowing self-representation in state courts">Self-representation</a></li> +<li><a href="/wiki/List_of_smoking_bans_in_the_United_States" title="List of smoking bans in the United States">Smoking</a></li> +</ul> +</div> +</td> +</tr> +<tr style="height:2px;"> +<td colspan="2"></td> +</tr> +<tr> +<th scope="row" class="navbox-group">Miscellaneous</th> +<td class="navbox-list navbox-odd hlist" style="text-align:left;border-left-width:2px;border-left-style:solid;width:100%;padding:0px;"> +<div style="padding:0em 0.25em;"> +<ul> +<li><a href="/wiki/List_of_U.S._state_abbreviations" title="List of U.S. state abbreviations">Abbreviations</a></li> +<li><a href="/wiki/List_of_U.S._state_abbreviations" title="List of U.S. state abbreviations">Codes</a></li> +<li><a href="/wiki/List_of_demonyms_for_U.S._states" title="List of demonyms for U.S. states">Demonyms</a></li> +<li><a href="/wiki/List_of_U.S._state,_district,_and_territorial_insignia" title="List of U.S. state, district, and territorial insignia">Insignia</a></li> +<li><a href="/wiki/List_of_U.S._states_by_vehicles_per_capita" title="List of U.S. states by vehicles per capita">Motor vehicles</a></li> +<li><a href="/wiki/Wikipedia:List_of_U.S._state_portals" title="Wikipedia:List of U.S. state portals">Portals</a></li> +<li><a href="/wiki/Lists_of_United_States_state_insignia" title="Lists of United States state insignia" class="mw-redirect">Symbols</a></li> +<li><a href="/wiki/List_of_tallest_buildings_by_U.S._state" title="List of tallest buildings by U.S. state">Tallest buildings</a></li> +<li><a href="/wiki/List_of_time_zones_by_U.S._state" title="List of time zones by U.S. state" class="mw-redirect">Time zones</a></li> +<li><a href="/wiki/List_of_fictional_U.S._states" title="List of fictional U.S. states">Fictional states</a></li> +</ul> +</div> +</td> +</tr> +</table> +</td> +</tr> +</table> + + +<!-- +NewPP limit report +Parsed by terbium +CPU time usage: 6.220 seconds +Real time usage: 7.420 seconds +Preprocessor visited node count: 33194/1000000 +Preprocessor generated node count: 33781/1500000 +Post‐expand include size: 222845/2048000 bytes +Template argument size: 25771/2048000 bytes +Highest expansion depth: 18/40 +Expensive parser function count: 2/500 +Lua time usage: 0.493/10.000 seconds +Lua memory usage: 4.17 MB/50 MB +--> + +<!-- Saved in parser cache with key enwiki:pcache:idhash:87513-0!*!0!!en!4!* and timestamp 20140725194944 and revision id 614847271 + --> +<noscript><img src="//en.wikipedia.org/wiki/Special:CentralAutoLogin/start?type=1x1" alt="" title="" width="1" height="1" style="border: none; position: absolute;" /></noscript></div> <div class="printfooter"> + Retrieved from "<a dir="ltr" href="http://en.wikipedia.org/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;oldid=614847271">http://en.wikipedia.org/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;oldid=614847271</a>" </div> + <div id='catlinks' class='catlinks'><div id="mw-normal-catlinks" class="mw-normal-catlinks"><a href="/wiki/Help:Category" title="Help:Category">Categories</a>: <ul><li><a href="/wiki/Category:Geography_of_the_United_States" title="Category:Geography of the United States">Geography of the United States</a></li><li><a href="/wiki/Category:Lists_of_states_of_the_United_States" title="Category:Lists of states of the United States">Lists of states of the United States</a></li></ul></div></div> <div class="visualClear"></div> + </div> + </div> + <div id="mw-navigation"> + <h2>Navigation menu</h2> + + <div id="mw-head"> + <div id="p-personal" role="navigation" class="" aria-labelledby="p-personal-label"> + <h3 id="p-personal-label">Personal tools</h3> + <ul> + <li id="pt-createaccount"><a href="/w/index.php?title=Special:UserLogin&amp;returnto=List+of+U.S.+states+and+territories+by+area&amp;type=signup">Create account</a></li><li id="pt-login"><a href="/w/index.php?title=Special:UserLogin&amp;returnto=List+of+U.S.+states+and+territories+by+area" title="You're encouraged to log in; however, it's not mandatory. [o]" accesskey="o">Log in</a></li> </ul> + </div> + <div id="left-navigation"> + <div id="p-namespaces" role="navigation" class="vectorTabs" aria-labelledby="p-namespaces-label"> + <h3 id="p-namespaces-label">Namespaces</h3> + <ul> + <li id="ca-nstab-main" class="selected"><span><a href="/wiki/List_of_U.S._states_and_territories_by_area" title="View the content page [c]" accesskey="c">Article</a></span></li> + <li id="ca-talk"><span><a href="/wiki/Talk:List_of_U.S._states_and_territories_by_area" title="Discussion about the content page [t]" accesskey="t">Talk</a></span></li> + </ul> + </div> + <div id="p-variants" role="navigation" class="vectorMenu emptyPortlet" aria-labelledby="p-variants-label"> + <h3 id="mw-vector-current-variant"> + </h3> + + <h3 id="p-variants-label"><span>Variants</span><a href="#"></a></h3> + + <div class="menu"> + <ul> + </ul> + </div> + </div> + </div> + <div id="right-navigation"> + <div id="p-views" role="navigation" class="vectorTabs" aria-labelledby="p-views-label"> + <h3 id="p-views-label">Views</h3> + <ul> + <li id="ca-view" class="selected"><span><a href="/wiki/List_of_U.S._states_and_territories_by_area" >Read</a></span></li> + <li id="ca-edit"><span><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=edit" title="You can edit this page. Please use the preview button before saving [e]" accesskey="e">Edit</a></span></li> + <li id="ca-history" class="collapsible"><span><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=history" title="Past versions of this page [h]" accesskey="h">View history</a></span></li> + </ul> + </div> + <div id="p-cactions" role="navigation" class="vectorMenu emptyPortlet" aria-labelledby="p-cactions-label"> + <h3 id="p-cactions-label"><span>More</span><a href="#"></a></h3> + + <div class="menu"> + <ul> + </ul> + </div> + </div> + <div id="p-search" role="search"> + <h3> + <label for="searchInput">Search</label> + </h3> + + <form action="/w/index.php" id="searchform"> + <div id="simpleSearch"> + <input type="search" name="search" placeholder="Search" title="Search Wikipedia [f]" accesskey="f" id="searchInput" /><input type="hidden" value="Special:Search" name="title" /><input type="submit" name="fulltext" value="Search" title="Search Wikipedia for this text" id="mw-searchButton" class="searchButton mw-fallbackSearchButton" /><input type="submit" name="go" value="Go" title="Go to a page with this exact name if one exists" id="searchButton" class="searchButton" /> </div> + </form> + </div> + </div> + </div> + <div id="mw-panel"> + <div id="p-logo" role="banner"><a style="background-image: url(//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png);" href="/wiki/Main_Page" title="Visit the main page"></a></div> + <div class="portal" role="navigation" id='p-navigation' aria-labelledby='p-navigation-label'> + <h3 id='p-navigation-label'>Navigation</h3> + + <div class="body"> + <ul> + <li id="n-mainpage-description"><a href="/wiki/Main_Page" title="Visit the main page [z]" accesskey="z">Main page</a></li> + <li id="n-contents"><a href="/wiki/Portal:Contents" title="Guides to browsing Wikipedia">Contents</a></li> + <li id="n-featuredcontent"><a href="/wiki/Portal:Featured_content" title="Featured content – the best of Wikipedia">Featured content</a></li> + <li id="n-currentevents"><a href="/wiki/Portal:Current_events" title="Find background information on current events">Current events</a></li> + <li id="n-randompage"><a href="/wiki/Special:Random" title="Load a random article [x]" accesskey="x">Random article</a></li> + <li id="n-sitesupport"><a href="https://donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&amp;utm_medium=sidebar&amp;utm_campaign=C13_en.wikipedia.org&amp;uselang=en" title="Support us">Donate to Wikipedia</a></li> + <li id="n-shoplink"><a href="//shop.wikimedia.org" title="Visit the Wikimedia Shop">Wikimedia Shop</a></li> + </ul> + </div> + </div> + <div class="portal" role="navigation" id='p-interaction' aria-labelledby='p-interaction-label'> + <h3 id='p-interaction-label'>Interaction</h3> + + <div class="body"> + <ul> + <li id="n-help"><a href="/wiki/Help:Contents" title="Guidance on how to use and edit Wikipedia">Help</a></li> + <li id="n-aboutsite"><a href="/wiki/Wikipedia:About" title="Find out about Wikipedia">About Wikipedia</a></li> + <li id="n-portal"><a href="/wiki/Wikipedia:Community_portal" title="About the project, what you can do, where to find things">Community portal</a></li> + <li id="n-recentchanges"><a href="/wiki/Special:RecentChanges" title="A list of recent changes in the wiki [r]" accesskey="r">Recent changes</a></li> + <li id="n-contactpage"><a href="//en.wikipedia.org/wiki/Wikipedia:Contact_us">Contact page</a></li> + </ul> + </div> + </div> + <div class="portal" role="navigation" id='p-tb' aria-labelledby='p-tb-label'> + <h3 id='p-tb-label'>Tools</h3> + + <div class="body"> + <ul> + <li id="t-whatlinkshere"><a href="/wiki/Special:WhatLinksHere/List_of_U.S._states_and_territories_by_area" title="List of all English Wikipedia pages containing links to this page [j]" accesskey="j">What links here</a></li> + <li id="t-recentchangeslinked"><a href="/wiki/Special:RecentChangesLinked/List_of_U.S._states_and_territories_by_area" title="Recent changes in pages linked from this page [k]" accesskey="k">Related changes</a></li> + <li id="t-upload"><a href="/wiki/Wikipedia:File_Upload_Wizard" title="Upload files [u]" accesskey="u">Upload file</a></li> + <li id="t-specialpages"><a href="/wiki/Special:SpecialPages" title="A list of all special pages [q]" accesskey="q">Special pages</a></li> + <li id="t-permalink"><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;oldid=614847271" title="Permanent link to this revision of the page">Permanent link</a></li> + <li id="t-info"><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;action=info">Page information</a></li> + <li id="t-wikibase"><a href="//www.wikidata.org/wiki/Q150340" title="Link to connected data repository item [g]" accesskey="g">Wikidata item</a></li> + <li id="t-cite"><a href="/w/index.php?title=Special:Cite&amp;page=List_of_U.S._states_and_territories_by_area&amp;id=614847271" title="Information on how to cite this page">Cite this page</a></li> </ul> + </div> + </div> + <div class="portal" role="navigation" id='p-coll-print_export' aria-labelledby='p-coll-print_export-label'> + <h3 id='p-coll-print_export-label'>Print/export</h3> + + <div class="body"> + <ul> + <li id="coll-create_a_book"><a href="/w/index.php?title=Special:Book&amp;bookcmd=book_creator&amp;referer=List+of+U.S.+states+and+territories+by+area">Create a book</a></li> + <li id="coll-download-as-rl"><a href="/w/index.php?title=Special:Book&amp;bookcmd=render_article&amp;arttitle=List+of+U.S.+states+and+territories+by+area&amp;oldid=614847271&amp;writer=rl">Download as PDF</a></li> + <li id="t-print"><a href="/w/index.php?title=List_of_U.S._states_and_territories_by_area&amp;printable=yes" title="Printable version of this page [p]" accesskey="p">Printable version</a></li> + </ul> + </div> + </div> + <div class="portal" role="navigation" id='p-lang' aria-labelledby='p-lang-label'> + <h3 id='p-lang-label'>Languages</h3> + + <div class="body"> + <ul> + <li class="interlanguage-link interwiki-ar"><a href="//ar.wikipedia.org/wiki/%D9%85%D9%84%D8%AD%D9%82:%D9%82%D8%A7%D8%A6%D9%85%D8%A9_%D8%A7%D9%84%D9%88%D9%84%D8%A7%D9%8A%D8%A7%D8%AA_%D8%A7%D9%84%D8%A3%D9%85%D8%B1%D9%8A%D9%83%D9%8A%D8%A9_%D8%AD%D8%B3%D8%A8_%D8%A7%D9%84%D9%85%D8%B3%D8%A7%D8%AD%D8%A9" title="ملحق:قائمة الولايات الأمريكية حسب المساحة – Arabic" lang="ar" hreflang="ar">العربية</a></li> + <li class="interlanguage-link interwiki-bg"><a href="//bg.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D1%8A%D0%BA_%D0%BD%D0%B0_%D1%89%D0%B0%D1%82%D0%B8%D1%82%D0%B5_%D0%B2_%D0%A1%D0%90%D0%A9_%D0%BF%D0%BE_%D0%BF%D0%BB%D0%BE%D1%89" title="Списък на щатите в САЩ по площ – Bulgarian" lang="bg" hreflang="bg">Български</a></li> + <li class="interlanguage-link interwiki-bar"><a href="//bar.wikipedia.org/wiki/Bundesstootn_vo_da_USA_noch_Fl%C3%A4chn" title="Bundesstootn vo da USA noch Flächn – Bavarian" lang="bar" hreflang="bar">Boarisch</a></li> + <li class="interlanguage-link interwiki-ca"><a href="//ca.wikipedia.org/wiki/Llista_d%27estats_dels_Estats_Units_per_superf%C3%ADcie" title="Llista d'estats dels Estats Units per superfície – Catalan" lang="ca" hreflang="ca">Català</a></li> + <li class="interlanguage-link interwiki-cs"><a href="//cs.wikipedia.org/wiki/Seznam_st%C3%A1t%C5%AF_a_teritori%C3%AD_USA_podle_rozlohy" title="Seznam států a teritorií USA podle rozlohy – Czech" lang="cs" hreflang="cs">Čeština</a></li> + <li class="interlanguage-link interwiki-cy"><a href="//cy.wikipedia.org/wiki/Rhestr_taleithau%27r_Unol_Daleithiau_yn_%C3%B4l_arwynebedd" title="Rhestr taleithau'r Unol Daleithiau yn ôl arwynebedd – Welsh" lang="cy" hreflang="cy">Cymraeg</a></li> + <li class="interlanguage-link interwiki-da"><a href="//da.wikipedia.org/wiki/USA%27s_delstater_efter_areal" title="USA's delstater efter areal – Danish" lang="da" hreflang="da">Dansk</a></li> + <li class="interlanguage-link interwiki-de"><a href="//de.wikipedia.org/wiki/Liste_der_Bundesstaaten_der_Vereinigten_Staaten_nach_Fl%C3%A4che" title="Liste der Bundesstaaten der Vereinigten Staaten nach Fläche – German" lang="de" hreflang="de">Deutsch</a></li> + <li class="interlanguage-link interwiki-el"><a href="//el.wikipedia.org/wiki/%CE%9A%CE%B1%CF%84%CE%AC%CE%BB%CE%BF%CE%B3%CE%BF%CF%82_%CF%80%CE%BF%CE%BB%CE%B9%CF%84%CE%B5%CE%B9%CF%8E%CE%BD_%CE%BA%CE%B1%CE%B9_%CE%B5%CE%B4%CE%B1%CF%86%CF%8E%CE%BD_%CF%84%CF%89%CE%BD_%CE%97%CE%A0%CE%91_%CE%B1%CE%BD%CE%AC_%CE%AD%CE%BA%CF%84%CE%B1%CF%83%CE%B7" title="Κατάλογος πολιτειών και εδαφών των ΗΠΑ ανά έκταση – Greek" lang="el" hreflang="el">Ελληνικά</a></li> + <li class="interlanguage-link interwiki-es"><a href="//es.wikipedia.org/wiki/Anexo:Estados_de_los_Estados_Unidos_por_superficie" title="Anexo:Estados de los Estados Unidos por superficie – Spanish" lang="es" hreflang="es">Español</a></li> + <li class="interlanguage-link interwiki-fr"><a href="//fr.wikipedia.org/wiki/%C3%89tats_des_%C3%89tats-Unis_par_superficie" title="États des États-Unis par superficie – French" lang="fr" hreflang="fr">Français</a></li> + <li class="interlanguage-link interwiki-ga"><a href="//ga.wikipedia.org/wiki/Liosta_st%C3%A1it_SAM_de_r%C3%A9ir_achair" title="Liosta stáit SAM de réir achair – Irish" lang="ga" hreflang="ga">Gaeilge</a></li> + <li class="interlanguage-link interwiki-gl"><a href="//gl.wikipedia.org/wiki/Lista_dos_estados_dos_EUA_por_%C3%A1rea" title="Lista dos estados dos EUA por área – Galician" lang="gl" hreflang="gl">Galego</a></li> + <li class="interlanguage-link interwiki-ilo"><a href="//ilo.wikipedia.org/wiki/Listaan_dagiti_estado_ken_territorio_iti_Estados_Unidos_babaen_ti_kadakkel" title="Listaan dagiti estado ken territorio iti Estados Unidos babaen ti kadakkel – Iloko" lang="ilo" hreflang="ilo">Ilokano</a></li> + <li class="interlanguage-link interwiki-it"><a href="//it.wikipedia.org/wiki/Stati_degli_Stati_Uniti_d%27America_per_superficie" title="Stati degli Stati Uniti d'America per superficie – Italian" lang="it" hreflang="it">Italiano</a></li> + <li class="interlanguage-link interwiki-jv"><a href="//jv.wikipedia.org/wiki/Dhaptar_negara_bag%C3%A9an_Am%C3%A9rika_Sar%C3%A9kat_miturut_jembar_wewengkon" title="Dhaptar negara bagéan Amérika Sarékat miturut jembar wewengkon – Javanese" lang="jv" hreflang="jv">Basa Jawa</a></li> + <li class="interlanguage-link interwiki-la"><a href="//la.wikipedia.org/wiki/Index_civitatum_Americae_per_superficiem" title="Index civitatum Americae per superficiem – Latin" lang="la" hreflang="la">Latina</a></li> + <li class="interlanguage-link interwiki-hu"><a href="//hu.wikipedia.org/wiki/Az_Amerikai_Egyes%C3%BClt_%C3%81llamok_tag%C3%A1llamainak_list%C3%A1ja_ter%C3%BClet%C3%BCk_szerint" title="Az Amerikai Egyesült Államok tagállamainak listája területük szerint – Hungarian" lang="hu" hreflang="hu">Magyar</a></li> + <li class="interlanguage-link interwiki-mk"><a href="//mk.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D0%BD%D0%B0_%D1%81%D0%BE%D1%98%D1%83%D0%B7%D0%BD%D0%B8_%D0%B4%D1%80%D0%B6%D0%B0%D0%B2%D0%B8_%D0%B8_%D1%82%D0%B5%D1%80%D0%B8%D1%82%D0%BE%D1%80%D0%B8%D0%B8_%D0%BD%D0%B0_%D0%A1%D0%90%D0%94_%D0%BF%D0%BE_%D0%BF%D0%BE%D0%B2%D1%80%D1%88%D0%B8%D0%BD%D0%B0" title="Список на сојузни држави и територии на САД по површина – Macedonian" lang="mk" hreflang="mk">Македонски</a></li> + <li class="interlanguage-link interwiki-no"><a href="//no.wikipedia.org/wiki/Liste_over_USAs_delstater_etter_areal" title="Liste over USAs delstater etter areal – Norwegian (bokmål)" lang="no" hreflang="no">Norsk bokmål</a></li> + <li class="interlanguage-link interwiki-pl"><a href="//pl.wikipedia.org/wiki/Stany_USA_wed%C5%82ug_powierzchni" title="Stany USA według powierzchni – Polish" lang="pl" hreflang="pl">Polski</a></li> + <li class="interlanguage-link interwiki-pt"><a href="//pt.wikipedia.org/wiki/Anexo:Lista_de_estados_e_territ%C3%B3rios_dos_Estados_Unidos_por_%C3%A1rea" title="Anexo:Lista de estados e territórios dos Estados Unidos por área – Portuguese" lang="pt" hreflang="pt">Português</a></li> + <li class="interlanguage-link interwiki-ro"><a href="//ro.wikipedia.org/wiki/List%C4%83_a_statelor_SUA_ordonate_dup%C4%83_m%C4%83rimea_suprafe%C8%9Bei" title="Listă a statelor SUA ordonate după mărimea suprafeței – Romanian" lang="ro" hreflang="ro">Română</a></li> + <li class="interlanguage-link interwiki-sq"><a href="//sq.wikipedia.org/wiki/Renditja_e_Shteteve_t%C3%AB_SHBA-s%C3%AB_sipas_Sip%C3%ABrfaqes" title="Renditja e Shteteve të SHBA-së sipas Sipërfaqes – Albanian" lang="sq" hreflang="sq">Shqip</a></li> + <li class="interlanguage-link interwiki-simple"><a href="//simple.wikipedia.org/wiki/List_of_U.S._states_by_area" title="List of U.S. states by area – Simple English" lang="simple" hreflang="simple">Simple English</a></li> + <li class="interlanguage-link interwiki-sk"><a href="//sk.wikipedia.org/wiki/Zoznam_%C5%A1t%C3%A1tov_a_terit%C3%B3ri%C3%AD_USA_pod%C4%BEa_rozlohy" title="Zoznam štátov a teritórií USA podľa rozlohy – Slovak" lang="sk" hreflang="sk">Slovenčina</a></li> + <li class="interlanguage-link interwiki-sr"><a href="//sr.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%B0%D0%BA_%D1%81%D0%B0%D0%B2%D0%B5%D0%B7%D0%BD%D0%B8%D1%85_%D0%B4%D1%80%D0%B6%D0%B0%D0%B2%D0%B0_%D0%B8_%D1%82%D0%B5%D1%80%D0%B8%D1%82%D0%BE%D1%80%D0%B8%D1%98%D0%B0_%D0%A1%D0%90%D0%94_%D0%BF%D0%BE_%D0%BF%D0%BE%D0%B2%D1%80%D1%88%D0%B8%D0%BD%D0%B8" title="Списак савезних држава и територија САД по површини – Serbian" lang="sr" hreflang="sr">Српски / srpski</a></li> + <li class="interlanguage-link interwiki-fi"><a href="//fi.wikipedia.org/wiki/Luettelo_Yhdysvaltain_osavaltioista_pinta-alan_mukaan" title="Luettelo Yhdysvaltain osavaltioista pinta-alan mukaan – Finnish" lang="fi" hreflang="fi">Suomi</a></li> + <li class="interlanguage-link interwiki-sv"><a href="//sv.wikipedia.org/wiki/Lista_%C3%B6ver_USA:s_delstater_och_territorier_efter_yta" title="Lista över USA:s delstater och territorier efter yta – Swedish" lang="sv" hreflang="sv">Svenska</a></li> + <li class="interlanguage-link interwiki-ur"><a href="//ur.wikipedia.org/wiki/%D9%81%DB%81%D8%B1%D8%B3%D8%AA_%D8%A7%D9%85%D8%B1%DB%8C%DA%A9%DB%8C_%D8%B1%DB%8C%D8%A7%D8%B3%D8%AA%DB%8C%DA%BA_%D8%A7%D9%88%D8%B1_%D8%B9%D9%84%D8%A7%D9%82%DB%81_%D8%AC%D8%A7%D8%AA_%D8%A8%D9%84%D8%AD%D8%A7%D8%B8_%D8%B1%D9%82%D8%A8%DB%81" title="فہرست امریکی ریاستیں اور علاقہ جات بلحاظ رقبہ – Urdu" lang="ur" hreflang="ur">اردو</a></li> + <li class="interlanguage-link interwiki-vi"><a href="//vi.wikipedia.org/wiki/Danh_s%C3%A1ch_ti%E1%BB%83u_bang_Hoa_K%E1%BB%B3_theo_di%E1%BB%87n_t%C3%ADch" title="Danh sách tiểu bang Hoa Kỳ theo diện tích – Vietnamese" lang="vi" hreflang="vi">Tiếng Việt</a></li> + <li class="interlanguage-link interwiki-zh"><a href="//zh.wikipedia.org/wiki/%E7%BE%8E%E5%9B%BD%E5%90%84%E5%B7%9E%E9%9D%A2%E7%A7%AF%E5%88%97%E8%A1%A8" title="美国各州面积列表 – Chinese" lang="zh" hreflang="zh">中文</a></li> + <li class="uls-p-lang-dummy"><a href="#"></a></li> + </ul> + <div class='after-portlet after-portlet-lang'><span class="wb-langlinks-edit wb-langlinks-link"><a action="edit" href="//www.wikidata.org/wiki/Q150340#sitelinks-wikipedia" text="Edit links" title="Edit interlanguage links" class="wbc-editpage">Edit links</a></span></div> </div> + </div> + </div> + </div> + <div id="footer" role="contentinfo"> + <ul id="footer-info"> + <li id="footer-info-lastmod"> This page was last modified on 29 June 2014 at 05:36.<br /></li> + <li id="footer-info-copyright">Text is available under the <a rel="license" href="//en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License">Creative Commons Attribution-ShareAlike License</a><a rel="license" href="//creativecommons.org/licenses/by-sa/3.0/" style="display:none;"></a>; +additional terms may apply. By using this site, you agree to the <a href="//wikimediafoundation.org/wiki/Terms_of_Use">Terms of Use</a> and <a href="//wikimediafoundation.org/wiki/Privacy_policy">Privacy Policy</a>. Wikipedia® is a registered trademark of the <a href="//www.wikimediafoundation.org/">Wikimedia Foundation, Inc.</a>, a non-profit organization.</li> + </ul> + <ul id="footer-places"> + <li id="footer-places-privacy"><a href="//wikimediafoundation.org/wiki/Privacy_policy" title="wikimedia:Privacy policy">Privacy policy</a></li> + <li id="footer-places-about"><a href="/wiki/Wikipedia:About" title="Wikipedia:About">About Wikipedia</a></li> + <li id="footer-places-disclaimer"><a href="/wiki/Wikipedia:General_disclaimer" title="Wikipedia:General disclaimer">Disclaimers</a></li> + <li id="footer-places-contact"><a href="//en.wikipedia.org/wiki/Wikipedia:Contact_us">Contact Wikipedia</a></li> + <li id="footer-places-developers"><a href="https://www.mediawiki.org/wiki/Special:MyLanguage/How_to_contribute">Developers</a></li> + <li id="footer-places-mobileview"><a href="//en.m.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_area" class="noprint stopMobileRedirectToggle">Mobile view</a></li> + </ul> + <ul id="footer-icons" class="noprint"> + <li id="footer-copyrightico"> + <a href="//wikimediafoundation.org/"><img src="//bits.wikimedia.org/images/wikimedia-button.png" width="88" height="31" alt="Wikimedia Foundation"/></a> + </li> + <li id="footer-poweredbyico"> + <a href="//www.mediawiki.org/"><img src="//bits.wikimedia.org/static-1.24wmf14/skins/common/images/poweredby_mediawiki_88x31.png" alt="Powered by MediaWiki" width="88" height="31" /></a> + </li> + </ul> + <div style="clear:both"></div> + </div> + <script>/*<![CDATA[*/window.jQuery && jQuery.ready();/*]]>*/</script><script>if(window.mw){ +mw.loader.state({"site":"loading","user":"ready","user.groups":"ready"}); +}</script> +<script>if(window.mw){ +mw.loader.load(["ext.cite","mediawiki.toc","mobile.desktop","mediawiki.action.view.postEdit","mediawiki.user","mediawiki.hidpi","mediawiki.page.ready","mediawiki.searchSuggest","ext.gadget.teahouse","ext.gadget.ReferenceTooltips","ext.gadget.DRN-wizard","ext.gadget.charinsert","ext.gadget.refToolbar","mmv.bootstrap.autostart","ext.eventLogging.subscriber","ext.navigationTiming","schema.UniversalLanguageSelector","ext.uls.eventlogger","ext.uls.interlanguage"],null,true); +}</script> +<script src="//bits.wikimedia.org/en.wikipedia.org/load.php?debug=false&amp;lang=en&amp;modules=site&amp;only=scripts&amp;skin=vector&amp;*"></script> +<script>if(window.mw){ +mw.config.set({"wgBackendResponseTime":215,"wgHostname":"mw1025"}); +}</script> + </body> +</html> + \ No newline at end of file diff --git a/pandas/io/tests/test_html.py b/pandas/io/tests/test_html.py index a7540fc716e1f..ecfc4c87d585d 100644 --- a/pandas/io/tests/test_html.py +++ b/pandas/io/tests/test_html.py @@ -86,26 +86,21 @@ def test_bs4_version_fails(): flavor='bs4') -class TestReadHtml(tm.TestCase): - @classmethod - def setUpClass(cls): - super(TestReadHtml, cls).setUpClass() - _skip_if_none_of(('bs4', 'html5lib')) - +class ReadHtmlMixin(object): def read_html(self, *args, **kwargs): - kwargs['flavor'] = kwargs.get('flavor', self.flavor) + kwargs.setdefault('flavor', self.flavor) return read_html(*args, **kwargs) - def setup_data(self): - self.spam_data = os.path.join(DATA_PATH, 'spam.html') - self.banklist_data = os.path.join(DATA_PATH, 'banklist.html') - def setup_flavor(self): - self.flavor = 'bs4' +class TestReadHtml(tm.TestCase, ReadHtmlMixin): + flavor = 'bs4' + spam_data = os.path.join(DATA_PATH, 'spam.html') + banklist_data = os.path.join(DATA_PATH, 'banklist.html') - def setUp(self): - self.setup_data() - self.setup_flavor() + @classmethod + def setUpClass(cls): + super(TestReadHtml, cls).setUpClass() + _skip_if_none_of(('bs4', 'html5lib')) def test_to_html_compat(self): df = mkdf(4, 3, data_gen_f=lambda *args: rand(), c_idx_names=False, @@ -262,8 +257,7 @@ def test_infer_types(self): df2 = self.read_html(self.spam_data, 'Unit', index_col=0, infer_types=True) - with tm.assertRaises(AssertionError): - assert_framelist_equal(df1, df2) + assert_framelist_equal(df1, df2) def test_string_io(self): with open(self.spam_data) as f: @@ -568,7 +562,9 @@ def test_different_number_of_rows(self): def test_parse_dates_list(self): df = DataFrame({'date': date_range('1/1/2001', periods=10)}) expected = df.to_html() - res = self.read_html(expected, parse_dates=[0], index_col=0) + res = self.read_html(expected, parse_dates=[1], index_col=0) + tm.assert_frame_equal(df, res[0]) + res = self.read_html(expected, parse_dates=['date'], index_col=0) tm.assert_frame_equal(df, res[0]) def test_parse_dates_combine(self): @@ -588,6 +584,13 @@ def test_computer_sales_page(self): with tm.assert_produces_warning(FutureWarning): self.read_html(data, infer_types=False, header=[0, 1]) + def test_wikipedia_states_table(self): + data = os.path.join(DATA_PATH, 'wikipedia_states.html') + assert os.path.isfile(data), '%r is not a file' % data + assert os.path.getsize(data), '%r is an empty file' % data + result = self.read_html(data, 'Arizona', header=1)[0] + nose.tools.assert_equal(result['sq mi'].dtype, np.dtype('float64')) + def _lang_enc(filename): return os.path.splitext(os.path.basename(filename))[0].split('_') @@ -637,31 +640,28 @@ def setUpClass(cls): _skip_if_no(cls.flavor) -class TestReadHtmlLxml(tm.TestCase): +class TestReadHtmlLxml(tm.TestCase, ReadHtmlMixin): + flavor = 'lxml' + @classmethod def setUpClass(cls): super(TestReadHtmlLxml, cls).setUpClass() _skip_if_no('lxml') - def read_html(self, *args, **kwargs): - self.flavor = ['lxml'] - kwargs['flavor'] = kwargs.get('flavor', self.flavor) - return read_html(*args, **kwargs) - def test_data_fail(self): from lxml.etree import XMLSyntaxError spam_data = os.path.join(DATA_PATH, 'spam.html') banklist_data = os.path.join(DATA_PATH, 'banklist.html') with tm.assertRaises(XMLSyntaxError): - self.read_html(spam_data, flavor=['lxml']) + self.read_html(spam_data) with tm.assertRaises(XMLSyntaxError): - self.read_html(banklist_data, flavor=['lxml']) + self.read_html(banklist_data) def test_works_on_valid_markup(self): filename = os.path.join(DATA_PATH, 'valid_markup.html') - dfs = self.read_html(filename, index_col=0, flavor=['lxml']) + dfs = self.read_html(filename, index_col=0) tm.assert_isinstance(dfs, list) tm.assert_isinstance(dfs[0], DataFrame) @@ -674,7 +674,9 @@ def test_fallback_success(self): def test_parse_dates_list(self): df = DataFrame({'date': date_range('1/1/2001', periods=10)}) expected = df.to_html() - res = self.read_html(expected, parse_dates=[0], index_col=0) + res = self.read_html(expected, parse_dates=[1], index_col=0) + tm.assert_frame_equal(df, res[0]) + res = self.read_html(expected, parse_dates=['date'], index_col=0) tm.assert_frame_equal(df, res[0]) def test_parse_dates_combine(self): @@ -694,8 +696,8 @@ def test_computer_sales_page(self): def test_invalid_flavor(): url = 'google.com' - nose.tools.assert_raises(ValueError, read_html, url, 'google', - flavor='not a* valid**++ flaver') + with tm.assertRaises(ValueError): + read_html(url, 'google', flavor='not a* valid**++ flaver') def get_elements_from_file(url, element='table'):
Also, `infer_types` now has no effect _for real_ :) closes #7762 closes #7032
https://api.github.com/repos/pandas-dev/pandas/pulls/7851
2014-07-26T14:47:20Z
2014-07-28T13:24:39Z
2014-07-28T13:24:39Z
2014-07-28T13:24:39Z
BUG: fix multi-column sort that includes Categoricals / concat (GH7848/GH7864)
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index b0267c3dc5163..9279d8b0288c4 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -116,7 +116,8 @@ Categoricals in Series/DataFrame ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :class:`~pandas.Categorical` can now be included in `Series` and `DataFrames` and gained new -methods to manipulate. Thanks to Jan Schultz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`, :issue:`7444`, :issue:`7839`). +methods to manipulate. Thanks to Jan Schultz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`, +:issue:`7444`, :issue:`7839`, :issue:`7848`, :issue:`7864`). For full docs, see the :ref:`Categorical introduction <categorical>` and the :ref:`API documentation <api.categorical>`. diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index d049a6d64aac3..f9ed6c2fecc3c 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -16,7 +16,6 @@ from pandas.core.config import get_option from pandas.core import format as fmt - def _cat_compare_op(op): def f(self, other): if isinstance(other, (Categorical, np.ndarray)): @@ -45,16 +44,6 @@ def _maybe_to_categorical(array): return array -def _get_codes_for_values(values, levels): - from pandas.core.algorithms import _get_data_algo, _hashtables - if values.dtype != levels.dtype: - values = com._ensure_object(values) - levels = com._ensure_object(levels) - (hash_klass, vec_klass), vals = _get_data_algo(values, _hashtables) - t = hash_klass(len(levels)) - t.map_locations(levels) - return com._ensure_platform_int(t.lookup(values)) - _codes_doc = """The level codes of this categorical. Level codes are an array if integer which are the positions of the real @@ -484,7 +473,7 @@ def argsort(self, ascending=True, **kwargs): result = result[::-1] return result - def order(self, inplace=False, ascending=True, **kwargs): + def order(self, inplace=False, ascending=True, na_position='last', **kwargs): """ Sorts the Category by level value returning a new Categorical by default. Only ordered Categoricals can be sorted! @@ -495,11 +484,11 @@ def order(self, inplace=False, ascending=True, **kwargs): ---------- ascending : boolean, default True Sort ascending. Passing False sorts descending + inplace : boolean, default False + Do operation in place. na_position : {'first', 'last'} (optional, default='last') 'first' puts NaNs at the beginning 'last' puts NaNs at the end - inplace : boolean, default False - Do operation in place. Returns ------- @@ -511,18 +500,22 @@ def order(self, inplace=False, ascending=True, **kwargs): """ if not self.ordered: raise TypeError("Categorical not ordered") - _sorted = np.sort(self._codes.copy()) + if na_position not in ['last','first']: + raise ValueError('invalid na_position: {!r}'.format(na_position)) + + codes = np.sort(self._codes.copy()) if not ascending: - _sorted = _sorted[::-1] + codes = codes[::-1] + if inplace: - self._codes = _sorted + self._codes = codes return else: - return Categorical(values=_sorted,levels=self.levels, ordered=self.ordered, + return Categorical(values=codes,levels=self.levels, ordered=self.ordered, name=self.name, fastpath=True) - def sort(self, inplace=True, ascending=True, **kwargs): + def sort(self, inplace=True, ascending=True, na_position='last', **kwargs): """ Sorts the Category inplace by level value. Only ordered Categoricals can be sorted! @@ -533,11 +526,11 @@ def sort(self, inplace=True, ascending=True, **kwargs): ---------- ascending : boolean, default True Sort ascending. Passing False sorts descending + inplace : boolean, default False + Do operation in place. na_position : {'first', 'last'} (optional, default='last') 'first' puts NaNs at the beginning 'last' puts NaNs at the end - inplace : boolean, default False - Do operation in place. Returns ------- @@ -932,3 +925,20 @@ def describe(self): result.index.name = 'levels' result.columns = ['counts','freqs'] return result + +##### utility routines ##### + +def _get_codes_for_values(values, levels): + """" + utility routine to turn values into codes given the specified levels + """ + + from pandas.core.algorithms import _get_data_algo, _hashtables + if values.dtype != levels.dtype: + values = com._ensure_object(values) + levels = com._ensure_object(levels) + (hash_klass, vec_klass), vals = _get_data_algo(values, _hashtables) + t = hash_klass(len(levels)) + t.map_locations(levels) + return com._ensure_platform_int(t.lookup(values)) + diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 48c3b4ece1d95..9659d4c3bd6e0 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -3415,34 +3415,38 @@ def _lexsort_indexer(keys, orders=None, na_position='last'): orders = [True] * len(keys) for key, order in zip(keys, orders): - key = np.asanyarray(key) - rizer = _hash.Factorizer(len(key)) - if not key.dtype == np.object_: - key = key.astype('O') + # we are already a Categorical + if is_categorical_dtype(key): + c = key - # factorize maps nans to na_sentinel=-1 - ids = rizer.factorize(key, sort=True) - n = len(rizer.uniques) - mask = (ids == -1) + # create the Categorical + else: + c = Categorical(key,ordered=True) + + if na_position not in ['last','first']: + raise ValueError('invalid na_position: {!r}'.format(na_position)) + + n = len(c.levels) + codes = c.codes.copy() + + mask = (c.codes == -1) if order: # ascending if na_position == 'last': - ids = np.where(mask, n, ids) + codes = np.where(mask, n, codes) elif na_position == 'first': - ids += 1 - else: - raise ValueError('invalid na_position: {!r}'.format(na_position)) + codes += 1 else: # not order means descending if na_position == 'last': - ids = np.where(mask, n, n-ids-1) + codes = np.where(mask, n, n-codes-1) elif na_position == 'first': - ids = np.where(mask, 0, n-ids) - else: - raise ValueError('invalid na_position: {!r}'.format(na_position)) + codes = np.where(mask, 0, n-codes) if mask.any(): n += 1 + shape.append(n) - labels.append(ids) + labels.append(codes) + return _indexer_from_factorized(labels, shape) def _nargsort(items, kind='quicksort', ascending=True, na_position='last'): diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 98e8d4f88104f..23ba06938825d 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -451,9 +451,9 @@ def to_native_types(self, slicer=None, na_rep='', **kwargs): values[mask] = na_rep return values.tolist() - def _validate_merge(self, blocks): - """ validate that we can merge these blocks """ - return True + def _concat_blocks(self, blocks, values): + """ return the block concatenation """ + return self._holder(values[0]) # block actions #### def copy(self, deep=True): @@ -1639,15 +1639,19 @@ def _astype(self, dtype, copy=False, raise_on_error=True, values=None, ndim=self.ndim, placement=self.mgr_locs) - def _validate_merge(self, blocks): - """ validate that we can merge these blocks """ + def _concat_blocks(self, blocks, values): + """ + validate that we can merge these blocks + + return the block concatenation + """ levels = self.values.levels for b in blocks: if not levels.equals(b.values.levels): raise ValueError("incompatible levels in categorical block merge") - return True + return self._holder(values[0], levels=levels) def to_native_types(self, slicer=None, na_rep='', **kwargs): """ convert to our native types format, slicing if desired """ @@ -4026,17 +4030,11 @@ def concatenate_join_units(join_units, concat_axis, copy): else: concat_values = com._concat_compat(to_concat, axis=concat_axis) - # FIXME: optimization potential: if len(join_units) == 1, single join unit - # is densified and sparsified back. if any(unit.needs_block_conversion for unit in join_units): # need to ask the join unit block to convert to the underlying repr for us blocks = [ unit.block for unit in join_units if unit.block is not None ] - - # may need to validate this combination - blocks[0]._validate_merge(blocks) - - return blocks[0]._holder(concat_values[0]) + return blocks[0]._concat_blocks(blocks, concat_values) else: return concat_values diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index b70e50eb3d030..642912805d06d 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -983,6 +983,47 @@ def f(): df.sort(columns=["unsort"], ascending=False) self.assertRaises(TypeError, f) + # multi-columns sort + # GH 7848 + df = DataFrame({"id":[6,5,4,3,2,1], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']}) + df["grade"] = pd.Categorical(df["raw_grade"]) + df['grade'].cat.reorder_levels(['b', 'e', 'a']) + + # sorts 'grade' according to the order of the levels + result = df.sort(columns=['grade']) + expected = df.iloc[[1,2,5,0,3,4]] + tm.assert_frame_equal(result,expected) + + # multi + result = df.sort(columns=['grade', 'id']) + expected = df.iloc[[2,1,5,4,3,0]] + tm.assert_frame_equal(result,expected) + + # reverse + cat = Categorical(["a","c","c","b","d"], ordered=True) + res = cat.order(ascending=False) + exp_val = np.array(["d","c", "c", "b","a"],dtype=object) + exp_levels = np.array(["a","b","c","d"],dtype=object) + self.assert_numpy_array_equal(res.__array__(), exp_val) + self.assert_numpy_array_equal(res.levels, exp_levels) + + # some NaN positions + + cat = Categorical(["a","c","b","d", np.nan], ordered=True) + res = cat.order(ascending=False, na_position='last') + exp_val = np.array(["d","c","b","a", np.nan],dtype=object) + exp_levels = np.array(["a","b","c","d"],dtype=object) + # FIXME: IndexError: Out of bounds on buffer access (axis 0) + #self.assert_numpy_array_equal(res.__array__(), exp_val) + #self.assert_numpy_array_equal(res.levels, exp_levels) + + cat = Categorical(["a","c","b","d", np.nan], ordered=True) + res = cat.order(ascending=False, na_position='first') + exp_val = np.array([np.nan, "d","c","b","a"],dtype=object) + exp_levels = np.array(["a","b","c","d"],dtype=object) + # FIXME: IndexError: Out of bounds on buffer access (axis 0) + #self.assert_numpy_array_equal(res.__array__(), exp_val) + #self.assert_numpy_array_equal(res.levels, exp_levels) def test_slicing(self): cat = Series(Categorical([1,2,3,4])) @@ -1429,6 +1470,22 @@ def f(): pd.concat([df,df_wrong_levels]) self.assertRaises(ValueError, f) + # GH 7864 + # make sure ordering is preserverd + df = pd.DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']}) + df["grade"] = pd.Categorical(df["raw_grade"]) + df['grade'].cat.reorder_levels(['e', 'a', 'b']) + + df1 = df[0:3] + df2 = df[3:] + + self.assert_numpy_array_equal(df['grade'].cat.levels, df1['grade'].cat.levels) + self.assert_numpy_array_equal(df['grade'].cat.levels, df2['grade'].cat.levels) + + dfx = pd.concat([df1, df2]) + dfx['grade'].cat.levels + self.assert_numpy_array_equal(df['grade'].cat.levels, dfx['grade'].cat.levels) + def test_append(self): cat = pd.Categorical(["a","b"], levels=["a","b"]) vals = [1,2]
CLN: refactor _lexsort_indexer to use Categoricals closes #7848 closes #7864
https://api.github.com/repos/pandas-dev/pandas/pulls/7850
2014-07-26T13:53:03Z
2014-07-29T22:44:36Z
2014-07-29T22:44:36Z
2014-07-31T21:27:35Z
Docs: improve installation instructions, recommend Anaconda.
diff --git a/doc/source/install.rst b/doc/source/install.rst index fe56b53d7cb82..c30a086295f00 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -2,64 +2,250 @@ .. currentmodule:: pandas -************ +============ Installation -************ +============ -You have the option to install an `official release -<http://pypi.python.org/pypi/pandas>`__ or to build the `development version -<http://github.com/pydata/pandas>`__. If you choose to install from source and -are running Windows, you will have to ensure that you have a compatible C -compiler (MinGW or Visual Studio) installed. `How-to install MinGW on Windows -<http://docs.cython.org/src/tutorial/appendix.html>`__ +The easiest way for the majority of users to install pandas is to install it +as part of the `Anaconda <http://docs.continuum.io/anaconda/>`__ distribution, a +cross platform distribution for data analysis and scientific computing. +This is the recommended installation method for most users. + +Instructions for installing from source, +`PyPI <http://pypi.python.org/pypi/pandas>`__, various Linux distributions, or a +`development version <http://github.com/pydata/pandas>`__ are also provided. Python version support -~~~~~~~~~~~~~~~~~~~~~~ +---------------------- Officially Python 2.6, 2.7, 3.2, 3.3, and 3.4. +Installing pandas +----------------- + +Trying out pandas, no installation required! +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The easiest way to start experimenting with pandas doesn't involve installing +pandas at all. + +`Wakari <https://wakari.io>`__ is a free service that provides a hosted +`IPython Notebook <http://ipython.org/notebook.html>`__ service in the cloud. + +Simply create an account, and have access to pandas from within your brower via +an `IPython Notebook <http://ipython.org/notebook.html>`__ in a few minutes. + +Installing pandas with Anaconda +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Installing pandas and the rest of the `NumPy <http://www.numpy.org/>`__ and +`SciPy <http://www.scipy.org/>`__ stack can be a little +difficult for inexperienced users. + +The simplest way to install not only pandas, but Python and the most popular +packages that make up the `SciPy <http://www.scipy.org/>`__ stack +(`IPython <http://ipython.org/>`__, `NumPy <http://www.numpy.org/>`__, +`Matplotlib <http://matplotlib.org/>`__, ...) is with +`Anaconda <http://docs.continuum.io/anaconda/>`__, a cross-platform +(Linux, Mac OS X, Windows) Python distribution for data analytics and +scientific computing. + +After running a simple installer, the user will have access to pandas and the +rest of the `SciPy <http://www.scipy.org/>`__ stack without needing to install +anything else, and without needing to wait for any software to be compiled. + +Installation instructions for `Anaconda <http://docs.continuum.io/anaconda/>`__ +`can be found here <http://docs.continuum.io/anaconda/install.html>`__. + +A full list of the packages available as part of the +`Anaconda <http://docs.continuum.io/anaconda/>`__ distribution +`can be found here <http://docs.continuum.io/anaconda/pkg-docs.html>`__. + +An additional advantage of installing with Anaconda is that you don't require +admin rights to install it, it will install in the user's home directory, and +this also makes it trivial to delete Anaconda at a later date (just delete +that folder). + +Installing pandas with Miniconda +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The previous section outlined how to get pandas installed as part of the +`Anaconda <http://docs.continuum.io/anaconda/>`__ distribution. +However this approach means you will install well over one hundred packages +and involves downloading the installer which is a few hundred megabytes in size. + +If you want to have more control on which packages, or have a limited internet +bandwidth, then installing pandas with +`Miniconda <http://conda.pydata.org/miniconda.html>`__ may be a better solution. + +`Conda <http://conda.pydata.org/docs/>`__ is the package manager that the +`Anaconda <http://docs.continuum.io/anaconda/>`__ distribution is built upon. +It is a package manager that is both cross-platform and language agnostic +(it can play a similar role to a pip and virtualenv combination). + +`Miniconda <http://conda.pydata.org/miniconda.html>`__ allows you to create a +minimal self contained Python installation, and then use the +`Conda <http://conda.pydata.org/docs/>`__ command to install additional packages. + +First you will need `Conda <http://conda.pydata.org/docs/>`__ to be installed and +downloading and running the `Miniconda +<http://conda.pydata.org/miniconda.html>`__ +will do this for you. The installer +`can be found here <http://conda.pydata.org/miniconda.html>`__ + +The next step is to create a new conda environment (these are analogous to a +virtualenv but they also allow you to specify precisely which Python version +to install also). Run the following commands from a terminal window:: + + conda create -n name_of_my_env python + +This will create a minimal environment with only Python installed in it. +To put your self inside this environment run:: + + source activate name_of_my_env + +On Windows the command is:: -Binary installers -~~~~~~~~~~~~~~~~~ + activate name_of_my_env -.. _all-platforms: +The final step required is to install pandas. This can be done with the +following command:: -All platforms -_____________ + conda install pandas -Stable installers available on `PyPI <http://pypi.python.org/pypi/pandas>`__ +To install a specific pandas version:: -Preliminary builds and installers on the `pandas download page <http://pandas.pydata.org/getpandas.html>`__ . + conda install pandas=0.13.1 -Overview -___________ +To install other packages, IPython for example:: + + conda install ipython + +To install the full `Anaconda <http://docs.continuum.io/anaconda/>`__ +distribution:: + + conda install anaconda + +If you require any packages that are available to pip but not conda, simply +install pip, and use pip to install these packages:: + + conda install pip + pip install django + +Installing from PyPI +~~~~~~~~~~~~~~~~~~~~ + +pandas can be installed via pip from +`PyPI <http://pypi.python.org/pypi/pandas>`__. + +:: + + pip install pandas + +This will likely require the installation of a number of dependencies, +including NumPy, will require a compiler to compile required bits of code, +and can take a few minutes to complete. + +Installing using your Linux distribution's package manager. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. csv-table:: - :header: "Platform", "Distribution", "Status", "Download / Repository Link", "Install method" - :widths: 10, 10, 10, 20, 50 + :header: "Distribution", "Status", "Download / Repository Link", "Install method" + :widths: 10, 10, 20, 50 + + + Debian, stable, `official Debian repository <http://packages.debian.org/search?keywords=pandas&searchon=names&suite=all&section=all>`__ , ``sudo apt-get install python-pandas`` + Debian & Ubuntu, unstable (latest packages), `NeuroDebian <http://neuro.debian.net/index.html#how-to-use-this-repository>`__ , ``sudo apt-get install python-pandas`` + Ubuntu, stable, `official Ubuntu repository <http://packages.ubuntu.com/search?keywords=pandas&searchon=names&suite=all&section=all>`__ , ``sudo apt-get install python-pandas`` + Ubuntu, unstable (daily builds), `PythonXY PPA <https://code.launchpad.net/~pythonxy/+archive/pythonxy-devel>`__; activate by: ``sudo add-apt-repository ppa:pythonxy/pythonxy-devel && sudo apt-get update``, ``sudo apt-get install python-pandas`` + OpenSuse & Fedora, stable, `OpenSuse Repository <http://software.opensuse.org/package/python-pandas?search_term=pandas>`__ , ``zypper in python-pandas`` + + + + + + + + - Windows, all, stable, :ref:`all-platforms`, ``pip install pandas`` - Mac, all, stable, :ref:`all-platforms`, ``pip install pandas`` - Linux, Debian, stable, `official Debian repository <http://packages.debian.org/search?keywords=pandas&searchon=names&suite=all&section=all>`__ , ``sudo apt-get install python-pandas`` - Linux, Debian & Ubuntu, unstable (latest packages), `NeuroDebian <http://neuro.debian.net/index.html#how-to-use-this-repository>`__ , ``sudo apt-get install python-pandas`` - Linux, Ubuntu, stable, `official Ubuntu repository <http://packages.ubuntu.com/search?keywords=pandas&searchon=names&suite=all&section=all>`__ , ``sudo apt-get install python-pandas`` - Linux, Ubuntu, unstable (daily builds), `PythonXY PPA <https://code.launchpad.net/~pythonxy/+archive/pythonxy-devel>`__; activate by: ``sudo add-apt-repository ppa:pythonxy/pythonxy-devel && sudo apt-get update``, ``sudo apt-get install python-pandas`` - Linux, OpenSuse & Fedora, stable, `OpenSuse Repository <http://software.opensuse.org/package/python-pandas?search_term=pandas>`__ , ``zypper in python-pandas`` +Installing from source +~~~~~~~~~~~~~~~~~~~~~~ +.. note:: + Installing from the git repository requires a recent installation of `Cython + <http://cython.org>`__ as the cythonized C sources are no longer checked + into source control. Released source distributions will contain the built C + files. I recommend installing the latest Cython via ``easy_install -U + Cython`` +The source code is hosted at http://github.com/pydata/pandas, it can be checked +out using git and compiled / installed like so: +:: + git clone git://github.com/pydata/pandas.git + cd pandas + python setup.py install +Make sure you have Cython installed when installing from the repository, +rather then a tarball or pypi. +On Windows, I suggest installing the MinGW compiler suite following the +directions linked to above. Once configured property, run the following on the +command line: + +:: + + python setup.py build --compiler=mingw32 + python setup.py install + +Note that you will not be able to import pandas if you open an interpreter in +the source directory unless you build the C extensions in place: + +:: + + python setup.py build_ext --inplace + +The most recent version of MinGW (any installer dated after 2011-08-03) +has removed the '-mno-cygwin' option but Distutils has not yet been updated to +reflect that. Thus, you may run into an error like "unrecognized command line +option '-mno-cygwin'". Until the bug is fixed in Distutils, you may need to +install a slightly older version of MinGW (2011-08-02 installer). + +Running the test suite +~~~~~~~~~~~~~~~~~~~~~~ + +pandas is equipped with an exhaustive set of unit tests covering about 97% of +the codebase as of this writing. To run it on your machine to verify that +everything is working (and you have all of the dependencies, soft and hard, +installed), make sure you have `nose +<http://readthedocs.org/docs/nose/en/latest/>`__ and run: +:: + $ nosetests pandas + .......................................................................... + .......................S.................................................. + .......................................................................... + .......................................................................... + .......................................................................... + .......................................................................... + .......................................................................... + .......................................................................... + .......................................................................... + .......................................................................... + .................S........................................................ + .... + ---------------------------------------------------------------------- + Ran 818 tests in 21.631s + OK (SKIP=2) Dependencies -~~~~~~~~~~~~ +------------ * `NumPy <http://www.numpy.org>`__: 1.6.1 or higher * `python-dateutil <http://labix.org/python-dateutil>`__ 1.5 @@ -165,75 +351,3 @@ Optional Dependencies distribution like `Enthought Canopy <http://enthought.com/products/canopy>`__ may be worth considering. -Installing from source -~~~~~~~~~~~~~~~~~~~~~~ -.. note:: - - Installing from the git repository requires a recent installation of `Cython - <http://cython.org>`__ as the cythonized C sources are no longer checked - into source control. Released source distributions will contain the built C - files. I recommend installing the latest Cython via ``easy_install -U - Cython`` - -The source code is hosted at http://github.com/pydata/pandas, it can be checked -out using git and compiled / installed like so: - -:: - - git clone git://github.com/pydata/pandas.git - cd pandas - python setup.py install - -Make sure you have Cython installed when installing from the repository, -rather then a tarball or pypi. - -On Windows, I suggest installing the MinGW compiler suite following the -directions linked to above. Once configured property, run the following on the -command line: - -:: - - python setup.py build --compiler=mingw32 - python setup.py install - -Note that you will not be able to import pandas if you open an interpreter in -the source directory unless you build the C extensions in place: - -:: - - python setup.py build_ext --inplace - -The most recent version of MinGW (any installer dated after 2011-08-03) -has removed the '-mno-cygwin' option but Distutils has not yet been updated to -reflect that. Thus, you may run into an error like "unrecognized command line -option '-mno-cygwin'". Until the bug is fixed in Distutils, you may need to -install a slightly older version of MinGW (2011-08-02 installer). - -Running the test suite -~~~~~~~~~~~~~~~~~~~~~~ - -pandas is equipped with an exhaustive set of unit tests covering about 97% of -the codebase as of this writing. To run it on your machine to verify that -everything is working (and you have all of the dependencies, soft and hard, -installed), make sure you have `nose -<http://readthedocs.org/docs/nose/en/latest/>`__ and run: - -:: - - $ nosetests pandas - .......................................................................... - .......................S.................................................. - .......................................................................... - .......................................................................... - .......................................................................... - .......................................................................... - .......................................................................... - .......................................................................... - .......................................................................... - .......................................................................... - .................S........................................................ - .... - ---------------------------------------------------------------------- - Ran 818 tests in 21.631s - - OK (SKIP=2)
I believe installing pandas via Anaconda should definitely be the recommended installation method for most users. It is cross platform, doesn't require a compiler, and will install all requirements for the user also (including NumPy).
https://api.github.com/repos/pandas-dev/pandas/pulls/7849
2014-07-26T10:18:17Z
2014-07-29T09:58:55Z
2014-07-29T09:58:55Z
2014-07-31T02:22:40Z