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 |
|---|---|---|---|---|---|---|---|
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 |
WIP: Troublehsoot nbformat | diff --git a/environment.yml b/environment.yml
index be6fb9a4cac7d..09736aeea25f2 100644
--- a/environment.yml
+++ b/environment.yml
@@ -68,7 +68,7 @@ dependencies:
# unused (required indirectly may be?)
- ipywidgets
- - nbformat=5.0.8
+ - nbformat
- notebook>=5.7.5
- pip
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 054c924daa81c..80fd7b243f6ce 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -42,7 +42,7 @@ pytest-instafail
seaborn
statsmodels
ipywidgets
-nbformat==5.0.8
+nbformat
notebook>=5.7.5
pip
blosc
| I could reproduce this locally, but after automatically downloading new object.inv files the issue was gone.
It seemed as the warning was unknown keyword and, have to troubleshoot here | https://api.github.com/repos/pandas-dev/pandas/pulls/39180 | 2021-01-14T23:32:34Z | 2021-01-15T00:19:53Z | null | 2021-04-26T22:00:27Z |
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 |
ERR: Fix missing space in warning message | diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index a11bf370412d2..a6ffa685054fa 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -1924,7 +1924,7 @@ def _concatenate_chunks(list chunks):
if warning_columns:
warning_names = ','.join(warning_columns)
warning_message = " ".join([
- f"Columns ({warning_names}) have mixed types."
+ f"Columns ({warning_names}) have mixed types.",
f"Specify dtype option on import or set low_memory=False."
])
warnings.warn(warning_message, DtypeWarning, stacklevel=8)
diff --git a/pandas/tests/io/parser/common/test_chunksize.py b/pandas/tests/io/parser/common/test_chunksize.py
index 6d5aeaa713687..303174d9dbd1a 100644
--- a/pandas/tests/io/parser/common/test_chunksize.py
+++ b/pandas/tests/io/parser/common/test_chunksize.py
@@ -6,6 +6,7 @@
import numpy as np
import pytest
+import regex as re
from pandas.errors import DtypeWarning
@@ -190,7 +191,11 @@ def test_warn_if_chunks_have_mismatched_type(all_parsers, request):
buf = StringIO(data)
try:
- with tm.assert_produces_warning(warning_type):
+ msg = (
+ "Columns (0) have mixed types. Specify dtype option on import or "
+ "set low_memory=False."
+ )
+ with tm.assert_produces_warning(warning_type, match=re.escape(msg)):
df = parser.read_csv(buf)
except AssertionError as err:
# 2021-02-21 this occasionally fails on the CI with an unexpected
| - [x] closes #39158
- [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/39159 | 2021-01-13T23:51:03Z | 2021-05-26T02:20:11Z | null | 2023-05-11T01:20:44Z |
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 |
TYP: fix mypy error in pandas/core/common.py | diff --git a/pandas/core/common.py b/pandas/core/common.py
index a6514b5167460..62b3f3639a335 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -463,12 +463,14 @@ def convert_to_list_like(
values: Union[Scalar, Iterable, AnyArrayLike]
) -> Union[List, AnyArrayLike]:
"""
- Convert list-like or scalar input to list-like. List, numpy and pandas array-like
- inputs are returned unmodified whereas others are converted to list.
+ Convert list-like or scalar input to list-like.
+
+ List, numpy and pandas array-like inputs are returned unmodified
+ whereas others are converted to list.
"""
if isinstance(values, (list, np.ndarray, ABCIndex, ABCSeries, ABCExtensionArray)):
# np.ndarray resolving as Any gives a false positive
- return values # type: ignore[return-value]
+ return cast(Union[List, AnyArrayLike], values)
elif isinstance(values, abc.Iterable) and not isinstance(values, str):
return list(values)
| - [ ] 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 error in ``pandas/core/common.py``. | https://api.github.com/repos/pandas-dev/pandas/pulls/39106 | 2021-01-11T13:44:27Z | 2021-01-11T14:52:28Z | null | 2021-01-11T14:52:28Z |
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 |
DOC: Added reverse rolling window examples | diff --git a/doc/source/user_guide/window.rst b/doc/source/user_guide/window.rst
index 08641bc5b17ae..afb706d61f405 100644
--- a/doc/source/user_guide/window.rst
+++ b/doc/source/user_guide/window.rst
@@ -50,16 +50,16 @@ As noted above, some operations support specifying a window based on a time offs
.. ipython:: python
- s = pd.Series(range(5), index=pd.date_range('2020-01-01', periods=5, freq='1D'))
- s.rolling(window='2D').sum()
+ s = pd.Series(range(5), index=pd.date_range("2020-01-01", periods=5, freq="1D"))
+ s.rolling(window="2D").sum()
Additionally, some methods support chaining a ``groupby`` operation with a windowing operation
which will first group the data by the specified keys and then perform a windowing operation per group.
.. ipython:: python
- df = pd.DataFrame({'A': ['a', 'b', 'a', 'b', 'a'], 'B': range(5)})
- df.groupby('A').expanding().sum()
+ df = pd.DataFrame({"A": ["a", "b", "a", "b", "a"], "B": range(5)})
+ df.groupby("A").expanding().sum()
.. note::
@@ -95,8 +95,11 @@ be calculated with :meth:`~Rolling.apply` by specifying a separate column of wei
arr[:, :2] = (x[:, :2] * x[:, 2]).sum(axis=0) / x[:, 2].sum()
return arr
+
df = pd.DataFrame([[1, 2, 0.6], [2, 3, 0.4], [3, 4, 0.2], [4, 5, 0.7]])
- df.rolling(2, method="table", min_periods=0).apply(weighted_mean, raw=True, engine="numba") # noqa:E501
+ df.rolling(2, method="table", min_periods=0).apply(
+ weighted_mean, raw=True, engine="numba"
+ ) # noqa:E501
All windowing operations support a ``min_periods`` argument that dictates the minimum amount of
@@ -132,13 +135,13 @@ time based index must be monotonic.
.. ipython:: python
- times = ['2020-01-01', '2020-01-03', '2020-01-04', '2020-01-05', '2020-01-29']
+ times = ["2020-01-01", "2020-01-03", "2020-01-04", "2020-01-05", "2020-01-29"]
s = pd.Series(range(5), index=pd.DatetimeIndex(times))
s
# Window with 2 observations
s.rolling(window=2).sum()
# Window with 2 days worth of observations
- s.rolling(window='2D').sum()
+ s.rolling(window="2D").sum()
For all supported aggregation functions, see :ref:`api.functions_rolling`.
@@ -198,6 +201,53 @@ from present information back to past information. This allows the rolling windo
df
+.. _window.reverse_rolling_window:
+
+Reverse rolling window
+~~~~~~~~~~~~~~~~~~~~~~
+
+Get the window of a rolling function to look forward.
+
+We can achieve this by using slicing in python by applying rolling aggregation and then flipping the result
+as shown in example below:
+
+.. ipython:: python
+
+ df = pd.DataFrame(
+ data=[
+ [pd.Timestamp("2018-01-01 00:00:00"), 100],
+ [pd.Timestamp("2018-01-01 00:00:01"), 101],
+ [pd.Timestamp("2018-01-01 00:00:03"), 103],
+ [pd.Timestamp("2018-01-01 00:00:04"), 111],
+ ],
+ columns=["time", "value"],
+ ).set_index("time")
+ df
+
+ df1 = df[::-1].rolling("2s").sum()[::-1]
+ df1
+
+Or we can also do it using FixedForwardWindowIndexer which basically Creates window boundaries
+for fixed-length windows that include the current row.
+
+.. ipython:: python
+
+ df = pd.DataFrame(
+ data=[
+ [pd.Timestamp("2018-01-01 00:00:00"), 100],
+ [pd.Timestamp("2018-01-01 00:00:01"), 101],
+ [pd.Timestamp("2018-01-01 00:00:03"), 103],
+ [pd.Timestamp("2018-01-01 00:00:04"), 111],
+ ],
+ columns=["time", "value"],
+ ).set_index("time")
+ df
+
+ indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2)
+
+ df2 = df.rolling(window=indexer, min_periods=1).sum()
+ df2
+
.. _window.custom_rolling_window:
@@ -280,11 +330,23 @@ conditions. In these cases it can be useful to perform forward-looking rolling w
This :func:`BaseIndexer <pandas.api.indexers.BaseIndexer>` subclass implements a closed fixed-width
forward-looking rolling window, and we can use it as follows:
-.. ipython:: ipython
+.. ipython:: python
+
+ df = pd.DataFrame(
+ data=[
+ [pd.Timestamp("2018-01-01 00:00:00"), 100],
+ [pd.Timestamp("2018-01-01 00:00:01"), 101],
+ [pd.Timestamp("2018-01-01 00:00:03"), 103],
+ [pd.Timestamp("2018-01-01 00:00:04"), 111],
+ ],
+ columns=["time", "value"],
+ ).set_index("time")
+ df
- from pandas.api.indexers import FixedForwardWindowIndexer
- indexer = FixedForwardWindowIndexer(window_size=2)
- df.rolling(indexer, min_periods=1).sum()
+ indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2)
+
+ df_out = df.rolling(window=indexer, min_periods=1).sum()
+ df_out
.. _window.rolling_apply:
@@ -302,6 +364,7 @@ the windows are cast as :class:`Series` objects (``raw=False``) or ndarray objec
def mad(x):
return np.fabs(x - x.mean()).mean()
+
s = pd.Series(range(10))
s.rolling(window=4).apply(mad, raw=True)
@@ -407,11 +470,7 @@ can even be omitted:
.. ipython:: python
- covs = (
- df[["B", "C", "D"]]
- .rolling(window=4)
- .cov(df[["A", "B", "C"]], pairwise=True)
- )
+ covs = df[["B", "C", "D"]].rolling(window=4).cov(df[["A", "B", "C"]], pairwise=True)
covs
| - [x] closes #38627
- [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/39091 | 2021-01-10T15:29:50Z | 2021-03-14T03:57:55Z | null | 2021-03-14T03:57:55Z |
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 #39069: 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 4b7a4180ee9f9..d40ff81af313b 100644
--- a/doc/source/whatsnew/v1.2.1.rst
+++ b/doc/source/whatsnew/v1.2.1.rst
@@ -24,6 +24,7 @@ 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 :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`)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 1d411f3b1b287..58384405a5cab 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1981,7 +1981,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 59d49ad8bdae4..a260aaf6e057d 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -1697,64 +1697,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 ae01093fbadbf..ac97ff7af262d 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)
| https://api.github.com/repos/pandas-dev/pandas/pulls/39081 | 2021-01-10T00:57:30Z | 2021-01-10T02:37:20Z | null | 2021-01-10T02:37:20Z | |
Auto backport of pr 39069 on 1.2.x | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c00cec450c85e..48a3c464b8fe2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,7 +6,7 @@ on:
pull_request:
branches:
- master
- - 1.1.x
+ - 1.2.x
env:
ENV_FILE: environment.yml
@@ -64,7 +64,7 @@ jobs:
- name: Testing docstring validation script
run: |
source activate pandas-dev
- pytest --capture=no --strict scripts
+ pytest --capture=no --strict-markers scripts
if: always()
- name: Running benchmarks
diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml
new file mode 100644
index 0000000000000..c2f332cc5454a
--- /dev/null
+++ b/.github/workflows/database.yml
@@ -0,0 +1,186 @@
+name: Database
+
+on:
+ push:
+ branches: [master]
+ pull_request:
+ branches:
+ - master
+ - 1.2.x
+
+env:
+ PYTEST_WORKERS: "auto"
+ PANDAS_CI: 1
+ PATTERN: ((not slow and not network and not clipboard) or (single and db))
+
+jobs:
+ Linux_py37_locale:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ shell: bash -l {0}
+
+ env:
+ ENV_FILE: ci/deps/actions-37-locale.yaml
+ LOCALE_OVERRIDE: zh_CN.UTF-8
+
+ services:
+ mysql:
+ image: mysql
+ env:
+ MYSQL_ALLOW_EMPTY_PASSWORD: yes
+ MYSQL_DATABASE: pandas
+ options: >-
+ --health-cmd "mysqladmin ping"
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ ports:
+ - 3306:3306
+
+ postgres:
+ image: postgres
+ env:
+ POSTGRES_USER: postgres
+ POSTGRES_PASSWORD: postgres
+ POSTGRES_DB: pandas
+ options: >-
+ --health-cmd pg_isready
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ ports:
+ - 5432:5432
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v1
+
+ - name: Cache conda
+ uses: actions/cache@v1
+ env:
+ CACHE_NUMBER: 0
+ with:
+ path: ~/conda_pkgs_dir
+ key: ${{ runner.os }}-conda-${{ env.CACHE_NUMBER }}-${{
+ hashFiles('${{ env.ENV_FILE }}') }}
+
+ - 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: |
+ 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: Test
+ run: ci/run_tests.sh
+ if: always()
+
+ - name: Build Version
+ run: pushd /tmp && python -c "import pandas; pandas.show_versions();" && popd
+
+ - name: Publish test results
+ uses: actions/upload-artifact@master
+ with:
+ name: Test results
+ path: test-data.xml
+ if: failure()
+
+ - name: Print skipped tests
+ run: python ci/print_skipped.py
+
+ Linux_py37_cov:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ shell: bash -l {0}
+
+ env:
+ ENV_FILE: ci/deps/actions-37-cov.yaml
+ PANDAS_TESTING_MODE: deprecate
+ COVERAGE: true
+
+ services:
+ mysql:
+ image: mysql
+ env:
+ MYSQL_ALLOW_EMPTY_PASSWORD: yes
+ MYSQL_DATABASE: pandas
+ options: >-
+ --health-cmd "mysqladmin ping"
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ ports:
+ - 3306:3306
+
+ postgres:
+ image: postgres
+ env:
+ POSTGRES_USER: postgres
+ POSTGRES_PASSWORD: postgres
+ POSTGRES_DB: pandas
+ options: >-
+ --health-cmd pg_isready
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ ports:
+ - 5432:5432
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v1
+
+ - name: Cache conda
+ uses: actions/cache@v1
+ env:
+ CACHE_NUMBER: 0
+ with:
+ path: ~/conda_pkgs_dir
+ key: ${{ runner.os }}-conda-${{ env.CACHE_NUMBER }}-${{
+ hashFiles('${{ env.ENV_FILE }}') }}
+
+ - 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: |
+ 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: Test
+ run: ci/run_tests.sh
+ if: always()
+
+ - name: Build Version
+ run: pushd /tmp && python -c "import pandas; pandas.show_versions();" && popd
+
+ - name: Publish test results
+ uses: actions/upload-artifact@master
+ with:
+ name: Test results
+ path: test-data.xml
+ if: failure()
+
+ - name: Print skipped tests
+ run: python ci/print_skipped.py
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 717334bfe1299..90d65327ea980 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -144,6 +144,11 @@ repos:
\#\ type:\s?ignore(?!\[)
language: pygrep
types: [python]
+ - id: np-bool
+ name: Check for use of np.bool instead of np.bool_
+ entry: np\.bool[^_8]
+ language: pygrep
+ types_or: [python, cython, rst]
- id: no-os-remove
name: Check code for instances of os.remove
entry: os\.remove
diff --git a/.travis.yml b/.travis.yml
index 1ddd886699d38..8ede978074a9c 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -16,13 +16,13 @@ services:
# travis cache --delete inside the project directory from the travis command line client
# The cache directories will be deleted if anything in ci/ changes in a commit
cache:
+ apt: true
ccache: true
directories:
- $HOME/.cache # cython cache
env:
global:
- - PYTEST_WORKERS="auto"
# create a github personal access token
# cd pandas-dev/pandas
# travis encrypt 'PANDAS_GH_TOKEN=personal_access_token' -r pandas-dev/pandas
@@ -35,31 +35,10 @@ matrix:
fast_finish: true
include:
- - env:
- - JOB="3.8, slow" ENV_FILE="ci/deps/travis-38-slow.yaml" PATTERN="slow" SQL="1"
- services:
- - mysql
- - postgresql
-
- - env:
- - JOB="3.7, locale" ENV_FILE="ci/deps/travis-37-locale.yaml" PATTERN="((not slow and not network and not clipboard) or (single and db))" LOCALE_OVERRIDE="zh_CN.UTF-8" SQL="1"
- services:
- - mysql
- - postgresql
-
- arch: arm64
env:
- JOB="3.7, arm64" PYTEST_WORKERS=1 ENV_FILE="ci/deps/travis-37-arm64.yaml" PATTERN="(not slow and not network and not clipboard and not arm_slow)"
- - env:
- # Enabling Deprecations when running tests
- # PANDAS_TESTING_MODE="deprecate" causes DeprecationWarning messages to be displayed in the logs
- # See pandas/_testing.py for more details.
- - JOB="3.7, coverage" ENV_FILE="ci/deps/travis-37-cov.yaml" PATTERN="((not slow and not network and not clipboard) or (single and db))" PANDAS_TESTING_MODE="deprecate" COVERAGE=true SQL="1"
- services:
- - mysql
- - postgresql
-
allow_failures:
# Moved to allowed_failures 2020-09-29 due to timeouts https://github.com/pandas-dev/pandas/issues/36719
- arch: arm64
diff --git a/asv_bench/benchmarks/algorithms.py b/asv_bench/benchmarks/algorithms.py
index 03480ae198345..65e52e03c43c7 100644
--- a/asv_bench/benchmarks/algorithms.py
+++ b/asv_bench/benchmarks/algorithms.py
@@ -5,7 +5,6 @@
from pandas._libs import lib
import pandas as pd
-from pandas.core.algorithms import make_duplicates_of_left_unique_in_right
from .pandas_vb_common import tm
@@ -175,15 +174,4 @@ def time_argsort(self, N):
self.array.argsort()
-class RemoveDuplicates:
- def setup(self):
- N = 10 ** 5
- na = np.arange(int(N / 2))
- self.left = np.concatenate([na[: int(N / 4)], na[: int(N / 4)]])
- self.right = np.concatenate([na, na])
-
- def time_make_duplicates_of_left_unique_in_right(self):
- make_duplicates_of_left_unique_in_right(self.left, self.right)
-
-
from .pandas_vb_common import setup # noqa: F401 isort:skip
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py
index 6ce63ff8badca..6cc8e15786795 100644
--- a/asv_bench/benchmarks/groupby.py
+++ b/asv_bench/benchmarks/groupby.py
@@ -625,7 +625,7 @@ class TransformBools:
def setup(self):
N = 120000
transition_points = np.sort(np.random.choice(np.arange(N), 1400))
- transitions = np.zeros(N, dtype=np.bool)
+ transitions = np.zeros(N, dtype=np.bool_)
transitions[transition_points] = True
self.g = transitions.cumsum()
self.df = DataFrame({"signal": np.random.rand(N)})
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index c49742095e1d8..464bad7884362 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -1,11 +1,11 @@
# Adapted from https://github.com/numba/numba/blob/master/azure-pipelines.yml
trigger:
- master
-- 1.1.x
+- 1.2.x
pr:
- master
-- 1.1.x
+- 1.2.x
variables:
PYTEST_WORKERS: auto
diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml
index 8e44db0b4bcd4..4cb4eaf95f6f5 100644
--- a/ci/azure/posix.yml
+++ b/ci/azure/posix.yml
@@ -43,6 +43,11 @@ jobs:
CONDA_PY: "38"
PATTERN: "not slow and not network and not clipboard"
+ py38_slow:
+ ENV_FILE: ci/deps/azure-38-slow.yaml
+ CONDA_PY: "38"
+ PATTERN: "slow"
+
py38_locale:
ENV_FILE: ci/deps/azure-38-locale.yaml
CONDA_PY: "38"
diff --git a/ci/deps/travis-37-cov.yaml b/ci/deps/actions-37-cov.yaml
similarity index 96%
rename from ci/deps/travis-37-cov.yaml
rename to ci/deps/actions-37-cov.yaml
index c89b42ef06a2e..5381caaa242cf 100644
--- a/ci/deps/travis-37-cov.yaml
+++ b/ci/deps/actions-37-cov.yaml
@@ -15,7 +15,7 @@ dependencies:
- beautifulsoup4
- botocore>=1.11
- dask
- - fastparquet>=0.3.2
+ - fastparquet>=0.4.0
- fsspec>=0.7.4
- gcsfs>=0.6.0
- geopandas
@@ -43,7 +43,7 @@ dependencies:
- sqlalchemy
- statsmodels
- xarray
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- pip
diff --git a/ci/deps/travis-37-locale.yaml b/ci/deps/actions-37-locale.yaml
similarity index 85%
rename from ci/deps/travis-37-locale.yaml
rename to ci/deps/actions-37-locale.yaml
index 4e442b10482a7..b18ce37d05ca0 100644
--- a/ci/deps/travis-37-locale.yaml
+++ b/ci/deps/actions-37-locale.yaml
@@ -1,6 +1,5 @@
name: pandas-dev
channels:
- - defaults
- conda-forge
dependencies:
- python=3.7.*
@@ -18,9 +17,9 @@ dependencies:
# optional
- beautifulsoup4
- - blosc=1.15.0
+ - blosc=1.17.0
- python-blosc
- - fastparquet=0.3.2
+ - fastparquet=0.4.0
- html5lib
- ipython
- jinja2
@@ -31,11 +30,11 @@ dependencies:
- openpyxl
- pandas-gbq
- google-cloud-bigquery>=1.27.2 # GH 36436
- - pyarrow>=0.17
+ - pyarrow=0.17 # GH 38803
- pytables>=3.5.1
- scipy
- xarray=0.12.3
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
@@ -43,5 +42,5 @@ dependencies:
# sql
- psycopg2=2.7
- - pymysql=0.7.11
+ - pymysql=0.8.1
- sqlalchemy=1.3.0
diff --git a/ci/deps/azure-37-slow.yaml b/ci/deps/azure-37-slow.yaml
index 50fccf86b6340..05b33fa351ac9 100644
--- a/ci/deps/azure-37-slow.yaml
+++ b/ci/deps/azure-37-slow.yaml
@@ -31,7 +31,7 @@ dependencies:
- moto>=1.3.14
- scipy
- sqlalchemy
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/azure-38-locale.yaml b/ci/deps/azure-38-locale.yaml
index f879111a32e67..15d503e8fd0a5 100644
--- a/ci/deps/azure-38-locale.yaml
+++ b/ci/deps/azure-38-locale.yaml
@@ -18,6 +18,7 @@ dependencies:
- html5lib
- ipython
- jinja2
+ - jedi<0.18.0
- lxml
- matplotlib <3.3.0
- moto
@@ -30,7 +31,7 @@ dependencies:
- pytz
- scipy
- xarray
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/travis-38-slow.yaml b/ci/deps/azure-38-slow.yaml
similarity index 95%
rename from ci/deps/travis-38-slow.yaml
rename to ci/deps/azure-38-slow.yaml
index e4b719006a11e..fd40f40294b7f 100644
--- a/ci/deps/travis-38-slow.yaml
+++ b/ci/deps/azure-38-slow.yaml
@@ -1,6 +1,5 @@
name: pandas-dev
channels:
- - defaults
- conda-forge
dependencies:
- python=3.8.*
@@ -30,7 +29,7 @@ dependencies:
- moto>=1.3.14
- scipy
- sqlalchemy
- - xlrd
+ - xlrd>=2.0
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/azure-macos-37.yaml b/ci/deps/azure-macos-37.yaml
index 31e0ffca81424..0b8aff83fe230 100644
--- a/ci/deps/azure-macos-37.yaml
+++ b/ci/deps/azure-macos-37.yaml
@@ -26,7 +26,7 @@ dependencies:
- python-dateutil==2.7.3
- pytz
- xarray
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
- pip
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index 16b4bd72683b4..e7ac4c783b855 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -33,7 +33,7 @@ dependencies:
- s3fs>=0.4.2
- scipy
- sqlalchemy
- - xlrd
+ - xlrd>=2.0
- xlsxwriter
- xlwt
- pyreadstat
diff --git a/ci/deps/azure-windows-38.yaml b/ci/deps/azure-windows-38.yaml
index 449bbd05991bf..661d8813d32d2 100644
--- a/ci/deps/azure-windows-38.yaml
+++ b/ci/deps/azure-windows-38.yaml
@@ -15,7 +15,7 @@ dependencies:
# pandas dependencies
- blosc
- bottleneck
- - fastparquet>=0.3.2
+ - fastparquet>=0.4.0
- flask
- fsspec>=0.8.0
- matplotlib=3.1.3
@@ -31,6 +31,6 @@ dependencies:
- pytz
- s3fs>=0.4.0
- scipy
- - xlrd
+ - xlrd<2.0
- xlsxwriter
- xlwt
diff --git a/ci/run_tests.sh b/ci/run_tests.sh
index 78d24c814840a..593939431d5eb 100755
--- a/ci/run_tests.sh
+++ b/ci/run_tests.sh
@@ -20,7 +20,7 @@ if [[ $(uname) == "Linux" && -z $DISPLAY ]]; then
XVFB="xvfb-run "
fi
-PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile -s --strict --durations=30 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas"
+PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile -s --strict-markers --durations=30 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas"
if [[ $(uname) != "Linux" && $(uname) != "Darwin" ]]; then
# GH#37455 windows py38 build appears to be running out of memory
diff --git a/doc/source/conf.py b/doc/source/conf.py
index 15e7a13ff5b72..8ab1c8c2f3428 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -427,7 +427,7 @@
ipython_warning_is_error = False
-ipython_exec_lines = [
+ipython_execlines = [
"import numpy as np",
"import pandas as pd",
# This ensures correct rendering on system with console encoding != utf8
@@ -687,6 +687,30 @@ def process_class_docstrings(app, what, name, obj, options, lines):
lines[:] = joined.split("\n")
+_BUSINED_ALIASES = [
+ "pandas.tseries.offsets." + name
+ for name in [
+ "BDay",
+ "CDay",
+ "BMonthEnd",
+ "BMonthBegin",
+ "CBMonthEnd",
+ "CBMonthBegin",
+ ]
+]
+
+
+def process_business_alias_docstrings(app, what, name, obj, options, lines):
+ """
+ Starting with sphinx 3.4, the "autodoc-process-docstring" event also
+ gets called for alias classes. This results in numpydoc adding the
+ methods/attributes to the docstring, which we don't want (+ this
+ causes warnings with sphinx).
+ """
+ if name in _BUSINED_ALIASES:
+ lines[:] = []
+
+
suppress_warnings = [
# We "overwrite" autosummary with our PandasAutosummary, but
# still want the regular autosummary setup to run. So we just
@@ -716,6 +740,7 @@ def setup(app):
app.connect("source-read", rstjinja)
app.connect("autodoc-process-docstring", remove_flags_docstring)
app.connect("autodoc-process-docstring", process_class_docstrings)
+ app.connect("autodoc-process-docstring", process_business_alias_docstrings)
app.add_autodocumenter(AccessorDocumenter)
app.add_autodocumenter(AccessorAttributeDocumenter)
app.add_autodocumenter(AccessorMethodDocumenter)
diff --git a/doc/source/development/debugging_extensions.rst b/doc/source/development/debugging_extensions.rst
new file mode 100644
index 0000000000000..358c4036df961
--- /dev/null
+++ b/doc/source/development/debugging_extensions.rst
@@ -0,0 +1,93 @@
+.. _debugging_c_extensions:
+
+{{ header }}
+
+======================
+Debugging C extensions
+======================
+
+Pandas uses select C extensions for high performance IO operations. In case you need to debug segfaults or general issues with those extensions, the following steps may be helpful.
+
+First, be sure to compile the extensions with the appropriate flags to generate debug symbols and remove optimizations. This can be achieved as follows:
+
+.. code-block:: sh
+
+ python setup.py build_ext --inplace -j4 --with-debugging-symbols
+
+Using a debugger
+================
+
+Assuming you are on a Unix-like operating system, you can use either lldb or gdb to debug. The choice between either is largely dependent on your compilation toolchain - typically you would use lldb if using clang and gdb if using gcc. For macOS users, please note that ``gcc`` is on modern systems an alias for ``clang``, so if using Xcode you usually opt for lldb. Regardless of which debugger you choose, please refer to your operating systems instructions on how to install.
+
+After installing a debugger you can create a script that hits the extension module you are looking to debug. For demonstration purposes, let's assume you have a script called ``debug_testing.py`` with the following contents:
+
+.. code-block:: python
+
+ import pandas as pd
+
+ pd.DataFrame([[1, 2]]).to_json()
+
+Place the ``debug_testing.py`` script in the project root and launch a Python process under your debugger. If using lldb:
+
+.. code-block:: sh
+
+ lldb python
+
+If using gdb:
+
+.. code-block:: sh
+
+ gdb python
+
+Before executing our script, let's set a breakpoint in our JSON serializer in its entry function called ``objToJSON``. The lldb syntax would look as follows:
+
+.. code-block:: sh
+
+ breakpoint set --name objToJSON
+
+Similarly for gdb:
+
+.. code-block:: sh
+
+ break objToJSON
+
+.. note::
+
+ You may get a warning that this breakpoint cannot be resolved in lldb. gdb may give a similar warning and prompt you to make the breakpoint on a future library load, which you should say yes to. This should only happen on the very first invocation as the module you wish to debug has not yet been loaded into memory.
+
+Now go ahead and execute your script:
+
+.. code-block:: sh
+
+ run <the_script>.py
+
+Code execution will halt at the breakpoint defined or at the occurance of any segfault. LLDB's `GDB to LLDB command map <https://lldb.llvm.org/use/map.html>`_ provides a listing of debugger command that you can execute using either debugger.
+
+Another option to execute the entire test suite under lldb would be to run the following:
+
+.. code-block:: sh
+
+ lldb -- python -m pytest
+
+Or for gdb
+
+.. code-block:: sh
+
+ gdb --args python -m pytest
+
+Once the process launches, simply type ``run`` and the test suite will begin, stopping at any segmentation fault that may occur.
+
+Checking memory leaks with valgrind
+===================================
+
+You can use `Valgrind <https://www.valgrind.org>`_ to check for and log memory leaks in extensions. For instance, to check for a memory leak in a test from the suite you can run:
+
+.. code-block:: sh
+
+ PYTHONMALLOC=malloc valgrind --leak-check=yes --track-origins=yes --log-file=valgrind-log.txt python -m pytest <path_to_a_test>
+
+Note that code execution under valgrind will take much longer than usual. While you can run valgrind against extensions compiled with any optimization level, it is suggested to have optimizations turned off from compiled extensions to reduce the amount of false positives. The ``--with-debugging-symbols`` flag passed during package setup will do this for you automatically.
+
+.. note::
+
+ For best results, you should run use a Python installation configured with Valgrind support (--with-valgrind)
diff --git a/doc/source/development/index.rst b/doc/source/development/index.rst
index e842c827b417f..abe2fc1409bfb 100644
--- a/doc/source/development/index.rst
+++ b/doc/source/development/index.rst
@@ -17,6 +17,7 @@ Development
maintaining
internals
test_writing
+ debugging_extensions
extending
developer
policies
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index c823ad01f10bf..9c070efa694d4 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -263,12 +263,12 @@ Jinja2 2.10 Conditional formatting with DataFra
PyQt4 Clipboard I/O
PyQt5 Clipboard I/O
PyTables 3.5.1 HDF5-based reading / writing
-SQLAlchemy 1.2.8 SQL support for databases other than sqlite
+SQLAlchemy 1.3.0 SQL support for databases other than sqlite
SciPy 1.12.0 Miscellaneous statistical functions
xlsxwriter 1.0.2 Excel writing
-blosc 1.15.0 Compression for HDF5
+blosc 1.17.0 Compression for HDF5
fsspec 0.7.4 Handling files aside from local and HTTP
-fastparquet 0.3.2 Parquet reading / writing
+fastparquet 0.4.0 Parquet reading / writing
gcsfs 0.6.0 Google Cloud Storage access
html5lib 1.0.1 HTML parser for read_html (see :ref:`note <optional_html>`)
lxml 4.3.0 HTML parser for read_html (see :ref:`note <optional_html>`)
@@ -278,7 +278,7 @@ openpyxl 2.6.0 Reading / writing for xlsx files
pandas-gbq 0.12.0 Google Big Query access
psycopg2 2.7 PostgreSQL engine for sqlalchemy
pyarrow 0.15.0 Parquet, ORC, and feather reading / writing
-pymysql 0.7.11 MySQL engine for sqlalchemy
+pymysql 0.8.1 MySQL engine for sqlalchemy
pyreadstat SPSS files (.sav) reading
pyxlsb 1.0.6 Reading for xlsb files
qtpy Clipboard I/O
diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst
index ffecaa222e1f9..8d38c12252df4 100644
--- a/doc/source/user_guide/basics.rst
+++ b/doc/source/user_guide/basics.rst
@@ -2229,7 +2229,7 @@ Convert certain columns to a specific dtype by passing a dict to :meth:`~DataFra
.. ipython:: python
dft1 = pd.DataFrame({"a": [1, 0, 1], "b": [4, 5, 6], "c": [7, 8, 9]})
- dft1 = dft1.astype({"a": np.bool, "c": np.float64})
+ dft1 = dft1.astype({"a": np.bool_, "c": np.float64})
dft1
dft1.dtypes
diff --git a/doc/source/user_guide/cookbook.rst b/doc/source/user_guide/cookbook.rst
index 5a6f56388dee5..77791b4b7e491 100644
--- a/doc/source/user_guide/cookbook.rst
+++ b/doc/source/user_guide/cookbook.rst
@@ -1406,7 +1406,7 @@ Often it's useful to obtain the lower (or upper) triangular form of a correlatio
df = pd.DataFrame(np.random.random(size=(100, 5)))
corr_mat = df.corr()
- mask = np.tril(np.ones_like(corr_mat, dtype=np.bool), k=-1)
+ mask = np.tril(np.ones_like(corr_mat, dtype=np.bool_), k=-1)
corr_mat.where(mask)
diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst
index 817ea3445f995..0a11344d575f1 100644
--- a/doc/source/user_guide/indexing.rst
+++ b/doc/source/user_guide/indexing.rst
@@ -380,6 +380,8 @@ NA values in a boolean array propagate as ``False``:
.. versionchanged:: 1.0.2
+.. ipython:: python
+
mask = pd.array([True, False, True, False, pd.NA, False], dtype="boolean")
mask
df1[mask]
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index 965833c013c03..a78af82ba4db8 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -2430,16 +2430,14 @@ Read a URL with no options:
.. ipython:: python
- url = "https://www.fdic.gov/bank/individual/failed/banklist.html"
+ url = (
+ "https://raw.githubusercontent.com/pandas-dev/pandas/master/"
+ "pandas/tests/io/data/html/spam.html"
+ )
dfs = pd.read_html(url)
dfs
-.. note::
-
- The data from the above URL changes every Monday so the resulting data above
- and the data below may be slightly different.
-
-Read in the content of the file from the above URL and pass it to ``read_html``
+Read in the content of the "banklist.html" file and pass it to ``read_html``
as a string:
.. ipython:: python
@@ -2820,15 +2818,40 @@ parse HTML tables in the top-level pandas io function ``read_html``.
Excel files
-----------
-The :func:`~pandas.read_excel` method can read Excel 2003 (``.xls``)
-files using the ``xlrd`` Python module. Excel 2007+ (``.xlsx``) files
-can be read using either ``xlrd`` or ``openpyxl``. Binary Excel (``.xlsb``)
+The :func:`~pandas.read_excel` method can read Excel 2007+ (``.xlsx``) files
+using the ``openpyxl`` Python module. Excel 2003 (``.xls``) files
+can be read using ``xlrd``. Binary Excel (``.xlsb``)
files can be read using ``pyxlsb``.
The :meth:`~DataFrame.to_excel` instance method is used for
saving a ``DataFrame`` to Excel. Generally the semantics are
similar to working with :ref:`csv<io.read_csv_table>` data.
See the :ref:`cookbook<cookbook.excel>` for some advanced strategies.
+.. warning::
+
+ The `xlwt <https://xlwt.readthedocs.io/en/latest/>`__ package for writing old-style ``.xls``
+ excel files is no longer maintained.
+ The `xlrd <https://xlrd.readthedocs.io/en/latest/>`__ package is now only for reading
+ old-style ``.xls`` files.
+
+ Previously, the default argument ``engine=None`` to :func:`~pandas.read_excel`
+ would result in using the ``xlrd`` engine in many cases, including new
+ Excel 2007+ (``.xlsx``) files.
+ If `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`__ is installed,
+ many of these cases will now default to using the ``openpyxl`` engine.
+ See the :func:`read_excel` documentation for more details.
+
+ Thus, it is strongly encouraged to install ``openpyxl`` to read Excel 2007+
+ (``.xlsx``) files.
+ **Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.**
+ This is no longer supported, switch to using ``openpyxl`` instead.
+
+ Attempting to use the the ``xlwt`` engine will raise a ``FutureWarning``
+ unless the option :attr:`io.excel.xls.writer` is set to ``"xlwt"``.
+ While this option is now deprecated and will also raise a ``FutureWarning``,
+ it can be globally set and the warning suppressed. Users are recommended to
+ write ``.xlsx`` files using the ``openpyxl`` engine instead.
+
.. _io.excel_reader:
Reading Excel files
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst
index 310857faec436..55e3971502c0a 100644
--- a/doc/source/whatsnew/index.rst
+++ b/doc/source/whatsnew/index.rst
@@ -16,6 +16,7 @@ Version 1.2
.. toctree::
:maxdepth: 2
+ v1.2.1
v1.2.0
Version 1.1
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index e054ac830ce41..64552b104c053 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -716,6 +716,19 @@ apply and applymap on ``DataFrame`` evaluates first row/column only once
df.apply(func, axis=1)
+.. _whatsnew_110.api_breaking:
+
+Backwards incompatible API changes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. _whatsnew_110.api_breaking.testing.check_freq:
+
+Added ``check_freq`` argument to ``testing.assert_frame_equal`` and ``testing.assert_series_equal``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``check_freq`` argument was added to :func:`testing.assert_frame_equal` and :func:`testing.assert_series_equal` in pandas 1.1.0 and defaults to ``True``. :func:`testing.assert_frame_equal` and :func:`testing.assert_series_equal` now raise ``AssertionError`` if the indexes do not have the same frequency. Before pandas 1.1.0, the index frequency was not checked.
+
+
Increased minimum versions for dependencies
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index acf1b3bce8113..8e9361125513b 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -1,7 +1,7 @@
.. _whatsnew_120:
-What's new in 1.2.0 (??)
-------------------------
+What's new in 1.2.0 (December 26, 2020)
+---------------------------------------
These are the changes in pandas 1.2.0. See :ref:`release` for a full changelog
including other versions of pandas.
@@ -10,23 +10,24 @@ including other versions of pandas.
.. warning::
- The packages `xlrd <https://xlrd.readthedocs.io/en/latest/>`_ for reading excel
- files and `xlwt <https://xlwt.readthedocs.io/en/latest/>`_ for
- writing excel files are no longer maintained. These are the only engines in pandas
- that support the xls format.
+ The `xlwt <https://xlwt.readthedocs.io/en/latest/>`_ package for writing old-style ``.xls``
+ excel files is no longer maintained.
+ The `xlrd <https://xlrd.readthedocs.io/en/latest/>`_ package is now only for reading
+ old-style ``.xls`` files.
- Previously, the default argument ``engine=None`` to ``pd.read_excel``
- would result in using the ``xlrd`` engine in many cases. If
- `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`_ is installed,
+ Previously, the default argument ``engine=None`` to :func:`~pandas.read_excel`
+ would result in using the ``xlrd`` engine in many cases, including new
+ Excel 2007+ (``.xlsx``) files.
+ If `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`_ is installed,
many of these cases will now default to using the ``openpyxl`` engine.
- See the :func:`read_excel` documentation for more details. Attempting to read
- ``.xls`` files or specifying ``engine="xlrd"`` to ``pd.read_excel`` will not
- raise a warning. However users should be aware that ``xlrd`` is already
- broken with certain package configurations, for example with Python 3.9
- when `defusedxml <https://github.com/tiran/defusedxml/>`_ is installed, and
- is anticipated to be unusable in the future.
-
- Attempting to use the the ``xlwt`` engine will raise a ``FutureWarning``
+ See the :func:`read_excel` documentation for more details.
+
+ Thus, it is strongly encouraged to install ``openpyxl`` to read Excel 2007+
+ (``.xlsx``) files.
+ **Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.**
+ This is no longer supported, switch to using ``openpyxl`` instead.
+
+ Attempting to use the ``xlwt`` engine will raise a ``FutureWarning``
unless the option :attr:`io.excel.xls.writer` is set to ``"xlwt"``.
While this option is now deprecated and will also raise a ``FutureWarning``,
it can be globally set and the warning suppressed. Users are recommended to
@@ -188,16 +189,16 @@ These are extension data types dedicated to floating point data that can hold th
``pd.NA`` missing value indicator (:issue:`32265`, :issue:`34307`).
While the default float data type already supports missing values using ``np.nan``,
-these new data types use ``pd.NA`` (and its corresponding behaviour) as the missing
+these new data types use ``pd.NA`` (and its corresponding behavior) as the missing
value indicator, in line with the already existing nullable :ref:`integer <integer_na>`
and :ref:`boolean <boolean>` data types.
-One example where the behaviour of ``np.nan`` and ``pd.NA`` is different is
+One example where the behavior of ``np.nan`` and ``pd.NA`` is different is
comparison operations:
.. ipython:: python
- # the default numpy float64 dtype
+ # the default NumPy float64 dtype
s1 = pd.Series([1.5, None])
s1
s1 > 1
@@ -209,7 +210,7 @@ comparison operations:
s2
s2 > 1
-See the :ref:`missing_data.NA` doc section for more details on the behaviour
+See the :ref:`missing_data.NA` doc section for more details on the behavior
when using the ``pd.NA`` missing value indicator.
As shown above, the dtype can be specified using the "Float64" or "Float32"
@@ -226,7 +227,7 @@ give float results will now also use the nullable floating data types (:issue:`3
.. warning::
Experimental: the new floating data types are currently experimental, and their
- behaviour or API may still change without warning. Especially the behaviour
+ behavior or API may still change without warning. Especially the behavior
regarding NaN (distinct from NA missing values) is subject to change.
.. _whatsnew_120.index_name_preservation:
@@ -251,7 +252,7 @@ level-by-level basis.
.. _whatsnew_120.groupby_ewm:
-Groupby supports EWM operations directly
+GroupBy supports EWM operations directly
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:class:`.DataFrameGroupBy` now supports exponentially weighted window operations directly (:issue:`16037`).
@@ -281,16 +282,13 @@ Other enhancements
- :meth:`.Styler.set_table_styles` now allows the direct styling of rows and columns and can be chained (:issue:`35607`)
- :class:`.Styler` now allows direct CSS class name addition to individual data cells (:issue:`36159`)
- :meth:`.Rolling.mean` and :meth:`.Rolling.sum` use Kahan summation to calculate the mean to avoid numerical problems (:issue:`10319`, :issue:`11645`, :issue:`13254`, :issue:`32761`, :issue:`36031`)
-- :meth:`.DatetimeIndex.searchsorted`, :meth:`.TimedeltaIndex.searchsorted`, :meth:`PeriodIndex.searchsorted`, and :meth:`Series.searchsorted` with datetimelike dtypes will now try to cast string arguments (listlike and scalar) to the matching datetimelike type (:issue:`36346`)
+- :meth:`.DatetimeIndex.searchsorted`, :meth:`.TimedeltaIndex.searchsorted`, :meth:`PeriodIndex.searchsorted`, and :meth:`Series.searchsorted` with datetime-like dtypes will now try to cast string arguments (list-like and scalar) to the matching datetime-like type (:issue:`36346`)
- Added methods :meth:`IntegerArray.prod`, :meth:`IntegerArray.min`, and :meth:`IntegerArray.max` (:issue:`33790`)
-- Calling a NumPy ufunc on a ``DataFrame`` with extension types now preserves the extension types when possible (:issue:`23743`).
+- Calling a NumPy ufunc on a ``DataFrame`` with extension types now preserves the extension types when possible (:issue:`23743`)
- Calling a binary-input NumPy ufunc on multiple ``DataFrame`` objects now aligns, matching the behavior of binary operations and ufuncs on ``Series`` (:issue:`23743`).
- Where possible :meth:`RangeIndex.difference` and :meth:`RangeIndex.symmetric_difference` will return :class:`RangeIndex` instead of :class:`Int64Index` (:issue:`36564`)
- :meth:`DataFrame.to_parquet` now supports :class:`MultiIndex` for columns in parquet format (:issue:`34777`)
-- :func:`read_parquet` gained a ``use_nullable_dtypes=True`` option to use
- nullable dtypes that use ``pd.NA`` as missing value indicator where possible
- for the resulting DataFrame (default is False, and only applicable for
- ``engine="pyarrow"``) (:issue:`31242`)
+- :func:`read_parquet` gained a ``use_nullable_dtypes=True`` option to use nullable dtypes that use ``pd.NA`` as missing value indicator where possible for the resulting DataFrame (default is ``False``, and only applicable for ``engine="pyarrow"``) (:issue:`31242`)
- Added :meth:`.Rolling.sem` and :meth:`Expanding.sem` to compute the standard error of the mean (:issue:`26476`)
- :meth:`.Rolling.var` and :meth:`.Rolling.std` use Kahan summation and Welford's Method to avoid numerical issues (:issue:`37051`)
- :meth:`DataFrame.corr` and :meth:`DataFrame.cov` use Welford's Method to avoid numerical issues (:issue:`37448`)
@@ -307,7 +305,8 @@ Other enhancements
- Improve numerical stability for :meth:`.Rolling.skew`, :meth:`.Rolling.kurt`, :meth:`Expanding.skew` and :meth:`Expanding.kurt` through implementation of Kahan summation (:issue:`6929`)
- Improved error reporting for subsetting columns of a :class:`.DataFrameGroupBy` with ``axis=1`` (:issue:`37725`)
- Implement method ``cross`` for :meth:`DataFrame.merge` and :meth:`DataFrame.join` (:issue:`5401`)
-- When :func:`read_csv/sas/json` are called with ``chuncksize``/``iterator`` they can be used in a ``with`` statement as they return context-managers (:issue:`38225`)
+- When :func:`read_csv`, :func:`read_sas` and :func:`read_json` are called with ``chunksize``/``iterator`` they can be used in a ``with`` statement as they return context-managers (:issue:`38225`)
+- Augmented the list of named colors available for styling Excel exports, enabling all of CSS4 colors (:issue:`38247`)
.. ---------------------------------------------------------------------------
@@ -482,7 +481,7 @@ Optional libraries below the lowest tested version may still work, but are not c
+-----------------+-----------------+---------+
| sqlalchemy | 1.2.8 | X |
+-----------------+-----------------+---------+
-| xarray | 0.12.0 | X |
+| xarray | 0.12.3 | X |
+-----------------+-----------------+---------+
| xlrd | 1.2.0 | X |
+-----------------+-----------------+---------+
@@ -495,12 +494,12 @@ Optional libraries below the lowest tested version may still work, but are not c
See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more.
-.. _whatsnew_200.api.other:
+.. _whatsnew_120.api.other:
Other API changes
^^^^^^^^^^^^^^^^^
-- Sorting in descending order is now stable for :meth:`Series.sort_values` and :meth:`Index.sort_values` for DateTime-like :class:`Index` subclasses. This will affect sort order when sorting a DataFrame on multiple columns, sorting with a key function that produces duplicates, or requesting the sorting index when using :meth:`Index.sort_values`. When using :meth:`Series.value_counts`, the count of missing values is no longer necessarily last in the list of duplicate counts. Instead, its position corresponds to the position in the original Series. When using :meth:`Index.sort_values` for DateTime-like :class:`Index` subclasses, NaTs ignored the ``na_position`` argument and were sorted to the beginning. Now they respect ``na_position``, the default being ``last``, same as other :class:`Index` subclasses. (:issue:`35992`)
+- Sorting in descending order is now stable for :meth:`Series.sort_values` and :meth:`Index.sort_values` for Datetime-like :class:`Index` subclasses. This will affect sort order when sorting a DataFrame on multiple columns, sorting with a key function that produces duplicates, or requesting the sorting index when using :meth:`Index.sort_values`. When using :meth:`Series.value_counts`, the count of missing values is no longer necessarily last in the list of duplicate counts. Instead, its position corresponds to the position in the original Series. When using :meth:`Index.sort_values` for Datetime-like :class:`Index` subclasses, NaTs ignored the ``na_position`` argument and were sorted to the beginning. Now they respect ``na_position``, the default being ``last``, same as other :class:`Index` subclasses (:issue:`35992`)
- Passing an invalid ``fill_value`` to :meth:`Categorical.take`, :meth:`.DatetimeArray.take`, :meth:`TimedeltaArray.take`, or :meth:`PeriodArray.take` now raises a ``TypeError`` instead of a ``ValueError`` (:issue:`37733`)
- Passing an invalid ``fill_value`` to :meth:`Series.shift` with a ``CategoricalDtype`` now raises a ``TypeError`` instead of a ``ValueError`` (:issue:`37733`)
- Passing an invalid value to :meth:`IntervalIndex.insert` or :meth:`CategoricalIndex.insert` now raises a ``TypeError`` instead of a ``ValueError`` (:issue:`37733`)
@@ -519,16 +518,13 @@ Deprecations
- Date parser functions :func:`~pandas.io.date_converters.parse_date_time`, :func:`~pandas.io.date_converters.parse_date_fields`, :func:`~pandas.io.date_converters.parse_all_fields` and :func:`~pandas.io.date_converters.generic_parser` from ``pandas.io.date_converters`` are deprecated and will be removed in a future version; use :func:`to_datetime` instead (:issue:`35741`)
- :meth:`DataFrame.lookup` is deprecated and will be removed in a future version, use :meth:`DataFrame.melt` and :meth:`DataFrame.loc` instead (:issue:`18682`)
- The method :meth:`Index.to_native_types` is deprecated. Use ``.astype(str)`` instead (:issue:`28867`)
-- Deprecated indexing :class:`DataFrame` rows with a single datetime-like string as ``df[string]``
- (given the ambiguity whether it is indexing the rows or selecting a column), use
- ``df.loc[string]`` instead (:issue:`36179`)
-- Deprecated casting an object-dtype index of ``datetime`` objects to :class:`.DatetimeIndex` in the :class:`Series` constructor (:issue:`23598`)
+- Deprecated indexing :class:`DataFrame` rows with a single datetime-like string as ``df[string]`` (given the ambiguity whether it is indexing the rows or selecting a column), use ``df.loc[string]`` instead (:issue:`36179`)
- Deprecated :meth:`Index.is_all_dates` (:issue:`27744`)
-- The default value of ``regex`` for :meth:`Series.str.replace` will change from ``True`` to ``False`` in a future release. In addition, single character regular expressions will *not* be treated as literal strings when ``regex=True`` is set. (:issue:`24804`)
+- The default value of ``regex`` for :meth:`Series.str.replace` will change from ``True`` to ``False`` in a future release. In addition, single character regular expressions will *not* be treated as literal strings when ``regex=True`` is set (:issue:`24804`)
- Deprecated automatic alignment on comparison operations between :class:`DataFrame` and :class:`Series`, do ``frame, ser = frame.align(ser, axis=1, copy=False)`` before e.g. ``frame == ser`` (:issue:`28759`)
- :meth:`Rolling.count` with ``min_periods=None`` will default to the size of the window in a future version (:issue:`31302`)
- Using "outer" ufuncs on DataFrames to return 4d ndarray is now deprecated. Convert to an ndarray first (:issue:`23743`)
-- Deprecated slice-indexing on timezone-aware :class:`DatetimeIndex` with naive ``datetime`` objects, to match scalar indexing behavior (:issue:`36148`)
+- Deprecated slice-indexing on tz-aware :class:`DatetimeIndex` with naive ``datetime`` objects, to match scalar indexing behavior (:issue:`36148`)
- :meth:`Index.ravel` returning a ``np.ndarray`` is deprecated, in the future this will return a view on the same index (:issue:`19956`)
- Deprecate use of strings denoting units with 'M', 'Y' or 'y' in :func:`~pandas.to_timedelta` (:issue:`36666`)
- :class:`Index` methods ``&``, ``|``, and ``^`` behaving as the set operations :meth:`Index.intersection`, :meth:`Index.union`, and :meth:`Index.symmetric_difference`, respectively, are deprecated and in the future will behave as pointwise boolean operations matching :class:`Series` behavior. Use the named set methods instead (:issue:`36758`)
@@ -555,8 +551,7 @@ Performance improvements
- :class:`.Styler` uuid method altered to compress data transmission over web whilst maintaining reasonably low table collision probability (:issue:`36345`)
- Performance improvement in :func:`to_datetime` with non-ns time unit for ``float`` ``dtype`` columns (:issue:`20445`)
- Performance improvement in setting values on an :class:`IntervalArray` (:issue:`36310`)
-- The internal index method :meth:`~Index._shallow_copy` now makes the new index and original index share cached attributes,
- avoiding creating these again, if created on either. This can speed up operations that depend on creating copies of existing indexes (:issue:`36840`)
+- The internal index method :meth:`~Index._shallow_copy` now makes the new index and original index share cached attributes, avoiding creating these again, if created on either. This can speed up operations that depend on creating copies of existing indexes (:issue:`36840`)
- Performance improvement in :meth:`.RollingGroupby.count` (:issue:`35625`)
- Small performance decrease to :meth:`.Rolling.min` and :meth:`.Rolling.max` for fixed windows (:issue:`36567`)
- Reduced peak memory usage in :meth:`DataFrame.to_pickle` when using ``protocol=5`` in python 3.8+ (:issue:`34244`)
@@ -566,6 +561,7 @@ Performance improvements
- Performance improvement in :meth:`DataFrame.groupby` for ``float`` ``dtype`` (:issue:`28303`), changes of the underlying hash-function can lead to changes in float based indexes sort ordering for ties (e.g. :meth:`Index.value_counts`)
- Performance improvement in :meth:`pd.isin` for inputs with more than 1e6 elements (:issue:`36611`)
- Performance improvement for :meth:`DataFrame.__setitem__` with list-like indexers (:issue:`37954`)
+- :meth:`read_json` now avoids reading entire file into memory when chunksize is specified (:issue:`34548`)
.. ---------------------------------------------------------------------------
@@ -580,30 +576,30 @@ Categorical
- Bug in :meth:`Categorical.__setitem__` that incorrectly raised when trying to set a tuple value (:issue:`20439`)
- Bug in :meth:`CategoricalIndex.equals` incorrectly casting non-category entries to ``np.nan`` (:issue:`37667`)
- Bug in :meth:`CategoricalIndex.where` incorrectly setting non-category entries to ``np.nan`` instead of raising ``TypeError`` (:issue:`37977`)
-- Bug in :meth:`Categorical.to_numpy` and ``np.array(categorical)`` with timezone-aware ``datetime64`` categories incorrectly dropping the timezone information instead of casting to object dtype (:issue:`38136`)
+- Bug in :meth:`Categorical.to_numpy` and ``np.array(categorical)`` with tz-aware ``datetime64`` categories incorrectly dropping the time zone information instead of casting to object dtype (:issue:`38136`)
-Datetimelike
-^^^^^^^^^^^^
+Datetime-like
+^^^^^^^^^^^^^
- Bug in :meth:`DataFrame.combine_first` that would convert datetime-like column on other :class:`DataFrame` to integer when the column is not present in original :class:`DataFrame` (:issue:`28481`)
- Bug in :attr:`.DatetimeArray.date` where a ``ValueError`` would be raised with a read-only backing array (:issue:`33530`)
- Bug in ``NaT`` comparisons failing to raise ``TypeError`` on invalid inequality comparisons (:issue:`35046`)
-- Bug in :class:`.DateOffset` where attributes reconstructed from pickle files differ from original objects when input values exceed normal ranges (e.g months=12) (:issue:`34511`)
+- Bug in :class:`.DateOffset` where attributes reconstructed from pickle files differ from original objects when input values exceed normal ranges (e.g. months=12) (:issue:`34511`)
- Bug in :meth:`.DatetimeIndex.get_slice_bound` where ``datetime.date`` objects were not accepted or naive :class:`Timestamp` with a tz-aware :class:`.DatetimeIndex` (:issue:`35690`)
- Bug in :meth:`.DatetimeIndex.slice_locs` where ``datetime.date`` objects were not accepted (:issue:`34077`)
- Bug in :meth:`.DatetimeIndex.searchsorted`, :meth:`.TimedeltaIndex.searchsorted`, :meth:`PeriodIndex.searchsorted`, and :meth:`Series.searchsorted` with ``datetime64``, ``timedelta64`` or :class:`Period` dtype placement of ``NaT`` values being inconsistent with NumPy (:issue:`36176`, :issue:`36254`)
-- Inconsistency in :class:`.DatetimeArray`, :class:`.TimedeltaArray`, and :class:`.PeriodArray` method ``__setitem__`` casting arrays of strings to datetimelike scalars but not scalar strings (:issue:`36261`)
-- Bug in :meth:`.DatetimeArray.take` incorrectly allowing ``fill_value`` with a mismatched timezone (:issue:`37356`)
+- Inconsistency in :class:`.DatetimeArray`, :class:`.TimedeltaArray`, and :class:`.PeriodArray` method ``__setitem__`` casting arrays of strings to datetime-like scalars but not scalar strings (:issue:`36261`)
+- Bug in :meth:`.DatetimeArray.take` incorrectly allowing ``fill_value`` with a mismatched time zone (:issue:`37356`)
- Bug in :class:`.DatetimeIndex.shift` incorrectly raising when shifting empty indexes (:issue:`14811`)
-- :class:`Timestamp` and :class:`.DatetimeIndex` comparisons between timezone-aware and timezone-naive objects now follow the standard library ``datetime`` behavior, returning ``True``/``False`` for ``!=``/``==`` and raising for inequality comparisons (:issue:`28507`)
+- :class:`Timestamp` and :class:`.DatetimeIndex` comparisons between tz-aware and tz-naive objects now follow the standard library ``datetime`` behavior, returning ``True``/``False`` for ``!=``/``==`` and raising for inequality comparisons (:issue:`28507`)
- Bug in :meth:`.DatetimeIndex.equals` and :meth:`.TimedeltaIndex.equals` incorrectly considering ``int64`` indexes as equal (:issue:`36744`)
-- :meth:`Series.to_json`, :meth:`DataFrame.to_json`, and :meth:`read_json` now implement timezone parsing when orient structure is ``table`` (:issue:`35973`)
-- :meth:`astype` now attempts to convert to ``datetime64[ns, tz]`` directly from ``object`` with inferred timezone from string (:issue:`35973`)
+- :meth:`Series.to_json`, :meth:`DataFrame.to_json`, and :meth:`read_json` now implement time zone parsing when orient structure is ``table`` (:issue:`35973`)
+- :meth:`astype` now attempts to convert to ``datetime64[ns, tz]`` directly from ``object`` with inferred time zone from string (:issue:`35973`)
- Bug in :meth:`.TimedeltaIndex.sum` and :meth:`Series.sum` with ``timedelta64`` dtype on an empty index or series returning ``NaT`` instead of ``Timedelta(0)`` (:issue:`31751`)
-- Bug in :meth:`.DatetimeArray.shift` incorrectly allowing ``fill_value`` with a mismatched timezone (:issue:`37299`)
+- Bug in :meth:`.DatetimeArray.shift` incorrectly allowing ``fill_value`` with a mismatched time zone (:issue:`37299`)
- Bug in adding a :class:`.BusinessDay` with nonzero ``offset`` to a non-scalar other (:issue:`37457`)
- Bug in :func:`to_datetime` with a read-only array incorrectly raising (:issue:`34857`)
- Bug in :meth:`Series.isin` with ``datetime64[ns]`` dtype and :meth:`.DatetimeIndex.isin` incorrectly casting integers to datetimes (:issue:`36621`)
-- Bug in :meth:`Series.isin` with ``datetime64[ns]`` dtype and :meth:`.DatetimeIndex.isin` failing to consider timezone-aware and timezone-naive datetimes as always different (:issue:`35728`)
+- Bug in :meth:`Series.isin` with ``datetime64[ns]`` dtype and :meth:`.DatetimeIndex.isin` failing to consider tz-aware and tz-naive datetimes as always different (:issue:`35728`)
- Bug in :meth:`Series.isin` with ``PeriodDtype`` dtype and :meth:`PeriodIndex.isin` failing to consider arguments with different ``PeriodDtype`` as always different (:issue:`37528`)
- Bug in :class:`Period` constructor now correctly handles nanoseconds in the ``value`` argument (:issue:`34621` and :issue:`17053`)
@@ -617,7 +613,7 @@ Timedelta
Timezones
^^^^^^^^^
-- Bug in :func:`date_range` was raising AmbiguousTimeError for valid input with ``ambiguous=False`` (:issue:`35297`)
+- Bug in :func:`date_range` was raising ``AmbiguousTimeError`` for valid input with ``ambiguous=False`` (:issue:`35297`)
- Bug in :meth:`Timestamp.replace` was losing fold information (:issue:`37610`)
@@ -625,8 +621,8 @@ Numeric
^^^^^^^
- Bug in :func:`to_numeric` where float precision was incorrect (:issue:`31364`)
- Bug in :meth:`DataFrame.any` with ``axis=1`` and ``bool_only=True`` ignoring the ``bool_only`` keyword (:issue:`32432`)
-- Bug in :meth:`Series.equals` where a ``ValueError`` was raised when numpy arrays were compared to scalars (:issue:`35267`)
-- Bug in :class:`Series` where two Series each have a :class:`.DatetimeIndex` with different timezones having those indexes incorrectly changed when performing arithmetic operations (:issue:`33671`)
+- Bug in :meth:`Series.equals` where a ``ValueError`` was raised when NumPy arrays were compared to scalars (:issue:`35267`)
+- Bug in :class:`Series` where two Series each have a :class:`.DatetimeIndex` with different time zones having those indexes incorrectly changed when performing arithmetic operations (:issue:`33671`)
- Bug in :mod:`pandas.testing` module functions when used with ``check_exact=False`` on complex numeric types (:issue:`28235`)
- Bug in :meth:`DataFrame.__rmatmul__` error handling reporting transposed shapes (:issue:`21581`)
- Bug in :class:`Series` flex arithmetic methods where the result when operating with a ``list``, ``tuple`` or ``np.ndarray`` would have an incorrect name (:issue:`36760`)
@@ -643,15 +639,13 @@ Numeric
Conversion
^^^^^^^^^^
-- Bug in :meth:`DataFrame.to_dict` with ``orient='records'`` now returns python native datetime objects for datetimelike columns (:issue:`21256`)
+- Bug in :meth:`DataFrame.to_dict` with ``orient='records'`` now returns python native datetime objects for datetime-like columns (:issue:`21256`)
- Bug in :meth:`Series.astype` conversion from ``string`` to ``float`` raised in presence of ``pd.NA`` values (:issue:`37626`)
--
Strings
^^^^^^^
- Bug in :meth:`Series.to_string`, :meth:`DataFrame.to_string`, and :meth:`DataFrame.to_latex` adding a leading space when ``index=False`` (:issue:`24980`)
- Bug in :func:`to_numeric` raising a ``TypeError`` when attempting to convert a string dtype Series containing only numeric strings and ``NA`` (:issue:`37262`)
--
Interval
^^^^^^^^
@@ -660,15 +654,14 @@ Interval
- Bug in :meth:`IntervalIndex.take` with negative indices and ``fill_value=None`` (:issue:`37330`)
- Bug in :meth:`IntervalIndex.putmask` with datetime-like dtype incorrectly casting to object dtype (:issue:`37968`)
- Bug in :meth:`IntervalArray.astype` incorrectly dropping dtype information with a :class:`CategoricalDtype` object (:issue:`37984`)
--
Indexing
^^^^^^^^
- Bug in :meth:`PeriodIndex.get_loc` incorrectly raising ``ValueError`` on non-datelike strings instead of ``KeyError``, causing similar errors in :meth:`Series.__getitem__`, :meth:`Series.__contains__`, and :meth:`Series.loc.__getitem__` (:issue:`34240`)
-- Bug in :meth:`Index.sort_values` where, when empty values were passed, the method would break by trying to compare missing values instead of pushing them to the end of the sort order. (:issue:`35584`)
-- Bug in :meth:`Index.get_indexer` and :meth:`Index.get_indexer_non_unique` where ``int64`` arrays are returned instead of ``intp``. (:issue:`36359`)
-- Bug in :meth:`DataFrame.sort_index` where parameter ascending passed as a list on a single level index gives wrong result. (:issue:`32334`)
+- Bug in :meth:`Index.sort_values` where, when empty values were passed, the method would break by trying to compare missing values instead of pushing them to the end of the sort order (:issue:`35584`)
+- Bug in :meth:`Index.get_indexer` and :meth:`Index.get_indexer_non_unique` where ``int64`` arrays are returned instead of ``intp`` (:issue:`36359`)
+- Bug in :meth:`DataFrame.sort_index` where parameter ascending passed as a list on a single level index gives wrong result (:issue:`32334`)
- Bug in :meth:`DataFrame.reset_index` was incorrectly raising a ``ValueError`` for input with a :class:`MultiIndex` with missing values in a level with ``Categorical`` dtype (:issue:`24206`)
- Bug in indexing with boolean masks on datetime-like values sometimes returning a view instead of a copy (:issue:`36210`)
- Bug in :meth:`DataFrame.__getitem__` and :meth:`DataFrame.loc.__getitem__` with :class:`IntervalIndex` columns and a numeric indexer (:issue:`26490`)
@@ -679,11 +672,11 @@ Indexing
- Bug in :meth:`DataFrame.loc` returning empty result when indexer is a slice with negative step size (:issue:`38071`)
- Bug in :meth:`Series.loc` and :meth:`DataFrame.loc` raises when the index was of ``object`` dtype and the given numeric label was in the index (:issue:`26491`)
- Bug in :meth:`DataFrame.loc` returned requested key plus missing values when ``loc`` was applied to single level from a :class:`MultiIndex` (:issue:`27104`)
-- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using a listlike indexer containing NA values (:issue:`37722`)
+- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using a list-like indexer containing NA values (:issue:`37722`)
- Bug in :meth:`DataFrame.loc.__setitem__` expanding an empty :class:`DataFrame` with mixed dtypes (:issue:`37932`)
- Bug in :meth:`DataFrame.xs` ignored ``droplevel=False`` for columns (:issue:`19056`)
-- Bug in :meth:`DataFrame.reindex` raising ``IndexingError`` wrongly for empty DataFrame with ``tolerance`` not None or ``method="nearest"`` (:issue:`27315`)
-- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using listlike indexer that contains elements that are in the index's ``categories`` but not in the index itself failing to raise ``KeyError`` (:issue:`37901`)
+- Bug in :meth:`DataFrame.reindex` raising ``IndexingError`` wrongly for empty DataFrame with ``tolerance`` not ``None`` or ``method="nearest"`` (:issue:`27315`)
+- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using list-like indexer that contains elements that are in the index's ``categories`` but not in the index itself failing to raise ``KeyError`` (:issue:`37901`)
- Bug on inserting a boolean label into a :class:`DataFrame` with a numeric :class:`Index` columns incorrectly casting to integer (:issue:`36319`)
- Bug in :meth:`DataFrame.iloc` and :meth:`Series.iloc` aligning objects in ``__setitem__`` (:issue:`22046`)
- Bug in :meth:`MultiIndex.drop` does not raise if labels are partially found (:issue:`37820`)
@@ -694,8 +687,8 @@ Indexing
- Bug in :meth:`DataFrame.loc` and :meth:`DataFrame.__getitem__` raising ``KeyError`` when columns were :class:`MultiIndex` with only one level (:issue:`29749`)
- Bug in :meth:`Series.__getitem__` and :meth:`DataFrame.__getitem__` raising blank ``KeyError`` without missing keys for :class:`IntervalIndex` (:issue:`27365`)
- Bug in setting a new label on a :class:`DataFrame` or :class:`Series` with a :class:`CategoricalIndex` incorrectly raising ``TypeError`` when the new label is not among the index's categories (:issue:`38098`)
-- Bug in :meth:`Series.loc` and :meth:`Series.iloc` raising ``ValueError`` when inserting a listlike ``np.array``, ``list`` or ``tuple`` in an ``object`` Series of equal length (:issue:`37748`, :issue:`37486`)
-- Bug in :meth:`Series.loc` and :meth:`Series.iloc` setting all the values of an ``object`` Series with those of a listlike ``ExtensionArray`` instead of inserting it (:issue:`38271`)
+- Bug in :meth:`Series.loc` and :meth:`Series.iloc` raising ``ValueError`` when inserting a list-like ``np.array``, ``list`` or ``tuple`` in an ``object`` Series of equal length (:issue:`37748`, :issue:`37486`)
+- Bug in :meth:`Series.loc` and :meth:`Series.iloc` setting all the values of an ``object`` Series with those of a list-like ``ExtensionArray`` instead of inserting it (:issue:`38271`)
Missing
^^^^^^^
@@ -703,7 +696,6 @@ Missing
- Bug in :meth:`.SeriesGroupBy.transform` now correctly handles missing values for ``dropna=False`` (:issue:`35014`)
- Bug in :meth:`Series.nunique` with ``dropna=True`` was returning incorrect results when both ``NA`` and ``None`` missing values were present (:issue:`37566`)
- Bug in :meth:`Series.interpolate` where kwarg ``limit_area`` and ``limit_direction`` had no effect when using methods ``pad`` and ``backfill`` (:issue:`31048`)
--
MultiIndex
^^^^^^^^^^
@@ -731,20 +723,23 @@ I/O
- Bumped minimum pytables version to 3.5.1 to avoid a ``ValueError`` in :meth:`read_hdf` (:issue:`24839`)
- Bug in :func:`read_table` and :func:`read_csv` when ``delim_whitespace=True`` and ``sep=default`` (:issue:`36583`)
- Bug in :meth:`DataFrame.to_json` and :meth:`Series.to_json` when used with ``lines=True`` and ``orient='records'`` the last line of the record is not appended with 'new line character' (:issue:`36888`)
-- Bug in :meth:`read_parquet` with fixed offset timezones. String representation of timezones was not recognized (:issue:`35997`, :issue:`36004`)
+- Bug in :meth:`read_parquet` with fixed offset time zones. String representation of time zones was not recognized (:issue:`35997`, :issue:`36004`)
- Bug in :meth:`DataFrame.to_html`, :meth:`DataFrame.to_string`, and :meth:`DataFrame.to_latex` ignoring the ``na_rep`` argument when ``float_format`` was also specified (:issue:`9046`, :issue:`13828`)
- Bug in output rendering of complex numbers showing too many trailing zeros (:issue:`36799`)
- Bug in :class:`HDFStore` threw a ``TypeError`` when exporting an empty DataFrame with ``datetime64[ns, tz]`` dtypes with a fixed HDF5 store (:issue:`20594`)
-- Bug in :class:`HDFStore` was dropping timezone information when exporting a Series with ``datetime64[ns, tz]`` dtypes with a fixed HDF5 store (:issue:`20594`)
+- Bug in :class:`HDFStore` was dropping time zone information when exporting a Series with ``datetime64[ns, tz]`` dtypes with a fixed HDF5 store (:issue:`20594`)
- :func:`read_csv` was closing user-provided binary file handles when ``engine="c"`` and an ``encoding`` was requested (:issue:`36980`)
- Bug in :meth:`DataFrame.to_hdf` was not dropping missing rows with ``dropna=True`` (:issue:`35719`)
- Bug in :func:`read_html` was raising a ``TypeError`` when supplying a ``pathlib.Path`` argument to the ``io`` parameter (:issue:`37705`)
- :meth:`DataFrame.to_excel`, :meth:`Series.to_excel`, :meth:`DataFrame.to_markdown`, and :meth:`Series.to_markdown` now support writing to fsspec URLs such as S3 and Google Cloud Storage (:issue:`33987`)
- Bug in :func:`read_fwf` with ``skip_blank_lines=True`` was not skipping blank lines (:issue:`37758`)
- Parse missing values using :func:`read_json` with ``dtype=False`` to ``NaN`` instead of ``None`` (:issue:`28501`)
-- :meth:`read_fwf` was inferring compression with ``compression=None`` which was not consistent with the other :meth:``read_*`` functions (:issue:`37909`)
+- :meth:`read_fwf` was inferring compression with ``compression=None`` which was not consistent with the other ``read_*`` functions (:issue:`37909`)
- :meth:`DataFrame.to_html` was ignoring ``formatters`` argument for ``ExtensionDtype`` columns (:issue:`36525`)
- Bumped minimum xarray version to 0.12.3 to avoid reference to the removed ``Panel`` class (:issue:`27101`)
+- :meth:`DataFrame.to_csv` was re-opening file-like handles that also implement ``os.PathLike`` (:issue:`38125`)
+- Bug in the conversion of a sliced ``pyarrow.Table`` with missing values to a DataFrame (:issue:`38525`)
+- Bug in :func:`read_sql_table` raising a ``sqlalchemy.exc.OperationalError`` when column names contained a percentage sign (:issue:`37517`)
Period
^^^^^^
@@ -761,9 +756,13 @@ Plotting
- Bug in :meth:`Series.plot` and :meth:`DataFrame.plot` was throwing a :exc:`ValueError` when the Series or DataFrame was
indexed by a :class:`.TimedeltaIndex` with a fixed frequency and the x-axis lower limit was greater than the upper limit (:issue:`37454`)
- Bug in :meth:`.DataFrameGroupBy.boxplot` when ``subplots=False`` would raise a ``KeyError`` (:issue:`16748`)
-- Bug in :meth:`DataFrame.plot` and :meth:`Series.plot` was overwriting matplotlib's shared y axes behaviour when no ``sharey`` parameter was passed (:issue:`37942`)
+- Bug in :meth:`DataFrame.plot` and :meth:`Series.plot` was overwriting matplotlib's shared y axes behavior when no ``sharey`` parameter was passed (:issue:`37942`)
- Bug in :meth:`DataFrame.plot` was raising a ``TypeError`` with ``ExtensionDtype`` columns (:issue:`32073`)
+Styler
+^^^^^^
+
+- Bug in :meth:`Styler.render` HTML was generated incorrectly because of formatting error in ``rowspan`` attribute, it now matches with w3 syntax (:issue:`38234`)
Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
@@ -773,7 +772,7 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrame.resample` that would throw a ``ValueError`` when resampling from ``"D"`` to ``"24H"`` over a transition into daylight savings time (DST) (:issue:`35219`)
- Bug when combining methods :meth:`DataFrame.groupby` with :meth:`DataFrame.resample` and :meth:`DataFrame.interpolate` raising a ``TypeError`` (:issue:`35325`)
- Bug in :meth:`.DataFrameGroupBy.apply` where a non-nuisance grouping column would be dropped from the output columns if another groupby method was called before ``.apply`` (:issue:`34656`)
-- Bug when subsetting columns on a :class:`~pandas.core.groupby.DataFrameGroupBy` (e.g. ``df.groupby('a')[['b']])``) would reset the attributes ``axis``, ``dropna``, ``group_keys``, ``level``, ``mutated``, ``sort``, and ``squeeze`` to their default values. (:issue:`9959`)
+- Bug when subsetting columns on a :class:`~pandas.core.groupby.DataFrameGroupBy` (e.g. ``df.groupby('a')[['b']])``) would reset the attributes ``axis``, ``dropna``, ``group_keys``, ``level``, ``mutated``, ``sort``, and ``squeeze`` to their default values (:issue:`9959`)
- Bug in :meth:`.DataFrameGroupBy.tshift` failing to raise ``ValueError`` when a frequency cannot be inferred for the index of a group (:issue:`35937`)
- Bug in :meth:`DataFrame.groupby` does not always maintain column index name for ``any``, ``all``, ``bfill``, ``ffill``, ``shift`` (:issue:`29764`)
- Bug in :meth:`.DataFrameGroupBy.apply` raising error with ``np.nan`` group(s) when ``dropna=False`` (:issue:`35889`)
@@ -783,14 +782,15 @@ Groupby/resample/rolling
- Bug in :meth:`.DataFrameGroupBy.ffill` and :meth:`.DataFrameGroupBy.bfill` where a ``NaN`` group would return filled values instead of ``NaN`` when ``dropna=True`` (:issue:`34725`)
- Bug in :meth:`.RollingGroupby.count` where a ``ValueError`` was raised when specifying the ``closed`` parameter (:issue:`35869`)
- Bug in :meth:`.DataFrameGroupBy.rolling` returning wrong values with partial centered window (:issue:`36040`)
-- Bug in :meth:`.DataFrameGroupBy.rolling` returned wrong values with timeaware window containing ``NaN``. Raises ``ValueError`` because windows are not monotonic now (:issue:`34617`)
+- Bug in :meth:`.DataFrameGroupBy.rolling` returned wrong values with time aware window containing ``NaN``. Raises ``ValueError`` because windows are not monotonic now (:issue:`34617`)
- Bug in :meth:`.Rolling.__iter__` where a ``ValueError`` was not raised when ``min_periods`` was larger than ``window`` (:issue:`37156`)
- Using :meth:`.Rolling.var` instead of :meth:`.Rolling.std` avoids numerical issues for :meth:`.Rolling.corr` when :meth:`.Rolling.var` is still within floating point precision while :meth:`.Rolling.std` is not (:issue:`31286`)
- Bug in :meth:`.DataFrameGroupBy.quantile` and :meth:`.Resampler.quantile` raised ``TypeError`` when values were of type ``Timedelta`` (:issue:`29485`)
- Bug in :meth:`.Rolling.median` and :meth:`.Rolling.quantile` returned wrong values for :class:`.BaseIndexer` subclasses with non-monotonic starting or ending points for windows (:issue:`37153`)
- Bug in :meth:`DataFrame.groupby` dropped ``nan`` groups from result with ``dropna=False`` when grouping over a single column (:issue:`35646`, :issue:`35542`)
-- Bug in :meth:`.DataFrameGroupBy.head`, :meth:`.DataFrameGroupBy.tail`, :meth:`SeriesGroupBy.head`, and :meth:`SeriesGroupBy.tail` would raise when used with ``axis=1`` (:issue:`9772`)
+- Bug in :meth:`.DataFrameGroupBy.head`, :meth:`DataFrameGroupBy.tail`, :meth:`SeriesGroupBy.head`, and :meth:`SeriesGroupBy.tail` would raise when used with ``axis=1`` (:issue:`9772`)
- Bug in :meth:`.DataFrameGroupBy.transform` would raise when used with ``axis=1`` and a transformation kernel (e.g. "shift") (:issue:`36308`)
+- Bug in :meth:`.DataFrameGroupBy.resample` using ``.agg`` with sum produced different result than just calling ``.sum`` (:issue:`33548`)
- Bug in :meth:`.DataFrameGroupBy.apply` dropped values on ``nan`` group when returning the same axes with the original frame (:issue:`38227`)
- Bug in :meth:`.DataFrameGroupBy.quantile` couldn't handle with arraylike ``q`` when grouping by columns (:issue:`33795`)
- Bug in :meth:`DataFrameGroupBy.rank` with ``datetime64tz`` or period dtype incorrectly casting results to those dtypes instead of returning ``float64`` dtype (:issue:`38187`)
@@ -803,7 +803,7 @@ Reshaping
- Bug in :func:`concat` and :class:`DataFrame` constructor where input index names are not preserved in some cases (:issue:`13475`)
- Bug in func :meth:`crosstab` when using multiple columns with ``margins=True`` and ``normalize=True`` (:issue:`35144`)
- Bug in :meth:`DataFrame.stack` where an empty DataFrame.stack would raise an error (:issue:`36113`). Now returning an empty Series with empty MultiIndex.
-- Bug in :meth:`Series.unstack`. Now a Series with single level of Index trying to unstack would raise a ValueError. (:issue:`36113`)
+- Bug in :meth:`Series.unstack`. Now a Series with single level of Index trying to unstack would raise a ``ValueError`` (:issue:`36113`)
- Bug in :meth:`DataFrame.agg` with ``func={'name':<FUNC>}`` incorrectly raising ``TypeError`` when ``DataFrame.columns==['Name']`` (:issue:`36212`)
- Bug in :meth:`Series.transform` would give incorrect results or raise when the argument ``func`` was a dictionary (:issue:`35811`)
- Bug in :meth:`DataFrame.pivot` did not preserve :class:`MultiIndex` level names for columns when rows and columns are both multiindexed (:issue:`36360`)
@@ -812,25 +812,18 @@ Reshaping
- Bug in :meth:`DataFrame.combine_first` caused wrong alignment with dtype ``string`` and one level of ``MultiIndex`` containing only ``NA`` (:issue:`37591`)
- Fixed regression in :func:`merge` on merging :class:`.DatetimeIndex` with empty DataFrame (:issue:`36895`)
- Bug in :meth:`DataFrame.apply` not setting index of return value when ``func`` return type is ``dict`` (:issue:`37544`)
-- Bug in :func:`concat` resulting in a ``ValueError`` when at least one of both inputs had a non-unique index (:issue:`36263`)
- Bug in :meth:`DataFrame.merge` and :meth:`pandas.merge` returning inconsistent ordering in result for ``how=right`` and ``how=left`` (:issue:`35382`)
- Bug in :func:`merge_ordered` couldn't handle list-like ``left_by`` or ``right_by`` (:issue:`35269`)
- Bug in :func:`merge_ordered` returned wrong join result when length of ``left_by`` or ``right_by`` equals to the rows of ``left`` or ``right`` (:issue:`38166`)
- Bug in :func:`merge_ordered` didn't raise when elements in ``left_by`` or ``right_by`` not exist in ``left`` columns or ``right`` columns (:issue:`38167`)
- Bug in :func:`DataFrame.drop_duplicates` not validating bool dtype for ``ignore_index`` keyword (:issue:`38274`)
-Sparse
-^^^^^^
-
--
--
-
ExtensionArray
^^^^^^^^^^^^^^
- Fixed bug where :class:`DataFrame` column set to scalar extension type via a dict instantiation was considered an object type rather than the extension type (:issue:`35965`)
- Fixed bug where ``astype()`` with equal dtype and ``copy=False`` would return a new object (:issue:`28488`)
-- Fixed bug when applying a NumPy ufunc with multiple outputs to an :class:`.IntegerArray` returning None (:issue:`36913`)
+- Fixed bug when applying a NumPy ufunc with multiple outputs to an :class:`.IntegerArray` returning ``None`` (:issue:`36913`)
- Fixed an inconsistency in :class:`.PeriodArray`'s ``__init__`` signature to those of :class:`.DatetimeArray` and :class:`.TimedeltaArray` (:issue:`37289`)
- Reductions for :class:`.BooleanArray`, :class:`.Categorical`, :class:`.DatetimeArray`, :class:`.FloatingArray`, :class:`.IntegerArray`, :class:`.PeriodArray`, :class:`.TimedeltaArray`, and :class:`.PandasArray` are now keyword-only methods (:issue:`37541`)
- Fixed a bug where a ``TypeError`` was wrongly raised if a membership check was made on an ``ExtensionArray`` containing nan-like values (:issue:`37867`)
@@ -850,14 +843,14 @@ Other
- Bug in :meth:`Index.difference` failing to set the correct name on the returned :class:`Index` in some corner cases (:issue:`38268`)
- Bug in :meth:`Index.union` behaving differently depending on whether operand is an :class:`Index` or other list-like (:issue:`36384`)
- Bug in :meth:`Index.intersection` with non-matching numeric dtypes casting to ``object`` dtype instead of minimal common dtype (:issue:`38122`)
-- Bug in :meth:`IntervalIndex.intersection` returning an incorrectly-typed :class:`Index` when empty (:issue:`38282`)
+- Bug in :meth:`IntervalIndex.union` returning an incorrectly-typed :class:`Index` when empty (:issue:`38282`)
- Passing an array with 2 or more dimensions to the :class:`Series` constructor now raises the more specific ``ValueError`` rather than a bare ``Exception`` (:issue:`35744`)
- Bug in ``dir`` where ``dir(obj)`` wouldn't show attributes defined on the instance for pandas objects (:issue:`37173`)
- Bug in :meth:`Index.drop` raising ``InvalidIndexError`` when index has duplicates (:issue:`38051`)
- Bug in :meth:`RangeIndex.difference` returning :class:`Int64Index` in some cases where it should return :class:`RangeIndex` (:issue:`38028`)
- Fixed bug in :func:`assert_series_equal` when comparing a datetime-like array with an equivalent non extension dtype array (:issue:`37609`)
-
-
+- Bug in :func:`.is_bool_dtype` would raise when passed a valid string such as ``"boolean"`` (:issue:`38386`)
+- Fixed regression in logical operators raising ``ValueError`` when columns of :class:`DataFrame` are a :class:`CategoricalIndex` with unused categories (:issue:`38367`)
.. ---------------------------------------------------------------------------
@@ -866,4 +859,4 @@ Other
Contributors
~~~~~~~~~~~~
-.. contributors:: v1.1.4..v1.2.0|HEAD
+.. contributors:: v1.1.5..v1.2.0
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst
new file mode 100644
index 0000000000000..8b0d100b9e1b3
--- /dev/null
+++ b/doc/source/whatsnew/v1.2.1.rst
@@ -0,0 +1,65 @@
+.. _whatsnew_121:
+
+What's new in 1.2.1 (January ??, 2021)
+--------------------------------------
+
+These are the changes in pandas 1.2.1. See :ref:`release` for a full changelog
+including other versions of pandas.
+
+{{ header }}
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_121.regressions:
+
+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 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`)
+- 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 :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`)
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_121.bug_fixes:
+
+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`)
+
+-
+-
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_121.other:
+
+Other
+~~~~~
+- 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`)
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_121.contributors:
+
+Contributors
+~~~~~~~~~~~~
+
+.. contributors:: v1.2.0..v1.2.1|HEAD
diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx
index 734b3d5c09cbf..4cddd49381a83 100644
--- a/pandas/_libs/algos.pyx
+++ b/pandas/_libs/algos.pyx
@@ -824,7 +824,7 @@ def rank_1d(
if values.dtype != np.object_:
values = values.astype('O')
else:
- values = np.asarray(in_arr)
+ values = np.asarray(in_arr).copy()
keep_na = na_option == 'keep'
@@ -835,11 +835,6 @@ def rank_1d(
elif rank_t is int64_t:
mask = values == NPY_NAT
- # create copy in case of NPY_NAT
- # values are mutated inplace
- if mask.any():
- values = values.copy()
-
# double sort first by mask and then by values to ensure nan values are
# either at the beginning or the end. mask/(~mask) controls padding at
# tail or the head
diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c
index 88144330c1fe9..4ddbd6cf3ae60 100644
--- a/pandas/_libs/src/parser/tokenizer.c
+++ b/pandas/_libs/src/parser/tokenizer.c
@@ -1733,7 +1733,7 @@ double precise_xstrtod(const char *str, char **endptr, char decimal,
// Process string of digits.
num_digits = 0;
n = 0;
- while (isdigit_ascii(*p)) {
+ while (num_digits < max_digits && isdigit_ascii(*p)) {
n = n * 10 + (*p - '0');
num_digits++;
p++;
@@ -1754,10 +1754,13 @@ double precise_xstrtod(const char *str, char **endptr, char decimal,
} else if (exponent > 0) {
number *= e[exponent];
} else if (exponent < -308) { // Subnormal
- if (exponent < -616) // Prevent invalid array access.
+ if (exponent < -616) { // Prevent invalid array access.
number = 0.;
- number /= e[-308 - exponent];
- number /= e[308];
+ } else {
+ number /= e[-308 - exponent];
+ number /= e[308];
+ }
+
} else {
number /= e[-exponent];
}
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index 54a09a6d2ede7..882674a5c5c92 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -523,7 +523,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start,
float64_t x = 0, xx = 0, xxx = 0
int64_t nobs = 0, i, j, N = len(values), nobs_mean = 0
int64_t s, e
- ndarray[float64_t] output, mean_array
+ ndarray[float64_t] output, mean_array, values_copy
bint is_monotonic_increasing_bounds
minp = max(minp, 3)
@@ -532,10 +532,11 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start,
)
output = np.empty(N, dtype=float)
min_val = np.nanmin(values)
+ values_copy = np.copy(values)
with nogil:
for i in range(0, N):
- val = values[i]
+ val = values_copy[i]
if notnan(val):
nobs_mean += 1
sum_val += val
@@ -544,7 +545,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start,
if min_val - mean_val > -1e5:
mean_val = round(mean_val)
for i in range(0, N):
- values[i] = values[i] - mean_val
+ values_copy[i] = values_copy[i] - mean_val
for i in range(0, N):
@@ -556,7 +557,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start,
if i == 0 or not is_monotonic_increasing_bounds:
for j in range(s, e):
- val = values[j]
+ val = values_copy[j]
add_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_add,
&compensation_xx_add, &compensation_xxx_add)
@@ -566,13 +567,13 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start,
# and removed
# calculate deletes
for j in range(start[i - 1], s):
- val = values[j]
+ val = values_copy[j]
remove_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_remove,
&compensation_xx_remove, &compensation_xxx_remove)
# calculate adds
for j in range(end[i - 1], e):
- val = values[j]
+ val = values_copy[j]
add_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_add,
&compensation_xx_add, &compensation_xxx_add)
@@ -703,7 +704,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start,
float64_t compensation_x_remove = 0, compensation_x_add = 0
float64_t x = 0, xx = 0, xxx = 0, xxxx = 0
int64_t nobs = 0, i, j, s, e, N = len(values), nobs_mean = 0
- ndarray[float64_t] output
+ ndarray[float64_t] output, values_copy
bint is_monotonic_increasing_bounds
minp = max(minp, 4)
@@ -711,11 +712,12 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start,
start, end
)
output = np.empty(N, dtype=float)
+ values_copy = np.copy(values)
min_val = np.nanmin(values)
with nogil:
for i in range(0, N):
- val = values[i]
+ val = values_copy[i]
if notnan(val):
nobs_mean += 1
sum_val += val
@@ -724,7 +726,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start,
if min_val - mean_val > -1e4:
mean_val = round(mean_val)
for i in range(0, N):
- values[i] = values[i] - mean_val
+ values_copy[i] = values_copy[i] - mean_val
for i in range(0, N):
@@ -736,7 +738,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start,
if i == 0 or not is_monotonic_increasing_bounds:
for j in range(s, e):
- add_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx,
+ add_kurt(values_copy[j], &nobs, &x, &xx, &xxx, &xxxx,
&compensation_x_add, &compensation_xx_add,
&compensation_xxx_add, &compensation_xxxx_add)
@@ -746,13 +748,13 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start,
# and removed
# calculate deletes
for j in range(start[i - 1], s):
- remove_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx,
+ remove_kurt(values_copy[j], &nobs, &x, &xx, &xxx, &xxxx,
&compensation_x_remove, &compensation_xx_remove,
&compensation_xxx_remove, &compensation_xxxx_remove)
# calculate adds
for j in range(end[i - 1], e):
- add_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx,
+ add_kurt(values_copy[j], &nobs, &x, &xx, &xxx, &xxxx,
&compensation_x_add, &compensation_xx_add,
&compensation_xxx_add, &compensation_xxxx_add)
diff --git a/pandas/_testing.py b/pandas/_testing.py
index 469f5e1bed6ba..90840033ca099 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -108,6 +108,8 @@
+ BYTES_DTYPES
)
+NULL_OBJECTS = [None, np.nan, pd.NaT, float("nan"), pd.NA]
+
# set testing_mode
_testing_mode_warnings = (DeprecationWarning, ResourceWarning)
@@ -1332,6 +1334,8 @@ def assert_series_equal(
.. versionadded:: 1.0.2
check_freq : bool, default True
Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex.
+
+ .. versionadded:: 1.1.0
check_flags : bool, default True
Whether to check the `flags` attribute.
@@ -1576,6 +1580,8 @@ def assert_frame_equal(
(same as in columns) - same labels must be with the same data.
check_freq : bool, default True
Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex.
+
+ .. versionadded:: 1.1.0
check_flags : bool, default True
Whether to check the `flags` attribute.
rtol : float, default 1e-5
diff --git a/pandas/conftest.py b/pandas/conftest.py
index 2bac2ed198789..d84a72d4cc7a8 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -266,7 +266,7 @@ def nselect_method(request):
# ----------------------------------------------------------------
# Missing values & co.
# ----------------------------------------------------------------
-@pytest.fixture(params=[None, np.nan, pd.NaT, float("nan"), pd.NA], ids=str)
+@pytest.fixture(params=tm.NULL_OBJECTS, ids=str)
def nulls_fixture(request):
"""
Fixture for each null type in pandas.
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 67a0e02fc2d4d..58384405a5cab 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1981,7 +1981,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:
@@ -2193,24 +2199,3 @@ def _sort_tuples(values: np.ndarray[tuple]):
arrays, _ = to_arrays(values, None)
indexer = lexsort_indexer(arrays, orders=True)
return values[indexer]
-
-
-def make_duplicates_of_left_unique_in_right(
- left: np.ndarray, right: np.ndarray
-) -> np.ndarray:
- """
- If left has duplicates, which are also duplicated in right, this duplicated values
- are dropped from right, meaning that every duplicate value from left exists only
- once in right.
-
- Parameters
- ----------
- left: ndarray
- right: ndarray
-
- Returns
- -------
- Duplicates of left are unique in right
- """
- left_duplicates = unique(left[duplicated(left)])
- return right[~(duplicated(right) & isin(right, left_duplicates))]
diff --git a/pandas/core/arrays/_arrow_utils.py b/pandas/core/arrays/_arrow_utils.py
index c89f5554d0715..959a13d9c107d 100644
--- a/pandas/core/arrays/_arrow_utils.py
+++ b/pandas/core/arrays/_arrow_utils.py
@@ -30,7 +30,7 @@ def pyarrow_array_to_numpy_and_mask(arr, dtype):
bitmask = buflist[0]
if bitmask is not None:
mask = pyarrow.BooleanArray.from_buffers(
- pyarrow.bool_(), len(arr), [None, bitmask]
+ pyarrow.bool_(), len(arr), [None, bitmask], offset=arr.offset
)
mask = np.asarray(mask)
else:
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index be9864731842d..2f2f8efc0c360 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1621,6 +1621,17 @@ def floor(self, freq, ambiguous="raise", nonexistent="raise"):
def ceil(self, freq, ambiguous="raise", nonexistent="raise"):
return self._round(freq, RoundTo.PLUS_INFTY, ambiguous, nonexistent)
+ # --------------------------------------------------------------
+ # Reductions
+
+ def any(self, *, axis: Optional[int] = None, skipna: bool = True):
+ # GH#34479 discussion of desired behavior long-term
+ return nanops.nanany(self._ndarray, axis=axis, skipna=skipna, mask=self.isna())
+
+ def all(self, *, axis: Optional[int] = None, skipna: bool = True):
+ # GH#34479 discussion of desired behavior long-term
+ return nanops.nanall(self._ndarray, axis=axis, skipna=skipna, mask=self.isna())
+
# --------------------------------------------------------------
# Frequency Methods
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 184fbc050036b..7d3806fe11bd2 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -29,13 +29,12 @@
except ImportError:
pa = None
else:
- # our min supported version of pyarrow, 0.15.1, does not have a compute
- # module
- try:
+ # PyArrow backed StringArrays are available starting at 1.0.0, but this
+ # file is imported from even if pyarrow is < 1.0.0, before pyarrow.compute
+ # and its compute functions existed. GH38801
+ if LooseVersion(pa.__version__) >= "1.0.0":
import pyarrow.compute as pc
- except ImportError:
- pass
- else:
+
ARROW_CMP_FUNCS = {
"eq": pc.equal,
"ne": pc.not_equal,
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index b4f6d587c6642..73cf20979a8ad 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -1382,7 +1382,7 @@ def is_bool_dtype(arr_or_dtype) -> bool:
return False
try:
dtype = get_dtype(arr_or_dtype)
- except TypeError:
+ except (TypeError, ValueError):
return False
if isinstance(arr_or_dtype, CategoricalDtype):
@@ -1397,7 +1397,7 @@ def is_bool_dtype(arr_or_dtype) -> bool:
# guess this
return arr_or_dtype.is_object and arr_or_dtype.inferred_type == "boolean"
elif is_extension_array_dtype(arr_or_dtype):
- return getattr(arr_or_dtype, "dtype", arr_or_dtype)._is_boolean
+ return getattr(dtype, "_is_boolean", False)
return issubclass(dtype.type, np.bool_)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index a1582a57e9a71..396108bab47b7 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4572,20 +4572,23 @@ def shift(
if axis == 1 and periods != 0 and fill_value is lib.no_default and ncols > 0:
# We will infer fill_value to match the closest column
+ # Use a column that we know is valid for our column's dtype GH#38434
+ label = self.columns[0]
+
if periods > 0:
result = self.iloc[:, :-periods]
for col in range(min(ncols, abs(periods))):
# TODO(EA2D): doing this in a loop unnecessary with 2D EAs
# Define filler inside loop so we get a copy
filler = self.iloc[:, 0].shift(len(self))
- result.insert(0, col, filler, allow_duplicates=True)
+ result.insert(0, label, filler, allow_duplicates=True)
else:
result = self.iloc[:, -periods:]
for col in range(min(ncols, abs(periods))):
# Define filler inside loop so we get a copy
filler = self.iloc[:, -1].shift(len(self))
result.insert(
- len(result.columns), col, filler, allow_duplicates=True
+ len(result.columns), label, filler, allow_duplicates=True
)
result.columns = self.columns.copy()
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index b851c4d7d4931..2f7e78d696d7c 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -172,7 +172,9 @@ class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
]
_internal_names_set: Set[str] = set(_internal_names)
_accessors: Set[str] = set()
- _hidden_attrs: FrozenSet[str] = frozenset(["get_values", "tshift"])
+ _hidden_attrs: FrozenSet[str] = frozenset(
+ ["_AXIS_NAMES", "_AXIS_NUMBERS", "get_values", "tshift"]
+ )
_metadata: List[str] = []
_is_copy = None
_mgr: BlockManager
@@ -9689,12 +9691,6 @@ def truncate(
# if we have a date index, convert to dates, otherwise
# treat like a slice
if ax._is_all_dates:
- if is_object_dtype(ax.dtype):
- warnings.warn(
- "Treating object-dtype Index of date objects as DatetimeIndex "
- "is deprecated, will be removed in a future version.",
- FutureWarning,
- )
from pandas.core.tools.datetimes import to_datetime
before = to_datetime(before)
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 23f0e178130be..1272ea7547209 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1606,12 +1606,11 @@ def sem(self, ddof: int = 1):
if result.ndim == 1:
result /= np.sqrt(self.count())
else:
- cols = result.columns.get_indexer_for(
- result.columns.difference(self.exclusions).unique()
- )
- result.iloc[:, cols] = result.iloc[:, cols] / np.sqrt(
- self.count().iloc[:, cols]
- )
+ cols = result.columns.difference(self.exclusions).unique()
+ counts = self.count()
+ result_ilocs = result.columns.get_indexer_for(cols)
+ count_ilocs = counts.columns.get_indexer_for(cols)
+ result.iloc[:, result_ilocs] /= np.sqrt(counts.iloc[:, count_ilocs])
return result
@final
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py
index d814a7cee436e..17584ffc5b1bf 100644
--- a/pandas/core/groupby/grouper.py
+++ b/pandas/core/groupby/grouper.py
@@ -287,6 +287,7 @@ def __init__(
self.indexer = None
self.binner = None
self._grouper = None
+ self._indexer = None
self.dropna = dropna
@final
@@ -341,15 +342,24 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False):
# Keep self.grouper value before overriding
if self._grouper is None:
self._grouper = self.grouper
+ self._indexer = self.indexer
# the key must be a valid info item
if self.key is not None:
key = self.key
# The 'on' is already defined
if getattr(self.grouper, "name", None) == key and isinstance(obj, Series):
- # pandas\core\groupby\grouper.py:348: error: Item "None" of
- # "Optional[Any]" has no attribute "take" [union-attr]
- ax = self._grouper.take(obj.index) # type: ignore[union-attr]
+ # Sometimes self._grouper will have been resorted while
+ # obj has not. In this case there is a mismatch when we
+ # call self._grouper.take(obj.index) so we need to undo the sorting
+ # before we call _grouper.take.
+ assert self._grouper is not None
+ if self._indexer is not None:
+ reverse_indexer = self._indexer.argsort()
+ unsorted_ax = self._grouper.take(reverse_indexer)
+ ax = unsorted_ax.take(obj.index)
+ else:
+ ax = self._grouper.take(obj.index)
else:
if key not in obj._info_axis:
raise KeyError(f"The grouper name {key} is not found")
@@ -572,13 +582,8 @@ def indices(self):
if isinstance(self.grouper, ops.BaseGrouper):
return self.grouper.indices
- # Return a dictionary of {group label: [indices belonging to the group label]}
- # respecting whether sort was specified
- codes, uniques = algorithms.factorize(self.grouper, sort=self.sort)
- return {
- category: np.flatnonzero(codes == i)
- for i, category in enumerate(Index(uniques))
- }
+ values = Categorical(self.grouper)
+ return values._reverse_indexer()
@property
def codes(self) -> np.ndarray:
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 7724e3930f7df..e2ba2768a885a 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -53,6 +53,7 @@
is_timedelta64_dtype,
needs_i8_conversion,
)
+from pandas.core.dtypes.generic import ABCCategoricalIndex
from pandas.core.dtypes.missing import isna, maybe_fill
import pandas.core.algorithms as algorithms
@@ -244,6 +245,11 @@ def apply(self, f: F, data: FrameOrSeries, axis: int = 0):
@cache_readonly
def indices(self):
""" dict {group name -> group indices} """
+ if len(self.groupings) == 1 and isinstance(
+ self.result_index, ABCCategoricalIndex
+ ):
+ # This shows unused categories in indices GH#38642
+ return self.groupings[0].indices
codes_list = [ping.codes for ping in self.groupings]
keys = [ping.group_index for ping in self.groupings]
return get_indexer_dict(codes_list, keys)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 46a1646727bae..11d191597d61e 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4455,15 +4455,16 @@ def equals(self, other: object) -> bool:
if not isinstance(other, Index):
return False
- # If other is a subclass of self and defines its own equals method, we
- # dispatch to the subclass method. For instance for a MultiIndex,
- # a d-level MultiIndex can equal d-tuple Index.
- # Note: All EA-backed Index subclasses override equals
- if (
- isinstance(other, type(self))
- and type(other) is not type(self)
- and other.equals is not self.equals
- ):
+ if is_object_dtype(self.dtype) and not is_object_dtype(other.dtype):
+ # if other is not object, use other's logic for coercion
+ return other.equals(self)
+
+ if isinstance(other, ABCMultiIndex):
+ # d-level MultiIndex can equal d-tuple Index
+ return other.equals(self)
+
+ if is_extension_array_dtype(other.dtype):
+ # All EA-backed Index subclasses override equals
return other.equals(self)
return array_equivalent(self._values, other._values)
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py
index d8b5dba424cbf..7b14a5c636abe 100644
--- a/pandas/core/ops/__init__.py
+++ b/pandas/core/ops/__init__.py
@@ -309,11 +309,11 @@ def should_reindex_frame_op(
if fill_value is None and level is None and axis is default_axis:
# TODO: any other cases we should handle here?
- cols = left.columns.intersection(right.columns)
# Intersection is always unique so we have to check the unique columns
left_uniques = left.columns.unique()
right_uniques = right.columns.unique()
+ cols = left_uniques.intersection(right_uniques)
if len(cols) and not (cols.equals(left_uniques) and cols.equals(right_uniques)):
# TODO: is there a shortcut available when len(cols) == 0?
return True
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index 4a2629daf63d7..70668ac64625c 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -23,7 +23,6 @@
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
from pandas.core.dtypes.missing import isna
-import pandas.core.algorithms as algos
from pandas.core.arrays.categorical import (
factorize_from_iterable,
factorize_from_iterables,
@@ -514,14 +513,7 @@ def get_result(self):
# 1-ax to convert BlockManager axis to DataFrame axis
obj_labels = obj.axes[1 - ax]
if not new_labels.equals(obj_labels):
- # We have to remove the duplicates from obj_labels
- # in new labels to make them unique, otherwise we would
- # duplicate or duplicates again
- if not obj_labels.is_unique:
- new_labels = algos.make_duplicates_of_left_unique_in_right(
- np.asarray(obj_labels), np.asarray(new_labels)
- )
- indexers[ax] = obj_labels.reindex(new_labels)[1]
+ indexers[ax] = obj_labels.get_indexer(new_labels)
mgrs_indexers.append((obj._mgr, indexers))
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 2c6cdb846221f..95fdb21824234 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -859,7 +859,7 @@ def _maybe_add_join_keys(self, result, left_indexer, right_indexer):
mask_right = right_indexer == -1
if mask_left.all():
key_col = rvals
- elif mask_right.all():
+ elif right_indexer is not None and mask_right.all():
key_col = lvals
else:
key_col = Index(lvals).where(~mask_left, rvals)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 0e9476285c258..1449b78ee91d8 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -430,13 +430,6 @@ def _set_axis(self, axis: int, labels, fastpath: bool = False) -> None:
# need to set here because we changed the index
if fastpath:
self._mgr.set_axis(axis, labels)
- warnings.warn(
- "Automatically casting object-dtype Index of datetimes to "
- "DatetimeIndex is deprecated and will be removed in a "
- "future version. Explicitly cast to DatetimeIndex instead.",
- FutureWarning,
- stacklevel=3,
- )
except (tslibs.OutOfBoundsDatetime, ValueError):
# labels may exceeds datetime bounds,
# or not be a DatetimeIndex
diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py
index 3aeb3b664b27f..4007ef50932fc 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 apply, add group keys to index to identify pieces.
+ When calling ``groupby().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 e6185f8ae0679..e50a907901dc7 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -767,28 +767,22 @@ def _apply(
numba_cache_key,
**kwargs,
)
- # Reconstruct the resulting MultiIndex from tuples
+ # Reconstruct the resulting MultiIndex
# 1st set of levels = group by labels
- # 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
+ # 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
- column_keys = [
+ drop_columns = [
key
- for key in result_index_names
+ for key in groupby_keys
if key not in self.obj.index.names or key is None
]
-
- 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")
+ 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")
codes = self._groupby.grouper.codes
levels = self._groupby.grouper.levels
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 9fede5180e727..e838e10a27d21 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -4,10 +4,10 @@
from collections import abc
import dataclasses
import gzip
-from io import BufferedIOBase, BytesIO, RawIOBase, TextIOWrapper
+from io import BufferedIOBase, BytesIO, RawIOBase, StringIO, TextIOWrapper
import mmap
import os
-from typing import IO, Any, AnyStr, Dict, List, Mapping, Optional, Tuple, cast
+from typing import IO, Any, AnyStr, Dict, List, Mapping, Optional, Tuple, Union, cast
from urllib.parse import (
urljoin,
urlparse as parse_url,
@@ -152,6 +152,7 @@ def validate_header_arg(header) -> None:
def stringify_path(
filepath_or_buffer: FilePathOrBuffer[AnyStr],
+ convert_file_like: bool = False,
) -> FileOrBuffer[AnyStr]:
"""
Attempt to convert a path-like object to a string.
@@ -169,12 +170,15 @@ def stringify_path(
Objects supporting the fspath protocol (python 3.6+) are coerced
according to its __fspath__ method.
- For backwards compatibility with older pythons, pathlib.Path and
- py.path objects are specially coerced.
-
Any other object is passed through unchanged, which includes bytes,
strings, buffers, or anything else that's not even path-like.
"""
+ if not convert_file_like and is_file_like(filepath_or_buffer):
+ # GH 38125: some fsspec objects implement os.PathLike but have already opened a
+ # file. This prevents opening the file a second time. infer_compression calls
+ # this function with convert_file_like=True to infer the compression.
+ return cast(FileOrBuffer[AnyStr], filepath_or_buffer)
+
if isinstance(filepath_or_buffer, os.PathLike):
filepath_or_buffer = filepath_or_buffer.__fspath__()
return _expand_user(filepath_or_buffer)
@@ -462,7 +466,7 @@ def infer_compression(
# Infer compression
if compression == "infer":
# Convert all path types (e.g. pathlib.Path) to strings
- filepath_or_buffer = stringify_path(filepath_or_buffer)
+ filepath_or_buffer = stringify_path(filepath_or_buffer, convert_file_like=True)
if not isinstance(filepath_or_buffer, str):
# Cannot infer compression of a buffer, assume no compression
return None
@@ -543,8 +547,7 @@ def get_handle(
Returns the dataclass IOHandles
"""
# Windows does not default to utf-8. Set to utf-8 for a consistent behavior
- if encoding is None:
- encoding = "utf-8"
+ encoding_passed, encoding = encoding, encoding or "utf-8"
# read_csv does not know whether the buffer is opened in binary/text mode
if _is_binary_mode(path_or_buf, mode) and "b" not in mode:
@@ -631,6 +634,9 @@ def get_handle(
# Check whether the filename is to be opened in binary mode.
# Binary mode does not support 'encoding' and 'newline'.
if ioargs.encoding and "b" not in ioargs.mode:
+ if errors is None and encoding_passed is None:
+ # ignore errors when no encoding is specified
+ errors = "replace"
# Encoding
handle = open(
handle,
@@ -703,17 +709,36 @@ def __init__(
archive_name: Optional[str] = None,
**kwargs,
):
- if mode in ["wb", "rb"]:
- mode = mode.replace("b", "")
+ mode = mode.replace("b", "")
self.archive_name = archive_name
+ self.multiple_write_buffer: Optional[Union[StringIO, BytesIO]] = None
+
kwargs_zip: Dict[str, Any] = {"compression": zipfile.ZIP_DEFLATED}
kwargs_zip.update(kwargs)
+
super().__init__(file, mode, **kwargs_zip) # type: ignore[arg-type]
def write(self, data):
+ # buffer multiple write calls, write on flush
+ if self.multiple_write_buffer is None:
+ self.multiple_write_buffer = (
+ BytesIO() if isinstance(data, bytes) else StringIO()
+ )
+ self.multiple_write_buffer.write(data)
+
+ def flush(self) -> None:
+ # write to actual handle and close write buffer
+ if self.multiple_write_buffer is None or self.multiple_write_buffer.closed:
+ return
+
# ZipFile needs a non-empty string
archive_name = self.archive_name or self.filename or "zip"
- super().writestr(archive_name, data)
+ with self.multiple_write_buffer:
+ super().writestr(archive_name, self.multiple_write_buffer.getvalue())
+
+ def close(self):
+ self.flush()
+ super().close()
@property
def closed(self):
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index bf1011176693f..5be8dbf152309 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -1,11 +1,13 @@
import abc
import datetime
+from distutils.version import LooseVersion
import inspect
from io import BufferedIOBase, BytesIO, RawIOBase
import os
from textwrap import fill
-from typing import Any, Dict, Mapping, Union, cast
+from typing import IO, Any, Dict, Mapping, Optional, Union, cast
import warnings
+import zipfile
from pandas._config import config
@@ -13,11 +15,12 @@
from pandas._typing import Buffer, FilePathOrBuffer, StorageOptions
from pandas.compat._optional import import_optional_dependency
from pandas.errors import EmptyDataError
-from pandas.util._decorators import Appender, deprecate_nonkeyword_arguments
+from pandas.util._decorators import Appender, deprecate_nonkeyword_arguments, doc
from pandas.core.dtypes.common import is_bool, is_float, is_integer, is_list_like
from pandas.core.frame import DataFrame
+from pandas.core.shared_docs import _shared_docs
from pandas.io.common import IOHandles, get_handle, stringify_path, validate_header_arg
from pandas.io.excel._util import (
@@ -105,28 +108,26 @@
Supported engines: "xlrd", "openpyxl", "odf", "pyxlsb".
Engine compatibility :
- - "xlrd" supports most old/new Excel file formats.
+ - "xlrd" supports old-style Excel files (.xls).
- "openpyxl" supports newer Excel file formats.
- "odf" supports OpenDocument file formats (.odf, .ods, .odt).
- "pyxlsb" supports Binary Excel files.
.. versionchanged:: 1.2.0
The engine `xlrd <https://xlrd.readthedocs.io/en/latest/>`_
- is no longer maintained, and is not supported with
- python >= 3.9. When ``engine=None``, the following logic will be
- used to determine the engine.
-
- - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
- then `odf <https://pypi.org/project/odfpy/>`_ will be used.
- - Otherwise if ``path_or_buffer`` is a bytes stream, the file has the
- extension ``.xls``, or is an ``xlrd`` Book instance, then ``xlrd`` will
- be used.
- - Otherwise if `openpyxl <https://pypi.org/project/openpyxl/>`_ is installed,
- then ``openpyxl`` will be used.
- - Otherwise ``xlrd`` will be used and a ``FutureWarning`` will be raised.
-
- Specifying ``engine="xlrd"`` will continue to be allowed for the
- indefinite future.
+ now only supports old-style ``.xls`` files.
+ When ``engine=None``, the following logic will be
+ used to determine the engine:
+
+ - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
+ then `odf <https://pypi.org/project/odfpy/>`_ will be used.
+ - Otherwise if ``path_or_buffer`` is an xls format,
+ ``xlrd`` will be used.
+ - Otherwise if `openpyxl <https://pypi.org/project/openpyxl/>`_ is installed,
+ then ``openpyxl`` will be used.
+ - Otherwise if ``xlrd >= 2.0`` is installed, a ``ValueError`` will be raised.
+ - Otherwise ``xlrd`` will be used and a ``FutureWarning`` will be raised. This
+ case will raise a ``ValueError`` in a future version of pandas.
converters : dict, default None
Dict of functions for converting values in certain columns. Keys can
@@ -888,39 +889,92 @@ def close(self):
return content
-def _is_ods_stream(stream: Union[BufferedIOBase, RawIOBase]) -> bool:
+XLS_SIGNATURE = b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
+ZIP_SIGNATURE = b"PK\x03\x04"
+PEEK_SIZE = max(len(XLS_SIGNATURE), len(ZIP_SIGNATURE))
+
+
+@doc(storage_options=_shared_docs["storage_options"])
+def inspect_excel_format(
+ path: Optional[str] = None,
+ content: Union[None, BufferedIOBase, RawIOBase, bytes] = None,
+ storage_options: StorageOptions = None,
+) -> str:
"""
- Check if the stream is an OpenDocument Spreadsheet (.ods) file
+ Inspect the path or content of an excel file and get its format.
- It uses magic values inside the stream
+ At least one of path or content must be not None. If both are not None,
+ content will take precedence.
+
+ Adopted from xlrd: https://github.com/python-excel/xlrd.
Parameters
----------
- stream : Union[BufferedIOBase, RawIOBase]
- IO stream with data which might be an ODS file
+ path : str, optional
+ Path to file to inspect. May be a URL.
+ content : file-like object, optional
+ Content of file to inspect.
+ {storage_options}
Returns
-------
- is_ods : bool
- Boolean indication that this is indeed an ODS file or not
+ str
+ Format of file.
+
+ Raises
+ ------
+ ValueError
+ If resulting stream is empty.
+ BadZipFile
+ If resulting stream does not have an XLS signature and is not a valid zipfile.
"""
- stream.seek(0)
- is_ods = False
- if stream.read(4) == b"PK\003\004":
- stream.seek(30)
- is_ods = (
- stream.read(54) == b"mimetype"
- b"application/vnd.oasis.opendocument.spreadsheet"
- )
- stream.seek(0)
- return is_ods
+ content_or_path: Union[None, str, BufferedIOBase, RawIOBase, IO[bytes]]
+ if isinstance(content, bytes):
+ content_or_path = BytesIO(content)
+ else:
+ content_or_path = content or path
+ assert content_or_path is not None
+
+ with get_handle(
+ content_or_path, "rb", storage_options=storage_options, is_text=False
+ ) as handle:
+ stream = handle.handle
+ stream.seek(0)
+ buf = stream.read(PEEK_SIZE)
+ if buf is None:
+ raise ValueError("stream is empty")
+ else:
+ assert isinstance(buf, bytes)
+ peek = buf
+ stream.seek(0)
+
+ if peek.startswith(XLS_SIGNATURE):
+ return "xls"
+ elif not peek.startswith(ZIP_SIGNATURE):
+ raise ValueError("File is not a recognized excel file")
+
+ # ZipFile typing is overly-strict
+ # https://github.com/python/typeshed/issues/4212
+ zf = zipfile.ZipFile(stream) # type: ignore[arg-type]
+
+ # Workaround for some third party files that use forward slashes and
+ # lower case names.
+ component_names = [name.replace("\\", "/").lower() for name in zf.namelist()]
+
+ if "xl/workbook.xml" in component_names:
+ return "xlsx"
+ if "xl/workbook.bin" in component_names:
+ return "xlsb"
+ if "content.xml" in component_names:
+ return "ods"
+ return "zip"
class ExcelFile:
"""
Class for parsing tabular excel sheets into DataFrame objects.
- Uses xlrd engine by default. See read_excel for more documentation
+ See read_excel for more documentation.
Parameters
----------
@@ -933,7 +987,7 @@ class ExcelFile:
Supported engines: ``xlrd``, ``openpyxl``, ``odf``, ``pyxlsb``
Engine compatibility :
- - ``xlrd`` supports most old/new Excel file formats.
+ - ``xlrd`` supports old-style Excel files (.xls).
- ``openpyxl`` supports newer Excel file formats.
- ``odf`` supports OpenDocument file formats (.odf, .ods, .odt).
- ``pyxlsb`` supports Binary Excel files.
@@ -941,21 +995,24 @@ class ExcelFile:
.. versionchanged:: 1.2.0
The engine `xlrd <https://xlrd.readthedocs.io/en/latest/>`_
- is no longer maintained, and is not supported with
- python >= 3.9. When ``engine=None``, the following logic will be
- used to determine the engine.
+ now only supports old-style ``.xls`` files.
+ When ``engine=None``, the following logic will be
+ used to determine the engine:
- If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
then `odf <https://pypi.org/project/odfpy/>`_ will be used.
- - Otherwise if ``path_or_buffer`` is a bytes stream, the file has the
- extension ``.xls``, or is an ``xlrd`` Book instance, then ``xlrd``
- will be used.
+ - Otherwise if ``path_or_buffer`` is an xls format,
+ ``xlrd`` will be used.
- Otherwise if `openpyxl <https://pypi.org/project/openpyxl/>`_ is installed,
then ``openpyxl`` will be used.
+ - Otherwise if ``xlrd >= 2.0`` is installed, a ``ValueError`` will be raised.
- Otherwise ``xlrd`` will be used and a ``FutureWarning`` will be raised.
+ This case will raise a ``ValueError`` in a future version of pandas.
+
+ .. warning::
- Specifying ``engine="xlrd"`` will continue to be allowed for the
- indefinite future.
+ Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.
+ This is not supported, switch to using ``openpyxl`` instead.
"""
from pandas.io.excel._odfreader import ODFReader
@@ -973,33 +1030,42 @@ class ExcelFile:
def __init__(
self, path_or_buffer, engine=None, storage_options: StorageOptions = None
):
- if engine is None:
- # Determine ext and use odf for ods stream/file
- if isinstance(path_or_buffer, (BufferedIOBase, RawIOBase)):
- ext = None
- if _is_ods_stream(path_or_buffer):
- engine = "odf"
- else:
- ext = os.path.splitext(str(path_or_buffer))[-1]
- if ext == ".ods":
- engine = "odf"
+ if engine is not None and engine not in self._engines:
+ raise ValueError(f"Unknown engine: {engine}")
- if (
- import_optional_dependency(
- "xlrd", raise_on_missing=False, on_version="ignore"
- )
- is not None
- ):
- from xlrd import Book
+ # Could be a str, ExcelFile, Book, etc.
+ self.io = path_or_buffer
+ # Always a string
+ self._io = stringify_path(path_or_buffer)
- if isinstance(path_or_buffer, Book):
- engine = "xlrd"
+ # Determine xlrd version if installed
+ if (
+ import_optional_dependency(
+ "xlrd", raise_on_missing=False, on_version="ignore"
+ )
+ is None
+ ):
+ xlrd_version = None
+ else:
+ import xlrd
- # GH 35029 - Prefer openpyxl except for xls files
- if engine is None:
- if ext is None or isinstance(path_or_buffer, bytes) or ext == ".xls":
- engine = "xlrd"
- elif (
+ xlrd_version = LooseVersion(xlrd.__version__)
+
+ if xlrd_version is not None and isinstance(path_or_buffer, xlrd.Book):
+ ext = "xls"
+ else:
+ ext = inspect_excel_format(
+ content=path_or_buffer, storage_options=storage_options
+ )
+
+ if engine is None:
+ if ext == "ods":
+ engine = "odf"
+ elif ext == "xls":
+ engine = "xlrd"
+ else:
+ # GH 35029 - Prefer openpyxl except for xls files
+ if (
import_optional_dependency(
"openpyxl", raise_on_missing=False, on_version="ignore"
)
@@ -1007,37 +1073,39 @@ def __init__(
):
engine = "openpyxl"
else:
- caller = inspect.stack()[1]
- if (
- caller.filename.endswith("pandas/io/excel/_base.py")
- and caller.function == "read_excel"
- ):
- stacklevel = 4
- else:
- stacklevel = 2
- warnings.warn(
- "The xlrd engine is no longer maintained and is not "
- "supported when using pandas with python >= 3.9. However, "
- "the engine xlrd will continue to be allowed for the "
- "indefinite future. Beginning with pandas 1.2.0, the "
- "openpyxl engine will be used if it is installed and the "
- "engine argument is not specified. Either install openpyxl "
- "or specify engine='xlrd' to silence this warning.",
- FutureWarning,
- stacklevel=stacklevel,
- )
engine = "xlrd"
- if engine not in self._engines:
- raise ValueError(f"Unknown engine: {engine}")
+
+ if engine == "xlrd" and ext != "xls" and xlrd_version is not None:
+ if xlrd_version >= "2":
+ raise ValueError(
+ f"Your version of xlrd is {xlrd_version}. In xlrd >= 2.0, "
+ f"only the xls format is supported. Install openpyxl instead."
+ )
+ else:
+ caller = inspect.stack()[1]
+ if (
+ caller.filename.endswith(
+ os.path.join("pandas", "io", "excel", "_base.py")
+ )
+ and caller.function == "read_excel"
+ ):
+ stacklevel = 4
+ else:
+ stacklevel = 2
+ warnings.warn(
+ f"Your version of xlrd is {xlrd_version}. In xlrd >= 2.0, "
+ f"only the xls format is supported. As a result, the "
+ f"openpyxl engine will be used if it is installed and the "
+ f"engine argument is not specified. Install "
+ f"openpyxl instead.",
+ FutureWarning,
+ stacklevel=stacklevel,
+ )
+ assert engine in self._engines, f"Engine {engine} not recognized"
self.engine = engine
self.storage_options = storage_options
- # Could be a str, ExcelFile, Book, etc.
- self.io = path_or_buffer
- # Always a string
- self._io = stringify_path(path_or_buffer)
-
self._reader = self._engines[engine](self._io, storage_options=storage_options)
def __fspath__(self):
diff --git a/pandas/io/formats/_color_data.py b/pandas/io/formats/_color_data.py
new file mode 100644
index 0000000000000..e5b72b2befa4f
--- /dev/null
+++ b/pandas/io/formats/_color_data.py
@@ -0,0 +1,155 @@
+# GH37967: Enable the use of CSS named colors, as defined in
+# matplotlib.colors.CSS4_COLORS, when exporting to Excel.
+# This data has been copied here, instead of being imported from matplotlib,
+# not to have ``to_excel`` methods require matplotlib.
+# source: matplotlib._color_data (3.3.3)
+CSS4_COLORS = {
+ "aliceblue": "F0F8FF",
+ "antiquewhite": "FAEBD7",
+ "aqua": "00FFFF",
+ "aquamarine": "7FFFD4",
+ "azure": "F0FFFF",
+ "beige": "F5F5DC",
+ "bisque": "FFE4C4",
+ "black": "000000",
+ "blanchedalmond": "FFEBCD",
+ "blue": "0000FF",
+ "blueviolet": "8A2BE2",
+ "brown": "A52A2A",
+ "burlywood": "DEB887",
+ "cadetblue": "5F9EA0",
+ "chartreuse": "7FFF00",
+ "chocolate": "D2691E",
+ "coral": "FF7F50",
+ "cornflowerblue": "6495ED",
+ "cornsilk": "FFF8DC",
+ "crimson": "DC143C",
+ "cyan": "00FFFF",
+ "darkblue": "00008B",
+ "darkcyan": "008B8B",
+ "darkgoldenrod": "B8860B",
+ "darkgray": "A9A9A9",
+ "darkgreen": "006400",
+ "darkgrey": "A9A9A9",
+ "darkkhaki": "BDB76B",
+ "darkmagenta": "8B008B",
+ "darkolivegreen": "556B2F",
+ "darkorange": "FF8C00",
+ "darkorchid": "9932CC",
+ "darkred": "8B0000",
+ "darksalmon": "E9967A",
+ "darkseagreen": "8FBC8F",
+ "darkslateblue": "483D8B",
+ "darkslategray": "2F4F4F",
+ "darkslategrey": "2F4F4F",
+ "darkturquoise": "00CED1",
+ "darkviolet": "9400D3",
+ "deeppink": "FF1493",
+ "deepskyblue": "00BFFF",
+ "dimgray": "696969",
+ "dimgrey": "696969",
+ "dodgerblue": "1E90FF",
+ "firebrick": "B22222",
+ "floralwhite": "FFFAF0",
+ "forestgreen": "228B22",
+ "fuchsia": "FF00FF",
+ "gainsboro": "DCDCDC",
+ "ghostwhite": "F8F8FF",
+ "gold": "FFD700",
+ "goldenrod": "DAA520",
+ "gray": "808080",
+ "green": "008000",
+ "greenyellow": "ADFF2F",
+ "grey": "808080",
+ "honeydew": "F0FFF0",
+ "hotpink": "FF69B4",
+ "indianred": "CD5C5C",
+ "indigo": "4B0082",
+ "ivory": "FFFFF0",
+ "khaki": "F0E68C",
+ "lavender": "E6E6FA",
+ "lavenderblush": "FFF0F5",
+ "lawngreen": "7CFC00",
+ "lemonchiffon": "FFFACD",
+ "lightblue": "ADD8E6",
+ "lightcoral": "F08080",
+ "lightcyan": "E0FFFF",
+ "lightgoldenrodyellow": "FAFAD2",
+ "lightgray": "D3D3D3",
+ "lightgreen": "90EE90",
+ "lightgrey": "D3D3D3",
+ "lightpink": "FFB6C1",
+ "lightsalmon": "FFA07A",
+ "lightseagreen": "20B2AA",
+ "lightskyblue": "87CEFA",
+ "lightslategray": "778899",
+ "lightslategrey": "778899",
+ "lightsteelblue": "B0C4DE",
+ "lightyellow": "FFFFE0",
+ "lime": "00FF00",
+ "limegreen": "32CD32",
+ "linen": "FAF0E6",
+ "magenta": "FF00FF",
+ "maroon": "800000",
+ "mediumaquamarine": "66CDAA",
+ "mediumblue": "0000CD",
+ "mediumorchid": "BA55D3",
+ "mediumpurple": "9370DB",
+ "mediumseagreen": "3CB371",
+ "mediumslateblue": "7B68EE",
+ "mediumspringgreen": "00FA9A",
+ "mediumturquoise": "48D1CC",
+ "mediumvioletred": "C71585",
+ "midnightblue": "191970",
+ "mintcream": "F5FFFA",
+ "mistyrose": "FFE4E1",
+ "moccasin": "FFE4B5",
+ "navajowhite": "FFDEAD",
+ "navy": "000080",
+ "oldlace": "FDF5E6",
+ "olive": "808000",
+ "olivedrab": "6B8E23",
+ "orange": "FFA500",
+ "orangered": "FF4500",
+ "orchid": "DA70D6",
+ "palegoldenrod": "EEE8AA",
+ "palegreen": "98FB98",
+ "paleturquoise": "AFEEEE",
+ "palevioletred": "DB7093",
+ "papayawhip": "FFEFD5",
+ "peachpuff": "FFDAB9",
+ "peru": "CD853F",
+ "pink": "FFC0CB",
+ "plum": "DDA0DD",
+ "powderblue": "B0E0E6",
+ "purple": "800080",
+ "rebeccapurple": "663399",
+ "red": "FF0000",
+ "rosybrown": "BC8F8F",
+ "royalblue": "4169E1",
+ "saddlebrown": "8B4513",
+ "salmon": "FA8072",
+ "sandybrown": "F4A460",
+ "seagreen": "2E8B57",
+ "seashell": "FFF5EE",
+ "sienna": "A0522D",
+ "silver": "C0C0C0",
+ "skyblue": "87CEEB",
+ "slateblue": "6A5ACD",
+ "slategray": "708090",
+ "slategrey": "708090",
+ "snow": "FFFAFA",
+ "springgreen": "00FF7F",
+ "steelblue": "4682B4",
+ "tan": "D2B48C",
+ "teal": "008080",
+ "thistle": "D8BFD8",
+ "tomato": "FF6347",
+ "turquoise": "40E0D0",
+ "violet": "EE82EE",
+ "wheat": "F5DEB3",
+ "white": "FFFFFF",
+ "whitesmoke": "F5F5F5",
+ "yellow": "FFFF00",
+ "yellowgreen": "9ACD32",
+}
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index be8f2de1d53fb..0cad67169feff 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -21,6 +21,7 @@
from pandas.core import generic
import pandas.core.common as com
+from pandas.io.formats._color_data import CSS4_COLORS
from pandas.io.formats.css import CSSResolver, CSSWarning
from pandas.io.formats.format import get_level_lengths
from pandas.io.formats.printing import pprint_thing
@@ -65,28 +66,7 @@ class CSSToExcelConverter:
CSS processed by :meth:`__call__`.
"""
- NAMED_COLORS = {
- "maroon": "800000",
- "brown": "A52A2A",
- "red": "FF0000",
- "pink": "FFC0CB",
- "orange": "FFA500",
- "yellow": "FFFF00",
- "olive": "808000",
- "green": "008000",
- "purple": "800080",
- "fuchsia": "FF00FF",
- "lime": "00FF00",
- "teal": "008080",
- "aqua": "00FFFF",
- "blue": "0000FF",
- "navy": "000080",
- "black": "000000",
- "gray": "808080",
- "grey": "808080",
- "silver": "C0C0C0",
- "white": "FFFFFF",
- }
+ NAMED_COLORS = CSS4_COLORS
VERTICAL_MAP = {
"top": "top",
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index db34b882a3c35..d0b821a3679bb 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -1305,7 +1305,7 @@ def _format(x):
if not is_float_type[i] and leading_space:
fmt_values.append(f" {_format(v)}")
elif is_float_type[i]:
- fmt_values.append(float_format(v))
+ fmt_values.append(_trim_zeros_single_float(float_format(v)))
else:
if leading_space is False:
# False specifically, so that the default is
@@ -1315,8 +1315,6 @@ def _format(x):
tpl = " {v}"
fmt_values.append(tpl.format(v=_format(v)))
- fmt_values = _trim_zeros_float(str_floats=fmt_values, decimal=".")
-
return fmt_values
@@ -1832,11 +1830,25 @@ def _trim_zeros_complex(str_complexes: np.ndarray, decimal: str = ".") -> List[s
return padded
+def _trim_zeros_single_float(str_float: str) -> str:
+ """
+ Trims trailing zeros after a decimal point,
+ leaving just one if necessary.
+ """
+ str_float = str_float.rstrip("0")
+ if str_float.endswith("."):
+ str_float += "0"
+
+ return str_float
+
+
def _trim_zeros_float(
str_floats: Union[np.ndarray, List[str]], decimal: str = "."
) -> List[str]:
"""
- Trims zeros, leaving just one before the decimal points if need be.
+ Trims the maximum number of trailing zeros equally from
+ all numbers containing decimals, leaving just one if
+ necessary.
"""
trimmed = str_floats
number_regex = re.compile(fr"^\s*[\+-]?[0-9]+\{decimal}[0-9]*$")
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 4557c10927a15..6ed31f38893dc 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -389,7 +389,7 @@ def format_attr(pair):
rowspan = idx_lengths.get((c, r), 0)
if rowspan > 1:
es["attributes"] = [
- format_attr({"key": "rowspan", "value": rowspan})
+ format_attr({"key": "rowspan", "value": f'"{rowspan}"'})
]
row_es.append(es)
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index da085d0d0eb2f..e1ac7b1b02f21 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -630,7 +630,7 @@ def _preprocess_data(self, data):
If self.chunksize, we prepare the data for the `__next__` method.
Otherwise, we read it into memory for the `read` method.
"""
- if hasattr(data, "read") and (not self.chunksize or not self.nrows):
+ if hasattr(data, "read") and not (self.chunksize or self.nrows):
data = data.read()
self.close()
if not hasattr(data, "read") and (self.chunksize or self.nrows):
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 5b623c360c3ef..fcbf7ec3897fc 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -74,7 +74,7 @@
from pandas.core.series import Series
from pandas.core.tools import datetimes as tools
-from pandas.io.common import IOHandles, get_handle, stringify_path, validate_header_arg
+from pandas.io.common import IOHandles, get_handle, validate_header_arg
from pandas.io.date_converters import generic_parser
# BOM character (byte order mark)
@@ -774,7 +774,7 @@ class TextFileReader(abc.Iterator):
def __init__(self, f, engine=None, **kwds):
- self.f = stringify_path(f)
+ self.f = f
if engine is not None:
engine_specified = True
@@ -859,14 +859,14 @@ def _get_options_with_defaults(self, engine):
def _check_file_or_buffer(self, f, engine):
# see gh-16530
- if is_file_like(f):
+ if is_file_like(f) and engine != "c" and not hasattr(f, "__next__"):
# The C engine doesn't need the file-like to have the "__next__"
# attribute. However, the Python engine explicitly calls
# "__next__(...)" when iterating through such an object, meaning it
# needs to have that attribute
- if engine != "c" and not hasattr(f, "__next__"):
- msg = "The 'python' engine cannot iterate through this file buffer."
- raise ValueError(msg)
+ raise ValueError(
+ "The 'python' engine cannot iterate through this file buffer."
+ )
def _clean_options(self, options, engine):
result = options.copy()
@@ -1689,9 +1689,8 @@ def _convert_to_ndarrays(
values, set(col_na_values) | col_na_fvalues, try_num_bool=False
)
else:
- is_str_or_ea_dtype = is_string_dtype(
- cast_type
- ) or is_extension_array_dtype(cast_type)
+ is_ea = is_extension_array_dtype(cast_type)
+ is_str_or_ea_dtype = is_ea or is_string_dtype(cast_type)
# skip inference if specified dtype is object
# or casting to an EA
try_num_bool = not (cast_type and is_str_or_ea_dtype)
@@ -1706,16 +1705,15 @@ def _convert_to_ndarrays(
not is_dtype_equal(cvals, cast_type)
or is_extension_array_dtype(cast_type)
):
- try:
- if (
- is_bool_dtype(cast_type)
- and not is_categorical_dtype(cast_type)
- and na_count > 0
- ):
- raise ValueError(f"Bool column has NA values in column {c}")
- except (AttributeError, TypeError):
- # invalid input to is_bool_dtype
- pass
+ if not is_ea and na_count > 0:
+ try:
+ if is_bool_dtype(cast_type):
+ raise ValueError(
+ f"Bool column has NA values in column {c}"
+ )
+ except (AttributeError, TypeError):
+ # invalid input to is_bool_dtype
+ pass
cvals = self._cast_types(cvals, cast_type, c)
result[c] = cvals
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 5678133d5a706..02b06b164a2a1 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -1159,9 +1159,7 @@ def run_transaction(self):
def execute(self, *args, **kwargs):
"""Simple passthrough to SQLAlchemy connectable"""
- return self.connectable.execution_options(no_parameters=True).execute(
- *args, **kwargs
- )
+ return self.connectable.execution_options().execute(*args, **kwargs)
def read_table(
self,
diff --git a/pandas/tests/arrays/masked/test_arrow_compat.py b/pandas/tests/arrays/masked/test_arrow_compat.py
index ca6fb1cf9dca0..8bb32dec2cc0e 100644
--- a/pandas/tests/arrays/masked/test_arrow_compat.py
+++ b/pandas/tests/arrays/masked/test_arrow_compat.py
@@ -52,3 +52,15 @@ def test_arrow_from_arrow_uint():
expected = pd.array([1, 2, 3, 4, None], dtype="UInt32")
tm.assert_extension_array_equal(result, expected)
+
+
+@td.skip_if_no("pyarrow", min_version="0.16.0")
+def test_arrow_sliced():
+ # https://github.com/pandas-dev/pandas/issues/38525
+ import pyarrow as pa
+
+ df = pd.DataFrame({"a": pd.array([0, None, 2, 3, None], dtype="Int64")})
+ table = pa.table(df)
+ result = table.slice(2, None).to_pandas()
+ expected = df.iloc[2:].reset_index(drop=True)
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py
index ce6737db44195..128f505402eff 100644
--- a/pandas/tests/dtypes/test_common.py
+++ b/pandas/tests/dtypes/test_common.py
@@ -545,6 +545,7 @@ def test_is_bool_dtype():
assert not com.is_bool_dtype(pd.Series([1, 2]))
assert not com.is_bool_dtype(np.array(["a", "b"]))
assert not com.is_bool_dtype(pd.Index(["a", "b"]))
+ assert not com.is_bool_dtype("Int64")
assert com.is_bool_dtype(bool)
assert com.is_bool_dtype(np.bool_)
@@ -553,6 +554,12 @@ def test_is_bool_dtype():
assert com.is_bool_dtype(pd.BooleanDtype())
assert com.is_bool_dtype(pd.array([True, False, None], dtype="boolean"))
+ assert com.is_bool_dtype("boolean")
+
+
+def test_is_bool_dtype_numpy_error():
+ # GH39010
+ assert not com.is_bool_dtype("0 - Name")
@pytest.mark.filterwarnings("ignore:'is_extension_type' is deprecated:FutureWarning")
diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py
index 922b3b94c16c1..b731859a761a4 100644
--- a/pandas/tests/extension/arrow/test_bool.py
+++ b/pandas/tests/extension/arrow/test_bool.py
@@ -51,8 +51,8 @@ def test_view(self, data):
data.view()
@pytest.mark.xfail(raises=AssertionError, reason="Not implemented yet")
- def test_contains(self, data, data_missing, nulls_fixture):
- super().test_contains(data, data_missing, nulls_fixture)
+ def test_contains(self, data, data_missing):
+ super().test_contains(data, data_missing)
class TestConstructors(BaseArrowTests, base.BaseConstructorsTests):
diff --git a/pandas/tests/extension/base/interface.py b/pandas/tests/extension/base/interface.py
index d7997310dde3d..6a4ff68b4580f 100644
--- a/pandas/tests/extension/base/interface.py
+++ b/pandas/tests/extension/base/interface.py
@@ -29,7 +29,7 @@ def test_can_hold_na_valid(self, data):
# GH-20761
assert data._can_hold_na is True
- def test_contains(self, data, data_missing, nulls_fixture):
+ def test_contains(self, data, data_missing):
# GH-37867
# Tests for membership checks. Membership checks for nan-likes is tricky and
# the settled on rule is: `nan_like in arr` is True if nan_like is
@@ -47,10 +47,12 @@ def test_contains(self, data, data_missing, nulls_fixture):
assert na_value in data_missing
assert na_value not in data
- if nulls_fixture is not na_value:
- # the data can never contain other nan-likes than na_value
- assert nulls_fixture not in data
- assert nulls_fixture not in data_missing
+ # the data can never contain other nan-likes than na_value
+ for na_value_obj in tm.NULL_OBJECTS:
+ if na_value_obj is na_value:
+ continue
+ assert na_value_obj not in data
+ assert na_value_obj not in data_missing
def test_memory_usage(self, data):
s = pd.Series(data)
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index d03a9ab6b2588..4a0fb8f81ed56 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -87,7 +87,7 @@ def test_memory_usage(self, data):
# Is this deliberate?
super().test_memory_usage(data)
- def test_contains(self, data, data_missing, nulls_fixture):
+ def test_contains(self, data, data_missing):
# GH-37867
# na value handling in Categorical.__contains__ is deprecated.
# See base.BaseInterFaceTests.test_contains for more details.
@@ -105,9 +105,11 @@ def test_contains(self, data, data_missing, nulls_fixture):
assert na_value not in data
# Categoricals can contain other nan-likes than na_value
- if nulls_fixture is not na_value:
- assert nulls_fixture not in data
- assert nulls_fixture in data_missing # this line differs from super method
+ for na_value_obj in tm.NULL_OBJECTS:
+ if na_value_obj is na_value:
+ continue
+ assert na_value_obj not in data
+ assert na_value_obj in data_missing # this line differs from super method
class TestConstructors(base.BaseConstructorsTests):
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 884cb6c20b77e..cedef4784e4a1 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -1,6 +1,7 @@
import numpy as np
import pytest
+from pandas.core.dtypes.base import registry as ea_registry
from pandas.core.dtypes.dtypes import DatetimeTZDtype, IntervalDtype, PeriodDtype
from pandas import (
@@ -197,6 +198,25 @@ def test_setitem_extension_types(self, obj, dtype):
tm.assert_frame_equal(df, expected)
+ @pytest.mark.parametrize(
+ "ea_name",
+ [
+ dtype.name
+ for dtype in ea_registry.dtypes
+ # property would require instantiation
+ if not isinstance(dtype.name, property)
+ ]
+ # mypy doesn't allow adding lists of different types
+ # https://github.com/python/mypy/issues/5492
+ + ["datetime64[ns, UTC]", "period[D]"], # type: ignore[list-item]
+ )
+ def test_setitem_with_ea_name(self, ea_name):
+ # GH 38386
+ result = DataFrame([0])
+ result[ea_name] = [1]
+ expected = DataFrame({0: [0], ea_name: [1]})
+ tm.assert_frame_equal(result, expected)
+
def test_setitem_dt64_ndarray_with_NaT_and_diff_time_units(self):
# GH#7492
data_ns = np.array([1, "nat"], dtype="datetime64[ns]")
@@ -336,6 +356,13 @@ def test_setitem_listlike_views(self):
expected = Series([100, 2, 3], name="a")
tm.assert_series_equal(ser, expected)
+ def test_setitem_string_column_numpy_dtype_raising(self):
+ # GH#39010
+ df = DataFrame([[1, 2], [3, 4]])
+ df["0 - Name"] = [5, 6]
+ expected = DataFrame([[1, 2, 5], [3, 4, 6]], columns=[0, 1, "0 - Name"])
+ tm.assert_frame_equal(df, expected)
+
class TestDataFrameSetItemSlicing:
def test_setitem_slice_position(self):
diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py
index 2e21ce8ec2256..40b3f1e89c015 100644
--- a/pandas/tests/frame/methods/test_shift.py
+++ b/pandas/tests/frame/methods/test_shift.py
@@ -2,7 +2,7 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Series, date_range, offsets
+from pandas import CategoricalIndex, DataFrame, Index, Series, date_range, offsets
import pandas._testing as tm
@@ -292,3 +292,25 @@ def test_shift_dt64values_int_fill_deprecated(self):
expected = DataFrame({"A": [pd.Timestamp(0), pd.Timestamp(0)], "B": df2["A"]})
tm.assert_frame_equal(result, expected)
+
+ def test_shift_axis1_categorical_columns(self):
+ # GH#38434
+ ci = CategoricalIndex(["a", "b", "c"])
+ df = DataFrame(
+ {"a": [1, 3], "b": [2, 4], "c": [5, 6]}, index=ci[:-1], columns=ci
+ )
+ result = df.shift(axis=1)
+
+ expected = DataFrame(
+ {"a": [np.nan, np.nan], "b": [1, 3], "c": [2, 4]}, index=ci[:-1], columns=ci
+ )
+ tm.assert_frame_equal(result, expected)
+
+ # periods != 1
+ result = df.shift(2, axis=1)
+ expected = DataFrame(
+ {"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 3]},
+ index=ci[:-1],
+ columns=ci,
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py
index 157c8687808b3..a7e2fa760b7e4 100644
--- a/pandas/tests/frame/test_api.py
+++ b/pandas/tests/frame/test_api.py
@@ -1,7 +1,6 @@
from copy import deepcopy
import inspect
import pydoc
-import warnings
import numpy as np
import pytest
@@ -330,19 +329,17 @@ def test_set_flags(self, allows_duplicate_labels, frame_or_series):
result.iloc[key] = 10
assert obj.iloc[key] == 0
- @skip_if_no("jinja2")
def test_constructor_expanddim_lookup(self):
# GH#33628 accessing _constructor_expanddim should not
# raise NotImplementedError
df = DataFrame()
- with warnings.catch_warnings(record=True) as wrn:
- # _AXIS_NUMBERS, _AXIS_NAMES lookups
- inspect.getmembers(df)
-
- # some versions give FutureWarning, others DeprecationWarning
- assert len(wrn)
- assert any(x.category in [FutureWarning, DeprecationWarning] for x in wrn)
-
with pytest.raises(NotImplementedError, match="Not supported for DataFrames!"):
df._constructor_expanddim(np.arange(27).reshape(3, 3, 3))
+
+ @skip_if_no("jinja2")
+ def test_inspect_getmembers(self):
+ # GH38740
+ df = DataFrame()
+ with tm.assert_produces_warning(None):
+ inspect.getmembers(df)
diff --git a/pandas/tests/frame/test_logical_ops.py b/pandas/tests/frame/test_logical_ops.py
index efabc666993ee..dca12c632a418 100644
--- a/pandas/tests/frame/test_logical_ops.py
+++ b/pandas/tests/frame/test_logical_ops.py
@@ -4,7 +4,7 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import CategoricalIndex, DataFrame, Interval, Series, isnull
import pandas._testing as tm
@@ -162,3 +162,24 @@ def test_logical_with_nas(self):
result = d["a"].fillna(False, downcast=False) | d["b"]
expected = Series([True, True])
tm.assert_series_equal(result, expected)
+
+ def test_logical_ops_categorical_columns(self):
+ # GH#38367
+ intervals = [Interval(1, 2), Interval(3, 4)]
+ data = DataFrame(
+ [[1, np.nan], [2, np.nan]],
+ columns=CategoricalIndex(
+ intervals, categories=intervals + [Interval(5, 6)]
+ ),
+ )
+ mask = DataFrame(
+ [[False, False], [False, False]], columns=data.columns, dtype=bool
+ )
+ result = mask | isnull(data)
+ expected = DataFrame(
+ [[False, True], [False, True]],
+ columns=CategoricalIndex(
+ intervals, categories=intervals + [Interval(5, 6)]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py
index d33d91f2cefca..d843d4b0e9504 100644
--- a/pandas/tests/frame/test_reductions.py
+++ b/pandas/tests/frame/test_reductions.py
@@ -1091,9 +1091,13 @@ def test_any_all_bool_only(self):
(np.all, {"A": Series([0, 1], dtype=int)}, False),
(np.any, {"A": Series([0, 1], dtype=int)}, True),
pytest.param(np.all, {"A": Series([0, 1], dtype="M8[ns]")}, False),
+ pytest.param(np.all, {"A": Series([0, 1], dtype="M8[ns, UTC]")}, False),
pytest.param(np.any, {"A": Series([0, 1], dtype="M8[ns]")}, True),
+ pytest.param(np.any, {"A": Series([0, 1], dtype="M8[ns, UTC]")}, True),
pytest.param(np.all, {"A": Series([1, 2], dtype="M8[ns]")}, True),
+ pytest.param(np.all, {"A": Series([1, 2], dtype="M8[ns, UTC]")}, True),
pytest.param(np.any, {"A": Series([1, 2], dtype="M8[ns]")}, True),
+ pytest.param(np.any, {"A": Series([1, 2], dtype="M8[ns, UTC]")}, True),
pytest.param(np.all, {"A": Series([0, 1], dtype="m8[ns]")}, False),
pytest.param(np.any, {"A": Series([0, 1], dtype="m8[ns]")}, True),
pytest.param(np.all, {"A": Series([1, 2], dtype="m8[ns]")}, True),
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py
index 8cf77ca6335f4..f0bc58cbf07bf 100644
--- a/pandas/tests/groupby/test_categorical.py
+++ b/pandas/tests/groupby/test_categorical.py
@@ -1678,3 +1678,23 @@ def test_df_groupby_first_on_categorical_col_grouped_on_2_categoricals(
df_grp = df.groupby(["a", "b"], observed=observed)
result = getattr(df_grp, func)()
tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_categorical_indices_unused_categories():
+ # GH#38642
+ df = DataFrame(
+ {
+ "key": Categorical(["b", "b", "a"], categories=["a", "b", "c"]),
+ "col": range(3),
+ }
+ )
+ grouped = df.groupby("key", sort=False)
+ result = grouped.indices
+ expected = {
+ "b": np.array([0, 1], dtype="int64"),
+ "a": np.array([2], dtype="int64"),
+ "c": np.array([], dtype="int64"),
+ }
+ assert result.keys() == expected.keys()
+ for key in result.keys():
+ tm.assert_numpy_array_equal(result[key], expected[key])
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 7c179a79513fa..a260aaf6e057d 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -842,6 +842,14 @@ def test_omit_nuisance(df):
grouped.agg(lambda x: x.sum(0, numeric_only=False))
+def test_omit_nuisance_sem(df):
+ # GH 38774 - sem should work with nuisance columns
+ grouped = df.groupby("A")
+ result = grouped.sem()
+ expected = df.loc[:, ["A", "C", "D"]].groupby("A").sem()
+ tm.assert_frame_equal(result, expected)
+
+
def test_omit_nuisance_python_multiple(three_group):
grouped = three_group.groupby(["A", "B"])
@@ -1689,64 +1697,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/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index f750b3667cec2..e8bd0cfea844d 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -535,9 +535,7 @@ def test_string_slice(self):
df["2011"]
with pytest.raises(KeyError, match="'2011'"):
- with tm.assert_produces_warning(FutureWarning):
- # This does an is_all_dates check
- df.loc["2011", 0]
+ df.loc["2011", 0]
df = DataFrame()
assert not df.index._is_all_dates
diff --git a/pandas/tests/io/__init__.py b/pandas/tests/io/__init__.py
index c5e867f45b92d..39474dedba78c 100644
--- a/pandas/tests/io/__init__.py
+++ b/pandas/tests/io/__init__.py
@@ -14,4 +14,8 @@
r"Use 'tree.iter\(\)' or 'list\(tree.iter\(\)\)' instead."
":PendingDeprecationWarning"
),
+ # GH 26552
+ pytest.mark.filterwarnings(
+ "ignore:As the xlwt package is no longer maintained:FutureWarning"
+ ),
]
diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py
index bcc666a88e3be..5d4705dbe7d77 100644
--- a/pandas/tests/io/conftest.py
+++ b/pandas/tests/io/conftest.py
@@ -50,8 +50,7 @@ def s3_base(worker_id):
pytest.importorskip("s3fs")
pytest.importorskip("boto3")
requests = pytest.importorskip("requests")
- # GH 38090: Suppress http logs in tests by moto_server
- logging.getLogger("werkzeug").disabled = True
+ logging.getLogger("requests").disabled = True
with tm.ensure_safe_environment_variables():
# temporary workaround as moto fails for botocore >= 1.11 otherwise,
@@ -71,7 +70,9 @@ def s3_base(worker_id):
# pipe to null to avoid logging in terminal
proc = subprocess.Popen(
- shlex.split(f"moto_server s3 -p {endpoint_port}"), stdout=subprocess.DEVNULL
+ shlex.split(f"moto_server s3 -p {endpoint_port}"),
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
)
timeout = 5
diff --git a/pandas/tests/io/excel/__init__.py b/pandas/tests/io/excel/__init__.py
index 384f1006c44df..b7ceb28573484 100644
--- a/pandas/tests/io/excel/__init__.py
+++ b/pandas/tests/io/excel/__init__.py
@@ -1,5 +1,9 @@
+from distutils.version import LooseVersion
+
import pytest
+from pandas.compat._optional import import_optional_dependency
+
pytestmark = [
pytest.mark.filterwarnings(
# Looks like tree.getiterator is deprecated in favor of tree.iter
@@ -13,4 +17,19 @@
pytest.mark.filterwarnings(
"ignore:As the xlwt package is no longer maintained:FutureWarning"
),
+ # GH 38571
+ pytest.mark.filterwarnings(
+ "ignore:.*In xlrd >= 2.0, only the xls format is supported:FutureWarning"
+ ),
]
+
+
+if (
+ import_optional_dependency("xlrd", raise_on_missing=False, on_version="ignore")
+ is None
+):
+ xlrd_version = None
+else:
+ import xlrd
+
+ xlrd_version = LooseVersion(xlrd.__version__)
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 98a55ae39bd77..8b1a96f694e71 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -11,6 +11,7 @@
import pandas as pd
from pandas import DataFrame, Index, MultiIndex, Series
import pandas._testing as tm
+from pandas.tests.io.excel import xlrd_version
read_ext_params = [".xls", ".xlsx", ".xlsm", ".xlsb", ".ods"]
engine_params = [
@@ -57,6 +58,13 @@ def _is_valid_engine_ext_pair(engine, read_ext: str) -> bool:
return False
if read_ext == ".xlsb" and engine != "pyxlsb":
return False
+ if (
+ engine == "xlrd"
+ and xlrd_version is not None
+ and xlrd_version >= "2"
+ and read_ext != ".xls"
+ ):
+ return False
return True
@@ -614,6 +622,19 @@ def test_bad_engine_raises(self, read_ext):
with pytest.raises(ValueError, match="Unknown engine: foo"):
pd.read_excel("", engine=bad_engine)
+ def test_missing_file_raises(self, read_ext):
+ bad_file = f"foo{read_ext}"
+ # CI tests with zh_CN.utf8, translates to "No such file or directory"
+ with pytest.raises(
+ FileNotFoundError, match=r"(No such file or directory|没有那个文件或目录)"
+ ):
+ pd.read_excel(bad_file)
+
+ def test_corrupt_bytes_raises(self, read_ext, engine):
+ bad_stream = b"foo"
+ with pytest.raises(ValueError, match="File is not a recognized excel file"):
+ pd.read_excel(bad_stream)
+
@tm.network
def test_read_from_http_url(self, read_ext):
url = (
@@ -636,6 +657,22 @@ def test_read_from_s3_url(self, read_ext, s3_resource, s3so):
local_table = pd.read_excel("test1" + read_ext)
tm.assert_frame_equal(url_table, local_table)
+ def test_read_from_s3_object(self, read_ext, s3_resource, s3so):
+ # GH 38788
+ # Bucket "pandas-test" created in tests/io/conftest.py
+ with open("test1" + read_ext, "rb") as f:
+ s3_resource.Bucket("pandas-test").put_object(Key="test1" + read_ext, Body=f)
+
+ import s3fs
+
+ s3 = s3fs.S3FileSystem(**s3so)
+
+ with s3.open("s3://pandas-test/test1" + read_ext) as f:
+ url_table = pd.read_excel(f)
+
+ local_table = pd.read_excel("test1" + read_ext)
+ tm.assert_frame_equal(url_table, local_table)
+
@pytest.mark.slow
def test_read_from_file_url(self, read_ext, datapath):
@@ -1158,6 +1195,19 @@ def test_excel_read_binary(self, engine, read_ext):
actual = pd.read_excel(data, engine=engine)
tm.assert_frame_equal(expected, actual)
+ def test_excel_read_binary_via_read_excel(self, read_ext, engine):
+ # GH 38424
+ if read_ext == ".xlsb" and engine == "pyxlsb":
+ pytest.xfail("GH 38667 - should default to pyxlsb but doesn't")
+ with open("test1" + read_ext, "rb") as f:
+ result = pd.read_excel(f)
+ expected = pd.read_excel("test1" + read_ext, engine=engine)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.skipif(
+ xlrd_version is not None and xlrd_version >= "2",
+ reason="xlrd no longer supports xlsx",
+ )
def test_excel_high_surrogate(self, engine):
# GH 23809
expected = DataFrame(["\udc88"], columns=["Column1"])
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index 80ebeb4c03d89..e67769bc774b0 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -492,7 +492,7 @@ def test_float_types(self, np_type, path):
@pytest.mark.parametrize("np_type", [np.bool8, np.bool_])
def test_bool_types(self, np_type, path):
- # Test np.bool values read come back as float.
+ # Test np.bool8 and np.bool_ values read come back as float.
df = DataFrame([1, 0, True, False], dtype=np_type)
df.to_excel(path, "test1")
@@ -1195,9 +1195,9 @@ def test_datetimes(self, path):
write_frame = DataFrame({"A": datetimes})
write_frame.to_excel(path, "Sheet1")
- # GH 35029 - Default changed to openpyxl, but test is for odf/xlrd
- engine = "odf" if path.endswith("ods") else "xlrd"
- read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0, engine=engine)
+ if path.endswith("xlsx") or path.endswith("xlsm"):
+ pytest.skip("Defaults to openpyxl and fails - GH #38644")
+ read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0)
tm.assert_series_equal(write_frame["A"], read_frame["A"])
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
index f2fbcbc2e2f04..2a1114a9570f0 100644
--- a/pandas/tests/io/excel/test_xlrd.py
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -4,6 +4,7 @@
import pandas as pd
import pandas._testing as tm
+from pandas.tests.io.excel import xlrd_version
from pandas.io.excel import ExcelFile
@@ -17,6 +18,8 @@ def skip_ods_and_xlsb_files(read_ext):
pytest.skip("Not valid for xlrd")
if read_ext == ".xlsb":
pytest.skip("Not valid for xlrd")
+ if read_ext in (".xlsx", ".xlsm") and xlrd_version >= "2":
+ pytest.skip("Not valid for xlrd >= 2.0")
def test_read_xlrd_book(read_ext, frame):
@@ -66,7 +69,7 @@ def test_excel_file_warning_with_xlsx_file(datapath):
pd.read_excel(path, "Sheet1", engine=None)
-def test_read_excel_warning_with_xlsx_file(tmpdir, datapath):
+def test_read_excel_warning_with_xlsx_file(datapath):
# GH 29375
path = datapath("io", "data", "excel", "test1.xlsx")
has_openpyxl = (
@@ -76,12 +79,19 @@ def test_read_excel_warning_with_xlsx_file(tmpdir, datapath):
is not None
)
if not has_openpyxl:
- with tm.assert_produces_warning(
- FutureWarning,
- raise_on_extra_warnings=False,
- match="The xlrd engine is no longer maintained",
- ):
- pd.read_excel(path, "Sheet1", engine=None)
+ if xlrd_version >= "2":
+ with pytest.raises(
+ ValueError,
+ match="Your version of xlrd is ",
+ ):
+ pd.read_excel(path, "Sheet1", engine=None)
+ else:
+ with tm.assert_produces_warning(
+ FutureWarning,
+ raise_on_extra_warnings=False,
+ match="The xlrd engine is no longer maintained",
+ ):
+ pd.read_excel(path, "Sheet1", engine=None)
else:
with tm.assert_produces_warning(None):
pd.read_excel(path, "Sheet1", engine=None)
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index fe85849c6dcca..b0b07045a9156 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -2002,6 +2002,25 @@ def test_float_trim_zeros(self):
assert ("+10" in line) or skip
skip = False
+ @pytest.mark.parametrize(
+ "data, expected",
+ [
+ (["3.50"], "0 3.50\ndtype: object"),
+ ([1.20, "1.00"], "0 1.2\n1 1.00\ndtype: object"),
+ ([np.nan], "0 NaN\ndtype: float64"),
+ ([None], "0 None\ndtype: object"),
+ (["3.50", np.nan], "0 3.50\n1 NaN\ndtype: object"),
+ ([3.50, np.nan], "0 3.5\n1 NaN\ndtype: float64"),
+ ([3.50, np.nan, "3.50"], "0 3.5\n1 NaN\n2 3.50\ndtype: object"),
+ ([3.50, None, "3.50"], "0 3.5\n1 None\n2 3.50\ndtype: object"),
+ ],
+ )
+ def test_repr_str_float_truncation(self, data, expected):
+ # GH#38708
+ series = Series(data)
+ result = repr(series)
+ assert result == expected
+
def test_dict_entries(self):
df = DataFrame({"A": [{"a": 1, "b": 2}]})
diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py
index 64fe8a7730ae2..0bb422658df25 100644
--- a/pandas/tests/io/formats/test_style.py
+++ b/pandas/tests/io/formats/test_style.py
@@ -1411,7 +1411,7 @@ def test_mi_sparse(self):
"display_value": "a",
"is_visible": True,
"type": "th",
- "attributes": ["rowspan=2"],
+ "attributes": ['rowspan="2"'],
"class": "row_heading level0 row0",
"id": "level0_row0",
}
@@ -1740,6 +1740,15 @@ def test_colspan_w3(self):
s = Styler(df, uuid="_", cell_ids=False)
assert '<th class="col_heading level0 col0" colspan="2">l0</th>' in s.render()
+ def test_rowspan_w3(self):
+ # GH 38533
+ df = DataFrame(data=[[1, 2]], index=[["l0", "l0"], ["l1a", "l1b"]])
+ s = Styler(df, uuid="_", cell_ids=False)
+ assert (
+ '<th id="T___level0_row0" class="row_heading '
+ 'level0 row0" rowspan="2">l0</th>' in s.render()
+ )
+
@pytest.mark.parametrize("len_", [1, 5, 32, 33, 100])
def test_uuid_len(self, len_):
# GH 36345
diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py
index a9673ded7c377..6416cb93c7ff5 100644
--- a/pandas/tests/io/formats/test_to_csv.py
+++ b/pandas/tests/io/formats/test_to_csv.py
@@ -640,3 +640,25 @@ def test_to_csv_encoding_binary_handle(self, mode):
handle.seek(0)
assert handle.read().startswith(b'\xef\xbb\xbf""')
+
+
+def test_to_csv_iterative_compression_name(compression):
+ # GH 38714
+ df = tm.makeDataFrame()
+ with tm.ensure_clean() as path:
+ df.to_csv(path, compression=compression, chunksize=1)
+ tm.assert_frame_equal(
+ pd.read_csv(path, compression=compression, index_col=0), df
+ )
+
+
+def test_to_csv_iterative_compression_buffer(compression):
+ # GH 38714
+ df = tm.makeDataFrame()
+ with io.BytesIO() as buffer:
+ df.to_csv(buffer, compression=compression, chunksize=1)
+ buffer.seek(0)
+ tm.assert_frame_equal(
+ pd.read_csv(buffer, compression=compression, index_col=0), df
+ )
+ assert not buffer.closed
diff --git a/pandas/tests/io/formats/test_to_excel.py b/pandas/tests/io/formats/test_to_excel.py
index 4f1af132204bb..968ad63eaceef 100644
--- a/pandas/tests/io/formats/test_to_excel.py
+++ b/pandas/tests/io/formats/test_to_excel.py
@@ -2,9 +2,12 @@
ExcelFormatter is tested implicitly in pandas/tests/io/excel
"""
+import string
import pytest
+import pandas.util._test_decorators as td
+
import pandas._testing as tm
from pandas.io.formats.css import CSSWarning
@@ -313,3 +316,18 @@ def test_css_to_excel_bad_colors(input_color):
with tm.assert_produces_warning(CSSWarning):
convert = CSSToExcelConverter()
assert expected == convert(css)
+
+
+def tests_css_named_colors_valid():
+ upper_hexs = set(map(str.upper, string.hexdigits))
+ for color in CSSToExcelConverter.NAMED_COLORS.values():
+ assert len(color) == 6 and all(c in upper_hexs for c in color)
+
+
+@td.skip_if_no_mpl
+def test_css_named_colors_from_mpl_present():
+ from matplotlib.colors import CSS4_COLORS as mpl_colors
+
+ pd_colors = CSSToExcelConverter.NAMED_COLORS
+ for name, color in mpl_colors.items():
+ assert name in pd_colors and pd_colors[name] == color[1:]
diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py
index 4bbd81ada995b..099d99507e136 100644
--- a/pandas/tests/io/json/test_readlines.py
+++ b/pandas/tests/io/json/test_readlines.py
@@ -252,3 +252,31 @@ def test_readjson_lines_chunks_fileurl(datapath):
with pd.read_json(file_url, lines=True, chunksize=1) as url_reader:
for index, chuck in enumerate(url_reader):
tm.assert_frame_equal(chuck, df_list_expected[index])
+
+
+def test_chunksize_is_incremental():
+ # See https://github.com/pandas-dev/pandas/issues/34548
+ jsonl = (
+ """{"a": 1, "b": 2}
+ {"a": 3, "b": 4}
+ {"a": 5, "b": 6}
+ {"a": 7, "b": 8}\n"""
+ * 1000
+ )
+
+ class MyReader:
+ def __init__(self, contents):
+ self.read_count = 0
+ self.stringio = StringIO(contents)
+
+ def read(self, *args):
+ self.read_count += 1
+ return self.stringio.read(*args)
+
+ def __iter__(self):
+ self.read_count += 1
+ return iter(self.stringio)
+
+ reader = MyReader(jsonl)
+ assert len(list(pd.read_json(reader, lines=True, chunksize=100))) > 1
+ assert reader.read_count > 10
diff --git a/pandas/tests/io/parser/conftest.py b/pandas/tests/io/parser/conftest.py
index e8893b4c02238..ec098353960d7 100644
--- a/pandas/tests/io/parser/conftest.py
+++ b/pandas/tests/io/parser/conftest.py
@@ -97,6 +97,33 @@ def python_parser_only(request):
return request.param
+def _get_all_parser_float_precision_combinations():
+ """
+ Return all allowable parser and float precision
+ combinations and corresponding ids.
+ """
+ params = []
+ ids = []
+ for parser, parser_id in zip(_all_parsers, _all_parser_ids):
+ for precision in parser.float_precision_choices:
+ params.append((parser, precision))
+ ids.append(f"{parser_id}-{precision}")
+
+ return {"params": params, "ids": ids}
+
+
+@pytest.fixture(
+ params=_get_all_parser_float_precision_combinations()["params"],
+ ids=_get_all_parser_float_precision_combinations()["ids"],
+)
+def all_parsers_all_precisions(request):
+ """
+ Fixture for all allowable combinations of parser
+ and float precision
+ """
+ return request.param
+
+
_utf_values = [8, 16, 32]
_encoding_seps = ["", "-", "_"]
diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py
index c8ed0d75b13a2..d42bd7a004584 100644
--- a/pandas/tests/io/parser/test_common.py
+++ b/pandas/tests/io/parser/test_common.py
@@ -15,6 +15,7 @@
import pytest
from pandas._libs.tslib import Timestamp
+from pandas.compat import is_platform_linux
from pandas.errors import DtypeWarning, EmptyDataError, ParserError
import pandas.util._test_decorators as td
@@ -1258,15 +1259,14 @@ def test_float_parser(all_parsers):
tm.assert_frame_equal(result, expected)
-def test_scientific_no_exponent(all_parsers):
+def test_scientific_no_exponent(all_parsers_all_precisions):
# see gh-12215
df = DataFrame.from_dict({"w": ["2e"], "x": ["3E"], "y": ["42e"], "z": ["632E"]})
data = df.to_csv(index=False)
- parser = all_parsers
+ parser, precision = all_parsers_all_precisions
- for precision in parser.float_precision_choices:
- df_roundtrip = parser.read_csv(StringIO(data), float_precision=precision)
- tm.assert_frame_equal(df_roundtrip, df)
+ df_roundtrip = parser.read_csv(StringIO(data), float_precision=precision)
+ tm.assert_frame_equal(df_roundtrip, df)
@pytest.mark.parametrize("conv", [None, np.int64, np.uint64])
@@ -1350,6 +1350,35 @@ def test_numeric_range_too_wide(all_parsers, exp_data):
tm.assert_frame_equal(result, expected)
+@pytest.mark.parametrize("neg_exp", [-617, -100000, -99999999999999999])
+def test_very_negative_exponent(all_parsers_all_precisions, neg_exp):
+ # GH#38753
+ parser, precision = all_parsers_all_precisions
+ data = f"data\n10E{neg_exp}"
+ result = parser.read_csv(StringIO(data), float_precision=precision)
+ expected = DataFrame({"data": [0.0]})
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("exp", [999999999999999999, -999999999999999999])
+def test_too_many_exponent_digits(all_parsers_all_precisions, exp, request):
+ # GH#38753
+ parser, precision = all_parsers_all_precisions
+ data = f"data\n10E{exp}"
+ result = parser.read_csv(StringIO(data), float_precision=precision)
+ if precision == "round_trip":
+ if exp == 999999999999999999 and is_platform_linux():
+ mark = pytest.mark.xfail(reason="GH38794, on Linux gives object result")
+ request.node.add_marker(mark)
+
+ value = np.inf if exp > 0 else 0.0
+ expected = DataFrame({"data": [value]})
+ else:
+ expected = DataFrame({"data": [f"10E{exp}"]})
+
+ tm.assert_frame_equal(result, expected)
+
+
@pytest.mark.parametrize("iterator", [True, False])
def test_empty_with_nrows_chunksize(all_parsers, iterator):
# see gh-9535
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index b35414724d946..7b3b01aef8244 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -2358,17 +2358,13 @@ def test_series(self, setup_path):
ts = tm.makeTimeSeries()
self._check_roundtrip(ts, tm.assert_series_equal, path=setup_path)
- with tm.assert_produces_warning(FutureWarning):
- # auto-casting object->DatetimeIndex deprecated
- ts2 = Series(ts.index, Index(ts.index, dtype=object))
+ ts2 = Series(ts.index, Index(ts.index, dtype=object))
self._check_roundtrip(ts2, tm.assert_series_equal, path=setup_path)
- with tm.assert_produces_warning(FutureWarning):
- # auto-casting object->DatetimeIndex deprecated
- ts3 = Series(
- ts.values, Index(np.asarray(ts.index, dtype=object), dtype=object)
- )
- self._check_roundtrip(ts3, 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):
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
index c3b21daa0ac04..2ea944d9502b3 100644
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -85,6 +85,13 @@ def test_stringify_path_fspath(self):
result = icom.stringify_path(p)
assert result == "foo/bar.csv"
+ def test_stringify_file_and_path_like(self):
+ # GH 38125: do not stringify file objects that are also path-like
+ fsspec = pytest.importorskip("fsspec")
+ with tm.ensure_clean() as path:
+ with fsspec.open(f"file://{path}", mode="wb") as fsspec_obj:
+ assert fsspec_obj == icom.stringify_path(fsspec_obj)
+
@pytest.mark.parametrize(
"extension,expected",
[
@@ -411,3 +418,11 @@ def test_is_fsspec_url():
assert not icom.is_fsspec_url("random:pandas/somethingelse.com")
assert not icom.is_fsspec_url("/local/path")
assert not icom.is_fsspec_url("relative/local/path")
+
+
+def test_default_errors():
+ # GH 38989
+ with tm.ensure_clean() as path:
+ file = Path(path)
+ file.write_bytes(b"\xe4\na\n1")
+ tm.assert_frame_equal(pd.read_csv(file, skiprows=[0]), pd.DataFrame({"a": [1]}))
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py
index ba8b1a8a0679d..aed1aaedf2fa3 100644
--- a/pandas/tests/io/test_html.py
+++ b/pandas/tests/io/test_html.py
@@ -129,6 +129,7 @@ def test_to_html_compat(self):
res = self.read_html(out, attrs={"class": "dataframe"}, index_col=0)[0]
tm.assert_frame_equal(res, df)
+ @pytest.mark.xfail(reason="Html file was removed")
@tm.network
def test_banklist_url_positional_match(self):
url = "https://www.fdic.gov/bank/individual/failed/banklist.html"
@@ -142,6 +143,7 @@ def test_banklist_url_positional_match(self):
assert_framelist_equal(df1, df2)
+ @pytest.mark.xfail(reason="Html file was removed")
@tm.network
def test_banklist_url(self):
url = "https://www.fdic.gov/bank/individual/failed/banklist.html"
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index fe3ca0d0937b3..a9357ef89de92 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -671,12 +671,7 @@ def test_s3_roundtrip(self, df_compat, s3_resource, pa, s3so):
@pytest.mark.parametrize(
"partition_col",
[
- pytest.param(
- ["A"],
- marks=pytest.mark.xfail(
- PY38, reason="Getting back empty DataFrame", raises=AssertionError
- ),
- ),
+ ["A"],
[],
],
)
@@ -885,7 +880,7 @@ def test_timezone_aware_index(self, pa, timezone_aware_date_list):
# this use-case sets the resolution to 1 minute
check_round_trip(df, pa, check_dtype=False)
- @td.skip_if_no("pyarrow", min_version="0.17")
+ @td.skip_if_no("pyarrow", min_version="1.0.0")
def test_filter_row_groups(self, pa):
# https://github.com/pandas-dev/pandas/issues/26551
df = pd.DataFrame({"a": list(range(0, 3))})
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 0195b61d13798..16d4bc65094f8 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -1125,6 +1125,15 @@ def test_query_by_select_obj(self):
all_names = set(iris_df["Name"])
assert all_names == {"Iris-setosa"}
+ def test_column_with_percentage(self):
+ # GH 37157
+ df = DataFrame({"A": [0, 1, 2], "%_variation": [3, 4, 5]})
+ df.to_sql("test_column_percentage", self.conn, index=False)
+
+ res = sql.read_sql_table("test_column_percentage", self.conn)
+
+ tm.assert_frame_equal(res, df)
+
class _EngineToConnMixin:
"""
@@ -1185,7 +1194,7 @@ def test_sql_open_close(self):
@pytest.mark.skipif(SQLALCHEMY_INSTALLED, reason="SQLAlchemy is installed")
def test_con_string_import_error(self):
- conn = "mysql://root@localhost/pandas_nosetest"
+ conn = "mysql://root@localhost/pandas"
msg = "Using URI string without sqlalchemy installed"
with pytest.raises(ImportError, match=msg):
sql.read_sql("SELECT * FROM iris", conn)
@@ -1922,11 +1931,12 @@ class _TestMySQLAlchemy:
"""
flavor = "mysql"
+ port = 3306
@classmethod
def connect(cls):
return sqlalchemy.create_engine(
- f"mysql+{cls.driver}://root@localhost/pandas_nosetest",
+ f"mysql+{cls.driver}://root@localhost:{cls.port}/pandas",
connect_args=cls.connect_args,
)
@@ -1991,11 +2001,12 @@ class _TestPostgreSQLAlchemy:
"""
flavor = "postgresql"
+ port = 5432
@classmethod
def connect(cls):
return sqlalchemy.create_engine(
- f"postgresql+{cls.driver}://postgres@localhost/pandas_nosetest"
+ f"postgresql+{cls.driver}://postgres:postgres@localhost:{cls.port}/pandas"
)
@classmethod
@@ -2611,7 +2622,7 @@ class TestXMySQL(MySQLMixIn):
@pytest.fixture(autouse=True, scope="class")
def setup_class(cls):
pymysql = pytest.importorskip("pymysql")
- pymysql.connect(host="localhost", user="root", passwd="", db="pandas_nosetest")
+ pymysql.connect(host="localhost", user="root", passwd="", db="pandas")
try:
pymysql.connect(read_default_group="pandas")
except pymysql.ProgrammingError as err:
@@ -2631,7 +2642,7 @@ def setup_class(cls):
@pytest.fixture(autouse=True)
def setup_method(self, request, datapath):
pymysql = pytest.importorskip("pymysql")
- pymysql.connect(host="localhost", user="root", passwd="", db="pandas_nosetest")
+ pymysql.connect(host="localhost", user="root", passwd="", db="pandas")
try:
pymysql.connect(read_default_group="pandas")
except pymysql.ProgrammingError as err:
diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py
index 397a064f6adad..66a4f9598c49b 100644
--- a/pandas/tests/plotting/test_datetimelike.py
+++ b/pandas/tests/plotting/test_datetimelike.py
@@ -277,16 +277,9 @@ def test_irreg_hf(self):
_, ax = self.plt.subplots()
df2 = df.copy()
df2.index = df.index.astype(object)
- with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
- # This warning will be emitted
- # pandas/core/frame.py:3216:
- # FutureWarning: Automatically casting object-dtype Index of datetimes
- # to DatetimeIndex is deprecated and will be removed in a future version.
- # Explicitly cast to DatetimeIndex instead.
- # return klass(values, index=self.index, name=name, fastpath=True)
- df2.plot(ax=ax)
- diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
- assert (np.fabs(diffs[1:] - sec) < 1e-8).all()
+ df2.plot(ax=ax)
+ diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
+ assert (np.fabs(diffs[1:] - sec) < 1e-8).all()
def test_irregular_datetime64_repr_bug(self):
ser = tm.makeTimeSeries()
@@ -997,16 +990,9 @@ def test_irreg_dtypes(self):
# np.datetime64
idx = date_range("1/1/2000", periods=10)
idx = idx[[0, 2, 5, 9]].astype(object)
- with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
- # This warning will be emitted
- # pandas/core/frame.py:3216:
- # FutureWarning: Automatically casting object-dtype Index of datetimes
- # to DatetimeIndex is deprecated and will be removed in a future version.
- # Explicitly cast to DatetimeIndex instead.
- # return klass(values, index=self.index, name=name, fastpath=True)
- df = DataFrame(np.random.randn(len(idx), 3), idx)
- _, ax = self.plt.subplots()
- _check_plot_works(df.plot, ax=ax)
+ df = DataFrame(np.random.randn(len(idx), 3), idx)
+ _, ax = self.plt.subplots()
+ _check_plot_works(df.plot, ax=ax)
def test_time(self):
t = datetime(1, 1, 1, 3, 30, 0)
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index 8c2297699807d..94afa204db891 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -17,6 +17,7 @@
Timedelta,
TimedeltaIndex,
Timestamp,
+ date_range,
isna,
timedelta_range,
to_timedelta,
@@ -923,6 +924,48 @@ def test_any_axis1_bool_only(self):
expected = Series([True, False])
tm.assert_series_equal(result, expected)
+ def test_any_all_datetimelike(self):
+ # GH#38723 these may not be the desired long-term behavior (GH#34479)
+ # but in the interim should be internally consistent
+ dta = date_range("1995-01-02", periods=3)._data
+ ser = Series(dta)
+ df = DataFrame(ser)
+
+ assert dta.all()
+ assert dta.any()
+
+ assert ser.all()
+ assert ser.any()
+
+ assert df.any().all()
+ assert df.all().all()
+
+ dta = dta.tz_localize("UTC")
+ ser = Series(dta)
+ df = DataFrame(ser)
+
+ assert dta.all()
+ assert dta.any()
+
+ assert ser.all()
+ assert ser.any()
+
+ assert df.any().all()
+ assert df.all().all()
+
+ tda = dta - dta[0]
+ ser = Series(tda)
+ df = DataFrame(ser)
+
+ assert tda.any()
+ assert not tda.all()
+
+ assert ser.any()
+ assert not ser.all()
+
+ assert df.any().all()
+ assert not df.all().any()
+
def test_timedelta64_analytics(self):
# index min/max
diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py
index 15dd49f8bf182..da5bb0eb59f70 100644
--- a/pandas/tests/resample/test_resampler_grouper.py
+++ b/pandas/tests/resample/test_resampler_grouper.py
@@ -362,3 +362,39 @@ def test_apply_to_one_column_of_df():
tm.assert_series_equal(result, expected)
result = df.resample("H").apply(lambda group: group["col"].sum())
tm.assert_series_equal(result, expected)
+
+
+def test_resample_groupby_agg():
+ # GH: 33548
+ df = DataFrame(
+ {
+ "cat": [
+ "cat_1",
+ "cat_1",
+ "cat_2",
+ "cat_1",
+ "cat_2",
+ "cat_1",
+ "cat_2",
+ "cat_1",
+ ],
+ "num": [5, 20, 22, 3, 4, 30, 10, 50],
+ "date": [
+ "2019-2-1",
+ "2018-02-03",
+ "2020-3-11",
+ "2019-2-2",
+ "2019-2-2",
+ "2018-12-4",
+ "2020-3-11",
+ "2020-12-12",
+ ],
+ }
+ )
+ df["date"] = pd.to_datetime(df["date"])
+
+ resampled = df.groupby("cat").resample("Y", on="date")
+ expected = resampled.sum()
+ result = resampled.agg({"num": "sum"})
+
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/reshape/concat/test_dataframe.py b/pandas/tests/reshape/concat/test_dataframe.py
index babc8124877e9..295846ee1b264 100644
--- a/pandas/tests/reshape/concat/test_dataframe.py
+++ b/pandas/tests/reshape/concat/test_dataframe.py
@@ -167,14 +167,3 @@ def test_concat_dataframe_keys_bug(self, sort):
# it works
result = concat([t1, t2], axis=1, keys=["t1", "t2"], sort=sort)
assert list(result.columns) == [("t1", "value"), ("t2", "value")]
-
- def test_concat_duplicate_indexes(self):
- # GH#36263 ValueError with non unique indexes
- df1 = DataFrame([1, 2, 3, 4], index=[0, 1, 1, 4], columns=["a"])
- df2 = DataFrame([6, 7, 8, 9], index=[0, 0, 1, 3], columns=["b"])
- result = concat([df1, df2], axis=1)
- expected = DataFrame(
- {"a": [1, 1, 2, 3, np.nan, 4], "b": [6, 7, 8, 8, 9, np.nan]},
- index=Index([0, 0, 1, 1, 3, 4]),
- )
- tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index f43ae58fbcc2f..e4aab4d1ef92c 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -2349,3 +2349,20 @@ def test_merge_join_cols_error_reporting_on_and_index(func, kwargs):
)
with pytest.raises(MergeError, match=msg):
getattr(pd, func)(left, right, on="a", **kwargs)
+
+
+def test_merge_right_left_index():
+ # GH#38616
+ left = DataFrame({"x": [1, 1], "z": ["foo", "foo"]})
+ right = DataFrame({"x": [1, 1], "z": ["foo", "foo"]})
+ result = pd.merge(left, right, how="right", left_index=True, right_on="x")
+ expected = DataFrame(
+ {
+ "x": [1, 1],
+ "x_x": [1, 1],
+ "z_x": ["foo", "foo"],
+ "x_y": [1, 1],
+ "z_y": ["foo", "foo"],
+ }
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 5b13091470b09..8e0d2193ad999 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -1614,8 +1614,7 @@ def test_constructor_infer_index_tz(self):
class TestSeriesConstructorIndexCoercion:
def test_series_constructor_datetimelike_index_coercion(self):
idx = tm.makeDateIndex(10000)
- with tm.assert_produces_warning(FutureWarning):
- ser = Series(np.random.randn(len(idx)), idx.astype(object))
+ ser = Series(np.random.randn(len(idx)), idx.astype(object))
with tm.assert_produces_warning(FutureWarning):
assert ser.index.is_all_dates
assert isinstance(ser.index, DatetimeIndex)
diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py
index 75e7f8a17eda3..836135c3d6310 100644
--- a/pandas/tests/series/test_repr.py
+++ b/pandas/tests/series/test_repr.py
@@ -184,9 +184,7 @@ def test_timeseries_repr_object_dtype(self):
index = Index(
[datetime(2000, 1, 1) + timedelta(i) for i in range(1000)], dtype=object
)
- with tm.assert_produces_warning(FutureWarning):
- # Index.is_all_dates deprecated
- ts = Series(np.random.randn(len(index)), index)
+ ts = Series(np.random.randn(len(index)), index)
repr(ts)
ts = tm.makeTimeSeries(1000)
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 35411d7e9cfb7..ac97ff7af262d 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -2410,14 +2410,9 @@ def test_diff_ea_axis(self):
with pytest.raises(ValueError, match=msg):
algos.diff(dta, 1, axis=1)
-
-@pytest.mark.parametrize(
- "left_values", [[0, 1, 1, 4], [0, 1, 1, 4, 4], [0, 1, 1, 1, 4]]
-)
-def test_make_duplicates_of_left_unique_in_right(left_values):
- # GH#36263
- left = np.array(left_values)
- right = np.array([0, 0, 1, 1, 4])
- result = algos.make_duplicates_of_left_unique_in_right(left, right)
- expected = np.array([0, 0, 1, 4])
- tm.assert_numpy_array_equal(result, expected)
+ @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)
diff --git a/pandas/tests/util/test_show_versions.py b/pandas/tests/util/test_show_versions.py
index 4ea3ebe5000ad..b6a16d027db77 100644
--- a/pandas/tests/util/test_show_versions.py
+++ b/pandas/tests/util/test_show_versions.py
@@ -39,7 +39,8 @@ def test_show_versions(capsys):
assert re.search(r"commit\s*:\s[0-9a-f]{40}\n", result)
# check required dependency
- assert re.search(r"numpy\s*:\s([0-9\.\+a-f\_]|dev)+\n", result)
+ # 2020-12-09 npdev has "dirty" in the tag
+ assert re.search(r"numpy\s*:\s([0-9\.\+a-g\_]|dev)+(dirty)?\n", result)
# check optional dependency
assert re.search(r"pyarrow\s*:\s([0-9\.]+|None)\n", result)
diff --git a/pandas/tests/window/moments/test_moments_rolling_apply.py b/pandas/tests/window/moments/test_moments_rolling_apply.py
index e9e672e1d3dae..e48d88b365d8d 100644
--- a/pandas/tests/window/moments/test_moments_rolling_apply.py
+++ b/pandas/tests/window/moments/test_moments_rolling_apply.py
@@ -122,16 +122,13 @@ def test_center_reindex_series(raw, series):
s = [f"x{x:d}" for x in range(12)]
minp = 10
- warn = None if raw else FutureWarning
- with tm.assert_produces_warning(warn, check_stacklevel=False):
- # GH#36697 is_all_dates deprecated
- series_xp = (
- series.reindex(list(series.index) + s)
- .rolling(window=25, min_periods=minp)
- .apply(f, raw=raw)
- .shift(-12)
- .reindex(series.index)
- )
+ series_xp = (
+ series.reindex(list(series.index) + s)
+ .rolling(window=25, min_periods=minp)
+ .apply(f, raw=raw)
+ .shift(-12)
+ .reindex(series.index)
+ )
series_rs = series.rolling(window=25, min_periods=minp, center=True).apply(
f, raw=raw
)
@@ -143,15 +140,12 @@ def test_center_reindex_frame(raw, frame):
s = [f"x{x:d}" for x in range(12)]
minp = 10
- warn = None if raw else FutureWarning
- with tm.assert_produces_warning(warn, check_stacklevel=False):
- # GH#36697 is_all_dates deprecated
- frame_xp = (
- frame.reindex(list(frame.index) + s)
- .rolling(window=25, min_periods=minp)
- .apply(f, raw=raw)
- .shift(-12)
- .reindex(frame.index)
- )
+ frame_xp = (
+ frame.reindex(list(frame.index) + s)
+ .rolling(window=25, min_periods=minp)
+ .apply(f, raw=raw)
+ .shift(-12)
+ .reindex(frame.index)
+ )
frame_rs = frame.rolling(window=25, min_periods=minp, center=True).apply(f, raw=raw)
tm.assert_frame_equal(frame_xp, frame_rs)
diff --git a/pandas/tests/window/test_groupby.py b/pandas/tests/window/test_groupby.py
index b89fb35ac3a70..f915da3330ba7 100644
--- a/pandas/tests/window/test_groupby.py
+++ b/pandas/tests/window/test_groupby.py
@@ -556,23 +556,31 @@ 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)
- def test_groupby_rolling_group_keys(self):
+ @pytest.mark.parametrize("group_keys", [True, False])
+ def test_groupby_rolling_group_keys(self, group_keys):
# 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=False).rolling(1).mean()
+ result = s.groupby(["idx1", "idx2"], group_keys=group_keys).rolling(1).mean()
expected = Series(
[1.0, 2.0, 3.0],
index=MultiIndex.from_tuples(
- [("val1", "val1"), ("val1", "val1"), ("val2", "val2")],
- names=["idx1", "idx2"],
+ [
+ ("val1", "val1", "val1", "val1"),
+ ("val1", "val1", "val1", "val1"),
+ ("val2", "val2", "val2", "val2"),
+ ],
+ names=["idx1", "idx2", "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"))
@@ -581,7 +589,12 @@ 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", 1), ("val2", 2)], names=["idx1", "A"]
+ [
+ ("val1", 1, "val1", "val1"),
+ ("val1", 1, "val1", "val1"),
+ ("val2", 2, "val2", "val2"),
+ ],
+ names=["idx1", "A", "idx1", "idx2"],
),
)
tm.assert_frame_equal(result, expected)
@@ -640,6 +653,30 @@ 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):
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index 10b23cadfe279..e2cdf76d038ec 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -1102,11 +1102,13 @@ def test_groupby_rolling_nan_included():
@pytest.mark.parametrize("method", ["skew", "kurt"])
def test_rolling_skew_kurt_numerical_stability(method):
- # GH: 6929
- s = Series(np.random.rand(10))
- expected = getattr(s.rolling(3), method)()
- s = s + 50000
- result = getattr(s.rolling(3), method)()
+ # GH#6929
+ ser = Series(np.random.rand(10))
+ ser_copy = ser.copy()
+ expected = getattr(ser.rolling(3), method)()
+ tm.assert_series_equal(ser, ser_copy)
+ ser = ser + 50000
+ result = getattr(ser.rolling(3), method)()
tm.assert_series_equal(result, expected)
diff --git a/setup.py b/setup.py
index 0b1007794bbdb..f9c4a1158fee0 100755
--- a/setup.py
+++ b/setup.py
@@ -421,6 +421,8 @@ def run(self):
extra_compile_args.append("-Werror")
if debugging_symbols_requested:
extra_compile_args.append("-g")
+ extra_compile_args.append("-UNDEBUG")
+ extra_compile_args.append("-O0")
# Build for at least macOS 10.9 when compiling on a 10.9 system or above,
# overriding CPython distuitls behaviour which is to target the version that
@@ -433,7 +435,7 @@ def run(self):
"MACOSX_DEPLOYMENT_TARGET", current_system
)
if (
- LooseVersion(python_target) < "10.9"
+ LooseVersion(str(python_target)) < "10.9"
and LooseVersion(current_system) >= "10.9"
):
os.environ["MACOSX_DEPLOYMENT_TARGET"] = "10.9"
diff --git a/test_fast.bat b/test_fast.bat
index f2c4e9fa71fcd..34c61fea08ab4 100644
--- a/test_fast.bat
+++ b/test_fast.bat
@@ -1,3 +1,3 @@
:: test on windows
set PYTHONHASHSEED=314159265
-pytest --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sXX --strict pandas
+pytest --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sXX --strict-markers pandas
diff --git a/test_fast.sh b/test_fast.sh
index 0a47f9de600ea..6444b81b3c6da 100755
--- a/test_fast.sh
+++ b/test_fast.sh
@@ -5,4 +5,4 @@
# https://github.com/pytest-dev/pytest/issues/1075
export PYTHONHASHSEED=$(python -c 'import random; print(random.randint(1, 4294967295))')
-pytest pandas --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sxX --strict "$@"
+pytest pandas --skip-slow --skip-network --skip-db -m "not single" -n 4 -r sxX --strict-markers "$@"
| https://api.github.com/repos/pandas-dev/pandas/pulls/39080 | 2021-01-10T00:56:13Z | 2021-01-10T00:56:31Z | null | 2021-01-10T00:56:31Z | |
BUG: read_csv with custom date parser and na_filter=True results in ValueError | diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py
index c0b29d5019675..a73768e9ccca7 100644
--- a/pandas/tests/io/parser/test_parse_dates.py
+++ b/pandas/tests/io/parser/test_parse_dates.py
@@ -56,6 +56,40 @@ def test_separator_date_conflict(all_parsers):
tm.assert_frame_equal(df, expected)
+def test_read_csv_with_custom_date_parser(all_parsers):
+ # GH36111
+ def __custom_date_parser(time):
+ time = time.astype(np.float)
+ time = time.astype(np.int) # convert float seconds to int type
+ return pd.to_timedelta(time, unit="s")
+
+ testdata = StringIO(
+ """time e n h
+ 41047.00 -98573.7297 871458.0640 389.0089
+ 41048.00 -98573.7299 871458.0640 389.0089
+ 41049.00 -98573.7300 871458.0642 389.0088
+ 41050.00 -98573.7299 871458.0643 389.0088
+ 41051.00 -98573.7302 871458.0640 389.0086
+ """
+ )
+ result = all_parsers.read_csv(
+ testdata,
+ delim_whitespace=True,
+ parse_dates=True,
+ date_parser=__custom_date_parser,
+ index_col="time",
+ )
+ expected = pd.DataFrame(
+ {
+ "e": [-98573.7297, -98573.7299, -98573.7300, -98573.7299, -98573.7302],
+ "n": [871458.0640, 871458.0640, 871458.0642, 871458.0643, 871458.0640],
+ "h": [389.0089, 389.0089, 389.0088, 389.0088, 389.0086],
+ },
+ index=[41047, 41048, 41049, 41050, 41051],
+ )
+ tm.assert_frame_equal(result, expected)
+
+
@pytest.mark.parametrize("keep_date_col", [True, False])
def test_multiple_date_col_custom(all_parsers, keep_date_col):
data = """\
diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py
index d59f0c05c7462..ac9ac6c040d6d 100644
--- a/pandas/tests/series/test_dtypes.py
+++ b/pandas/tests/series/test_dtypes.py
@@ -111,4 +111,17 @@ def test_reindex_astype_order_consistency(self):
new_dtype = str
s1 = s.reindex(new_index).astype(temp_dtype).astype(new_dtype)
s2 = s.astype(temp_dtype).reindex(new_index).astype(new_dtype)
- tm.assert_series_equal(s1, s2)
+ tm.assert_series_equal(s1, s2
+
+ def test_series_with_object_dtype(self):
+ # GH 21881
+ timestamp = pd.Timestamp(1412526600000000000)
+ series = pd.Series([], dtype=object)
+ series['timestamp'] = timestamp
+ expected = type(series.timestamp)
+
+ series = pd.Series([], dtype=object)
+ series['anything'] = 300.0
+ series['timestamp'] = timestamp
+ result = type(series.timestamp)
+ assert result == expected
| - [ ] closes #36111
- [ ] 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/39079 | 2021-01-10T00:44:25Z | 2021-01-31T00:11:56Z | null | 2021-02-01T10:00:48Z |
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: prep _generate_range_overflow_safe for numpy 1.20 | diff --git a/pandas/core/arrays/_ranges.py b/pandas/core/arrays/_ranges.py
index 14b442bf71080..dfed3c927b810 100644
--- a/pandas/core/arrays/_ranges.py
+++ b/pandas/core/arrays/_ranges.py
@@ -70,7 +70,7 @@ def generate_regular_range(
def _generate_range_overflow_safe(
endpoint: int, periods: int, stride: int, side: str = "start"
-) -> int:
+):
"""
Calculate the second endpoint for passing to np.arange, checking
to avoid an integer overflow. Catch OverflowError and re-raise
@@ -89,7 +89,7 @@ def _generate_range_overflow_safe(
Returns
-------
- other_end : int
+ np.integer
Raises
------
@@ -137,7 +137,7 @@ def _generate_range_overflow_safe(
def _generate_range_overflow_safe_signed(
endpoint: int, periods: int, stride: int, side: str
-) -> int:
+):
"""
A special case for _generate_range_overflow_safe where `periods * stride`
can be calculated without overflowing int64 bounds.
| difficult call, will replace
pandas/core/arrays/_ranges.py:153: error: Incompatible return value type (got "signedinteger[_64Bit]", expected "int") [return-value]
pandas/core/arrays/_ranges.py:171: error: Incompatible return value type (got "unsignedinteger[_64Bit]", expected "int") [return-value]
with
pandas/core/arrays/_ranges.py:129: error: Argument 1 to "_generate_range_overflow_safe" has incompatible type "Union[int, number[Any]]"; expected "Union[int, integer[Any]]" [arg-type]
pandas/core/arrays/_ranges.py:129: error: Argument 2 to "_generate_range_overflow_safe" has incompatible type "Union[int, number[Any]]"; expected "Union[int, integer[Any]]" [arg-type]
pandas/core/arrays/_ranges.py:137: error: Argument 2 to "_generate_range_overflow_safe" has incompatible type "Union[int, number[Any]]"; expected "Union[int, integer[Any]]" [arg-type]
pandas/core/arrays/_ranges.py:138: error: Argument 2 to "_generate_range_overflow_safe" has incompatible type "Union[int, number[Any]]"; expected "Union[int, integer[Any]]" [arg-type]
these are from arithmetic operations on np.integer (including floordiv) which AFAICT should return np.integer and not np.number
can't add the ignores yet, since we will get unused ignore mypy messages - active branch with fixes https://github.com/pandas-dev/pandas/compare/master...simonjayhawkins:numpy-fixes?expand=1 | https://api.github.com/repos/pandas-dev/pandas/pulls/39067 | 2021-01-09T20:30:00Z | 2021-02-02T09:00:19Z | null | 2021-02-02T09:00:19Z |
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 |
BUG: in network decorator | diff --git a/pandas/_testing/_io.py b/pandas/_testing/_io.py
index 5f27b016b68a2..f3de9c1502c37 100644
--- a/pandas/_testing/_io.py
+++ b/pandas/_testing/_io.py
@@ -1,7 +1,7 @@
import bz2
from functools import wraps
import gzip
-from typing import Any, Callable, Optional, Tuple
+from typing import Any, Callable, Iterable, Optional, Tuple
import zipfile
from pandas._typing import FilePathOrBuffer, FrameOrSeries
@@ -100,7 +100,7 @@ def network(
raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT,
check_before_test=False,
error_classes=None,
- skip_errnos=_network_errno_vals,
+ skip_errnos: Iterable[int] = _network_errno_vals,
_skip_on_messages=_network_error_messages,
):
"""
@@ -129,7 +129,7 @@ def network(
error classes to ignore. If not in ``error_classes``, raises the error.
defaults to IOError. Be careful about changing the error classes here.
skip_errnos : iterable of int
- Any exception that has .errno or .reason.erno set to one
+ Any exception that has .errno or .reason.errno set to one
of these values will be skipped with an appropriate
message.
_skip_on_messages: iterable of string
@@ -204,9 +204,9 @@ def wrapper(*args, **kwargs):
return t(*args, **kwargs)
except Exception as err:
errno = getattr(err, "errno", None)
- if not errno and hasattr(errno, "reason"):
- # pandas\_testing.py:2521: error: "Exception" has no attribute
- # "reason"
+ if not errno and hasattr(err, "reason"):
+ # https://github.com/python/mypy/issues/1424
+ # error: "Exception" has no attribute "reason"
errno = getattr(err.reason, "errno", None) # type: ignore[attr-defined]
if errno in skip_errnos:
| https://api.github.com/repos/pandas-dev/pandas/pulls/39060 | 2021-01-09T15:18:04Z | 2021-01-11T20:45:34Z | null | 2021-01-11T20:45:34Z | |
TYP: remove ignore in optional_args | diff --git a/pandas/_testing/_io.py b/pandas/_testing/_io.py
index 5f27b016b68a2..bc38d894c3d5b 100644
--- a/pandas/_testing/_io.py
+++ b/pandas/_testing/_io.py
@@ -82,10 +82,7 @@ def dec(f):
is_decorating = not kwargs and len(args) == 1 and callable(args[0])
if is_decorating:
f = args[0]
- # pandas\_testing.py:2331: error: Incompatible types in assignment
- # (expression has type "List[<nothing>]", variable has type
- # "Tuple[Any, ...]")
- args = [] # type: ignore[assignment]
+ args = ()
return dec(f)
else:
return dec
| xref #37715 | https://api.github.com/repos/pandas-dev/pandas/pulls/39059 | 2021-01-09T14:25:09Z | 2021-02-02T09:01:04Z | null | 2021-02-02T09:01:04Z |
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 |
TST: extend check for leaked files | diff --git a/ci/deps/actions-37-db.yaml b/ci/deps/actions-37-db.yaml
index 5381caaa242cf..dc6658cc45690 100644
--- a/ci/deps/actions-37-db.yaml
+++ b/ci/deps/actions-37-db.yaml
@@ -51,4 +51,4 @@ dependencies:
- brotlipy
- coverage
- pandas-datareader
- - pyxlsb
+ - pyxlsb>=1.0.8
diff --git a/ci/deps/actions-37-minimum_versions.yaml b/ci/deps/actions-37-minimum_versions.yaml
index e14e51a36be31..aa5eec5e19b92 100644
--- a/ci/deps/actions-37-minimum_versions.yaml
+++ b/ci/deps/actions-37-minimum_versions.yaml
@@ -24,6 +24,7 @@ dependencies:
- python-dateutil=2.7.3
- pytz=2017.3
- pyarrow=0.15
+ - pyxlsb>=1.0.8
- scipy=1.2
- xlrd=1.2.0
- xlsxwriter=1.0.2
diff --git a/ci/deps/actions-38-locale.yaml b/ci/deps/actions-38-locale.yaml
index 629804c71e726..4838fb1ded447 100644
--- a/ci/deps/actions-38-locale.yaml
+++ b/ci/deps/actions-38-locale.yaml
@@ -38,4 +38,4 @@ dependencies:
- pyarrow=1.0.0
- pip
- pip:
- - pyxlsb
+ - pyxlsb>=1.0.8
diff --git a/ci/deps/azure-macos-37.yaml b/ci/deps/azure-macos-37.yaml
index d667adddda859..3e34af1a666c8 100644
--- a/ci/deps/azure-macos-37.yaml
+++ b/ci/deps/azure-macos-37.yaml
@@ -33,4 +33,4 @@ dependencies:
- pip:
- cython>=0.29.21
- pyreadstat
- - pyxlsb
+ - pyxlsb>=1.0.8
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index e7ac4c783b855..e9ec808524a73 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -39,4 +39,4 @@ dependencies:
- pyreadstat
- pip
- pip:
- - pyxlsb
+ - pyxlsb>=1.0.8
diff --git a/ci/run_tests.sh b/ci/run_tests.sh
index d73940c1010ad..37cc5db7a08bb 100755
--- a/ci/run_tests.sh
+++ b/ci/run_tests.sh
@@ -1,5 +1,7 @@
#!/bin/bash -e
+PYTEST_WORKERS=0
+
# Workaround for pytest-xdist (it collects different tests in the workers if PYTHONHASHSEED is not set)
# https://github.com/pytest-dev/pytest/issues/920
# https://github.com/pytest-dev/pytest/issues/1075
@@ -19,7 +21,7 @@ if [[ $(uname) == "Linux" && -z $DISPLAY ]]; then
XVFB="xvfb-run "
fi
-PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile -s --strict-markers --durations=30 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas"
+PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n 0 --dist=no -s --strict-markers --durations=30 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas"
if [[ $(uname) != "Linux" && $(uname) != "Darwin" ]]; then
# GH#37455 windows py38 build appears to be running out of memory
@@ -30,7 +32,7 @@ fi
echo $PYTEST_CMD
sh -c "$PYTEST_CMD"
-PYTEST_AM_CMD="PANDAS_DATA_MANAGER=array pytest -m \"$PATTERN and arraymanager\" -n $PYTEST_WORKERS --dist=loadfile -s --strict-markers --durations=30 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas"
+PYTEST_AM_CMD="PANDAS_DATA_MANAGER=array pytest -m \"$PATTERN and arraymanager\" -n 0 --dist=no -s --strict-markers --durations=30 --junitxml=test-data.xml $TEST_ARGS $COVERAGE pandas"
echo $PYTEST_AM_CMD
sh -c "$PYTEST_AM_CMD"
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index a9c3d637a41e3..821c6e85297fe 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -275,6 +275,17 @@ Dependency Minimum Version Notes
SciPy 1.12.0 Miscellaneous statistical functions
numba 0.46.0 Alternative execution engine for rolling operations
(see :ref:`Enhancing Performance <enhancingperf.numba>`)
+openpyxl 2.6.0 Reading / writing for xlsx files
+pandas-gbq 0.12.0 Google Big Query access
+psycopg2 2.7 PostgreSQL engine for sqlalchemy
+pyarrow 0.15.0 Parquet, ORC, and feather reading / writing
+pymysql 0.8.1 MySQL engine for sqlalchemy
+pyreadstat SPSS files (.sav) reading
+pyxlsb 1.0.8 Reading for xlsb files
+qtpy Clipboard I/O
+s3fs 0.4.0 Amazon S3 access
+tabulate 0.8.7 Printing in Markdown-friendly format (see `tabulate`_)
+>>>>>>> TST: extend check for leaked files
xarray 0.12.3 pandas-like API for N-dimensional data
========================= ================== =============================================================
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 63902b53ea36d..3a50c804b0630 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -431,6 +431,8 @@ Optional libraries below the lowest tested version may still work, but are not c
+-----------------+-----------------+---------+
| pytables | 3.5.1 | |
+-----------------+-----------------+---------+
+| pyxlsb | 1.0.8 | X |
++-----------------+-----------------+---------+
| s3fs | 0.4.0 | |
+-----------------+-----------------+---------+
| scipy | 1.2.0 | |
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index a26da75d921ef..9652b918044cd 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -21,7 +21,7 @@
"pandas_gbq": "0.12.0",
"pyarrow": "0.15.0",
"pytest": "5.0.1",
- "pyxlsb": "1.0.6",
+ "pyxlsb": "1.0.8",
"s3fs": "0.4.0",
"scipy": "1.2.0",
"sqlalchemy": "1.2.8",
diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py
index 76cfd77d254f2..aa138b58348f5 100644
--- a/pandas/tests/frame/test_api.py
+++ b/pandas/tests/frame/test_api.py
@@ -269,7 +269,7 @@ def _check_f(base, f):
_check_f(d.copy(), f)
@async_mark()
- @td.check_file_leaks
+ @td.check_file_leaks()
async def test_tab_complete_warning(self, ip, frame_or_series):
# GH 16409
pytest.importorskip("IPython", minversion="6.0.0")
diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py
index 5d4705dbe7d77..83ed90336549a 100644
--- a/pandas/tests/io/conftest.py
+++ b/pandas/tests/io/conftest.py
@@ -6,6 +6,8 @@
import pytest
+import pandas.util._test_decorators as td
+
import pandas._testing as tm
from pandas.io.parsers import read_csv
@@ -163,3 +165,17 @@ def add_tips_files(bucket_name):
while cli.list_buckets()["Buckets"] and timeout > 0:
time.sleep(0.1)
timeout -= 0.1
+
+
+@pytest.fixture(autouse=True)
+def check_for_file_leaks(request):
+ """
+ Fixture to run around every test to ensure that we are not leaking files.
+
+ See also
+ --------
+ _test_decorators.check_file_leaks
+ """
+ # GH#30162
+ with td.check_file_leaks(ignore_connections=True):
+ yield
diff --git a/pandas/tests/io/excel/conftest.py b/pandas/tests/io/excel/conftest.py
index 0455e0d61ad97..958b9b5f777fd 100644
--- a/pandas/tests/io/excel/conftest.py
+++ b/pandas/tests/io/excel/conftest.py
@@ -43,23 +43,9 @@ def read_ext(request):
return request.param
+# override auto-fixture to also check connections
@pytest.fixture(autouse=True)
-def check_for_file_leaks():
- """
- Fixture to run around every test to ensure that we are not leaking files.
-
- See also
- --------
- _test_decorators.check_file_leaks
- """
+def check_for_file_leaks(request):
# GH#30162
- psutil = td.safe_import("psutil")
- if not psutil:
- yield
-
- else:
- proc = psutil.Process()
- flist = proc.open_files()
+ with td.check_file_leaks(ignore_connections=False):
yield
- flist2 = proc.open_files()
- assert flist == flist2
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 382c8412ab050..cb4c3e76135da 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -797,7 +797,6 @@ def test_read_from_pathlib_path(self, read_ext):
tm.assert_frame_equal(expected, actual)
@td.skip_if_no("py.path")
- @td.check_file_leaks
def test_read_from_py_localpath(self, read_ext):
# GH12655
@@ -811,7 +810,6 @@ def test_read_from_py_localpath(self, read_ext):
tm.assert_frame_equal(expected, actual)
- @td.check_file_leaks
def test_close_from_py_localpath(self, read_ext):
# GH31467
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index 17445b2f134d3..28a90f3fcccf1 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -3266,7 +3266,7 @@ def test_format_percentiles_integer_idx():
assert result == expected
-@td.check_file_leaks
+@td.check_file_leaks()
def test_repr_html_ipython_config(ip):
code = textwrap.dedent(
"""\
diff --git a/pandas/tests/io/parser/common/test_file_buffer_url.py b/pandas/tests/io/parser/common/test_file_buffer_url.py
index 2a3d7328aa662..d8305f578b6e6 100644
--- a/pandas/tests/io/parser/common/test_file_buffer_url.py
+++ b/pandas/tests/io/parser/common/test_file_buffer_url.py
@@ -417,15 +417,12 @@ def test_file_descriptor_leak(all_parsers):
parser = all_parsers
with tm.ensure_clean() as path:
-
- def test():
+ with td.check_file_leaks():
with pytest.raises(EmptyDataError, match="No columns to parse from file"):
parser.read_csv(path)
- td.check_file_leaks(test)()
-
-@td.check_file_leaks
+@td.check_file_leaks()
def test_memory_map(all_parsers, csv_dir_path):
mmap_file = os.path.join(csv_dir_path, "test_mmap.csv")
parser = all_parsers
diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py
index 4e3d99af685ec..90c914dad4f2f 100644
--- a/pandas/tests/io/parser/common/test_read_errors.py
+++ b/pandas/tests/io/parser/common/test_read_errors.py
@@ -2,6 +2,7 @@
Tests that work on both the Python and C engines but do not have a
specific classification into the other test modules.
"""
+
import codecs
import csv
from io import StringIO
@@ -217,7 +218,7 @@ def test_null_byte_char(all_parsers):
parser.read_csv(StringIO(data), names=names)
-@td.check_file_leaks
+@td.check_file_leaks()
def test_open_file(all_parsers):
# GH 39024
parser = all_parsers
diff --git a/pandas/tests/io/sas/test_xport.py b/pandas/tests/io/sas/test_xport.py
index a8713f5bf36c9..69ec6f4451703 100644
--- a/pandas/tests/io/sas/test_xport.py
+++ b/pandas/tests/io/sas/test_xport.py
@@ -31,7 +31,7 @@ def setup_method(self, datapath):
self.file03 = os.path.join(self.dirpath, "DRXFCD_G.xpt")
self.file04 = os.path.join(self.dirpath, "paxraw_d_short.xpt")
- with td.file_leak_context():
+ with td.check_file_leaks():
yield
def test1_basic(self):
@@ -129,10 +129,9 @@ def test2_binary(self):
numeric_as_float(data_csv)
with open(self.file02, "rb") as fd:
- with td.file_leak_context():
- # GH#35693 ensure that if we pass an open file, we
- # dont incorrectly close it in read_sas
- data = read_sas(fd, format="xport")
+ # GH#35693 ensure that if we pass an open file, we
+ # dont incorrectly close it in read_sas
+ data = read_sas(fd, format="xport")
tm.assert_frame_equal(data, data_csv)
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
index d882eb930137b..00ceeec3e9ab4 100644
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -524,3 +524,13 @@ def test_bad_encdoing_errors():
with tm.ensure_clean() as path:
with pytest.raises(ValueError, match="Invalid value for `encoding_errors`"):
icom.get_handle(path, "w", errors="bad")
+
+
+def test_resource_warnings():
+ msg = '[ResourceWarning("unclosed file *)]'
+ with tm.ensure_clean("_resource_test") as path:
+ with pytest.raises(AssertionError, match=msg):
+ with td.check_file_leaks():
+ handle = open(path)
+ # prevent the auto fixture from throwing an AssertionError
+ handle.close()
diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py
index 999d8a6c90ba2..51259b04fb4aa 100644
--- a/pandas/tests/resample/test_resampler_grouper.py
+++ b/pandas/tests/resample/test_resampler_grouper.py
@@ -23,7 +23,7 @@
@async_mark()
-@td.check_file_leaks
+@td.check_file_leaks()
async def test_tab_complete_ipython6_warning(ip):
from IPython.core.completer import provisionalcompleter
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index 752ed43849d2b..0aef33a90f61a 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -23,14 +23,11 @@ def test_foo():
For more information, refer to the ``pytest`` documentation on ``skipif``.
"""
-from contextlib import contextmanager
-from distutils.version import LooseVersion
import locale
-from typing import (
- Callable,
- Optional,
-)
import warnings
+from contextlib import ContextDecorator
+from distutils.version import LooseVersion
+from typing import Callable, Optional
import numpy as np
import pytest
@@ -42,11 +39,7 @@ def test_foo():
is_platform_windows,
)
from pandas.compat._optional import import_optional_dependency
-
-from pandas.core.computation.expressions import (
- NUMEXPR_INSTALLED,
- USE_NUMEXPR,
-)
+from pandas.core.computation.expressions import NUMEXPR_INSTALLED, USE_NUMEXPR
def safe_import(mod_name: str, min_version: Optional[str] = None):
@@ -245,38 +238,67 @@ def documented_fixture(fixture):
return documented_fixture
-def check_file_leaks(func) -> Callable:
- """
- Decorate a test function to check that we are not leaking file descriptors.
+class check_file_leaks(ContextDecorator):
"""
- with file_leak_context():
- return func
+ Use psutil and ResourceWarning to identify forgotten resources.
-
-@contextmanager
-def file_leak_context():
- """
- ContextManager analogue to check_file_leaks.
+ ResourceWarnings that contain the string 'ssl' are ignored as they are very likely
+ caused by boto3 (GH#17058).
"""
- psutil = safe_import("psutil")
- if not psutil:
- yield
- else:
- proc = psutil.Process()
- flist = proc.open_files()
- conns = proc.connections()
-
- yield
-
- flist2 = proc.open_files()
- # on some builds open_files includes file position, which we _dont_
- # expect to remain unchanged, so we need to compare excluding that
- flist_ex = [(x.path, x.fd) for x in flist]
- flist2_ex = [(x.path, x.fd) for x in flist2]
- assert flist2_ex == flist_ex, (flist2, flist)
- conns2 = proc.connections()
- assert conns2 == conns, (conns2, conns)
+ def __init__(self, ignore_connections: bool = False):
+ super().__init__()
+ self.ignore_connections = ignore_connections
+
+ def __enter__(self):
+ # catch warnings
+ self.catcher = warnings.catch_warnings(record=True)
+ self.record = self.catcher.__enter__()
+
+ # get files and connections
+ self.psutil = safe_import("psutil")
+ if self.psutil:
+ self.proc = self.psutil.Process()
+ self.flist = self.proc.open_files()
+ self.conns = self.proc.connections()
+
+ return self
+
+ def __exit__(self, *exc):
+ self.catcher.__exit__(*exc)
+
+ # re-throw warnings
+ fields = ("category", "source", "filename", "lineno")
+ for message in self.record:
+ warnings.warn_explicit(
+ message.message, **{field: getattr(message, field) for field in fields}
+ )
+
+ # assert no non-ssl ResourceWarnings
+ messages = [
+ warn.message
+ for warn in self.record
+ if issubclass(warn.category, ResourceWarning)
+ and "ssl" not in str(warn.message)
+ ]
+ assert not messages, f"{messages}"
+
+ # psutil
+ if self.psutil:
+ flist2 = self.proc.open_files()
+
+ # on some builds open_files includes file position, which we _dont_
+ # expect to remain unchanged, so we need to compare excluding that
+ flist_ex = {(x.path, x.fd) for x in self.flist}
+ flist2_ex = {(x.path, x.fd) for x in flist2}
+ assert (
+ flist2_ex == flist_ex
+ ), f"{flist_ex - flist2_ex} {flist2_ex - flist_ex}"
+
+ if not self.ignore_connections:
+ conns = set(self.conns)
+ conns2 = set(self.proc.connections())
+ assert conns2 == conns, f"{conns - conns2} {conns2 - conns}"
def async_mark():
diff --git a/setup.cfg b/setup.cfg
index a0b6a0cdfc260..11742d62c8a4c 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -118,6 +118,7 @@ xfail_strict = True
filterwarnings =
error:Sparse:FutureWarning
error:The SparseArray:FutureWarning
+ always::ResourceWarning
junit_family = xunit2
[codespell]
| Use `ResourceWarning`s as indicators of leaked files. I left the `psutil`-based check for leaked files.
I enabled the check for leaked files for all io tests.
boto3 (#17058) is probably causing all of the unclosed ssl connections. This PR ignores ResourceWarnings that contain the string `'ssl'`. The fixture applied to all io tests further ignores all connections found by `psutils` for the same reason. Connections are checked for code that was previously covered by `check_file_leaks`. | https://api.github.com/repos/pandas-dev/pandas/pulls/39047 | 2021-01-09T02:31:51Z | 2021-03-31T22:34:37Z | null | 2022-06-08T19:26:45Z |
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 |
BUG/API: make setitem-inplace preserve dtype when possible with PandasArray, IntegerArray, FloatingArray | diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index ef645313de614..a2f200192eacb 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -505,14 +505,28 @@ def array_equals(left: ArrayLike, right: ArrayLike) -> bool:
return array_equivalent(left, right, dtype_equal=True)
-def infer_fill_value(val):
+def infer_fill_value(val, length: int):
"""
- infer the fill value for the nan/NaT from the provided
- scalar/ndarray/list-like if we are a NaT, return the correct dtyped
- element to provide proper block construction
+ `val` is going to be inserted as (part of) a new column in a DataFrame
+ with the given length. If val cannot be made to fit exactly,
+ find an appropriately-dtyped NA value to construct a complete column from,
+ which we will later set `val` into.
"""
if not is_list_like(val):
val = [val]
+
+ if is_extension_array_dtype(val):
+ # We cannot use dtype._na_value bc pd.NA/pd.NaT do not preserve dtype
+ if len(val) == length:
+ # TODO: in this case see if we can avoid making a copy later on
+ return val
+ if length == 0:
+ return val[:0].copy()
+
+ dtype = val.dtype
+ cls = dtype.construct_array_type()
+ return cls._from_sequence([dtype.na_value], dtype=dtype).repeat(length)
+
val = np.array(val, copy=False)
if needs_i8_conversion(val.dtype):
return np.array("NaT", dtype=val.dtype)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index cc7c5f666feda..fd6adcc62d032 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1605,7 +1605,7 @@ def _setitem_with_indexer(self, indexer, value, name="iloc"):
# We are setting an entire column
self.obj[key] = value
else:
- self.obj[key] = infer_fill_value(value)
+ self.obj[key] = infer_fill_value(value, len(self.obj))
new_indexer = convert_from_missing_indexer_tuple(
indexer, self.obj.axes
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 3c27e34dcbcf6..41f8d3064b6b4 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -69,6 +69,8 @@
Categorical,
DatetimeArray,
ExtensionArray,
+ FloatingArray,
+ IntegerArray,
PandasArray,
TimedeltaArray,
)
@@ -623,10 +625,17 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
)
raise TypeError(msg)
+ values = self.values
dtype = pandas_dtype(dtype)
+ if isinstance(dtype, ExtensionDtype) and self.values.ndim == 2:
+ # TODO(EA2D): kludge not needed with 2D EAs (astype_nansafe would raise)
+ # note DataFrame.astype has special handling to avoid getting here
+ if self.shape[0] != 1:
+ raise NotImplementedError("Need 2D EAs!")
+ values = values[0]
try:
- new_values = self._astype(dtype, copy=copy)
+ new_values = astype_block_compat(values, dtype, copy=copy)
except (ValueError, TypeError):
# e.g. astype_nansafe can fail on object-dtype of strings
# trying to convert to float
@@ -645,25 +654,6 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
)
return newb
- def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike:
- values = self.values
-
- if is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype):
- return astype_dt64_to_dt64tz(values, dtype, copy, via_utc=True)
-
- if is_dtype_equal(values.dtype, dtype):
- if copy:
- return values.copy()
- return values
-
- if isinstance(values, ExtensionArray):
- values = values.astype(dtype, copy=copy)
-
- else:
- values = astype_nansafe(values, dtype, copy=copy)
-
- return values
-
def convert(
self,
copy: bool = True,
@@ -908,6 +898,15 @@ def setitem(self, indexer, value):
# current dtype cannot store value, coerce to common dtype
return self.coerce_to_target_dtype(value).setitem(indexer, value)
+ value = extract_array(value, extract_numpy=True)
+
+ if isinstance(value, (IntegerArray, FloatingArray)) and not value._mask.any():
+ # GH#38896
+ value = value.to_numpy(value.dtype.numpy_dtype)
+ if self.ndim == 2 and value.ndim == 1:
+ # TODO(EA2D): special case not needed with 2D EAs
+ value = np.atleast_2d(value).T
+
if self.dtype.kind in ["m", "M"]:
arr = self.array_values().T
arr[indexer] = value
@@ -1882,6 +1881,11 @@ class NumericBlock(Block):
is_numeric = True
def _can_hold_element(self, element: Any) -> bool:
+ if isinstance(element, (IntegerArray, FloatingArray)):
+ # GH#38896
+ if element._mask.any():
+ return False
+
return can_hold_element(self.dtype, element)
@property
@@ -2500,3 +2504,24 @@ def safe_reshape(arr: ArrayLike, new_shape: Shape) -> ArrayLike:
# TODO(EA2D): special case will be unnecessary with 2D EAs
arr = np.asarray(arr).reshape(new_shape)
return arr
+
+
+def astype_block_compat(values: ArrayLike, dtype: DtypeObj, copy: bool) -> ArrayLike:
+ """
+ Series/DataFrame implementation of .astype
+ """
+ if is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype):
+ return astype_dt64_to_dt64tz(values, dtype, copy, via_utc=True)
+
+ if is_dtype_equal(values.dtype, dtype):
+ if copy:
+ return values.copy()
+ return values
+
+ if isinstance(values, ExtensionArray):
+ values = values.astype(dtype, copy=copy)
+
+ else:
+ values = astype_nansafe(values, dtype, copy=copy)
+
+ return values
diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py
index 4ee9cb89fc227..fc0b34e05dce8 100644
--- a/pandas/tests/extension/test_integer.py
+++ b/pandas/tests/extension/test_integer.py
@@ -32,8 +32,11 @@
from pandas.tests.extension import base
-def make_data():
- return list(range(1, 9)) + [pd.NA] + list(range(10, 98)) + [pd.NA] + [99, 100]
+def make_data(with_nas: bool = True):
+ if with_nas:
+ return list(range(1, 9)) + [pd.NA] + list(range(10, 98)) + [pd.NA] + [99, 100]
+
+ return list(range(1, 101))
@pytest.fixture(
@@ -52,9 +55,10 @@ def dtype(request):
return request.param()
-@pytest.fixture
-def data(dtype):
- return pd.array(make_data(), dtype=dtype)
+@pytest.fixture(params=[True, False])
+def data(dtype, request):
+ with_nas = request.param
+ return pd.array(make_data(with_nas), dtype=dtype)
@pytest.fixture
@@ -193,7 +197,21 @@ class TestGetitem(base.BaseGetitemTests):
class TestSetitem(base.BaseSetitemTests):
- pass
+ def test_setitem_series(self, data, full_indexer):
+ # https://github.com/pandas-dev/pandas/issues/32395
+ # overriden because we have a different `expected` in some cases
+ ser = expected = pd.Series(data, name="data")
+ result = pd.Series(index=ser.index, dtype=object, name="data")
+
+ key = full_indexer(ser)
+ result.loc[key] = ser
+
+ if not data._mask.any():
+ # GH#38896 like we do with ndarray, we set the values inplace
+ # but cast to the new numpy dtype
+ expected = pd.Series(data.to_numpy(data.dtype.numpy_dtype), name="data")
+
+ self.assert_series_equal(result, expected)
class TestMissing(base.BaseMissingTests):
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index a5b54bc153f5d..0f7d4524f9943 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -17,10 +17,12 @@
import pytest
from pandas.core.dtypes.dtypes import ExtensionDtype, PandasDtype
+from pandas.core.dtypes.missing import infer_fill_value as infer_fill_value_orig
import pandas as pd
import pandas._testing as tm
-from pandas.core.arrays.numpy_ import PandasArray
+from pandas.core.arrays import PandasArray, StringArray
+from pandas.core.construction import extract_array
from pandas.tests.extension import base
@@ -29,6 +31,31 @@ def dtype(request):
return PandasDtype(np.dtype(request.param))
+orig_setitem = pd.core.internals.Block.setitem
+
+
+def setitem(self, indexer, value):
+ # patch Block.setitem
+ value = extract_array(value, extract_numpy=True)
+ if isinstance(value, PandasArray) and not isinstance(value, StringArray):
+ value = value.to_numpy()
+ if self.ndim == 2 and value.ndim == 1:
+ # TODO(EA2D): special case not needed with 2D EAs
+ value = np.atleast_2d(value)
+
+ return orig_setitem(self, indexer, value)
+
+
+def infer_fill_value(val, length: int):
+ # GH#39044 we have to patch core.dtypes.missing.infer_fill_value
+ # to unwrap PandasArray bc it won't recognize PandasArray with
+ # is_extension_dtype
+ if isinstance(val, PandasArray):
+ val = val.to_numpy()
+
+ return infer_fill_value_orig(val, length)
+
+
@pytest.fixture
def allow_in_pandas(monkeypatch):
"""
@@ -48,6 +75,8 @@ def allow_in_pandas(monkeypatch):
"""
with monkeypatch.context() as m:
m.setattr(PandasArray, "_typ", "extension")
+ m.setattr(pd.core.indexing, "infer_fill_value", infer_fill_value)
+ m.setattr(pd.core.internals.Block, "setitem", setitem)
yield
@@ -457,6 +486,42 @@ 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, request):
+ # https://github.com/pandas-dev/pandas/issues/32395
+ df = pd.DataFrame({"data": pd.Series(data)})
+ result = pd.DataFrame(index=df.index)
+
+ key = full_indexer(df)
+ result.loc[key, "data"] = df["data"]._values
+
+ expected = pd.DataFrame({"data": data})
+ if data.dtype.numpy_dtype != object:
+ # For PandasArray we expect to get unboxed to numpy
+ expected = pd.DataFrame({"data": data.to_numpy()})
+
+ if isinstance(key, slice) and (
+ key == slice(None) and data.dtype.numpy_dtype != object
+ ):
+ mark = pytest.mark.xfail(
+ reason="This case goes through a different code path"
+ )
+ # Other cases go through Block.setitem
+ request.node.add_marker(mark)
+
+ self.assert_frame_equal(result, expected)
+
+ def test_setitem_series(self, data, full_indexer):
+ # https://github.com/pandas-dev/pandas/issues/32395
+ ser = pd.Series(data, name="data")
+ result = pd.Series(index=ser.index, dtype=object, name="data")
+
+ key = full_indexer(ser)
+ result.loc[key] = ser
+
+ # For PandasArray we expect to get unboxed to numpy
+ expected = pd.Series(data.to_numpy(), name="data")
+ self.assert_series_equal(result, expected)
+
@skip_nested
class TestParsing(BaseNumPyTests, base.BaseParsingTests):
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index 1cd352e4e0899..6edc783afb715 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -18,6 +18,7 @@
Index,
IndexSlice,
MultiIndex,
+ NaT,
Series,
SparseDtype,
Timedelta,
@@ -1348,6 +1349,19 @@ def test_loc_setitem_categorical_column_retains_dtype(self, ordered):
expected = DataFrame({"A": [1], "B": Categorical(["b"], ordered=ordered)})
tm.assert_frame_equal(result, expected)
+ def test_loc_setitem_ea_not_full_column(self):
+ # GH#39163
+ df = DataFrame({"A": range(5)})
+
+ val = date_range("2016-01-01", periods=3, tz="US/Pacific")
+
+ df.loc[[0, 1, 2], "B"] = val
+
+ bex = val.append(DatetimeIndex([NaT, NaT], dtype=val.dtype))
+ expected = DataFrame({"A": range(5), "B": bex})
+ assert expected.dtypes["B"] == val.dtype
+ tm.assert_frame_equal(df, expected)
+
class TestLocCallable:
def test_frame_loc_getitem_callable(self):
diff --git a/pandas/util/_exceptions.py b/pandas/util/_exceptions.py
index 5ca96a1f9989f..9fdfc30ef7e76 100644
--- a/pandas/util/_exceptions.py
+++ b/pandas/util/_exceptions.py
@@ -31,7 +31,7 @@ def find_stack_level() -> int:
if stack[n].function == "astype":
break
- while stack[n].function in ["astype", "apply", "_astype"]:
+ while stack[n].function in ["astype", "apply", "astype_block_compat"]:
# e.g.
# bump up Block.astype -> BlockManager.astype -> NDFrame.astype
# bump up Datetime.Array.astype -> DatetimeIndex.astype
| - [ ] 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
xref #38896 (doesn't close). In general `df[:, "A"] = foo` tries to operate in-place before falling back to casting. This makes sure we do that when `foo` is a `PandasArray`, `IntegerArray`, or `FloatingArray`
I guess could/should do the same for BooleanArray
| https://api.github.com/repos/pandas-dev/pandas/pulls/39044 | 2021-01-08T22:30:49Z | 2021-02-18T00:15:28Z | null | 2021-07-16T16:08:40Z |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.