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 |
|---|---|---|---|---|---|---|---|
TYP: remove ignore from pandas/tseries/frequencies.py II | diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py
index 522daf7188bfb..caa34a067ac69 100644
--- a/pandas/tseries/frequencies.py
+++ b/pandas/tseries/frequencies.py
@@ -140,10 +140,7 @@ def infer_freq(
>>> pd.infer_freq(idx)
'D'
"""
- from pandas.core.api import (
- DatetimeIndex,
- Index,
- )
+ from pandas.core.api import DatetimeIndex
if isinstance(index, ABCSeries):
values = index._values
@@ -172,15 +169,10 @@ def infer_freq(
inferer = _TimedeltaFrequencyInferer(index)
return inferer.get_freq()
- if isinstance(index, Index) and not isinstance(index, DatetimeIndex):
- if is_numeric_dtype(index.dtype):
- raise TypeError(
- f"cannot infer freq from a non-convertible index of dtype {index.dtype}"
- )
- # error: Incompatible types in assignment (expression has type
- # "Union[ExtensionArray, ndarray[Any, Any]]", variable has type
- # "Union[DatetimeIndex, TimedeltaIndex, Series, DatetimeLikeArrayMixin]")
- index = index._values # type: ignore[assignment]
+ elif is_numeric_dtype(index.dtype):
+ raise TypeError(
+ f"cannot infer freq from a non-convertible index of dtype {index.dtype}"
+ )
if not isinstance(index, DatetimeIndex):
index = DatetimeIndex(index)
| Related to pr #52623, which doesn't work correctly.
mypy ignore[assignment] was removed from pandas/tseries/frequencies.py | https://api.github.com/repos/pandas-dev/pandas/pulls/53120 | 2023-05-06T15:36:53Z | 2023-05-08T14:59:17Z | 2023-05-08T14:59:17Z | 2023-05-08T14:59:25Z |
REGR: read_sql dropping duplicated columns | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 1bc2fda7b8af9..c234de3e3b3ae 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -13,6 +13,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Fixed regression in :func:`read_sql` dropping columns with duplicated column names (:issue:`53117`)
- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
- Fixed regression in :meth:`DataFrame.to_string` printing a backslash at the end of the first row of data, instead of headers, when the DataFrame doesn't fit the line width (:issue:`53054`)
- Fixed regression in :meth:`MultiIndex.join` returning levels in wrong order (:issue:`53093`)
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 6a161febfe316..ebb994f92d8ad 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -161,7 +161,9 @@ def _convert_arrays_to_dataframe(
ArrowExtensionArray(pa.array(arr, from_pandas=True)) for arr in arrays
]
if arrays:
- return DataFrame(dict(zip(columns, arrays)))
+ df = DataFrame(dict(zip(list(range(len(columns))), arrays)))
+ df.columns = columns
+ return df
else:
return DataFrame(columns=columns)
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 035fda29f8ffb..77e7e6f8d6c41 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -1492,6 +1492,18 @@ def test_escaped_table_name(self):
tm.assert_frame_equal(res, df)
+ def test_read_sql_duplicate_columns(self):
+ # GH#53117
+ df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": 1})
+ df.to_sql("test_table", self.conn, index=False)
+
+ result = pd.read_sql("SELECT a, b, a +1 as a, c FROM test_table;", self.conn)
+ expected = DataFrame(
+ [[1, 0.1, 2, 1], [2, 0.2, 3, 1], [3, 0.3, 4, 1]],
+ columns=["a", "b", "a", "c"],
+ )
+ tm.assert_frame_equal(result, expected)
+
@pytest.mark.skipif(not SQLALCHEMY_INSTALLED, reason="SQLAlchemy not installed")
class TestSQLApi(SQLAlchemyMixIn, _TestSQLApi):
| - [x] closes #53117 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53118 | 2023-05-06T10:51:14Z | 2023-05-08T13:14:35Z | 2023-05-08T13:14:35Z | 2023-05-08T15:55:45Z |
REF: move SparseDtype, ArrowDtype to dtypes.dtypes | diff --git a/pandas/__init__.py b/pandas/__init__.py
index ffdd7294cace1..d11a429987ac4 100644
--- a/pandas/__init__.py
+++ b/pandas/__init__.py
@@ -108,7 +108,7 @@
DataFrame,
)
-from pandas.core.arrays.sparse import SparseDtype
+from pandas.core.dtypes.dtypes import SparseDtype
from pandas.tseries.api import infer_freq
from pandas.tseries import offsets
diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py
index 9800c960f031b..c15dd7b37be93 100644
--- a/pandas/compat/pickle_compat.py
+++ b/pandas/compat/pickle_compat.py
@@ -134,6 +134,10 @@ def load_reduce(self):
"pandas.core.indexes.base",
"Index",
),
+ ("pandas.core.arrays.sparse.dtype", "SparseDtype"): (
+ "pandas.core.dtypes.dtypes",
+ "SparseDtype",
+ ),
}
diff --git a/pandas/core/api.py b/pandas/core/api.py
index c0b828d9330b4..2cfe5ffc0170d 100644
--- a/pandas/core/api.py
+++ b/pandas/core/api.py
@@ -7,6 +7,7 @@
from pandas._libs.missing import NA
from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
CategoricalDtype,
DatetimeTZDtype,
IntervalDtype,
@@ -25,7 +26,6 @@
value_counts,
)
from pandas.core.arrays import Categorical
-from pandas.core.arrays.arrow import ArrowDtype
from pandas.core.arrays.boolean import BooleanDtype
from pandas.core.arrays.floating import (
Float32Dtype,
diff --git a/pandas/core/arrays/arrow/__init__.py b/pandas/core/arrays/arrow/__init__.py
index e7fa6fae0a5a1..58b268cbdd221 100644
--- a/pandas/core/arrays/arrow/__init__.py
+++ b/pandas/core/arrays/arrow/__init__.py
@@ -1,4 +1,3 @@
from pandas.core.arrays.arrow.array import ArrowExtensionArray
-from pandas.core.arrays.arrow.dtype import ArrowDtype
-__all__ = ["ArrowDtype", "ArrowExtensionArray"]
+__all__ = ["ArrowExtensionArray"]
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index d842e49589c4d..59c89c4a148e3 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -60,8 +60,9 @@
import pyarrow as pa
import pyarrow.compute as pc
+ from pandas.core.dtypes.dtypes import ArrowDtype
+
from pandas.core.arrays.arrow._arrow_utils import fallback_performancewarning
- from pandas.core.arrays.arrow.dtype import ArrowDtype
ARROW_CMP_FUNCS = {
"eq": pc.equal,
diff --git a/pandas/core/arrays/arrow/dtype.py b/pandas/core/arrays/arrow/dtype.py
deleted file mode 100644
index c416fbd03417a..0000000000000
--- a/pandas/core/arrays/arrow/dtype.py
+++ /dev/null
@@ -1,323 +0,0 @@
-from __future__ import annotations
-
-from datetime import (
- date,
- datetime,
- time,
- timedelta,
-)
-from decimal import Decimal
-import re
-from typing import TYPE_CHECKING
-
-import numpy as np
-
-from pandas._libs.tslibs import (
- Timedelta,
- Timestamp,
-)
-from pandas.compat import pa_version_under7p0
-from pandas.util._decorators import cache_readonly
-
-from pandas.core.dtypes.base import (
- StorageExtensionDtype,
- register_extension_dtype,
-)
-from pandas.core.dtypes.dtypes import CategoricalDtypeType
-
-if not pa_version_under7p0:
- import pyarrow as pa
-
-if TYPE_CHECKING:
- from pandas._typing import (
- DtypeObj,
- type_t,
- )
-
- from pandas.core.arrays.arrow import ArrowExtensionArray
-
-
-@register_extension_dtype
-class ArrowDtype(StorageExtensionDtype):
- """
- An ExtensionDtype for PyArrow data types.
-
- .. warning::
-
- ArrowDtype is considered experimental. The implementation and
- parts of the API may change without warning.
-
- While most ``dtype`` arguments can accept the "string"
- constructor, e.g. ``"int64[pyarrow]"``, ArrowDtype is useful
- if the data type contains parameters like ``pyarrow.timestamp``.
-
- Parameters
- ----------
- pyarrow_dtype : pa.DataType
- An instance of a `pyarrow.DataType <https://arrow.apache.org/docs/python/api/datatypes.html#factory-functions>`__.
-
- Attributes
- ----------
- pyarrow_dtype
-
- Methods
- -------
- None
-
- Returns
- -------
- ArrowDtype
-
- Examples
- --------
- >>> import pyarrow as pa
- >>> pd.ArrowDtype(pa.int64())
- int64[pyarrow]
-
- Types with parameters must be constructed with ArrowDtype.
-
- >>> pd.ArrowDtype(pa.timestamp("s", tz="America/New_York"))
- timestamp[s, tz=America/New_York][pyarrow]
- >>> pd.ArrowDtype(pa.list_(pa.int64()))
- list<item: int64>[pyarrow]
- """ # noqa: E501
-
- _metadata = ("storage", "pyarrow_dtype") # type: ignore[assignment]
-
- def __init__(self, pyarrow_dtype: pa.DataType) -> None:
- super().__init__("pyarrow")
- if pa_version_under7p0:
- raise ImportError("pyarrow>=7.0.0 is required for ArrowDtype")
- if not isinstance(pyarrow_dtype, pa.DataType):
- raise ValueError(
- f"pyarrow_dtype ({pyarrow_dtype}) must be an instance "
- f"of a pyarrow.DataType. Got {type(pyarrow_dtype)} instead."
- )
- self.pyarrow_dtype = pyarrow_dtype
-
- def __repr__(self) -> str:
- return self.name
-
- @property
- def type(self):
- """
- Returns associated scalar type.
- """
- pa_type = self.pyarrow_dtype
- if pa.types.is_integer(pa_type):
- return int
- elif pa.types.is_floating(pa_type):
- return float
- elif pa.types.is_string(pa_type) or pa.types.is_large_string(pa_type):
- return str
- elif (
- pa.types.is_binary(pa_type)
- or pa.types.is_fixed_size_binary(pa_type)
- or pa.types.is_large_binary(pa_type)
- ):
- return bytes
- elif pa.types.is_boolean(pa_type):
- return bool
- elif pa.types.is_duration(pa_type):
- if pa_type.unit == "ns":
- return Timedelta
- else:
- return timedelta
- elif pa.types.is_timestamp(pa_type):
- if pa_type.unit == "ns":
- return Timestamp
- else:
- return datetime
- elif pa.types.is_date(pa_type):
- return date
- elif pa.types.is_time(pa_type):
- return time
- elif pa.types.is_decimal(pa_type):
- return Decimal
- elif pa.types.is_dictionary(pa_type):
- # TODO: Potentially change this & CategoricalDtype.type to
- # something more representative of the scalar
- return CategoricalDtypeType
- elif pa.types.is_list(pa_type) or pa.types.is_large_list(pa_type):
- return list
- elif pa.types.is_map(pa_type):
- return dict
- elif pa.types.is_null(pa_type):
- # TODO: None? pd.NA? pa.null?
- return type(pa_type)
- else:
- raise NotImplementedError(pa_type)
-
- @property
- def name(self) -> str: # type: ignore[override]
- """
- A string identifying the data type.
- """
- return f"{str(self.pyarrow_dtype)}[{self.storage}]"
-
- @cache_readonly
- def numpy_dtype(self) -> np.dtype:
- """Return an instance of the related numpy dtype"""
- if pa.types.is_timestamp(self.pyarrow_dtype):
- # pa.timestamp(unit).to_pandas_dtype() returns ns units
- # regardless of the pyarrow timestamp units.
- # This can be removed if/when pyarrow addresses it:
- # https://github.com/apache/arrow/issues/34462
- return np.dtype(f"datetime64[{self.pyarrow_dtype.unit}]")
- if pa.types.is_duration(self.pyarrow_dtype):
- # pa.duration(unit).to_pandas_dtype() returns ns units
- # regardless of the pyarrow duration units
- # This can be removed if/when pyarrow addresses it:
- # https://github.com/apache/arrow/issues/34462
- return np.dtype(f"timedelta64[{self.pyarrow_dtype.unit}]")
- if pa.types.is_string(self.pyarrow_dtype):
- # pa.string().to_pandas_dtype() = object which we don't want
- return np.dtype(str)
- try:
- return np.dtype(self.pyarrow_dtype.to_pandas_dtype())
- except (NotImplementedError, TypeError):
- return np.dtype(object)
-
- @cache_readonly
- def kind(self) -> str:
- if pa.types.is_timestamp(self.pyarrow_dtype):
- # To mirror DatetimeTZDtype
- return "M"
- return self.numpy_dtype.kind
-
- @cache_readonly
- def itemsize(self) -> int:
- """Return the number of bytes in this dtype"""
- return self.numpy_dtype.itemsize
-
- @classmethod
- def construct_array_type(cls) -> type_t[ArrowExtensionArray]:
- """
- Return the array type associated with this dtype.
-
- Returns
- -------
- type
- """
- from pandas.core.arrays.arrow import ArrowExtensionArray
-
- return ArrowExtensionArray
-
- @classmethod
- def construct_from_string(cls, string: str) -> ArrowDtype:
- """
- Construct this type from a string.
-
- Parameters
- ----------
- string : str
- string should follow the format f"{pyarrow_type}[pyarrow]"
- e.g. int64[pyarrow]
- """
- if not isinstance(string, str):
- raise TypeError(
- f"'construct_from_string' expects a string, got {type(string)}"
- )
- if not string.endswith("[pyarrow]"):
- raise TypeError(f"'{string}' must end with '[pyarrow]'")
- if string == "string[pyarrow]":
- # Ensure Registry.find skips ArrowDtype to use StringDtype instead
- raise TypeError("string[pyarrow] should be constructed by StringDtype")
-
- base_type = string[:-9] # get rid of "[pyarrow]"
- try:
- pa_dtype = pa.type_for_alias(base_type)
- except ValueError as err:
- has_parameters = re.search(r"[\[\(].*[\]\)]", base_type)
- if has_parameters:
- # Fallback to try common temporal types
- try:
- return cls._parse_temporal_dtype_string(base_type)
- except (NotImplementedError, ValueError):
- # Fall through to raise with nice exception message below
- pass
-
- raise NotImplementedError(
- "Passing pyarrow type specific parameters "
- f"({has_parameters.group()}) in the string is not supported. "
- "Please construct an ArrowDtype object with a pyarrow_dtype "
- "instance with specific parameters."
- ) from err
- raise TypeError(f"'{base_type}' is not a valid pyarrow data type.") from err
- return cls(pa_dtype)
-
- # TODO(arrow#33642): This can be removed once supported by pyarrow
- @classmethod
- def _parse_temporal_dtype_string(cls, string: str) -> ArrowDtype:
- """
- Construct a temporal ArrowDtype from string.
- """
- # we assume
- # 1) "[pyarrow]" has already been stripped from the end of our string.
- # 2) we know "[" is present
- head, tail = string.split("[", 1)
-
- if not tail.endswith("]"):
- raise ValueError
- tail = tail[:-1]
-
- if head == "timestamp":
- assert "," in tail # otherwise type_for_alias should work
- unit, tz = tail.split(",", 1)
- unit = unit.strip()
- tz = tz.strip()
- if tz.startswith("tz="):
- tz = tz[3:]
-
- pa_type = pa.timestamp(unit, tz=tz)
- dtype = cls(pa_type)
- return dtype
-
- raise NotImplementedError(string)
-
- @property
- def _is_numeric(self) -> bool:
- """
- Whether columns with this dtype should be considered numeric.
- """
- # TODO: pa.types.is_boolean?
- return (
- pa.types.is_integer(self.pyarrow_dtype)
- or pa.types.is_floating(self.pyarrow_dtype)
- or pa.types.is_decimal(self.pyarrow_dtype)
- )
-
- @property
- def _is_boolean(self) -> bool:
- """
- Whether this dtype should be considered boolean.
- """
- return pa.types.is_boolean(self.pyarrow_dtype)
-
- def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
- # We unwrap any masked dtypes, find the common dtype we would use
- # for that, then re-mask the result.
- # Mirrors BaseMaskedDtype
- from pandas.core.dtypes.cast import find_common_type
-
- new_dtype = find_common_type(
- [
- dtype.numpy_dtype if isinstance(dtype, ArrowDtype) else dtype
- for dtype in dtypes
- ]
- )
- if not isinstance(new_dtype, np.dtype):
- return None
- try:
- pa_dtype = pa.from_numpy_dtype(new_dtype)
- return type(self)(pa_dtype)
- except NotImplementedError:
- return None
-
- def __from_arrow__(self, array: pa.Array | pa.ChunkedArray):
- """
- Construct IntegerArray/FloatingArray from pyarrow Array/ChunkedArray.
- """
- array_class = self.construct_array_type()
- arr = array.cast(self.pyarrow_dtype, safe=True)
- return array_class(arr)
diff --git a/pandas/core/arrays/sparse/__init__.py b/pandas/core/arrays/sparse/__init__.py
index 56dbc6df54fc9..adf83963aca39 100644
--- a/pandas/core/arrays/sparse/__init__.py
+++ b/pandas/core/arrays/sparse/__init__.py
@@ -8,7 +8,6 @@
SparseArray,
make_sparse_index,
)
-from pandas.core.arrays.sparse.dtype import SparseDtype
__all__ = [
"BlockIndex",
@@ -16,6 +15,5 @@
"make_sparse_index",
"SparseAccessor",
"SparseArray",
- "SparseDtype",
"SparseFrameAccessor",
]
diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py
index 4c1a6e6e219c6..eeff44cfa3c9c 100644
--- a/pandas/core/arrays/sparse/accessor.py
+++ b/pandas/core/arrays/sparse/accessor.py
@@ -8,13 +8,13 @@
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.cast import find_common_type
+from pandas.core.dtypes.dtypes import SparseDtype
from pandas.core.accessor import (
PandasDelegate,
delegate_names,
)
from pandas.core.arrays.sparse.array import SparseArray
-from pandas.core.arrays.sparse.dtype import SparseDtype
if TYPE_CHECKING:
from pandas import (
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index d03e60131fd74..4f5505015ef76 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -51,7 +51,10 @@
is_string_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.dtypes import DatetimeTZDtype
+from pandas.core.dtypes.dtypes import (
+ DatetimeTZDtype,
+ SparseDtype,
+)
from pandas.core.dtypes.generic import (
ABCIndex,
ABCSeries,
@@ -66,7 +69,6 @@
import pandas.core.algorithms as algos
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import ExtensionArray
-from pandas.core.arrays.sparse.dtype import SparseDtype
from pandas.core.base import PandasObject
import pandas.core.common as com
from pandas.core.construction import (
diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py
deleted file mode 100644
index f4f87f60cc3a7..0000000000000
--- a/pandas/core/arrays/sparse/dtype.py
+++ /dev/null
@@ -1,456 +0,0 @@
-"""Sparse Dtype"""
-from __future__ import annotations
-
-import re
-from typing import (
- TYPE_CHECKING,
- Any,
-)
-import warnings
-
-import numpy as np
-
-from pandas.errors import PerformanceWarning
-from pandas.util._exceptions import find_stack_level
-
-from pandas.core.dtypes.astype import astype_array
-from pandas.core.dtypes.base import (
- ExtensionDtype,
- register_extension_dtype,
-)
-from pandas.core.dtypes.cast import can_hold_element
-from pandas.core.dtypes.common import (
- is_bool_dtype,
- is_object_dtype,
- is_scalar,
- is_string_dtype,
- pandas_dtype,
-)
-from pandas.core.dtypes.dtypes import CategoricalDtype
-from pandas.core.dtypes.missing import (
- is_valid_na_for_dtype,
- isna,
- na_value_for_dtype,
-)
-
-from pandas.core.construction import ensure_wrapped_if_datetimelike
-
-if TYPE_CHECKING:
- from pandas._typing import (
- Dtype,
- DtypeObj,
- type_t,
- )
-
- from pandas.core.arrays.sparse.array import SparseArray
-
-
-@register_extension_dtype
-class SparseDtype(ExtensionDtype):
- """
- Dtype for data stored in :class:`SparseArray`.
-
- This dtype implements the pandas ExtensionDtype interface.
-
- Parameters
- ----------
- dtype : str, ExtensionDtype, numpy.dtype, type, default numpy.float64
- The dtype of the underlying array storing the non-fill value values.
- fill_value : scalar, optional
- The scalar value not stored in the SparseArray. By default, this
- depends on `dtype`.
-
- =========== ==========
- dtype na_value
- =========== ==========
- float ``np.nan``
- int ``0``
- bool ``False``
- datetime64 ``pd.NaT``
- timedelta64 ``pd.NaT``
- =========== ==========
-
- The default value may be overridden by specifying a `fill_value`.
-
- Attributes
- ----------
- None
-
- Methods
- -------
- None
- """
-
- # We include `_is_na_fill_value` in the metadata to avoid hash collisions
- # between SparseDtype(float, 0.0) and SparseDtype(float, nan).
- # Without is_na_fill_value in the comparison, those would be equal since
- # hash(nan) is (sometimes?) 0.
- _metadata = ("_dtype", "_fill_value", "_is_na_fill_value")
-
- def __init__(self, dtype: Dtype = np.float64, fill_value: Any = None) -> None:
- if isinstance(dtype, type(self)):
- if fill_value is None:
- fill_value = dtype.fill_value
- dtype = dtype.subtype
-
- dtype = pandas_dtype(dtype)
- if is_string_dtype(dtype):
- dtype = np.dtype("object")
- if not isinstance(dtype, np.dtype):
- # GH#53160
- raise TypeError("SparseDtype subtype must be a numpy dtype")
-
- if fill_value is None:
- fill_value = na_value_for_dtype(dtype)
-
- self._dtype = dtype
- self._fill_value = fill_value
- self._check_fill_value()
-
- def __hash__(self) -> int:
- # Python3 doesn't inherit __hash__ when a base class overrides
- # __eq__, so we explicitly do it here.
- return super().__hash__()
-
- def __eq__(self, other: Any) -> bool:
- # We have to override __eq__ to handle NA values in _metadata.
- # The base class does simple == checks, which fail for NA.
- if isinstance(other, str):
- try:
- other = self.construct_from_string(other)
- except TypeError:
- return False
-
- if isinstance(other, type(self)):
- subtype = self.subtype == other.subtype
- if self._is_na_fill_value:
- # this case is complicated by two things:
- # SparseDtype(float, float(nan)) == SparseDtype(float, np.nan)
- # SparseDtype(float, np.nan) != SparseDtype(float, pd.NaT)
- # i.e. we want to treat any floating-point NaN as equal, but
- # not a floating-point NaN and a datetime NaT.
- fill_value = (
- other._is_na_fill_value
- and isinstance(self.fill_value, type(other.fill_value))
- or isinstance(other.fill_value, type(self.fill_value))
- )
- else:
- with warnings.catch_warnings():
- # Ignore spurious numpy warning
- warnings.filterwarnings(
- "ignore",
- "elementwise comparison failed",
- category=DeprecationWarning,
- )
-
- fill_value = self.fill_value == other.fill_value
-
- return subtype and fill_value
- return False
-
- @property
- def fill_value(self):
- """
- The fill value of the array.
-
- Converting the SparseArray to a dense ndarray will fill the
- array with this value.
-
- .. warning::
-
- It's possible to end up with a SparseArray that has ``fill_value``
- values in ``sp_values``. This can occur, for example, when setting
- ``SparseArray.fill_value`` directly.
- """
- return self._fill_value
-
- def _check_fill_value(self):
- if not is_scalar(self._fill_value):
- raise ValueError(
- f"fill_value must be a scalar. Got {self._fill_value} instead"
- )
-
- # GH#23124 require fill_value and subtype to match
- val = self._fill_value
- if isna(val):
- if not is_valid_na_for_dtype(val, self.subtype):
- warnings.warn(
- "Allowing arbitrary scalar fill_value in SparseDtype is "
- "deprecated. In a future version, the fill_value must be "
- "a valid value for the SparseDtype.subtype.",
- FutureWarning,
- stacklevel=find_stack_level(),
- )
- elif isinstance(self.subtype, CategoricalDtype):
- # TODO: is this even supported? It is reached in
- # test_dtype_sparse_with_fill_value_not_present_in_data
- if self.subtype.categories is None or val not in self.subtype.categories:
- warnings.warn(
- "Allowing arbitrary scalar fill_value in SparseDtype is "
- "deprecated. In a future version, the fill_value must be "
- "a valid value for the SparseDtype.subtype.",
- FutureWarning,
- stacklevel=find_stack_level(),
- )
- else:
- dummy = np.empty(0, dtype=self.subtype)
- dummy = ensure_wrapped_if_datetimelike(dummy)
-
- if not can_hold_element(dummy, val):
- warnings.warn(
- "Allowing arbitrary scalar fill_value in SparseDtype is "
- "deprecated. In a future version, the fill_value must be "
- "a valid value for the SparseDtype.subtype.",
- FutureWarning,
- stacklevel=find_stack_level(),
- )
-
- @property
- def _is_na_fill_value(self) -> bool:
- return isna(self.fill_value)
-
- @property
- def _is_numeric(self) -> bool:
- return not is_object_dtype(self.subtype)
-
- @property
- def _is_boolean(self) -> bool:
- return is_bool_dtype(self.subtype)
-
- @property
- def kind(self) -> str:
- """
- The sparse kind. Either 'integer', or 'block'.
- """
- return self.subtype.kind
-
- @property
- def type(self):
- return self.subtype.type
-
- @property
- def subtype(self):
- return self._dtype
-
- @property
- def name(self) -> str:
- return f"Sparse[{self.subtype.name}, {repr(self.fill_value)}]"
-
- def __repr__(self) -> str:
- return self.name
-
- @classmethod
- def construct_array_type(cls) -> type_t[SparseArray]:
- """
- Return the array type associated with this dtype.
-
- Returns
- -------
- type
- """
- from pandas.core.arrays.sparse.array import SparseArray
-
- return SparseArray
-
- @classmethod
- def construct_from_string(cls, string: str) -> SparseDtype:
- """
- Construct a SparseDtype from a string form.
-
- Parameters
- ----------
- string : str
- Can take the following forms.
-
- string dtype
- ================ ============================
- 'int' SparseDtype[np.int64, 0]
- 'Sparse' SparseDtype[np.float64, nan]
- 'Sparse[int]' SparseDtype[np.int64, 0]
- 'Sparse[int, 0]' SparseDtype[np.int64, 0]
- ================ ============================
-
- It is not possible to specify non-default fill values
- with a string. An argument like ``'Sparse[int, 1]'``
- will raise a ``TypeError`` because the default fill value
- for integers is 0.
-
- Returns
- -------
- SparseDtype
- """
- if not isinstance(string, str):
- raise TypeError(
- f"'construct_from_string' expects a string, got {type(string)}"
- )
- msg = f"Cannot construct a 'SparseDtype' from '{string}'"
- if string.startswith("Sparse"):
- try:
- sub_type, has_fill_value = cls._parse_subtype(string)
- except ValueError as err:
- raise TypeError(msg) from err
- else:
- result = SparseDtype(sub_type)
- msg = (
- f"Cannot construct a 'SparseDtype' from '{string}'.\n\nIt "
- "looks like the fill_value in the string is not "
- "the default for the dtype. Non-default fill_values "
- "are not supported. Use the 'SparseDtype()' "
- "constructor instead."
- )
- if has_fill_value and str(result) != string:
- raise TypeError(msg)
- return result
- else:
- raise TypeError(msg)
-
- @staticmethod
- def _parse_subtype(dtype: str) -> tuple[str, bool]:
- """
- Parse a string to get the subtype
-
- Parameters
- ----------
- dtype : str
- A string like
-
- * Sparse[subtype]
- * Sparse[subtype, fill_value]
-
- Returns
- -------
- subtype : str
-
- Raises
- ------
- ValueError
- When the subtype cannot be extracted.
- """
- xpr = re.compile(r"Sparse\[(?P<subtype>[^,]*)(, )?(?P<fill_value>.*?)?\]$")
- m = xpr.match(dtype)
- has_fill_value = False
- if m:
- subtype = m.groupdict()["subtype"]
- has_fill_value = bool(m.groupdict()["fill_value"])
- elif dtype == "Sparse":
- subtype = "float64"
- else:
- raise ValueError(f"Cannot parse {dtype}")
- return subtype, has_fill_value
-
- @classmethod
- def is_dtype(cls, dtype: object) -> bool:
- dtype = getattr(dtype, "dtype", dtype)
- if isinstance(dtype, str) and dtype.startswith("Sparse"):
- sub_type, _ = cls._parse_subtype(dtype)
- dtype = np.dtype(sub_type)
- elif isinstance(dtype, cls):
- return True
- return isinstance(dtype, np.dtype) or dtype == "Sparse"
-
- def update_dtype(self, dtype) -> SparseDtype:
- """
- Convert the SparseDtype to a new dtype.
-
- This takes care of converting the ``fill_value``.
-
- Parameters
- ----------
- dtype : Union[str, numpy.dtype, SparseDtype]
- The new dtype to use.
-
- * For a SparseDtype, it is simply returned
- * For a NumPy dtype (or str), the current fill value
- is converted to the new dtype, and a SparseDtype
- with `dtype` and the new fill value is returned.
-
- Returns
- -------
- SparseDtype
- A new SparseDtype with the correct `dtype` and fill value
- for that `dtype`.
-
- Raises
- ------
- ValueError
- When the current fill value cannot be converted to the
- new `dtype` (e.g. trying to convert ``np.nan`` to an
- integer dtype).
-
-
- Examples
- --------
- >>> SparseDtype(int, 0).update_dtype(float)
- Sparse[float64, 0.0]
-
- >>> SparseDtype(int, 1).update_dtype(SparseDtype(float, np.nan))
- Sparse[float64, nan]
- """
- cls = type(self)
- dtype = pandas_dtype(dtype)
-
- if not isinstance(dtype, cls):
- if not isinstance(dtype, np.dtype):
- raise TypeError("sparse arrays of extension dtypes not supported")
-
- fv_asarray = np.atleast_1d(np.array(self.fill_value))
- fvarr = astype_array(fv_asarray, dtype)
- # NB: not fv_0d.item(), as that casts dt64->int
- fill_value = fvarr[0]
- dtype = cls(dtype, fill_value=fill_value)
-
- return dtype
-
- @property
- def _subtype_with_str(self):
- """
- Whether the SparseDtype's subtype should be considered ``str``.
-
- Typically, pandas will store string data in an object-dtype array.
- When converting values to a dtype, e.g. in ``.astype``, we need to
- be more specific, we need the actual underlying type.
-
- Returns
- -------
- >>> SparseDtype(int, 1)._subtype_with_str
- dtype('int64')
-
- >>> SparseDtype(object, 1)._subtype_with_str
- dtype('O')
-
- >>> dtype = SparseDtype(str, '')
- >>> dtype.subtype
- dtype('O')
-
- >>> dtype._subtype_with_str
- <class 'str'>
- """
- if isinstance(self.fill_value, str):
- return type(self.fill_value)
- return self.subtype
-
- def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
- # TODO for now only handle SparseDtypes and numpy dtypes => extend
- # with other compatible extension dtypes
- if any(
- isinstance(x, ExtensionDtype) and not isinstance(x, SparseDtype)
- for x in dtypes
- ):
- return None
-
- fill_values = [x.fill_value for x in dtypes if isinstance(x, SparseDtype)]
- fill_value = fill_values[0]
-
- # np.nan isn't a singleton, so we may end up with multiple
- # NaNs here, so we ignore the all NA case too.
- if not (len(set(fill_values)) == 1 or isna(fill_values).all()):
- warnings.warn(
- "Concatenating sparse arrays with multiple fill "
- f"values: '{fill_values}'. Picking the first and "
- "converting the rest.",
- PerformanceWarning,
- stacklevel=find_stack_level(),
- )
-
- np_dtypes = [x.subtype if isinstance(x, SparseDtype) else x for x in dtypes]
- return SparseDtype(np.find_common_type(np_dtypes, []), fill_value=fill_value)
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 08a5f9c79274b..5f859d1bc6ee6 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -58,6 +58,7 @@
pandas_dtype as pandas_dtype_func,
)
from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
BaseMaskedDtype,
CategoricalDtype,
DatetimeTZDtype,
@@ -1070,7 +1071,6 @@ def convert_dtypes(
if dtype_backend == "pyarrow":
from pandas.core.arrays.arrow.array import to_pyarrow_type
- from pandas.core.arrays.arrow.dtype import ArrowDtype
from pandas.core.arrays.string_ import StringDtype
assert not isinstance(inferred_dtype, str)
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 2c426187c83e8..3931b12e06f9b 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -28,6 +28,7 @@
ExtensionDtype,
IntervalDtype,
PeriodDtype,
+ SparseDtype,
)
from pandas.core.dtypes.generic import ABCIndex
from pandas.core.dtypes.inference import (
@@ -213,7 +214,6 @@ def is_sparse(arr) -> bool:
FutureWarning,
stacklevel=find_stack_level(),
)
- from pandas.core.arrays.sparse import SparseDtype
dtype = getattr(arr, "dtype", arr)
return isinstance(dtype, SparseDtype)
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index 7fff0f0d2d805..a3481cbe9eae1 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -3,6 +3,13 @@
"""
from __future__ import annotations
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+)
+from decimal import Decimal
import re
from typing import (
TYPE_CHECKING,
@@ -10,11 +17,15 @@
MutableMapping,
cast,
)
+import warnings
import numpy as np
import pytz
-from pandas._libs import missing as libmissing
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+)
from pandas._libs.interval import Interval
from pandas._libs.properties import cache_readonly
from pandas._libs.tslibs import (
@@ -22,6 +33,7 @@
NaT,
NaTType,
Period,
+ Timedelta,
Timestamp,
timezones,
to_offset,
@@ -31,9 +43,13 @@
PeriodDtypeBase,
abbrev_to_npy_unit,
)
+from pandas.compat import pa_version_under7p0
+from pandas.errors import PerformanceWarning
+from pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.base import (
ExtensionDtype,
+ StorageExtensionDtype,
register_extension_dtype,
)
from pandas.core.dtypes.generic import (
@@ -45,10 +61,13 @@
is_list_like,
)
+if not pa_version_under7p0:
+ import pyarrow as pa
+
if TYPE_CHECKING:
from datetime import tzinfo
- import pyarrow
+ import pyarrow as pa # noqa: F811, TCH004
from pandas._typing import (
Dtype,
@@ -69,7 +88,9 @@
IntervalArray,
PandasArray,
PeriodArray,
+ SparseArray,
)
+ from pandas.core.arrays.arrow import ArrowExtensionArray
str_type = str
@@ -606,8 +627,6 @@ def _is_boolean(self) -> bool:
return is_bool_dtype(self.categories)
def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
- from pandas.core.arrays.sparse import SparseDtype
-
# check if we have all categorical dtype with identical categories
if all(isinstance(x, CategoricalDtype) for x in dtypes):
first = dtypes[0]
@@ -821,9 +840,7 @@ def __eq__(self, other: Any) -> bool:
and tz_compare(self.tz, other.tz)
)
- def __from_arrow__(
- self, array: pyarrow.Array | pyarrow.ChunkedArray
- ) -> DatetimeArray:
+ def __from_arrow__(self, array: pa.Array | pa.ChunkedArray) -> DatetimeArray:
"""
Construct DatetimeArray from pyarrow Array/ChunkedArray.
@@ -1028,9 +1045,7 @@ def construct_array_type(cls) -> type_t[PeriodArray]:
return PeriodArray
- def __from_arrow__(
- self, array: pyarrow.Array | pyarrow.ChunkedArray
- ) -> PeriodArray:
+ def __from_arrow__(self, array: pa.Array | pa.ChunkedArray) -> PeriodArray:
"""
Construct PeriodArray from pyarrow Array/ChunkedArray.
"""
@@ -1278,9 +1293,7 @@ def is_dtype(cls, dtype: object) -> bool:
return False
return super().is_dtype(dtype)
- def __from_arrow__(
- self, array: pyarrow.Array | pyarrow.ChunkedArray
- ) -> IntervalArray:
+ def __from_arrow__(self, array: pa.Array | pa.ChunkedArray) -> IntervalArray:
"""
Construct IntervalArray from pyarrow Array/ChunkedArray.
"""
@@ -1500,3 +1513,721 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
return type(self).from_numpy_dtype(new_dtype)
except (KeyError, NotImplementedError):
return None
+
+
+@register_extension_dtype
+class SparseDtype(ExtensionDtype):
+ """
+ Dtype for data stored in :class:`SparseArray`.
+
+ This dtype implements the pandas ExtensionDtype interface.
+
+ Parameters
+ ----------
+ dtype : str, ExtensionDtype, numpy.dtype, type, default numpy.float64
+ The dtype of the underlying array storing the non-fill value values.
+ fill_value : scalar, optional
+ The scalar value not stored in the SparseArray. By default, this
+ depends on `dtype`.
+
+ =========== ==========
+ dtype na_value
+ =========== ==========
+ float ``np.nan``
+ int ``0``
+ bool ``False``
+ datetime64 ``pd.NaT``
+ timedelta64 ``pd.NaT``
+ =========== ==========
+
+ The default value may be overridden by specifying a `fill_value`.
+
+ Attributes
+ ----------
+ None
+
+ Methods
+ -------
+ None
+ """
+
+ # We include `_is_na_fill_value` in the metadata to avoid hash collisions
+ # between SparseDtype(float, 0.0) and SparseDtype(float, nan).
+ # Without is_na_fill_value in the comparison, those would be equal since
+ # hash(nan) is (sometimes?) 0.
+ _metadata = ("_dtype", "_fill_value", "_is_na_fill_value")
+
+ def __init__(self, dtype: Dtype = np.float64, fill_value: Any = None) -> None:
+ if isinstance(dtype, type(self)):
+ if fill_value is None:
+ fill_value = dtype.fill_value
+ dtype = dtype.subtype
+
+ from pandas.core.dtypes.common import (
+ is_string_dtype,
+ pandas_dtype,
+ )
+ from pandas.core.dtypes.missing import na_value_for_dtype
+
+ dtype = pandas_dtype(dtype)
+ if is_string_dtype(dtype):
+ dtype = np.dtype("object")
+ if not isinstance(dtype, np.dtype):
+ # GH#53160
+ raise TypeError("SparseDtype subtype must be a numpy dtype")
+
+ if fill_value is None:
+ fill_value = na_value_for_dtype(dtype)
+
+ self._dtype = dtype
+ self._fill_value = fill_value
+ self._check_fill_value()
+
+ def __hash__(self) -> int:
+ # Python3 doesn't inherit __hash__ when a base class overrides
+ # __eq__, so we explicitly do it here.
+ return super().__hash__()
+
+ def __eq__(self, other: Any) -> bool:
+ # We have to override __eq__ to handle NA values in _metadata.
+ # The base class does simple == checks, which fail for NA.
+ if isinstance(other, str):
+ try:
+ other = self.construct_from_string(other)
+ except TypeError:
+ return False
+
+ if isinstance(other, type(self)):
+ subtype = self.subtype == other.subtype
+ if self._is_na_fill_value:
+ # this case is complicated by two things:
+ # SparseDtype(float, float(nan)) == SparseDtype(float, np.nan)
+ # SparseDtype(float, np.nan) != SparseDtype(float, pd.NaT)
+ # i.e. we want to treat any floating-point NaN as equal, but
+ # not a floating-point NaN and a datetime NaT.
+ fill_value = (
+ other._is_na_fill_value
+ and isinstance(self.fill_value, type(other.fill_value))
+ or isinstance(other.fill_value, type(self.fill_value))
+ )
+ else:
+ with warnings.catch_warnings():
+ # Ignore spurious numpy warning
+ warnings.filterwarnings(
+ "ignore",
+ "elementwise comparison failed",
+ category=DeprecationWarning,
+ )
+
+ fill_value = self.fill_value == other.fill_value
+
+ return subtype and fill_value
+ return False
+
+ @property
+ def fill_value(self):
+ """
+ The fill value of the array.
+
+ Converting the SparseArray to a dense ndarray will fill the
+ array with this value.
+
+ .. warning::
+
+ It's possible to end up with a SparseArray that has ``fill_value``
+ values in ``sp_values``. This can occur, for example, when setting
+ ``SparseArray.fill_value`` directly.
+ """
+ return self._fill_value
+
+ def _check_fill_value(self):
+ if not lib.is_scalar(self._fill_value):
+ raise ValueError(
+ f"fill_value must be a scalar. Got {self._fill_value} instead"
+ )
+
+ from pandas.core.dtypes.cast import can_hold_element
+ from pandas.core.dtypes.missing import (
+ is_valid_na_for_dtype,
+ isna,
+ )
+
+ from pandas.core.construction import ensure_wrapped_if_datetimelike
+
+ # GH#23124 require fill_value and subtype to match
+ val = self._fill_value
+ if isna(val):
+ if not is_valid_na_for_dtype(val, self.subtype):
+ warnings.warn(
+ "Allowing arbitrary scalar fill_value in SparseDtype is "
+ "deprecated. In a future version, the fill_value must be "
+ "a valid value for the SparseDtype.subtype.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ elif isinstance(self.subtype, CategoricalDtype):
+ # TODO: is this even supported? It is reached in
+ # test_dtype_sparse_with_fill_value_not_present_in_data
+ if self.subtype.categories is None or val not in self.subtype.categories:
+ warnings.warn(
+ "Allowing arbitrary scalar fill_value in SparseDtype is "
+ "deprecated. In a future version, the fill_value must be "
+ "a valid value for the SparseDtype.subtype.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ else:
+ dummy = np.empty(0, dtype=self.subtype)
+ dummy = ensure_wrapped_if_datetimelike(dummy)
+
+ if not can_hold_element(dummy, val):
+ warnings.warn(
+ "Allowing arbitrary scalar fill_value in SparseDtype is "
+ "deprecated. In a future version, the fill_value must be "
+ "a valid value for the SparseDtype.subtype.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+
+ @property
+ def _is_na_fill_value(self) -> bool:
+ from pandas import isna
+
+ return isna(self.fill_value)
+
+ @property
+ def _is_numeric(self) -> bool:
+ return not self.subtype == object
+
+ @property
+ def _is_boolean(self) -> bool:
+ return self.subtype.kind == "b"
+
+ @property
+ def kind(self) -> str:
+ """
+ The sparse kind. Either 'integer', or 'block'.
+ """
+ return self.subtype.kind
+
+ @property
+ def type(self):
+ return self.subtype.type
+
+ @property
+ def subtype(self):
+ return self._dtype
+
+ @property
+ def name(self) -> str:
+ return f"Sparse[{self.subtype.name}, {repr(self.fill_value)}]"
+
+ def __repr__(self) -> str:
+ return self.name
+
+ @classmethod
+ def construct_array_type(cls) -> type_t[SparseArray]:
+ """
+ Return the array type associated with this dtype.
+
+ Returns
+ -------
+ type
+ """
+ from pandas.core.arrays.sparse.array import SparseArray
+
+ return SparseArray
+
+ @classmethod
+ def construct_from_string(cls, string: str) -> SparseDtype:
+ """
+ Construct a SparseDtype from a string form.
+
+ Parameters
+ ----------
+ string : str
+ Can take the following forms.
+
+ string dtype
+ ================ ============================
+ 'int' SparseDtype[np.int64, 0]
+ 'Sparse' SparseDtype[np.float64, nan]
+ 'Sparse[int]' SparseDtype[np.int64, 0]
+ 'Sparse[int, 0]' SparseDtype[np.int64, 0]
+ ================ ============================
+
+ It is not possible to specify non-default fill values
+ with a string. An argument like ``'Sparse[int, 1]'``
+ will raise a ``TypeError`` because the default fill value
+ for integers is 0.
+
+ Returns
+ -------
+ SparseDtype
+ """
+ if not isinstance(string, str):
+ raise TypeError(
+ f"'construct_from_string' expects a string, got {type(string)}"
+ )
+ msg = f"Cannot construct a 'SparseDtype' from '{string}'"
+ if string.startswith("Sparse"):
+ try:
+ sub_type, has_fill_value = cls._parse_subtype(string)
+ except ValueError as err:
+ raise TypeError(msg) from err
+ else:
+ result = SparseDtype(sub_type)
+ msg = (
+ f"Cannot construct a 'SparseDtype' from '{string}'.\n\nIt "
+ "looks like the fill_value in the string is not "
+ "the default for the dtype. Non-default fill_values "
+ "are not supported. Use the 'SparseDtype()' "
+ "constructor instead."
+ )
+ if has_fill_value and str(result) != string:
+ raise TypeError(msg)
+ return result
+ else:
+ raise TypeError(msg)
+
+ @staticmethod
+ def _parse_subtype(dtype: str) -> tuple[str, bool]:
+ """
+ Parse a string to get the subtype
+
+ Parameters
+ ----------
+ dtype : str
+ A string like
+
+ * Sparse[subtype]
+ * Sparse[subtype, fill_value]
+
+ Returns
+ -------
+ subtype : str
+
+ Raises
+ ------
+ ValueError
+ When the subtype cannot be extracted.
+ """
+ xpr = re.compile(r"Sparse\[(?P<subtype>[^,]*)(, )?(?P<fill_value>.*?)?\]$")
+ m = xpr.match(dtype)
+ has_fill_value = False
+ if m:
+ subtype = m.groupdict()["subtype"]
+ has_fill_value = bool(m.groupdict()["fill_value"])
+ elif dtype == "Sparse":
+ subtype = "float64"
+ else:
+ raise ValueError(f"Cannot parse {dtype}")
+ return subtype, has_fill_value
+
+ @classmethod
+ def is_dtype(cls, dtype: object) -> bool:
+ dtype = getattr(dtype, "dtype", dtype)
+ if isinstance(dtype, str) and dtype.startswith("Sparse"):
+ sub_type, _ = cls._parse_subtype(dtype)
+ dtype = np.dtype(sub_type)
+ elif isinstance(dtype, cls):
+ return True
+ return isinstance(dtype, np.dtype) or dtype == "Sparse"
+
+ def update_dtype(self, dtype) -> SparseDtype:
+ """
+ Convert the SparseDtype to a new dtype.
+
+ This takes care of converting the ``fill_value``.
+
+ Parameters
+ ----------
+ dtype : Union[str, numpy.dtype, SparseDtype]
+ The new dtype to use.
+
+ * For a SparseDtype, it is simply returned
+ * For a NumPy dtype (or str), the current fill value
+ is converted to the new dtype, and a SparseDtype
+ with `dtype` and the new fill value is returned.
+
+ Returns
+ -------
+ SparseDtype
+ A new SparseDtype with the correct `dtype` and fill value
+ for that `dtype`.
+
+ Raises
+ ------
+ ValueError
+ When the current fill value cannot be converted to the
+ new `dtype` (e.g. trying to convert ``np.nan`` to an
+ integer dtype).
+
+
+ Examples
+ --------
+ >>> SparseDtype(int, 0).update_dtype(float)
+ Sparse[float64, 0.0]
+
+ >>> SparseDtype(int, 1).update_dtype(SparseDtype(float, np.nan))
+ Sparse[float64, nan]
+ """
+ from pandas.core.dtypes.astype import astype_array
+ from pandas.core.dtypes.common import pandas_dtype
+
+ cls = type(self)
+ dtype = pandas_dtype(dtype)
+
+ if not isinstance(dtype, cls):
+ if not isinstance(dtype, np.dtype):
+ raise TypeError("sparse arrays of extension dtypes not supported")
+
+ fv_asarray = np.atleast_1d(np.array(self.fill_value))
+ fvarr = astype_array(fv_asarray, dtype)
+ # NB: not fv_0d.item(), as that casts dt64->int
+ fill_value = fvarr[0]
+ dtype = cls(dtype, fill_value=fill_value)
+
+ return dtype
+
+ @property
+ def _subtype_with_str(self):
+ """
+ Whether the SparseDtype's subtype should be considered ``str``.
+
+ Typically, pandas will store string data in an object-dtype array.
+ When converting values to a dtype, e.g. in ``.astype``, we need to
+ be more specific, we need the actual underlying type.
+
+ Returns
+ -------
+ >>> SparseDtype(int, 1)._subtype_with_str
+ dtype('int64')
+
+ >>> SparseDtype(object, 1)._subtype_with_str
+ dtype('O')
+
+ >>> dtype = SparseDtype(str, '')
+ >>> dtype.subtype
+ dtype('O')
+
+ >>> dtype._subtype_with_str
+ <class 'str'>
+ """
+ if isinstance(self.fill_value, str):
+ return type(self.fill_value)
+ return self.subtype
+
+ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
+ # TODO for now only handle SparseDtypes and numpy dtypes => extend
+ # with other compatible extension dtypes
+ if any(
+ isinstance(x, ExtensionDtype) and not isinstance(x, SparseDtype)
+ for x in dtypes
+ ):
+ return None
+
+ fill_values = [x.fill_value for x in dtypes if isinstance(x, SparseDtype)]
+ fill_value = fill_values[0]
+
+ from pandas import isna
+
+ # np.nan isn't a singleton, so we may end up with multiple
+ # NaNs here, so we ignore the all NA case too.
+ if not (len(set(fill_values)) == 1 or isna(fill_values).all()):
+ warnings.warn(
+ "Concatenating sparse arrays with multiple fill "
+ f"values: '{fill_values}'. Picking the first and "
+ "converting the rest.",
+ PerformanceWarning,
+ stacklevel=find_stack_level(),
+ )
+
+ np_dtypes = [x.subtype if isinstance(x, SparseDtype) else x for x in dtypes]
+ return SparseDtype(np.find_common_type(np_dtypes, []), fill_value=fill_value)
+
+
+@register_extension_dtype
+class ArrowDtype(StorageExtensionDtype):
+ """
+ An ExtensionDtype for PyArrow data types.
+
+ .. warning::
+
+ ArrowDtype is considered experimental. The implementation and
+ parts of the API may change without warning.
+
+ While most ``dtype`` arguments can accept the "string"
+ constructor, e.g. ``"int64[pyarrow]"``, ArrowDtype is useful
+ if the data type contains parameters like ``pyarrow.timestamp``.
+
+ Parameters
+ ----------
+ pyarrow_dtype : pa.DataType
+ An instance of a `pyarrow.DataType <https://arrow.apache.org/docs/python/api/datatypes.html#factory-functions>`__.
+
+ Attributes
+ ----------
+ pyarrow_dtype
+
+ Methods
+ -------
+ None
+
+ Returns
+ -------
+ ArrowDtype
+
+ Examples
+ --------
+ >>> import pyarrow as pa
+ >>> pd.ArrowDtype(pa.int64())
+ int64[pyarrow]
+
+ Types with parameters must be constructed with ArrowDtype.
+
+ >>> pd.ArrowDtype(pa.timestamp("s", tz="America/New_York"))
+ timestamp[s, tz=America/New_York][pyarrow]
+ >>> pd.ArrowDtype(pa.list_(pa.int64()))
+ list<item: int64>[pyarrow]
+ """ # noqa: E501
+
+ _metadata = ("storage", "pyarrow_dtype") # type: ignore[assignment]
+
+ def __init__(self, pyarrow_dtype: pa.DataType) -> None:
+ super().__init__("pyarrow")
+ if pa_version_under7p0:
+ raise ImportError("pyarrow>=7.0.0 is required for ArrowDtype")
+ if not isinstance(pyarrow_dtype, pa.DataType):
+ raise ValueError(
+ f"pyarrow_dtype ({pyarrow_dtype}) must be an instance "
+ f"of a pyarrow.DataType. Got {type(pyarrow_dtype)} instead."
+ )
+ self.pyarrow_dtype = pyarrow_dtype
+
+ def __repr__(self) -> str:
+ return self.name
+
+ @property
+ def type(self):
+ """
+ Returns associated scalar type.
+ """
+ pa_type = self.pyarrow_dtype
+ if pa.types.is_integer(pa_type):
+ return int
+ elif pa.types.is_floating(pa_type):
+ return float
+ elif pa.types.is_string(pa_type) or pa.types.is_large_string(pa_type):
+ return str
+ elif (
+ pa.types.is_binary(pa_type)
+ or pa.types.is_fixed_size_binary(pa_type)
+ or pa.types.is_large_binary(pa_type)
+ ):
+ return bytes
+ elif pa.types.is_boolean(pa_type):
+ return bool
+ elif pa.types.is_duration(pa_type):
+ if pa_type.unit == "ns":
+ return Timedelta
+ else:
+ return timedelta
+ elif pa.types.is_timestamp(pa_type):
+ if pa_type.unit == "ns":
+ return Timestamp
+ else:
+ return datetime
+ elif pa.types.is_date(pa_type):
+ return date
+ elif pa.types.is_time(pa_type):
+ return time
+ elif pa.types.is_decimal(pa_type):
+ return Decimal
+ elif pa.types.is_dictionary(pa_type):
+ # TODO: Potentially change this & CategoricalDtype.type to
+ # something more representative of the scalar
+ return CategoricalDtypeType
+ elif pa.types.is_list(pa_type) or pa.types.is_large_list(pa_type):
+ return list
+ elif pa.types.is_map(pa_type):
+ return dict
+ elif pa.types.is_null(pa_type):
+ # TODO: None? pd.NA? pa.null?
+ return type(pa_type)
+ else:
+ raise NotImplementedError(pa_type)
+
+ @property
+ def name(self) -> str: # type: ignore[override]
+ """
+ A string identifying the data type.
+ """
+ return f"{str(self.pyarrow_dtype)}[{self.storage}]"
+
+ @cache_readonly
+ def numpy_dtype(self) -> np.dtype:
+ """Return an instance of the related numpy dtype"""
+ if pa.types.is_timestamp(self.pyarrow_dtype):
+ # pa.timestamp(unit).to_pandas_dtype() returns ns units
+ # regardless of the pyarrow timestamp units.
+ # This can be removed if/when pyarrow addresses it:
+ # https://github.com/apache/arrow/issues/34462
+ return np.dtype(f"datetime64[{self.pyarrow_dtype.unit}]")
+ if pa.types.is_duration(self.pyarrow_dtype):
+ # pa.duration(unit).to_pandas_dtype() returns ns units
+ # regardless of the pyarrow duration units
+ # This can be removed if/when pyarrow addresses it:
+ # https://github.com/apache/arrow/issues/34462
+ return np.dtype(f"timedelta64[{self.pyarrow_dtype.unit}]")
+ if pa.types.is_string(self.pyarrow_dtype):
+ # pa.string().to_pandas_dtype() = object which we don't want
+ return np.dtype(str)
+ try:
+ return np.dtype(self.pyarrow_dtype.to_pandas_dtype())
+ except (NotImplementedError, TypeError):
+ return np.dtype(object)
+
+ @cache_readonly
+ def kind(self) -> str:
+ if pa.types.is_timestamp(self.pyarrow_dtype):
+ # To mirror DatetimeTZDtype
+ return "M"
+ return self.numpy_dtype.kind
+
+ @cache_readonly
+ def itemsize(self) -> int:
+ """Return the number of bytes in this dtype"""
+ return self.numpy_dtype.itemsize
+
+ @classmethod
+ def construct_array_type(cls) -> type_t[ArrowExtensionArray]:
+ """
+ Return the array type associated with this dtype.
+
+ Returns
+ -------
+ type
+ """
+ from pandas.core.arrays.arrow import ArrowExtensionArray
+
+ return ArrowExtensionArray
+
+ @classmethod
+ def construct_from_string(cls, string: str) -> ArrowDtype:
+ """
+ Construct this type from a string.
+
+ Parameters
+ ----------
+ string : str
+ string should follow the format f"{pyarrow_type}[pyarrow]"
+ e.g. int64[pyarrow]
+ """
+ if not isinstance(string, str):
+ raise TypeError(
+ f"'construct_from_string' expects a string, got {type(string)}"
+ )
+ if not string.endswith("[pyarrow]"):
+ raise TypeError(f"'{string}' must end with '[pyarrow]'")
+ if string == "string[pyarrow]":
+ # Ensure Registry.find skips ArrowDtype to use StringDtype instead
+ raise TypeError("string[pyarrow] should be constructed by StringDtype")
+
+ base_type = string[:-9] # get rid of "[pyarrow]"
+ try:
+ pa_dtype = pa.type_for_alias(base_type)
+ except ValueError as err:
+ has_parameters = re.search(r"[\[\(].*[\]\)]", base_type)
+ if has_parameters:
+ # Fallback to try common temporal types
+ try:
+ return cls._parse_temporal_dtype_string(base_type)
+ except (NotImplementedError, ValueError):
+ # Fall through to raise with nice exception message below
+ pass
+
+ raise NotImplementedError(
+ "Passing pyarrow type specific parameters "
+ f"({has_parameters.group()}) in the string is not supported. "
+ "Please construct an ArrowDtype object with a pyarrow_dtype "
+ "instance with specific parameters."
+ ) from err
+ raise TypeError(f"'{base_type}' is not a valid pyarrow data type.") from err
+ return cls(pa_dtype)
+
+ # TODO(arrow#33642): This can be removed once supported by pyarrow
+ @classmethod
+ def _parse_temporal_dtype_string(cls, string: str) -> ArrowDtype:
+ """
+ Construct a temporal ArrowDtype from string.
+ """
+ # we assume
+ # 1) "[pyarrow]" has already been stripped from the end of our string.
+ # 2) we know "[" is present
+ head, tail = string.split("[", 1)
+
+ if not tail.endswith("]"):
+ raise ValueError
+ tail = tail[:-1]
+
+ if head == "timestamp":
+ assert "," in tail # otherwise type_for_alias should work
+ unit, tz = tail.split(",", 1)
+ unit = unit.strip()
+ tz = tz.strip()
+ if tz.startswith("tz="):
+ tz = tz[3:]
+
+ pa_type = pa.timestamp(unit, tz=tz)
+ dtype = cls(pa_type)
+ return dtype
+
+ raise NotImplementedError(string)
+
+ @property
+ def _is_numeric(self) -> bool:
+ """
+ Whether columns with this dtype should be considered numeric.
+ """
+ # TODO: pa.types.is_boolean?
+ return (
+ pa.types.is_integer(self.pyarrow_dtype)
+ or pa.types.is_floating(self.pyarrow_dtype)
+ or pa.types.is_decimal(self.pyarrow_dtype)
+ )
+
+ @property
+ def _is_boolean(self) -> bool:
+ """
+ Whether this dtype should be considered boolean.
+ """
+ return pa.types.is_boolean(self.pyarrow_dtype)
+
+ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
+ # We unwrap any masked dtypes, find the common dtype we would use
+ # for that, then re-mask the result.
+ # Mirrors BaseMaskedDtype
+ from pandas.core.dtypes.cast import find_common_type
+
+ new_dtype = find_common_type(
+ [
+ dtype.numpy_dtype if isinstance(dtype, ArrowDtype) else dtype
+ for dtype in dtypes
+ ]
+ )
+ if not isinstance(new_dtype, np.dtype):
+ return None
+ try:
+ pa_dtype = pa.from_numpy_dtype(new_dtype)
+ return type(self)(pa_dtype)
+ except NotImplementedError:
+ return None
+
+ def __from_arrow__(self, array: pa.Array | pa.ChunkedArray):
+ """
+ Construct IntegerArray/FloatingArray from pyarrow Array/ChunkedArray.
+ """
+ array_class = self.construct_array_type()
+ arr = array.cast(self.pyarrow_dtype, safe=True)
+ return array_class(arr)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 485cc9db5ffe7..e7c09900cfbdc 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -105,7 +105,10 @@
needs_i8_conversion,
pandas_dtype,
)
-from pandas.core.dtypes.dtypes import ExtensionDtype
+from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
+ ExtensionDtype,
+)
from pandas.core.dtypes.missing import (
isna,
notna,
@@ -131,7 +134,6 @@
PeriodArray,
TimedeltaArray,
)
-from pandas.core.arrays.arrow import ArrowDtype
from pandas.core.arrays.sparse import SparseFrameAccessor
from pandas.core.construction import (
ensure_wrapped_if_datetimelike,
diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py
index 3ddc8aaf02d97..c6da7d847c363 100644
--- a/pandas/core/indexes/accessors.py
+++ b/pandas/core/indexes/accessors.py
@@ -19,6 +19,7 @@
is_list_like,
)
from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
CategoricalDtype,
DatetimeTZDtype,
PeriodDtype,
@@ -35,7 +36,6 @@
TimedeltaArray,
)
from pandas.core.arrays.arrow.array import ArrowExtensionArray
-from pandas.core.arrays.arrow.dtype import ArrowDtype
from pandas.core.base import (
NoNewAttributesMixin,
PandasObject,
diff --git a/pandas/core/interchange/column.py b/pandas/core/interchange/column.py
index fea96d861f12c..ff4ff487e23ea 100644
--- a/pandas/core/interchange/column.py
+++ b/pandas/core/interchange/column.py
@@ -9,9 +9,10 @@
from pandas.errors import NoBufferPresent
from pandas.util._decorators import cache_readonly
+from pandas.core.dtypes.dtypes import ArrowDtype
+
import pandas as pd
from pandas.api.types import is_string_dtype
-from pandas.core.arrays.arrow.dtype import ArrowDtype
from pandas.core.interchange.buffer import PandasBuffer
from pandas.core.interchange.dataframe_protocol import (
Column,
diff --git a/pandas/core/interchange/utils.py b/pandas/core/interchange/utils.py
index e92899583176f..6b690ee031471 100644
--- a/pandas/core/interchange/utils.py
+++ b/pandas/core/interchange/utils.py
@@ -11,9 +11,10 @@
from pandas._libs import lib
-from pandas.core.dtypes.dtypes import CategoricalDtype
-
-from pandas.core.arrays.arrow.dtype import ArrowDtype
+from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
+ CategoricalDtype,
+)
if typing.TYPE_CHECKING:
from pandas._typing import DtypeObj
diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index 0d2058e66cfab..15f3630b2d735 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -41,6 +41,7 @@
from pandas.core.dtypes.dtypes import (
ExtensionDtype,
PandasDtype,
+ SparseDtype,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
@@ -61,7 +62,6 @@
PandasArray,
TimedeltaArray,
)
-from pandas.core.arrays.sparse import SparseDtype
from pandas.core.construction import (
ensure_wrapped_if_datetimelike,
extract_array,
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 02f8393eed102..911cd4ae255ce 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -66,6 +66,7 @@
IntervalDtype,
PandasDtype,
PeriodDtype,
+ SparseDtype,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
@@ -104,7 +105,6 @@
PeriodArray,
TimedeltaArray,
)
-from pandas.core.arrays.sparse.dtype import SparseDtype
from pandas.core.base import PandasObject
import pandas.core.common as com
from pandas.core.computation import expressions
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index e34e7fbf1035e..cc46977cee6dc 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -29,14 +29,16 @@
needs_i8_conversion,
)
from pandas.core.dtypes.concat import concat_compat
-from pandas.core.dtypes.dtypes import ExtensionDtype
+from pandas.core.dtypes.dtypes import (
+ ExtensionDtype,
+ SparseDtype,
+)
from pandas.core.dtypes.missing import (
is_valid_na_for_dtype,
isna,
isna_all,
)
-from pandas.core.arrays.sparse import SparseDtype
from pandas.core.construction import ensure_wrapped_if_datetimelike
from pandas.core.internals.array_manager import ArrayManager
from pandas.core.internals.blocks import (
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 397f9d5b1bbe6..31827a6bcf6d0 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -40,6 +40,7 @@
from pandas.core.dtypes.dtypes import (
DatetimeTZDtype,
ExtensionDtype,
+ SparseDtype,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
@@ -53,7 +54,6 @@
import pandas.core.algorithms as algos
from pandas.core.arrays import DatetimeArray
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
-from pandas.core.arrays.sparse import SparseDtype
import pandas.core.common as com
from pandas.core.construction import (
ensure_wrapped_if_datetimelike,
diff --git a/pandas/core/methods/describe.py b/pandas/core/methods/describe.py
index 9d597b9f4b489..71693f5b9195c 100644
--- a/pandas/core/methods/describe.py
+++ b/pandas/core/methods/describe.py
@@ -32,11 +32,11 @@
is_numeric_dtype,
)
from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
DatetimeTZDtype,
ExtensionDtype,
)
-from pandas.core.arrays.arrow.dtype import ArrowDtype
from pandas.core.arrays.floating import Float64Dtype
from pandas.core.reshape.concat import concat
diff --git a/pandas/core/sparse/api.py b/pandas/core/sparse/api.py
index 2a324ebf77d9d..6650a5c4e90a0 100644
--- a/pandas/core/sparse/api.py
+++ b/pandas/core/sparse/api.py
@@ -1,6 +1,5 @@
-from pandas.core.arrays.sparse import (
- SparseArray,
- SparseDtype,
-)
+from pandas.core.dtypes.dtypes import SparseDtype
+
+from pandas.core.arrays.sparse import SparseArray
__all__ = ["SparseArray", "SparseDtype"]
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 9ffb0444f1516..c8430b832f782 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -32,7 +32,10 @@
is_object_dtype,
is_re,
)
-from pandas.core.dtypes.dtypes import CategoricalDtype
+from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
+ CategoricalDtype,
+)
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCIndex,
@@ -41,7 +44,6 @@
)
from pandas.core.dtypes.missing import isna
-from pandas.core.arrays.arrow.dtype import ArrowDtype
from pandas.core.base import NoNewAttributesMixin
from pandas.core.construction import extract_array
diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py
index 57df011590caf..e387a7cee8c56 100644
--- a/pandas/core/tools/numeric.py
+++ b/pandas/core/tools/numeric.py
@@ -22,13 +22,13 @@
is_string_dtype,
needs_i8_conversion,
)
+from pandas.core.dtypes.dtypes import ArrowDtype
from pandas.core.dtypes.generic import (
ABCIndex,
ABCSeries,
)
from pandas.core.arrays import BaseMaskedArray
-from pandas.core.arrays.arrow import ArrowDtype
from pandas.core.arrays.string_ import StringDtype
if TYPE_CHECKING:
diff --git a/pandas/tests/arrays/sparse/test_accessor.py b/pandas/tests/arrays/sparse/test_accessor.py
index ff5fc63318c38..e782b148803d7 100644
--- a/pandas/tests/arrays/sparse/test_accessor.py
+++ b/pandas/tests/arrays/sparse/test_accessor.py
@@ -6,11 +6,9 @@
import pandas.util._test_decorators as td
import pandas as pd
+from pandas import SparseDtype
import pandas._testing as tm
-from pandas.core.arrays.sparse import (
- SparseArray,
- SparseDtype,
-)
+from pandas.core.arrays.sparse import SparseArray
class TestSeriesAccessor:
diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py
index a2b8c071b9d3c..6c11979506b58 100644
--- a/pandas/tests/arrays/sparse/test_arithmetics.py
+++ b/pandas/tests/arrays/sparse/test_arithmetics.py
@@ -4,11 +4,9 @@
import pytest
import pandas as pd
+from pandas import SparseDtype
import pandas._testing as tm
-from pandas.core.arrays.sparse import (
- SparseArray,
- SparseDtype,
-)
+from pandas.core.arrays.sparse import SparseArray
@pytest.fixture(params=["integer", "block"])
diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py
index b8effc3eff1d1..883d6ea3959ff 100644
--- a/pandas/tests/arrays/sparse/test_array.py
+++ b/pandas/tests/arrays/sparse/test_array.py
@@ -6,12 +6,12 @@
from pandas._libs.sparse import IntIndex
import pandas as pd
-from pandas import isna
-import pandas._testing as tm
-from pandas.core.arrays.sparse import (
- SparseArray,
+from pandas import (
SparseDtype,
+ isna,
)
+import pandas._testing as tm
+from pandas.core.arrays.sparse import SparseArray
@pytest.fixture
diff --git a/pandas/tests/arrays/sparse/test_astype.py b/pandas/tests/arrays/sparse/test_astype.py
index d729a31668ade..83a507e679d46 100644
--- a/pandas/tests/arrays/sparse/test_astype.py
+++ b/pandas/tests/arrays/sparse/test_astype.py
@@ -3,12 +3,12 @@
from pandas._libs.sparse import IntIndex
-from pandas import Timestamp
-import pandas._testing as tm
-from pandas.core.arrays.sparse import (
- SparseArray,
+from pandas import (
SparseDtype,
+ Timestamp,
)
+import pandas._testing as tm
+from pandas.core.arrays.sparse import SparseArray
class TestAstype:
diff --git a/pandas/tests/arrays/sparse/test_constructors.py b/pandas/tests/arrays/sparse/test_constructors.py
index 29438b692fa72..efe60fe3c7a62 100644
--- a/pandas/tests/arrays/sparse/test_constructors.py
+++ b/pandas/tests/arrays/sparse/test_constructors.py
@@ -5,12 +5,12 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import isna
-import pandas._testing as tm
-from pandas.core.arrays.sparse import (
- SparseArray,
+from pandas import (
SparseDtype,
+ isna,
)
+import pandas._testing as tm
+from pandas.core.arrays.sparse import SparseArray
class TestConstructors:
diff --git a/pandas/tests/arrays/sparse/test_dtype.py b/pandas/tests/arrays/sparse/test_dtype.py
index 8337a79e10243..6c95770e9290f 100644
--- a/pandas/tests/arrays/sparse/test_dtype.py
+++ b/pandas/tests/arrays/sparse/test_dtype.py
@@ -5,7 +5,7 @@
import pytest
import pandas as pd
-from pandas.core.arrays.sparse import SparseDtype
+from pandas import SparseDtype
@pytest.mark.parametrize(
diff --git a/pandas/tests/arrays/sparse/test_indexing.py b/pandas/tests/arrays/sparse/test_indexing.py
index 5acb2167915d2..f639e9b18596c 100644
--- a/pandas/tests/arrays/sparse/test_indexing.py
+++ b/pandas/tests/arrays/sparse/test_indexing.py
@@ -2,11 +2,9 @@
import pytest
import pandas as pd
+from pandas import SparseDtype
import pandas._testing as tm
-from pandas.core.arrays.sparse import (
- SparseArray,
- SparseDtype,
-)
+from pandas.core.arrays.sparse import SparseArray
arr_data = np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6])
arr = SparseArray(arr_data)
diff --git a/pandas/tests/arrays/sparse/test_reductions.py b/pandas/tests/arrays/sparse/test_reductions.py
index 5d6d65dde69ad..f44423d5e635c 100644
--- a/pandas/tests/arrays/sparse/test_reductions.py
+++ b/pandas/tests/arrays/sparse/test_reductions.py
@@ -3,13 +3,11 @@
from pandas import (
NaT,
+ SparseDtype,
Timestamp,
isna,
)
-from pandas.core.arrays.sparse import (
- SparseArray,
- SparseDtype,
-)
+from pandas.core.arrays.sparse import SparseArray
class TestReductions:
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index 1cc10d14b904f..155c61508b706 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -33,13 +33,11 @@
DatetimeIndex,
IntervalIndex,
Series,
+ SparseDtype,
date_range,
)
import pandas._testing as tm
-from pandas.core.arrays.sparse import (
- SparseArray,
- SparseDtype,
-)
+from pandas.core.arrays.sparse import SparseArray
class Base:
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 5078a4e8078f8..f18ff45c011e2 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -40,7 +40,10 @@
)
from pandas.errors import PerformanceWarning
-from pandas.core.dtypes.dtypes import CategoricalDtypeType
+from pandas.core.dtypes.dtypes import (
+ ArrowDtype,
+ CategoricalDtypeType,
+)
import pandas as pd
import pandas._testing as tm
@@ -59,8 +62,6 @@
from pandas.core.arrays.arrow.array import ArrowExtensionArray
-from pandas.core.arrays.arrow.dtype import ArrowDtype # isort:skip
-
@pytest.fixture(params=tm.ALL_PYARROW_DTYPES, ids=str)
def dtype(request):
diff --git a/pandas/tests/reshape/test_get_dummies.py b/pandas/tests/reshape/test_get_dummies.py
index 6e943863072f1..3bfff56cfedf2 100644
--- a/pandas/tests/reshape/test_get_dummies.py
+++ b/pandas/tests/reshape/test_get_dummies.py
@@ -13,13 +13,11 @@
DataFrame,
RangeIndex,
Series,
+ SparseDtype,
get_dummies,
)
import pandas._testing as tm
-from pandas.core.arrays.sparse import (
- SparseArray,
- SparseDtype,
-)
+from pandas.core.arrays.sparse import SparseArray
class TestGetDummies:
diff --git a/pandas/util/__init__.py b/pandas/util/__init__.py
index 89ac6e2963e98..8fe928ed6c5cf 100644
--- a/pandas/util/__init__.py
+++ b/pandas/util/__init__.py
@@ -1,11 +1,25 @@
-# pyright: reportUnusedImport = false
-from pandas.util._decorators import ( # noqa: F401
- Appender,
- Substitution,
- cache_readonly,
-)
-
-from pandas.core.util.hashing import ( # noqa: F401
- hash_array,
- hash_pandas_object,
-)
+def __getattr__(key: str):
+ # These imports need to be lazy to avoid circular import errors
+ if key == "hash_array":
+ from pandas.core.util.hashing import hash_array
+
+ return hash_array
+ if key == "hash_pandas_object":
+ from pandas.core.util.hashing import hash_pandas_object
+
+ return hash_pandas_object
+ if key == "Appender":
+ from pandas.util._decorators import Appender
+
+ return Appender
+ if key == "Substitution":
+ from pandas.util._decorators import Substitution
+
+ return Substitution
+
+ if key == "cache_readonly":
+ from pandas.util._decorators import cache_readonly
+
+ return cache_readonly
+
+ raise AttributeError(f"module 'pandas.util' has no attribute '{key}'")
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53116 | 2023-05-05T22:54:17Z | 2023-05-15T20:44:28Z | 2023-05-15T20:44:28Z | 2023-05-15T20:50:42Z |
Backport PR #53102 on branch 2.0.x (REGR: MultiIndex.join not resorting levels of new index) | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index ae251f25de578..7864791f8bc59 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -15,6 +15,8 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
- Fixed regression in :meth:`DataFrame.to_string` printing a backslash at the end of the first row of data, instead of headers, when the DataFrame doesn't fit the line width (:issue:`53054`)
+- Fixed regression in :meth:`MultiIndex.join` returning levels in wrong order (:issue:`53093`)
+-
.. ---------------------------------------------------------------------------
.. _whatsnew_202.bug_fixes:
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 890ac084680a1..e2b8400188136 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4877,7 +4877,7 @@ def _wrap_joined_index(
mask = lidx == -1
join_idx = self.take(lidx)
right = other.take(ridx)
- join_index = join_idx.putmask(mask, right)
+ join_index = join_idx.putmask(mask, right)._sort_levels_monotonic()
return join_index.set_names(name) # type: ignore[return-value]
else:
name = get_op_result_name(self, other)
diff --git a/pandas/tests/indexes/multi/test_join.py b/pandas/tests/indexes/multi/test_join.py
index 4fff862961920..c5a3512113655 100644
--- a/pandas/tests/indexes/multi/test_join.py
+++ b/pandas/tests/indexes/multi/test_join.py
@@ -257,3 +257,15 @@ def test_join_dtypes_all_nan(any_numeric_ea_dtype):
]
)
tm.assert_index_equal(result, expected)
+
+
+def test_join_index_levels():
+ # GH#53093
+ midx = midx = MultiIndex.from_tuples([("a", "2019-02-01"), ("a", "2019-02-01")])
+ midx2 = MultiIndex.from_tuples([("a", "2019-01-31")])
+ result = midx.join(midx2, how="outer")
+ expected = MultiIndex.from_tuples(
+ [("a", "2019-01-31"), ("a", "2019-02-01"), ("a", "2019-02-01")]
+ )
+ tm.assert_index_equal(result.levels[1], expected.levels[1])
+ tm.assert_index_equal(result, expected)
| Backport PR #53102: REGR: MultiIndex.join not resorting levels of new index | https://api.github.com/repos/pandas-dev/pandas/pulls/53113 | 2023-05-05T22:24:35Z | 2023-05-06T14:42:11Z | 2023-05-06T14:42:11Z | 2023-05-06T14:42:11Z |
TYP: remove mypy ignore from pandas/core/construction.py | diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index 7e03d2ec8092e..9b4d67a20a7cd 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -502,9 +502,7 @@ def sanitize_masked_array(data: ma.MaskedArray) -> np.ndarray:
if mask.any():
dtype, fill_value = maybe_promote(data.dtype, np.nan)
dtype = cast(np.dtype, dtype)
- # Incompatible types in assignment (expression has type "ndarray[Any,
- # dtype[Any]]", variable has type "MaskedArray[Any, Any]")
- data = data.astype(dtype, copy=True) # type: ignore[assignment]
+ data = ma.asarray(data.astype(dtype, copy=True))
data.soften_mask() # set hardmask False if it was True
data[mask] = fill_value
else:
| Related to #37715
mypy ignore[assignment] was removed from pandas/core/construction.py | https://api.github.com/repos/pandas-dev/pandas/pulls/53112 | 2023-05-05T21:01:14Z | 2023-05-06T17:29:30Z | 2023-05-06T17:29:30Z | 2023-05-06T17:29:30Z |
Backport PR #53055 on branch 2.0.x (BUG: Fix regression when printing backslash in DataFrame.to_string) | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 726ff60f7a197..ae251f25de578 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -14,7 +14,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
--
+- Fixed regression in :meth:`DataFrame.to_string` printing a backslash at the end of the first row of data, instead of headers, when the DataFrame doesn't fit the line width (:issue:`53054`)
.. ---------------------------------------------------------------------------
.. _whatsnew_202.bug_fixes:
diff --git a/pandas/io/formats/string.py b/pandas/io/formats/string.py
index 071afc059b166..c143988bdc885 100644
--- a/pandas/io/formats/string.py
+++ b/pandas/io/formats/string.py
@@ -135,12 +135,6 @@ def _join_multiline(self, strcols_input: Iterable[list[str]]) -> str:
col_bins = _binify(col_widths, lwidth)
nbins = len(col_bins)
- if self.fmt.is_truncated_vertically:
- assert self.fmt.max_rows_fitted is not None
- nrows = self.fmt.max_rows_fitted + 1
- else:
- nrows = len(self.frame)
-
str_lst = []
start = 0
for i, end in enumerate(col_bins):
@@ -148,6 +142,7 @@ def _join_multiline(self, strcols_input: Iterable[list[str]]) -> str:
if self.fmt.index:
row.insert(0, idx)
if nbins > 1:
+ nrows = len(row[-1])
if end <= len(strcols) and i < nbins - 1:
row.append([" \\"] + [" "] * (nrows - 1))
else:
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index 0d84ecf955700..fcb7f6657beac 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -1397,25 +1397,100 @@ def test_to_string_no_index(self):
assert df_s == expected
def test_to_string_line_width_no_index(self):
- # GH 13998, GH 22505, # GH 49230
+ # GH 13998, GH 22505
df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
df_s = df.to_string(line_width=1, index=False)
- expected = " x \n 1 \\\n 2 \n 3 \n\n y \n 4 \n 5 \n 6 "
+ expected = " x \\\n 1 \n 2 \n 3 \n\n y \n 4 \n 5 \n 6 "
assert df_s == expected
df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})
df_s = df.to_string(line_width=1, index=False)
- expected = " x \n11 \\\n22 \n33 \n\n y \n 4 \n 5 \n 6 "
+ expected = " x \\\n11 \n22 \n33 \n\n y \n 4 \n 5 \n 6 "
assert df_s == expected
df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})
df_s = df.to_string(line_width=1, index=False)
- expected = " x \n 11 \\\n 22 \n-33 \n\n y \n 4 \n 5 \n-6 "
+ expected = " x \\\n 11 \n 22 \n-33 \n\n y \n 4 \n 5 \n-6 "
+
+ assert df_s == expected
+
+ def test_to_string_line_width_no_header(self):
+ # GH 53054
+ df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1, header=False)
+ expected = "0 1 \\\n1 2 \n2 3 \n\n0 4 \n1 5 \n2 6 "
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1, header=False)
+ expected = "0 11 \\\n1 22 \n2 33 \n\n0 4 \n1 5 \n2 6 "
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})
+
+ df_s = df.to_string(line_width=1, header=False)
+ expected = "0 11 \\\n1 22 \n2 -33 \n\n0 4 \n1 5 \n2 -6 "
+
+ assert df_s == expected
+
+ def test_to_string_line_width_no_index_no_header(self):
+ # GH 53054
+ df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1, index=False, header=False)
+ expected = "1 \\\n2 \n3 \n\n4 \n5 \n6 "
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1, index=False, header=False)
+ expected = "11 \\\n22 \n33 \n\n4 \n5 \n6 "
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})
+
+ df_s = df.to_string(line_width=1, index=False, header=False)
+ expected = " 11 \\\n 22 \n-33 \n\n 4 \n 5 \n-6 "
+
+ assert df_s == expected
+
+ def test_to_string_line_width_with_both_index_and_header(self):
+ # GH 53054
+ df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1)
+ expected = (
+ " x \\\n0 1 \n1 2 \n2 3 \n\n y \n0 4 \n1 5 \n2 6 "
+ )
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1)
+ expected = (
+ " x \\\n0 11 \n1 22 \n2 33 \n\n y \n0 4 \n1 5 \n2 6 "
+ )
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})
+
+ df_s = df.to_string(line_width=1)
+ expected = (
+ " x \\\n0 11 \n1 22 \n2 -33 \n\n y \n0 4 \n1 5 \n2 -6 "
+ )
assert df_s == expected
| Backport PR #53055: BUG: Fix regression when printing backslash in DataFrame.to_string | https://api.github.com/repos/pandas-dev/pandas/pulls/53107 | 2023-05-05T17:16:08Z | 2023-05-05T19:26:53Z | 2023-05-05T19:26:53Z | 2023-05-05T19:26:54Z |
CLN: avoid upcasting in tests where unnecessary (PDEP-6 precursor) | diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py
index a1939de0d2a8d..cfc42e81a4234 100644
--- a/pandas/tests/frame/indexing/test_where.py
+++ b/pandas/tests/frame/indexing/test_where.py
@@ -328,15 +328,14 @@ def test_where_bug_mixed(self, any_signed_int_numpy_dtype):
)
expected = DataFrame(
- {"a": [np.nan, np.nan, 3.0, 4.0], "b": [4.0, 3.0, np.nan, np.nan]},
- dtype="float64",
- )
+ {"a": [-1, -1, 3, 4], "b": [4.0, 3.0, -1, -1]},
+ ).astype({"a": any_signed_int_numpy_dtype, "b": "float64"})
- result = df.where(df > 2, np.nan)
+ result = df.where(df > 2, -1)
tm.assert_frame_equal(result, expected)
result = df.copy()
- return_value = result.where(result > 2, np.nan, inplace=True)
+ return_value = result.where(result > 2, -1, inplace=True)
assert return_value is None
tm.assert_frame_equal(result, expected)
@@ -1028,7 +1027,7 @@ def test_where_int_overflow(replacement):
def test_where_inplace_no_other():
# GH#51685
- df = DataFrame({"a": [1, 2], "b": ["x", "y"]})
+ df = DataFrame({"a": [1.0, 2.0], "b": ["x", "y"]})
cond = DataFrame({"a": [True, False], "b": [False, True]})
df.where(cond, inplace=True)
expected = DataFrame({"a": [1, np.nan], "b": [np.nan, "y"]})
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index bf817a1db73c4..b4cb7abbd418f 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -429,6 +429,7 @@ def test_set_index_nan(self):
def test_multi_assign(self):
# GH 3626, an assignment of a sub-df to a df
+ # set float64 to avoid upcast when setting nan
df = DataFrame(
{
"FC": ["a", "b", "a", "b", "a", "b"],
@@ -436,7 +437,7 @@ def test_multi_assign(self):
"col1": list(range(6)),
"col2": list(range(6, 12)),
}
- )
+ ).astype({"col2": "float64"})
df.iloc[1, 0] = np.nan
df2 = df.copy()
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index 3f0d530a1cbd4..3aab884f06131 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -863,7 +863,8 @@ def test_loc_setitem_with_scalar_index(self, indexer, value):
# assigning like "df.loc[0, ['A']] = ['Z']" should be evaluated
# elementwisely, not using "setter('A', ['Z'])".
- df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
+ # Set object dtype to avoid upcast when setting 'Z'
+ df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"]).astype({"A": object})
df.loc[0, indexer] = value
result = df.loc[0, "A"]
@@ -1524,7 +1525,8 @@ def test_loc_setitem_td64_non_nano(self):
def test_loc_setitem_2d_to_1d_raises(self):
data = np.random.randn(2, 2)
- ser = Series(range(2))
+ # float64 dtype to avoid upcast when trying to set float data
+ ser = Series(range(2), dtype="float64")
msg = "|".join(
[
diff --git a/pandas/tests/interchange/test_impl.py b/pandas/tests/interchange/test_impl.py
index 83543e3e1ea46..606f1374a61ce 100644
--- a/pandas/tests/interchange/test_impl.py
+++ b/pandas/tests/interchange/test_impl.py
@@ -171,7 +171,7 @@ def test_missing_from_masked():
{
"x": np.array([1.0, 2.0, 3.0, 4.0, 0.0]),
"y": np.array([1.5, 2.5, 3.5, 4.5, 0]),
- "z": np.array([True, False, True, True, True]),
+ "z": np.array([1.0, 0.0, 1.0, 1.0, 1.0]),
}
)
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index 39cbf2b7bac10..9df607cb6c64c 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -61,7 +61,8 @@ def test_setitem_multiindex_empty_slice(self):
def test_setitem_with_string_index(self):
# GH#23451
- ser = Series([1, 2, 3], index=["Date", "b", "other"])
+ # Set object dtype to avoid upcast when setting date.today()
+ ser = Series([1, 2, 3], index=["Date", "b", "other"], dtype=object)
ser["Date"] = date.today()
assert ser.Date == date.today()
assert ser["Date"] == date.today()
@@ -459,7 +460,8 @@ def test_setitem_callable_other(self):
# GH#13299
inc = lambda x: x + 1
- ser = Series([1, 2, -1, 4])
+ # set object dtype to avoid upcast when setting inc
+ ser = Series([1, 2, -1, 4], dtype=object)
ser[ser < 0] = inc
expected = Series([1, 2, inc, 4])
| another precursor to PDEP6, similar to https://github.com/pandas-dev/pandas/pull/52957
turns out there were even more of these which could be factored upon further inspection | https://api.github.com/repos/pandas-dev/pandas/pulls/53104 | 2023-05-05T14:36:58Z | 2023-05-05T17:43:55Z | 2023-05-05T17:43:55Z | 2023-05-05T21:37:01Z |
DEPR: stricter downcast values in fillna | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index da1b2e750392c..d29aa8d8a2d1d 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -259,6 +259,7 @@ Deprecations
- Deprecated unused "closed" and "normalize" keywords in the :class:`DatetimeIndex` constructor (:issue:`52628`)
- Deprecated unused "closed" keyword in the :class:`TimedeltaIndex` constructor (:issue:`52628`)
- Deprecated logical operation between two non boolean :class:`Series` with different indexes always coercing the result to bool dtype. In a future version, this will maintain the return type of the inputs. (:issue:`52500`, :issue:`52538`)
+- Deprecated allowing ``downcast`` keyword other than ``None``, ``False``, "infer", or a dict with these as values in :meth:`Series.fillna`, :meth:`DataFrame.fillna` (:issue:`40988`)
- Deprecated constructing :class:`SparseArray` from scalar data, pass a sequence instead (:issue:`53039`)
-
@@ -360,7 +361,7 @@ Indexing
Missing
^^^^^^^
--
+- Bug in :meth:`Series.interpolate` and :meth:`DataFrame.interpolate` failing to raise on invalid ``downcast`` keyword, which can be only ``None`` or "infer" (:issue:`53103`)
-
MultiIndex
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 4eb29428b7dd1..64f664c76927b 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6972,6 +6972,25 @@ def fillna(
inplace = validate_bool_kwarg(inplace, "inplace")
value, method = validate_fillna_kwargs(value, method)
+ if isinstance(downcast, dict):
+ # GH#40988
+ for dc in downcast.values():
+ if dc is not None and dc is not False and dc != "infer":
+ warnings.warn(
+ "downcast entries other than None, False, and 'infer' "
+ "are deprecated and will raise in a future version",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ elif downcast is not None and downcast is not False and downcast != "infer":
+ # GH#40988
+ warnings.warn(
+ "downcast other than None, False, and 'infer' are deprecated "
+ "and will raise in a future version",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+
# set the default here, so functions examining the signaure
# can detect if something was set (e.g. in groupby) (GH9221)
if axis is None:
@@ -7548,7 +7567,7 @@ def interpolate(
inplace: bool_t = False,
limit_direction: Literal["forward", "backward", "both"] | None = None,
limit_area: Literal["inside", "outside"] | None = None,
- downcast: str | None = None,
+ downcast: Literal["infer"] | None = None,
**kwargs,
) -> Self | None:
"""
@@ -7746,6 +7765,9 @@ def interpolate(
3 16.0
Name: d, dtype: float64
"""
+ if downcast is not None and downcast != "infer":
+ raise ValueError("downcast must be either None or 'infer'")
+
inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 85463d803b9a7..8d5f4d542cf72 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -7,6 +7,7 @@
Any,
Callable,
Iterable,
+ Literal,
Sequence,
cast,
final,
@@ -1327,7 +1328,7 @@ def interpolate(
limit_direction: str = "forward",
limit_area: str | None = None,
fill_value: Any | None = None,
- downcast: str | None = None,
+ downcast: Literal["infer"] | None = None,
using_cow: bool = False,
**kwargs,
) -> list[Block]:
diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py
index d80c3c0da9935..027e12392206b 100644
--- a/pandas/tests/frame/methods/test_fillna.py
+++ b/pandas/tests/frame/methods/test_fillna.py
@@ -297,7 +297,11 @@ def test_fillna_downcast_noop(self, frame_or_series):
# 2) _can_hold_na + noop + not can_hold_element
obj = frame_or_series([1, 2, 3], dtype=np.int64)
- res = obj.fillna("foo", downcast=np.dtype(np.int32))
+
+ msg = "downcast other than None, False, and 'infer' are deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#40988
+ res = obj.fillna("foo", downcast=np.dtype(np.int32))
expected = obj.astype(np.int32)
tm.assert_equal(res, expected)
@@ -306,7 +310,9 @@ def test_fillna_downcast_noop(self, frame_or_series):
expected2 = obj # get back int64
tm.assert_equal(res2, expected2)
- res3 = obj2.fillna("foo", downcast=np.dtype(np.int32))
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#40988
+ res3 = obj2.fillna("foo", downcast=np.dtype(np.int32))
tm.assert_equal(res3, expected)
@pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]])
@@ -605,7 +611,10 @@ def test_fill_corner(self, float_frame, float_string_frame):
def test_fillna_downcast_dict(self):
# GH#40809
df = DataFrame({"col1": [1, np.nan]})
- result = df.fillna({"col1": 2}, downcast={"col1": "int64"})
+
+ msg = "downcast entries other than None, False, and 'infer' are deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.fillna({"col1": 2}, downcast={"col1": "int64"})
expected = DataFrame({"col1": [1, 2]})
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py
index d6da967106fe6..2b54c34096152 100644
--- a/pandas/tests/frame/methods/test_interpolate.py
+++ b/pandas/tests/frame/methods/test_interpolate.py
@@ -151,6 +151,23 @@ def test_interp_combo(self):
expected = Series([1, 2, 3, 4], name="A")
tm.assert_series_equal(result, expected)
+ def test_inerpolate_invalid_downcast(self):
+ # GH#53103
+ df = DataFrame(
+ {
+ "A": [1.0, 2.0, np.nan, 4.0],
+ "B": [1, 4, 9, np.nan],
+ "C": [1, 2, 3, 5],
+ "D": list("abcd"),
+ }
+ )
+
+ msg = "downcast must be either None or 'infer'"
+ with pytest.raises(ValueError, match=msg):
+ df.interpolate(downcast="int64")
+ with pytest.raises(ValueError, match=msg):
+ df["A"].interpolate(downcast="int64")
+
def test_interp_nan_idx(self):
df = DataFrame({"A": [1, 2, np.nan, 4], "B": [np.nan, 2, 3, 4]})
df = df.set_index("A")
| xref #40988 (doesn't close) | https://api.github.com/repos/pandas-dev/pandas/pulls/53103 | 2023-05-05T14:04:32Z | 2023-05-05T19:25:54Z | 2023-05-05T19:25:54Z | 2023-05-05T19:58:51Z |
REGR: MultiIndex.join not resorting levels of new index | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 7dc00e8e4bfeb..1bc2fda7b8af9 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -15,6 +15,8 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
- Fixed regression in :meth:`DataFrame.to_string` printing a backslash at the end of the first row of data, instead of headers, when the DataFrame doesn't fit the line width (:issue:`53054`)
+- Fixed regression in :meth:`MultiIndex.join` returning levels in wrong order (:issue:`53093`)
+-
.. ---------------------------------------------------------------------------
.. _whatsnew_202.bug_fixes:
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 841d8bb0749d0..98e71cff09823 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4907,7 +4907,7 @@ def _wrap_joined_index(
mask = lidx == -1
join_idx = self.take(lidx)
right = other.take(ridx)
- join_index = join_idx.putmask(mask, right)
+ join_index = join_idx.putmask(mask, right)._sort_levels_monotonic()
return join_index.set_names(name) # type: ignore[return-value]
else:
name = get_op_result_name(self, other)
diff --git a/pandas/tests/indexes/multi/test_join.py b/pandas/tests/indexes/multi/test_join.py
index 4fff862961920..c5a3512113655 100644
--- a/pandas/tests/indexes/multi/test_join.py
+++ b/pandas/tests/indexes/multi/test_join.py
@@ -257,3 +257,15 @@ def test_join_dtypes_all_nan(any_numeric_ea_dtype):
]
)
tm.assert_index_equal(result, expected)
+
+
+def test_join_index_levels():
+ # GH#53093
+ midx = midx = MultiIndex.from_tuples([("a", "2019-02-01"), ("a", "2019-02-01")])
+ midx2 = MultiIndex.from_tuples([("a", "2019-01-31")])
+ result = midx.join(midx2, how="outer")
+ expected = MultiIndex.from_tuples(
+ [("a", "2019-01-31"), ("a", "2019-02-01"), ("a", "2019-02-01")]
+ )
+ tm.assert_index_equal(result.levels[1], expected.levels[1])
+ tm.assert_index_equal(result, expected)
| - [x] closes #53093 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Not resorting causes all kinds of problems when indexing | https://api.github.com/repos/pandas-dev/pandas/pulls/53102 | 2023-05-05T13:57:17Z | 2023-05-05T19:26:24Z | 2023-05-05T19:26:24Z | 2023-05-14T16:20:32Z |
TYP: added explanation of the join methods within df.align | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 09f5e0542db18..017fb44413c8f 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -9471,6 +9471,14 @@ def align(
----------
other : DataFrame or Series
join : {{'outer', 'inner', 'left', 'right'}}, default 'outer'
+ Type of alignment to be performed.
+
+ * left: use only keys from left frame, preserve key order.
+ * right: use only keys from right frame, preserve key order.
+ * outer: use union of keys from both frames, sort keys lexicographically.
+ * inner: use intersection of keys from both frames,
+ preserve the order of the left keys.
+
axis : allowed axis of the other object, default None
Align on index (0), columns (1), or both (None).
level : int or level name, default None
| - closes #53092
Added type annotations of the join methods within df.align - ([here](https://github.com/Antony-evm/pandas-aevmorfop/blob/0.21.x/pandas/core/generic.py))
from join : {{'outer', 'inner', 'left', 'right'}}, default 'outer'
To
join : {{'outer', 'inner', 'left', 'right'}}, default 'outer'
Type of alignment to be performed.
left: use only keys from left frame, preserve key order.
right: use only keys from right frame, preserve key order.
outer: use union of keys from both frames, sort keys lexicographically.
inner: use intersection of keys from both frames, preserve the order of the left keys.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53101 | 2023-05-05T13:36:47Z | 2023-05-09T16:43:39Z | 2023-05-09T16:43:39Z | 2023-05-09T16:43:47Z |
Fix bug #37782 | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 36b2aa3c28da5..8fac2f7737fc3 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -374,6 +374,7 @@ I/O
^^^
- :meth:`DataFrame.to_orc` now raising ``ValueError`` when non-default :class:`Index` is given (:issue:`51828`)
- :meth:`DataFrame.to_sql` now raising ``ValueError`` when the name param is left empty while using SQLAlchemy to connect (:issue:`52675`)
+- Bug in :func:`json_normalize`, fix json_normalize cannot parse metadata fields list type (:issue:`37782`)
- Bug in :func:`read_hdf` not properly closing store after a ``IndexError`` is raised (:issue:`52781`)
- Bug in :func:`read_html`, style elements were read into DataFrames (:issue:`52197`)
- Bug in :func:`read_html`, tail texts were removed together with elements containing ``display:none`` style (:issue:`51629`)
diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py
index 0937828b00e38..459b4035627cc 100644
--- a/pandas/io/json/_normalize.py
+++ b/pandas/io/json/_normalize.py
@@ -535,5 +535,15 @@ def _recursive_extract(data, path, seen_meta, level: int = 0) -> None:
raise ValueError(
f"Conflicting metadata name {k}, need distinguishing prefix "
)
- result[k] = np.array(v, dtype=object).repeat(lengths)
+ # GH 37782
+
+ values = np.array(v, dtype=object)
+
+ if values.ndim > 1:
+ # GH 37782
+ values = np.empty((len(v),), dtype=object)
+ for i, v in enumerate(v):
+ values[i] = v
+
+ result[k] = values.repeat(lengths)
return result
diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py
index 78181fe2c4729..316f262885424 100644
--- a/pandas/tests/io/json/test_normalize.py
+++ b/pandas/tests/io/json/test_normalize.py
@@ -170,6 +170,20 @@ def test_simple_normalize(self, state_data):
tm.assert_frame_equal(result, expected)
+ def test_fields_list_type_normalize(self):
+ parse_metadata_fields_list_type = [
+ {"values": [1, 2, 3], "metadata": {"listdata": [1, 2]}}
+ ]
+ result = json_normalize(
+ parse_metadata_fields_list_type,
+ record_path=["values"],
+ meta=[["metadata", "listdata"]],
+ )
+ expected = DataFrame(
+ {0: [1, 2, 3], "metadata.listdata": [[1, 2], [1, 2], [1, 2]]}
+ )
+ tm.assert_frame_equal(result, expected)
+
def test_empty_array(self):
result = json_normalize([])
expected = DataFrame()
| - [X] closes #37782
- [X] [Tests added and passed]
- [X] All [code checks passed]
- [X] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53099 | 2023-05-05T11:14:25Z | 2023-05-08T16:44:34Z | 2023-05-08T16:44:33Z | 2023-05-08T16:44:40Z |
REF: define _header_line and have_mi_columns non-dynamically | diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index 4e1bcf54c0ae9..36d5ef7111685 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -365,6 +365,17 @@ def _convert_data(
clean_dtypes,
)
+ @cache_readonly
+ def _have_mi_columns(self) -> bool:
+ if self.header is None:
+ return False
+
+ header = self.header
+ if isinstance(header, (list, tuple, np.ndarray)):
+ return len(header) > 1
+ else:
+ return False
+
def _infer_columns(
self,
) -> tuple[list[list[Scalar | None]], int, set[Scalar | None]]:
@@ -372,18 +383,16 @@ def _infer_columns(
num_original_columns = 0
clear_buffer = True
unnamed_cols: set[Scalar | None] = set()
- self._header_line = None
if self.header is not None:
header = self.header
+ have_mi_columns = self._have_mi_columns
if isinstance(header, (list, tuple, np.ndarray)):
- have_mi_columns = len(header) > 1
# we have a mi columns, so read an extra line
if have_mi_columns:
header = list(header) + [header[-1] + 1]
else:
- have_mi_columns = False
header = [header]
columns: list[list[Scalar | None]] = []
@@ -531,27 +540,14 @@ def _infer_columns(
columns, columns[0], num_original_columns
)
else:
- try:
- line = self._buffered_line()
-
- except StopIteration as err:
- if not names:
- raise EmptyDataError("No columns to parse from file") from err
-
- line = names[:]
-
- # Store line, otherwise it is lost for guessing the index
- self._header_line = line
- ncols = len(line)
+ ncols = len(self._header_line)
num_original_columns = ncols
if not names:
columns = [list(range(ncols))]
- columns = self._handle_usecols(
- columns, columns[0], num_original_columns
- )
- elif self.usecols is None or len(names) >= num_original_columns:
- columns = self._handle_usecols([names], names, num_original_columns)
+ columns = self._handle_usecols(columns, columns[0], ncols)
+ elif self.usecols is None or len(names) >= ncols:
+ columns = self._handle_usecols([names], names, ncols)
num_original_columns = len(names)
elif not callable(self.usecols) and len(names) != len(self.usecols):
raise ValueError(
@@ -560,12 +556,26 @@ def _infer_columns(
)
else:
# Ignore output but set used columns.
- self._handle_usecols([names], names, ncols)
columns = [names]
- num_original_columns = ncols
+ self._handle_usecols(columns, columns[0], ncols)
return columns, num_original_columns, unnamed_cols
+ @cache_readonly
+ def _header_line(self):
+ # Store line for reuse in _get_index_name
+ if self.header is not None:
+ return None
+
+ try:
+ line = self._buffered_line()
+ except StopIteration as err:
+ if not self.names:
+ raise EmptyDataError("No columns to parse from file") from err
+
+ line = self.names[:]
+ return line
+
def _handle_usecols(
self,
columns: list[list[Scalar | None]],
| Trying to make this code a little less stateful. Not having much luck. Pushing what I have before it falls off the radar. | https://api.github.com/repos/pandas-dev/pandas/pulls/53091 | 2023-05-04T23:51:24Z | 2023-05-05T20:45:39Z | 2023-05-05T20:45:39Z | 2023-05-05T21:04:21Z |
ENH: EA._from_scalars | diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index e7b7ecba60e0b..05e6fc09a5ef6 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -86,6 +86,7 @@
AstypeArg,
AxisInt,
Dtype,
+ DtypeObj,
FillnaOptions,
InterpolateOptions,
NumpySorter,
@@ -293,6 +294,38 @@ def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = Fal
"""
raise AbstractMethodError(cls)
+ @classmethod
+ def _from_scalars(cls, scalars, *, dtype: DtypeObj) -> Self:
+ """
+ Strict analogue to _from_sequence, allowing only sequences of scalars
+ that should be specifically inferred to the given dtype.
+
+ Parameters
+ ----------
+ scalars : sequence
+ dtype : ExtensionDtype
+
+ Raises
+ ------
+ TypeError or ValueError
+
+ Notes
+ -----
+ This is called in a try/except block when casting the result of a
+ pointwise operation.
+ """
+ try:
+ return cls._from_sequence(scalars, dtype=dtype, copy=False)
+ except (ValueError, TypeError):
+ raise
+ except Exception:
+ warnings.warn(
+ "_from_scalars should only raise ValueError or TypeError. "
+ "Consider overriding _from_scalars where appropriate.",
+ stacklevel=find_stack_level(),
+ )
+ raise
+
@classmethod
def _from_sequence_of_strings(
cls, strings, *, dtype: Dtype | None = None, copy: bool = False
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index e19635af6ab0b..154d78a8cd85a 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -101,6 +101,7 @@
AstypeArg,
AxisInt,
Dtype,
+ DtypeObj,
NpDtype,
Ordered,
Self,
@@ -509,6 +510,22 @@ def _from_sequence(
) -> Self:
return cls(scalars, dtype=dtype, copy=copy)
+ @classmethod
+ def _from_scalars(cls, scalars, *, dtype: DtypeObj) -> Self:
+ if dtype is None:
+ # The _from_scalars strictness doesn't make much sense in this case.
+ raise NotImplementedError
+
+ res = cls._from_sequence(scalars, dtype=dtype)
+
+ # if there are any non-category elements in scalars, these will be
+ # converted to NAs in res.
+ mask = isna(scalars)
+ if not (mask == res.isna()).all():
+ # Some non-category element in scalars got converted to NA in res.
+ raise ValueError
+ return res
+
@overload
def astype(self, dtype: npt.DTypeLike, copy: bool = ...) -> np.ndarray:
...
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index a2742aed31e4c..b94cbe9c3fc60 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -77,6 +77,7 @@
from pandas._typing import (
DateTimeErrorChoices,
+ DtypeObj,
IntervalClosedType,
Self,
TimeAmbiguous,
@@ -266,6 +267,14 @@ def _scalar_type(self) -> type[Timestamp]:
_freq: BaseOffset | None = None
_default_dtype = DT64NS_DTYPE # used in TimeLikeOps.__init__
+ @classmethod
+ def _from_scalars(cls, scalars, *, dtype: DtypeObj) -> Self:
+ if lib.infer_dtype(scalars, skipna=True) not in ["datetime", "datetime64"]:
+ # TODO: require any NAs be valid-for-DTA
+ # TODO: if dtype is passed, check for tzawareness compat?
+ raise ValueError
+ return cls._from_sequence(scalars, dtype=dtype)
+
@classmethod
def _validate_dtype(cls, values, dtype):
# used in TimeLikeOps.__init__
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index 693ebad0ca16f..ce0f0eec7f37c 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -56,6 +56,7 @@
from pandas._typing import (
AxisInt,
Dtype,
+ DtypeObj,
NumpySorter,
NumpyValueArrayLike,
Scalar,
@@ -253,6 +254,13 @@ def tolist(self):
return [x.tolist() for x in self]
return list(self.to_numpy())
+ @classmethod
+ def _from_scalars(cls, scalars, dtype: DtypeObj) -> Self:
+ if lib.infer_dtype(scalars, skipna=True) != "string":
+ # TODO: require any NAs be valid-for-string
+ raise ValueError
+ return cls._from_sequence(scalars, dtype=dtype)
+
# error: Definition of "_concat_same_type" in base class "NDArrayBacked" is
# incompatible with definition in base class "ExtensionArray"
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 3208a742738a3..28e83fd70519c 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -464,16 +464,11 @@ def maybe_cast_pointwise_result(
"""
if isinstance(dtype, ExtensionDtype):
- if not isinstance(dtype, (CategoricalDtype, DatetimeTZDtype)):
- # TODO: avoid this special-casing
- # We have to special case categorical so as not to upcast
- # things like counts back to categorical
-
- cls = dtype.construct_array_type()
- if same_dtype:
- result = _maybe_cast_to_extension_array(cls, result, dtype=dtype)
- else:
- result = _maybe_cast_to_extension_array(cls, result)
+ cls = dtype.construct_array_type()
+ if same_dtype:
+ result = _maybe_cast_to_extension_array(cls, result, dtype=dtype)
+ else:
+ result = _maybe_cast_to_extension_array(cls, result)
elif (numeric_only and dtype.kind in "iufcb") or not numeric_only:
result = maybe_downcast_to_dtype(result, dtype)
@@ -498,11 +493,14 @@ def _maybe_cast_to_extension_array(
-------
ExtensionArray or obj
"""
- from pandas.core.arrays.string_ import BaseStringArray
+ result: ArrayLike
- # Everything can be converted to StringArrays, but we may not want to convert
- if issubclass(cls, BaseStringArray) and lib.infer_dtype(obj) != "string":
- return obj
+ if dtype is not None:
+ try:
+ result = cls._from_scalars(obj, dtype=dtype)
+ except (TypeError, ValueError):
+ return obj
+ return result
try:
result = cls._from_sequence(obj, dtype=dtype)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index fdd03debf6de4..b02cee3c1fcf3 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -75,7 +75,10 @@
pandas_dtype,
validate_all_hashable,
)
-from pandas.core.dtypes.dtypes import ExtensionDtype
+from pandas.core.dtypes.dtypes import (
+ CategoricalDtype,
+ ExtensionDtype,
+)
from pandas.core.dtypes.generic import ABCDataFrame
from pandas.core.dtypes.inference import is_hashable
from pandas.core.dtypes.missing import (
@@ -100,6 +103,7 @@
from pandas.core.arrays.arrow import StructAccessor
from pandas.core.arrays.categorical import CategoricalAccessor
from pandas.core.arrays.sparse import SparseAccessor
+from pandas.core.arrays.string_ import StringDtype
from pandas.core.construction import (
extract_array,
sanitize_array,
@@ -3377,7 +3381,12 @@ def combine(
# try_float=False is to match agg_series
npvalues = lib.maybe_convert_objects(new_values, try_float=False)
- res_values = maybe_cast_pointwise_result(npvalues, self.dtype, same_dtype=False)
+ # same_dtype here is a kludge to avoid casting e.g. [True, False] to
+ # ["True", "False"]
+ same_dtype = isinstance(self.dtype, (StringDtype, CategoricalDtype))
+ res_values = maybe_cast_pointwise_result(
+ npvalues, self.dtype, same_dtype=same_dtype
+ )
return self._constructor(res_values, index=new_index, name=new_name, copy=False)
def combine_first(self, other) -> Series:
diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py
index 606403ba56494..79f9492062063 100644
--- a/pandas/tests/resample/test_timedelta.py
+++ b/pandas/tests/resample/test_timedelta.py
@@ -103,7 +103,7 @@ def test_resample_categorical_data_with_timedeltaindex():
index=pd.TimedeltaIndex([0, 10], unit="s", freq="10s"),
)
expected = expected.reindex(["Group_obj", "Group"], axis=1)
- expected["Group"] = expected["Group_obj"]
+ expected["Group"] = expected["Group_obj"].astype("category")
tm.assert_frame_equal(result, expected)
| - [x] closes #33254
- [x] closes #31108 (someone double-check me on this)
xref #33254 _from_sequence is generally not very strict. This implements _from_scalars for a few EAs as a POC to get rid of an ugly kluge in `maybe_cast_pointwise_result`. The changed behavior in test_resample_categorical_data_with_timedeltaindex looks like a clear improvement to me.
cc @jorisvandenbossche
Things to work out before this leaves the "WIP" zone:
- [x] implement/document it on the base class, none of this "hasattr" shenanigans
- [x] decide whether dtype should be required. Not specifying dtype has different implications for different EA subclasses, which is not ideal. I think part of the motivation is to be able to preserve pyarrow/masked "flavors" when doing pointwise ops.
- [x] see if this fixes #49163, #52411 <b>update</b> Nope! | https://api.github.com/repos/pandas-dev/pandas/pulls/53089 | 2023-05-04T23:24:00Z | 2023-10-16T18:50:28Z | 2023-10-16T18:50:28Z | 2023-10-16T18:50:43Z |
PERF: Improve performance when accessing GroupBy.groups | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index da1b2e750392c..468a0eefc62ef 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -285,6 +285,7 @@ Performance improvements
- Performance improvement accessing :attr:`arrays.IntegerArrays.dtype` & :attr:`arrays.FloatingArray.dtype` (:issue:`52998`)
- Performance improvement in :class:`Series` reductions (:issue:`52341`)
- Performance improvement in :func:`concat` when ``axis=1`` and objects have different indexes (:issue:`52541`)
+- Performance improvement in :meth:`.DataFrameGroupBy.groups` (:issue:`53088`)
- Performance improvement in :meth:`DataFrame.loc` when selecting rows and columns (:issue:`53014`)
- Performance improvement in :meth:`Series.corr` and :meth:`Series.cov` for extension dtypes (:issue:`52502`)
- Performance improvement in :meth:`Series.to_numpy` when dtype is a numpy float dtype and ``na_value`` is ``np.nan`` (:issue:`52430`)
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index d177ca324ec54..0e280f15b9ea1 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -697,8 +697,14 @@ def groups(self) -> dict[Hashable, np.ndarray]:
if len(self.groupings) == 1:
return self.groupings[0].groups
else:
- to_groupby = zip(*(ping.grouping_vector for ping in self.groupings))
- index = Index(to_groupby)
+ to_groupby = []
+ for ping in self.groupings:
+ gv = ping.grouping_vector
+ if not isinstance(gv, BaseGrouper):
+ to_groupby.append(gv)
+ else:
+ to_groupby.append(gv.groupings[0].grouping_vector)
+ index = MultiIndex.from_arrays(to_groupby)
return self.axis.groupby(index)
@final
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
```
df = DataFrame(np.random.randint(1, 100, (5_000_000, 5)))
df.groupby([0, 1]).groups
# main
%timeit df.groupby([0, 1]).groups
1.68 s ± 7.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# pr
%timeit df.groupby([0, 1]).groups
504 ms ± 9.24 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/53088 | 2023-05-04T22:59:39Z | 2023-05-05T17:59:41Z | 2023-05-05T17:59:41Z | 2023-05-05T18:00:59Z |
CI: Build wheel from sdist | diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml
index 0ebede6501f5f..0a508a8b1701f 100644
--- a/.github/workflows/wheels.yml
+++ b/.github/workflows/wheels.yml
@@ -4,7 +4,7 @@
# In an attempt to save CI resources, wheel builds do
# not run on each push but only weekly and for releases.
# Wheel builds can be triggered from the Actions page
-# (if you have the perms) on a commit to master.
+# (if you have the permissions) on a commit to main.
#
# Alternatively, you can add labels to the pull request in order to trigger wheel
# builds.
@@ -14,13 +14,8 @@ name: Wheel builder
on:
schedule:
- # ┌───────────── minute (0 - 59)
- # │ ┌───────────── hour (0 - 23)
- # │ │ ┌───────────── day of the month (1 - 31)
- # │ │ │ ┌───────────── month (1 - 12 or JAN-DEC)
- # │ │ │ │ ┌───────────── day of the week (0 - 6 or SUN-SAT)
- # │ │ │ │ │
- - cron: "27 3 */1 * *"
+ # 3:27 UTC every day
+ - cron: "27 3 * * *"
push:
pull_request:
types: [labeled, opened, synchronize, reopened]
@@ -37,103 +32,68 @@ permissions:
contents: read
jobs:
- build_wheels:
- name: Build wheel for ${{ matrix.python[0] }}-${{ matrix.buildplat[1] }}
+ build_sdist:
+ name: Build sdist
if: >-
(github.event_name == 'schedule' && github.repository_owner == 'pandas-dev') ||
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'pull_request' &&
contains(github.event.pull_request.labels.*.name, 'Build')) ||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && ( ! endsWith(github.ref, 'dev0')))
- runs-on: ${{ matrix.buildplat[0] }}
- strategy:
- # Ensure that a wheel builder finishes even if another fails
- fail-fast: false
- matrix:
- # GitHub Actions doesn't support pairing matrix values together, let's improvise
- # https://github.com/github/feedback/discussions/7835#discussioncomment-1769026
- buildplat:
- - [ubuntu-20.04, manylinux_x86_64]
- - [macos-11, macosx_*]
- - [windows-2019, win_amd64]
- # TODO: support PyPy?
- python: [["cp39", "3.9"], ["cp310", "3.10"], ["cp311", "3.11"]]# "pp39"]
+ runs-on: ubuntu-22.04
env:
IS_PUSH: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }}
IS_SCHEDULE_DISPATCH: ${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }}
+ outputs:
+ sdist_file: ${{ steps.save-path.outputs.sdist_name }}
steps:
- name: Checkout pandas
uses: actions/checkout@v3
with:
- submodules: true
- # versioneer.py requires the latest tag to be reachable. Here we
- # fetch the complete history to get access to the tags.
- # A shallow clone can work when the following issue is resolved:
- # https://github.com/actions/checkout/issues/338
fetch-depth: 0
- - name: Build wheels
- uses: pypa/cibuildwheel@v2.13.0
- env:
- CIBW_BUILD: ${{ matrix.python[0] }}-${{ matrix.buildplat[1] }}
-
- # Used to test(Windows-only) and push the built wheels
- # You might need to use setup-python separately
- # if the new Python-dev version
- # is unavailable on conda-forge.
- - uses: conda-incubator/setup-miniconda@v2
+ - name: Set up Python
+ uses: actions/setup-python@v4
with:
- auto-update-conda: true
- python-version: ${{ matrix.python[1] }}
- activate-environment: test
- channels: conda-forge, anaconda
- channel-priority: true
- # mamba fails to solve, also we really don't need this since we're just installing python
- # mamba-version: "*"
-
- - name: Test wheels (Windows 64-bit only)
- if: ${{ matrix.buildplat[1] == 'win_amd64' }}
- shell: cmd /C CALL {0}
+ python-version: '3.11'
+
+ - name: Build sdist
run: |
- python ci/test_wheels.py wheelhouse
+ python -m pip install build
+ python -m build --sdist
- uses: actions/upload-artifact@v3
with:
- name: ${{ matrix.python[0] }}-${{ startsWith(matrix.buildplat[1], 'macosx') && 'macosx' || matrix.buildplat[1] }}
- path: ./wheelhouse/*.whl
-
+ name: sdist
+ path: ./dist/*
- - name: Install anaconda client
- if: ${{ success() && (env.IS_SCHEDULE_DISPATCH == 'true' || env.IS_PUSH == 'true') }}
+ - name: Output sdist name
+ id: save-path
shell: bash -el {0}
- run: conda install -q -y anaconda-client
+ run: echo "sdist_name=$(ls ./dist)" >> "$GITHUB_OUTPUT"
-
- - name: Upload wheels
- if: ${{ success() && (env.IS_SCHEDULE_DISPATCH == 'true' || env.IS_PUSH == 'true') }}
- shell: bash -el {0}
- env:
- PANDAS_STAGING_UPLOAD_TOKEN: ${{ secrets.PANDAS_STAGING_UPLOAD_TOKEN }}
- PANDAS_NIGHTLY_UPLOAD_TOKEN: ${{ secrets.PANDAS_NIGHTLY_UPLOAD_TOKEN }}
- run: |
- source ci/upload_wheels.sh
- set_upload_vars
- # trigger an upload to
- # https://anaconda.org/scipy-wheels-nightly/pandas
- # for cron jobs or "Run workflow" (restricted to main branch).
- # Tags will upload to
- # https://anaconda.org/multibuild-wheels-staging/pandas
- # The tokens were originally generated at anaconda.org
- upload_wheels
- build_sdist:
- name: Build sdist
+ build_wheels:
+ needs: build_sdist
+ name: Build wheel for ${{ matrix.python[0] }}-${{ matrix.buildplat[1] }}
if: >-
- github.event_name == 'schedule' ||
+ (github.event_name == 'schedule' && github.repository_owner == 'pandas-dev') ||
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'pull_request' &&
contains(github.event.pull_request.labels.*.name, 'Build')) ||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && ( ! endsWith(github.ref, 'dev0')))
- runs-on: ubuntu-22.04
+ runs-on: ${{ matrix.buildplat[0] }}
+ strategy:
+ fail-fast: false
+ matrix:
+ # GitHub Actions doesn't support pairing matrix values together, let's improvise
+ # https://github.com/github/feedback/discussions/7835#discussioncomment-1769026
+ buildplat:
+ - [ubuntu-22.04, manylinux_x86_64]
+ - [ubuntu-22.04, musllinux_x86_64]
+ - [macos-12, macosx_*]
+ - [windows-2022, win_amd64]
+ # TODO: support PyPy?
+ python: [["cp39", "3.9"], ["cp310", "3.10"], ["cp311", "3.11"]]
env:
IS_PUSH: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }}
IS_SCHEDULE_DISPATCH: ${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }}
@@ -141,66 +101,67 @@ jobs:
- name: Checkout pandas
uses: actions/checkout@v3
with:
- submodules: true
- # versioneer.py requires the latest tag to be reachable. Here we
- # fetch the complete history to get access to the tags.
- # A shallow clone can work when the following issue is resolved:
- # https://github.com/actions/checkout/issues/338
fetch-depth: 0
- # Used to push the built sdist
- - uses: conda-incubator/setup-miniconda@v2
+ - name: Download sdist
+ uses: actions/download-artifact@v3
with:
- auto-update-conda: true
- # Really doesn't matter what version we upload with
- # just the version we test with
- python-version: '3.10'
- channels: conda-forge
- channel-priority: true
- # mamba fails to solve, also we really don't need this since we're just installing python
- # mamba-version: "*"
+ name: sdist
+ path: ./dist
- - name: Build sdist
- run: |
- pip install build
- python -m build --sdist
- - name: Test the sdist
- shell: bash -el {0}
- run: |
- # TODO: Don't run test suite, and instead build wheels from sdist
- # by splitting the wheel builders into a two stage job
- # (1. Generate sdist 2. Build wheels from sdist)
- # This tests the sdists, and saves some build time
- python -m pip install dist/*.gz
- pip install hypothesis>=6.46.1 pytest>=7.0.0 pytest-xdist>=2.2.0 pytest-asyncio>=0.17
- cd .. # Not a good idea to test within the src tree
- python -c "import pandas; print(pandas.__version__);
- pandas.test(extra_args=['-m not clipboard and not single_cpu and not slow and not network and not db', '-n 2']);
- pandas.test(extra_args=['-m not clipboard and single_cpu and not slow and not network and not db'])"
- - uses: actions/upload-artifact@v3
+ - name: Build wheels
+ uses: pypa/cibuildwheel@v2.13.0
with:
- name: sdist
- path: ./dist/*
+ package-dir: ./dist/${{ needs.build_sdist.outputs.sdist_file }}
+ env:
+ CIBW_BUILD: ${{ matrix.python[0] }}-${{ matrix.buildplat[1] }}
- - name: Install anaconda client
- if: ${{ success() && (env.IS_SCHEDULE_DISPATCH == 'true' || env.IS_PUSH == 'true') }}
+ - name: Set up Python
+ uses: mamba-org/setup-micromamba@v1
+ with:
+ environment-name: wheel-env
+ create-args: >-
+ python=${{ matrix.python[1] }}
+ anaconda-client
+ wheel
+ cache-downloads: true
+ cache-environment: true
+
+ - name: Validate wheel RECORD
shell: bash -el {0}
+ run: for whl in $(ls wheelhouse); do wheel unpack wheelhouse/$whl -d /tmp; done
+
+ # Testing on windowsservercore instead of GHA runner to fail on missing DLLs
+ - name: Test Windows Wheels
+ if: ${{ matrix.buildplat[1] == 'win_amd64' }}
+ shell: pwsh
run: |
- conda install -q -y anaconda-client
+ $TST_CMD = @"
+ python -m pip install pytz six numpy python-dateutil tzdata>=2022.1 hypothesis>=6.46.1 pytest>=7.0.0 pytest-xdist>=2.2.0 pytest-asyncio>=0.17;
+ python -m pip install --find-links=pandas\wheelhouse --no-index pandas;
+ python -c `'import pandas as pd; pd.test()`';
+ "@
+ docker pull python:${{ matrix.python[1] }}-windowsservercore
+ docker run --env PANDAS_CI='1' -v ${PWD}:C:\pandas python:${{ matrix.python[1] }}-windowsservercore powershell -Command $TST_CMD
+
+ - uses: actions/upload-artifact@v3
+ with:
+ name: ${{ matrix.python[0] }}-${{ startsWith(matrix.buildplat[1], 'macosx') && 'macosx' || matrix.buildplat[1] }}
+ path: ./wheelhouse/*.whl
- - name: Upload sdist
+ - name: Upload wheels & sdist
if: ${{ success() && (env.IS_SCHEDULE_DISPATCH == 'true' || env.IS_PUSH == 'true') }}
shell: bash -el {0}
env:
PANDAS_STAGING_UPLOAD_TOKEN: ${{ secrets.PANDAS_STAGING_UPLOAD_TOKEN }}
PANDAS_NIGHTLY_UPLOAD_TOKEN: ${{ secrets.PANDAS_NIGHTLY_UPLOAD_TOKEN }}
+ # trigger an upload to
+ # https://anaconda.org/scipy-wheels-nightly/pandas
+ # for cron jobs or "Run workflow" (restricted to main branch).
+ # Tags will upload to
+ # https://anaconda.org/multibuild-wheels-staging/pandas
+ # The tokens were originally generated at anaconda.org
run: |
source ci/upload_wheels.sh
set_upload_vars
- # trigger an upload to
- # https://anaconda.org/scipy-wheels-nightly/pandas
- # for cron jobs or "Run workflow" (restricted to main branch).
- # Tags will upload to
- # https://anaconda.org/multibuild-wheels-staging/pandas
- # The tokens were originally generated at anaconda.org
upload_wheels
diff --git a/MANIFEST.in b/MANIFEST.in
index 781a72fdb5481..9894381ed6252 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,6 +1,3 @@
-include RELEASE.md
-include versioneer.py
-
graft doc
prune doc/build
@@ -10,6 +7,7 @@ graft pandas
global-exclude *.bz2
global-exclude *.csv
+global-exclude *.data
global-exclude *.dta
global-exclude *.feather
global-exclude *.tar
@@ -18,9 +16,12 @@ global-exclude *.h5
global-exclude *.html
global-exclude *.json
global-exclude *.jsonl
+global-exclude *.kml
global-exclude *.msgpack
global-exclude *.pdf
+global-exclude *.parquet
global-exclude *.pickle
+global-exclude *.pkl
global-exclude *.png
global-exclude *.pptx
global-exclude *.ods
@@ -29,12 +30,15 @@ global-exclude *.orc
global-exclude *.sas7bdat
global-exclude *.sav
global-exclude *.so
+global-exclude *.txt
global-exclude *.xls
global-exclude *.xlsb
global-exclude *.xlsm
global-exclude *.xlsx
global-exclude *.xpt
global-exclude *.cpt
+global-exclude *.xml
+global-exclude *.xsl
global-exclude *.xz
global-exclude *.zip
global-exclude *.zst
diff --git a/ci/fix_wheels.py b/ci/fix_wheels.py
deleted file mode 100644
index 76b70fdde9ea0..0000000000000
--- a/ci/fix_wheels.py
+++ /dev/null
@@ -1,61 +0,0 @@
-"""
-This file "repairs" our Windows wheels by copying the necessary DLLs for pandas to run
-on a barebones Windows installation() into the wheel.
-
-NOTE: The paths for the DLLs are hard-coded to the location of the Visual Studio
-redistributables
-"""
-import os
-import shutil
-import subprocess
-from subprocess import CalledProcessError
-import sys
-import zipfile
-
-try:
- if len(sys.argv) != 3:
- raise ValueError(
- "User must pass the path to the wheel and the destination directory."
- )
- wheel_path = sys.argv[1]
- dest_dir = sys.argv[2]
- # Figure out whether we are building on 32 or 64 bit python
- is_32 = sys.maxsize <= 2**32
- PYTHON_ARCH = "x86" if is_32 else "x64"
-except ValueError:
- # Too many/little values to unpack
- raise ValueError(
- "User must pass the path to the wheel and the destination directory."
- )
-if not os.path.isdir(dest_dir):
- print(f"Created directory {dest_dir}")
- os.mkdir(dest_dir)
-
-wheel_name = os.path.basename(wheel_path)
-success = True
-
-try:
- # Use the wheel CLI for zipping up the wheel since the CLI will
- # take care of rebuilding the hashes found in the record file
- tmp_dir = os.path.join(dest_dir, "tmp")
- with zipfile.ZipFile(wheel_path, "r") as f:
- # Extracting all the members of the zip
- # into a specific location.
- f.extractall(path=tmp_dir)
- base_redist_dir = (
- f"C:/Program Files (x86)/Microsoft Visual Studio/2019/"
- f"Enterprise/VC/Redist/MSVC/14.29.30133/{PYTHON_ARCH}/"
- f"Microsoft.VC142.CRT/"
- )
- required_dlls = ["msvcp140.dll", "concrt140.dll"]
- if not is_32:
- required_dlls += ["vcruntime140_1.dll"]
- dest_dll_dir = os.path.join(tmp_dir, "pandas/_libs/window")
- for dll in required_dlls:
- src = os.path.join(base_redist_dir, dll)
- shutil.copy(src, dest_dll_dir)
- subprocess.run(["wheel", "pack", tmp_dir, "-d", dest_dir], check=True)
-except CalledProcessError:
- print("Failed to add DLLS to wheel.")
- sys.exit(1)
-print("Successfully repaired wheel")
diff --git a/ci/test_wheels.py b/ci/test_wheels.py
deleted file mode 100644
index 75675d7e4ffc3..0000000000000
--- a/ci/test_wheels.py
+++ /dev/null
@@ -1,62 +0,0 @@
-import glob
-import os
-import shutil
-import subprocess
-from subprocess import CalledProcessError
-import sys
-
-if os.name == "nt":
- py_ver = f"{sys.version_info.major}.{sys.version_info.minor}"
- is_32_bit = os.getenv("IS_32_BIT") == "true"
- try:
- wheel_dir = sys.argv[1]
- wheel_path = glob.glob(f"{wheel_dir}/*.whl")[0]
- except IndexError:
- # Not passed
- wheel_path = None
- print(f"IS_32_BIT is {is_32_bit}")
- print(f"Path to built wheel is {wheel_path}")
-
- print("Verifying file hashes in wheel RECORD file")
- try:
- tmp_dir = "tmp"
- subprocess.run(["wheel", "unpack", wheel_path, "-d", tmp_dir], check=True)
- except CalledProcessError:
- print("wheel RECORD file hash verification failed.")
- sys.exit(1)
- finally:
- shutil.rmtree(tmp_dir)
-
- if is_32_bit:
- sys.exit(0) # No way to test Windows 32-bit(no docker image)
- if wheel_path is None:
- raise ValueError("Wheel path must be passed in if on 64-bit Windows")
- print(f"Pulling docker image to test Windows 64-bit Python {py_ver}")
- subprocess.run(f"docker pull python:{py_ver}-windowsservercore", check=True)
- pandas_base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
- print(f"pandas project dir is {pandas_base_dir}")
- dist_dir = os.path.join(pandas_base_dir, "dist")
- print(f"Copying wheel into pandas_base_dir/dist ({dist_dir})")
- os.mkdir(dist_dir)
- shutil.copy(wheel_path, dist_dir)
- print(os.listdir(dist_dir))
- subprocess.run(
- rf"docker run -v %cd%:c:\pandas "
- f"python:{py_ver}-windowsservercore /pandas/ci/test_wheels_windows.bat",
- check=True,
- shell=True,
- cwd=pandas_base_dir,
- )
-else:
- import pandas as pd
-
- multi_args = [
- "-m not clipboard and not single_cpu and not slow and not network and not db",
- "-n 2",
- ]
- pd.test(extra_args=multi_args)
- pd.test(
- extra_args=[
- "-m not clipboard and single_cpu and not slow and not network and not db",
- ]
- )
diff --git a/ci/test_wheels_windows.bat b/ci/test_wheels_windows.bat
deleted file mode 100644
index 9864446d71137..0000000000000
--- a/ci/test_wheels_windows.bat
+++ /dev/null
@@ -1,9 +0,0 @@
-set test_command=import pandas as pd; print(pd.__version__); ^
-pd.test(extra_args=['-m not clipboard and not single_cpu and not slow and not network and not db', '-n 2']); ^
-pd.test(extra_args=['-m not clipboard and single_cpu and not slow and not network and not db'])
-
-python --version
-pip install pytz six numpy python-dateutil tzdata>=2022.1
-pip install hypothesis>=6.46.1 pytest>=7.0.0 pytest-xdist>=2.2.0 pytest-asyncio>=0.17
-pip install --find-links=pandas/dist --no-index pandas
-python -c "%test_command%"
diff --git a/pandas/util/_tester.py b/pandas/util/_tester.py
index e9f516bac6ad2..6a2a8189ad896 100644
--- a/pandas/util/_tester.py
+++ b/pandas/util/_tester.py
@@ -28,7 +28,7 @@ def test(extra_args: list[str] | None = None, run_doctests: bool = False) -> Non
"""
pytest = import_optional_dependency("pytest")
import_optional_dependency("hypothesis")
- cmd = ['-m "not slow and not network and not db"']
+ cmd = ["-m not slow and not network and not db"]
if extra_args:
if not isinstance(extra_args, list):
extra_args = [extra_args]
diff --git a/pyproject.toml b/pyproject.toml
index f9dfe65ab2a01..e14bcaa265684 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -143,23 +143,32 @@ parentdir_prefix = "pandas-"
setup = ['--vsenv'] # For Windows
[tool.cibuildwheel]
-skip = "cp36-* cp37-* pp37-* *-manylinux_i686 *_ppc64le *_s390x *-musllinux*"
+skip = "cp36-* cp37-* cp38-* pp* *_i686 *_ppc64le *_s390x *-musllinux_aarch64"
build-verbosity = "3"
-environment = {LDFLAGS="-Wl,--strip-all" }
+environment = {LDFLAGS="-Wl,--strip-all"}
test-requires = "hypothesis>=6.46.1 pytest>=7.0.0 pytest-xdist>=2.2.0 pytest-asyncio>=0.17"
-test-command = "python {project}/ci/test_wheels.py"
+test-command = """
+ PANDAS_CI='1' python -c 'import pandas as pd; \
+ pd.test(extra_args=["-m not clipboard and not single_cpu and not slow and not network and not db", "-n 2"]); \
+ pd.test(extra_args=["-m not clipboard and single_cpu and not slow and not network and not db"]);' \
+ """
[tool.cibuildwheel.macos]
archs = "x86_64 arm64"
test-skip = "*_arm64"
[tool.cibuildwheel.windows]
-repair-wheel-command = "python ci/fix_wheels.py {wheel} {dest_dir}"
+before-build = "pip install delvewheel"
+repair-wheel-command = "delvewheel repair -w {dest_dir} {wheel}"
+
+[[tool.cibuildwheel.overrides]]
+select = "*-musllinux*"
+before-test = "apk update && apk add musl-locales"
[[tool.cibuildwheel.overrides]]
select = "*-win*"
# We test separately for Windows, since we use
-# the base windows docker image to check if any dlls are
+# the windowsservercore docker image to check if any dlls are
# missing from the wheel
test-command = ""
@@ -170,10 +179,6 @@ test-command = ""
select = "*-macosx*"
environment = {CFLAGS="-g0"}
-[[tool.cibuildwheel.overrides]]
-select = "*-win32"
-environment = { IS_32_BIT="true" }
-
[tool.black]
target-version = ['py39', 'py310']
required-version = '23.3.0'
| Builds the wheels for all platforms/Python versions from the sdist
Other changes:
* Cleans up the `wheel.yml` file
* Uses `delvewheel` to repair the windows wheels instead of manually patching
* Tests windows wheels with `windows-servercore` directly in the `wheels.yml` file
* Runs `wheel unpack` for every wheel for validation, not just windows wheels
* Adds musllinux wheels per https://github.com/MacPython/pandas-wheels/issues/176
| https://api.github.com/repos/pandas-dev/pandas/pulls/53087 | 2023-05-04T22:55:19Z | 2023-06-01T23:12:22Z | 2023-06-01T23:12:22Z | 2023-06-12T23:46:38Z |
CLN: assorted | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index da1b2e750392c..4139b65e248d8 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -438,7 +438,7 @@ Metadata
Other
^^^^^
-- Bug in :class:`FloatingArray.__contains__` with ``NaN`` item incorrectly returning ``False`` when ``NaN`` values are presnet (:issue:`52840`)
+- Bug in :class:`FloatingArray.__contains__` with ``NaN`` item incorrectly returning ``False`` when ``NaN`` values are present (:issue:`52840`)
- Bug in :func:`assert_almost_equal` now throwing assertion error for two unequal sets (:issue:`51727`)
- Bug in :func:`assert_frame_equal` checks category dtypes even when asked not to check index type (:issue:`52126`)
- Bug in :meth:`DataFrame.reindex` with a ``fill_value`` that should be inferred with a :class:`ExtensionDtype` incorrectly inferring ``object`` dtype (:issue:`52586`)
diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx
index 94ad2aa3a751f..2861f917d8336 100644
--- a/pandas/_libs/algos.pyx
+++ b/pandas/_libs/algos.pyx
@@ -346,7 +346,7 @@ def kth_smallest(numeric_t[::1] arr, Py_ssize_t k) -> numeric_t:
def nancorr(const float64_t[:, :] mat, bint cov=False, minp=None):
cdef:
Py_ssize_t i, xi, yi, N, K
- bint minpv
+ int64_t minpv
float64_t[:, ::1] result
ndarray[uint8_t, ndim=2] mask
int64_t nobs = 0
@@ -357,7 +357,7 @@ def nancorr(const float64_t[:, :] mat, bint cov=False, minp=None):
if minp is None:
minpv = 1
else:
- minpv = <int>minp
+ minpv = <int64_t>minp
result = np.empty((K, K), dtype=np.float64)
mask = np.isfinite(mat).view(np.uint8)
diff --git a/pandas/_libs/index.pyi b/pandas/_libs/index.pyi
index e08faaaa03139..8321200a84b76 100644
--- a/pandas/_libs/index.pyi
+++ b/pandas/_libs/index.pyi
@@ -5,6 +5,8 @@ from pandas._typing import npt
from pandas import MultiIndex
from pandas.core.arrays import ExtensionArray
+multiindex_nulls_shift: int
+
class IndexEngine:
over_size_threshold: bool
def __init__(self, values: np.ndarray) -> None: ...
diff --git a/pandas/_libs/internals.pyi b/pandas/_libs/internals.pyi
index 14dfcb2b1e712..9996fbfc346df 100644
--- a/pandas/_libs/internals.pyi
+++ b/pandas/_libs/internals.pyi
@@ -102,5 +102,5 @@ class BlockValuesRefs:
referenced_blocks: list[weakref.ref]
def __init__(self, blk: SharedBlock | None = ...) -> None: ...
def add_reference(self, blk: SharedBlock) -> None: ...
- def add_index_reference(self, index: object) -> None: ...
+ def add_index_reference(self, index: Index) -> None: ...
def has_reference(self) -> bool: ...
diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx
index 88c61b7fce7f0..cfc43521cf606 100644
--- a/pandas/_libs/internals.pyx
+++ b/pandas/_libs/internals.pyx
@@ -966,7 +966,7 @@ cdef class BlockValuesRefs:
Parameters
----------
- index: object
+ index : Index
The index that the new reference should point to.
"""
self.referenced_blocks.append(weakref.ref(index))
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index a6a9a431a9658..bc2886e5b531c 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -2612,7 +2612,7 @@ def maybe_convert_objects(ndarray[object] objects,
return tdi._data._ndarray
seen.object_ = True
- if seen.period_:
+ elif seen.period_:
if is_period_array(objects):
from pandas import PeriodIndex
pi = PeriodIndex(objects)
@@ -2621,7 +2621,7 @@ def maybe_convert_objects(ndarray[object] objects,
return pi._data
seen.object_ = True
- if seen.interval_:
+ elif seen.interval_:
if is_interval_array(objects):
from pandas import IntervalIndex
ii = IntervalIndex(objects)
@@ -2631,7 +2631,7 @@ def maybe_convert_objects(ndarray[object] objects,
seen.object_ = True
- if seen.nat_:
+ elif seen.nat_:
if not seen.object_ and not seen.numeric_ and not seen.bool_:
# all NaT, None, or nan (at least one NaT)
# see GH#49340 for discussion of desired behavior
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py
index 032e43bf9c089..7908c9df60df8 100644
--- a/pandas/_testing/__init__.py
+++ b/pandas/_testing/__init__.py
@@ -852,9 +852,7 @@ def _constructor_sliced(self):
class SubclassedCategorical(Categorical):
- @property
- def _constructor(self):
- return SubclassedCategorical
+ pass
def _make_skipna_wrapper(alternative, skipna_alternative=None):
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 74ae5796e85fc..37c1fa76fbbcf 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1240,7 +1240,7 @@ def take(
if not is_array_like(arr):
arr = np.asarray(arr)
- indices = np.asarray(indices, dtype=np.intp)
+ indices = ensure_platform_int(indices)
if allow_fill:
# Pandas style, -1 means NA
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 1a1ccd6bba131..0c2adb89a2422 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -1086,15 +1086,10 @@ def agg(self):
result = super().agg()
if result is None:
f = self.f
- kwargs = self.kwargs
# string, list-like, and dict-like are entirely handled in super
assert callable(f)
- # we can be called from an inner function which
- # passes this meta-data
- kwargs.pop("_level", None)
-
# try a regular apply, this evaluates lambdas
# row-by-row; however if the lambda is expected a Series
# expression, e.g.: lambda x: x-x.quantile(0.25)
diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py
index 74cc30a4e030d..f65d2d20e028e 100644
--- a/pandas/core/array_algos/putmask.py
+++ b/pandas/core/array_algos/putmask.py
@@ -138,7 +138,7 @@ def setitem_datetimelike_compat(values: np.ndarray, num_set: int, other):
if values.dtype == object:
dtype, _ = infer_dtype_from(other)
- if isinstance(dtype, np.dtype) and dtype.kind in "mM":
+ if lib.is_np_dtype(dtype, "mM"):
# https://github.com/numpy/numpy/issues/12550
# timedelta64 will incorrectly cast to int
if not is_list_like(other):
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index a4447bffed5f5..41e05ffc70b2e 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -2022,7 +2022,7 @@ def _validate_listlike(self, value):
"Cannot set a Categorical with another, "
"without identical categories"
)
- # is_dtype_equal implies categories_match_up_to_permutation
+ # dtype equality implies categories_match_up_to_permutation
value = self._encode_with_my_categories(value)
return value._codes
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 126a70a930065..39dade594a5af 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -63,7 +63,6 @@
from pandas.core.arrays import datetimelike as dtl
from pandas.core.arrays._ranges import generate_regular_range
-from pandas.core.arrays.sparse.dtype import SparseDtype
import pandas.core.common as com
from pandas.tseries.frequencies import get_period_alias
@@ -2035,11 +2034,7 @@ def _sequence_to_dt64ns(
if out_unit is not None:
out_dtype = np.dtype(f"M8[{out_unit}]")
- if (
- data_dtype == object
- or is_string_dtype(data_dtype)
- or isinstance(data_dtype, SparseDtype)
- ):
+ if data_dtype == object or is_string_dtype(data_dtype):
# TODO: We do not have tests specific to string-dtypes,
# also complex or categorical or other extension
copy = False
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 8c9b45bd452a0..35ce12a6fa795 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -48,7 +48,6 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import BaseMaskedDtype
-from pandas.core.dtypes.inference import is_array_like
from pandas.core.dtypes.missing import (
array_equivalent,
is_valid_na_for_dtype,
@@ -172,20 +171,13 @@ def __getitem__(self, item: PositionalIndexer) -> Self | Any:
return type(self)(self._data[item], newmask)
- @doc(ExtensionArray.fillna)
@doc(ExtensionArray.fillna)
def fillna(self, value=None, method=None, limit: int | None = None) -> Self:
value, method = validate_fillna_kwargs(value, method)
mask = self._mask
- if is_array_like(value):
- if len(value) != len(self):
- raise ValueError(
- f"Length of 'value' does not match. Got ({len(value)}) "
- f" expected {len(self)}"
- )
- value = value[mask]
+ value = missing.check_value_size(value, mask, len(self))
if mask.any():
if method is not None:
diff --git a/pandas/core/flags.py b/pandas/core/flags.py
index f07c6917d91e5..c4d92bcb4e994 100644
--- a/pandas/core/flags.py
+++ b/pandas/core/flags.py
@@ -1,7 +1,11 @@
from __future__ import annotations
+from typing import TYPE_CHECKING
import weakref
+if TYPE_CHECKING:
+ from pandas.core.generic import NDFrame
+
class Flags:
"""
@@ -44,9 +48,9 @@ class Flags:
<Flags(allows_duplicate_labels=True)>
"""
- _keys = {"allows_duplicate_labels"}
+ _keys: set[str] = {"allows_duplicate_labels"}
- def __init__(self, obj, *, allows_duplicate_labels) -> None:
+ def __init__(self, obj: NDFrame, *, allows_duplicate_labels: bool) -> None:
self._allows_duplicate_labels = allows_duplicate_labels
self._obj = weakref.ref(obj)
@@ -95,13 +99,13 @@ def allows_duplicate_labels(self, value: bool) -> None:
self._allows_duplicate_labels = value
- def __getitem__(self, key):
+ def __getitem__(self, key: str):
if key not in self._keys:
raise KeyError(key)
return getattr(self, key)
- def __setitem__(self, key, value) -> None:
+ def __setitem__(self, key: str, value) -> None:
if key not in self._keys:
raise ValueError(f"Unknown flag {key}. Must be one of {self._keys}")
setattr(self, key, value)
@@ -109,7 +113,7 @@ def __setitem__(self, key, value) -> None:
def __repr__(self) -> str:
return f"<Flags(allows_duplicate_labels={self.allows_duplicate_labels})>"
- def __eq__(self, other):
+ def __eq__(self, other) -> bool:
if isinstance(other, type(self)):
return self.allows_duplicate_labels == other.allows_duplicate_labels
return False
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 9cd3a4e91eaf8..5357dc35b70ee 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -6530,7 +6530,7 @@ def sort_values(
axis: Axis = ...,
ascending=...,
inplace: Literal[True],
- kind: str = ...,
+ kind: SortKind = ...,
na_position: str = ...,
ignore_index: bool = ...,
key: ValueKeyFunc = ...,
@@ -6544,7 +6544,7 @@ def sort_values(
axis: Axis = 0,
ascending: bool | list[bool] | tuple[bool, ...] = True,
inplace: bool = False,
- kind: str = "quicksort",
+ kind: SortKind = "quicksort",
na_position: str = "last",
ignore_index: bool = False,
key: ValueKeyFunc = None,
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 4eb29428b7dd1..78f7b69beb118 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6206,7 +6206,7 @@ def _check_inplace_setting(self, value) -> bool_t:
"""check whether we allow in-place setting with this type of value"""
if self._is_mixed_type and not self._mgr.is_numeric_mixed_type:
# allow an actual np.nan through
- if is_float(value) and np.isnan(value) or value is lib.no_default:
+ if (is_float(value) and np.isnan(value)) or value is lib.no_default:
return True
raise TypeError(
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 841d8bb0749d0..179e118bf3c0f 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -2868,8 +2868,9 @@ def fillna(self, value=None, downcast=None):
DataFrame.fillna : Fill NaN values of a DataFrame.
Series.fillna : Fill NaN Values of a Series.
"""
+ if not is_scalar(value):
+ raise TypeError(f"'value' must be a scalar, passed: {type(value).__name__}")
- value = self._require_scalar(value)
if self.hasnans:
result = self.putmask(self._isnan, value)
if downcast is None:
@@ -3211,7 +3212,7 @@ def union(self, other, sort=None):
elif not len(other) or self.equals(other):
# NB: whether this (and the `if not len(self)` check below) come before
- # or after the is_dtype_equal check above affects the returned dtype
+ # or after the dtype equality check above affects the returned dtype
result = self._get_reconciled_name_object(other)
if sort is True:
return result.sort_values()
@@ -5119,16 +5120,6 @@ def _validate_fill_value(self, value):
raise TypeError
return value
- @final
- def _require_scalar(self, value):
- """
- Check that this is a scalar value that we can use for setitem-like
- operations without changing dtype.
- """
- if not is_scalar(value):
- raise TypeError(f"'value' must be a scalar, passed: {type(value).__name__}")
- return value
-
def _is_memory_usage_qualified(self) -> bool:
"""
Return a boolean if we need a qualified .info display.
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 62b0e40268716..deff5129ad64d 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1116,11 +1116,7 @@ def _engine(self):
# calculating the indexer are shifted to 0
sizes = np.ceil(
np.log2(
- [
- len(level)
- + libindex.multiindex_nulls_shift # type: ignore[attr-defined]
- for level in self.levels
- ]
+ [len(level) + libindex.multiindex_nulls_shift for level in self.levels]
)
)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 85463d803b9a7..ff523862f8770 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -309,11 +309,7 @@ def should_store(self, value: ArrayLike) -> bool:
-------
bool
"""
- # faster equivalent to is_dtype_equal(value.dtype, self.dtype)
- try:
- return value.dtype == self.dtype
- except TypeError:
- return False
+ return value.dtype == self.dtype
# ---------------------------------------------------------------------
# Apply/Reduce and Helpers
diff --git a/pandas/core/ops/invalid.py b/pandas/core/ops/invalid.py
index eb27cf7450119..e5ae6d359ac22 100644
--- a/pandas/core/ops/invalid.py
+++ b/pandas/core/ops/invalid.py
@@ -4,11 +4,15 @@
from __future__ import annotations
import operator
+from typing import TYPE_CHECKING
import numpy as np
+if TYPE_CHECKING:
+ from pandas._typing import npt
-def invalid_comparison(left, right, op) -> np.ndarray:
+
+def invalid_comparison(left, right, op) -> npt.NDArray[np.bool_]:
"""
If a comparison has mismatched types and is not necessarily meaningful,
follow python3 conventions by:
diff --git a/pandas/core/ops/missing.py b/pandas/core/ops/missing.py
index 9707f5df927fb..fc685935a35fc 100644
--- a/pandas/core/ops/missing.py
+++ b/pandas/core/ops/missing.py
@@ -27,16 +27,10 @@
import numpy as np
-from pandas.core.dtypes.common import (
- is_float_dtype,
- is_integer_dtype,
- is_scalar,
-)
-
from pandas.core import roperator
-def _fill_zeros(result, x, y):
+def _fill_zeros(result: np.ndarray, x, y):
"""
If this is a reversed op, then flip x,y
@@ -46,11 +40,11 @@ def _fill_zeros(result, x, y):
Mask the nan's from x.
"""
- if is_float_dtype(result.dtype):
+ if result.dtype.kind == "f":
return result
is_variable_type = hasattr(y, "dtype")
- is_scalar_type = is_scalar(y)
+ is_scalar_type = not isinstance(y, np.ndarray)
if not is_variable_type and not is_scalar_type:
# e.g. test_series_ops_name_retention with mod we get here with list/tuple
@@ -59,7 +53,7 @@ def _fill_zeros(result, x, y):
if is_scalar_type:
y = np.array(y)
- if is_integer_dtype(y.dtype):
+ if y.dtype.kind in "iu":
ymask = y == 0
if ymask.any():
# GH#7325, mask and nans must be broadcastable
@@ -143,7 +137,9 @@ def dispatch_fill_zeros(op, left, right, result):
----------
op : function (operator.add, operator.div, ...)
left : object (np.ndarray for non-reversed ops)
+ We have excluded ExtensionArrays here
right : object (np.ndarray for reversed ops)
+ We have excluded ExtensionArrays here
result : ndarray
Returns
diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py
index dd9c952cc08ff..b63f3f28b8f6c 100644
--- a/pandas/core/sorting.py
+++ b/pandas/core/sorting.py
@@ -71,9 +71,9 @@ def get_indexer_indexer(
target : Index
level : int or level name or list of ints or list of level names
ascending : bool or list of bools, default True
- kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
- na_position : {'first', 'last'}, default 'last'
- sort_remaining : bool, default True
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}
+ na_position : {'first', 'last'}
+ sort_remaining : bool
key : callable, optional
Returns
@@ -424,7 +424,7 @@ def lexsort_indexer(
def nargsort(
items: ArrayLike | Index | Series,
- kind: str = "quicksort",
+ kind: SortKind = "quicksort",
ascending: bool = True,
na_position: str = "last",
key: Callable | None = None,
@@ -440,7 +440,7 @@ def nargsort(
Parameters
----------
items : np.ndarray, ExtensionArray, Index, or Series
- kind : str, default 'quicksort'
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
ascending : bool, default True
na_position : {'first', 'last'}, default 'last'
key : Optional[Callable], default None
@@ -480,10 +480,7 @@ def nargsort(
# i.e. ExtensionArray
return items.argsort(
ascending=ascending,
- # error: Argument "kind" to "argsort" of "ExtensionArray" has
- # incompatible type "str"; expected "Literal['quicksort',
- # 'mergesort', 'heapsort', 'stable']"
- kind=kind, # type: ignore[arg-type]
+ kind=kind,
na_position=na_position,
)
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index d7f7a0b8801ed..7fa1cb2840fae 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -76,6 +76,8 @@
Self,
)
+ from pandas import Index
+
# -----------------------------------------------------------------------------
# -- Helper functions
@@ -1256,7 +1258,7 @@ def _harmonize_columns(
except KeyError:
pass # this column not in results
- def _sqlalchemy_type(self, col):
+ def _sqlalchemy_type(self, col: Index | Series):
dtype: DtypeArg = self.dtype or {}
if is_dict_like(dtype):
dtype = cast(dict, dtype)
@@ -1284,7 +1286,8 @@ def _sqlalchemy_type(self, col):
# GH 9086: TIMESTAMP is the suggested type if the column contains
# timezone information
try:
- if col.dt.tz is not None:
+ # error: Item "Index" of "Union[Index, Series]" has no attribute "dt"
+ if col.dt.tz is not None: # type: ignore[union-attr]
return TIMESTAMP(timezone=True)
except AttributeError:
# The column is actually a DatetimeIndex
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 10859c0fa58c4..aed28efecb696 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -414,7 +414,7 @@ def _datetime_to_stata_elapsed_vec(dates: Series, fmt: str) -> Series:
US_PER_DAY = NS_PER_DAY / 1000
def parse_dates_safe(
- dates, delta: bool = False, year: bool = False, days: bool = False
+ dates: Series, delta: bool = False, year: bool = False, days: bool = False
):
d = {}
if lib.is_np_dtype(dates.dtype, "M"):
diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py
index 88b681d18fa3b..720106590cba3 100644
--- a/pandas/tests/frame/test_block_internals.py
+++ b/pandas/tests/frame/test_block_internals.py
@@ -228,6 +228,7 @@ def test_construction_with_conversions(self):
"dt1": Timestamp("20130101"),
"dt2": date_range("20130101", periods=3).astype("M8[s]"),
# 'dt3' : date_range('20130101 00:00:01',periods=3,freq='s'),
+ # FIXME: don't leave commented-out
},
index=range(3),
)
@@ -242,6 +243,7 @@ def test_construction_with_conversions(self):
# df['dt3'] = np.array(['2013-01-01 00:00:01','2013-01-01
# 00:00:02','2013-01-01 00:00:03'],dtype='datetime64[s]')
+ # FIXME: don't leave commented-out
tm.assert_frame_equal(df, expected)
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 3380a43126cec..8624e54955d83 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -3068,7 +3068,7 @@ def test_from_out_of_bounds_ns_datetime(self, constructor, cls):
result = constructor(scalar)
item = get1(result)
- dtype = result.dtype if isinstance(result, Series) else result.dtypes.iloc[0]
+ dtype = tm.get_dtype(result)
assert type(item) is Timestamp
assert item.asm8.dtype == exp_dtype
@@ -3079,7 +3079,7 @@ def test_out_of_s_bounds_datetime64(self, constructor):
result = constructor(scalar)
item = get1(result)
assert type(item) is np.datetime64
- dtype = result.dtype if isinstance(result, Series) else result.dtypes.iloc[0]
+ dtype = tm.get_dtype(result)
assert dtype == object
@pytest.mark.xfail(
@@ -3097,7 +3097,7 @@ def test_from_out_of_bounds_ns_timedelta(self, constructor, cls):
result = constructor(scalar)
item = get1(result)
- dtype = result.dtype if isinstance(result, Series) else result.dtypes.iloc[0]
+ dtype = tm.get_dtype(result)
assert type(item) is Timedelta
assert item.asm8.dtype == exp_dtype
@@ -3109,7 +3109,7 @@ def test_out_of_s_bounds_timedelta64(self, constructor, cls):
result = constructor(scalar)
item = get1(result)
assert type(item) is cls
- dtype = result.dtype if isinstance(result, Series) else result.dtypes.iloc[0]
+ dtype = tm.get_dtype(result)
assert dtype == object
def test_tzaware_data_tznaive_dtype(self, constructor, box, frame_or_series):
diff --git a/pandas/tests/series/methods/test_asof.py b/pandas/tests/series/methods/test_asof.py
index 9d8a8320eb978..638216302b92f 100644
--- a/pandas/tests/series/methods/test_asof.py
+++ b/pandas/tests/series/methods/test_asof.py
@@ -5,12 +5,14 @@
from pandas import (
DatetimeIndex,
+ PeriodIndex,
Series,
Timestamp,
date_range,
isna,
notna,
offsets,
+ period_range,
)
import pandas._testing as tm
@@ -114,11 +116,6 @@ def test_with_nan(self):
tm.assert_series_equal(result, expected)
def test_periodindex(self):
- from pandas import (
- PeriodIndex,
- period_range,
- )
-
# array or list or dates
N = 50
rng = period_range("1/1/1990", periods=N, freq="H")
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53086 | 2023-05-04T22:54:54Z | 2023-05-05T18:02:30Z | 2023-05-05T18:02:30Z | 2023-05-05T18:23:17Z |
STY: Enable more ruff checks | diff --git a/pyproject.toml b/pyproject.toml
index 042d13ea7956a..6eef8e4fa9b7c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -208,8 +208,12 @@ select = [
"B",
# flake8-quotes
"Q",
+ # flake8-debugger
+ "T10",
+ # flake8-gettext
+ "INT",
# pylint
- "PLE", "PLR", "PLW",
+ "PLC", "PLE", "PLR", "PLW",
# misc lints
"PIE",
# flake8-pyi
@@ -273,6 +277,8 @@ ignore = [
"PLW0603",
# Docstrings should not be included in stubs
"PYI021",
+ # compare-to-empty-string
+ "PLC1901",
# Use typing_extensions.TypeAlias for type aliases
# "PYI026", # not yet implemented
# Use "collections.abc.*" instead of "typing.*" (PEP 585 syntax)
| Enable ruff's pylint PLC, flake8-gettext, and flake8-debugger | https://api.github.com/repos/pandas-dev/pandas/pulls/53082 | 2023-05-04T20:14:36Z | 2023-05-05T10:37:24Z | 2023-05-05T10:37:24Z | 2023-05-05T17:09:47Z |
Backport PR #53078 on branch 2.0.x (BUG: pd.api.interchange.from_pandas raises with all-null categorical) | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 8322c8408a0e3..71c31e61fa6a3 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -20,6 +20,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
+- Bug in :func:`api.interchange.from_dataframe` was raising ``IndexError`` on empty categorical data (:issue:`53077`)
- Bug in :func:`api.interchange.from_dataframe` was returning :class:`DataFrame`'s of incorrect sizes when called on slices (:issue:`52824`)
- Bug in :func:`api.interchange.from_dataframe` was unnecessarily raising on bitmasks (:issue:`49888`)
- Bug in :meth:`DataFrame.convert_dtypes` ignores ``convert_*`` keywords when set to False ``dtype_backend="pyarrow"`` (:issue:`52872`)
diff --git a/pandas/core/interchange/from_dataframe.py b/pandas/core/interchange/from_dataframe.py
index 45d6bdd7917c1..78e530f915117 100644
--- a/pandas/core/interchange/from_dataframe.py
+++ b/pandas/core/interchange/from_dataframe.py
@@ -202,7 +202,10 @@ def categorical_column_to_series(col: Column) -> tuple[pd.Series, Any]:
# Doing module in order to not get ``IndexError`` for
# out-of-bounds sentinel values in `codes`
- values = categories[codes % len(categories)]
+ if len(categories) > 0:
+ values = categories[codes % len(categories)]
+ else:
+ values = codes
cat = pd.Categorical(
values, categories=categories, ordered=categorical["is_ordered"]
diff --git a/pandas/tests/interchange/test_impl.py b/pandas/tests/interchange/test_impl.py
index d393ba6fd3957..301cccec9e0ed 100644
--- a/pandas/tests/interchange/test_impl.py
+++ b/pandas/tests/interchange/test_impl.py
@@ -89,6 +89,18 @@ def test_categorical_pyarrow():
tm.assert_frame_equal(result, expected)
+def test_empty_categorical_pyarrow():
+ # https://github.com/pandas-dev/pandas/issues/53077
+ pa = pytest.importorskip("pyarrow", "11.0.0")
+
+ arr = [None]
+ table = pa.table({"arr": pa.array(arr, "float64").dictionary_encode()})
+ exchange_df = table.__dataframe__()
+ result = pd.api.interchange.from_dataframe(exchange_df)
+ expected = pd.DataFrame({"arr": pd.Categorical([np.nan])})
+ tm.assert_frame_equal(result, expected)
+
+
def test_large_string_pyarrow():
# GH 52795
pa = pytest.importorskip("pyarrow", "11.0.0")
| Backport PR #53078: BUG: pd.api.interchange.from_pandas raises with all-null categorical | https://api.github.com/repos/pandas-dev/pandas/pulls/53081 | 2023-05-04T17:45:12Z | 2023-05-04T20:15:55Z | 2023-05-04T20:15:55Z | 2023-05-04T20:15:55Z |
Backport PR #53060 on branch 2.0.x (REGR: df.loc setitem losing midx names) | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 8322c8408a0e3..4b5735c5721fd 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -13,6 +13,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index da61d5e88a882..8be8ed188cce2 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -9538,7 +9538,12 @@ def _append(
"or if the Series has a name"
)
- index = Index([other.name], name=self.index.name)
+ index = Index(
+ [other.name],
+ name=self.index.names
+ if isinstance(self.index, MultiIndex)
+ else self.index.name,
+ )
row_df = other.to_frame().T
# infer_objects is needed for
# test_append_empty_frame_to_series_with_dateutil_tz
diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py
index 27b4a4be73032..e6f44359a1a62 100644
--- a/pandas/tests/indexing/multiindex/test_setitem.py
+++ b/pandas/tests/indexing/multiindex/test_setitem.py
@@ -479,6 +479,21 @@ def test_setitem_new_column_all_na(self):
df["new"] = s
assert df["new"].isna().all()
+ def test_setitem_enlargement_keep_index_names(self):
+ # GH#53053
+ mi = MultiIndex.from_tuples([(1, 2, 3)], names=["i1", "i2", "i3"])
+ df = DataFrame(data=[[10, 20, 30]], index=mi, columns=["A", "B", "C"])
+ df.loc[(0, 0, 0)] = df.loc[(1, 2, 3)]
+ mi_expected = MultiIndex.from_tuples(
+ [(1, 2, 3), (0, 0, 0)], names=["i1", "i2", "i3"]
+ )
+ expected = DataFrame(
+ data=[[10, 20, 30], [10, 20, 30]],
+ index=mi_expected,
+ columns=["A", "B", "C"],
+ )
+ tm.assert_frame_equal(df, expected)
+
@td.skip_array_manager_invalid_test # df["foo"] select multiple columns -> .values
# is not a view
| Backport PR #53060: REGR: df.loc setitem losing midx names | https://api.github.com/repos/pandas-dev/pandas/pulls/53080 | 2023-05-04T17:23:11Z | 2023-05-04T20:32:22Z | 2023-05-04T20:32:22Z | 2023-05-04T20:32:23Z |
CLN: clean Apply._try_aggregate_string_function | diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 0c2adb89a2422..585afc571132f 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -278,7 +278,7 @@ def transform_str_or_callable(self, func) -> DataFrame | Series:
kwargs = self.kwargs
if isinstance(func, str):
- return self._try_aggregate_string_function(obj, func, *args, **kwargs)
+ return self._apply_str(obj, func, *args, **kwargs)
if not args and not kwargs:
f = com.get_cython_func(func)
@@ -543,7 +543,7 @@ def apply_str(self) -> DataFrame | Series:
self.kwargs["axis"] = self.axis
else:
self.kwargs["axis"] = self.axis
- return self._try_aggregate_string_function(obj, f, *self.args, **self.kwargs)
+ return self._apply_str(obj, f, *self.args, **self.kwargs)
def apply_multiple(self) -> DataFrame | Series:
"""
@@ -601,34 +601,32 @@ def normalize_dictlike_arg(
func = new_func
return func
- def _try_aggregate_string_function(self, obj, arg: str, *args, **kwargs):
+ def _apply_str(self, obj, arg: str, *args, **kwargs):
"""
if arg is a string, then try to operate on it:
- - try to find a function (or attribute) on ourselves
+ - try to find a function (or attribute) on obj
- try to find a numpy function
- raise
"""
assert isinstance(arg, str)
- f = getattr(obj, arg, None)
- if f is not None:
+ if hasattr(obj, arg):
+ f = getattr(obj, arg)
if callable(f):
return f(*args, **kwargs)
- # people may try to aggregate on a non-callable attribute
+ # people may aggregate on a non-callable attribute
# but don't let them think they can pass args to it
assert len(args) == 0
assert len([kwarg for kwarg in kwargs if kwarg not in ["axis"]]) == 0
return f
-
- f = getattr(np, arg, None)
- if f is not None and hasattr(obj, "__array__"):
+ elif hasattr(np, arg) and hasattr(obj, "__array__"):
# in particular exclude Window
+ f = getattr(np, arg)
return f(obj, *args, **kwargs)
-
- raise AttributeError(
- f"'{arg}' is not a valid function for '{type(obj).__name__}' object"
- )
+ else:
+ msg = f"'{arg}' is not a valid function for '{type(obj).__name__}' object"
+ raise AttributeError(msg)
class NDFrameApply(Apply):
| CC @rhshadrach. | https://api.github.com/repos/pandas-dev/pandas/pulls/53079 | 2023-05-04T16:25:21Z | 2023-05-18T16:27:19Z | 2023-05-18T16:27:19Z | 2023-05-18T16:49:38Z |
BUG: pd.api.interchange.from_pandas raises with all-null categorical | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index b6c6df8424ef1..e10fc77699dd6 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -20,6 +20,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
+- Bug in :func:`api.interchange.from_dataframe` was raising ``IndexError`` on empty categorical data (:issue:`53077`)
- Bug in :func:`api.interchange.from_dataframe` was returning :class:`DataFrame`'s of incorrect sizes when called on slices (:issue:`52824`)
- Bug in :func:`api.interchange.from_dataframe` was unnecessarily raising on bitmasks (:issue:`49888`)
- Bug in :func:`to_timedelta` was raising ``ValueError`` with ``pandas.NA`` (:issue:`52909`)
diff --git a/pandas/core/interchange/from_dataframe.py b/pandas/core/interchange/from_dataframe.py
index 45d6bdd7917c1..78e530f915117 100644
--- a/pandas/core/interchange/from_dataframe.py
+++ b/pandas/core/interchange/from_dataframe.py
@@ -202,7 +202,10 @@ def categorical_column_to_series(col: Column) -> tuple[pd.Series, Any]:
# Doing module in order to not get ``IndexError`` for
# out-of-bounds sentinel values in `codes`
- values = categories[codes % len(categories)]
+ if len(categories) > 0:
+ values = categories[codes % len(categories)]
+ else:
+ values = codes
cat = pd.Categorical(
values, categories=categories, ordered=categorical["is_ordered"]
diff --git a/pandas/tests/interchange/test_impl.py b/pandas/tests/interchange/test_impl.py
index d393ba6fd3957..301cccec9e0ed 100644
--- a/pandas/tests/interchange/test_impl.py
+++ b/pandas/tests/interchange/test_impl.py
@@ -89,6 +89,18 @@ def test_categorical_pyarrow():
tm.assert_frame_equal(result, expected)
+def test_empty_categorical_pyarrow():
+ # https://github.com/pandas-dev/pandas/issues/53077
+ pa = pytest.importorskip("pyarrow", "11.0.0")
+
+ arr = [None]
+ table = pa.table({"arr": pa.array(arr, "float64").dictionary_encode()})
+ exchange_df = table.__dataframe__()
+ result = pd.api.interchange.from_dataframe(exchange_df)
+ expected = pd.DataFrame({"arr": pd.Categorical([np.nan])})
+ tm.assert_frame_equal(result, expected)
+
+
def test_large_string_pyarrow():
# GH 52795
pa = pytest.importorskip("pyarrow", "11.0.0")
| - [ ] closes #53077 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
pretty simple, hoping this can be bundled together with the other interchange fixes in 2.0.2
| https://api.github.com/repos/pandas-dev/pandas/pulls/53078 | 2023-05-04T15:27:38Z | 2023-05-04T17:45:05Z | 2023-05-04T17:45:05Z | 2023-05-04T17:45:11Z |
Added test for sort_index parameter multiindex 'sort_remaining' = False | diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py
index af55bc424d396..d7de369703ae9 100644
--- a/pandas/tests/frame/methods/test_sort_index.py
+++ b/pandas/tests/frame/methods/test_sort_index.py
@@ -914,3 +914,32 @@ def test_sort_index_na_position(self):
expected = df.copy()
result = df.sort_index(level=[0, 1], na_position="last")
tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("ascending", [True, False])
+ def test_sort_index_multiindex_sort_remaining(self, ascending):
+ # GH #24247
+ df = DataFrame(
+ {"A": [1, 2, 3, 4, 5], "B": [10, 20, 30, 40, 50]},
+ index=MultiIndex.from_tuples(
+ [("a", "x"), ("a", "y"), ("b", "x"), ("b", "y"), ("c", "x")]
+ ),
+ )
+
+ result = df.sort_index(level=1, sort_remaining=False, ascending=ascending)
+
+ if ascending:
+ expected = DataFrame(
+ {"A": [1, 3, 5, 2, 4], "B": [10, 30, 50, 20, 40]},
+ index=MultiIndex.from_tuples(
+ [("a", "x"), ("b", "x"), ("c", "x"), ("a", "y"), ("b", "y")]
+ ),
+ )
+ else:
+ expected = DataFrame(
+ {"A": [2, 4, 1, 3, 5], "B": [20, 40, 10, 30, 50]},
+ index=MultiIndex.from_tuples(
+ [("a", "y"), ("b", "y"), ("a", "x"), ("b", "x"), ("c", "x")]
+ ),
+ )
+
+ tm.assert_frame_equal(result, expected)
| - [x] closes #24247
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests)
Issue fixed on main, added validation tests | https://api.github.com/repos/pandas-dev/pandas/pulls/53076 | 2023-05-04T15:01:50Z | 2023-05-06T14:43:31Z | 2023-05-06T14:43:31Z | 2023-05-08T07:08:34Z |
CLN: avoid upcasting in tests where unnecessary (PDEP-6 precursor) | diff --git a/pandas/tests/indexing/test_at.py b/pandas/tests/indexing/test_at.py
index 9df6cb640257e..01315647c464b 100644
--- a/pandas/tests/indexing/test_at.py
+++ b/pandas/tests/indexing/test_at.py
@@ -114,9 +114,10 @@ def test_at_setitem_multiindex(self):
@pytest.mark.parametrize("row", (Timestamp("2019-01-01"), "2019-01-01"))
def test_at_datetime_index(self, row):
+ # Set float64 dtype to avoid upcast when setting .5
df = DataFrame(
data=[[1] * 2], index=DatetimeIndex(data=["2019-01-01", "2019-01-02"])
- )
+ ).astype({0: "float64"})
expected = DataFrame(
data=[[0.5, 1], [1.0, 1]],
index=DatetimeIndex(data=["2019-01-01", "2019-01-02"]),
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index bd9abbdb32441..bfa9a6497b3d5 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -719,7 +719,8 @@ def test_iloc_setitem_with_scalar_index(self, indexer, value):
# assigning like "df.iloc[0, [0]] = ['Z']" should be evaluated
# elementwisely, not using "setter('A', ['Z'])".
- df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
+ # Set object type to avoid upcast when setting "Z"
+ df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"]).astype({"A": object})
df.iloc[0, indexer] = value
result = df.iloc[0, 0]
diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py
index 1cb8c4f808fbd..1bc7953014d89 100644
--- a/pandas/tests/indexing/test_scalar.py
+++ b/pandas/tests/indexing/test_scalar.py
@@ -202,7 +202,7 @@ def test_mixed_index_at_iat_loc_iloc_dataframe(self):
def test_iat_setter_incompatible_assignment(self):
# GH 23236
- result = DataFrame({"a": [0, 1], "b": [4, 5]})
+ result = DataFrame({"a": [0.0, 1.0], "b": [4, 5]})
result.iat[0, 0] = None
expected = DataFrame({"a": [None, 1], "b": [4, 5]})
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/interchange/test_impl.py b/pandas/tests/interchange/test_impl.py
index d393ba6fd3957..28d7d6b55ba5f 100644
--- a/pandas/tests/interchange/test_impl.py
+++ b/pandas/tests/interchange/test_impl.py
@@ -157,7 +157,7 @@ def test_dataframe(data):
def test_missing_from_masked():
df = pd.DataFrame(
{
- "x": np.array([1, 2, 3, 4, 0]),
+ "x": np.array([1.0, 2.0, 3.0, 4.0, 0.0]),
"y": np.array([1.5, 2.5, 3.5, 4.5, 0]),
"z": np.array([True, False, True, True, True]),
}
diff --git a/pandas/tests/reshape/test_from_dummies.py b/pandas/tests/reshape/test_from_dummies.py
index 0c4c61e932033..aab49538a2dcf 100644
--- a/pandas/tests/reshape/test_from_dummies.py
+++ b/pandas/tests/reshape/test_from_dummies.py
@@ -163,6 +163,8 @@ def test_error_with_prefix_default_category_dict_not_complete(
def test_error_with_prefix_contains_nan(dummies_basic):
+ # Set float64 dtype to avoid upcast when setting np.nan
+ dummies_basic["col2_c"] = dummies_basic["col2_c"].astype("float64")
dummies_basic.loc[2, "col2_c"] = np.nan
with pytest.raises(
ValueError, match=r"Dummy DataFrame contains NA value in column: 'col2_c'"
@@ -171,6 +173,8 @@ def test_error_with_prefix_contains_nan(dummies_basic):
def test_error_with_prefix_contains_non_dummies(dummies_basic):
+ # Set object dtype to avoid upcast when setting "str"
+ dummies_basic["col2_c"] = dummies_basic["col2_c"].astype(object)
dummies_basic.loc[2, "col2_c"] = "str"
with pytest.raises(TypeError, match=r"Passed DataFrame contains non-dummy data"):
from_dummies(dummies_basic, sep="_")
diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py
index afcf07489c002..af7e629f74227 100644
--- a/pandas/tests/series/methods/test_update.py
+++ b/pandas/tests/series/methods/test_update.py
@@ -25,6 +25,8 @@ def test_update(self, using_copy_on_write):
# GH 3217
df = DataFrame([{"a": 1}, {"a": 3, "b": 2}])
df["c"] = np.nan
+ # Cast to object to avoid upcast when setting "foo"
+ df["c"] = df["c"].astype(object)
df_orig = df.copy()
df["c"].update(Series(["foo"], index=[0]))
diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py
index c7d80a705b2e4..6cf67e22b6f19 100644
--- a/pandas/tests/series/test_missing.py
+++ b/pandas/tests/series/test_missing.py
@@ -91,7 +91,8 @@ def test_valid(self, datetime_series):
def test_hasnans_uncached_for_series():
# GH#19700
- idx = Index([0, 1])
+ # set float64 dtype to avoid upcast when setting nan
+ idx = Index([0, 1], dtype="float64")
assert idx.hasnans is False
assert "hasnans" in idx._cache
ser = idx.to_series()
| another precursor to PDEP6, similar to https://github.com/pandas-dev/pandas/pull/52957
getting there...I think most of the remaining ones are when the test explicitly checks for upcasting behaviour, and so probably can't be changed right now | https://api.github.com/repos/pandas-dev/pandas/pulls/53075 | 2023-05-04T14:39:53Z | 2023-05-04T17:05:16Z | 2023-05-04T17:05:16Z | 2023-05-04T17:05:23Z |
Fix ns precision isoformat | diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx
index 27ff719b1a143..9e4bba1cf3544 100644
--- a/pandas/_libs/tslibs/timestamps.pyx
+++ b/pandas/_libs/tslibs/timestamps.pyx
@@ -1026,7 +1026,7 @@ cdef class _Timestamp(ABCTimestamp):
base1, base2 = base, ""
if timespec == "nanoseconds" or (timespec == "auto" and self.nanosecond):
- if self.microsecond:
+ if self.microsecond or timespec == "nanoseconds":
base1 += f"{self.nanosecond:03d}"
else:
base1 += f".{self.nanosecond:09d}"
diff --git a/pandas/tests/tslibs/test_parse_iso8601.py b/pandas/tests/tslibs/test_parse_iso8601.py
index 72b136e17445e..1992faae2ea6a 100644
--- a/pandas/tests/tslibs/test_parse_iso8601.py
+++ b/pandas/tests/tslibs/test_parse_iso8601.py
@@ -73,3 +73,47 @@ def test_parsers_iso8601_leading_space():
date_str, expected = ("2013-1-1 5:30:00", datetime(2013, 1, 1, 5, 30))
actual = tslib._test_parse_iso8601(" " * 200 + date_str)
assert actual == expected
+
+
+@pytest.mark.parametrize(
+ "date_str, timespec, exp",
+ [
+ ("2023-01-01 00:00:00", "auto", "2023-01-01T00:00:00"),
+ ("2023-01-01 00:00:00", "seconds", "2023-01-01T00:00:00"),
+ ("2023-01-01 00:00:00", "milliseconds", "2023-01-01T00:00:00.000"),
+ ("2023-01-01 00:00:00", "microseconds", "2023-01-01T00:00:00.000000"),
+ ("2023-01-01 00:00:00", "nanoseconds", "2023-01-01T00:00:00.000000000"),
+ ("2023-01-01 00:00:00.001", "auto", "2023-01-01T00:00:00.001000"),
+ ("2023-01-01 00:00:00.001", "seconds", "2023-01-01T00:00:00"),
+ ("2023-01-01 00:00:00.001", "milliseconds", "2023-01-01T00:00:00.001"),
+ ("2023-01-01 00:00:00.001", "microseconds", "2023-01-01T00:00:00.001000"),
+ ("2023-01-01 00:00:00.001", "nanoseconds", "2023-01-01T00:00:00.001000000"),
+ ("2023-01-01 00:00:00.000001", "auto", "2023-01-01T00:00:00.000001"),
+ ("2023-01-01 00:00:00.000001", "seconds", "2023-01-01T00:00:00"),
+ ("2023-01-01 00:00:00.000001", "milliseconds", "2023-01-01T00:00:00.000"),
+ ("2023-01-01 00:00:00.000001", "microseconds", "2023-01-01T00:00:00.000001"),
+ ("2023-01-01 00:00:00.000001", "nanoseconds", "2023-01-01T00:00:00.000001000"),
+ ("2023-01-01 00:00:00.000000001", "auto", "2023-01-01T00:00:00.000000001"),
+ ("2023-01-01 00:00:00.000000001", "seconds", "2023-01-01T00:00:00"),
+ ("2023-01-01 00:00:00.000000001", "milliseconds", "2023-01-01T00:00:00.000"),
+ ("2023-01-01 00:00:00.000000001", "microseconds", "2023-01-01T00:00:00.000000"),
+ (
+ "2023-01-01 00:00:00.000000001",
+ "nanoseconds",
+ "2023-01-01T00:00:00.000000001",
+ ),
+ ("2023-01-01 00:00:00.000001001", "auto", "2023-01-01T00:00:00.000001001"),
+ ("2023-01-01 00:00:00.000001001", "seconds", "2023-01-01T00:00:00"),
+ ("2023-01-01 00:00:00.000001001", "milliseconds", "2023-01-01T00:00:00.000"),
+ ("2023-01-01 00:00:00.000001001", "microseconds", "2023-01-01T00:00:00.000001"),
+ (
+ "2023-01-01 00:00:00.000001001",
+ "nanoseconds",
+ "2023-01-01T00:00:00.000001001",
+ ),
+ ],
+)
+def test_iso8601_formatter(date_str: str, timespec: str, exp: str):
+ # GH#53020
+ ts = Timestamp(date_str)
+ assert ts.isoformat(timespec=timespec) == exp
| - [x] closes #53020
- [x] [Tests added and passed] Added new tests
- [x] All [code checks passed]
- [x] Added [type annotations]
- [x] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file
| https://api.github.com/repos/pandas-dev/pandas/pulls/53073 | 2023-05-04T13:35:35Z | 2023-05-09T18:04:04Z | 2023-05-09T18:04:04Z | 2023-05-09T18:04:13Z |
CLN: avoid upcasting in tests where unnecessary (PDEP-6 precursor) | diff --git a/pandas/tests/arrays/masked_shared.py b/pandas/tests/arrays/masked_shared.py
index 831fc64512b98..b0523ed496d45 100644
--- a/pandas/tests/arrays/masked_shared.py
+++ b/pandas/tests/arrays/masked_shared.py
@@ -24,11 +24,11 @@ def _compare_other(self, data, op, other):
ser = pd.Series(data)
result = op(ser, other)
- expected = op(pd.Series(data._data), other)
+ # Set nullable dtype here to avoid upcasting when setting to pd.NA below
+ expected = op(pd.Series(data._data), other).astype("boolean")
# fill the nan locations
expected[data._mask] = pd.NA
- expected = expected.astype("boolean")
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/frame/indexing/test_mask.py b/pandas/tests/frame/indexing/test_mask.py
index 233e2dcce81a7..ed0bf256d1ee7 100644
--- a/pandas/tests/frame/indexing/test_mask.py
+++ b/pandas/tests/frame/indexing/test_mask.py
@@ -145,7 +145,7 @@ def test_mask_return_dtype():
def test_mask_inplace_no_other():
# GH#51685
- df = DataFrame({"a": [1, 2], "b": ["x", "y"]})
+ df = DataFrame({"a": [1.0, 2.0], "b": ["x", "y"]})
cond = DataFrame({"a": [True, False], "b": [False, True]})
df.mask(cond, inplace=True)
expected = DataFrame({"a": [np.nan, 2], "b": ["x", np.nan]})
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 4c8b93814e277..a51955548232b 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -987,7 +987,8 @@ def test_setitem_other_callable(self):
def inc(x):
return x + 1
- df = DataFrame([[-1, 1], [1, -1]])
+ # Set dtype object straight away to avoid upcast when setting inc below
+ df = DataFrame([[-1, 1], [1, -1]], dtype=object)
df[df > 0] = inc
expected = DataFrame([[-1, inc], [inc, -1]])
diff --git a/pandas/tests/frame/methods/test_asof.py b/pandas/tests/frame/methods/test_asof.py
index a08f8bf5f502e..09cb3fbe1bacb 100644
--- a/pandas/tests/frame/methods/test_asof.py
+++ b/pandas/tests/frame/methods/test_asof.py
@@ -79,7 +79,8 @@ def test_missing(self, date_range_frame):
# GH 15118
# no match found - `where` value before earliest date in index
N = 10
- df = date_range_frame.iloc[:N].copy()
+ # Cast to 'float64' to avoid upcast when introducing nan in df.asof
+ df = date_range_frame.iloc[:N].copy().astype("float64")
result = df.asof("1989-12-31")
diff --git a/pandas/tests/frame/methods/test_map.py b/pandas/tests/frame/methods/test_map.py
index 596ef453b2e02..53cae2d079217 100644
--- a/pandas/tests/frame/methods/test_map.py
+++ b/pandas/tests/frame/methods/test_map.py
@@ -111,7 +111,8 @@ def test_map_na_ignore(float_frame):
strlen_frame_na_ignore = float_frame_with_na.map(
lambda x: len(str(x)), na_action="ignore"
)
- strlen_frame_with_na = strlen_frame.copy()
+ # Set float64 type to avoid upcast when setting NA below
+ strlen_frame_with_na = strlen_frame.copy().astype("float64")
strlen_frame_with_na[mask] = pd.NA
tm.assert_frame_equal(strlen_frame_na_ignore, strlen_frame_with_na)
diff --git a/pandas/tests/groupby/test_counting.py b/pandas/tests/groupby/test_counting.py
index acfb0ef657023..97e4e8a852429 100644
--- a/pandas/tests/groupby/test_counting.py
+++ b/pandas/tests/groupby/test_counting.py
@@ -327,9 +327,10 @@ def test_count_object():
def test_count_cross_type():
# GH8169
+ # Set float64 dtype to avoid upcast when setting nan below
vals = np.hstack(
(np.random.randint(0, 5, (100, 2)), np.random.randint(0, 2, (100, 2)))
- )
+ ).astype("float64")
df = DataFrame(vals, columns=["a", "b", "c", "d"])
df[df == 2] = np.nan
diff --git a/pandas/tests/groupby/test_filters.py b/pandas/tests/groupby/test_filters.py
index d580b89f2f006..ccf307fbdf380 100644
--- a/pandas/tests/groupby/test_filters.py
+++ b/pandas/tests/groupby/test_filters.py
@@ -363,7 +363,8 @@ def test_filter_and_transform_with_non_unique_int_index():
tm.assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
- expected = df.copy()
+ # Cast to avoid upcast when setting nan below
+ expected = df.copy().astype("float64")
expected.iloc[[0, 3, 5, 6]] = np.nan
tm.assert_frame_equal(actual, expected)
@@ -405,7 +406,8 @@ def test_filter_and_transform_with_multiple_non_unique_int_index():
tm.assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
- expected = df.copy()
+ # Cast to avoid upcast when setting nan below
+ expected = df.copy().astype("float64")
expected.iloc[[0, 3, 5, 6]] = np.nan
tm.assert_frame_equal(actual, expected)
@@ -447,7 +449,8 @@ def test_filter_and_transform_with_non_unique_float_index():
tm.assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
- expected = df.copy()
+ # Cast to avoid upcast when setting nan below
+ expected = df.copy().astype("float64")
expected.iloc[[0, 3, 5, 6]] = np.nan
tm.assert_frame_equal(actual, expected)
@@ -492,7 +495,8 @@ def test_filter_and_transform_with_non_unique_timestamp_index():
tm.assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
- expected = df.copy()
+ # Cast to avoid upcast when setting nan below
+ expected = df.copy().astype("float64")
expected.iloc[[0, 3, 5, 6]] = np.nan
tm.assert_frame_equal(actual, expected)
@@ -534,7 +538,8 @@ def test_filter_and_transform_with_non_unique_string_index():
tm.assert_frame_equal(actual, expected)
actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False)
- expected = df.copy()
+ # Cast to avoid upcast when setting nan below
+ expected = df.copy().astype("float64")
expected.iloc[[0, 3, 5, 6]] = np.nan
tm.assert_frame_equal(actual, expected)
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 8ea8b505cb28c..383a008d1f32b 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -166,7 +166,8 @@ def f_1(grp):
return grp.iloc[0]
result = df.groupby("A").apply(f_1)[["B"]]
- e = expected.copy()
+ # Cast to avoid upcast when setting nan below
+ e = expected.copy().astype("float64")
e.loc["Tiger"] = np.nan
tm.assert_frame_equal(result, e)
| another precursor to PDEP6, similar to #52957 | https://api.github.com/repos/pandas-dev/pandas/pulls/53070 | 2023-05-04T10:25:08Z | 2023-05-04T13:43:13Z | 2023-05-04T13:43:13Z | 2023-05-04T13:43:20Z |
REF: implement Manager.concat_vertical, concat_horizontal | diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index c3be914aa095d..d7b899cc192fc 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -3,6 +3,7 @@
"""
from __future__ import annotations
+import itertools
from typing import (
TYPE_CHECKING,
Any,
@@ -20,9 +21,13 @@
)
from pandas.util._validators import validate_bool_kwarg
-from pandas.core.dtypes.astype import astype_array_safe
+from pandas.core.dtypes.astype import (
+ astype_array,
+ astype_array_safe,
+)
from pandas.core.dtypes.cast import (
ensure_dtype_can_hold_na,
+ find_common_type,
infer_dtype_from_scalar,
)
from pandas.core.dtypes.common import (
@@ -1136,6 +1141,30 @@ def as_array(
return result
+ @classmethod
+ def concat_horizontal(cls, mgrs: list[Self], axes: list[Index]) -> Self:
+ """
+ Concatenate uniformly-indexed ArrayManagers horizontally.
+ """
+ # concatting along the columns -> combine reindexed arrays in a single manager
+ arrays = list(itertools.chain.from_iterable([mgr.arrays for mgr in mgrs]))
+ new_mgr = cls(arrays, [axes[1], axes[0]], verify_integrity=False)
+ return new_mgr
+
+ @classmethod
+ def concat_vertical(cls, mgrs: list[Self], axes: list[Index]) -> Self:
+ """
+ Concatenate uniformly-indexed ArrayManagers vertically.
+ """
+ # concatting along the rows -> concat the reindexed arrays
+ # TODO(ArrayManager) doesn't yet preserve the correct dtype
+ arrays = [
+ concat_arrays([mgrs[i].arrays[j] for i in range(len(mgrs))])
+ for j in range(len(mgrs[0].arrays))
+ ]
+ new_mgr = cls(arrays, [axes[1], axes[0]], verify_integrity=False)
+ return new_mgr
+
class SingleArrayManager(BaseArrayManager, SingleDataManager):
__slots__ = [
@@ -1354,3 +1383,59 @@ def to_array(self, dtype: DtypeObj) -> ArrayLike:
arr = np.empty(self.n, dtype=dtype)
arr.fill(fill_value)
return ensure_wrapped_if_datetimelike(arr)
+
+
+def concat_arrays(to_concat: list) -> ArrayLike:
+ """
+ Alternative for concat_compat but specialized for use in the ArrayManager.
+
+ Differences: only deals with 1D arrays (no axis keyword), assumes
+ ensure_wrapped_if_datetimelike and does not skip empty arrays to determine
+ the dtype.
+ In addition ensures that all NullArrayProxies get replaced with actual
+ arrays.
+
+ Parameters
+ ----------
+ to_concat : list of arrays
+
+ Returns
+ -------
+ np.ndarray or ExtensionArray
+ """
+ # ignore the all-NA proxies to determine the resulting dtype
+ to_concat_no_proxy = [x for x in to_concat if not isinstance(x, NullArrayProxy)]
+
+ dtypes = {x.dtype for x in to_concat_no_proxy}
+ single_dtype = len(dtypes) == 1
+
+ if single_dtype:
+ target_dtype = to_concat_no_proxy[0].dtype
+ elif all(x.kind in "iub" and isinstance(x, np.dtype) for x in dtypes):
+ # GH#42092
+ target_dtype = np.find_common_type(list(dtypes), [])
+ else:
+ target_dtype = find_common_type([arr.dtype for arr in to_concat_no_proxy])
+
+ to_concat = [
+ arr.to_array(target_dtype)
+ if isinstance(arr, NullArrayProxy)
+ else astype_array(arr, target_dtype, copy=False)
+ for arr in to_concat
+ ]
+
+ if isinstance(to_concat[0], ExtensionArray):
+ cls = type(to_concat[0])
+ return cls._concat_same_type(to_concat)
+
+ result = np.concatenate(to_concat)
+
+ # TODO decide on exact behaviour (we shouldn't do this only for empty result)
+ # see https://github.com/pandas-dev/pandas/issues/39817
+ if len(result) == 0:
+ # all empties -> check for bool to not coerce to float
+ kinds = {obj.dtype.kind for obj in to_concat_no_proxy}
+ if len(kinds) != 1:
+ if "b" in kinds:
+ result = result.astype(object)
+ return result
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index d2abf3dcb628d..e34e7fbf1035e 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import itertools
from typing import (
TYPE_CHECKING,
Sequence,
@@ -20,7 +19,6 @@
from pandas.util._decorators import cache_readonly
from pandas.util._exceptions import find_stack_level
-from pandas.core.dtypes.astype import astype_array
from pandas.core.dtypes.cast import (
ensure_dtype_can_hold_na,
find_common_type,
@@ -38,13 +36,9 @@
isna_all,
)
-from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.sparse import SparseDtype
from pandas.core.construction import ensure_wrapped_if_datetimelike
-from pandas.core.internals.array_manager import (
- ArrayManager,
- NullArrayProxy,
-)
+from pandas.core.internals.array_manager import ArrayManager
from pandas.core.internals.blocks import (
ensure_block_shape,
new_block_2d,
@@ -59,7 +53,7 @@
ArrayLike,
AxisInt,
DtypeObj,
- Manager,
+ Manager2D,
Shape,
)
@@ -71,8 +65,8 @@
def _concatenate_array_managers(
- mgrs: list[Manager], axes: list[Index], concat_axis: AxisInt
-) -> Manager:
+ mgrs: list[ArrayManager], axes: list[Index], concat_axis: AxisInt
+) -> Manager2D:
"""
Concatenate array managers into one.
@@ -87,80 +81,16 @@ def _concatenate_array_managers(
ArrayManager
"""
if concat_axis == 1:
- # concatting along the rows -> concat the reindexed arrays
- # TODO(ArrayManager) doesn't yet preserve the correct dtype
- arrays = [
- concat_arrays([mgrs[i].arrays[j] for i in range(len(mgrs))])
- for j in range(len(mgrs[0].arrays))
- ]
+ return mgrs[0].concat_vertical(mgrs, axes)
else:
# concatting along the columns -> combine reindexed arrays in a single manager
assert concat_axis == 0
- arrays = list(itertools.chain.from_iterable([mgr.arrays for mgr in mgrs]))
-
- new_mgr = ArrayManager(arrays, [axes[1], axes[0]], verify_integrity=False)
- return new_mgr
-
-
-def concat_arrays(to_concat: list) -> ArrayLike:
- """
- Alternative for concat_compat but specialized for use in the ArrayManager.
-
- Differences: only deals with 1D arrays (no axis keyword), assumes
- ensure_wrapped_if_datetimelike and does not skip empty arrays to determine
- the dtype.
- In addition ensures that all NullArrayProxies get replaced with actual
- arrays.
-
- Parameters
- ----------
- to_concat : list of arrays
-
- Returns
- -------
- np.ndarray or ExtensionArray
- """
- # ignore the all-NA proxies to determine the resulting dtype
- to_concat_no_proxy = [x for x in to_concat if not isinstance(x, NullArrayProxy)]
-
- dtypes = {x.dtype for x in to_concat_no_proxy}
- single_dtype = len(dtypes) == 1
-
- if single_dtype:
- target_dtype = to_concat_no_proxy[0].dtype
- elif all(x.kind in "iub" and isinstance(x, np.dtype) for x in dtypes):
- # GH#42092
- target_dtype = np.find_common_type(list(dtypes), [])
- else:
- target_dtype = find_common_type([arr.dtype for arr in to_concat_no_proxy])
-
- to_concat = [
- arr.to_array(target_dtype)
- if isinstance(arr, NullArrayProxy)
- else astype_array(arr, target_dtype, copy=False)
- for arr in to_concat
- ]
-
- if isinstance(to_concat[0], ExtensionArray):
- cls = type(to_concat[0])
- return cls._concat_same_type(to_concat)
-
- result = np.concatenate(to_concat)
-
- # TODO decide on exact behaviour (we shouldn't do this only for empty result)
- # see https://github.com/pandas-dev/pandas/issues/39817
- if len(result) == 0:
- # all empties -> check for bool to not coerce to float
- kinds = {obj.dtype.kind for obj in to_concat_no_proxy}
- if len(kinds) != 1:
- if "b" in kinds:
- result = result.astype(object)
- return result
+ return mgrs[0].concat_horizontal(mgrs, axes)
def concatenate_managers(
mgrs_indexers, axes: list[Index], concat_axis: AxisInt, copy: bool
-) -> Manager:
+) -> Manager2D:
"""
Concatenate block managers into one.
@@ -196,7 +126,7 @@ def concatenate_managers(
if concat_axis == 0:
mgrs = _maybe_reindex_columns_na_proxy(axes, mgrs_indexers, needs_copy)
- return _concat_managers_axis0(mgrs, axes)
+ return mgrs[0].concat_horizontal(mgrs, axes)
if len(mgrs_indexers) > 0 and mgrs_indexers[0][0].nblocks > 0:
first_dtype = mgrs_indexers[0][0].blocks[0].dtype
@@ -266,29 +196,6 @@ def concatenate_managers(
return BlockManager(tuple(blocks), axes)
-def _concat_managers_axis0(mgrs: list[BlockManager], axes: list[Index]) -> BlockManager:
- """
- concat_managers specialized to concat_axis=0, with reindexing already
- having been done in _maybe_reindex_columns_na_proxy.
- """
-
- offset = 0
- blocks: list[Block] = []
- for i, mgr in enumerate(mgrs):
- for blk in mgr.blocks:
- # We need to do getitem_block here otherwise we would be altering
- # blk.mgr_locs in place, which would render it invalid. This is only
- # relevant in the copy=False case.
- nb = blk.getitem_block(slice(None))
- nb._mgr_locs = nb._mgr_locs.add(offset)
- blocks.append(nb)
-
- offset += len(mgr.items)
-
- result = BlockManager(tuple(blocks), axes)
- return result
-
-
def _maybe_reindex_columns_na_proxy(
axes: list[Index],
mgrs_indexers: list[tuple[BlockManager, dict[int, np.ndarray]]],
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 36dd0cece0f20..329b98da6a4d0 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1841,6 +1841,37 @@ def _consolidate_inplace(self) -> None:
self._known_consolidated = True
self._rebuild_blknos_and_blklocs()
+ # ----------------------------------------------------------------
+ # Concatenation
+
+ @classmethod
+ def concat_horizontal(cls, mgrs: list[Self], axes: list[Index]) -> Self:
+ """
+ Concatenate uniformly-indexed BlockManagers horizontally.
+ """
+ offset = 0
+ blocks: list[Block] = []
+ for mgr in mgrs:
+ for blk in mgr.blocks:
+ # We need to do getitem_block here otherwise we would be altering
+ # blk.mgr_locs in place, which would render it invalid. This is only
+ # relevant in the copy=False case.
+ nb = blk.getitem_block(slice(None))
+ nb._mgr_locs = nb._mgr_locs.add(offset)
+ blocks.append(nb)
+
+ offset += len(mgr.items)
+
+ new_mgr = cls(tuple(blocks), axes)
+ return new_mgr
+
+ @classmethod
+ def concat_vertical(cls, mgrs: list[Self], axes: list[Index]) -> Self:
+ """
+ Concatenate uniformly-indexed BlockManagers vertically.
+ """
+ raise NotImplementedError("This logic lives (for now) in internals.concat")
+
class SingleBlockManager(BaseBlockManager, SingleDataManager):
"""manage a single block with"""
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53066 | 2023-05-04T01:48:49Z | 2023-05-04T22:11:07Z | 2023-05-04T22:11:07Z | 2023-05-04T22:14:54Z |
CLN: remove pandas_dtype kwd from infer_dtype_from_x | diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py
index 8c8d962e7782b..74cc30a4e030d 100644
--- a/pandas/core/array_algos/putmask.py
+++ b/pandas/core/array_algos/putmask.py
@@ -136,7 +136,7 @@ def setitem_datetimelike_compat(values: np.ndarray, num_set: int, other):
other : Any
"""
if values.dtype == object:
- dtype, _ = infer_dtype_from(other, pandas_dtype=True)
+ dtype, _ = infer_dtype_from(other)
if isinstance(dtype, np.dtype) and dtype.kind in "mM":
# https://github.com/numpy/numpy/issues/12550
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index db8bdd08ee112..21c490d360f0d 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -631,7 +631,7 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan):
# returns tuple of (dtype, fill_value)
if issubclass(dtype.type, np.datetime64):
- inferred, fv = infer_dtype_from_scalar(fill_value, pandas_dtype=True)
+ inferred, fv = infer_dtype_from_scalar(fill_value)
if inferred == dtype:
return dtype, fv
@@ -645,7 +645,7 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan):
return _dtype_obj, fill_value
elif issubclass(dtype.type, np.timedelta64):
- inferred, fv = infer_dtype_from_scalar(fill_value, pandas_dtype=True)
+ inferred, fv = infer_dtype_from_scalar(fill_value)
if inferred == dtype:
return dtype, fv
@@ -735,33 +735,26 @@ def _ensure_dtype_type(value, dtype: np.dtype):
return dtype.type(value)
-def infer_dtype_from(val, pandas_dtype: bool = False) -> tuple[DtypeObj, Any]:
+def infer_dtype_from(val) -> tuple[DtypeObj, Any]:
"""
Interpret the dtype from a scalar or array.
Parameters
----------
val : object
- pandas_dtype : bool, default False
- whether to infer dtype including pandas extension types.
- If False, scalar/array belongs to pandas extension types is inferred as
- object
"""
if not is_list_like(val):
- return infer_dtype_from_scalar(val, pandas_dtype=pandas_dtype)
- return infer_dtype_from_array(val, pandas_dtype=pandas_dtype)
+ return infer_dtype_from_scalar(val)
+ return infer_dtype_from_array(val)
-def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> tuple[DtypeObj, Any]:
+def infer_dtype_from_scalar(val) -> tuple[DtypeObj, Any]:
"""
Interpret the dtype from a scalar.
Parameters
----------
- pandas_dtype : bool, default False
- whether to infer dtype including pandas extension types.
- If False, scalar belongs to pandas extension types is inferred as
- object
+ val : object
"""
dtype: DtypeObj = _dtype_obj
@@ -796,11 +789,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> tuple[DtypeObj,
dtype = val.dtype
# TODO: test with datetime(2920, 10, 1) based on test_replace_dtypes
else:
- if pandas_dtype:
- dtype = DatetimeTZDtype(unit="ns", tz=val.tz)
- else:
- # return datetimetz as object
- return _dtype_obj, val
+ dtype = DatetimeTZDtype(unit="ns", tz=val.tz)
elif isinstance(val, (np.timedelta64, dt.timedelta)):
try:
@@ -834,12 +823,11 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> tuple[DtypeObj,
elif is_complex(val):
dtype = np.dtype(np.complex_)
- elif pandas_dtype:
- if lib.is_period(val):
- dtype = PeriodDtype(freq=val.freq)
- elif lib.is_interval(val):
- subtype = infer_dtype_from_scalar(val.left, pandas_dtype=True)[0]
- dtype = IntervalDtype(subtype=subtype, closed=val.closed)
+ if lib.is_period(val):
+ dtype = PeriodDtype(freq=val.freq)
+ elif lib.is_interval(val):
+ subtype = infer_dtype_from_scalar(val.left)[0]
+ dtype = IntervalDtype(subtype=subtype, closed=val.closed)
return dtype, val
@@ -859,32 +847,18 @@ def dict_compat(d: dict[Scalar, Scalar]) -> dict[Scalar, Scalar]:
return {maybe_box_datetimelike(key): value for key, value in d.items()}
-def infer_dtype_from_array(
- arr, pandas_dtype: bool = False
-) -> tuple[DtypeObj, ArrayLike]:
+def infer_dtype_from_array(arr) -> tuple[DtypeObj, ArrayLike]:
"""
Infer the dtype from an array.
Parameters
----------
arr : array
- pandas_dtype : bool, default False
- whether to infer dtype including pandas extension types.
- If False, array belongs to pandas extension types
- is inferred as object
Returns
-------
- tuple (numpy-compat/pandas-compat dtype, array)
-
- Notes
- -----
- if pandas_dtype=False. these infer to numpy dtypes
- exactly with the exception that mixed / object dtypes
- are not coerced by stringifying or conversion
+ tuple (pandas-compat dtype, array)
- if pandas_dtype=True. datetime64tz-aware/categorical
- types will retain there character.
Examples
--------
@@ -901,7 +875,7 @@ def infer_dtype_from_array(
raise TypeError("'arr' must be list-like")
arr_dtype = getattr(arr, "dtype", None)
- if pandas_dtype and isinstance(arr_dtype, ExtensionDtype):
+ if isinstance(arr_dtype, ExtensionDtype):
return arr.dtype, arr
elif isinstance(arr, ABCSeries):
@@ -1303,7 +1277,7 @@ def find_result_type(left: ArrayLike, right: Any) -> DtypeObj:
new_dtype = ensure_dtype_can_hold_na(left.dtype)
else:
- dtype, _ = infer_dtype_from(right, pandas_dtype=True)
+ dtype, _ = infer_dtype_from(right)
new_dtype = find_common_type([left.dtype, dtype])
@@ -1466,7 +1440,7 @@ def construct_1d_arraylike_from_scalar(
if dtype is None:
try:
- dtype, value = infer_dtype_from_scalar(value, pandas_dtype=True)
+ dtype, value = infer_dtype_from_scalar(value)
except OutOfBoundsDatetime:
dtype = _dtype_obj
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 636267e54027f..3ab548aec06e2 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -824,7 +824,7 @@ def __init__(
columns = ensure_index(columns)
if not dtype:
- dtype, _ = infer_dtype_from_scalar(data, pandas_dtype=True)
+ dtype, _ = infer_dtype_from_scalar(data)
# For data is a scalar extension dtype
if isinstance(dtype, ExtensionDtype):
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index c977e4dc25584..841d8bb0749d0 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -6088,7 +6088,7 @@ def _find_common_type_compat(self, target) -> DtypeObj:
Implementation of find_common_type that adjusts for Index-specific
special cases.
"""
- target_dtype, _ = infer_dtype_from(target, pandas_dtype=True)
+ target_dtype, _ = infer_dtype_from(target)
# special case: if one dtype is uint64 and the other a signed int, return object
# See https://github.com/pandas-dev/pandas/issues/26778 for discussion
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 72c88d2967b35..50838f8c65881 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -558,7 +558,7 @@ def _maybe_convert_i8(self, key):
if scalar:
# Timestamp/Timedelta
- key_dtype, key_i8 = infer_dtype_from_scalar(key, pandas_dtype=True)
+ key_dtype, key_i8 = infer_dtype_from_scalar(key)
if lib.is_period(key):
key_i8 = key.ordinal
elif isinstance(key_i8, Timestamp):
diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index c3be914aa095d..dbc80a69a5f69 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -84,6 +84,7 @@
new_block,
to_native_types,
)
+from pandas.core.internals.managers import make_na_array
if TYPE_CHECKING:
from pandas._typing import (
@@ -665,13 +666,8 @@ def _make_na_array(self, fill_value=None, use_na_proxy: bool = False):
fill_value = np.nan
dtype, fill_value = infer_dtype_from_scalar(fill_value)
- # error: Argument "dtype" to "empty" has incompatible type "Union[dtype[Any],
- # ExtensionDtype]"; expected "Union[dtype[Any], None, type, _SupportsDType, str,
- # Union[Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], List[Any],
- # _DTypeDict, Tuple[Any, Any]]]"
- values = np.empty(self.shape_proper[0], dtype=dtype) # type: ignore[arg-type]
- values.fill(fill_value)
- return values
+ array_values = make_na_array(dtype, self.shape_proper[:1], fill_value)
+ return array_values
def _equal_values(self, other) -> bool:
"""
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 36dd0cece0f20..567ad2b741317 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -921,7 +921,7 @@ def _make_na_block(
shape = (len(placement), self.shape[1])
- dtype, fill_value = infer_dtype_from_scalar(fill_value, pandas_dtype=True)
+ dtype, fill_value = infer_dtype_from_scalar(fill_value)
block_values = make_na_array(dtype, shape, fill_value)
return new_block_2d(block_values, placement=placement)
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index 585ad50ad9069..7762ba8e2c730 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -80,11 +80,14 @@ def mask_missing(arr: ArrayLike, values_to_mask) -> npt.NDArray[np.bool_]:
# known to be holdable by arr.
# When called from Series._single_replace, values_to_mask is tuple or list
dtype, values_to_mask = infer_dtype_from(values_to_mask)
- # error: Argument "dtype" to "array" has incompatible type "Union[dtype[Any],
- # ExtensionDtype]"; expected "Union[dtype[Any], None, type, _SupportsDType, str,
- # Union[Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], List[Any],
- # _DTypeDict, Tuple[Any, Any]]]"
- values_to_mask = np.array(values_to_mask, dtype=dtype) # type: ignore[arg-type]
+
+ if isinstance(dtype, np.dtype):
+ values_to_mask = np.array(values_to_mask, dtype=dtype)
+ else:
+ cls = dtype.construct_array_type()
+ if not lib.is_list_like(values_to_mask):
+ values_to_mask = [values_to_mask]
+ values_to_mask = cls._from_sequence(values_to_mask, dtype=dtype, copy=False)
potential_na = False
if is_object_dtype(arr.dtype):
diff --git a/pandas/tests/dtypes/cast/test_infer_dtype.py b/pandas/tests/dtypes/cast/test_infer_dtype.py
index 902130bf93d54..53d0656a11f81 100644
--- a/pandas/tests/dtypes/cast/test_infer_dtype.py
+++ b/pandas/tests/dtypes/cast/test_infer_dtype.py
@@ -25,11 +25,6 @@
)
-@pytest.fixture(params=[True, False])
-def pandas_dtype(request):
- return request.param
-
-
def test_infer_dtype_from_int_scalar(any_int_numpy_dtype):
# Test that infer_dtype_from_scalar is
# returning correct dtype for int and float.
@@ -81,36 +76,32 @@ def test_infer_dtype_from_timedelta(data):
@pytest.mark.parametrize("freq", ["M", "D"])
-def test_infer_dtype_from_period(freq, pandas_dtype):
+def test_infer_dtype_from_period(freq):
p = Period("2011-01-01", freq=freq)
- dtype, val = infer_dtype_from_scalar(p, pandas_dtype=pandas_dtype)
+ dtype, val = infer_dtype_from_scalar(p)
- if pandas_dtype:
- exp_dtype = f"period[{freq}]"
- else:
- exp_dtype = np.object_
+ exp_dtype = f"period[{freq}]"
assert dtype == exp_dtype
assert val == p
-@pytest.mark.parametrize(
- "data", [date(2000, 1, 1), "foo", Timestamp(1, tz="US/Eastern")]
-)
-def test_infer_dtype_misc(data):
- dtype, val = infer_dtype_from_scalar(data)
+def test_infer_dtype_misc():
+ dt = date(2000, 1, 1)
+ dtype, val = infer_dtype_from_scalar(dt)
assert dtype == np.object_
+ ts = Timestamp(1, tz="US/Eastern")
+ dtype, val = infer_dtype_from_scalar(ts)
+ assert dtype == "datetime64[ns, US/Eastern]"
+
@pytest.mark.parametrize("tz", ["UTC", "US/Eastern", "Asia/Tokyo"])
-def test_infer_from_scalar_tz(tz, pandas_dtype):
+def test_infer_from_scalar_tz(tz):
dt = Timestamp(1, tz=tz)
- dtype, val = infer_dtype_from_scalar(dt, pandas_dtype=pandas_dtype)
+ dtype, val = infer_dtype_from_scalar(dt)
- if pandas_dtype:
- exp_dtype = f"datetime64[ns, {tz}]"
- else:
- exp_dtype = np.object_
+ exp_dtype = f"datetime64[ns, {tz}]"
assert dtype == exp_dtype
assert val == dt
@@ -126,11 +117,11 @@ def test_infer_from_scalar_tz(tz, pandas_dtype):
(Timedelta(0), Timedelta(1), "timedelta64[ns]"),
],
)
-def test_infer_from_interval(left, right, subtype, closed, pandas_dtype):
+def test_infer_from_interval(left, right, subtype, closed):
# GH 30337
interval = Interval(left, right, closed)
- result_dtype, result_value = infer_dtype_from_scalar(interval, pandas_dtype)
- expected_dtype = f"interval[{subtype}, {closed}]" if pandas_dtype else np.object_
+ result_dtype, result_value = infer_dtype_from_scalar(interval)
+ expected_dtype = f"interval[{subtype}, {closed}]"
assert result_dtype == expected_dtype
assert result_value == interval
@@ -143,54 +134,49 @@ def test_infer_dtype_from_scalar_errors():
@pytest.mark.parametrize(
- "value, expected, pandas_dtype",
+ "value, expected",
[
- ("foo", np.object_, False),
- (b"foo", np.object_, False),
- (1, np.int64, False),
- (1.5, np.float_, False),
- (np.datetime64("2016-01-01"), np.dtype("M8[ns]"), False),
- (Timestamp("20160101"), np.dtype("M8[ns]"), False),
- (Timestamp("20160101", tz="UTC"), np.object_, False),
- (Timestamp("20160101", tz="UTC"), "datetime64[ns, UTC]", True),
+ ("foo", np.object_),
+ (b"foo", np.object_),
+ (1, np.int64),
+ (1.5, np.float_),
+ (np.datetime64("2016-01-01"), np.dtype("M8[ns]")),
+ (Timestamp("20160101"), np.dtype("M8[ns]")),
+ (Timestamp("20160101", tz="UTC"), "datetime64[ns, UTC]"),
],
)
-def test_infer_dtype_from_scalar(value, expected, pandas_dtype):
- dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=pandas_dtype)
+def test_infer_dtype_from_scalar(value, expected):
+ dtype, _ = infer_dtype_from_scalar(value)
assert is_dtype_equal(dtype, expected)
with pytest.raises(TypeError, match="must be list-like"):
- infer_dtype_from_array(value, pandas_dtype=pandas_dtype)
+ infer_dtype_from_array(value)
@pytest.mark.parametrize(
- "arr, expected, pandas_dtype",
+ "arr, expected",
[
- ([1], np.int_, False),
- (np.array([1], dtype=np.int64), np.int64, False),
- ([np.nan, 1, ""], np.object_, False),
- (np.array([[1.0, 2.0]]), np.float_, False),
- (Categorical(list("aabc")), np.object_, False),
- (Categorical([1, 2, 3]), np.int64, False),
- (Categorical(list("aabc")), "category", True),
- (Categorical([1, 2, 3]), "category", True),
- (date_range("20160101", periods=3), np.dtype("=M8[ns]"), False),
+ ([1], np.int_),
+ (np.array([1], dtype=np.int64), np.int64),
+ ([np.nan, 1, ""], np.object_),
+ (np.array([[1.0, 2.0]]), np.float_),
+ (Categorical(list("aabc")), "category"),
+ (Categorical([1, 2, 3]), "category"),
+ (date_range("20160101", periods=3), np.dtype("=M8[ns]")),
(
date_range("20160101", periods=3, tz="US/Eastern"),
"datetime64[ns, US/Eastern]",
- True,
),
- (Series([1.0, 2, 3]), np.float64, False),
- (Series(list("abc")), np.object_, False),
+ (Series([1.0, 2, 3]), np.float64),
+ (Series(list("abc")), np.object_),
(
Series(date_range("20160101", periods=3, tz="US/Eastern")),
"datetime64[ns, US/Eastern]",
- True,
),
],
)
-def test_infer_dtype_from_array(arr, expected, pandas_dtype):
- dtype, _ = infer_dtype_from_array(arr, pandas_dtype=pandas_dtype)
+def test_infer_dtype_from_array(arr, expected):
+ dtype, _ = infer_dtype_from_array(arr)
assert is_dtype_equal(dtype, expected)
| The only non-test place it is not True is in mask_missing, where that leads to an unnecessary object-dtype cast. | https://api.github.com/repos/pandas-dev/pandas/pulls/53064 | 2023-05-04T00:29:24Z | 2023-05-04T17:15:13Z | 2023-05-04T17:15:13Z | 2023-05-04T17:49:25Z |
CLN: avoid infer_dtype | diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index b90ceb7c2074d..8c9b45bd452a0 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -75,7 +75,11 @@
from pandas.core.array_algos.quantile import quantile_with_mask
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays.base import ExtensionArray
-from pandas.core.construction import ensure_wrapped_if_datetimelike
+from pandas.core.construction import (
+ array as pd_array,
+ ensure_wrapped_if_datetimelike,
+ extract_array,
+)
from pandas.core.indexers import check_array_indexer
from pandas.core.ops import invalid_comparison
@@ -645,20 +649,8 @@ def _arith_method(self, other, op):
and len(other) == len(self)
):
# Try inferring masked dtype instead of casting to object
- inferred_dtype = lib.infer_dtype(other, skipna=True)
- if inferred_dtype == "integer":
- from pandas.core.arrays import IntegerArray
-
- other = IntegerArray._from_sequence(other)
- elif inferred_dtype in ["floating", "mixed-integer-float"]:
- from pandas.core.arrays import FloatingArray
-
- other = FloatingArray._from_sequence(other)
-
- elif inferred_dtype in ["boolean"]:
- from pandas.core.arrays import BooleanArray
-
- other = BooleanArray._from_sequence(other)
+ other = pd_array(other)
+ other = extract_array(other, extract_numpy=True)
if isinstance(other, BaseMaskedArray):
other, omask = other._data, other._mask
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index f27941331e7f9..2c426187c83e8 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -1654,9 +1654,8 @@ def is_all_strings(value: ArrayLike) -> bool:
dtype = value.dtype
if isinstance(dtype, np.dtype):
- return (
- dtype == np.dtype("object")
- and lib.infer_dtype(value, skipna=False) == "string"
+ return dtype == np.dtype("object") and lib.is_string_array(
+ np.asarray(value), skipna=False
)
elif isinstance(dtype, CategoricalDtype):
return dtype.categories.inferred_type == "string"
diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py
index ca8dc1da1aae2..29e0bb11be4dc 100644
--- a/pandas/core/internals/construction.py
+++ b/pandas/core/internals/construction.py
@@ -27,8 +27,6 @@
)
from pandas.core.dtypes.common import (
is_1d_only_ea_dtype,
- is_bool_dtype,
- is_float_dtype,
is_integer_dtype,
is_list_like,
is_named_tuple,
@@ -44,14 +42,10 @@
algorithms,
common as com,
)
-from pandas.core.arrays import (
- BooleanArray,
- ExtensionArray,
- FloatingArray,
- IntegerArray,
-)
+from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.string_ import StringDtype
from pandas.core.construction import (
+ array as pd_array,
ensure_wrapped_if_datetimelike,
extract_array,
range_to_ndarray,
@@ -1027,12 +1021,8 @@ def convert(arr):
if dtype_backend != "numpy" and arr.dtype == np.dtype("O"):
arr = StringDtype().construct_array_type()._from_sequence(arr)
elif dtype_backend != "numpy" and isinstance(arr, np.ndarray):
- if is_integer_dtype(arr.dtype):
- arr = IntegerArray(arr, np.zeros(arr.shape, dtype=np.bool_))
- elif is_bool_dtype(arr.dtype):
- arr = BooleanArray(arr, np.zeros(arr.shape, dtype=np.bool_))
- elif is_float_dtype(arr.dtype):
- arr = FloatingArray(arr, np.isnan(arr))
+ if arr.dtype.kind in "iufb":
+ arr = pd_array(arr, copy=False)
elif isinstance(dtype, ExtensionDtype):
# TODO: test(s) that get here
diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py
index 315bfbee8572e..4c0cffffb423e 100644
--- a/pandas/io/parsers/base_parser.py
+++ b/pandas/io/parsers/base_parser.py
@@ -757,8 +757,7 @@ def _infer_types(
result = BooleanArray(result, bool_mask)
elif result.dtype == np.object_ and non_default_dtype_backend:
# read_excel sends array of datetime objects
- inferred_type = lib.infer_dtype(result)
- if inferred_type != "datetime":
+ if not lib.is_datetime_array(result, skipna=True):
result = StringDtype().construct_array_type()._from_sequence(values)
if dtype_backend == "pyarrow":
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53063 | 2023-05-04T00:01:35Z | 2023-05-04T17:19:53Z | 2023-05-04T17:19:53Z | 2023-05-04T17:46:10Z |
STY: Enable pygrep ruff checks | diff --git a/asv_bench/benchmarks/pandas_vb_common.py b/asv_bench/benchmarks/pandas_vb_common.py
index 97d91111e833a..4bd56ccb1b5ce 100644
--- a/asv_bench/benchmarks/pandas_vb_common.py
+++ b/asv_bench/benchmarks/pandas_vb_common.py
@@ -17,7 +17,7 @@
try:
import pandas._testing as tm
except ImportError:
- import pandas.util.testing as tm # noqa:F401
+ import pandas.util.testing as tm # noqa: F401
numeric_dtypes = [
diff --git a/doc/source/user_guide/window.rst b/doc/source/user_guide/window.rst
index dcbae66906a29..01bf999a1f99f 100644
--- a/doc/source/user_guide/window.rst
+++ b/doc/source/user_guide/window.rst
@@ -96,7 +96,7 @@ be calculated with :meth:`~Rolling.apply` by specifying a separate column of wei
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
.. versionadded:: 1.3
diff --git a/pandas/__init__.py b/pandas/__init__.py
index 6ddfbadcf91d1..cb00f9ed12647 100644
--- a/pandas/__init__.py
+++ b/pandas/__init__.py
@@ -21,7 +21,7 @@
try:
# numpy compat
from pandas.compat import (
- is_numpy_dev as _is_numpy_dev, # pyright: ignore # noqa:F401
+ is_numpy_dev as _is_numpy_dev, # pyright: ignore[reportUnusedImport] # noqa: F401,E501
)
except ImportError as _err: # pragma: no cover
_module = _err.name
@@ -41,7 +41,7 @@
)
# let init-time option registration happen
-import pandas.core.config_init # pyright: ignore # noqa:F401
+import pandas.core.config_init # pyright: ignore[reportUnusedImport] # noqa: F401
from pandas.core.api import (
# dtype
diff --git a/pandas/_config/__init__.py b/pandas/_config/__init__.py
index 73ed99c3a4640..c37ad563df8ef 100644
--- a/pandas/_config/__init__.py
+++ b/pandas/_config/__init__.py
@@ -17,7 +17,7 @@
"using_copy_on_write",
]
from pandas._config import config
-from pandas._config import dates # pyright: ignore # noqa:F401
+from pandas._config import dates # pyright: ignore[reportUnusedImport] # noqa: F401
from pandas._config.config import (
_global_config,
describe_option,
diff --git a/pandas/_libs/__init__.py b/pandas/_libs/__init__.py
index 2c532cda480f0..29ed375134a2b 100644
--- a/pandas/_libs/__init__.py
+++ b/pandas/_libs/__init__.py
@@ -13,8 +13,8 @@
# Below imports needs to happen first to ensure pandas top level
# module gets monkeypatched with the pandas_datetime_CAPI
# see pandas_datetime_exec in pd_datetime.c
-import pandas._libs.pandas_parser # noqa # isort: skip # type: ignore[reportUnusedImport]
-import pandas._libs.pandas_datetime # noqa # isort: skip # type: ignore[reportUnusedImport]
+import pandas._libs.pandas_parser # noqa: F401,E501 # isort: skip # type: ignore[reportUnusedImport]
+import pandas._libs.pandas_datetime # noqa: F401,E501 # isort: skip # type: ignore[reportUnusedImport]
from pandas._libs.interval import Interval
from pandas._libs.tslibs import (
NaT,
diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi
index 584486799e3ed..ae047939c6526 100644
--- a/pandas/_libs/lib.pyi
+++ b/pandas/_libs/lib.pyi
@@ -30,7 +30,7 @@ from enum import Enum
class _NoDefault(Enum):
no_default = ...
-no_default: Final = _NoDefault.no_default # noqa
+no_default: Final = _NoDefault.no_default # noqa: PYI015
NoDefault = Literal[_NoDefault.no_default]
i8max: int
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 39dade594a5af..9ba3067be5a14 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -534,7 +534,7 @@ def _box_func(self, x: np.datetime64) -> Timestamp | NaTType:
# error: Return type "Union[dtype, DatetimeTZDtype]" of "dtype"
# incompatible with return type "ExtensionDtype" in supertype
# "ExtensionArray"
- def dtype(self) -> np.dtype[np.datetime64] | DatetimeTZDtype: # type: ignore[override] # noqa:E501
+ def dtype(self) -> np.dtype[np.datetime64] | DatetimeTZDtype: # type: ignore[override] # noqa: E501
"""
The dtype for the DatetimeArray.
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 6dabb866b8f5c..08a5f9c79274b 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1200,7 +1200,7 @@ def _ensure_nanosecond_dtype(dtype: DtypeObj) -> None:
Traceback (most recent call last):
...
TypeError: dtype=timedelta64[ps] is not supported. Supported resolutions are 's', 'ms', 'us', and 'ns'
- """ # noqa:E501
+ """ # noqa: E501
msg = (
f"The '{dtype.name}' dtype has no unit. "
f"Please pass in '{dtype.name}[ns]' instead."
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index 093101e2ae5a4..7fff0f0d2d805 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -902,7 +902,7 @@ class PeriodDtype(PeriodDtypeBase, PandasExtensionDtype):
# error: Incompatible types in assignment (expression has type
# "Dict[int, PandasExtensionDtype]", base class "PandasExtensionDtype"
# defined the type as "Dict[str, PandasExtensionDtype]") [assignment]
- _cache_dtypes: dict[BaseOffset, PeriodDtype] = {} # type: ignore[assignment] # noqa:E501
+ _cache_dtypes: dict[BaseOffset, PeriodDtype] = {} # type: ignore[assignment] # noqa: E501
__hash__ = PeriodDtypeBase.__hash__
_freq: BaseOffset
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 674746e00c84b..56c58bc9347e0 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -10431,7 +10431,7 @@ def corr(
dogs cats
dogs 1.0 NaN
cats NaN 1.0
- """ # noqa:E501
+ """ # noqa: E501
data = self._get_numeric_data() if numeric_only else self
cols = data.columns
idx = cols.copy()
@@ -10676,7 +10676,7 @@ def corrwith(
d 1.0
e NaN
dtype: float64
- """ # noqa:E501
+ """ # noqa: E501
axis = self._get_axis_number(axis)
this = self._get_numeric_data() if numeric_only else self
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 78f7b69beb118..7bc70013d0fc5 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -210,7 +210,7 @@
_shared_doc_kwargs = {
"axes": "keywords for axes",
"klass": "Series/DataFrame",
- "axes_single_arg": "{0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for DataFrame", # noqa:E501
+ "axes_single_arg": "{0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for DataFrame", # noqa: E501
"inplace": """
inplace : bool, default False
If True, performs operation inplace and returns None.""",
@@ -2904,7 +2904,7 @@ def to_sql(
>>> with engine.connect() as conn:
... conn.execute(text("SELECT * FROM integers")).fetchall()
[(1,), (None,), (2,)]
- """ # noqa:E501
+ """ # noqa: E501
from pandas.io import sql
return sql.to_sql(
@@ -5901,7 +5901,7 @@ def sample(
num_legs num_wings num_specimen_seen
falcon 2 2 10
fish 0 0 8
- """ # noqa:E501
+ """ # noqa: E501
if axis is None:
axis = 0
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 072627b275a02..c32c96077bde7 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -4227,7 +4227,7 @@ def sample(
5 black 5
2 blue 2
0 red 0
- """ # noqa:E501
+ """ # noqa: E501
if self._selected_obj.empty:
# GH48459 prevent ValueError when object is empty
return self._selected_obj
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index ff523862f8770..cf9cc5e5a5c1d 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1536,7 +1536,7 @@ def delete(self, loc) -> list[Block]:
else:
# No overload variant of "__getitem__" of "ExtensionArray" matches
# argument type "Tuple[slice, slice]"
- values = self.values[previous_loc + 1 : idx, :] # type: ignore[call-overload] # noqa
+ values = self.values[previous_loc + 1 : idx, :] # type: ignore[call-overload] # noqa: E501
locs = mgr_locs_arr[previous_loc + 1 : idx]
nb = type(self)(
values, placement=BlockPlacement(locs), ndim=self.ndim, refs=refs
diff --git a/pandas/core/methods/describe.py b/pandas/core/methods/describe.py
index c8f8a2127083e..9d597b9f4b489 100644
--- a/pandas/core/methods/describe.py
+++ b/pandas/core/methods/describe.py
@@ -193,7 +193,7 @@ def _select_data(self) -> DataFrame:
include=self.include,
exclude=self.exclude,
)
- return data # pyright: ignore
+ return data # pyright: ignore[reportGeneralTypeIssues]
def reorder_columns(ldesc: Sequence[Series]) -> list[Hashable]:
diff --git a/pandas/core/series.py b/pandas/core/series.py
index afa124368a29e..f47b5edc0f243 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2682,7 +2682,7 @@ def corr(
>>> s2 = pd.Series([.3, .6, .0, .1])
>>> s1.corr(s2, method=histogram_intersection)
0.3
- """ # noqa:E501
+ """ # noqa: E501
this, other = self.align(other, join="inner", copy=False)
if len(this) == 0:
return np.nan
diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py
index b9a5c431d8387..57df011590caf 100644
--- a/pandas/core/tools/numeric.py
+++ b/pandas/core/tools/numeric.py
@@ -218,7 +218,7 @@ def to_numeric(
values = ensure_object(values)
coerce_numeric = errors not in ("ignore", "raise")
try:
- values, new_mask = lib.maybe_convert_numeric( # type: ignore[call-overload] # noqa
+ values, new_mask = lib.maybe_convert_numeric( # type: ignore[call-overload] # noqa: E501
values,
set(),
coerce_numeric=coerce_numeric,
diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py
index 2ea8de2211909..e8670757e1669 100644
--- a/pandas/io/parquet.py
+++ b/pandas/io/parquet.py
@@ -161,7 +161,7 @@ def __init__(self) -> None:
import pyarrow.parquet
# import utils to register the pyarrow extension types
- import pandas.core.arrays.arrow.extension_types # pyright: ignore # noqa:F401
+ import pandas.core.arrays.arrow.extension_types # pyright: ignore[reportUnusedImport] # noqa: F401,E501
self.api = pyarrow
@@ -243,7 +243,7 @@ def read(
mapping = _arrow_dtype_mapping()
to_pandas_kwargs["types_mapper"] = mapping.get
elif dtype_backend == "pyarrow":
- to_pandas_kwargs["types_mapper"] = pd.ArrowDtype # type: ignore[assignment] # noqa
+ to_pandas_kwargs["types_mapper"] = pd.ArrowDtype # type: ignore[assignment] # noqa: E501
manager = get_option("mode.data_manager")
if manager == "array":
diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py
index 4c0cffffb423e..564339cefa3aa 100644
--- a/pandas/io/parsers/base_parser.py
+++ b/pandas/io/parsers/base_parser.py
@@ -713,7 +713,7 @@ def _infer_types(
values,
na_values,
False,
- convert_to_masked_nullable=non_default_dtype_backend, # type: ignore[arg-type] # noqa
+ convert_to_masked_nullable=non_default_dtype_backend, # type: ignore[arg-type] # noqa: E501
)
except (ValueError, TypeError):
# e.g. encountering datetime string gets ValueError
@@ -749,7 +749,7 @@ def _infer_types(
np.asarray(values),
true_values=self.true_values,
false_values=self.false_values,
- convert_to_masked_nullable=non_default_dtype_backend, # type: ignore[arg-type] # noqa
+ convert_to_masked_nullable=non_default_dtype_backend, # type: ignore[arg-type] # noqa: E501
)
if result.dtype == np.bool_ and non_default_dtype_backend:
if bool_mask is None:
@@ -812,7 +812,7 @@ def _cast_types(self, values: ArrayLike, cast_type: DtypeObj, column) -> ArrayLi
if is_bool_dtype(cast_type):
# error: Unexpected keyword argument "true_values" for
# "_from_sequence_of_strings" of "ExtensionArray"
- return array_type._from_sequence_of_strings( # type: ignore[call-arg] # noqa:E501
+ return array_type._from_sequence_of_strings( # type: ignore[call-arg] # noqa: E501
values,
dtype=cast_type,
true_values=self.true_values,
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 7fa1cb2840fae..6a161febfe316 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -758,7 +758,7 @@ def to_sql(
rows as stipulated in the
`sqlite3 <https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.rowcount>`__ or
`SQLAlchemy <https://docs.sqlalchemy.org/en/14/core/connections.html#sqlalchemy.engine.BaseCursorResult.rowcount>`__
- """ # noqa:E501
+ """ # noqa: E501
if if_exists not in ("fail", "replace", "append"):
raise ValueError(f"'{if_exists}' is not valid for if_exists")
diff --git a/pandas/tests/arrays/categorical/test_repr.py b/pandas/tests/arrays/categorical/test_repr.py
index ffc44b30a3870..cdf5d967d9c3d 100644
--- a/pandas/tests/arrays/categorical/test_repr.py
+++ b/pandas/tests/arrays/categorical/test_repr.py
@@ -79,7 +79,7 @@ def test_unicode_print(self):
expected = """\
['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう']
Length: 60
-Categories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa:E501
+Categories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa: E501
assert repr(c) == expected
@@ -89,7 +89,7 @@ def test_unicode_print(self):
c = Categorical(["ああああ", "いいいいい", "ううううううう"] * 20)
expected = """['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう']
Length: 60
-Categories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa:E501
+Categories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa: E501
assert repr(c) == expected
@@ -214,14 +214,14 @@ def test_categorical_repr_datetime_ordered(self):
c = Categorical(idx, ordered=True)
exp = """[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00]
Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
- 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa:E501
+ 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx, ordered=True)
exp = """[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00, 2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00]
Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
- 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa:E501
+ 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
assert repr(c) == exp
@@ -230,7 +230,7 @@ def test_categorical_repr_datetime_ordered(self):
exp = """[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]
Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
- 2011-01-01 13:00:00-05:00]""" # noqa:E501
+ 2011-01-01 13:00:00-05:00]""" # noqa: E501
assert repr(c) == exp
@@ -238,7 +238,7 @@ def test_categorical_repr_datetime_ordered(self):
exp = """[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00, 2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]
Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
- 2011-01-01 13:00:00-05:00]""" # noqa:E501
+ 2011-01-01 13:00:00-05:00]""" # noqa: E501
assert repr(c) == exp
@@ -258,14 +258,14 @@ def test_categorical_repr_period(self):
c = Categorical(idx)
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
Categories (5, period[H]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
- 2011-01-01 13:00]""" # noqa:E501
+ 2011-01-01 13:00]""" # noqa: E501
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx)
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00, 2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
Categories (5, period[H]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
- 2011-01-01 13:00]""" # noqa:E501
+ 2011-01-01 13:00]""" # noqa: E501
assert repr(c) == exp
@@ -278,7 +278,7 @@ def test_categorical_repr_period(self):
c = Categorical(idx.append(idx), categories=idx)
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
-Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]""" # noqa:E501
+Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]""" # noqa: E501
assert repr(c) == exp
@@ -287,14 +287,14 @@ def test_categorical_repr_period_ordered(self):
c = Categorical(idx, ordered=True)
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
Categories (5, period[H]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
- 2011-01-01 13:00]""" # noqa:E501
+ 2011-01-01 13:00]""" # noqa: E501
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx, ordered=True)
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00, 2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
Categories (5, period[H]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
- 2011-01-01 13:00]""" # noqa:E501
+ 2011-01-01 13:00]""" # noqa: E501
assert repr(c) == exp
@@ -307,7 +307,7 @@ def test_categorical_repr_period_ordered(self):
c = Categorical(idx.append(idx), categories=idx, ordered=True)
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
-Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]""" # noqa:E501
+Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]""" # noqa: E501
assert repr(c) == exp
@@ -321,7 +321,7 @@ def test_categorical_repr_timedelta(self):
c = Categorical(idx.append(idx), categories=idx)
exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days]
-Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]""" # noqa:E501
+Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]""" # noqa: E501
assert repr(c) == exp
@@ -331,7 +331,7 @@ def test_categorical_repr_timedelta(self):
Length: 20
Categories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
3 days 01:00:00, ..., 16 days 01:00:00, 17 days 01:00:00,
- 18 days 01:00:00, 19 days 01:00:00]""" # noqa:E501
+ 18 days 01:00:00, 19 days 01:00:00]""" # noqa: E501
assert repr(c) == exp
@@ -340,7 +340,7 @@ def test_categorical_repr_timedelta(self):
Length: 40
Categories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
3 days 01:00:00, ..., 16 days 01:00:00, 17 days 01:00:00,
- 18 days 01:00:00, 19 days 01:00:00]""" # noqa:E501
+ 18 days 01:00:00, 19 days 01:00:00]""" # noqa: E501
assert repr(c) == exp
@@ -354,7 +354,7 @@ def test_categorical_repr_timedelta_ordered(self):
c = Categorical(idx.append(idx), categories=idx, ordered=True)
exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days]
-Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa:E501
+Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa: E501
assert repr(c) == exp
@@ -364,7 +364,7 @@ def test_categorical_repr_timedelta_ordered(self):
Length: 20
Categories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
3 days 01:00:00 ... 16 days 01:00:00 < 17 days 01:00:00 <
- 18 days 01:00:00 < 19 days 01:00:00]""" # noqa:E501
+ 18 days 01:00:00 < 19 days 01:00:00]""" # noqa: E501
assert repr(c) == exp
@@ -373,26 +373,26 @@ def test_categorical_repr_timedelta_ordered(self):
Length: 40
Categories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
3 days 01:00:00 ... 16 days 01:00:00 < 17 days 01:00:00 <
- 18 days 01:00:00 < 19 days 01:00:00]""" # noqa:E501
+ 18 days 01:00:00 < 19 days 01:00:00]""" # noqa: E501
assert repr(c) == exp
def test_categorical_index_repr(self):
idx = CategoricalIndex(Categorical([1, 2, 3]))
- exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == exp
i = CategoricalIndex(Categorical(np.arange(10, dtype=np.int64)))
- exp = """CategoricalIndex([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], categories=[0, 1, 2, 3, ..., 6, 7, 8, 9], ordered=False, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], categories=[0, 1, 2, 3, ..., 6, 7, 8, 9], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_ordered(self):
i = CategoricalIndex(Categorical([1, 2, 3], ordered=True))
- exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=True, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
i = CategoricalIndex(Categorical(np.arange(10, dtype=np.int64), ordered=True))
- exp = """CategoricalIndex([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], categories=[0, 1, 2, 3, ..., 6, 7, 8, 9], ordered=True, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], categories=[0, 1, 2, 3, ..., 6, 7, 8, 9], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_datetime(self):
@@ -401,7 +401,7 @@ def test_categorical_index_repr_datetime(self):
exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00',
'2011-01-01 11:00:00', '2011-01-01 12:00:00',
'2011-01-01 13:00:00'],
- categories=[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00], ordered=False, dtype='category')""" # noqa:E501
+ categories=[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
@@ -410,7 +410,7 @@ def test_categorical_index_repr_datetime(self):
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
'2011-01-01 13:00:00-05:00'],
- categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=False, dtype='category')""" # noqa:E501
+ categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
@@ -420,7 +420,7 @@ def test_categorical_index_repr_datetime_ordered(self):
exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00',
'2011-01-01 11:00:00', '2011-01-01 12:00:00',
'2011-01-01 13:00:00'],
- categories=[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00], ordered=True, dtype='category')""" # noqa:E501
+ categories=[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
@@ -429,7 +429,7 @@ def test_categorical_index_repr_datetime_ordered(self):
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
'2011-01-01 13:00:00-05:00'],
- categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=True, dtype='category')""" # noqa:E501
+ categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
@@ -439,7 +439,7 @@ def test_categorical_index_repr_datetime_ordered(self):
'2011-01-01 13:00:00-05:00', '2011-01-01 09:00:00-05:00',
'2011-01-01 10:00:00-05:00', '2011-01-01 11:00:00-05:00',
'2011-01-01 12:00:00-05:00', '2011-01-01 13:00:00-05:00'],
- categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=True, dtype='category')""" # noqa:E501
+ categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
@@ -447,24 +447,24 @@ def test_categorical_index_repr_period(self):
# test all length
idx = period_range("2011-01-01 09:00", freq="H", periods=1)
i = CategoricalIndex(Categorical(idx))
- exp = """CategoricalIndex(['2011-01-01 09:00'], categories=[2011-01-01 09:00], ordered=False, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex(['2011-01-01 09:00'], categories=[2011-01-01 09:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = period_range("2011-01-01 09:00", freq="H", periods=2)
i = CategoricalIndex(Categorical(idx))
- exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00], ordered=False, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = period_range("2011-01-01 09:00", freq="H", periods=3)
i = CategoricalIndex(Categorical(idx))
- exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00], ordered=False, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = period_range("2011-01-01 09:00", freq="H", periods=5)
i = CategoricalIndex(Categorical(idx))
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
'2011-01-01 12:00', '2011-01-01 13:00'],
- categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=False, dtype='category')""" # noqa:E501
+ categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
@@ -473,13 +473,13 @@ def test_categorical_index_repr_period(self):
'2011-01-01 12:00', '2011-01-01 13:00', '2011-01-01 09:00',
'2011-01-01 10:00', '2011-01-01 11:00', '2011-01-01 12:00',
'2011-01-01 13:00'],
- categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=False, dtype='category')""" # noqa:E501
+ categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = period_range("2011-01", freq="M", periods=5)
i = CategoricalIndex(Categorical(idx))
- exp = """CategoricalIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05'], categories=[2011-01, 2011-02, 2011-03, 2011-04, 2011-05], ordered=False, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05'], categories=[2011-01, 2011-02, 2011-03, 2011-04, 2011-05], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_period_ordered(self):
@@ -487,19 +487,19 @@ def test_categorical_index_repr_period_ordered(self):
i = CategoricalIndex(Categorical(idx, ordered=True))
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
'2011-01-01 12:00', '2011-01-01 13:00'],
- categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=True, dtype='category')""" # noqa:E501
+ categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = period_range("2011-01", freq="M", periods=5)
i = CategoricalIndex(Categorical(idx, ordered=True))
- exp = """CategoricalIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05'], categories=[2011-01, 2011-02, 2011-03, 2011-04, 2011-05], ordered=True, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05'], categories=[2011-01, 2011-02, 2011-03, 2011-04, 2011-05], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_timedelta(self):
idx = timedelta_range("1 days", periods=5)
i = CategoricalIndex(Categorical(idx))
- exp = """CategoricalIndex(['1 days', '2 days', '3 days', '4 days', '5 days'], categories=[1 days, 2 days, 3 days, 4 days, 5 days], ordered=False, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex(['1 days', '2 days', '3 days', '4 days', '5 days'], categories=[1 days, 2 days, 3 days, 4 days, 5 days], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = timedelta_range("1 hours", periods=10)
@@ -508,14 +508,14 @@ def test_categorical_index_repr_timedelta(self):
'3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00',
'6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00',
'9 days 01:00:00'],
- categories=[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00, 8 days 01:00:00, 9 days 01:00:00], ordered=False, dtype='category')""" # noqa:E501
+ categories=[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00, 8 days 01:00:00, 9 days 01:00:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_timedelta_ordered(self):
idx = timedelta_range("1 days", periods=5)
i = CategoricalIndex(Categorical(idx, ordered=True))
- exp = """CategoricalIndex(['1 days', '2 days', '3 days', '4 days', '5 days'], categories=[1 days, 2 days, 3 days, 4 days, 5 days], ordered=True, dtype='category')""" # noqa:E501
+ exp = """CategoricalIndex(['1 days', '2 days', '3 days', '4 days', '5 days'], categories=[1 days, 2 days, 3 days, 4 days, 5 days], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = timedelta_range("1 hours", periods=10)
@@ -524,7 +524,7 @@ def test_categorical_index_repr_timedelta_ordered(self):
'3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00',
'6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00',
'9 days 01:00:00'],
- categories=[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00, 8 days 01:00:00, 9 days 01:00:00], ordered=True, dtype='category')""" # noqa:E501
+ categories=[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00, 8 days 01:00:00, 9 days 01:00:00], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
diff --git a/pandas/tests/computation/test_compat.py b/pandas/tests/computation/test_compat.py
index f3566e040dc85..856a5b3a22a95 100644
--- a/pandas/tests/computation/test_compat.py
+++ b/pandas/tests/computation/test_compat.py
@@ -27,6 +27,6 @@ def test_compat():
def test_invalid_numexpr_version(engine, parser):
if engine == "numexpr":
pytest.importorskip("numexpr")
- a, b = 1, 2 # noqa:F841
+ a, b = 1, 2 # noqa: F841
res = pd.eval("a + b", engine=engine, parser=parser)
assert res == 3
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py
index 93ae2bfdd01e4..35960c707d3bd 100644
--- a/pandas/tests/computation/test_eval.py
+++ b/pandas/tests/computation/test_eval.py
@@ -622,8 +622,8 @@ def test_unary_in_function(self):
),
)
def test_disallow_scalar_bool_ops(self, ex, engine, parser):
- x, a, b = np.random.randn(3), 1, 2 # noqa:F841
- df = DataFrame(np.random.randn(3, 2)) # noqa:F841
+ x, a, b = np.random.randn(3), 1, 2 # noqa: F841
+ df = DataFrame(np.random.randn(3, 2)) # noqa: F841
msg = "cannot evaluate scalar only bool ops|'BoolOp' nodes are not"
with pytest.raises(NotImplementedError, match=msg):
@@ -657,7 +657,7 @@ def test_identical(self, engine, parser):
tm.assert_numpy_array_equal(result, np.array([1.5]))
assert result.shape == (1,)
- x = np.array([False]) # noqa:F841
+ x = np.array([False]) # noqa: F841
result = pd.eval("x", engine=engine, parser=parser)
tm.assert_numpy_array_equal(result, np.array([False]))
assert result.shape == (1,)
@@ -1103,7 +1103,7 @@ def test_single_variable(self):
tm.assert_frame_equal(df, df2)
def test_failing_subscript_with_name_error(self):
- df = DataFrame(np.random.randn(5, 3)) # noqa:F841
+ df = DataFrame(np.random.randn(5, 3)) # noqa: F841
with pytest.raises(NameError, match="name 'x' is not defined"):
self.eval("df[x > 2] > 2")
@@ -1172,7 +1172,7 @@ def test_assignment_single_assign_new(self):
def test_assignment_single_assign_local_overlap(self):
df = DataFrame(np.random.randn(5, 2), columns=list("ab"))
df = df.copy()
- a = 1 # noqa:F841
+ a = 1 # noqa: F841
df.eval("a = 1 + b", inplace=True)
expected = df.copy()
@@ -1182,7 +1182,7 @@ def test_assignment_single_assign_local_overlap(self):
def test_assignment_single_assign_name(self):
df = DataFrame(np.random.randn(5, 2), columns=list("ab"))
- a = 1 # noqa:F841
+ a = 1 # noqa: F841
old_a = df.a.copy()
df.eval("a = a + b", inplace=True)
result = old_a + df.b
@@ -1481,7 +1481,7 @@ def test_simple_in_ops(self, engine, parser):
pd.eval("[3] not in (1, 2, [[3]])", engine=engine, parser=parser)
def test_check_many_exprs(self, engine, parser):
- a = 1 # noqa:F841
+ a = 1 # noqa: F841
expr = " * ".join("a" * 33)
expected = 1
res = pd.eval(expr, engine=engine, parser=parser)
@@ -1520,7 +1520,7 @@ def test_fails_and_or_not(self, expr, engine, parser):
@pytest.mark.parametrize("char", ["|", "&"])
def test_fails_ampersand_pipe(self, char, engine, parser):
- df = DataFrame(np.random.randn(5, 3)) # noqa:F841
+ df = DataFrame(np.random.randn(5, 3)) # noqa: F841
ex = f"(df + 2)[df > 1] > 0 {char} (df > 0)"
if parser == "python":
msg = "cannot evaluate scalar only bool ops"
@@ -1640,7 +1640,7 @@ def test_no_new_locals(self, engine, parser):
assert lcls == lcls2
def test_no_new_globals(self, engine, parser):
- x = 1 # noqa:F841
+ x = 1 # noqa: F841
gbls = globals().copy()
pd.eval("x + 1", engine=engine, parser=parser)
gbls2 = globals().copy()
@@ -1738,7 +1738,7 @@ def test_name_error_exprs(engine, parser):
@pytest.mark.parametrize("express", ["a + @b", "@a + b", "@a + @b"])
def test_invalid_local_variable_reference(engine, parser, express):
- a, b = 1, 2 # noqa:F841
+ a, b = 1, 2 # noqa: F841
if parser != "pandas":
with pytest.raises(SyntaxError, match="The '@' prefix is only"):
@@ -1782,7 +1782,7 @@ def test_more_than_one_expression_raises(engine, parser):
def test_bool_ops_fails_on_scalars(lhs, cmp, rhs, engine, parser):
gen = {int: lambda: np.random.randint(10), float: np.random.randn}
- mid = gen[lhs]() # noqa:F841
+ mid = gen[lhs]() # noqa: F841
lhs = gen[lhs]()
rhs = gen[rhs]()
diff --git a/pandas/tests/copy_view/index/test_index.py b/pandas/tests/copy_view/index/test_index.py
index 817be43475d0b..5e9c04c0adfc3 100644
--- a/pandas/tests/copy_view/index/test_index.py
+++ b/pandas/tests/copy_view/index/test_index.py
@@ -90,7 +90,7 @@ def test_index_from_series(using_copy_on_write):
def test_index_from_series_copy(using_copy_on_write):
ser = Series([1, 2])
- idx = Index(ser, copy=True) # noqa
+ idx = Index(ser, copy=True) # noqa: F841
arr = get_array(ser)
ser.iloc[0] = 100
assert np.shares_memory(get_array(ser), arr)
diff --git a/pandas/tests/copy_view/test_core_functionalities.py b/pandas/tests/copy_view/test_core_functionalities.py
index 204e26b35d680..25af197552335 100644
--- a/pandas/tests/copy_view/test_core_functionalities.py
+++ b/pandas/tests/copy_view/test_core_functionalities.py
@@ -47,7 +47,7 @@ def test_setitem_with_view_invalidated_does_not_copy(using_copy_on_write, reques
df["b"] = 100
arr = get_array(df, "a")
- view = None # noqa
+ view = None # noqa: F841
df.iloc[0, 0] = 100
if using_copy_on_write:
# Setitem split the block. Since the old block shared data with view
diff --git a/pandas/tests/extension/base/__init__.py b/pandas/tests/extension/base/__init__.py
index 7e765cc5342d1..dec41150a451c 100644
--- a/pandas/tests/extension/base/__init__.py
+++ b/pandas/tests/extension/base/__init__.py
@@ -41,32 +41,32 @@ class TestMyDtype(BaseDtypeTests):
``assert_series_equal`` on your base test class.
"""
-from pandas.tests.extension.base.accumulate import BaseAccumulateTests # noqa
-from pandas.tests.extension.base.casting import BaseCastingTests # noqa
-from pandas.tests.extension.base.constructors import BaseConstructorsTests # noqa
-from pandas.tests.extension.base.dim2 import ( # noqa
+from pandas.tests.extension.base.accumulate import BaseAccumulateTests # noqa: F401
+from pandas.tests.extension.base.casting import BaseCastingTests # noqa: F401
+from pandas.tests.extension.base.constructors import BaseConstructorsTests # noqa: F401
+from pandas.tests.extension.base.dim2 import ( # noqa: F401
Dim2CompatTests,
NDArrayBacked2DTests,
)
-from pandas.tests.extension.base.dtype import BaseDtypeTests # noqa
-from pandas.tests.extension.base.getitem import BaseGetitemTests # noqa
-from pandas.tests.extension.base.groupby import BaseGroupbyTests # noqa
-from pandas.tests.extension.base.index import BaseIndexTests # noqa
-from pandas.tests.extension.base.interface import BaseInterfaceTests # noqa
-from pandas.tests.extension.base.io import BaseParsingTests # noqa
-from pandas.tests.extension.base.methods import BaseMethodsTests # noqa
-from pandas.tests.extension.base.missing import BaseMissingTests # noqa
-from pandas.tests.extension.base.ops import ( # noqa
+from pandas.tests.extension.base.dtype import BaseDtypeTests # noqa: F401
+from pandas.tests.extension.base.getitem import BaseGetitemTests # noqa: F401
+from pandas.tests.extension.base.groupby import BaseGroupbyTests # noqa: F401
+from pandas.tests.extension.base.index import BaseIndexTests # noqa: F401
+from pandas.tests.extension.base.interface import BaseInterfaceTests # noqa: F401
+from pandas.tests.extension.base.io import BaseParsingTests # noqa: F401
+from pandas.tests.extension.base.methods import BaseMethodsTests # noqa: F401
+from pandas.tests.extension.base.missing import BaseMissingTests # noqa: F401
+from pandas.tests.extension.base.ops import ( # noqa: F401
BaseArithmeticOpsTests,
BaseComparisonOpsTests,
BaseOpsUtil,
BaseUnaryOpsTests,
)
-from pandas.tests.extension.base.printing import BasePrintingTests # noqa
-from pandas.tests.extension.base.reduce import ( # noqa
+from pandas.tests.extension.base.printing import BasePrintingTests # noqa: F401
+from pandas.tests.extension.base.reduce import ( # noqa: F401
BaseBooleanReduceTests,
BaseNoReduceTests,
BaseNumericReduceTests,
)
-from pandas.tests.extension.base.reshaping import BaseReshapingTests # noqa
-from pandas.tests.extension.base.setitem import BaseSetitemTests # noqa
+from pandas.tests.extension.base.reshaping import BaseReshapingTests # noqa: F401
+from pandas.tests.extension.base.setitem import BaseSetitemTests # noqa: F401
diff --git a/pandas/tests/frame/constructors/test_from_records.py b/pandas/tests/frame/constructors/test_from_records.py
index bf0436e9c01ef..9f44e85789cbd 100644
--- a/pandas/tests/frame/constructors/test_from_records.py
+++ b/pandas/tests/frame/constructors/test_from_records.py
@@ -264,8 +264,7 @@ def test_from_records_to_records(self):
arr = np.zeros((2,), dtype=("i4,f4,a10"))
arr[:] = [(1, 2.0, "Hello"), (2, 3.0, "World")]
- # TODO(wesm): unused
- frame = DataFrame.from_records(arr) # noqa
+ DataFrame.from_records(arr)
index = Index(np.arange(len(arr))[::-1])
indexed_frame = DataFrame.from_records(arr, index=index)
@@ -366,7 +365,7 @@ def test_from_records_columns_not_modified(self):
columns = ["a", "b", "c"]
original_columns = list(columns)
- df = DataFrame.from_records(tuples, columns=columns, index="a") # noqa
+ DataFrame.from_records(tuples, columns=columns, index="a")
assert columns == original_columns
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index 05b50c180ced0..224abbcef27df 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -525,7 +525,7 @@ def test_getitem_fancy_slice_integers_step(self):
df = DataFrame(np.random.randn(10, 5))
# this is OK
- result = df.iloc[:8:2] # noqa
+ df.iloc[:8:2]
df.iloc[:8:2] = np.nan
assert isna(df.iloc[:8:2]).values.all()
@@ -629,7 +629,7 @@ def test_setitem_fancy_scalar(self, float_frame):
# individual value
for j, col in enumerate(f.columns):
- ts = f[col] # noqa
+ f[col]
for idx in f.index[::5]:
i = f.index.get_loc(idx)
val = np.random.randn()
diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py
index cfc42e81a4234..c5e1e3c02c26e 100644
--- a/pandas/tests/frame/indexing/test_where.py
+++ b/pandas/tests/frame/indexing/test_where.py
@@ -819,7 +819,7 @@ def test_where_bool_comparison():
df_mask = DataFrame(
{"AAA": [True] * 4, "BBB": [False] * 4, "CCC": [True, False, True, False]}
)
- result = df_mask.where(df_mask == False) # noqa:E712
+ result = df_mask.where(df_mask == False) # noqa: E712
expected = DataFrame(
{
"AAA": np.array([np.nan] * 4, dtype=object),
diff --git a/pandas/tests/frame/methods/test_asfreq.py b/pandas/tests/frame/methods/test_asfreq.py
index 2cff2c4b2bc57..47cebd31451e3 100644
--- a/pandas/tests/frame/methods/test_asfreq.py
+++ b/pandas/tests/frame/methods/test_asfreq.py
@@ -143,11 +143,11 @@ def test_asfreq(self, datetime_frame):
tm.assert_frame_equal(offset_monthly, rule_monthly)
- filled = rule_monthly.asfreq("B", method="pad") # noqa
+ rule_monthly.asfreq("B", method="pad")
# TODO: actually check that this worked.
# don't forget!
- filled_dep = rule_monthly.asfreq("B", method="pad") # noqa
+ rule_monthly.asfreq("B", method="pad")
def test_asfreq_datetimeindex(self):
df = DataFrame(
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index 9fdb600b6efc4..5113630966201 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -113,17 +113,17 @@ def test_astype_with_exclude_string(self, float_frame):
def test_astype_with_view_float(self, float_frame):
# this is the only real reason to do it this way
tf = np.round(float_frame).astype(np.int32)
- casted = tf.astype(np.float32, copy=False)
+ tf.astype(np.float32, copy=False)
# TODO(wesm): verification?
tf = float_frame.astype(np.float64)
- casted = tf.astype(np.int64, copy=False) # noqa
+ tf.astype(np.int64, copy=False)
def test_astype_with_view_mixed_float(self, mixed_float_frame):
tf = mixed_float_frame.reindex(columns=["A", "B", "C"])
- casted = tf.astype(np.int64)
- casted = tf.astype(np.float32) # noqa
+ tf.astype(np.int64)
+ tf.astype(np.float32)
@pytest.mark.parametrize("dtype", [np.int32, np.int64])
@pytest.mark.parametrize("val", [np.nan, np.inf])
diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py
index d80c3c0da9935..4538925d84fbb 100644
--- a/pandas/tests/frame/methods/test_fillna.py
+++ b/pandas/tests/frame/methods/test_fillna.py
@@ -597,10 +597,7 @@ def test_fill_corner(self, float_frame, float_string_frame):
assert (filled.loc[filled.index[5:20], "foo"] == 0).all()
del float_string_frame["foo"]
- empty_float = float_frame.reindex(columns=[])
-
- # TODO(wesm): unused?
- result = empty_float.fillna(value=0) # noqa
+ float_frame.reindex(columns=[]).fillna(value=0)
def test_fillna_downcast_dict(self):
# GH#40809
diff --git a/pandas/tests/frame/methods/test_rank.py b/pandas/tests/frame/methods/test_rank.py
index e07ff7e919509..8b0251b2a9928 100644
--- a/pandas/tests/frame/methods/test_rank.py
+++ b/pandas/tests/frame/methods/test_rank.py
@@ -40,7 +40,7 @@ def method(self, request):
@td.skip_if_no_scipy
def test_rank(self, float_frame):
- import scipy.stats # noqa:F401
+ import scipy.stats # noqa: F401
from scipy.stats import rankdata
float_frame.loc[::2, "A"] = np.nan
@@ -142,7 +142,7 @@ def test_rank_mixed_frame(self, float_string_frame):
@td.skip_if_no_scipy
def test_rank_na_option(self, float_frame):
- import scipy.stats # noqa:F401
+ import scipy.stats # noqa: F401
from scipy.stats import rankdata
float_frame.loc[::2, "A"] = np.nan
@@ -226,7 +226,7 @@ def test_rank_axis(self):
@td.skip_if_no_scipy
def test_rank_methods_frame(self):
- import scipy.stats # noqa:F401
+ import scipy.stats # noqa: F401
from scipy.stats import rankdata
xs = np.random.randint(0, 21, (100, 26))
diff --git a/pandas/tests/frame/methods/test_tz_convert.py b/pandas/tests/frame/methods/test_tz_convert.py
index b3d2bd795c45a..8a484abaab54c 100644
--- a/pandas/tests/frame/methods/test_tz_convert.py
+++ b/pandas/tests/frame/methods/test_tz_convert.py
@@ -91,7 +91,7 @@ def test_tz_convert_and_localize(self, fn):
df4 = DataFrame(np.ones(5), MultiIndex.from_arrays([int_idx, l0]))
# TODO: untested
- df5 = getattr(df4, fn)("US/Pacific", level=1) # noqa
+ getattr(df4, fn)("US/Pacific", level=1)
tm.assert_index_equal(df3.index.levels[0], l0)
assert not df3.index.levels[0].equals(l0_expected)
diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py
index 720106590cba3..0ddcbf87e3b4c 100644
--- a/pandas/tests/frame/test_block_internals.py
+++ b/pandas/tests/frame/test_block_internals.py
@@ -79,8 +79,6 @@ def test_consolidate(self, float_frame):
assert len(float_frame._mgr.blocks) == 1
def test_consolidate_inplace(self, float_frame):
- frame = float_frame.copy() # noqa
-
# triggers in-place consolidation
for letter in range(ord("A"), ord("Z")):
float_frame[chr(letter)] = chr(letter)
@@ -352,8 +350,8 @@ def test_stale_cached_series_bug_473(self, using_copy_on_write):
else:
Y["g"]["c"] = np.NaN
repr(Y)
- result = Y.sum() # noqa
- exp = Y["g"].sum() # noqa
+ Y.sum()
+ Y["g"].sum()
if using_copy_on_write:
assert not pd.isna(Y["g"]["c"])
else:
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 8624e54955d83..5c1fa5483555b 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -262,12 +262,6 @@ def test_emptylike_constructor(self, emptylike, expected_index, expected_columns
tm.assert_frame_equal(result, expected)
def test_constructor_mixed(self, float_string_frame):
- index, data = tm.getMixedTypeDict()
-
- # TODO(wesm), incomplete test?
- indexed_frame = DataFrame(data, index=index) # noqa
- unindexed_frame = DataFrame(data) # noqa
-
assert float_string_frame["foo"].dtype == np.object_
def test_constructor_cast_failure(self):
diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py
index db68c4cd2546b..ae199d5c373d5 100644
--- a/pandas/tests/frame/test_query_eval.py
+++ b/pandas/tests/frame/test_query_eval.py
@@ -109,7 +109,7 @@ def test_ops(self, op_str, op, rop, n):
df.iloc[0] = 2
m = df.mean()
- base = DataFrame( # noqa:F841
+ base = DataFrame( # noqa: F841
np.tile(m.values, n).reshape(n, -1), columns=list("abcd")
)
@@ -491,7 +491,7 @@ def test_query_scope(self, engine, parser):
df = DataFrame(np.random.randn(20, 2), columns=list("ab"))
- a, b = 1, 2 # noqa:F841
+ a, b = 1, 2 # noqa: F841
res = df.query("a > b", engine=engine, parser=parser)
expected = df[df.a > df.b]
tm.assert_frame_equal(res, expected)
@@ -641,7 +641,7 @@ def test_local_variable_with_in(self, engine, parser):
def test_at_inside_string(self, engine, parser):
skip_if_no_pandas_parser(parser)
- c = 1 # noqa:F841
+ c = 1 # noqa: F841
df = DataFrame({"a": ["a", "a", "b", "b", "@c", "@c"]})
result = df.query('a == "@c"', engine=engine, parser=parser)
expected = df[df.a == "@c"]
@@ -660,7 +660,7 @@ def test_query_undefined_local(self):
def test_index_resolvers_come_after_columns_with_the_same_name(
self, engine, parser
):
- n = 1 # noqa:F841
+ n = 1 # noqa: F841
a = np.r_[20:101:20]
df = DataFrame({"index": a, "b": np.random.randn(a.size)})
@@ -805,7 +805,7 @@ def test_date_index_query_with_NaT_duplicates(self, engine, parser):
def test_nested_scope(self, engine, parser):
# smoke test
- x = 1 # noqa:F841
+ x = 1 # noqa: F841
result = pd.eval("x + 1", engine=engine, parser=parser)
assert result == 2
@@ -1066,7 +1066,7 @@ def test_query_string_scalar_variable(self, parser, engine):
}
)
e = df[df.Symbol == "BUD US"]
- symb = "BUD US" # noqa:F841
+ symb = "BUD US" # noqa: F841
r = df.query("Symbol == @symb", parser=parser, engine=engine)
tm.assert_frame_equal(e, r)
@@ -1246,7 +1246,7 @@ def test_call_non_named_expression(self, df):
def func(*_):
return 1
- funcs = [func] # noqa:F841
+ funcs = [func] # noqa: F841
df.eval("@func()")
@@ -1303,7 +1303,7 @@ def test_query_ea_dtypes(self, dtype):
pytest.importorskip("pyarrow")
# GH#50261
df = DataFrame({"a": Series([1, 2], dtype=dtype)})
- ref = {2} # noqa:F841
+ ref = {2} # noqa: F841
warning = RuntimeWarning if dtype == "Int64" and NUMEXPR_INSTALLED else None
with tm.assert_produces_warning(warning):
result = df.query("a in @ref")
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 383a008d1f32b..1eab4225e3dd9 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -2633,7 +2633,7 @@ def test_groupby_filtered_df_std():
]
df = DataFrame(dicts)
- df_filter = df[df["filter_col"] == True] # noqa:E712
+ df_filter = df[df["filter_col"] == True] # noqa: E712
dfgb = df_filter.groupby("groupby_col")
result = dfgb.std()
expected = DataFrame(
diff --git a/pandas/tests/indexes/categorical/test_formats.py b/pandas/tests/indexes/categorical/test_formats.py
index 8e09f68c16707..7dbcaaa8d4ba6 100644
--- a/pandas/tests/indexes/categorical/test_formats.py
+++ b/pandas/tests/indexes/categorical/test_formats.py
@@ -16,7 +16,7 @@ def test_format_different_scalar_lengths(self):
def test_string_categorical_index_repr(self):
# short
idx = CategoricalIndex(["a", "bb", "ccc"])
- expected = """CategoricalIndex(['a', 'bb', 'ccc'], categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" # noqa:E501
+ expected = """CategoricalIndex(['a', 'bb', 'ccc'], categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == expected
# multiple lines
@@ -24,7 +24,7 @@ def test_string_categorical_index_repr(self):
expected = """CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',
'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb',
'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],
- categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" # noqa:E501
+ categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == expected
@@ -33,7 +33,7 @@ def test_string_categorical_index_repr(self):
expected = """CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',
...
'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],
- categories=['a', 'bb', 'ccc'], ordered=False, dtype='category', length=300)""" # noqa:E501
+ categories=['a', 'bb', 'ccc'], ordered=False, dtype='category', length=300)""" # noqa: E501
assert repr(idx) == expected
@@ -41,13 +41,13 @@ def test_string_categorical_index_repr(self):
idx = CategoricalIndex(list("abcdefghijklmmo"))
expected = """CategoricalIndex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'm', 'o'],
- categories=['a', 'b', 'c', 'd', ..., 'k', 'l', 'm', 'o'], ordered=False, dtype='category')""" # noqa:E501
+ categories=['a', 'b', 'c', 'd', ..., 'k', 'l', 'm', 'o'], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == expected
# short
idx = CategoricalIndex(["あ", "いい", "ううう"])
- expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa:E501
+ expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == expected
# multiple lines
@@ -55,7 +55,7 @@ def test_string_categorical_index_repr(self):
expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ',
'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
- categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa:E501
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == expected
@@ -64,7 +64,7 @@ def test_string_categorical_index_repr(self):
expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ',
...
'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
- categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)""" # noqa:E501
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)""" # noqa: E501
assert repr(idx) == expected
@@ -72,7 +72,7 @@ def test_string_categorical_index_repr(self):
idx = CategoricalIndex(list("あいうえおかきくけこさしすせそ"))
expected = """CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', 'さ', 'し',
'す', 'せ', 'そ'],
- categories=['あ', 'い', 'う', 'え', ..., 'し', 'す', 'せ', 'そ'], ordered=False, dtype='category')""" # noqa:E501
+ categories=['あ', 'い', 'う', 'え', ..., 'し', 'す', 'せ', 'そ'], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == expected
@@ -80,7 +80,7 @@ def test_string_categorical_index_repr(self):
with cf.option_context("display.unicode.east_asian_width", True):
# short
idx = CategoricalIndex(["あ", "いい", "ううう"])
- expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa:E501
+ expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == expected
# multiple lines
@@ -89,7 +89,7 @@ def test_string_categorical_index_repr(self):
'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
- categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa:E501
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == expected
@@ -100,7 +100,7 @@ def test_string_categorical_index_repr(self):
...
'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
'あ', 'いい', 'ううう'],
- categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)""" # noqa:E501
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)""" # noqa: E501
assert repr(idx) == expected
@@ -108,6 +108,6 @@ def test_string_categorical_index_repr(self):
idx = CategoricalIndex(list("あいうえおかきくけこさしすせそ"))
expected = """CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ',
'さ', 'し', 'す', 'せ', 'そ'],
- categories=['あ', 'い', 'う', 'え', ..., 'し', 'す', 'せ', 'そ'], ordered=False, dtype='category')""" # noqa:E501
+ categories=['あ', 'い', 'う', 'え', ..., 'し', 'す', 'せ', 'そ'], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == expected
diff --git a/pandas/tests/indexes/multi/test_formats.py b/pandas/tests/indexes/multi/test_formats.py
index c3f6e1d88faba..011f61fac90e8 100644
--- a/pandas/tests/indexes/multi/test_formats.py
+++ b/pandas/tests/indexes/multi/test_formats.py
@@ -178,7 +178,7 @@ def test_tuple_width(self, wide_multi_index):
mi = wide_multi_index
result = mi[:1].__repr__()
expected = """MultiIndex([('a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...)],
- names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'])""" # noqa:E501
+ names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'])""" # noqa: E501
assert result == expected
result = mi[:10].__repr__()
diff --git a/pandas/tests/io/parser/common/test_common_basic.py b/pandas/tests/io/parser/common/test_common_basic.py
index 6656face3be84..9083d725887f1 100644
--- a/pandas/tests/io/parser/common/test_common_basic.py
+++ b/pandas/tests/io/parser/common/test_common_basic.py
@@ -351,7 +351,7 @@ def test_escapechar(all_parsers):
data = '''SEARCH_TERM,ACTUAL_URL
"bra tv board","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"
"tv p\xc3\xa5 hjul","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"
-"SLAGBORD, \\"Bergslagen\\", IKEA:s 1700-tals series","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"''' # noqa:E501
+"SLAGBORD, \\"Bergslagen\\", IKEA:s 1700-tals series","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"''' # noqa: E501
parser = all_parsers
result = parser.read_csv(
@@ -457,7 +457,7 @@ def test_read_empty_with_usecols(all_parsers, data, kwargs, expected):
],
)
def test_trailing_spaces(all_parsers, kwargs, expected):
- data = "A B C \nrandom line with trailing spaces \nskip\n1,2,3\n1,2.,4.\nrandom line with trailing tabs\t\t\t\n \n5.1,NaN,10.0\n" # noqa:E501
+ data = "A B C \nrandom line with trailing spaces \nskip\n1,2,3\n1,2.,4.\nrandom line with trailing tabs\t\t\t\n \n5.1,NaN,10.0\n" # noqa: E501
parser = all_parsers
result = parser.read_csv(StringIO(data.replace(",", " ")), **kwargs)
diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py
index 2a05a3aa3297e..030650ad0031d 100644
--- a/pandas/tests/io/parser/test_read_fwf.py
+++ b/pandas/tests/io/parser/test_read_fwf.py
@@ -329,7 +329,7 @@ def test_fwf_regression():
def test_fwf_for_uint8():
data = """1421302965.213420 PRI=3 PGN=0xef00 DST=0x17 SRC=0x28 04 154 00 00 00 00 00 127
-1421302964.226776 PRI=6 PGN=0xf002 SRC=0x47 243 00 00 255 247 00 00 71""" # noqa:E501
+1421302964.226776 PRI=6 PGN=0xf002 SRC=0x47 243 00 00 255 247 00 00 71""" # noqa: E501
df = read_fwf(
StringIO(data),
colspecs=[(0, 17), (25, 26), (33, 37), (49, 51), (58, 62), (63, 1000)],
diff --git a/pandas/tests/io/pytables/test_select.py b/pandas/tests/io/pytables/test_select.py
index 447d56ac91b24..f14a3ad7c5e10 100644
--- a/pandas/tests/io/pytables/test_select.py
+++ b/pandas/tests/io/pytables/test_select.py
@@ -181,12 +181,12 @@ def test_select_dtypes(setup_path):
_maybe_remove(store, "df")
store.append("df", df, data_columns=True)
- expected = df[df.boolv == True].reindex(columns=["A", "boolv"]) # noqa:E712
+ expected = df[df.boolv == True].reindex(columns=["A", "boolv"]) # noqa: E712
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:E712
+ expected = df[df.boolv == False].reindex(columns=["A", "boolv"]) # noqa: E712
for v in [False, "false", 0]:
result = store.select("df", f"boolv == {v}", columns=["A", "boolv"])
tm.assert_frame_equal(expected, result)
@@ -257,7 +257,7 @@ def test_select_dtypes(setup_path):
expected = df[df["A"] > 0]
store.append("df", df, data_columns=True)
- np_zero = np.float64(0) # noqa:F841
+ np_zero = np.float64(0) # noqa: F841
result = store.select("df", where=["A>np_zero"])
tm.assert_frame_equal(expected, result)
@@ -659,7 +659,7 @@ def test_frame_select_complex2(tmp_path):
expected = read_hdf(hh, "df", where="l1=[2, 3, 4]")
# scope with list like
- l0 = selection.index.tolist() # noqa:F841
+ l0 = selection.index.tolist() # noqa: F841
with HDFStore(hh) as store:
result = store.select("df", where="l1=l0")
tm.assert_frame_equal(result, expected)
@@ -668,7 +668,7 @@ def test_frame_select_complex2(tmp_path):
tm.assert_frame_equal(result, expected)
# index
- index = selection.index # noqa:F841
+ index = selection.index # noqa: F841
result = read_hdf(hh, "df", where="l1=index")
tm.assert_frame_equal(result, expected)
@@ -894,7 +894,7 @@ def test_query_compare_column_type(setup_path):
with ensure_clean_store(setup_path) as store:
store.append("test", df, format="table", data_columns=True)
- ts = Timestamp("2014-01-01") # noqa:F841
+ ts = Timestamp("2014-01-01") # noqa: F841
result = store.select("test", where="real_date > ts")
expected = df.loc[[1], :]
tm.assert_frame_equal(expected, result)
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py
index 4bd4e0cd7146f..bb62d1a194a3e 100644
--- a/pandas/tests/io/test_html.py
+++ b/pandas/tests/io/test_html.py
@@ -201,7 +201,7 @@ def test_dtype_backend(self, string_storage, dtype_backend):
check_before_test=True,
)
def test_banklist_url(self):
- url = "https://www.fdic.gov/resources/resolutions/bank-failures/failed-bank-list/index.html" # noqa E501
+ url = "https://www.fdic.gov/resources/resolutions/bank-failures/failed-bank-list/index.html" # noqa: E501
df1 = self.read_html(
# lxml cannot find attrs leave out for now
url,
diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py
index c47a5a55dfcf6..9bbc8f42b6704 100644
--- a/pandas/tests/plotting/test_boxplot_method.py
+++ b/pandas/tests/plotting/test_boxplot_method.py
@@ -439,20 +439,20 @@ def test_grouped_box_layout(self, hist_df):
# _check_plot_works adds an ax so catch warning. see GH #13188
with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
- box = _check_plot_works(
+ _check_plot_works(
df.groupby("gender").boxplot, column="height", return_type="dict"
)
self._check_axes_shape(self.plt.gcf().axes, axes_num=2, layout=(1, 2))
with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
- box = _check_plot_works(
+ _check_plot_works(
df.groupby("category").boxplot, column="height", return_type="dict"
)
self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(2, 2))
# GH 6769
with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
- box = _check_plot_works(
+ _check_plot_works(
df.groupby("classroom").boxplot, column="height", return_type="dict"
)
self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(2, 2))
@@ -469,13 +469,13 @@ def test_grouped_box_layout(self, hist_df):
self._check_visible(ax.get_xticklabels())
self._check_visible([ax.xaxis.get_label()])
- box = df.groupby("classroom").boxplot(
+ df.groupby("classroom").boxplot(
column=["height", "weight", "category"], return_type="dict"
)
self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(2, 2))
with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
- box = _check_plot_works(
+ _check_plot_works(
df.groupby("category").boxplot,
column="height",
layout=(3, 2),
@@ -483,7 +483,7 @@ def test_grouped_box_layout(self, hist_df):
)
self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(3, 2))
with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
- box = _check_plot_works(
+ _check_plot_works(
df.groupby("category").boxplot,
column="height",
layout=(3, -1),
@@ -491,22 +491,18 @@ def test_grouped_box_layout(self, hist_df):
)
self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(3, 2))
- box = df.boxplot(
- column=["height", "weight", "category"], by="gender", layout=(4, 1)
- )
+ df.boxplot(column=["height", "weight", "category"], by="gender", layout=(4, 1))
self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(4, 1))
- box = df.boxplot(
- column=["height", "weight", "category"], by="gender", layout=(-1, 1)
- )
+ df.boxplot(column=["height", "weight", "category"], by="gender", layout=(-1, 1))
self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(3, 1))
- box = df.groupby("classroom").boxplot(
+ df.groupby("classroom").boxplot(
column=["height", "weight", "category"], layout=(1, 4), return_type="dict"
)
self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(1, 4))
- box = df.groupby("classroom").boxplot( # noqa
+ df.groupby("classroom").boxplot(
column=["height", "weight", "category"], layout=(1, -1), return_type="dict"
)
self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(1, 3))
diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py
index 04228bde1c6b9..3392c309e0329 100644
--- a/pandas/tests/plotting/test_hist_method.py
+++ b/pandas/tests/plotting/test_hist_method.py
@@ -123,7 +123,7 @@ def test_hist_no_overlap(self):
def test_hist_by_no_extra_plots(self, hist_df):
df = hist_df
- axes = df.height.hist(by=df.gender) # noqa
+ df.height.hist(by=df.gender)
assert len(self.plt.get_fignums()) == 1
def test_plot_fails_when_ax_differs_from_figure(self, ts):
diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py
index 28e99bd3c0cc0..9514ccd24c1ca 100644
--- a/pandas/tests/resample/test_base.py
+++ b/pandas/tests/resample/test_base.py
@@ -21,7 +21,7 @@
# a fixture value can be overridden by the test parameter value. Note that the
# value of the fixture can be overridden this way even if the test doesn't use
# it directly (doesn't mention it in the function prototype).
-# see https://docs.pytest.org/en/latest/fixture.html#override-a-fixture-with-direct-test-parametrization # noqa:E501
+# see https://docs.pytest.org/en/latest/fixture.html#override-a-fixture-with-direct-test-parametrization # noqa: E501
# in this module we override the fixture values defined in conftest.py
# tuples of '_index_factory,_series_name,_index_start,_index_end'
DATE_RANGE = (date_range, "dti", datetime(2005, 1, 1), datetime(2005, 1, 10))
diff --git a/pandas/tests/scalar/timestamp/test_rendering.py b/pandas/tests/scalar/timestamp/test_rendering.py
index 216a055120a46..c351fb23fca0a 100644
--- a/pandas/tests/scalar/timestamp/test_rendering.py
+++ b/pandas/tests/scalar/timestamp/test_rendering.py
@@ -1,7 +1,7 @@
import pprint
import pytest
-import pytz # noqa # a test below uses pytz but only inside a `eval` call
+import pytz # noqa: F401 # a test below uses pytz but only inside a `eval` call
from pandas import Timestamp
diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py
index be53209d889ee..3aa81c5e99ffe 100644
--- a/pandas/tests/series/test_arithmetic.py
+++ b/pandas/tests/series/test_arithmetic.py
@@ -887,20 +887,20 @@ def test_none_comparison(request, series_with_simple_index):
series.iloc[0] = np.nan
# noinspection PyComparisonWithNone
- result = series == None # noqa:E711
+ result = series == None # noqa: E711
assert not result.iat[0]
assert not result.iat[1]
# noinspection PyComparisonWithNone
- result = series != None # noqa:E711
+ result = series != None # noqa: E711
assert result.iat[0]
assert result.iat[1]
- result = None == series # noqa:E711
+ result = None == series # noqa: E711
assert not result.iat[0]
assert not result.iat[1]
- result = None != series # noqa:E711
+ result = None != series # noqa: E711
assert result.iat[0]
assert result.iat[1]
diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py
index cccc4953bc3c7..c42b9f056878d 100644
--- a/pandas/tests/series/test_repr.py
+++ b/pandas/tests/series/test_repr.py
@@ -376,7 +376,7 @@ def test_categorical_series_repr_datetime(self):
4 2011-01-01 13:00:00
dtype: category
Categories (5, datetime64[ns]): [2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00,
- 2011-01-01 12:00:00, 2011-01-01 13:00:00]""" # noqa:E501
+ 2011-01-01 12:00:00, 2011-01-01 13:00:00]""" # noqa: E501
assert repr(s) == exp
@@ -390,7 +390,7 @@ def test_categorical_series_repr_datetime(self):
dtype: category
Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,
2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,
- 2011-01-01 13:00:00-05:00]""" # noqa:E501
+ 2011-01-01 13:00:00-05:00]""" # noqa: E501
assert repr(s) == exp
@@ -404,7 +404,7 @@ def test_categorical_series_repr_datetime_ordered(self):
4 2011-01-01 13:00:00
dtype: category
Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
- 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa:E501
+ 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
assert repr(s) == exp
@@ -418,7 +418,7 @@ def test_categorical_series_repr_datetime_ordered(self):
dtype: category
Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
- 2011-01-01 13:00:00-05:00]""" # noqa:E501
+ 2011-01-01 13:00:00-05:00]""" # noqa: E501
assert repr(s) == exp
@@ -432,7 +432,7 @@ def test_categorical_series_repr_period(self):
4 2011-01-01 13:00
dtype: category
Categories (5, period[H]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
- 2011-01-01 13:00]""" # noqa:E501
+ 2011-01-01 13:00]""" # noqa: E501
assert repr(s) == exp
@@ -458,7 +458,7 @@ def test_categorical_series_repr_period_ordered(self):
4 2011-01-01 13:00
dtype: category
Categories (5, period[H]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
- 2011-01-01 13:00]""" # noqa:E501
+ 2011-01-01 13:00]""" # noqa: E501
assert repr(s) == exp
@@ -502,7 +502,7 @@ def test_categorical_series_repr_timedelta(self):
dtype: category
Categories (10, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00,
- 8 days 01:00:00, 9 days 01:00:00]""" # noqa:E501
+ 8 days 01:00:00, 9 days 01:00:00]""" # noqa: E501
assert repr(s) == exp
@@ -534,6 +534,6 @@ def test_categorical_series_repr_timedelta_ordered(self):
dtype: category
Categories (10, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
3 days 01:00:00 ... 6 days 01:00:00 < 7 days 01:00:00 <
- 8 days 01:00:00 < 9 days 01:00:00]""" # noqa:E501
+ 8 days 01:00:00 < 9 days 01:00:00]""" # noqa: E501
assert repr(s) == exp
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index a97676578c079..0f5fdbefd13d2 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -40,8 +40,8 @@ def test_dask(df):
olduse = pd.get_option("compute.use_numexpr")
try:
- toolz = import_module("toolz") # noqa:F841
- dask = import_module("dask") # noqa:F841
+ toolz = import_module("toolz") # noqa: F841
+ dask = import_module("dask") # noqa: F841
import dask.dataframe as dd
@@ -58,7 +58,7 @@ def test_dask_ufunc():
olduse = pd.get_option("compute.use_numexpr")
try:
- dask = import_module("dask") # noqa:F841
+ dask = import_module("dask") # noqa: F841
import dask.array as da
import dask.dataframe as dd
@@ -100,7 +100,7 @@ def test_construct_dask_float_array_int_dtype_match_ndarray():
def test_xarray(df):
- xarray = import_module("xarray") # noqa:F841
+ xarray = import_module("xarray") # noqa: F841
assert df.to_xarray() is not None
@@ -142,7 +142,7 @@ def test_oo_optimized_datetime_index_unpickle():
@pytest.mark.network
@tm.network
def test_statsmodels():
- statsmodels = import_module("statsmodels") # noqa:F841
+ statsmodels = import_module("statsmodels") # noqa: F841
import statsmodels.api as sm
import statsmodels.formula.api as smf
@@ -151,7 +151,7 @@ def test_statsmodels():
def test_scikit_learn():
- sklearn = import_module("sklearn") # noqa:F841
+ sklearn = import_module("sklearn") # noqa: F841
from sklearn import (
datasets,
svm,
@@ -174,7 +174,7 @@ def test_seaborn():
def test_pandas_gbq():
# Older versions import from non-public, non-existent pandas funcs
pytest.importorskip("pandas_gbq", minversion="0.10.0")
- pandas_gbq = import_module("pandas_gbq") # noqa:F841
+ pandas_gbq = import_module("pandas_gbq") # noqa: F841
@pytest.mark.network
@@ -253,7 +253,7 @@ def test_frame_setitem_dask_array_into_new_col():
olduse = pd.get_option("compute.use_numexpr")
try:
- dask = import_module("dask") # noqa:F841
+ dask = import_module("dask") # noqa: F841
import dask.array as da
diff --git a/pandas/util/__init__.py b/pandas/util/__init__.py
index aa31c024fe338..89ac6e2963e98 100644
--- a/pandas/util/__init__.py
+++ b/pandas/util/__init__.py
@@ -1,11 +1,11 @@
# pyright: reportUnusedImport = false
-from pandas.util._decorators import ( # noqa:F401
+from pandas.util._decorators import ( # noqa: F401
Appender,
Substitution,
cache_readonly,
)
-from pandas.core.util.hashing import ( # noqa:F401
+from pandas.core.util.hashing import ( # noqa: F401
hash_array,
hash_pandas_object,
)
diff --git a/pyproject.toml b/pyproject.toml
index 6eef8e4fa9b7c..7caf1f2a54f26 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -226,6 +226,8 @@ select = [
"TCH",
# comprehensions
"C4",
+ # pygrep-hooks
+ "PGH"
]
ignore = [
@@ -277,6 +279,8 @@ ignore = [
"PLW0603",
# Docstrings should not be included in stubs
"PYI021",
+ # No builtin `eval()` allowed
+ "PGH001",
# compare-to-empty-string
"PLC1901",
# Use typing_extensions.TypeAlias for type aliases
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53062 | 2023-05-03T23:42:28Z | 2023-05-06T07:07:17Z | 2023-05-06T07:07:17Z | 2023-05-06T19:32:23Z |
REF: privatize maybe_cast_to_extension_array | diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 165a421989002..27eb7994d3ccb 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -38,7 +38,7 @@
validate_insert_loc,
)
-from pandas.core.dtypes.cast import maybe_cast_to_extension_array
+from pandas.core.dtypes.cast import maybe_cast_pointwise_result
from pandas.core.dtypes.common import (
is_list_like,
is_scalar,
@@ -1957,7 +1957,7 @@ def _maybe_convert(arr):
# https://github.com/pandas-dev/pandas/issues/22850
# We catch all regular exceptions here, and fall back
# to an ndarray.
- res = maybe_cast_to_extension_array(type(self), arr)
+ res = maybe_cast_pointwise_result(arr, self.dtype, same_dtype=False)
if not isinstance(res, type(self)):
# exception raised in _from_sequence; ensure we have ndarray
res = np.asarray(arr)
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index db8bdd08ee112..d25e2fc675390 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -67,7 +67,6 @@
PeriodDtype,
)
from pandas.core.dtypes.generic import (
- ABCExtensionArray,
ABCIndex,
ABCSeries,
)
@@ -463,9 +462,9 @@ def maybe_cast_pointwise_result(
cls = dtype.construct_array_type()
if same_dtype:
- result = maybe_cast_to_extension_array(cls, result, dtype=dtype)
+ result = _maybe_cast_to_extension_array(cls, result, dtype=dtype)
else:
- result = maybe_cast_to_extension_array(cls, result)
+ result = _maybe_cast_to_extension_array(cls, result)
elif (numeric_only and dtype.kind in "iufcb") or not numeric_only:
result = maybe_downcast_to_dtype(result, dtype)
@@ -473,7 +472,7 @@ def maybe_cast_pointwise_result(
return result
-def maybe_cast_to_extension_array(
+def _maybe_cast_to_extension_array(
cls: type[ExtensionArray], obj: ArrayLike, dtype: ExtensionDtype | None = None
) -> ArrayLike:
"""
@@ -492,10 +491,6 @@ def maybe_cast_to_extension_array(
"""
from pandas.core.arrays.string_ import BaseStringArray
- assert isinstance(cls, type), f"must pass a type: {cls}"
- assertion_msg = f"must pass a subclass of ExtensionArray: {cls}"
- assert issubclass(cls, ABCExtensionArray), assertion_msg
-
# Everything can be converted to StringArrays, but we may not want to convert
if issubclass(cls, BaseStringArray) and lib.infer_dtype(obj) != "string":
return obj
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/53061 | 2023-05-03T21:42:06Z | 2023-05-04T17:16:24Z | 2023-05-04T17:16:24Z | 2023-05-04T17:48:26Z |
REGR: df.loc setitem losing midx names | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index b6c6df8424ef1..5c3187cda15ae 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -13,6 +13,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 636267e54027f..928ebdd39f984 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -9914,7 +9914,12 @@ def _append(
"or if the Series has a name"
)
- index = Index([other.name], name=self.index.name)
+ index = Index(
+ [other.name],
+ name=self.index.names
+ if isinstance(self.index, MultiIndex)
+ else self.index.name,
+ )
row_df = other.to_frame().T
# infer_objects is needed for
# test_append_empty_frame_to_series_with_dateutil_tz
diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py
index 27b4a4be73032..e6f44359a1a62 100644
--- a/pandas/tests/indexing/multiindex/test_setitem.py
+++ b/pandas/tests/indexing/multiindex/test_setitem.py
@@ -479,6 +479,21 @@ def test_setitem_new_column_all_na(self):
df["new"] = s
assert df["new"].isna().all()
+ def test_setitem_enlargement_keep_index_names(self):
+ # GH#53053
+ mi = MultiIndex.from_tuples([(1, 2, 3)], names=["i1", "i2", "i3"])
+ df = DataFrame(data=[[10, 20, 30]], index=mi, columns=["A", "B", "C"])
+ df.loc[(0, 0, 0)] = df.loc[(1, 2, 3)]
+ mi_expected = MultiIndex.from_tuples(
+ [(1, 2, 3), (0, 0, 0)], names=["i1", "i2", "i3"]
+ )
+ expected = DataFrame(
+ data=[[10, 20, 30], [10, 20, 30]],
+ index=mi_expected,
+ columns=["A", "B", "C"],
+ )
+ tm.assert_frame_equal(df, expected)
+
@td.skip_array_manager_invalid_test # df["foo"] select multiple columns -> .values
# is not a view
| - [x] closes #53053 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53060 | 2023-05-03T21:36:00Z | 2023-05-04T17:21:41Z | 2023-05-04T17:21:41Z | 2023-05-04T17:29:26Z |
BUG: incorrect is_array_like checks | diff --git a/pandas/_typing.py b/pandas/_typing.py
index dc3f2f54a54ca..9d4acbe76ba15 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -155,7 +155,7 @@
RandomState = Union[
int,
- ArrayLike,
+ np.ndarray,
np.random.Generator,
np.random.BitGenerator,
np.random.RandomState,
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index b933a493603c6..4d62f680811ae 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -18,22 +18,6 @@
import numpy as np
from pandas._libs import lib
-from pandas._typing import (
- ArrayLike,
- AxisInt,
- Dtype,
- FillnaOptions,
- Iterator,
- NpDtype,
- PositionalIndexer,
- Scalar,
- Self,
- SortKind,
- TakeIndexer,
- TimeAmbiguous,
- TimeNonexistent,
- npt,
-)
from pandas.compat import (
pa_version_under7p0,
pa_version_under8p0,
@@ -140,8 +124,22 @@ def floordiv_compat(
if TYPE_CHECKING:
from pandas._typing import (
+ ArrayLike,
+ AxisInt,
+ Dtype,
+ FillnaOptions,
+ Iterator,
+ NpDtype,
NumpySorter,
NumpyValueArrayLike,
+ PositionalIndexer,
+ Scalar,
+ Self,
+ SortKind,
+ TakeIndexer,
+ TimeAmbiguous,
+ TimeNonexistent,
+ npt,
)
from pandas import Series
@@ -805,8 +803,9 @@ def fillna(
fallback_performancewarning()
return super().fillna(value=value, method=method, limit=limit)
- if is_array_like(value):
- value = cast(ArrayLike, value)
+ if isinstance(value, (np.ndarray, ExtensionArray)):
+ # Similar to check_value_size, but we do not mask here since we may
+ # end up passing it to the super() method.
if len(value) != len(self):
raise ValueError(
f"Length of 'value' does not match. Got ({len(value)}) "
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 0f0d40ccdc4f3..ee8fe220698b5 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -33,11 +33,9 @@
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
from pandas.core.dtypes.common import (
- is_array_like,
is_bool_dtype,
is_integer,
)
-from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.generic import (
ABCExtensionArray,
ABCIndex,
@@ -120,9 +118,7 @@ def is_bool_indexer(key: Any) -> bool:
check_array_indexer : Check that `key` is a valid array to index,
and convert to an ndarray.
"""
- if isinstance(key, (ABCSeries, np.ndarray, ABCIndex)) or (
- is_array_like(key) and isinstance(key.dtype, ExtensionDtype)
- ):
+ if isinstance(key, (ABCSeries, np.ndarray, ABCIndex, ABCExtensionArray)):
if key.dtype == np.object_:
key_array = np.asarray(key)
@@ -420,7 +416,7 @@ def random_state(state: np.random.Generator) -> np.random.Generator:
@overload
def random_state(
- state: int | ArrayLike | np.random.BitGenerator | np.random.RandomState | None,
+ state: int | np.ndarray | np.random.BitGenerator | np.random.RandomState | None,
) -> np.random.RandomState:
...
@@ -445,24 +441,8 @@ def random_state(state: RandomState | None = None):
np.random.RandomState or np.random.Generator. If state is None, returns np.random
"""
- if (
- is_integer(state)
- or is_array_like(state)
- or isinstance(state, np.random.BitGenerator)
- ):
- # error: Argument 1 to "RandomState" has incompatible type "Optional[Union[int,
- # Union[ExtensionArray, ndarray[Any, Any]], Generator, RandomState]]"; expected
- # "Union[None, Union[Union[_SupportsArray[dtype[Union[bool_, integer[Any]]]],
- # Sequence[_SupportsArray[dtype[Union[bool_, integer[Any]]]]],
- # Sequence[Sequence[_SupportsArray[dtype[Union[bool_, integer[Any]]]]]],
- # Sequence[Sequence[Sequence[_SupportsArray[dtype[Union[bool_,
- # integer[Any]]]]]]],
- # Sequence[Sequence[Sequence[Sequence[_SupportsArray[dtype[Union[bool_,
- # integer[Any]]]]]]]]], Union[bool, int, Sequence[Union[bool, int]],
- # Sequence[Sequence[Union[bool, int]]], Sequence[Sequence[Sequence[Union[bool,
- # int]]]], Sequence[Sequence[Sequence[Sequence[Union[bool, int]]]]]]],
- # BitGenerator]"
- return np.random.RandomState(state) # type: ignore[arg-type]
+ if is_integer(state) or isinstance(state, (np.ndarray, np.random.BitGenerator)):
+ return np.random.RandomState(state)
elif isinstance(state, np.random.RandomState):
return state
elif isinstance(state, np.random.Generator):
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53057 | 2023-05-03T18:40:38Z | 2023-05-04T17:25:40Z | 2023-05-04T17:25:40Z | 2023-05-04T17:45:35Z |
STY: Enable ruff C4 - comprehensions | diff --git a/asv_bench/benchmarks/dtypes.py b/asv_bench/benchmarks/dtypes.py
index 52c87455b12b3..c33043c0eddc1 100644
--- a/asv_bench/benchmarks/dtypes.py
+++ b/asv_bench/benchmarks/dtypes.py
@@ -24,7 +24,7 @@
class Dtypes:
- params = _dtypes + list(map(lambda dt: dt.name, _dtypes))
+ params = _dtypes + [dt.name for dt in _dtypes]
param_names = ["dtype"]
def time_pandas_dtype(self, dtype):
diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py
index 8436126232cf9..f8c8e6d87ff13 100644
--- a/pandas/core/computation/expr.py
+++ b/pandas/core/computation/expr.py
@@ -192,7 +192,7 @@ def _filter_nodes(superclass, all_nodes=_all_nodes):
return frozenset(node_names)
-_all_node_names = frozenset(map(lambda x: x.__name__, _all_nodes))
+_all_node_names = frozenset(x.__name__ for x in _all_nodes)
_mod_nodes = _filter_nodes(ast.mod)
_stmt_nodes = _filter_nodes(ast.stmt)
_expr_nodes = _filter_nodes(ast.expr)
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 56d6aa92022f9..072627b275a02 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -4115,9 +4115,9 @@ def _reindex_output(
# reindex `output`, and then reset the in-axis grouper columns.
# Select in-axis groupers
- in_axis_grps = list(
+ in_axis_grps = [
(i, ping.name) for (i, ping) in enumerate(groupings) if ping.in_axis
- )
+ ]
if len(in_axis_grps) > 0:
g_nums, g_names = zip(*in_axis_grps)
output = output.drop(labels=list(g_names), axis=1)
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index da35716a5b239..457bbced87d55 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -726,7 +726,7 @@ def _format_header(self) -> Iterable[ExcelCell]:
row = [x if x is not None else "" for x in self.df.index.names] + [
""
] * len(self.columns)
- if reduce(lambda x, y: x and y, map(lambda x: x != "", row)):
+ if reduce(lambda x, y: x and y, (x != "" for x in row)):
gen2 = (
ExcelCell(self.rowcounter, colindex, val, self.header_style)
for colindex, val in enumerate(row)
diff --git a/pandas/io/formats/html.py b/pandas/io/formats/html.py
index 6fbbbd01cf773..0ab02a81d4880 100644
--- a/pandas/io/formats/html.py
+++ b/pandas/io/formats/html.py
@@ -621,7 +621,7 @@ def write_style(self) -> None:
)
else:
element_props.append(("thead th", "text-align", "right"))
- template_mid = "\n\n".join(map(lambda t: template_select % t, element_props))
+ template_mid = "\n\n".join(template_select % t for t in element_props)
template = dedent("\n".join((template_first, template_mid, template_last)))
self.write(template)
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py
index 9374b232f3cd2..93ae2bfdd01e4 100644
--- a/pandas/tests/computation/test_eval.py
+++ b/pandas/tests/computation/test_eval.py
@@ -218,7 +218,7 @@ def test_compound_invert_op(self, op, lhs, rhs, request, engine, parser):
else:
# compound
if is_scalar(lhs) and is_scalar(rhs):
- lhs, rhs = map(lambda x: np.array([x]), (lhs, rhs))
+ lhs, rhs = (np.array([x]) for x in (lhs, rhs))
expected = _eval_single_bin(lhs, op, rhs, engine)
if is_scalar(expected):
expected = not expected
@@ -746,7 +746,7 @@ def test_binop_typecasting(self, engine, parser, op, dt, left_right):
def should_warn(*args):
not_mono = not any(map(operator.attrgetter("is_monotonic_increasing"), args))
only_one_dt = reduce(
- operator.xor, map(lambda x: issubclass(x.dtype.type, np.datetime64), args)
+ operator.xor, (issubclass(x.dtype.type, np.datetime64) for x in args)
)
return not_mono and only_one_dt
diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py
index 58bb551e036a9..0158e7589b214 100644
--- a/pandas/tests/dtypes/test_missing.py
+++ b/pandas/tests/dtypes/test_missing.py
@@ -643,7 +643,7 @@ def test_array_equivalent_nested_mixed_list(strict_nan):
np.array(["c", "d"], dtype=object),
]
left = np.array([subarr, None], dtype=object)
- right = np.array([list([[None, "b"], ["c", "d"]]), None], dtype=object)
+ right = np.array([[[None, "b"], ["c", "d"]], None], dtype=object)
assert array_equivalent(left, right, strict_nan=strict_nan)
assert not array_equivalent(left, right[::-1], strict_nan=strict_nan)
diff --git a/pandas/tests/extension/date/array.py b/pandas/tests/extension/date/array.py
index 08d7e0de82ba8..20373e323e2de 100644
--- a/pandas/tests/extension/date/array.py
+++ b/pandas/tests/extension/date/array.py
@@ -83,7 +83,7 @@ def __init__(
self._day = np.zeros(ldates, dtype=np.uint8) # 255 (1, 12)
# populate them
for i, (y, m, d) in enumerate(
- map(lambda date: (date.year, date.month, date.day), dates)
+ (date.year, date.month, date.day) for date in dates
):
self._year[i] = y
self._month[i] = m
@@ -94,7 +94,7 @@ def __init__(
if ldates != 3:
raise ValueError("only triples are valid")
# check if all elements have the same type
- if any(map(lambda x: not isinstance(x, np.ndarray), dates)):
+ if any(not isinstance(x, np.ndarray) for x in dates):
raise TypeError("invalid type")
ly, lm, ld = (len(cast(np.ndarray, d)) for d in dates)
if not ly == lm == ld:
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index 08546f03cee69..9fdb600b6efc4 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -152,9 +152,9 @@ def test_astype_str(self):
expected = DataFrame(
{
- "a": list(map(str, map(lambda x: Timestamp(x)._date_repr, a._values))),
+ "a": list(map(str, (Timestamp(x)._date_repr for x in a._values))),
"b": list(map(str, map(Timestamp, b._values))),
- "c": list(map(lambda x: Timedelta(x)._repr_base(), c._values)),
+ "c": [Timedelta(x)._repr_base() for x in c._values],
"d": list(map(str, d._values)),
"e": list(map(str, e._values)),
}
diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py
index 2d39120e1c1ff..41b7dde4bf631 100644
--- a/pandas/tests/groupby/test_grouping.py
+++ b/pandas/tests/groupby/test_grouping.py
@@ -992,7 +992,7 @@ def test_multi_iter_frame(self, three_group):
# calling `dict` on a DataFrameGroupBy leads to a TypeError,
# we need to use a dictionary comprehension here
# pylint: disable-next=unnecessary-comprehension
- groups = {key: gp for key, gp in grouped}
+ groups = {key: gp for key, gp in grouped} # noqa: C416
assert len(groups) == 2
# axis = 1
diff --git a/pandas/tests/groupby/test_raises.py b/pandas/tests/groupby/test_raises.py
index fb967430376de..6fb903b02b62f 100644
--- a/pandas/tests/groupby/test_raises.py
+++ b/pandas/tests/groupby/test_raises.py
@@ -229,7 +229,7 @@ def test_groupby_raises_string_np(
),
}[groupby_func_np]
- _call_and_check(klass, msg, how, gb, groupby_func_np, tuple())
+ _call_and_check(klass, msg, how, gb, groupby_func_np, ())
@pytest.mark.parametrize("how", ["method", "agg", "transform"])
@@ -333,7 +333,7 @@ def test_groupby_raises_datetime_np(
np.mean: (None, ""),
}[groupby_func_np]
- _call_and_check(klass, msg, how, gb, groupby_func_np, tuple())
+ _call_and_check(klass, msg, how, gb, groupby_func_np, ())
@pytest.mark.parametrize("func", ["prod", "cumprod", "skew", "var"])
@@ -526,7 +526,7 @@ def test_groupby_raises_category_np(
),
}[groupby_func_np]
- _call_and_check(klass, msg, how, gb, groupby_func_np, tuple())
+ _call_and_check(klass, msg, how, gb, groupby_func_np, ())
@pytest.mark.parametrize("how", ["method", "agg", "transform"])
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index 4adab3a1d6fff..04e6f5d2fdcaa 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -362,11 +362,11 @@ def test_dispatch_transform(tsframe):
def test_transform_fillna_null():
df = DataFrame(
- dict(
- price=[10, 10, 20, 20, 30, 30],
- color=[10, 10, 20, 20, 30, 30],
- cost=(100, 200, 300, 400, 500, 600),
- )
+ {
+ "price": [10, 10, 20, 20, 30, 30],
+ "color": [10, 10, 20, 20, 30, 30],
+ "cost": (100, 200, 300, 400, 500, 600),
+ }
)
with pytest.raises(ValueError, match="Must specify a fill 'value' or 'method'"):
df.groupby(["price"]).transform("fillna")
diff --git a/pandas/tests/indexing/multiindex/test_indexing_slow.py b/pandas/tests/indexing/multiindex/test_indexing_slow.py
index c59dd2724a94f..36b7dcfe4db12 100644
--- a/pandas/tests/indexing/multiindex/test_indexing_slow.py
+++ b/pandas/tests/indexing/multiindex/test_indexing_slow.py
@@ -34,7 +34,7 @@
np.random.choice(list("ZYXWVUTSRQP"), m),
]
keys = list(map(tuple, zip(*keys)))
-keys += list(map(lambda t: t[:-1], vals[:: n // m]))
+keys += [t[:-1] for t in vals[:: n // m]]
# covers both unique index and non-unique index
diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py
index a2fcd18ba5bfe..5d1d4ba6f638a 100644
--- a/pandas/tests/indexing/test_partial.py
+++ b/pandas/tests/indexing/test_partial.py
@@ -283,30 +283,30 @@ def test_partial_setting_frame(self, using_array_manager):
df.iat[4, 2] = 5.0
# row setting where it exists
- expected = DataFrame(dict({"A": [0, 4, 4], "B": [1, 5, 5]}))
+ expected = DataFrame({"A": [0, 4, 4], "B": [1, 5, 5]})
df = df_orig.copy()
df.iloc[1] = df.iloc[2]
tm.assert_frame_equal(df, expected)
- expected = DataFrame(dict({"A": [0, 4, 4], "B": [1, 5, 5]}))
+ expected = DataFrame({"A": [0, 4, 4], "B": [1, 5, 5]})
df = df_orig.copy()
df.loc[1] = df.loc[2]
tm.assert_frame_equal(df, expected)
# like 2578, partial setting with dtype preservation
- expected = DataFrame(dict({"A": [0, 2, 4, 4], "B": [1, 3, 5, 5]}))
+ expected = DataFrame({"A": [0, 2, 4, 4], "B": [1, 3, 5, 5]})
df = df_orig.copy()
df.loc[3] = df.loc[2]
tm.assert_frame_equal(df, expected)
# single dtype frame, overwrite
- expected = DataFrame(dict({"A": [0, 2, 4], "B": [0, 2, 4]}))
+ expected = DataFrame({"A": [0, 2, 4], "B": [0, 2, 4]})
df = df_orig.copy()
df.loc[:, "B"] = df.loc[:, "A"]
tm.assert_frame_equal(df, expected)
# mixed dtype frame, overwrite
- expected = DataFrame(dict({"A": [0, 2, 4], "B": Series([0.0, 2.0, 4.0])}))
+ expected = DataFrame({"A": [0, 2, 4], "B": Series([0.0, 2.0, 4.0])})
df = df_orig.copy()
df["B"] = df["B"].astype(np.float64)
# as of 2.0, df.loc[:, "B"] = ... attempts (and here succeeds) at
diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py
index 67f7e12fcc3c2..c44f42727faeb 100644
--- a/pandas/tests/io/formats/style/test_html.py
+++ b/pandas/tests/io/formats/style/test_html.py
@@ -978,7 +978,7 @@ def html_lines(foot_prefix: str):
def test_to_html_na_rep_non_scalar_data(datapath):
# GH47103
- df = DataFrame([dict(a=1, b=[1, 2, 3], c=np.nan)])
+ df = DataFrame([{"a": 1, "b": [1, 2, 3], "c": np.nan}])
result = df.style.format(na_rep="-").to_html(table_uuid="test")
expected = """\
<style type="text/css">
diff --git a/pandas/tests/io/formats/style/test_matplotlib.py b/pandas/tests/io/formats/style/test_matplotlib.py
index 591fa7f72050e..1485bd64e4b57 100644
--- a/pandas/tests/io/formats/style/test_matplotlib.py
+++ b/pandas/tests/io/formats/style/test_matplotlib.py
@@ -307,7 +307,7 @@ def test_pass_colormap_instance(df, plot_method):
# https://github.com/pandas-dev/pandas/issues/49374
cmap = mpl.colors.ListedColormap([[1, 1, 1], [0, 0, 0]])
df["c"] = df.A + df.B
- kwargs = dict(x="A", y="B", c="c", colormap=cmap)
+ kwargs = {"x": "A", "y": "B", "c": "c", "colormap": cmap}
if plot_method == "hexbin":
kwargs["C"] = kwargs.pop("c")
getattr(df.plot, plot_method)(**kwargs)
diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py
index a66858d3f983e..9c128756339ab 100644
--- a/pandas/tests/io/formats/test_to_html.py
+++ b/pandas/tests/io/formats/test_to_html.py
@@ -884,7 +884,7 @@ def test_to_html_na_rep_and_float_format(na_rep, datapath):
def test_to_html_na_rep_non_scalar_data(datapath):
# GH47103
- df = DataFrame([dict(a=1, b=[1, 2, 3])])
+ df = DataFrame([{"a": 1, "b": [1, 2, 3]}])
result = df.to_html(na_rep="-")
expected = expected_html(datapath, "gh47103_expected_output")
assert result == expected
diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py
index 55efb9254ee34..81de4f13de81d 100644
--- a/pandas/tests/io/parser/test_parse_dates.py
+++ b/pandas/tests/io/parser/test_parse_dates.py
@@ -746,9 +746,7 @@ def test_date_parser_int_bug(all_parsers):
def test_nat_parse(all_parsers):
# see gh-3062
parser = all_parsers
- df = DataFrame(
- dict({"A": np.arange(10, dtype="float64"), "B": Timestamp("20010101")})
- )
+ df = DataFrame({"A": np.arange(10, dtype="float64"), "B": Timestamp("20010101")})
df.iloc[3:6, :] = np.nan
with tm.ensure_clean("__nat_parse_.csv") as path:
diff --git a/pandas/tests/libs/test_hashtable.py b/pandas/tests/libs/test_hashtable.py
index 4a5d5e0c85a09..0685897e723a2 100644
--- a/pandas/tests/libs/test_hashtable.py
+++ b/pandas/tests/libs/test_hashtable.py
@@ -28,7 +28,7 @@ def get_allocated_khash_memory():
snapshot = snapshot.filter_traces(
(tracemalloc.DomainFilter(True, ht.get_hashtable_trace_domain()),)
)
- return sum(map(lambda x: x.size, snapshot.traces))
+ return sum(x.size for x in snapshot.traces)
@pytest.mark.parametrize(
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 8cfd0682e1f5d..7238232a46e60 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -369,14 +369,14 @@ def test_constructor_generator(self):
def test_constructor_map(self):
# GH8909
- m = map(lambda x: x, range(10))
+ m = (x for x in range(10))
result = Series(m)
exp = Series(range(10))
tm.assert_series_equal(result, exp)
# same but with non-default index
- m = map(lambda x: x, range(10))
+ m = (x for x in range(10))
result = Series(m, index=range(10, 20))
exp.index = range(10, 20)
tm.assert_series_equal(result, exp)
@@ -647,7 +647,7 @@ def test_constructor_default_index(self):
list(range(3)),
Categorical(["a", "b", "a"]),
(i for i in range(3)),
- map(lambda x: x, range(3)),
+ (x for x in range(3)),
],
)
def test_constructor_index_mismatch(self, input):
diff --git a/pandas/tests/util/test_assert_almost_equal.py b/pandas/tests/util/test_assert_almost_equal.py
index 5c50e5ad83967..ad54606547909 100644
--- a/pandas/tests/util/test_assert_almost_equal.py
+++ b/pandas/tests/util/test_assert_almost_equal.py
@@ -512,7 +512,7 @@ def test_assert_almost_equal_iterable_values_mismatch():
# same-length lists
(
np.array([subarr, None], dtype=object),
- np.array([list([[None, "b"], ["c", "d"]]), None], dtype=object),
+ np.array([[[None, "b"], ["c", "d"]], None], dtype=object),
),
# dicts
(
diff --git a/pyproject.toml b/pyproject.toml
index 7604046471fe8..042d13ea7956a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -195,14 +195,13 @@ line-length = 88
update-check = false
target-version = "py310"
fix = true
-unfixable = ["E711"]
+unfixable = []
select = [
# pyflakes
"F",
# pycodestyle
- "E",
- "W",
+ "E", "W",
# flake8-2020
"YTT",
# flake8-bugbear
@@ -221,6 +220,8 @@ select = [
"ISC",
# type-checking imports
"TCH",
+ # comprehensions
+ "C4",
]
ignore = [
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/53056 | 2023-05-03T17:43:52Z | 2023-05-03T21:37:42Z | 2023-05-03T21:37:42Z | 2023-05-03T21:37:45Z |
BUG: Fix regression when printing backslash in DataFrame.to_string | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 692315bb88d30..7dc00e8e4bfeb 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -14,7 +14,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
--
+- Fixed regression in :meth:`DataFrame.to_string` printing a backslash at the end of the first row of data, instead of headers, when the DataFrame doesn't fit the line width (:issue:`53054`)
.. ---------------------------------------------------------------------------
.. _whatsnew_202.bug_fixes:
diff --git a/pandas/io/formats/string.py b/pandas/io/formats/string.py
index 8ad545270dec1..a4ec058467fb7 100644
--- a/pandas/io/formats/string.py
+++ b/pandas/io/formats/string.py
@@ -135,12 +135,6 @@ def _join_multiline(self, strcols_input: Iterable[list[str]]) -> str:
col_bins = _binify(col_widths, lwidth)
nbins = len(col_bins)
- if self.fmt.is_truncated_vertically:
- assert self.fmt.max_rows_fitted is not None
- nrows = self.fmt.max_rows_fitted + 1
- else:
- nrows = len(self.frame)
-
str_lst = []
start = 0
for i, end in enumerate(col_bins):
@@ -148,6 +142,7 @@ def _join_multiline(self, strcols_input: Iterable[list[str]]) -> str:
if self.fmt.index:
row.insert(0, idx)
if nbins > 1:
+ nrows = len(row[-1])
if end <= len(strcols) and i < nbins - 1:
row.append([" \\"] + [" "] * (nrows - 1))
else:
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index e4680cca881e5..6acef0f564ef4 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -1446,25 +1446,100 @@ def test_to_string_no_index(self):
assert df_s == expected
def test_to_string_line_width_no_index(self):
- # GH 13998, GH 22505, # GH 49230
+ # GH 13998, GH 22505
df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
df_s = df.to_string(line_width=1, index=False)
- expected = " x \n 1 \\\n 2 \n 3 \n\n y \n 4 \n 5 \n 6 "
+ expected = " x \\\n 1 \n 2 \n 3 \n\n y \n 4 \n 5 \n 6 "
assert df_s == expected
df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})
df_s = df.to_string(line_width=1, index=False)
- expected = " x \n11 \\\n22 \n33 \n\n y \n 4 \n 5 \n 6 "
+ expected = " x \\\n11 \n22 \n33 \n\n y \n 4 \n 5 \n 6 "
assert df_s == expected
df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})
df_s = df.to_string(line_width=1, index=False)
- expected = " x \n 11 \\\n 22 \n-33 \n\n y \n 4 \n 5 \n-6 "
+ expected = " x \\\n 11 \n 22 \n-33 \n\n y \n 4 \n 5 \n-6 "
+
+ assert df_s == expected
+
+ def test_to_string_line_width_no_header(self):
+ # GH 53054
+ df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1, header=False)
+ expected = "0 1 \\\n1 2 \n2 3 \n\n0 4 \n1 5 \n2 6 "
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1, header=False)
+ expected = "0 11 \\\n1 22 \n2 33 \n\n0 4 \n1 5 \n2 6 "
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})
+
+ df_s = df.to_string(line_width=1, header=False)
+ expected = "0 11 \\\n1 22 \n2 -33 \n\n0 4 \n1 5 \n2 -6 "
+
+ assert df_s == expected
+
+ def test_to_string_line_width_no_index_no_header(self):
+ # GH 53054
+ df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1, index=False, header=False)
+ expected = "1 \\\n2 \n3 \n\n4 \n5 \n6 "
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1, index=False, header=False)
+ expected = "11 \\\n22 \n33 \n\n4 \n5 \n6 "
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})
+
+ df_s = df.to_string(line_width=1, index=False, header=False)
+ expected = " 11 \\\n 22 \n-33 \n\n 4 \n 5 \n-6 "
+
+ assert df_s == expected
+
+ def test_to_string_line_width_with_both_index_and_header(self):
+ # GH 53054
+ df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1)
+ expected = (
+ " x \\\n0 1 \n1 2 \n2 3 \n\n y \n0 4 \n1 5 \n2 6 "
+ )
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})
+
+ df_s = df.to_string(line_width=1)
+ expected = (
+ " x \\\n0 11 \n1 22 \n2 33 \n\n y \n0 4 \n1 5 \n2 6 "
+ )
+
+ assert df_s == expected
+
+ df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})
+
+ df_s = df.to_string(line_width=1)
+ expected = (
+ " x \\\n0 11 \n1 22 \n2 -33 \n\n y \n0 4 \n1 5 \n2 -6 "
+ )
assert df_s == expected
| - [x] closes #53054
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53055 | 2023-05-03T15:53:57Z | 2023-05-05T17:15:02Z | 2023-05-05T17:15:02Z | 2023-05-08T07:43:08Z |
DOC: Typo on the close argument of pandas.DataFrame.rolling | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index e26b4779ef7fa..56d6aa92022f9 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -2771,7 +2771,7 @@ def rolling(self, *args, **kwargs) -> RollingGroupby:
If ``'left'``, the last point in the window is excluded from calculations.
- If ``'both'``, the no points in the window are excluded from calculations.
+ If ``'both'``, no points in the window are excluded from calculations.
If ``'neither'``, the first and last points in the window are excluded
from calculations.
| The documentation "close" argument of pandas.DataFrame.rolling for option "both" had an extra "the", it is removed here.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53050 | 2023-05-03T08:03:41Z | 2023-05-03T15:55:09Z | 2023-05-03T15:55:09Z | 2023-05-03T15:55:17Z |
BUG: `GroupBy.quantile` implicitly sorts `index.levels` | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 9fb039de8f73a..08ea347708b8f 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -412,6 +412,7 @@ Groupby/resample/rolling
the function operated on the whole index rather than each element of the index. (:issue:`51979`)
- Bug in :meth:`DataFrameGroupBy.apply` causing an error to be raised when the input :class:`DataFrame` was subset as a :class:`DataFrame` after groupby (``[['a']]`` and not ``['a']``) and the given callable returned :class:`Series` that were not all indexed the same. (:issue:`52444`)
- Bug in :meth:`GroupBy.groups` with a datetime key in conjunction with another key produced incorrect number of group keys (:issue:`51158`)
+- Bug in :meth:`GroupBy.quantile` may implicitly sort the result index with ``sort=False`` (:issue:`53009`)
- Bug in :meth:`GroupBy.var` failing to raise ``TypeError`` when called with datetime64, timedelta64 or :class:`PeriodDtype` values (:issue:`52128`, :issue:`53045`)
-
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index c32c96077bde7..5928c32e22b7f 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -70,7 +70,10 @@ class providing the base-class of operations.
)
from pandas.util._exceptions import find_stack_level
-from pandas.core.dtypes.cast import ensure_dtype_can_hold_na
+from pandas.core.dtypes.cast import (
+ coerce_indexer_dtype,
+ ensure_dtype_can_hold_na,
+)
from pandas.core.dtypes.common import (
is_bool_dtype,
is_float_dtype,
@@ -4309,13 +4312,19 @@ def _insert_quantile_level(idx: Index, qs: npt.NDArray[np.float64]) -> MultiInde
MultiIndex
"""
nqs = len(qs)
+ lev_codes, lev = Index(qs).factorize()
+ lev_codes = coerce_indexer_dtype(lev_codes, lev)
if idx._is_multi:
idx = cast(MultiIndex, idx)
- lev_codes, lev = Index(qs).factorize()
levels = list(idx.levels) + [lev]
codes = [np.repeat(x, nqs) for x in idx.codes] + [np.tile(lev_codes, len(idx))]
mi = MultiIndex(levels=levels, codes=codes, names=idx.names + [None])
else:
- mi = MultiIndex.from_product([idx, qs])
+ nidx = len(idx)
+ idx_codes = coerce_indexer_dtype(np.arange(nidx), idx)
+ levels = [idx, lev]
+ codes = [np.repeat(idx_codes, nqs), np.tile(lev_codes, nidx)]
+ mi = MultiIndex(levels=levels, codes=codes, names=[idx.name, None])
+
return mi
diff --git a/pandas/tests/groupby/test_quantile.py b/pandas/tests/groupby/test_quantile.py
index 5801223c0e718..7bf168944a1ac 100644
--- a/pandas/tests/groupby/test_quantile.py
+++ b/pandas/tests/groupby/test_quantile.py
@@ -471,3 +471,33 @@ def test_groupby_quantile_dt64tz_period():
expected.index = expected.index.astype(np.int_)
tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_quantile_nonmulti_levels_order():
+ # Non-regression test for GH #53009
+ ind = pd.MultiIndex.from_tuples(
+ [
+ (0, "a", "B"),
+ (0, "a", "A"),
+ (0, "b", "B"),
+ (0, "b", "A"),
+ (1, "a", "B"),
+ (1, "a", "A"),
+ (1, "b", "B"),
+ (1, "b", "A"),
+ ],
+ names=["sample", "cat0", "cat1"],
+ )
+ ser = pd.Series(range(8), index=ind)
+ result = ser.groupby(level="cat1", sort=False).quantile([0.2, 0.8])
+
+ qind = pd.MultiIndex.from_tuples(
+ [("B", 0.2), ("B", 0.8), ("A", 0.2), ("A", 0.8)], names=["cat1", None]
+ )
+ expected = pd.Series([1.2, 4.8, 2.2, 5.8], index=qind)
+
+ tm.assert_series_equal(result, expected)
+
+ # We need to check that index levels are not sorted
+ expected_levels = pd.core.indexes.frozen.FrozenList([["B", "A"], [0.2, 0.8]])
+ tm.assert_equal(result.index.levels, expected_levels)
| - [x] Closes #53009
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests)
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit)
- [x] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file
| https://api.github.com/repos/pandas-dev/pandas/pulls/53049 | 2023-05-03T07:09:33Z | 2023-05-12T17:20:30Z | 2023-05-12T17:20:30Z | 2023-06-28T05:43:11Z |
STY: Bump black to 23.3.0 | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 2116bc64a5805..de1e615beaaa2 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -26,7 +26,7 @@ repos:
language: python
require_serial: true
types_or: [python, pyi]
- additional_dependencies: [black==23.1.0]
+ additional_dependencies: [black==23.3.0]
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.264
hooks:
diff --git a/environment.yml b/environment.yml
index 86272b9f325ca..de11c5e9d5967 100644
--- a/environment.yml
+++ b/environment.yml
@@ -73,7 +73,7 @@ dependencies:
- cxx-compiler
# code checks
- - black=23.1.0
+ - black=23.3.0
- cpplint
- flake8=6.0.0
- isort>=5.2.1 # check that imports are in the right order
diff --git a/pyproject.toml b/pyproject.toml
index 13362e998a57a..7604046471fe8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -171,7 +171,7 @@ environment = { IS_32_BIT="true" }
[tool.black]
target-version = ['py39', 'py310']
-required-version = '23.1.0'
+required-version = '23.3.0'
exclude = '''
(
asv_bench/env
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 4d5e1fda40680..9779f4e5f6cce 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -50,7 +50,7 @@ seaborn
moto
flask
asv>=0.5.1
-black==23.1.0
+black==23.3.0
cpplint
flake8==6.0.0
isort>=5.2.1
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53048 | 2023-05-03T03:14:32Z | 2023-05-03T08:42:00Z | 2023-05-03T08:42:00Z | 2023-05-03T15:45:40Z |
ERR: Raise TypeError for groupby.var with timeldeta | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 84e011bf80da6..4e0f31aa24f84 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -401,7 +401,7 @@ Groupby/resample/rolling
the function operated on the whole index rather than each element of the index. (:issue:`51979`)
- Bug in :meth:`DataFrameGroupBy.apply` causing an error to be raised when the input :class:`DataFrame` was subset as a :class:`DataFrame` after groupby (``[['a']]`` and not ``['a']``) and the given callable returned :class:`Series` that were not all indexed the same. (:issue:`52444`)
- Bug in :meth:`GroupBy.groups` with a datetime key in conjunction with another key produced incorrect number of group keys (:issue:`51158`)
-- Bug in :meth:`GroupBy.var` failing to raise ``TypeError`` when called with datetime64 or :class:`PeriodDtype` values (:issue:`52128`)
+- Bug in :meth:`GroupBy.var` failing to raise ``TypeError`` when called with datetime64, timedelta64 or :class:`PeriodDtype` values (:issue:`52128`, :issue:`53045`)
-
Reshaping
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 1c662e4412886..964e5a0944f16 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1583,7 +1583,7 @@ def _groupby_op(
)
else:
# timedeltas we can add but not multiply
- if how in ["prod", "cumprod", "skew"]:
+ if how in ["prod", "cumprod", "skew", "var"]:
raise TypeError(f"timedelta64 type does not support {how} operations")
# All of the functions implemented here are ordinal, so we can
diff --git a/pandas/tests/groupby/test_raises.py b/pandas/tests/groupby/test_raises.py
index 55a6bc37d6046..fb967430376de 100644
--- a/pandas/tests/groupby/test_raises.py
+++ b/pandas/tests/groupby/test_raises.py
@@ -66,6 +66,19 @@ def df_with_datetime_col():
return df
+@pytest.fixture
+def df_with_timedelta_col():
+ df = DataFrame(
+ {
+ "a": [1, 1, 1, 1, 1, 2, 2, 2, 2],
+ "b": [3, 3, 4, 4, 4, 4, 4, 3, 3],
+ "c": range(9),
+ "d": datetime.timedelta(days=1),
+ }
+ )
+ return df
+
+
@pytest.fixture
def df_with_cat_col():
df = DataFrame(
@@ -323,6 +336,21 @@ def test_groupby_raises_datetime_np(
_call_and_check(klass, msg, how, gb, groupby_func_np, tuple())
+@pytest.mark.parametrize("func", ["prod", "cumprod", "skew", "var"])
+def test_groupby_raises_timedelta(func, df_with_timedelta_col):
+ df = df_with_timedelta_col
+ gb = df.groupby(by="a")
+
+ _call_and_check(
+ TypeError,
+ "timedelta64 type does not support .* operations",
+ "method",
+ gb,
+ func,
+ [],
+ )
+
+
@pytest.mark.parametrize("how", ["method", "agg", "transform"])
def test_groupby_raises_category(
how, by, groupby_series, groupby_func, using_copy_on_write, df_with_cat_col
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53045 | 2023-05-02T21:09:25Z | 2023-05-03T14:41:35Z | 2023-05-03T14:41:35Z | 2023-05-03T18:25:31Z |
BUG: `MultiIndex` displays incorrectly with a long element | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 84e011bf80da6..c390f57a904cb 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -372,7 +372,7 @@ I/O
- Bug in :func:`read_hdf` not properly closing store after a ``IndexError`` is raised (:issue:`52781`)
- Bug in :func:`read_html`, style elements were read into DataFrames (:issue:`52197`)
- Bug in :func:`read_html`, tail texts were removed together with elements containing ``display:none`` style (:issue:`51629`)
--
+- Bug in displaying a :class:`MultiIndex` with a long element (:issue:`52960`)
Period
^^^^^^
diff --git a/pandas/io/formats/printing.py b/pandas/io/formats/printing.py
index 0062a4737740e..828f3cf3735e9 100644
--- a/pandas/io/formats/printing.py
+++ b/pandas/io/formats/printing.py
@@ -412,12 +412,14 @@ def best_len(values: list[str]) -> int:
# max_space
max_space = display_width - len(space2)
value = tail[0]
- for max_items in reversed(range(1, len(value) + 1)):
- pprinted_seq = _pprint_seq(value, max_seq_items=max_items)
+ max_items = 1
+ for num_items in reversed(range(1, len(value) + 1)):
+ pprinted_seq = _pprint_seq(value, max_seq_items=num_items)
if len(pprinted_seq) < max_space:
- head = [_pprint_seq(x, max_seq_items=max_items) for x in head]
- tail = [_pprint_seq(x, max_seq_items=max_items) for x in tail]
+ max_items = num_items
break
+ head = [_pprint_seq(x, max_seq_items=max_items) for x in head]
+ tail = [_pprint_seq(x, max_seq_items=max_items) for x in tail]
summary = ""
line = space2
diff --git a/pandas/tests/io/formats/test_printing.py b/pandas/tests/io/formats/test_printing.py
index 803ed8d342a2f..6f578b45bf71d 100644
--- a/pandas/tests/io/formats/test_printing.py
+++ b/pandas/tests/io/formats/test_printing.py
@@ -196,3 +196,14 @@ def test_enable_data_resource_formatter(self, ip):
assert formatters[mimetype].enabled
# smoke test that it works
ip.instance(config=ip.config).display_formatter.format(cf)
+
+
+def test_multiindex_long_element():
+ # Non-regression test towards GH #52960
+ data = pd.MultiIndex.from_tuples([("c" * 62,)])
+
+ expected = (
+ "MultiIndex([('cccccccccccccccccccccccccccccccccccccccc"
+ "cccccccccccccccccccccc',)],\n )"
+ )
+ assert str(data) == expected
| - [x] Closes #52960
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests)
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit)
- [x] Added an entry in the latest `doc/source/whatsnew/v2.1.0.rst` file
https://github.com/pandas-dev/pandas/blob/721bd7a22efbd1c57f86fd61d6f0e668b79942ae/pandas/io/formats/printing.py#L417-L420
The `if` branch as shown above may never be visited, so `head` and `tail` may not be correctly set. This pull request fixes this problem. | https://api.github.com/repos/pandas-dev/pandas/pulls/53044 | 2023-05-02T20:31:03Z | 2023-05-05T18:05:48Z | 2023-05-05T18:05:48Z | 2023-09-23T13:40:07Z |
DEPR: require SparseDtype.fill_value be compatible with SparseDtype.subtype | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 5b62883c2741e..63e212e40e9a3 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -261,6 +261,7 @@ Deprecations
- Deprecated unused "closed" keyword in the :class:`TimedeltaIndex` constructor (:issue:`52628`)
- Deprecated logical operation between two non boolean :class:`Series` with different indexes always coercing the result to bool dtype. In a future version, this will maintain the return type of the inputs. (:issue:`52500`, :issue:`52538`)
- Deprecated allowing ``downcast`` keyword other than ``None``, ``False``, "infer", or a dict with these as values in :meth:`Series.fillna`, :meth:`DataFrame.fillna` (:issue:`40988`)
+- Deprecated allowing arbitrary ``fill_value`` in :class:`SparseDtype`, in a future version the ``fill_value`` will need to be compatible with the ``dtype.subtype``, either a scalar that can be held by that subtype or ``NaN`` for integer or bool subtypes (:issue:`23124`)
- Deprecated constructing :class:`SparseArray` from scalar data, pass a sequence instead (:issue:`53039`)
-
diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py
index 5747ff807600d..f4f87f60cc3a7 100644
--- a/pandas/core/arrays/sparse/dtype.py
+++ b/pandas/core/arrays/sparse/dtype.py
@@ -18,6 +18,7 @@
ExtensionDtype,
register_extension_dtype,
)
+from pandas.core.dtypes.cast import can_hold_element
from pandas.core.dtypes.common import (
is_bool_dtype,
is_object_dtype,
@@ -25,11 +26,15 @@
is_string_dtype,
pandas_dtype,
)
+from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.missing import (
+ is_valid_na_for_dtype,
isna,
na_value_for_dtype,
)
+from pandas.core.construction import ensure_wrapped_if_datetimelike
+
if TYPE_CHECKING:
from pandas._typing import (
Dtype,
@@ -164,18 +169,41 @@ def _check_fill_value(self):
raise ValueError(
f"fill_value must be a scalar. Got {self._fill_value} instead"
)
- # TODO: Right now we can use Sparse boolean array
- # with any fill_value. Here was an attempt
- # to allow only 3 value: True, False or nan
- # but plenty test has failed.
- # see pull 44955
- # if self._is_boolean and not (
- # is_bool(self._fill_value) or isna(self._fill_value)
- # ):
- # raise ValueError(
- # "fill_value must be True, False or nan "
- # f"for boolean type. Got {self._fill_value} instead"
- # )
+
+ # GH#23124 require fill_value and subtype to match
+ val = self._fill_value
+ if isna(val):
+ if not is_valid_na_for_dtype(val, self.subtype):
+ warnings.warn(
+ "Allowing arbitrary scalar fill_value in SparseDtype is "
+ "deprecated. In a future version, the fill_value must be "
+ "a valid value for the SparseDtype.subtype.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ elif isinstance(self.subtype, CategoricalDtype):
+ # TODO: is this even supported? It is reached in
+ # test_dtype_sparse_with_fill_value_not_present_in_data
+ if self.subtype.categories is None or val not in self.subtype.categories:
+ warnings.warn(
+ "Allowing arbitrary scalar fill_value in SparseDtype is "
+ "deprecated. In a future version, the fill_value must be "
+ "a valid value for the SparseDtype.subtype.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ else:
+ dummy = np.empty(0, dtype=self.subtype)
+ dummy = ensure_wrapped_if_datetimelike(dummy)
+
+ if not can_hold_element(dummy, val):
+ warnings.warn(
+ "Allowing arbitrary scalar fill_value in SparseDtype is "
+ "deprecated. In a future version, the fill_value must be "
+ "a valid value for the SparseDtype.subtype.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
@property
def _is_na_fill_value(self) -> bool:
diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py
index 4a0795137f80b..b8effc3eff1d1 100644
--- a/pandas/tests/arrays/sparse/test_array.py
+++ b/pandas/tests/arrays/sparse/test_array.py
@@ -52,33 +52,21 @@ def test_set_fill_value(self):
arr.fill_value = 2
assert arr.fill_value == 2
- # TODO: this seems fine? You can construct an integer
- # sparsearray with NaN fill value, why not update one?
- # coerces to int
- # msg = "unable to set fill_value 3\\.1 to int64 dtype"
- # with pytest.raises(ValueError, match=msg):
- arr.fill_value = 3.1
+ msg = "Allowing arbitrary scalar fill_value in SparseDtype is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ arr.fill_value = 3.1
assert arr.fill_value == 3.1
- # msg = "unable to set fill_value nan to int64 dtype"
- # with pytest.raises(ValueError, match=msg):
arr.fill_value = np.nan
assert np.isnan(arr.fill_value)
arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool_)
arr.fill_value = True
- assert arr.fill_value
-
- # FIXME: don't leave commented-out
- # coerces to bool
- # TODO: we can construct an sparse array of bool
- # type and use as fill_value any value
- # msg = "fill_value must be True, False or nan"
- # with pytest.raises(ValueError, match=msg):
- # arr.fill_value = 0
-
- # msg = "unable to set fill_value nan to bool dtype"
- # with pytest.raises(ValueError, match=msg):
+ assert arr.fill_value is True
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ arr.fill_value = 0
+
arr.fill_value = np.nan
assert np.isnan(arr.fill_value)
diff --git a/pandas/tests/arrays/sparse/test_dtype.py b/pandas/tests/arrays/sparse/test_dtype.py
index 88f8577ded5b0..8337a79e10243 100644
--- a/pandas/tests/arrays/sparse/test_dtype.py
+++ b/pandas/tests/arrays/sparse/test_dtype.py
@@ -1,4 +1,5 @@
import re
+import warnings
import numpy as np
import pytest
@@ -67,15 +68,22 @@ def test_nans_equal():
assert b == a
-@pytest.mark.parametrize(
- "a, b",
- [
+with warnings.catch_warnings():
+ msg = "Allowing arbitrary scalar fill_value in SparseDtype is deprecated"
+ warnings.filterwarnings("ignore", msg, category=FutureWarning)
+
+ tups = [
(SparseDtype("float64"), SparseDtype("float32")),
(SparseDtype("float64"), SparseDtype("float64", 0)),
(SparseDtype("float64"), SparseDtype("datetime64[ns]", np.nan)),
(SparseDtype(int, pd.NaT), SparseDtype(float, pd.NaT)),
(SparseDtype("float64"), np.dtype("float64")),
- ],
+ ]
+
+
+@pytest.mark.parametrize(
+ "a, b",
+ tups,
)
def test_not_equal(a, b):
assert a != b
diff --git a/pandas/tests/reshape/test_get_dummies.py b/pandas/tests/reshape/test_get_dummies.py
index fab9b0a5d1846..6e943863072f1 100644
--- a/pandas/tests/reshape/test_get_dummies.py
+++ b/pandas/tests/reshape/test_get_dummies.py
@@ -57,7 +57,10 @@ def test_get_dummies_basic(self, sparse, dtype):
dtype=self.effective_dtype(dtype),
)
if sparse:
- expected = expected.apply(SparseArray, fill_value=0.0)
+ if dtype.kind == "b":
+ expected = expected.apply(SparseArray, fill_value=False)
+ else:
+ expected = expected.apply(SparseArray, fill_value=0.0)
result = get_dummies(s_list, sparse=sparse, dtype=dtype)
tm.assert_frame_equal(result, expected)
@@ -142,7 +145,10 @@ def test_get_dummies_include_na(self, sparse, dtype):
{"a": [1, 0, 0], "b": [0, 1, 0]}, dtype=self.effective_dtype(dtype)
)
if sparse:
- exp = exp.apply(SparseArray, fill_value=0.0)
+ if dtype.kind == "b":
+ exp = exp.apply(SparseArray, fill_value=False)
+ else:
+ exp = exp.apply(SparseArray, fill_value=0.0)
tm.assert_frame_equal(res, exp)
# Sparse dataframes do not allow nan labelled columns, see #GH8822
@@ -155,7 +161,10 @@ def test_get_dummies_include_na(self, sparse, dtype):
# hack (NaN handling in assert_index_equal)
exp_na.columns = res_na.columns
if sparse:
- exp_na = exp_na.apply(SparseArray, fill_value=0.0)
+ if dtype.kind == "b":
+ exp_na = exp_na.apply(SparseArray, fill_value=False)
+ else:
+ exp_na = exp_na.apply(SparseArray, fill_value=0.0)
tm.assert_frame_equal(res_na, exp_na)
res_just_na = get_dummies([np.nan], dummy_na=True, sparse=sparse, dtype=dtype)
@@ -174,7 +183,7 @@ def test_get_dummies_unicode(self, sparse):
{"letter_e": [True, False, False], f"letter_{eacute}": [False, True, True]}
)
if sparse:
- exp = exp.apply(SparseArray, fill_value=0)
+ exp = exp.apply(SparseArray, fill_value=False)
tm.assert_frame_equal(res, exp)
def test_dataframe_dummies_all_obj(self, df, sparse):
@@ -216,7 +225,10 @@ def test_dataframe_dummies_mix_default(self, df, sparse, dtype):
result = get_dummies(df, sparse=sparse, dtype=dtype)
if sparse:
arr = SparseArray
- typ = SparseDtype(dtype, 0)
+ if dtype.kind == "b":
+ typ = SparseDtype(dtype, False)
+ else:
+ typ = SparseDtype(dtype, 0)
else:
arr = np.array
typ = dtype
@@ -296,7 +308,7 @@ def test_dataframe_dummies_subset(self, df, sparse):
expected[["C"]] = df[["C"]]
if sparse:
cols = ["from_A_a", "from_A_b"]
- expected[cols] = expected[cols].astype(SparseDtype("bool", 0))
+ expected[cols] = expected[cols].astype(SparseDtype("bool", False))
tm.assert_frame_equal(result, expected)
def test_dataframe_dummies_prefix_sep(self, df, sparse):
@@ -314,7 +326,7 @@ def test_dataframe_dummies_prefix_sep(self, df, sparse):
expected = expected[["C", "A..a", "A..b", "B..b", "B..c"]]
if sparse:
cols = ["A..a", "A..b", "B..b", "B..c"]
- expected[cols] = expected[cols].astype(SparseDtype("bool", 0))
+ expected[cols] = expected[cols].astype(SparseDtype("bool", False))
tm.assert_frame_equal(result, expected)
@@ -359,7 +371,7 @@ def test_dataframe_dummies_prefix_dict(self, sparse):
columns = ["from_A_a", "from_A_b", "from_B_b", "from_B_c"]
expected[columns] = expected[columns].astype(bool)
if sparse:
- expected[columns] = expected[columns].astype(SparseDtype("bool", 0))
+ expected[columns] = expected[columns].astype(SparseDtype("bool", False))
tm.assert_frame_equal(result, expected)
@@ -371,7 +383,10 @@ def test_dataframe_dummies_with_na(self, df, sparse, dtype):
if sparse:
arr = SparseArray
- typ = SparseDtype(dtype, 0)
+ if dtype.kind == "b":
+ typ = SparseDtype(dtype, False)
+ else:
+ typ = SparseDtype(dtype, 0)
else:
arr = np.array
typ = dtype
@@ -399,7 +414,10 @@ def test_dataframe_dummies_with_categorical(self, df, sparse, dtype):
result = get_dummies(df, sparse=sparse, dtype=dtype).sort_index(axis=1)
if sparse:
arr = SparseArray
- typ = SparseDtype(dtype, 0)
+ if dtype.kind == "b":
+ typ = SparseDtype(dtype, False)
+ else:
+ typ = SparseDtype(dtype, 0)
else:
arr = np.array
typ = dtype
@@ -456,7 +474,7 @@ def test_get_dummies_basic_drop_first(self, sparse):
result = get_dummies(s_list, drop_first=True, sparse=sparse)
if sparse:
- expected = expected.apply(SparseArray, fill_value=0)
+ expected = expected.apply(SparseArray, fill_value=False)
tm.assert_frame_equal(result, expected)
result = get_dummies(s_series, drop_first=True, sparse=sparse)
@@ -490,7 +508,7 @@ def test_get_dummies_basic_drop_first_NA(self, sparse):
res = get_dummies(s_NA, drop_first=True, sparse=sparse)
exp = DataFrame({"b": [0, 1, 0]}, dtype=bool)
if sparse:
- exp = exp.apply(SparseArray, fill_value=0)
+ exp = exp.apply(SparseArray, fill_value=False)
tm.assert_frame_equal(res, exp)
@@ -499,7 +517,7 @@ def test_get_dummies_basic_drop_first_NA(self, sparse):
["b", np.nan], axis=1
)
if sparse:
- exp_na = exp_na.apply(SparseArray, fill_value=0)
+ exp_na = exp_na.apply(SparseArray, fill_value=False)
tm.assert_frame_equal(res_na, exp_na)
res_just_na = get_dummies(
@@ -513,7 +531,7 @@ def test_dataframe_dummies_drop_first(self, df, sparse):
result = get_dummies(df, drop_first=True, sparse=sparse)
expected = DataFrame({"A_b": [0, 1, 0], "B_c": [0, 0, 1]}, dtype=bool)
if sparse:
- expected = expected.apply(SparseArray, fill_value=0)
+ expected = expected.apply(SparseArray, fill_value=False)
tm.assert_frame_equal(result, expected)
def test_dataframe_dummies_drop_first_with_categorical(self, df, sparse, dtype):
@@ -632,7 +650,7 @@ def test_get_dummies_duplicate_columns(self, df):
def test_get_dummies_all_sparse(self):
df = DataFrame({"A": [1, 2]})
result = get_dummies(df, columns=["A"], sparse=True)
- dtype = SparseDtype("bool", 0)
+ dtype = SparseDtype("bool", False)
expected = DataFrame(
{
"A_1": SparseArray([1, 0], dtype=dtype),
| - [x] closes #23124 (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53043 | 2023-05-02T20:09:56Z | 2023-05-11T20:24:02Z | 2023-05-11T20:24:02Z | 2023-05-11T20:30:26Z |
REF: merge.py check for known arraylikes | diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 0c438a7b8eb7c..a96a08f18e81f 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -52,7 +52,6 @@
ensure_float64,
ensure_int64,
ensure_object,
- is_array_like,
is_bool,
is_bool_dtype,
is_extension_array_dtype,
@@ -124,6 +123,8 @@
np.object_: libhashtable.ObjectFactorizer,
}
+_known = (np.ndarray, ExtensionArray, Index, ABCSeries)
+
@Substitution("\nleft : DataFrame or named Series")
@Appender(_merge_doc, indents=0)
@@ -928,7 +929,7 @@ def _maybe_add_join_keys(
left_has_missing = None
right_has_missing = None
- assert all(is_array_like(x) for x in self.left_join_keys)
+ assert all(isinstance(x, _known) for x in self.left_join_keys)
keys = zip(self.join_names, self.left_on, self.right_on)
for i, (name, lname, rname) in enumerate(keys):
@@ -1141,8 +1142,8 @@ def _get_merge_keys(
left, right = self.left, self.right
- is_lkey = lambda x: is_array_like(x) and len(x) == len(left)
- is_rkey = lambda x: is_array_like(x) and len(x) == len(right)
+ is_lkey = lambda x: isinstance(x, _known) and len(x) == len(left)
+ is_rkey = lambda x: isinstance(x, _known) and len(x) == len(right)
# Note that pd.merge_asof() has separate 'on' and 'by' parameters. A
# user could, for example, request 'left_index' and 'left_by'. In a
@@ -1914,7 +1915,7 @@ def _validate_left_right_on(self, left_on, right_on):
# GH#29130 Check that merge keys do not have dtype object
if not self.left_index:
left_on_0 = left_on[0]
- if is_array_like(left_on_0):
+ if isinstance(left_on_0, _known):
lo_dtype = left_on_0.dtype
else:
lo_dtype = (
@@ -1927,7 +1928,7 @@ def _validate_left_right_on(self, left_on, right_on):
if not self.right_index:
right_on_0 = right_on[0]
- if is_array_like(right_on_0):
+ if isinstance(right_on_0, _known):
ro_dtype = right_on_0.dtype
else:
ro_dtype = (
| #48454 was going to do this as a deprecation, but before that got merged another PR accidentally made most weird-arraylikes raise (making it difficult to write a test for the deprecation). We agreed to wait a while to see if anyone complained about that, then to change over the checks explicitly. Among other things this will make the existing AnyArrayLike annotations in this file accurate. | https://api.github.com/repos/pandas-dev/pandas/pulls/53041 | 2023-05-02T16:10:44Z | 2023-05-04T17:41:27Z | 2023-05-04T17:41:27Z | 2023-05-04T17:43:47Z |
PERF: BaseMaskedArray._empty | diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index f1df86788ac44..7c30d53522ad9 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -132,6 +132,19 @@ def _from_sequence(cls, scalars, *, dtype=None, copy: bool = False) -> Self:
values, mask = cls._coerce_to_array(scalars, dtype=dtype, copy=copy)
return cls(values, mask)
+ @classmethod
+ @doc(ExtensionArray._empty)
+ def _empty(cls, shape: Shape, dtype: ExtensionDtype):
+ values = np.empty(shape, dtype=dtype.type)
+ values.fill(cls._internal_fill_value)
+ mask = np.ones(shape, dtype=bool)
+ result = cls(values, mask)
+ if not isinstance(result, cls) or dtype != result.dtype:
+ raise NotImplementedError(
+ f"Default 'empty' implementation is invalid for dtype='{dtype}'"
+ )
+ return result
+
@property
def dtype(self) -> BaseMaskedDtype:
raise AbstractMethodError(self)
diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index 7c05ec1ba33a9..f0e55aa178ec0 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -211,7 +211,7 @@ def construct_array_type(cls) -> type_t[ExtensionArray]:
"""
raise AbstractMethodError(cls)
- def empty(self, shape: Shape) -> type_t[ExtensionArray]:
+ def empty(self, shape: Shape) -> ExtensionArray:
"""
Construct an ExtensionArray of this dtype with the given shape.
| 10x improvement in this method (but small effect overall as this is typically a small part of total time cost). | https://api.github.com/repos/pandas-dev/pandas/pulls/53040 | 2023-05-02T16:10:17Z | 2023-05-02T19:40:55Z | 2023-05-02T19:40:54Z | 2023-05-02T21:02:23Z |
DEPR: SparseArray(scalar) | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 35f9f623bf8ef..2c655301e44ce 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -259,6 +259,8 @@ Deprecations
- Deprecated unused "closed" and "normalize" keywords in the :class:`DatetimeIndex` constructor (:issue:`52628`)
- Deprecated unused "closed" keyword in the :class:`TimedeltaIndex` constructor (:issue:`52628`)
- Deprecated logical operation between two non boolean :class:`Series` with different indexes always coercing the result to bool dtype. In a future version, this will maintain the return type of the inputs. (:issue:`52500`, :issue:`52538`)
+- Deprecated constructing :class:`SparseArray` from scalar data, pass a sequence instead (:issue:`53039`)
+-
.. ---------------------------------------------------------------------------
.. _whatsnew_210.performance:
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 512c0fb0c0ab2..d03e60131fd74 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -398,6 +398,12 @@ def __init__(
dtype = dtype.subtype
if is_scalar(data):
+ warnings.warn(
+ f"Constructing {type(self).__name__} with scalar data is deprecated "
+ "and will raise in a future version. Pass a sequence instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
if sparse_index is None:
npoints = 1
else:
diff --git a/pandas/tests/arrays/sparse/test_constructors.py b/pandas/tests/arrays/sparse/test_constructors.py
index 7c9d2977ffed8..29438b692fa72 100644
--- a/pandas/tests/arrays/sparse/test_constructors.py
+++ b/pandas/tests/arrays/sparse/test_constructors.py
@@ -145,13 +145,16 @@ def test_constructor_spindex_dtype(self):
@pytest.mark.parametrize("sparse_index", [None, IntIndex(1, [0])])
def test_constructor_spindex_dtype_scalar(self, sparse_index):
# scalar input
- arr = SparseArray(data=1, sparse_index=sparse_index, dtype=None)
+ msg = "Constructing SparseArray with scalar data is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ arr = SparseArray(data=1, sparse_index=sparse_index, dtype=None)
exp = SparseArray([1], dtype=None)
tm.assert_sp_array_equal(arr, exp)
assert arr.dtype == SparseDtype(np.int64)
assert arr.fill_value == 0
- arr = SparseArray(data=1, sparse_index=IntIndex(1, [0]), dtype=None)
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ arr = SparseArray(data=1, sparse_index=IntIndex(1, [0]), dtype=None)
exp = SparseArray([1], dtype=None)
tm.assert_sp_array_equal(arr, exp)
assert arr.dtype == SparseDtype(np.int64)
| - [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Better match all the other constructors. | https://api.github.com/repos/pandas-dev/pandas/pulls/53039 | 2023-05-02T15:55:41Z | 2023-05-02T19:41:37Z | 2023-05-02T19:41:37Z | 2023-05-02T19:42:44Z |
Backport PR #53001 on branch 2.0.x (BUG: Series.describe treating pyarrow timestamps/timedeltas as categorical) | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 3ee7031795d16..8322c8408a0e3 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -23,6 +23,7 @@ Bug fixes
- Bug in :func:`api.interchange.from_dataframe` was returning :class:`DataFrame`'s of incorrect sizes when called on slices (:issue:`52824`)
- Bug in :func:`api.interchange.from_dataframe` was unnecessarily raising on bitmasks (:issue:`49888`)
- Bug in :meth:`DataFrame.convert_dtypes` ignores ``convert_*`` keywords when set to False ``dtype_backend="pyarrow"`` (:issue:`52872`)
+- Bug in :meth:`Series.describe` treating pyarrow-backed timestamps and timedeltas as categorical data (:issue:`53001`)
- Bug in :meth:`pd.array` raising for ``NumPy`` array and ``pa.large_string`` or ``pa.large_binary`` (:issue:`52590`)
-
diff --git a/pandas/core/methods/describe.py b/pandas/core/methods/describe.py
index ef2cf8e96782d..ccd9ccfff808b 100644
--- a/pandas/core/methods/describe.py
+++ b/pandas/core/methods/describe.py
@@ -31,11 +31,10 @@
from pandas.core.dtypes.common import (
is_bool_dtype,
is_complex_dtype,
- is_datetime64_any_dtype,
is_extension_array_dtype,
is_numeric_dtype,
- is_timedelta64_dtype,
)
+from pandas.core.dtypes.dtypes import DatetimeTZDtype
from pandas.core.arrays.arrow.dtype import ArrowDtype
from pandas.core.arrays.floating import Float64Dtype
@@ -232,9 +231,13 @@ def describe_numeric_1d(series: Series, percentiles: Sequence[float]) -> Series:
dtype: DtypeObj | None
if is_extension_array_dtype(series):
if isinstance(series.dtype, ArrowDtype):
- import pyarrow as pa
+ if series.dtype.kind == "m":
+ # GH53001: describe timedeltas with object dtype
+ dtype = None
+ else:
+ import pyarrow as pa
- dtype = ArrowDtype(pa.float64())
+ dtype = ArrowDtype(pa.float64())
else:
dtype = Float64Dtype()
elif is_numeric_dtype(series) and not is_complex_dtype(series):
@@ -362,9 +365,9 @@ def select_describe_func(
return describe_categorical_1d
elif is_numeric_dtype(data):
return describe_numeric_1d
- elif is_datetime64_any_dtype(data.dtype):
+ elif data.dtype.kind == "M" or isinstance(data.dtype, DatetimeTZDtype):
return describe_timestamp_1d
- elif is_timedelta64_dtype(data.dtype):
+ elif data.dtype.kind == "m":
return describe_numeric_1d
else:
return describe_categorical_1d
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index fa21d861b4240..abad641819ed1 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -2658,6 +2658,36 @@ def test_describe_numeric_data(pa_type):
tm.assert_series_equal(result, expected)
+@pytest.mark.parametrize("pa_type", tm.TIMEDELTA_PYARROW_DTYPES)
+def test_describe_timedelta_data(pa_type):
+ # GH53001
+ data = pd.Series(range(1, 10), dtype=ArrowDtype(pa_type))
+ result = data.describe()
+ expected = pd.Series(
+ [9] + pd.to_timedelta([5, 2, 1, 3, 5, 7, 9], unit=pa_type.unit).tolist(),
+ dtype=object,
+ index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
+ )
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("pa_type", tm.DATETIME_PYARROW_DTYPES)
+def test_describe_datetime_data(pa_type):
+ # GH53001
+ data = pd.Series(range(1, 10), dtype=ArrowDtype(pa_type))
+ result = data.describe()
+ expected = pd.Series(
+ [9]
+ + [
+ pd.Timestamp(v, tz=pa_type.tz, unit=pa_type.unit)
+ for v in [5, 1, 3, 5, 7, 9]
+ ],
+ dtype=object,
+ index=["count", "mean", "min", "25%", "50%", "75%", "max"],
+ )
+ tm.assert_series_equal(result, expected)
+
+
@pytest.mark.xfail(
pa_version_under8p0,
reason="Function 'add_checked' has no kernel matching input types",
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/53031 | 2023-05-02T00:42:09Z | 2023-05-02T03:49:03Z | 2023-05-02T03:49:03Z | 2023-05-30T22:16:34Z |
DEPS: Unpin pydata-sphinx-theme | diff --git a/doc/source/conf.py b/doc/source/conf.py
index 6f7e770e5d554..66fca61c2c6e5 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -237,14 +237,14 @@
html_theme_options = {
"external_links": [],
- "footer_items": ["pandas_footer", "sphinx-version"],
+ "footer_start": ["pandas_footer", "sphinx-version"],
"github_url": "https://github.com/pandas-dev/pandas",
"twitter_url": "https://twitter.com/pandas_dev",
- "google_analytics_id": "UA-27880019-2",
+ "analytics": {"google_analytics_id": "UA-27880019-2"},
"logo": {"image_dark": "https://pandas.pydata.org/static/img/pandas_white.svg"},
"navbar_end": ["version-switcher", "theme-switcher", "navbar-icon-links"],
"switcher": {
- "json_url": "/versions.json",
+ "json_url": "https://pandas.pydata.org/versions.json",
"version_match": switcher_version,
},
"icon_links": [
diff --git a/doc/source/versions.json b/doc/source/versions.json
new file mode 100644
index 0000000000000..4be8f10a88334
--- /dev/null
+++ b/doc/source/versions.json
@@ -0,0 +1,42 @@
+[
+ {
+ "name": "dev",
+ "version": "dev",
+ "url": "https://pandas.pydata.org/docs/dev/"
+ },
+ {
+ "name": "2.0 (stable)",
+ "version": "2.0",
+ "url": "https://pandas.pydata.org/docs/"
+ },
+ {
+ "name": "1.5",
+ "version": "1.5",
+ "url": "https://pandas.pydata.org/pandas-docs/version/1.5/"
+ },
+ {
+ "name": "1.4",
+ "version": "1.4",
+ "url": "https://pandas.pydata.org/pandas-docs/version/1.4/"
+ },
+ {
+ "name": "1.3",
+ "version": "1.3",
+ "url": "https://pandas.pydata.org/pandas-docs/version/1.3/"
+ },
+ {
+ "name": "1.2",
+ "version": "1.2",
+ "url": "https://pandas.pydata.org/pandas-docs/version/1.2/"
+ },
+ {
+ "name": "1.1",
+ "version": "1.1",
+ "url": "https://pandas.pydata.org/pandas-docs/version/1.1/"
+ },
+ {
+ "name": "1.0",
+ "version": "1.0",
+ "url": "https://pandas.pydata.org/pandas-docs/version/1.0/"
+ }
+]
diff --git a/environment.yml b/environment.yml
index 90ed7634ec74b..fb8321a9fb6a7 100644
--- a/environment.yml
+++ b/environment.yml
@@ -89,7 +89,7 @@ dependencies:
- gitdb
- natsort # DataFrame.sort_values doctest
- numpydoc
- - pydata-sphinx-theme<0.11
+ - pydata-sphinx-theme
- pytest-cython # doctest
- sphinx
- sphinx-design
diff --git a/requirements-dev.txt b/requirements-dev.txt
index d3054ee34a1f4..546116b1fa23d 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -64,7 +64,7 @@ gitpython
gitdb
natsort
numpydoc
-pydata-sphinx-theme<0.11
+pydata-sphinx-theme
pytest-cython
sphinx
sphinx-design
diff --git a/web/pandas/versions.json b/web/pandas/versions.json
deleted file mode 100644
index 81021e5a7c72f..0000000000000
--- a/web/pandas/versions.json
+++ /dev/null
@@ -1,42 +0,0 @@
-[
- {
- "name": "dev",
- "version": "docs/dev",
- "url": "/docs/dev/"
- },
- {
- "name": "2.0 (stable)",
- "version": "docs",
- "url": "/docs/"
- },
- {
- "name": "1.5",
- "version": "pandas-docs/version/1.5",
- "url": "/pandas-docs/version/1.5/"
- },
- {
- "name": "1.4",
- "version": "pandas-docs/version/1.4",
- "url": "/pandas-docs/version/1.4/"
- },
- {
- "name": "1.3",
- "version": "pandas-docs/version/1.3",
- "url": "/pandas-docs/version/1.3/"
- },
- {
- "name": "1.2",
- "version": "pandas-docs/version/1.2",
- "url": "/pandas-docs/version/1.2/"
- },
- {
- "name": "1.1",
- "version": "pandas-docs/version/1.1",
- "url": "/pandas-docs/version/1.1/"
- },
- {
- "name": "1.0",
- "version": "pandas-docs/version/1.0",
- "url": "/pandas-docs/version/1.0/"
- }
-]
| - [ ] closes #48988 (Replace xxxx with the GitHub issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
closes #53167 | https://api.github.com/repos/pandas-dev/pandas/pulls/53029 | 2023-05-01T23:49:00Z | 2023-05-11T01:04:35Z | 2023-05-11T01:04:35Z | 2023-05-11T01:04:38Z |
ENH: Support multiple opening hours intervals for BusinessHour | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index da939687500b6..b647b8cff2058 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -158,6 +158,7 @@ Other enhancements
- :meth:`DataFrame.describe` now formats integer percentiles without decimal point (:issue:`26660`)
- Added support for reading SPSS .sav files using :func:`read_spss` (:issue:`26537`)
- Added new option ``plotting.backend`` to be able to select a plotting backend different than the existing ``matplotlib`` one. Use ``pandas.set_option('plotting.backend', '<backend-module>')`` where ``<backend-module`` is a library implementing the pandas plotting API (:issue:`14130`)
+- :class:`pandas.offsets.BusinessHour` supports multiple opening hours intervals (:issue:`15481`)
.. _whatsnew_0250.api_breaking:
diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py
index 5683924ee1283..c0021b1eade78 100644
--- a/pandas/tests/tseries/offsets/test_offsets.py
+++ b/pandas/tests/tseries/offsets/test_offsets.py
@@ -1,4 +1,4 @@
-from datetime import date, datetime, timedelta
+from datetime import date, datetime, time as dt_time, timedelta
import numpy as np
import pytest
@@ -759,15 +759,66 @@ def setup_method(self, method):
self.offset6 = BusinessHour(start='20:00', end='05:00')
self.offset7 = BusinessHour(n=-2, start=dt_time(21, 30),
end=dt_time(6, 30))
-
- def test_constructor_errors(self):
- from datetime import time as dt_time
- with pytest.raises(ValueError):
- BusinessHour(start=dt_time(11, 0, 5))
- with pytest.raises(ValueError):
- BusinessHour(start='AAA')
- with pytest.raises(ValueError):
- BusinessHour(start='14:00:05')
+ self.offset8 = BusinessHour(start=['09:00', '13:00'],
+ end=['12:00', '17:00'])
+ self.offset9 = BusinessHour(n=3, start=['09:00', '22:00'],
+ end=['13:00', '03:00'])
+ self.offset10 = BusinessHour(n=-1, start=['23:00', '13:00'],
+ end=['02:00', '17:00'])
+
+ @pytest.mark.parametrize("start,end,match", [
+ (
+ dt_time(11, 0, 5),
+ '17:00',
+ "time data must be specified only with hour and minute"
+ ),
+ (
+ 'AAA',
+ '17:00',
+ "time data must match '%H:%M' format"
+ ),
+ (
+ '14:00:05',
+ '17:00',
+ "time data must match '%H:%M' format"
+ ),
+ (
+ [],
+ '17:00',
+ "Must include at least 1 start time"
+ ),
+ (
+ '09:00',
+ [],
+ "Must include at least 1 end time"
+ ),
+ (
+ ['09:00', '11:00'],
+ '17:00',
+ "number of starting time and ending time must be the same"
+ ),
+ (
+ ['09:00', '11:00'],
+ ['10:00'],
+ "number of starting time and ending time must be the same"
+ ),
+ (
+ ['09:00', '11:00'],
+ ['12:00', '20:00'],
+ r"invalid starting and ending time\(s\): opening hours should not "
+ "touch or overlap with one another"
+ ),
+ (
+ ['12:00', '20:00'],
+ ['09:00', '11:00'],
+ r"invalid starting and ending time\(s\): opening hours should not "
+ "touch or overlap with one another"
+ ),
+ ])
+ def test_constructor_errors(self, start, end, match):
+ with pytest.raises(ValueError,
+ match=match):
+ BusinessHour(start=start, end=end)
def test_different_normalize_equals(self):
# GH#21404 changed __eq__ to return False when `normalize` doesnt match
@@ -784,6 +835,12 @@ def test_repr(self):
assert repr(self.offset5) == '<BusinessHour: BH=11:00-14:30>'
assert repr(self.offset6) == '<BusinessHour: BH=20:00-05:00>'
assert repr(self.offset7) == '<-2 * BusinessHours: BH=21:30-06:30>'
+ assert (repr(self.offset8) ==
+ '<BusinessHour: BH=09:00-12:00,13:00-17:00>')
+ assert (repr(self.offset9) ==
+ '<3 * BusinessHours: BH=09:00-13:00,22:00-03:00>')
+ assert (repr(self.offset10) ==
+ '<-1 * BusinessHour: BH=13:00-17:00,23:00-02:00>')
def test_with_offset(self):
expected = Timestamp('2014-07-01 13:00')
@@ -791,25 +848,59 @@ def test_with_offset(self):
assert self.d + BusinessHour() * 3 == expected
assert self.d + BusinessHour(n=3) == expected
- def test_eq(self):
- for offset in [self.offset1, self.offset2, self.offset3, self.offset4]:
- assert offset == offset
+ @pytest.mark.parametrize("offset_name", [
+ "offset1",
+ "offset2",
+ "offset3",
+ "offset4",
+ "offset8",
+ "offset9",
+ "offset10"
+ ])
+ def test_eq_attribute(self, offset_name):
+ offset = getattr(self, offset_name)
+ assert offset == offset
+
+ @pytest.mark.parametrize("offset1,offset2", [
+ (BusinessHour(start='09:00'), BusinessHour()),
+ (BusinessHour(start=['23:00', '13:00'], end=['12:00', '17:00']),
+ BusinessHour(start=['13:00', '23:00'], end=['17:00', '12:00'])),
+ ])
+ def test_eq(self, offset1, offset2):
+ assert offset1 == offset2
- assert BusinessHour() != BusinessHour(-1)
- assert BusinessHour(start='09:00') == BusinessHour()
- assert BusinessHour(start='09:00') != BusinessHour(start='09:01')
- assert (BusinessHour(start='09:00', end='17:00') !=
- BusinessHour(start='17:00', end='09:01'))
+ @pytest.mark.parametrize("offset1,offset2", [
+ (BusinessHour(), BusinessHour(-1)),
+ (BusinessHour(start='09:00'), BusinessHour(start='09:01')),
+ (BusinessHour(start='09:00', end='17:00'),
+ BusinessHour(start='17:00', end='09:01')),
+ (BusinessHour(start=['13:00', '23:00'], end=['18:00', '07:00']),
+ BusinessHour(start=['13:00', '23:00'], end=['17:00', '12:00'])),
+ ])
+ def test_neq(self, offset1, offset2):
+ assert offset1 != offset2
- def test_hash(self):
- for offset in [self.offset1, self.offset2, self.offset3, self.offset4]:
- assert hash(offset) == hash(offset)
+ @pytest.mark.parametrize("offset_name", [
+ "offset1",
+ "offset2",
+ "offset3",
+ "offset4",
+ "offset8",
+ "offset9",
+ "offset10"
+ ])
+ def test_hash(self, offset_name):
+ offset = getattr(self, offset_name)
+ assert offset == offset
def test_call(self):
assert self.offset1(self.d) == datetime(2014, 7, 1, 11)
assert self.offset2(self.d) == datetime(2014, 7, 1, 13)
assert self.offset3(self.d) == datetime(2014, 6, 30, 17)
assert self.offset4(self.d) == datetime(2014, 6, 30, 14)
+ assert self.offset8(self.d) == datetime(2014, 7, 1, 11)
+ assert self.offset9(self.d) == datetime(2014, 7, 1, 22)
+ assert self.offset10(self.d) == datetime(2014, 7, 1, 1)
def test_sub(self):
# we have to override test_sub here because self.offset2 is not
@@ -830,6 +921,9 @@ def testRollback1(self):
assert self.offset5.rollback(self.d) == datetime(2014, 6, 30, 14, 30)
assert self.offset6.rollback(self.d) == datetime(2014, 7, 1, 5, 0)
assert self.offset7.rollback(self.d) == datetime(2014, 7, 1, 6, 30)
+ assert self.offset8.rollback(self.d) == self.d
+ assert self.offset9.rollback(self.d) == self.d
+ assert self.offset10.rollback(self.d) == datetime(2014, 7, 1, 2)
d = datetime(2014, 7, 1, 0)
assert self.offset1.rollback(d) == datetime(2014, 6, 30, 17)
@@ -839,6 +933,9 @@ def testRollback1(self):
assert self.offset5.rollback(d) == datetime(2014, 6, 30, 14, 30)
assert self.offset6.rollback(d) == d
assert self.offset7.rollback(d) == d
+ assert self.offset8.rollback(d) == datetime(2014, 6, 30, 17)
+ assert self.offset9.rollback(d) == d
+ assert self.offset10.rollback(d) == d
assert self._offset(5).rollback(self.d) == self.d
@@ -857,6 +954,9 @@ def testRollforward1(self):
datetime(2014, 7, 1, 20, 0))
assert (self.offset7.rollforward(self.d) ==
datetime(2014, 7, 1, 21, 30))
+ assert self.offset8.rollforward(self.d) == self.d
+ assert self.offset9.rollforward(self.d) == self.d
+ assert self.offset10.rollforward(self.d) == datetime(2014, 7, 1, 13)
d = datetime(2014, 7, 1, 0)
assert self.offset1.rollforward(d) == datetime(2014, 7, 1, 9)
@@ -866,6 +966,9 @@ def testRollforward1(self):
assert self.offset5.rollforward(d) == datetime(2014, 7, 1, 11)
assert self.offset6.rollforward(d) == d
assert self.offset7.rollforward(d) == d
+ assert self.offset8.rollforward(d) == datetime(2014, 7, 1, 9)
+ assert self.offset9.rollforward(d) == d
+ assert self.offset10.rollforward(d) == d
assert self._offset(5).rollforward(self.d) == self.d
@@ -960,6 +1063,35 @@ def test_normalize(self, case):
datetime(2014, 7, 6, 23, 0): False,
datetime(2014, 7, 7, 3, 0): False}))
+ on_offset_cases.append((BusinessHour(start=['09:00', '13:00'],
+ end=['12:00', '17:00']), {
+ datetime(2014, 7, 1, 9): True,
+ datetime(2014, 7, 1, 8, 59): False,
+ datetime(2014, 7, 1, 8): False,
+ datetime(2014, 7, 1, 17): True,
+ datetime(2014, 7, 1, 17, 1): False,
+ datetime(2014, 7, 1, 18): False,
+ datetime(2014, 7, 5, 9): False,
+ datetime(2014, 7, 6, 12): False,
+ datetime(2014, 7, 1, 12, 30): False}))
+
+ on_offset_cases.append((BusinessHour(start=['19:00', '23:00'],
+ end=['21:00', '05:00']), {
+ datetime(2014, 7, 1, 9, 0): False,
+ datetime(2014, 7, 1, 10, 0): False,
+ datetime(2014, 7, 1, 15): False,
+ datetime(2014, 7, 1, 15, 1): False,
+ datetime(2014, 7, 5, 12, 0): False,
+ datetime(2014, 7, 6, 12, 0): False,
+ datetime(2014, 7, 1, 19, 0): True,
+ datetime(2014, 7, 2, 0, 0): True,
+ datetime(2014, 7, 4, 23): True,
+ datetime(2014, 7, 5, 1): True,
+ datetime(2014, 7, 5, 5, 0): True,
+ datetime(2014, 7, 6, 23, 0): False,
+ datetime(2014, 7, 7, 3, 0): False,
+ datetime(2014, 7, 4, 22): False}))
+
@pytest.mark.parametrize('case', on_offset_cases)
def test_onOffset(self, case):
offset, cases = case
@@ -1125,6 +1257,76 @@ def test_onOffset(self, case):
datetime(2014, 7, 7, 18): (datetime(2014, 7, 7, 17),
datetime(2014, 7, 8, 17))}))
+ opening_time_cases.append(([BusinessHour(start=['11:15', '15:00'],
+ end=['13:00', '20:00']),
+ BusinessHour(n=3, start=['11:15', '15:00'],
+ end=['12:00', '20:00']),
+ BusinessHour(start=['11:15', '15:00'],
+ end=['13:00', '17:00']),
+ BusinessHour(n=2, start=['11:15', '15:00'],
+ end=['12:00', '03:00']),
+ BusinessHour(n=3, start=['11:15', '15:00'],
+ end=['13:00', '16:00'])], {
+ datetime(2014, 7, 1, 11): (datetime(2014, 7, 1, 11, 15),
+ datetime(2014, 6, 30, 15)),
+ datetime(2014, 7, 1, 18): (datetime(2014, 7, 2, 11, 15),
+ datetime(2014, 7, 1, 15)),
+ datetime(2014, 7, 1, 23): (datetime(2014, 7, 2, 11, 15),
+ datetime(2014, 7, 1, 15)),
+ datetime(2014, 7, 2, 8): (datetime(2014, 7, 2, 11, 15),
+ datetime(2014, 7, 1, 15)),
+ datetime(2014, 7, 2, 9): (datetime(2014, 7, 2, 11, 15),
+ datetime(2014, 7, 1, 15)),
+ datetime(2014, 7, 2, 10): (datetime(2014, 7, 2, 11, 15),
+ datetime(2014, 7, 1, 15)),
+ datetime(2014, 7, 2, 11, 15): (datetime(2014, 7, 2, 11, 15),
+ datetime(2014, 7, 2, 11, 15)),
+ datetime(2014, 7, 2, 11, 15, 1): (datetime(2014, 7, 2, 15),
+ datetime(2014, 7, 2, 11, 15)),
+ datetime(2014, 7, 5, 10): (datetime(2014, 7, 7, 11, 15),
+ datetime(2014, 7, 4, 15)),
+ datetime(2014, 7, 4, 10): (datetime(2014, 7, 4, 11, 15),
+ datetime(2014, 7, 3, 15)),
+ datetime(2014, 7, 4, 23): (datetime(2014, 7, 7, 11, 15),
+ datetime(2014, 7, 4, 15)),
+ datetime(2014, 7, 6, 10): (datetime(2014, 7, 7, 11, 15),
+ datetime(2014, 7, 4, 15)),
+ datetime(2014, 7, 7, 5): (datetime(2014, 7, 7, 11, 15),
+ datetime(2014, 7, 4, 15)),
+ datetime(2014, 7, 7, 9, 1): (datetime(2014, 7, 7, 11, 15),
+ datetime(2014, 7, 4, 15)),
+ datetime(2014, 7, 7, 12): (datetime(2014, 7, 7, 15),
+ datetime(2014, 7, 7, 11, 15))}))
+
+ opening_time_cases.append(([BusinessHour(n=-1, start=['17:00', '08:00'],
+ end=['05:00', '10:00']),
+ BusinessHour(n=-2, start=['08:00', '17:00'],
+ end=['10:00', '03:00'])], {
+ datetime(2014, 7, 1, 11): (datetime(2014, 7, 1, 8),
+ datetime(2014, 7, 1, 17)),
+ datetime(2014, 7, 1, 18): (datetime(2014, 7, 1, 17),
+ datetime(2014, 7, 2, 8)),
+ datetime(2014, 7, 1, 23): (datetime(2014, 7, 1, 17),
+ datetime(2014, 7, 2, 8)),
+ datetime(2014, 7, 2, 8): (datetime(2014, 7, 2, 8),
+ datetime(2014, 7, 2, 8)),
+ datetime(2014, 7, 2, 9): (datetime(2014, 7, 2, 8),
+ datetime(2014, 7, 2, 17)),
+ datetime(2014, 7, 2, 16, 59): (datetime(2014, 7, 2, 8),
+ datetime(2014, 7, 2, 17)),
+ datetime(2014, 7, 5, 10): (datetime(2014, 7, 4, 17),
+ datetime(2014, 7, 7, 8)),
+ datetime(2014, 7, 4, 10): (datetime(2014, 7, 4, 8),
+ datetime(2014, 7, 4, 17)),
+ datetime(2014, 7, 4, 23): (datetime(2014, 7, 4, 17),
+ datetime(2014, 7, 7, 8)),
+ datetime(2014, 7, 6, 10): (datetime(2014, 7, 4, 17),
+ datetime(2014, 7, 7, 8)),
+ datetime(2014, 7, 7, 5): (datetime(2014, 7, 4, 17),
+ datetime(2014, 7, 7, 8)),
+ datetime(2014, 7, 7, 18): (datetime(2014, 7, 7, 17),
+ datetime(2014, 7, 8, 8))}))
+
@pytest.mark.parametrize('case', opening_time_cases)
def test_opening_time(self, case):
_offsets, cases = case
@@ -1303,6 +1505,81 @@ def test_opening_time(self, case):
datetime(2014, 7, 7, 3, 30, 30): datetime(2014, 7, 4, 22, 30, 30),
datetime(2014, 7, 7, 3, 30, 20): datetime(2014, 7, 4, 22, 30, 20)}))
+ # multiple business hours
+ apply_cases.append((BusinessHour(start=['09:00', '14:00'],
+ end=['12:00', '18:00']), {
+ datetime(2014, 7, 1, 11): datetime(2014, 7, 1, 14),
+ datetime(2014, 7, 1, 15): datetime(2014, 7, 1, 16),
+ datetime(2014, 7, 1, 19): datetime(2014, 7, 2, 10),
+ datetime(2014, 7, 1, 16): datetime(2014, 7, 1, 17),
+ datetime(2014, 7, 1, 16, 30, 15): datetime(2014, 7, 1, 17, 30, 15),
+ datetime(2014, 7, 1, 17): datetime(2014, 7, 2, 9),
+ datetime(2014, 7, 2, 11): datetime(2014, 7, 2, 14),
+ # out of business hours
+ datetime(2014, 7, 1, 13): datetime(2014, 7, 1, 15),
+ datetime(2014, 7, 2, 8): datetime(2014, 7, 2, 10),
+ datetime(2014, 7, 2, 19): datetime(2014, 7, 3, 10),
+ datetime(2014, 7, 2, 23): datetime(2014, 7, 3, 10),
+ datetime(2014, 7, 3, 0): datetime(2014, 7, 3, 10),
+ # saturday
+ datetime(2014, 7, 5, 15): datetime(2014, 7, 7, 10),
+ datetime(2014, 7, 4, 17): datetime(2014, 7, 7, 9),
+ datetime(2014, 7, 4, 17, 30): datetime(2014, 7, 7, 9, 30),
+ datetime(2014, 7, 4, 17, 30, 30): datetime(2014, 7, 7, 9, 30, 30)}))
+
+ apply_cases.append((BusinessHour(n=4, start=['09:00', '14:00'],
+ end=['12:00', '18:00']), {
+ datetime(2014, 7, 1, 11): datetime(2014, 7, 1, 17),
+ datetime(2014, 7, 1, 13): datetime(2014, 7, 2, 9),
+ datetime(2014, 7, 1, 15): datetime(2014, 7, 2, 10),
+ datetime(2014, 7, 1, 16): datetime(2014, 7, 2, 11),
+ datetime(2014, 7, 1, 17): datetime(2014, 7, 2, 14),
+ datetime(2014, 7, 2, 11): datetime(2014, 7, 2, 17),
+ datetime(2014, 7, 2, 8): datetime(2014, 7, 2, 15),
+ datetime(2014, 7, 2, 19): datetime(2014, 7, 3, 15),
+ datetime(2014, 7, 2, 23): datetime(2014, 7, 3, 15),
+ datetime(2014, 7, 3, 0): datetime(2014, 7, 3, 15),
+ datetime(2014, 7, 5, 15): datetime(2014, 7, 7, 15),
+ datetime(2014, 7, 4, 17): datetime(2014, 7, 7, 14),
+ datetime(2014, 7, 4, 16, 30): datetime(2014, 7, 7, 11, 30),
+ datetime(2014, 7, 4, 16, 30, 30): datetime(2014, 7, 7, 11, 30, 30)}))
+
+ apply_cases.append((BusinessHour(n=-4, start=['09:00', '14:00'],
+ end=['12:00', '18:00']), {
+ datetime(2014, 7, 1, 11): datetime(2014, 6, 30, 16),
+ datetime(2014, 7, 1, 13): datetime(2014, 6, 30, 17),
+ datetime(2014, 7, 1, 15): datetime(2014, 6, 30, 18),
+ datetime(2014, 7, 1, 16): datetime(2014, 7, 1, 10),
+ datetime(2014, 7, 1, 17): datetime(2014, 7, 1, 11),
+ datetime(2014, 7, 2, 11): datetime(2014, 7, 1, 16),
+ datetime(2014, 7, 2, 8): datetime(2014, 7, 1, 12),
+ datetime(2014, 7, 2, 19): datetime(2014, 7, 2, 12),
+ datetime(2014, 7, 2, 23): datetime(2014, 7, 2, 12),
+ datetime(2014, 7, 3, 0): datetime(2014, 7, 2, 12),
+ datetime(2014, 7, 5, 15): datetime(2014, 7, 4, 12),
+ datetime(2014, 7, 4, 18): datetime(2014, 7, 4, 12),
+ datetime(2014, 7, 7, 9, 30): datetime(2014, 7, 4, 14, 30),
+ datetime(2014, 7, 7, 9, 30, 30): datetime(2014, 7, 4, 14, 30, 30)}))
+
+ apply_cases.append((BusinessHour(n=-1, start=['19:00', '03:00'],
+ end=['01:00', '05:00']), {
+ datetime(2014, 7, 1, 17): datetime(2014, 7, 1, 4),
+ datetime(2014, 7, 2, 14): datetime(2014, 7, 2, 4),
+ datetime(2014, 7, 2, 8): datetime(2014, 7, 2, 4),
+ datetime(2014, 7, 2, 13): datetime(2014, 7, 2, 4),
+ datetime(2014, 7, 2, 20): datetime(2014, 7, 2, 5),
+ datetime(2014, 7, 2, 19): datetime(2014, 7, 2, 4),
+ datetime(2014, 7, 2, 4): datetime(2014, 7, 2, 1),
+ datetime(2014, 7, 2, 19, 30): datetime(2014, 7, 2, 4, 30),
+ datetime(2014, 7, 3, 0): datetime(2014, 7, 2, 23),
+ datetime(2014, 7, 3, 6): datetime(2014, 7, 3, 4),
+ datetime(2014, 7, 4, 23): datetime(2014, 7, 4, 22),
+ datetime(2014, 7, 5, 0): datetime(2014, 7, 4, 23),
+ datetime(2014, 7, 5, 4): datetime(2014, 7, 5, 0),
+ datetime(2014, 7, 7, 3, 30): datetime(2014, 7, 5, 0, 30),
+ datetime(2014, 7, 7, 19, 30): datetime(2014, 7, 7, 4, 30),
+ datetime(2014, 7, 7, 19, 30, 30): datetime(2014, 7, 7, 4, 30, 30)}))
+
@pytest.mark.parametrize('case', apply_cases)
def test_apply(self, case):
offset, cases = case
@@ -1359,6 +1636,42 @@ def test_apply(self, case):
datetime(2014, 7, 7, 1): datetime(2014, 7, 15, 0),
datetime(2014, 7, 7, 23, 30): datetime(2014, 7, 15, 21, 30)}))
+ # large n for multiple opening hours (3 days and 1 hour before)
+ apply_large_n_cases.append((BusinessHour(n=-25, start=['09:00', '14:00'],
+ end=['12:00', '19:00']), {
+ datetime(2014, 7, 1, 11): datetime(2014, 6, 26, 10),
+ datetime(2014, 7, 1, 13): datetime(2014, 6, 26, 11),
+ datetime(2014, 7, 1, 9): datetime(2014, 6, 25, 18),
+ datetime(2014, 7, 1, 10): datetime(2014, 6, 25, 19),
+ datetime(2014, 7, 3, 11): datetime(2014, 6, 30, 10),
+ datetime(2014, 7, 3, 8): datetime(2014, 6, 27, 18),
+ datetime(2014, 7, 3, 19): datetime(2014, 6, 30, 18),
+ datetime(2014, 7, 3, 23): datetime(2014, 6, 30, 18),
+ datetime(2014, 7, 4, 9): datetime(2014, 6, 30, 18),
+ datetime(2014, 7, 5, 15): datetime(2014, 7, 1, 18),
+ datetime(2014, 7, 6, 18): datetime(2014, 7, 1, 18),
+ datetime(2014, 7, 7, 9, 30): datetime(2014, 7, 1, 18, 30),
+ datetime(2014, 7, 7, 10, 30, 30): datetime(2014, 7, 2, 9, 30, 30)}))
+
+ # 5 days and 3 hours later
+ apply_large_n_cases.append((BusinessHour(28, start=['21:00', '03:00'],
+ end=['01:00', '04:00']), {
+ datetime(2014, 7, 1, 11): datetime(2014, 7, 9, 0),
+ datetime(2014, 7, 1, 22): datetime(2014, 7, 9, 3),
+ datetime(2014, 7, 1, 23): datetime(2014, 7, 9, 21),
+ datetime(2014, 7, 2, 2): datetime(2014, 7, 9, 23),
+ datetime(2014, 7, 3, 21): datetime(2014, 7, 11, 0),
+ datetime(2014, 7, 4, 1): datetime(2014, 7, 11, 23),
+ datetime(2014, 7, 4, 2): datetime(2014, 7, 11, 23),
+ datetime(2014, 7, 4, 3): datetime(2014, 7, 11, 23),
+ datetime(2014, 7, 4, 21): datetime(2014, 7, 12, 0),
+ datetime(2014, 7, 5, 0): datetime(2014, 7, 14, 22),
+ datetime(2014, 7, 5, 1): datetime(2014, 7, 14, 23),
+ datetime(2014, 7, 5, 15): datetime(2014, 7, 14, 23),
+ datetime(2014, 7, 6, 18): datetime(2014, 7, 14, 23),
+ datetime(2014, 7, 7, 1): datetime(2014, 7, 14, 23),
+ datetime(2014, 7, 7, 23, 30): datetime(2014, 7, 15, 21, 30)}))
+
@pytest.mark.parametrize('case', apply_large_n_cases)
def test_apply_large_n(self, case):
offset, cases = case
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index ac20ad1669638..087c05574090c 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -17,6 +17,7 @@
from pandas.util._decorators import Appender, Substitution, cache_readonly
from pandas.core.dtypes.generic import ABCPeriod
+from pandas.core.dtypes.inference import is_list_like
from pandas.core.tools.datetimes import to_datetime
@@ -581,9 +582,44 @@ class BusinessHourMixin(BusinessMixin):
def __init__(self, start='09:00', end='17:00', offset=timedelta(0)):
# must be validated here to equality check
- start = liboffsets._validate_business_time(start)
+ if not is_list_like(start):
+ start = [start]
+ if not len(start):
+ raise ValueError('Must include at least 1 start time')
+
+ if not is_list_like(end):
+ end = [end]
+ if not len(end):
+ raise ValueError('Must include at least 1 end time')
+
+ start = np.array([liboffsets._validate_business_time(x)
+ for x in start])
+ end = np.array([liboffsets._validate_business_time(x) for x in end])
+
+ # Validation of input
+ if len(start) != len(end):
+ raise ValueError('number of starting time and ending time '
+ 'must be the same')
+ num_openings = len(start)
+
+ # sort starting and ending time by starting time
+ index = np.argsort(start)
+
+ # convert to tuple so that start and end are hashable
+ start = tuple(start[index])
+ end = tuple(end[index])
+
+ total_secs = 0
+ for i in range(num_openings):
+ total_secs += self._get_business_hours_by_sec(start[i], end[i])
+ total_secs += self._get_business_hours_by_sec(
+ end[i], start[(i + 1) % num_openings])
+ if total_secs != 24 * 60 * 60:
+ raise ValueError('invalid starting and ending time(s): '
+ 'opening hours should not touch or overlap with '
+ 'one another')
+
object.__setattr__(self, "start", start)
- end = liboffsets._validate_business_time(end)
object.__setattr__(self, "end", end)
object.__setattr__(self, "_offset", offset)
@@ -605,62 +641,93 @@ def next_bday(self):
else:
return BusinessDay(n=nb_offset)
- @cache_readonly
- def _get_daytime_flag(self):
- if self.start == self.end:
- raise ValueError('start and end must not be the same')
- elif self.start < self.end:
- return True
- else:
- return False
-
- def _next_opening_time(self, other):
+ def _next_opening_time(self, other, sign=1):
"""
- If n is positive, return tomorrow's business day opening time.
- Otherwise yesterday's business day's opening time.
+ If self.n and sign have the same sign, return the earliest opening time
+ later than or equal to current time.
+ Otherwise the latest opening time earlier than or equal to current
+ time.
Opening time always locates on BusinessDay.
- Otherwise, closing time may not if business hour extends over midnight.
+ However, closing time may not if business hour extends over midnight.
+
+ Parameters
+ ----------
+ other : datetime
+ Current time.
+ sign : int, default 1.
+ Either 1 or -1. Going forward in time if it has the same sign as
+ self.n. Going backward in time otherwise.
+
+ Returns
+ -------
+ result : datetime
+ Next opening time.
"""
+ earliest_start = self.start[0]
+ latest_start = self.start[-1]
+
if not self.next_bday.onOffset(other):
- other = other + self.next_bday
+ # today is not business day
+ other = other + sign * self.next_bday
+ if self.n * sign >= 0:
+ hour, minute = earliest_start.hour, earliest_start.minute
+ else:
+ hour, minute = latest_start.hour, latest_start.minute
else:
- if self.n >= 0 and self.start < other.time():
- other = other + self.next_bday
- elif self.n < 0 and other.time() < self.start:
- other = other + self.next_bday
- return datetime(other.year, other.month, other.day,
- self.start.hour, self.start.minute)
+ if self.n * sign >= 0:
+ if latest_start < other.time():
+ # current time is after latest starting time in today
+ other = other + sign * self.next_bday
+ hour, minute = earliest_start.hour, earliest_start.minute
+ else:
+ # find earliest starting time no earlier than current time
+ for st in self.start:
+ if other.time() <= st:
+ hour, minute = st.hour, st.minute
+ break
+ else:
+ if other.time() < earliest_start:
+ # current time is before earliest starting time in today
+ other = other + sign * self.next_bday
+ hour, minute = latest_start.hour, latest_start.minute
+ else:
+ # find latest starting time no later than current time
+ for st in reversed(self.start):
+ if other.time() >= st:
+ hour, minute = st.hour, st.minute
+ break
+
+ return datetime(other.year, other.month, other.day, hour, minute)
def _prev_opening_time(self, other):
"""
- If n is positive, return yesterday's business day opening time.
- Otherwise yesterday business day's opening time.
+ If n is positive, return the latest opening time earlier than or equal
+ to current time.
+ Otherwise the earliest opening time later than or equal to current
+ time.
+
+ Parameters
+ ----------
+ other : datetime
+ Current time.
+
+ Returns
+ -------
+ result : datetime
+ Previous opening time.
"""
- if not self.next_bday.onOffset(other):
- other = other - self.next_bday
- else:
- if self.n >= 0 and other.time() < self.start:
- other = other - self.next_bday
- elif self.n < 0 and other.time() > self.start:
- other = other - self.next_bday
- return datetime(other.year, other.month, other.day,
- self.start.hour, self.start.minute)
+ return self._next_opening_time(other, sign=-1)
- @cache_readonly
- def _get_business_hours_by_sec(self):
+ def _get_business_hours_by_sec(self, start, end):
"""
Return business hours in a day by seconds.
"""
- if self._get_daytime_flag:
- # create dummy datetime to calculate businesshours in a day
- dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute)
- until = datetime(2014, 4, 1, self.end.hour, self.end.minute)
- return (until - dtstart).total_seconds()
- else:
- dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute)
- until = datetime(2014, 4, 2, self.end.hour, self.end.minute)
- return (until - dtstart).total_seconds()
+ # create dummy datetime to calculate businesshours in a day
+ dtstart = datetime(2014, 4, 1, start.hour, start.minute)
+ day = 1 if start < end else 2
+ until = datetime(2014, 4, day, end.hour, end.minute)
+ return int((until - dtstart).total_seconds())
@apply_wraps
def rollback(self, dt):
@@ -668,13 +735,11 @@ def rollback(self, dt):
Roll provided date backward to next offset only if not on offset.
"""
if not self.onOffset(dt):
- businesshours = self._get_business_hours_by_sec
if self.n >= 0:
- dt = self._prev_opening_time(
- dt) + timedelta(seconds=businesshours)
+ dt = self._prev_opening_time(dt)
else:
- dt = self._next_opening_time(
- dt) + timedelta(seconds=businesshours)
+ dt = self._next_opening_time(dt)
+ return self._get_closing_time(dt)
return dt
@apply_wraps
@@ -689,11 +754,28 @@ def rollforward(self, dt):
return self._prev_opening_time(dt)
return dt
+ def _get_closing_time(self, dt):
+ """
+ Get the closing time of a business hour interval by its opening time.
+
+ Parameters
+ ----------
+ dt : datetime
+ Opening time of a business hour interval.
+
+ Returns
+ -------
+ result : datetime
+ Corresponding closing time.
+ """
+ for i, st in enumerate(self.start):
+ if st.hour == dt.hour and st.minute == dt.minute:
+ return dt + timedelta(
+ seconds=self._get_business_hours_by_sec(st, self.end[i]))
+ assert False
+
@apply_wraps
def apply(self, other):
- businesshours = self._get_business_hours_by_sec
- bhdelta = timedelta(seconds=businesshours)
-
if isinstance(other, datetime):
# used for detecting edge condition
nanosecond = getattr(other, 'nanosecond', 0)
@@ -703,63 +785,75 @@ def apply(self, other):
other.hour, other.minute,
other.second, other.microsecond)
n = self.n
+
+ # adjust other to reduce number of cases to handle
if n >= 0:
- if (other.time() == self.end or
- not self._onOffset(other, businesshours)):
+ if (other.time() in self.end or
+ not self._onOffset(other)):
other = self._next_opening_time(other)
else:
- if other.time() == self.start:
+ if other.time() in self.start:
# adjustment to move to previous business day
other = other - timedelta(seconds=1)
- if not self._onOffset(other, businesshours):
+ if not self._onOffset(other):
other = self._next_opening_time(other)
- other = other + bhdelta
+ other = self._get_closing_time(other)
+
+ # get total business hours by sec in one business day
+ businesshours = sum(self._get_business_hours_by_sec(st, en)
+ for st, en in zip(self.start, self.end))
bd, r = divmod(abs(n * 60), businesshours // 60)
if n < 0:
bd, r = -bd, -r
+ # adjust by business days first
if bd != 0:
skip_bd = BusinessDay(n=bd)
# midnight business hour may not on BusinessDay
if not self.next_bday.onOffset(other):
- remain = other - self._prev_opening_time(other)
- other = self._next_opening_time(other + skip_bd) + remain
+ prev_open = self._prev_opening_time(other)
+ remain = other - prev_open
+ other = prev_open + skip_bd + remain
else:
other = other + skip_bd
- hours, minutes = divmod(r, 60)
- result = other + timedelta(hours=hours, minutes=minutes)
-
- # because of previous adjustment, time will be larger than start
- if n >= 0:
- bday_edge = self._prev_opening_time(other) + bhdelta
- if bday_edge < result:
- bday_remain = result - bday_edge
- result = self._next_opening_time(other)
- result += bday_remain
- else:
- bday_edge = self._next_opening_time(other)
- if bday_edge > result:
- bday_remain = result - bday_edge
- result = self._next_opening_time(result) + bhdelta
- result += bday_remain
+ # remaining business hours to adjust
+ bhour_remain = timedelta(minutes=r)
- # edge handling
if n >= 0:
- if result.time() == self.end:
- result = self._next_opening_time(result)
+ while bhour_remain != timedelta(0):
+ # business hour left in this business time interval
+ bhour = self._get_closing_time(
+ self._prev_opening_time(other)) - other
+ if bhour_remain < bhour:
+ # finish adjusting if possible
+ other += bhour_remain
+ bhour_remain = timedelta(0)
+ else:
+ # go to next business time interval
+ bhour_remain -= bhour
+ other = self._next_opening_time(other + bhour)
else:
- if result.time() == self.start and nanosecond == 0:
- # adjustment to move to previous business day
- result = self._next_opening_time(
- result - timedelta(seconds=1)) + bhdelta
+ while bhour_remain != timedelta(0):
+ # business hour left in this business time interval
+ bhour = self._next_opening_time(other) - other
+ if (bhour_remain > bhour or
+ bhour_remain == bhour and nanosecond != 0):
+ # finish adjusting if possible
+ other += bhour_remain
+ bhour_remain = timedelta(0)
+ else:
+ # go to next business time interval
+ bhour_remain -= bhour
+ other = self._get_closing_time(
+ self._next_opening_time(
+ other + bhour - timedelta(seconds=1)))
- return result
+ return other
else:
- # TODO: Figure out the end of this sente
raise ApplyTypeError(
- 'Only know how to combine business hour with ')
+ 'Only know how to combine business hour with datetime')
def onOffset(self, dt):
if self.normalize and not _is_normalized(dt):
@@ -770,10 +864,9 @@ def onOffset(self, dt):
dt.minute, dt.second, dt.microsecond)
# Valid BH can be on the different BusinessDay during midnight
# Distinguish by the time spent from previous opening time
- businesshours = self._get_business_hours_by_sec
- return self._onOffset(dt, businesshours)
+ return self._onOffset(dt)
- def _onOffset(self, dt, businesshours):
+ def _onOffset(self, dt):
"""
Slight speedups using calculated values.
"""
@@ -786,6 +879,11 @@ def _onOffset(self, dt, businesshours):
else:
op = self._next_opening_time(dt)
span = (dt - op).total_seconds()
+ businesshours = 0
+ for i, st in enumerate(self.start):
+ if op.hour == st.hour and op.minute == st.minute:
+ businesshours = self._get_business_hours_by_sec(
+ st, self.end[i])
if span <= businesshours:
return True
else:
@@ -793,17 +891,17 @@ def _onOffset(self, dt, businesshours):
def _repr_attrs(self):
out = super()._repr_attrs()
- start = self.start.strftime('%H:%M')
- end = self.end.strftime('%H:%M')
- attrs = ['{prefix}={start}-{end}'.format(prefix=self._prefix,
- start=start, end=end)]
+ hours = ','.join('{}-{}'.format(
+ st.strftime('%H:%M'), en.strftime('%H:%M'))
+ for st, en in zip(self.start, self.end))
+ attrs = ['{prefix}={hours}'.format(prefix=self._prefix, hours=hours)]
out += ': ' + ', '.join(attrs)
return out
class BusinessHour(BusinessHourMixin, SingleConstructorOffset):
"""
- DateOffset subclass representing possibly n business days.
+ DateOffset subclass representing possibly n business hours.
.. versionadded:: 0.16.1
"""
| - [x] closes #15481
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
I'm not sure why, but after rebasing on latest master my previous PR #26400 is automatically closed. So I created a new PR here. I have edited as per all the comments there. | https://api.github.com/repos/pandas-dev/pandas/pulls/26628 | 2019-06-03T08:00:14Z | 2019-06-28T14:10:21Z | 2019-06-28T14:10:21Z | 2019-06-28T14:10:28Z |
DOC/CI: Removing Panel specific code from validate_docstrings.py | diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py
index 63db50db45a7c..64eaf45376b2f 100755
--- a/scripts/validate_docstrings.py
+++ b/scripts/validate_docstrings.py
@@ -539,14 +539,9 @@ def first_line_ends_in_dot(self):
if self.doc:
return self.doc.split('\n')[0][-1] == '.'
- @property
- def deprecated_with_directive(self):
- return '.. deprecated:: ' in (self.summary + self.extended_summary)
-
@property
def deprecated(self):
- return (self.name.startswith('pandas.Panel')
- or self.deprecated_with_directive)
+ return '.. deprecated:: ' in (self.summary + self.extended_summary)
@property
def mentioned_private_classes(self):
@@ -674,7 +669,7 @@ def get_validation_data(doc):
errs.append(error('GL07',
correct_sections=', '.join(correct_order)))
- if (doc.deprecated_with_directive
+ if (doc.deprecated
and not doc.extended_summary.startswith('.. deprecated:: ')):
errs.append(error('GL09'))
@@ -859,9 +854,9 @@ def validate_all(prefix, ignore_deprecated=False):
seen[shared_code_key] = func_name
- # functions from introspecting Series, DataFrame and Panel
+ # functions from introspecting Series and DataFrame
api_item_names = set(list(zip(*api_items))[0])
- for class_ in (pandas.Series, pandas.DataFrame, pandas.Panel):
+ for class_ in (pandas.Series, pandas.DataFrame):
for member in inspect.getmembers(class_):
func_name = 'pandas.{}.{}'.format(class_.__name__, member[0])
if (not member[0].startswith('_')
| - [X] xref #25632
- [ ] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26627 | 2019-06-03T07:51:31Z | 2019-06-04T11:23:42Z | 2019-06-04T11:23:42Z | 2019-06-04T11:23:43Z |
DOC: Tidy documentation about plotting Series histograms | diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index fed4b0d90983c..3f6a30c4639bc 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -2477,8 +2477,6 @@ def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
bin edges are calculated and returned. If bins is a sequence, gives
bin edges, including left edge of first bin and right edge of last
bin. In this case, bins is returned unmodified.
- bins : integer, default 10
- Number of histogram bins to be used
`**kwds` : keywords
To be passed to the actual plotting function
| https://api.github.com/repos/pandas-dev/pandas/pulls/26624 | 2019-06-02T20:05:46Z | 2019-06-02T23:11:49Z | 2019-06-02T23:11:49Z | 2019-06-02T23:11:53Z | |
DOC/CI: restore travis CI doc build environment | diff --git a/.travis.yml b/.travis.yml
index 90dd904e6cb1e..ce8817133a477 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -51,14 +51,14 @@ matrix:
# In allow_failures
- dist: trusty
env:
- - JOB="3.6, doc" ENV_FILE="environment.yml" DOC=true
+ - JOB="3.6, doc" ENV_FILE="ci/deps/travis-36-doc.yaml" DOC=true
allow_failures:
- dist: trusty
env:
- JOB="3.6, slow" ENV_FILE="ci/deps/travis-36-slow.yaml" PATTERN="slow"
- dist: trusty
env:
- - JOB="3.6, doc" ENV_FILE="environment.yml" DOC=true
+ - JOB="3.6, doc" ENV_FILE="ci/deps/travis-36-doc.yaml" DOC=true
before_install:
- echo "before_install"
diff --git a/ci/deps/travis-36-doc.yaml b/ci/deps/travis-36-doc.yaml
new file mode 100644
index 0000000000000..9d6cbd82fdc05
--- /dev/null
+++ b/ci/deps/travis-36-doc.yaml
@@ -0,0 +1,46 @@
+name: pandas-dev
+channels:
+ - defaults
+ - conda-forge
+dependencies:
+ - beautifulsoup4
+ - bottleneck
+ - cython>=0.28.2
+ - fastparquet>=0.2.1
+ - gitpython
+ - html5lib
+ - hypothesis>=3.58.0
+ - ipykernel
+ - ipython
+ - ipywidgets
+ - lxml
+ - matplotlib
+ - nbconvert>=5.4.1
+ - nbformat
+ - nbsphinx
+ - notebook>=5.7.5
+ - numexpr
+ - numpy
+ - numpydoc
+ - openpyxl
+ - pandoc
+ - pyarrow
+ - pyqt
+ - pytables
+ - python-dateutil
+ - python-snappy
+ - python=3.6.*
+ - pytz
+ - scipy
+ - seaborn
+ - sphinx
+ - sqlalchemy
+ - statsmodels
+ - xarray
+ - xlrd
+ - xlsxwriter
+ - xlwt
+ # universal
+ - pytest>=4.0.2
+ - pytest-xdist
+ - isort
| xref https://github.com/pandas-dev/pandas/pull/26591#issuecomment-498040997
This is one option (adding back the specific doc build environment yml file), another option would be to actually update the main `environment.yaml` file to be suitable for the doc build.
At the moment, my preference is to add back the separate yml file because 1) those additional dependencies are not necessarily needed for a dev env setup, and just makes that env even more heavy and 2) we might want to pin to certain versions from time to time for the doc build (eg we should consider pinning sphinx to < 2.0, which is not necessarily needed for all contributors to do as well).
Another thing is that this env could actually use an update (eg python 3.6 -> 3.7)
cc @datapythonista
| https://api.github.com/repos/pandas-dev/pandas/pulls/26621 | 2019-06-02T15:38:29Z | 2019-06-03T05:35:26Z | 2019-06-03T05:35:26Z | 2019-06-03T07:28:29Z |
[CI] Add pytest-azurepipelines in pandas-dev | diff --git a/ci/deps/azure-35-compat.yaml b/ci/deps/azure-35-compat.yaml
index c783670e78d52..fe207d122657b 100644
--- a/ci/deps/azure-35-compat.yaml
+++ b/ci/deps/azure-35-compat.yaml
@@ -22,6 +22,7 @@ dependencies:
- hypothesis>=3.58.0
- pytest-xdist
- pytest-mock
+ - pytest-azurepipelines
- pip
- pip:
# for python 3.5, pytest>=4.0.2 is not available in conda
diff --git a/ci/deps/azure-36-locale.yaml b/ci/deps/azure-36-locale.yaml
index fbb240734d45d..99fa4d5c9e160 100644
--- a/ci/deps/azure-36-locale.yaml
+++ b/ci/deps/azure-36-locale.yaml
@@ -23,6 +23,7 @@ dependencies:
- pytest>=4.0.2
- pytest-xdist
- pytest-mock
+ - pytest-azurepipelines
- hypothesis>=3.58.0
- pip
- pip:
diff --git a/ci/deps/azure-36-locale_slow.yaml b/ci/deps/azure-36-locale_slow.yaml
index 9ddc782da930e..2bf2bd74795d2 100644
--- a/ci/deps/azure-36-locale_slow.yaml
+++ b/ci/deps/azure-36-locale_slow.yaml
@@ -29,6 +29,7 @@ dependencies:
- pytest>=4.0.2
- pytest-xdist
- pytest-mock
+ - pytest-azurepipelines
- moto
- pip
- pip:
diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml
index 2ebb7dda86e36..bd8ba912d5298 100644
--- a/ci/deps/azure-37-locale.yaml
+++ b/ci/deps/azure-37-locale.yaml
@@ -28,6 +28,7 @@ dependencies:
- pytest>=4.0.2
- pytest-xdist
- pytest-mock
+ - pytest-azurepipelines
- pip
- pip:
- hypothesis>=3.58.0
diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml
index 831f13fb421f0..c56dc819a90b1 100644
--- a/ci/deps/azure-37-numpydev.yaml
+++ b/ci/deps/azure-37-numpydev.yaml
@@ -17,3 +17,4 @@ dependencies:
- "--pre"
- "numpy"
- "scipy"
+ - pytest-azurepipelines
diff --git a/ci/deps/azure-macos-35.yaml b/ci/deps/azure-macos-35.yaml
index 24c753e16d98d..0b96dd9762ef5 100644
--- a/ci/deps/azure-macos-35.yaml
+++ b/ci/deps/azure-macos-35.yaml
@@ -29,3 +29,4 @@ dependencies:
- pytest-xdist
- pytest-mock
- hypothesis>=3.58.0
+ - pytest-azurepipelines
diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-36.yaml
index b1795059091b9..b0f3f5389ac85 100644
--- a/ci/deps/azure-windows-36.yaml
+++ b/ci/deps/azure-windows-36.yaml
@@ -26,4 +26,5 @@ dependencies:
- pytest>=4.0.2
- pytest-xdist
- pytest-mock
+ - pytest-azurepipelines
- hypothesis>=3.58.0
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index 5bdc29e0eec80..43504dec26953 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -28,6 +28,7 @@ dependencies:
- pytest>=4.0.2
- pytest-xdist
- pytest-mock
+ - pytest-azurepipelines
- moto
- hypothesis>=3.58.0
- pyreadstat
| - closes #26601
Is it better to put `pip install pytest-azurepipelines` inside `setup_env.sh`? | https://api.github.com/repos/pandas-dev/pandas/pulls/26620 | 2019-06-02T11:28:58Z | 2019-06-28T14:12:24Z | 2019-06-28T14:12:24Z | 2019-06-28T14:12:45Z |
CI: pin pytest version on Python 3.5 | diff --git a/ci/deps/azure-35-compat.yaml b/ci/deps/azure-35-compat.yaml
index d0a48bd3f8b27..e55a4fbdf3fa9 100644
--- a/ci/deps/azure-35-compat.yaml
+++ b/ci/deps/azure-35-compat.yaml
@@ -26,5 +26,5 @@ dependencies:
- pip
- pip:
# for python 3.5, pytest>=4.0.2 is not available in conda
- - pytest>=4.0.2
+ - pytest==4.5.0
- html5lib==1.0b2
diff --git a/ci/deps/azure-macos-35.yaml b/ci/deps/azure-macos-35.yaml
index 591266348a5f1..00c2051f29760 100644
--- a/ci/deps/azure-macos-35.yaml
+++ b/ci/deps/azure-macos-35.yaml
@@ -25,7 +25,7 @@ dependencies:
- pip:
- python-dateutil==2.5.3
# universal
- - pytest>=4.0.2
+ - pytest==4.5.0
- pytest-xdist
- pytest-mock
- hypothesis>=3.58.0
| closes #26614 | https://api.github.com/repos/pandas-dev/pandas/pulls/26619 | 2019-06-02T10:44:29Z | 2019-06-02T11:47:35Z | 2019-06-02T11:47:35Z | 2019-06-03T11:15:59Z |
PERF: custom ops for RangeIndex.[all|any|__contains__] | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 1fb9b5ae695a0..0f31078d7bf43 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -502,7 +502,7 @@ Performance Improvements
- Improved performance of :meth:`Series.searchsorted`. The speedup is especially large when the dtype is
int8/int16/int32 and the searched key is within the integer bounds for the dtype (:issue:`22034`)
- Improved performance of :meth:`pandas.core.groupby.GroupBy.quantile` (:issue:`20405`)
-- Improved performance when slicing :class:`RangeIndex` (:issue:`26565`)
+- Improved performance of slicing and other selected operation on a :class:`RangeIndex` (:issue:`26565`, :issue:`26617`)
- Improved performance of :meth:`read_csv` by faster tokenizing and faster parsing of small float numbers (:issue:`25784`)
- Improved performance of :meth:`read_csv` by faster parsing of N/A and boolean values (:issue:`25804`)
- Improved performance of :attr:`IntervalIndex.is_monotonic`, :attr:`IntervalIndex.is_monotonic_increasing` and :attr:`IntervalIndex.is_monotonic_decreasing` by removing conversion to :class:`MultiIndex` (:issue:`24813`)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 8538687ca3e91..b8c020ff0edb1 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4013,11 +4013,7 @@ def __contains__(self, key):
@Appender(_index_shared_docs['contains'] % _index_doc_kwargs)
def contains(self, key):
- hash(key)
- try:
- return key in self._engine
- except (TypeError, ValueError):
- return False
+ return key in self
def __hash__(self):
raise TypeError("unhashable type: %r" % type(self).__name__)
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index 82fd7342c027c..14ebc3c7e8e2a 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -1,6 +1,7 @@
from datetime import timedelta
import operator
from sys import getsizeof
+from typing import Union
import warnings
import numpy as np
@@ -334,6 +335,14 @@ def is_monotonic_decreasing(self):
def has_duplicates(self):
return False
+ def __contains__(self, key: Union[int, np.integer]) -> bool:
+ hash(key)
+ try:
+ key = ensure_python_int(key)
+ except TypeError:
+ return False
+ return key in self._range
+
@Appender(_index_shared_docs['get_loc'])
def get_loc(self, key, method=None, tolerance=None):
if is_integer(key) and method is None and tolerance is None:
@@ -640,6 +649,12 @@ def __floordiv__(self, other):
return self._simple_new(start, start + 1, 1, name=self.name)
return self._int64index // other
+ def all(self) -> bool:
+ return 0 not in self._range
+
+ def any(self) -> bool:
+ return any(self._range)
+
@classmethod
def _add_numeric_methods_binary(cls):
""" add in numeric methods, specialized to RangeIndex """
@@ -725,4 +740,3 @@ def _evaluate_numeric_binop(self, other):
RangeIndex._add_numeric_methods()
-RangeIndex._add_logical_methods()
diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py
index bca50186827de..6eece0ed8efee 100644
--- a/pandas/tests/indexes/test_range.py
+++ b/pandas/tests/indexes/test_range.py
@@ -245,10 +245,9 @@ def test_dtype(self):
assert self.index.dtype == np.int64
def test_cached_data(self):
- # GH 26565
- # Calling RangeIndex._data caches an int64 array of the same length as
- # self at self._cached_data.
- # This tests whether _cached_data is being set by various operations.
+ # GH 26565, GH26617
+ # Calling RangeIndex._data caches an int64 array of the same length at
+ # self._cached_data. This test checks whether _cached_data has been set
idx = RangeIndex(0, 100, 10)
assert idx._cached_data is None
@@ -262,6 +261,24 @@ def test_cached_data(self):
idx.get_loc(20)
assert idx._cached_data is None
+ 90 in idx
+ assert idx._cached_data is None
+
+ 91 in idx
+ assert idx._cached_data is None
+
+ idx.contains(90)
+ assert idx._cached_data is None
+
+ idx.contains(91)
+ assert idx._cached_data is None
+
+ idx.all()
+ assert idx._cached_data is None
+
+ idx.any()
+ assert idx._cached_data is None
+
df = pd.DataFrame({'a': range(10)}, index=idx)
df.loc[50]
| - [x] xref #26565
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Follow-up to #26565. Make ``RangeIndex._data`` be created in fewer cases.
Performance examples (but the larger gain is from memory savings by not creating the ``_data`` array):
```python
>>> rng = pd.RangeIndex(-5_000_000, 0, 6)
>>> %timeit rng.all()
789 µs ± 5.24 µs per loop # master
216 ns ± 0.957 ns per loop # this PR
>>> %timeit rng.any()
763 µs ± 6.08 µs per loop # master
124 ns ± 9.15 ns per loop # this PR
>>> %timeit (-2 in rng)
380 ns ± 1.85 ns per loop # master
689 ns ± 44.7 ns per loop # this PR, slightly slower
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/26617 | 2019-06-02T09:14:11Z | 2019-06-06T17:38:21Z | 2019-06-06T17:38:21Z | 2019-06-19T13:43:48Z |
CLN: Remove convert_objects | diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst
index dfa475684c834..b4fb85c028b3e 100644
--- a/doc/source/reference/frame.rst
+++ b/doc/source/reference/frame.rst
@@ -48,7 +48,6 @@ Conversion
:toctree: api/
DataFrame.astype
- DataFrame.convert_objects
DataFrame.infer_objects
DataFrame.copy
DataFrame.isna
diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst
index b406893e3414a..8fccdea979602 100644
--- a/doc/source/reference/series.rst
+++ b/doc/source/reference/series.rst
@@ -56,7 +56,6 @@ Conversion
Series.astype
Series.infer_objects
- Series.convert_objects
Series.copy
Series.bool
Series.to_numpy
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index f122c73325b7d..1cbec223008c4 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -483,6 +483,7 @@ Removal of prior version deprecations/changes
- Removed the previously deprecated ``TimeGrouper`` (:issue:`16942`)
- Removed the previously deprecated ``parse_cols`` keyword in :func:`read_excel` (:issue:`16488`)
- Removed the previously deprecated ``pd.options.html.border`` (:issue:`16970`)
+- Removed the previously deprecated ``convert_objects`` (:issue:`11221`)
.. _whatsnew_0250.performance:
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 33b0035e74913..2428bbad7003b 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -113,7 +113,7 @@ class NDFrame(PandasObject, SelectionMixin):
_internal_names_set = set(_internal_names) # type: Set[str]
_accessors = set() # type: Set[str]
_deprecations = frozenset([
- 'as_blocks', 'blocks', 'convert_objects', 'is_copy'
+ 'as_blocks', 'blocks', 'is_copy'
]) # type: FrozenSet[str]
_metadata = [] # type: List[str]
_is_copy = None
@@ -5913,52 +5913,6 @@ def _convert(self, datetime=False, numeric=False, timedelta=False,
timedelta=timedelta, coerce=coerce,
copy=copy)).__finalize__(self)
- def convert_objects(self, convert_dates=True, convert_numeric=False,
- convert_timedeltas=True, copy=True):
- """
- Attempt to infer better dtype for object columns.
-
- .. deprecated:: 0.21.0
-
- Parameters
- ----------
- convert_dates : boolean, default True
- If True, convert to date where possible. If 'coerce', force
- conversion, with unconvertible values becoming NaT.
- convert_numeric : boolean, default False
- If True, attempt to coerce to numbers (including strings), with
- unconvertible values becoming NaN.
- convert_timedeltas : boolean, default True
- If True, convert to timedelta where possible. If 'coerce', force
- conversion, with unconvertible values becoming NaT.
- copy : boolean, default True
- If True, return a copy even if no copy is necessary (e.g. no
- conversion was done). Note: This is meant for internal use, and
- should not be confused with inplace.
-
- Returns
- -------
- converted : same as input object
-
- See Also
- --------
- to_datetime : Convert argument to datetime.
- to_timedelta : Convert argument to timedelta.
- to_numeric : Convert argument to numeric type.
- """
- msg = ("convert_objects is deprecated. To re-infer data dtypes for "
- "object columns, use {klass}.infer_objects()\nFor all "
- "other conversions use the data-type specific converters "
- "pd.to_datetime, pd.to_timedelta and pd.to_numeric."
- ).format(klass=self.__class__.__name__)
- warnings.warn(msg, FutureWarning, stacklevel=2)
-
- return self._constructor(
- self._data.convert(convert_dates=convert_dates,
- convert_numeric=convert_numeric,
- convert_timedeltas=convert_timedeltas,
- copy=copy)).__finalize__(self)
-
def infer_objects(self):
"""
Attempt to infer better dtypes for object columns.
diff --git a/pandas/tests/series/test_internals.py b/pandas/tests/series/test_internals.py
index f6f4a2db359f7..29846f10dae33 100644
--- a/pandas/tests/series/test_internals.py
+++ b/pandas/tests/series/test_internals.py
@@ -12,131 +12,6 @@
class TestSeriesInternals:
- def test_convert_objects(self):
-
- s = Series([1., 2, 3], index=['a', 'b', 'c'])
- with tm.assert_produces_warning(FutureWarning):
- result = s.convert_objects(convert_dates=False,
- convert_numeric=True)
- assert_series_equal(result, s)
-
- # force numeric conversion
- r = s.copy().astype('O')
- r['a'] = '1'
- with tm.assert_produces_warning(FutureWarning):
- result = r.convert_objects(convert_dates=False,
- convert_numeric=True)
- assert_series_equal(result, s)
-
- r = s.copy().astype('O')
- r['a'] = '1.'
- with tm.assert_produces_warning(FutureWarning):
- result = r.convert_objects(convert_dates=False,
- convert_numeric=True)
- assert_series_equal(result, s)
-
- r = s.copy().astype('O')
- r['a'] = 'garbled'
- expected = s.copy()
- expected['a'] = np.nan
- with tm.assert_produces_warning(FutureWarning):
- result = r.convert_objects(convert_dates=False,
- convert_numeric=True)
- assert_series_equal(result, expected)
-
- # GH 4119, not converting a mixed type (e.g.floats and object)
- s = Series([1, 'na', 3, 4])
- with tm.assert_produces_warning(FutureWarning):
- result = s.convert_objects(convert_numeric=True)
- expected = Series([1, np.nan, 3, 4])
- assert_series_equal(result, expected)
-
- s = Series([1, '', 3, 4])
- with tm.assert_produces_warning(FutureWarning):
- result = s.convert_objects(convert_numeric=True)
- expected = Series([1, np.nan, 3, 4])
- assert_series_equal(result, expected)
-
- # dates
- s = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0),
- datetime(2001, 1, 3, 0, 0)])
- s2 = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0),
- datetime(2001, 1, 3, 0, 0), 'foo', 1.0, 1,
- Timestamp('20010104'), '20010105'],
- dtype='O')
- with tm.assert_produces_warning(FutureWarning):
- result = s.convert_objects(convert_dates=True,
- convert_numeric=False)
- expected = Series([Timestamp('20010101'), Timestamp('20010102'),
- Timestamp('20010103')], dtype='M8[ns]')
- assert_series_equal(result, expected)
-
- with tm.assert_produces_warning(FutureWarning):
- result = s.convert_objects(convert_dates='coerce',
- convert_numeric=False)
- with tm.assert_produces_warning(FutureWarning):
- result = s.convert_objects(convert_dates='coerce',
- convert_numeric=True)
- assert_series_equal(result, expected)
-
- expected = Series([Timestamp('20010101'), Timestamp('20010102'),
- Timestamp('20010103'),
- NaT, NaT, NaT, Timestamp('20010104'),
- Timestamp('20010105')], dtype='M8[ns]')
- with tm.assert_produces_warning(FutureWarning):
- result = s2.convert_objects(convert_dates='coerce',
- convert_numeric=False)
- assert_series_equal(result, expected)
- with tm.assert_produces_warning(FutureWarning):
- result = s2.convert_objects(convert_dates='coerce',
- convert_numeric=True)
- assert_series_equal(result, expected)
-
- # preserver all-nans (if convert_dates='coerce')
- s = Series(['foo', 'bar', 1, 1.0], dtype='O')
- with tm.assert_produces_warning(FutureWarning):
- result = s.convert_objects(convert_dates='coerce',
- convert_numeric=False)
- expected = Series([NaT] * 2 + [Timestamp(1)] * 2)
- assert_series_equal(result, expected)
-
- # preserver if non-object
- s = Series([1], dtype='float32')
- with tm.assert_produces_warning(FutureWarning):
- result = s.convert_objects(convert_dates='coerce',
- convert_numeric=False)
- assert_series_equal(result, s)
-
- # r = s.copy()
- # r[0] = np.nan
- # result = r.convert_objects(convert_dates=True,convert_numeric=False)
- # assert result.dtype == 'M8[ns]'
-
- # dateutil parses some single letters into today's value as a date
- for x in 'abcdefghijklmnopqrstuvwxyz':
- s = Series([x])
- with tm.assert_produces_warning(FutureWarning):
- result = s.convert_objects(convert_dates='coerce')
- assert_series_equal(result, s)
- s = Series([x.upper()])
- with tm.assert_produces_warning(FutureWarning):
- result = s.convert_objects(convert_dates='coerce')
- assert_series_equal(result, s)
-
- def test_convert_objects_preserve_bool(self):
- s = Series([1, True, 3, 5], dtype=object)
- with tm.assert_produces_warning(FutureWarning):
- r = s.convert_objects(convert_numeric=True)
- e = Series([1, 1, 3, 5], dtype='i8')
- tm.assert_series_equal(r, e)
-
- def test_convert_objects_preserve_all_bool(self):
- s = Series([False, True, False, False], dtype=object)
- with tm.assert_produces_warning(FutureWarning):
- r = s.convert_objects(convert_numeric=True)
- e = Series([False, True, False, False], dtype=bool)
- tm.assert_series_equal(r, e)
-
# GH 10265
def test_convert(self):
# Tests: All to nans, coerce, true
| - [x] xref #6581
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26612 | 2019-06-02T00:02:51Z | 2019-06-02T23:20:16Z | 2019-06-02T23:20:16Z | 2019-06-03T15:11:03Z |
CI: Removing doc build in azure | diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 0064d0a932960..85325c52e7e6d 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -116,63 +116,3 @@ jobs:
fi
displayName: 'Running benchmarks'
condition: true
-
-- job: 'Docs'
- pool:
- vmImage: ubuntu-16.04
- timeoutInMinutes: 90
- steps:
- - script: |
- echo '##vso[task.setvariable variable=CONDA_ENV]pandas-dev'
- echo '##vso[task.setvariable variable=ENV_FILE]environment.yml'
- displayName: 'Setting environment variables'
-
- - script: |
- export PATH=$HOME/miniconda3/bin:$PATH
- sudo apt-get install -y libc6-dev-i386
- ci/setup_env.sh
- displayName: 'Setup environment and build pandas'
-
- - script: |
- export PATH=$HOME/miniconda3/bin:$PATH
- source activate pandas-dev
- doc/make.py
- displayName: 'Build documentation'
-
- - script: |
- cd doc/build/html
- git init
- touch .nojekyll
- git add --all .
- git config user.email "pandas-dev@python.org"
- git config user.name "pandas-docs-bot"
- git commit -m "pandas documentation in master"
- displayName: 'Create git repo for docs build'
- condition : |
- and(not(eq(variables['Build.Reason'], 'PullRequest')),
- eq(variables['Build.SourceBranch'], 'refs/heads/master'))
-
- # This task to work requires next steps:
- # 1. Got to "Library > Secure files" in the azure-pipelines dashboard: https://dev.azure.com/pandas-dev/pandas/_library?itemType=SecureFiles
- # 2. Click on "+ Secure file"
- # 3. Upload the private key (the name of the file must match with the specified in "sshKeySecureFile" input below, "pandas_docs_key")
- # 4. Click on file name after it is created, tick the box "Authorize for use in all pipelines" and save
- # 5. The public key specified in "sshPublicKey" is the pair of the uploaded private key, and needs to be specified as a deploy key of the repo where the docs will be pushed: https://github.com/pandas-dev/pandas-dev.github.io/settings/keys
- - task: InstallSSHKey@0
- inputs:
- hostName: 'github.com'
- sshPublicKey: 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDfF0BSddjvZx/z4/2TXsy+RxjwBpgdHkmjtL9WfRHxEw1TchBuEj5vWWcxBNTK+9oVzD/Lca89HAXXrklsfkdAK3LvLfGCxTGpP8t/3CxxFdnSg3EN+4cDGKuDlbeTyzdASdPBOq0GTZjUFekl9ZfFrFJ9SoPpqZ4mmPRPapPrkwTs4xIrBly0eWcISFYgZcG58m65+XQpyyBMbpsO5ZHBBxE8kkWN0yY+gKt5PeeIO82xE+7F+3Qhlc67fKfB4FEitQ5SKrbKyGNNdFtEGcC6CEtD0B0vJxssltQEl5dDWPJP6tH4cIm/J6m28mpSYc5fEBhr75jE4Ybw6NtGgBZEdtFRFlnb91mSiVSjM/HEkV7/xYai+H1Gk+I/8tcl8cf3JCiJSP2glz8bp52+i5it29FUL8ITxdJSo0duUkVm3nZ8cDI6zag+nSSmzdZ1I9Fw7M7RRPHM2zd5+6RskeqamR5lY3Iv+t8Yo8cRX10IiHNF89b+3vI5ZkIKqytrPfrY45jGVMXA6x/whMh94Ac94qm+Do7P3eT/66a1lX0r+UfV6UnfwHE6cZ1ZFX2AzlmSiYMKmTD3hn1GNyHHuvk3Mneanbk4+x+8SjAXIK354zJ8c1Qgk1iEicDvna2IBd94R4tBWjYZ8xH7avmPlhs0HwbjiNOFDc45UXvwIl+D7w== pandas-dev@python.org'
- sshKeySecureFile: 'pandas_docs_key'
- displayName: 'Install GitHub ssh deployment key'
- condition : |
- and(not(eq(variables['Build.Reason'], 'PullRequest')),
- eq(variables['Build.SourceBranch'], 'refs/heads/master'))
-
- - script: |
- cd doc/build/html
- git remote add origin git@github.com:pandas-dev/pandas-dev.github.io.git
- git push origin master -f
- displayName: 'Publish docs to GitHub pages'
- condition : |
- and(not(eq(variables['Build.Reason'], 'PullRequest')),
- eq(variables['Build.SourceBranch'], 'refs/heads/master'))
| Stop building the docs in azure. Beside not working, azure became unreliable, raising random errors for unrelated changes.
See: #26591 #26602 #26604
CC: @jreback (sorry for the trouble, hopefully this takes things back to normality) | https://api.github.com/repos/pandas-dev/pandas/pulls/26609 | 2019-06-01T16:14:38Z | 2019-06-01T16:46:56Z | 2019-06-01T16:46:56Z | 2019-06-01T17:15:20Z |
TST/API: Forbid str-accessor for 1-level MultiIndex | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 461c883f542ab..0e8cd95084a8d 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -434,6 +434,7 @@ Other API Changes
- The ``arg`` argument in :meth:`pandas.core.groupby.DataFrameGroupBy.agg` has been renamed to ``func`` (:issue:`26089`)
- The ``arg`` argument in :meth:`pandas.core.window._Window.aggregate` has been renamed to ``func`` (:issue:`26372`)
- Most Pandas classes had a ``__bytes__`` method, which was used for getting a python2-style bytestring representation of the object. This method has been removed as a part of dropping Python2 (:issue:`26447`)
+- The `.str`-accessor has been disabled for 1-level :class:`MultiIndex`, use :meth:`MultiIndex.to_flat_index` if necessary (:issue:`23679`)
- Removed support of gtk package for clipboards (:issue:`26563`)
.. _whatsnew_0250.deprecations:
diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py
index 1ba0ef3918fb7..a1d522930e9aa 100644
--- a/pandas/tests/test_strings.py
+++ b/pandas/tests/test_strings.py
@@ -169,6 +169,14 @@ def test_api(self):
assert Series.str is strings.StringMethods
assert isinstance(Series(['']).str, strings.StringMethods)
+ def test_api_mi_raises(self):
+ # GH 23679
+ mi = MultiIndex.from_arrays([['a', 'b', 'c']])
+ with pytest.raises(AttributeError, match='Can only use .str accessor '
+ 'with Index, not MultiIndex'):
+ mi.str
+ assert not hasattr(mi, 'str')
+
@pytest.mark.parametrize('dtype', [object, 'category'])
@pytest.mark.parametrize('box', [Series, Index])
def test_api_per_dtype(self, box, dtype, any_skipna_inferred_dtype):
| - [x] closes #23679
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Another PR that had been blocked by #23167. | https://api.github.com/repos/pandas-dev/pandas/pulls/26608 | 2019-06-01T15:56:52Z | 2019-06-03T11:56:30Z | 2019-06-03T11:56:29Z | 2019-06-05T22:15:17Z |
Better error for str.cat with listlike of wrong dtype. | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index c1d4797af9145..720cbdc2aeba8 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -613,7 +613,7 @@ Strings
^^^^^^^
- Bug in the ``__name__`` attribute of several methods of :class:`Series.str`, which were set incorrectly (:issue:`23551`)
--
+- Improved error message when passing :class:`Series` of wrong dtype to :meth:`Series.str.cat` (:issue:`22722`)
-
diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index 619b49438cdbb..413c0e73f8410 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -2,7 +2,7 @@
from functools import wraps
import re
import textwrap
-from typing import Dict
+from typing import Dict, List
import warnings
import numpy as np
@@ -31,7 +31,7 @@
_shared_docs = dict() # type: Dict[str, str]
-def cat_core(list_of_columns, sep):
+def cat_core(list_of_columns: List, sep: str):
"""
Auxiliary function for :meth:`str.cat`
@@ -53,6 +53,41 @@ def cat_core(list_of_columns, sep):
return np.sum(list_with_sep, axis=0)
+def cat_safe(list_of_columns: List, sep: str):
+ """
+ Auxiliary function for :meth:`str.cat`.
+
+ Same signature as cat_core, but handles TypeErrors in concatenation, which
+ happen if the arrays in list_of columns have the wrong dtypes or content.
+
+ Parameters
+ ----------
+ list_of_columns : list of numpy arrays
+ List of arrays to be concatenated with sep;
+ these arrays may not contain NaNs!
+ sep : string
+ The separator string for concatenating the columns
+
+ Returns
+ -------
+ nd.array
+ The concatenation of list_of_columns with sep
+ """
+ try:
+ result = cat_core(list_of_columns, sep)
+ except TypeError:
+ # if there are any non-string values (wrong dtype or hidden behind
+ # object dtype), np.sum will fail; catch and return with better message
+ for column in list_of_columns:
+ dtype = lib.infer_dtype(column, skipna=True)
+ if dtype not in ['string', 'empty']:
+ raise TypeError(
+ 'Concatenation requires list-likes containing only '
+ 'strings (or missing values). Offending values found in '
+ 'column {}'.format(dtype)) from None
+ return result
+
+
def _na_map(f, arr, na_result=np.nan, dtype=object):
# should really _check_ for NA
return _map(f, arr, na_mask=True, na_value=na_result, dtype=dtype)
@@ -2314,16 +2349,16 @@ def cat(self, others=None, sep=None, na_rep=None, join=None):
np.putmask(result, union_mask, np.nan)
not_masked = ~union_mask
- result[not_masked] = cat_core([x[not_masked] for x in all_cols],
+ result[not_masked] = cat_safe([x[not_masked] for x in all_cols],
sep)
elif na_rep is not None and union_mask.any():
# fill NaNs with na_rep in case there are actually any NaNs
all_cols = [np.where(nm, na_rep, col)
for nm, col in zip(na_masks, all_cols)]
- result = cat_core(all_cols, sep)
+ result = cat_safe(all_cols, sep)
else:
# no NaNs - can just concatenate
- result = cat_core(all_cols, sep)
+ result = cat_safe(all_cols, sep)
if isinstance(self._orig, Index):
# add dtype for case that result is all-NA
diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py
index a1d522930e9aa..955554f60aa1f 100644
--- a/pandas/tests/test_strings.py
+++ b/pandas/tests/test_strings.py
@@ -428,6 +428,23 @@ def test_str_cat_categorical(self, box, dtype_caller, dtype_target, sep):
result = s.str.cat(t, sep=sep)
assert_series_or_index_equal(result, expected)
+ # test integer/float dtypes (inferred by constructor) and mixed
+ @pytest.mark.parametrize('data', [[1, 2, 3], [.1, .2, .3], [1, 2, 'b']],
+ ids=['integers', 'floats', 'mixed'])
+ # without dtype=object, np.array would cast [1, 2, 'b'] to ['1', '2', 'b']
+ @pytest.mark.parametrize('box', [Series, Index, list,
+ lambda x: np.array(x, dtype=object)],
+ ids=['Series', 'Index', 'list', 'np.array'])
+ def test_str_cat_wrong_dtype_raises(self, box, data):
+ # GH 22722
+ s = Series(['a', 'b', 'c'])
+ t = box(data)
+
+ msg = 'Concatenation requires list-likes containing only strings.*'
+ with pytest.raises(TypeError, match=msg):
+ # need to use outer and na_rep, as otherwise Index would not raise
+ s.str.cat(t, join='outer', na_rep='-')
+
@pytest.mark.parametrize('box', [Series, Index])
def test_str_cat_mixed_inputs(self, box):
s = Index(['a', 'b', 'c', 'd'])
| - [x] closes #22722
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
This had been blocked on #23167. | https://api.github.com/repos/pandas-dev/pandas/pulls/26607 | 2019-06-01T15:51:00Z | 2019-06-14T12:27:01Z | 2019-06-14T12:27:01Z | 2019-06-14T18:16:15Z |
Clean up ufuncs post numpy bump | diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py
index ecc06db2bd07b..926ed6a829a6d 100644
--- a/pandas/core/arrays/sparse.py
+++ b/pandas/core/arrays/sparse.py
@@ -573,7 +573,6 @@ class SparseArray(PandasObject, ExtensionArray, ExtensionOpsMixin):
Whether to explicitly copy the incoming `data` array.
"""
- __array_priority__ = 15
_pandas_ftype = 'sparse'
_subtyp = 'sparse_array' # register ABCSparseArray
@@ -1639,14 +1638,6 @@ def T(self):
# Ufuncs
# ------------------------------------------------------------------------
- def __array_wrap__(self, array, context=None):
- from pandas.core.dtypes.generic import ABCSparseSeries
-
- ufunc, inputs, _ = context
- inputs = tuple(x.to_dense() if isinstance(x, ABCSparseSeries) else x
- for x in inputs)
- return self.__array_ufunc__(ufunc, '__call__', *inputs)
-
_HANDLED_TYPES = (np.ndarray, numbers.Number)
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py
index bf1cec7571f4d..0320da6d9a48d 100644
--- a/pandas/core/sparse/frame.py
+++ b/pandas/core/sparse/frame.py
@@ -242,12 +242,6 @@ def _init_spmatrix(self, data, index, columns, dtype=None,
def to_coo(self):
return SparseFrameAccessor(self).to_coo()
- def __array_wrap__(self, result):
- return self._constructor(
- result, index=self.index, columns=self.columns,
- default_kind=self._default_kind,
- default_fill_value=self._default_fill_value).__finalize__(self)
-
def __getstate__(self):
# pickling
return dict(_typ=self._typ, _subtyp=self._subtyp, _data=self._data,
diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py
index 3f95acdbfb42c..3814d8bb66635 100644
--- a/pandas/core/sparse/series.py
+++ b/pandas/core/sparse/series.py
@@ -124,26 +124,6 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
fill_value=result.fill_value,
copy=False).__finalize__(self)
- def __array_wrap__(self, result, context=None):
- """
- Gets called prior to a ufunc (and after)
-
- See SparseArray.__array_wrap__ for detail.
- """
- result = self.values.__array_wrap__(result, context=context)
- return self._constructor(result, index=self.index,
- sparse_index=self.sp_index,
- fill_value=result.fill_value,
- copy=False).__finalize__(self)
-
- def __array_finalize__(self, obj):
- """
- Gets called after any ufunc or other array operations, necessary
- to pass on the index.
- """
- self.name = getattr(obj, 'name', None)
- self.fill_value = getattr(obj, 'fill_value', None)
-
# unary ops
# TODO: See if this can be shared
def __pos__(self):
| Found an old branch lying around I had forgotten about after the numpy bump, which had been requested by @TomAugspurger in [this comment](https://github.com/pandas-dev/pandas/pull/25554#pullrequestreview-212474594)
| https://api.github.com/repos/pandas-dev/pandas/pulls/26606 | 2019-06-01T15:42:26Z | 2019-06-02T23:34:28Z | 2019-06-02T23:34:27Z | 2019-06-03T05:17:26Z |
PERF: Add if branch for empty sep in str.cat | diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index 54882d039f135..43514153b0515 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -59,6 +59,9 @@ def cat_core(list_of_columns: List, sep: str):
nd.array
The concatenation of list_of_columns with sep
"""
+ if sep == "":
+ # no need to interleave sep if it is empty
+ return np.sum(list_of_columns, axis=0)
list_with_sep = [sep] * (2 * len(list_of_columns) - 1)
list_with_sep[::2] = list_of_columns
return np.sum(list_with_sep, axis=0)
| Follow-up to #23167, resp dropping py2. The branch I'm readding here had to be deleted originally to pass some python2 bytes-tests. In case there is no separator, we can avoid all the list-ops and speed up cat_core by a fair bit. | https://api.github.com/repos/pandas-dev/pandas/pulls/26605 | 2019-06-01T15:32:46Z | 2019-07-31T12:29:59Z | 2019-07-31T12:29:59Z | 2019-07-31T13:26:42Z |
CI: Changing dev docs ssh key | diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 9f83917024049..0064d0a932960 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -161,7 +161,7 @@ jobs:
- task: InstallSSHKey@0
inputs:
hostName: 'github.com'
- sshPublicKey: 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDHmz3l/EdqrgNxEUKkwDUuUcLv91unig03pYFGO/DMIgCmPdMG96zAgfnESd837Rm0wSSqylwSzkRJt5MV/TpFlcVifDLDQmUhqCeO8Z6dLl/oe35UKmyYICVwcvQTAaHNnYRpKC5IUlTh0JEtw9fGlnp1Ta7U1ENBLbKdpywczElhZu+hOQ892zqOj3CwA+U2329/d6cd7YnqIKoFN9DWT3kS5K6JE4IoBfQEVekIOs23bKjNLvPoOmi6CroAhu/K8j+NCWQjge5eJf2x/yTnIIP1PlEcXoHIr8io517posIx3TBup+CN8bNS1PpDW3jyD3ttl1uoBudjOQrobNnJeR6Rn67DRkG6IhSwr3BWj8alwUG5mTdZzwV5Pa9KZFdIiqX7NoDGg+itsR39QCn0thK8lGRNSR8KrWC1PSjecwelKBO7uQ7rnk/rkrZdBWR4oEA8YgNH8tirUw5WfOr5a0AIaJicKxGKNdMxZt+zmC+bS7F4YCOGIm9KHa43RrKhoGRhRf9fHHHKUPwFGqtWG4ykcUgoamDOURJyepesBAO3FiRE9rLU6ILbB3yEqqoekborHmAJD5vf7PWItW3Q/YQKuk3kkqRcKnexPyzyyq5lUgTi8CxxZdaASIOu294wjBhhdyHlXEkVTNJ9JKkj/obF+XiIIp0cBDsOXY9hDQ== pandas-dev@python.org'
+ sshPublicKey: 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDfF0BSddjvZx/z4/2TXsy+RxjwBpgdHkmjtL9WfRHxEw1TchBuEj5vWWcxBNTK+9oVzD/Lca89HAXXrklsfkdAK3LvLfGCxTGpP8t/3CxxFdnSg3EN+4cDGKuDlbeTyzdASdPBOq0GTZjUFekl9ZfFrFJ9SoPpqZ4mmPRPapPrkwTs4xIrBly0eWcISFYgZcG58m65+XQpyyBMbpsO5ZHBBxE8kkWN0yY+gKt5PeeIO82xE+7F+3Qhlc67fKfB4FEitQ5SKrbKyGNNdFtEGcC6CEtD0B0vJxssltQEl5dDWPJP6tH4cIm/J6m28mpSYc5fEBhr75jE4Ybw6NtGgBZEdtFRFlnb91mSiVSjM/HEkV7/xYai+H1Gk+I/8tcl8cf3JCiJSP2glz8bp52+i5it29FUL8ITxdJSo0duUkVm3nZ8cDI6zag+nSSmzdZ1I9Fw7M7RRPHM2zd5+6RskeqamR5lY3Iv+t8Yo8cRX10IiHNF89b+3vI5ZkIKqytrPfrY45jGVMXA6x/whMh94Ac94qm+Do7P3eT/66a1lX0r+UfV6UnfwHE6cZ1ZFX2AzlmSiYMKmTD3hn1GNyHHuvk3Mneanbk4+x+8SjAXIK354zJ8c1Qgk1iEicDvna2IBd94R4tBWjYZ8xH7avmPlhs0HwbjiNOFDc45UXvwIl+D7w== pandas-dev@python.org'
sshKeySecureFile: 'pandas_docs_key'
displayName: 'Install GitHub ssh deployment key'
condition : |
| #26591 made master builds to fail. Looks like there was a problem with the ssh keys. I regenerated them and updated them in the github deployment keys and azure pipelines secret. Updating the settings here.
CC: @jreback
| https://api.github.com/repos/pandas-dev/pandas/pulls/26604 | 2019-06-01T15:15:21Z | 2019-06-01T15:34:58Z | 2019-06-01T15:34:58Z | 2019-06-01T16:09:22Z |
TST/CLN: deduplicate fixture from test_to_latex.py | diff --git a/pandas/conftest.py b/pandas/conftest.py
index 8f71028f51ab4..09fe8e0829fa1 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -12,6 +12,8 @@
import pandas.util._test_decorators as td
import pandas as pd
+from pandas import DataFrame
+import pandas.util.testing as tm
hypothesis.settings.register_profile(
"ci",
@@ -690,3 +692,32 @@ def tick_classes(request):
normalize=st.booleans(),
startingMonth=st.integers(min_value=1, max_value=12)
))
+
+
+@pytest.fixture
+def float_frame():
+ """
+ Fixture for DataFrame of floats with index of unique strings
+
+ Columns are ['A', 'B', 'C', 'D'].
+
+ A B C D
+ P7GACiRnxd -0.465578 -0.361863 0.886172 -0.053465
+ qZKh6afn8n -0.466693 -0.373773 0.266873 1.673901
+ tkp0r6Qble 0.148691 -0.059051 0.174817 1.598433
+ wP70WOCtv8 0.133045 -0.581994 -0.992240 0.261651
+ M2AeYQMnCz -1.207959 -0.185775 0.588206 0.563938
+ QEPzyGDYDo -0.381843 -0.758281 0.502575 -0.565053
+ r78Jwns6dn -0.653707 0.883127 0.682199 0.206159
+ ... ... ... ... ...
+ IHEGx9NO0T -0.277360 0.113021 -1.018314 0.196316
+ lPMj8K27FA -1.313667 -0.604776 -1.305618 -0.863999
+ qa66YMWQa5 1.110525 0.475310 -0.747865 0.032121
+ yOa0ATsmcE -0.431457 0.067094 0.096567 -0.264962
+ 65znX3uRNG 1.528446 0.160416 -0.109635 -0.032987
+ eCOBvKqf3e 0.235281 1.622222 0.781255 0.392871
+ xSucinXxuV -1.263557 0.252799 -0.552247 0.400426
+
+ [30 rows x 4 columns]
+ """
+ return DataFrame(tm.getSeriesData())
diff --git a/pandas/tests/frame/conftest.py b/pandas/tests/frame/conftest.py
index c451cd58f1497..d8a590bc492a4 100644
--- a/pandas/tests/frame/conftest.py
+++ b/pandas/tests/frame/conftest.py
@@ -5,35 +5,6 @@
import pandas.util.testing as tm
-@pytest.fixture
-def float_frame():
- """
- Fixture for DataFrame of floats with index of unique strings
-
- Columns are ['A', 'B', 'C', 'D'].
-
- A B C D
- P7GACiRnxd -0.465578 -0.361863 0.886172 -0.053465
- qZKh6afn8n -0.466693 -0.373773 0.266873 1.673901
- tkp0r6Qble 0.148691 -0.059051 0.174817 1.598433
- wP70WOCtv8 0.133045 -0.581994 -0.992240 0.261651
- M2AeYQMnCz -1.207959 -0.185775 0.588206 0.563938
- QEPzyGDYDo -0.381843 -0.758281 0.502575 -0.565053
- r78Jwns6dn -0.653707 0.883127 0.682199 0.206159
- ... ... ... ... ...
- IHEGx9NO0T -0.277360 0.113021 -1.018314 0.196316
- lPMj8K27FA -1.313667 -0.604776 -1.305618 -0.863999
- qa66YMWQa5 1.110525 0.475310 -0.747865 0.032121
- yOa0ATsmcE -0.431457 0.067094 0.096567 -0.264962
- 65znX3uRNG 1.528446 0.160416 -0.109635 -0.032987
- eCOBvKqf3e 0.235281 1.622222 0.781255 0.392871
- xSucinXxuV -1.263557 0.252799 -0.552247 0.400426
-
- [30 rows x 4 columns]
- """
- return DataFrame(tm.getSeriesData())
-
-
@pytest.fixture
def float_frame_with_na():
"""
diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py
index 5a6511fbd20ee..b9f28ec36d021 100644
--- a/pandas/tests/io/formats/test_to_latex.py
+++ b/pandas/tests/io/formats/test_to_latex.py
@@ -8,19 +8,14 @@
from pandas.util import testing as tm
-@pytest.fixture
-def frame():
- return DataFrame(tm.getSeriesData())
-
-
class TestToLatex:
- def test_to_latex_filename(self, frame):
+ def test_to_latex_filename(self, float_frame):
with tm.ensure_clean('test.tex') as path:
- frame.to_latex(path)
+ float_frame.to_latex(path)
with open(path, 'r') as f:
- assert frame.to_latex() == f.read()
+ assert float_frame.to_latex() == f.read()
# test with utf-8 and encoding option (GH 7061)
df = DataFrame([['au\xdfgangen']])
@@ -35,9 +30,9 @@ def test_to_latex_filename(self, frame):
with codecs.open(path, 'r', encoding='utf-8') as f:
assert df.to_latex() == f.read()
- def test_to_latex(self, frame):
+ def test_to_latex(self, float_frame):
# it works!
- frame.to_latex()
+ float_frame.to_latex()
df = DataFrame({'a': [1, 2], 'b': ['b1', 'b2']})
withindex_result = df.to_latex()
@@ -66,9 +61,9 @@ def test_to_latex(self, frame):
assert withoutindex_result == withoutindex_expected
- def test_to_latex_format(self, frame):
+ def test_to_latex_format(self, float_frame):
# GH Bug #9402
- frame.to_latex(column_format='ccc')
+ float_frame.to_latex(column_format='ccc')
df = DataFrame({'a': [1, 2], 'b': ['b1', 'b2']})
withindex_result = df.to_latex(column_format='ccc')
@@ -389,8 +384,8 @@ def test_to_latex_special_escape(self):
"""
assert escaped_result == escaped_expected
- def test_to_latex_longtable(self, frame):
- frame.to_latex(longtable=True)
+ def test_to_latex_longtable(self, float_frame):
+ float_frame.to_latex(longtable=True)
df = DataFrame({'a': [1, 2], 'b': ['b1', 'b2']})
withindex_result = df.to_latex(longtable=True)
@@ -535,9 +530,9 @@ def test_to_latex_specified_header(self):
with pytest.raises(ValueError):
df.to_latex(header=['A'])
- def test_to_latex_decimal(self, frame):
+ def test_to_latex_decimal(self, float_frame):
# GH 12031
- frame.to_latex()
+ float_frame.to_latex()
df = DataFrame({'a': [1.0, 2.1], 'b': ['b1', 'b2']})
withindex_result = df.to_latex(decimal=',')
| this PR is basically just to promote the float_frame fixture to top-level conftest.
once there, there is opportunities to re-use by fixturising current instances of
```
df = DataFrame(tm.getSeriesData())
```
also allows removing duplicate fixture from pandas/tests/io/formats/test_to_latex.py
so this is just a move for now, fixturization in follow-on PRs | https://api.github.com/repos/pandas-dev/pandas/pulls/26603 | 2019-06-01T15:04:51Z | 2019-06-02T23:13:09Z | 2019-06-02T23:13:09Z | 2019-06-03T11:15:20Z |
MAINT: Condense TIMEZONE_IDS construction | diff --git a/pandas/conftest.py b/pandas/conftest.py
index 09fe8e0829fa1..c4285e9db038a 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -378,12 +378,7 @@ def unique_nulls_fixture(request):
FixedOffset(0), FixedOffset(-300), timezone.utc,
timezone(timedelta(hours=1)),
timezone(timedelta(hours=-1), name='foo')]
-TIMEZONE_IDS = ['None', 'UTC', 'US/Eastern', 'Asia/Tokyp',
- 'dateutil/US/Pacific', 'dateutil/Asia/Singapore',
- 'dateutil.tz.tzutz()', 'dateutil.tz.tzlocal()',
- 'pytz.FixedOffset(300)', 'pytz.FixedOffset(0)',
- 'pytz.FixedOffset(-300)', 'datetime.timezone.utc',
- 'datetime.timezone.+1', 'datetime.timezone.-1.named']
+TIMEZONE_IDS = [repr(i) for i in TIMEZONES]
@td.parametrize_fixture_doc(str(TIMEZONE_IDS))
| Follow-up to #26596 | https://api.github.com/repos/pandas-dev/pandas/pulls/26600 | 2019-06-01T06:33:07Z | 2019-06-06T14:50:05Z | 2019-06-06T14:50:05Z | 2019-06-06T18:11:24Z |
CLN: remove sample_time attributes from benchmarks | diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py
index 0fdf46e7c64de..896a20bae2069 100644
--- a/asv_bench/benchmarks/index_object.py
+++ b/asv_bench/benchmarks/index_object.py
@@ -52,7 +52,6 @@ def time_is_dates_only(self):
class Ops:
- sample_time = 0.2
params = ['float', 'int']
param_names = ['dtype']
diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py
index 2532d326dff4b..033b466c8b9be 100644
--- a/asv_bench/benchmarks/rolling.py
+++ b/asv_bench/benchmarks/rolling.py
@@ -4,7 +4,6 @@
class Methods:
- sample_time = 0.2
params = (['DataFrame', 'Series'],
[10, 1000],
['int', 'float'],
@@ -23,7 +22,6 @@ def time_rolling(self, constructor, window, dtype, method):
class ExpandingMethods:
- sample_time = 0.2
params = (['DataFrame', 'Series'],
['int', 'float'],
['median', 'mean', 'max', 'min', 'std', 'count', 'skew', 'kurt',
@@ -41,7 +39,6 @@ def time_expanding(self, constructor, dtype, method):
class EWMMethods:
- sample_time = 0.2
params = (['DataFrame', 'Series'],
[10, 1000],
['int', 'float'],
@@ -58,7 +55,6 @@ def time_ewm(self, constructor, window, dtype, method):
class VariableWindowMethods(Methods):
- sample_time = 0.2
params = (['DataFrame', 'Series'],
['50s', '1h', '1d'],
['int', 'float'],
@@ -75,7 +71,6 @@ def setup(self, constructor, window, dtype, method):
class Pairwise:
- sample_time = 0.2
params = ([10, 1000, None],
['corr', 'cov'],
[True, False])
@@ -95,7 +90,6 @@ def time_pairwise(self, window, method, pairwise):
class Quantile:
- sample_time = 0.2
params = (['DataFrame', 'Series'],
[10, 1000],
['int', 'float'],
| Very minor benchmark cleanup now that I was on it...
These attributes appear to have been brought in by direct replacement of a
deprecated ASV attribute goal_time -> sample_time, but the two have
different semantics (the value sample_time=0.2 is 20x the default).
Increasing this from the default value is probably not necessary and
increases runtime (here 3min vs 17min for rolling.*), so it's better to restore it to defaults. | https://api.github.com/repos/pandas-dev/pandas/pulls/26598 | 2019-05-31T17:57:53Z | 2019-06-01T14:08:20Z | 2019-06-01T14:08:20Z | 2019-06-01T14:08:37Z |
TST: prepare conftest for #25637 | diff --git a/pandas/conftest.py b/pandas/conftest.py
index 3c411f8ba3e31..8f71028f51ab4 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -376,10 +376,16 @@ def unique_nulls_fixture(request):
FixedOffset(0), FixedOffset(-300), timezone.utc,
timezone(timedelta(hours=1)),
timezone(timedelta(hours=-1), name='foo')]
+TIMEZONE_IDS = ['None', 'UTC', 'US/Eastern', 'Asia/Tokyp',
+ 'dateutil/US/Pacific', 'dateutil/Asia/Singapore',
+ 'dateutil.tz.tzutz()', 'dateutil.tz.tzlocal()',
+ 'pytz.FixedOffset(300)', 'pytz.FixedOffset(0)',
+ 'pytz.FixedOffset(-300)', 'datetime.timezone.utc',
+ 'datetime.timezone.+1', 'datetime.timezone.-1.named']
-@td.parametrize_fixture_doc(str(TIMEZONES))
-@pytest.fixture(params=TIMEZONES)
+@td.parametrize_fixture_doc(str(TIMEZONE_IDS))
+@pytest.fixture(params=TIMEZONES, ids=TIMEZONE_IDS)
def tz_naive_fixture(request):
"""
Fixture for trying timezones including default (None): {0}
@@ -387,8 +393,8 @@ def tz_naive_fixture(request):
return request.param
-@td.parametrize_fixture_doc(str(TIMEZONES[1:]))
-@pytest.fixture(params=TIMEZONES[1:])
+@td.parametrize_fixture_doc(str(TIMEZONE_IDS[1:]))
+@pytest.fixture(params=TIMEZONES[1:], ids=TIMEZONE_IDS[1:])
def tz_aware_fixture(request):
"""
Fixture for trying explicit timezones: {0}
@@ -398,6 +404,8 @@ def tz_aware_fixture(request):
# ----------------------------------------------------------------
# Dtypes
+# ----------------------------------------------------------------
+
UNSIGNED_INT_DTYPES = ["uint8", "uint16", "uint32", "uint64"]
UNSIGNED_EA_INT_DTYPES = ["UInt8", "UInt16", "UInt32", "UInt64"]
SIGNED_INT_DTYPES = [int, "int8", "int16", "int32", "int64"]
@@ -409,8 +417,8 @@ def tz_aware_fixture(request):
COMPLEX_DTYPES = [complex, "complex64", "complex128"]
STRING_DTYPES = [str, 'str', 'U']
-DATETIME_DTYPES = ['datetime64[ns]', 'M8[ns]']
-TIMEDELTA_DTYPES = ['timedelta64[ns]', 'm8[ns]']
+DATETIME64_DTYPES = ['datetime64[ns]', 'M8[ns]']
+TIMEDELTA64_DTYPES = ['timedelta64[ns]', 'm8[ns]']
BOOL_DTYPES = [bool, 'bool']
BYTES_DTYPES = [bytes, 'bytes']
@@ -418,7 +426,7 @@ def tz_aware_fixture(request):
ALL_REAL_DTYPES = FLOAT_DTYPES + ALL_INT_DTYPES
ALL_NUMPY_DTYPES = (ALL_REAL_DTYPES + COMPLEX_DTYPES + STRING_DTYPES +
- DATETIME_DTYPES + TIMEDELTA_DTYPES + BOOL_DTYPES +
+ DATETIME64_DTYPES + TIMEDELTA64_DTYPES + BOOL_DTYPES +
OBJECT_DTYPES + BYTES_DTYPES)
| Split off from #25637 at the [request](https://github.com/pandas-dev/pandas/pull/25637#discussion_r289447555) of @gfyoung
Relevant discussions:
https://github.com/pandas-dev/pandas/pull/25637#discussion_r289042255
https://github.com/pandas-dev/pandas/pull/25637#discussion_r289441644
| https://api.github.com/repos/pandas-dev/pandas/pulls/26596 | 2019-05-31T16:01:11Z | 2019-06-01T00:17:54Z | 2019-06-01T00:17:54Z | 2019-06-01T15:14:11Z |
Test conda 4.7.1 | diff --git a/ci/azure/windows.yml b/ci/azure/windows.yml
index 6d4afccb57865..20cad1bb4af96 100644
--- a/ci/azure/windows.yml
+++ b/ci/azure/windows.yml
@@ -21,7 +21,9 @@ jobs:
displayName: 'Add conda to PATH'
- script: conda update -q -n base conda
displayName: Update conda
- - script: conda env create -q --file ci\\deps\\azure-windows-$(CONDA_PY).yaml
+ - script: |
+ call activate
+ conda env create -q --file ci\\deps\\azure-windows-$(CONDA_PY).yaml
displayName: 'Create anaconda environment'
- script: |
call activate pandas-dev
diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml
index badf4e6932da8..75e3348adab7c 100644
--- a/ci/deps/travis-36-locale.yaml
+++ b/ci/deps/travis-36-locale.yaml
@@ -8,24 +8,22 @@ dependencies:
- python-blosc
- cython>=0.28.2
- fastparquet=0.2.1
- - gcsfs=0.1.0
+ - gcsfs=0.2.2
- html5lib
- ipython
- jinja2
- - lxml=3.7.0
- - matplotlib=3.0.0
+ - lxml=3.8.0
+ - matplotlib=3.0.*
- nomkl
- numexpr
- numpy
- openpyxl
- pandas-gbq=0.8.0
- psycopg2=2.6.2
- - pymysql=0.7.9
+ - pymysql=0.7.11
- pytables
- python-dateutil
- # cannot go past python=3.6.6 for matplotlib=3.0.0 due to
- # https://github.com/matplotlib/matplotlib/issues/12626
- - python=3.6.6
+ - python=3.6.*
- pytz
- s3fs=0.0.8
- scipy
diff --git a/doc/source/install.rst b/doc/source/install.rst
index ee4b36f898e31..013a27c980e97 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -276,15 +276,15 @@ SciPy 0.19.0 Miscellaneous statistical functions
XLsxWriter 0.9.8 Excel writing
blosc Compression for msgpack
fastparquet 0.2.1 Parquet reading / writing
-gcsfs 0.1.0 Google Cloud Storage access
+gcsfs 0.2.2 Google Cloud Storage access
html5lib HTML parser for read_html (see :ref:`note <optional_html>`)
-lxml HTML parser for read_html (see :ref:`note <optional_html>`)
+lxml 3.8.0 HTML parser for read_html (see :ref:`note <optional_html>`)
matplotlib 2.2.2 Visualization
openpyxl 2.4.8 Reading / writing for xlsx files
pandas-gbq 0.8.0 Google Big Query access
psycopg2 PostgreSQL engine for sqlalchemy
pyarrow 0.9.0 Parquet and feather reading / writing
-pymysql MySQL engine for sqlalchemy
+pymysql 0.7.11 MySQL engine for sqlalchemy
pyreadstat SPSS files (.sav) reading
pytables 3.4.2 HDF5 reading / writing
qtpy Clipboard I/O
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index a58cdc8c93ab7..18a3785867714 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -455,12 +455,18 @@ Optional libraries below the lowest tested version may still work, but are not c
+-----------------+-----------------+
| fastparquet | 0.2.1 |
+-----------------+-----------------+
+| gcsfs | 0.2.2 |
++-----------------+-----------------+
+| lxml | 3.8.0 |
++-----------------+-----------------+
| matplotlib | 2.2.2 |
+-----------------+-----------------+
| openpyxl | 2.4.8 |
+-----------------+-----------------+
| pyarrow | 0.9.0 |
+-----------------+-----------------+
+| pymysql | 0.7.1 |
++-----------------+-----------------+
| pytables | 3.4.2 |
+-----------------+-----------------+
| scipy | 0.19.0 |
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index 875edb3d3f1dd..31746dc3d6c16 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -9,7 +9,8 @@
"bs4": "4.6.0",
"bottleneck": "1.2.1",
"fastparquet": "0.2.1",
- "gcsfs": "0.1.0",
+ "gcsfs": "0.2.2",
+ "lxml.etree": "3.8.0",
"matplotlib": "2.2.2",
"numexpr": "2.6.2",
"openpyxl": "2.4.8",
diff --git a/pandas/io/html.py b/pandas/io/html.py
index 2e2327a35f2c7..15b9d25f6be6c 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -40,7 +40,7 @@ def _importers():
on_version="ignore")
_HAS_BS4 = bs4 is not None
- lxml = import_optional_dependency("lxml", raise_on_missing=False,
+ lxml = import_optional_dependency("lxml.etree", raise_on_missing=False,
on_version="ignore")
_HAS_LXML = lxml is not None
| Testing conda 4.7.x | https://api.github.com/repos/pandas-dev/pandas/pulls/26595 | 2019-05-31T14:44:43Z | 2019-06-26T11:21:37Z | 2019-06-26T11:21:37Z | 2019-06-26T12:17:57Z |
TST: add concrete examples of dataframe fixtures to docstrings | diff --git a/pandas/tests/frame/conftest.py b/pandas/tests/frame/conftest.py
index 27c0e070c10c2..c451cd58f1497 100644
--- a/pandas/tests/frame/conftest.py
+++ b/pandas/tests/frame/conftest.py
@@ -11,6 +11,25 @@ def float_frame():
Fixture for DataFrame of floats with index of unique strings
Columns are ['A', 'B', 'C', 'D'].
+
+ A B C D
+ P7GACiRnxd -0.465578 -0.361863 0.886172 -0.053465
+ qZKh6afn8n -0.466693 -0.373773 0.266873 1.673901
+ tkp0r6Qble 0.148691 -0.059051 0.174817 1.598433
+ wP70WOCtv8 0.133045 -0.581994 -0.992240 0.261651
+ M2AeYQMnCz -1.207959 -0.185775 0.588206 0.563938
+ QEPzyGDYDo -0.381843 -0.758281 0.502575 -0.565053
+ r78Jwns6dn -0.653707 0.883127 0.682199 0.206159
+ ... ... ... ... ...
+ IHEGx9NO0T -0.277360 0.113021 -1.018314 0.196316
+ lPMj8K27FA -1.313667 -0.604776 -1.305618 -0.863999
+ qa66YMWQa5 1.110525 0.475310 -0.747865 0.032121
+ yOa0ATsmcE -0.431457 0.067094 0.096567 -0.264962
+ 65znX3uRNG 1.528446 0.160416 -0.109635 -0.032987
+ eCOBvKqf3e 0.235281 1.622222 0.781255 0.392871
+ xSucinXxuV -1.263557 0.252799 -0.552247 0.400426
+
+ [30 rows x 4 columns]
"""
return DataFrame(tm.getSeriesData())
@@ -21,6 +40,25 @@ def float_frame_with_na():
Fixture for DataFrame of floats with index of unique strings
Columns are ['A', 'B', 'C', 'D']; some entries are missing
+
+ A B C D
+ ABwBzA0ljw -1.128865 -0.897161 0.046603 0.274997
+ DJiRzmbyQF 0.728869 0.233502 0.722431 -0.890872
+ neMgPD5UBF 0.486072 -1.027393 -0.031553 1.449522
+ 0yWA4n8VeX -1.937191 -1.142531 0.805215 -0.462018
+ 3slYUbbqU1 0.153260 1.164691 1.489795 -0.545826
+ soujjZ0A08 NaN NaN NaN NaN
+ 7W6NLGsjB9 NaN NaN NaN NaN
+ ... ... ... ... ...
+ uhfeaNkCR1 -0.231210 -0.340472 0.244717 -0.901590
+ n6p7GYuBIV -0.419052 1.922721 -0.125361 -0.727717
+ ZhzAeY6p1y 1.234374 -1.425359 -0.827038 -0.633189
+ uWdPsORyUh 0.046738 -0.980445 -1.102965 0.605503
+ 3DJA6aN590 -0.091018 -1.684734 -1.100900 0.215947
+ 2GBPAzdbMk -2.883405 -1.021071 1.209877 1.633083
+ sHadBoyVHw -2.223032 -0.326384 0.258931 0.245517
+
+ [30 rows x 4 columns]
"""
df = DataFrame(tm.getSeriesData())
# set some NAs
@@ -35,6 +73,25 @@ def bool_frame_with_na():
Fixture for DataFrame of booleans with index of unique strings
Columns are ['A', 'B', 'C', 'D']; some entries are missing
+
+ A B C D
+ zBZxY2IDGd False False False False
+ IhBWBMWllt False True True True
+ ctjdvZSR6R True False True True
+ AVTujptmxb False True False True
+ G9lrImrSWq False False False True
+ sFFwdIUfz2 NaN NaN NaN NaN
+ s15ptEJnRb NaN NaN NaN NaN
+ ... ... ... ... ...
+ UW41KkDyZ4 True True False False
+ l9l6XkOdqV True False False False
+ X2MeZfzDYA False True False False
+ xWkIKU7vfX False True False True
+ QOhL6VmpGU False False False True
+ 22PwkRJdat False True False False
+ kfboQ3VeIK True False True False
+
+ [30 rows x 4 columns]
"""
df = DataFrame(tm.getSeriesData()) > 0
df = df.astype(object)
@@ -50,6 +107,25 @@ def int_frame():
Fixture for DataFrame of ints with index of unique strings
Columns are ['A', 'B', 'C', 'D']
+
+ A B C D
+ vpBeWjM651 1 0 1 0
+ 5JyxmrP1En -1 0 0 0
+ qEDaoD49U2 -1 1 0 0
+ m66TkTfsFe 0 0 0 0
+ EHPaNzEUFm -1 0 -1 0
+ fpRJCevQhi 2 0 0 0
+ OlQvnmfi3Q 0 0 -2 0
+ ... .. .. .. ..
+ uB1FPlz4uP 0 0 0 1
+ EcSe6yNzCU 0 0 -1 0
+ L50VudaiI8 -1 1 -2 0
+ y3bpw4nwIp 0 -1 0 0
+ H0RdLLwrCT 1 1 0 0
+ rY82K0vMwm 0 0 0 0
+ 1OPIUjnkjk 2 0 0 0
+
+ [30 rows x 4 columns]
"""
df = DataFrame({k: v.astype(int) for k, v in tm.getSeriesData().items()})
# force these all to int64 to avoid platform testing issues
@@ -62,6 +138,25 @@ def datetime_frame():
Fixture for DataFrame of floats with DatetimeIndex
Columns are ['A', 'B', 'C', 'D']
+
+ A B C D
+ 2000-01-03 -1.122153 0.468535 0.122226 1.693711
+ 2000-01-04 0.189378 0.486100 0.007864 -1.216052
+ 2000-01-05 0.041401 -0.835752 -0.035279 -0.414357
+ 2000-01-06 0.430050 0.894352 0.090719 0.036939
+ 2000-01-07 -0.620982 -0.668211 -0.706153 1.466335
+ 2000-01-10 -0.752633 0.328434 -0.815325 0.699674
+ 2000-01-11 -2.236969 0.615737 -0.829076 -1.196106
+ ... ... ... ... ...
+ 2000-02-03 1.642618 -0.579288 0.046005 1.385249
+ 2000-02-04 -0.544873 -1.160962 -0.284071 -1.418351
+ 2000-02-07 -2.656149 -0.601387 1.410148 0.444150
+ 2000-02-08 -1.201881 -1.289040 0.772992 -1.445300
+ 2000-02-09 1.377373 0.398619 1.008453 -0.928207
+ 2000-02-10 0.473194 -0.636677 0.984058 0.511519
+ 2000-02-11 -0.965556 0.408313 -1.312844 -0.381948
+
+ [30 rows x 4 columns]
"""
return DataFrame(tm.getTimeSeriesData())
@@ -72,6 +167,25 @@ def float_string_frame():
Fixture for DataFrame of floats and strings with index of unique strings
Columns are ['A', 'B', 'C', 'D', 'foo'].
+
+ A B C D foo
+ w3orJvq07g -1.594062 -1.084273 -1.252457 0.356460 bar
+ PeukuVdmz2 0.109855 -0.955086 -0.809485 0.409747 bar
+ ahp2KvwiM8 -1.533729 -0.142519 -0.154666 1.302623 bar
+ 3WSJ7BUCGd 2.484964 0.213829 0.034778 -2.327831 bar
+ khdAmufk0U -0.193480 -0.743518 -0.077987 0.153646 bar
+ LE2DZiFlrE -0.193566 -1.343194 -0.107321 0.959978 bar
+ HJXSJhVn7b 0.142590 1.257603 -0.659409 -0.223844 bar
+ ... ... ... ... ... ...
+ 9a1Vypttgw -1.316394 1.601354 0.173596 1.213196 bar
+ h5d1gVFbEy 0.609475 1.106738 -0.155271 0.294630 bar
+ mK9LsTQG92 1.303613 0.857040 -1.019153 0.369468 bar
+ oOLksd9gKH 0.558219 -0.134491 -0.289869 -0.951033 bar
+ 9jgoOjKyHg 0.058270 -0.496110 -0.413212 -0.852659 bar
+ jZLDHclHAO 0.096298 1.267510 0.549206 -0.005235 bar
+ lR0nxDp1C2 -2.119350 -0.794384 0.544118 0.145849 bar
+
+ [30 rows x 5 columns]
"""
df = DataFrame(tm.getSeriesData())
df['foo'] = 'bar'
@@ -84,6 +198,25 @@ def mixed_float_frame():
Fixture for DataFrame of different float types with index of unique strings
Columns are ['A', 'B', 'C', 'D'].
+
+ A B C D
+ GI7bbDaEZe -0.237908 -0.246225 -0.468506 0.752993
+ KGp9mFepzA -1.140809 -0.644046 -1.225586 0.801588
+ VeVYLAb1l2 -1.154013 -1.677615 0.690430 -0.003731
+ kmPME4WKhO 0.979578 0.998274 -0.776367 0.897607
+ CPyopdXTiz 0.048119 -0.257174 0.836426 0.111266
+ 0kJZQndAj0 0.274357 -0.281135 -0.344238 0.834541
+ tqdwQsaHG8 -0.979716 -0.519897 0.582031 0.144710
+ ... ... ... ... ...
+ 7FhZTWILQj -2.906357 1.261039 -0.780273 -0.537237
+ 4pUDPM4eGq -2.042512 -0.464382 -0.382080 1.132612
+ B8dUgUzwTi -1.506637 -0.364435 1.087891 0.297653
+ hErlVYjVv9 1.477453 -0.495515 -0.713867 1.438427
+ 1BKN3o7YLs 0.127535 -0.349812 -0.881836 0.489827
+ 9S4Ekn7zga 1.445518 -2.095149 0.031982 0.373204
+ xN1dNn6OV6 1.425017 -0.983995 -0.363281 -0.224502
+
+ [30 rows x 4 columns]
"""
df = DataFrame(tm.getSeriesData())
df.A = df.A.astype('float32')
@@ -99,6 +232,25 @@ def mixed_int_frame():
Fixture for DataFrame of different int types with index of unique strings
Columns are ['A', 'B', 'C', 'D'].
+
+ A B C D
+ mUrCZ67juP 0 1 2 2
+ rw99ACYaKS 0 1 0 0
+ 7QsEcpaaVU 0 1 1 1
+ xkrimI2pcE 0 1 0 0
+ dz01SuzoS8 0 1 255 255
+ ccQkqOHX75 -1 1 0 0
+ DN0iXaoDLd 0 1 0 0
+ ... .. .. ... ...
+ Dfb141wAaQ 1 1 254 254
+ IPD8eQOVu5 0 1 0 0
+ CcaKulsCmv 0 1 0 0
+ rIBa8gu7E5 0 1 0 0
+ RP6peZmh5o 0 1 1 1
+ NMb9pipQWQ 0 1 0 0
+ PqgbJEzjib 0 1 3 3
+
+ [30 rows x 4 columns]
"""
df = DataFrame({k: v.astype(int) for k, v in tm.getSeriesData().items()})
df.A = df.A.astype('int32')
@@ -114,6 +266,11 @@ def timezone_frame():
Fixture for DataFrame of date_range Series with different time zones
Columns are ['A', 'B', 'C']; some entries are missing
+
+ A B C
+ 0 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00+01:00
+ 1 2013-01-02 NaT NaT
+ 2 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-03 00:00:00+01:00
"""
df = DataFrame({'A': date_range('20130101', periods=3),
'B': date_range('20130101', periods=3,
@@ -131,6 +288,11 @@ def simple_frame():
Fixture for simple 3x3 DataFrame
Columns are ['one', 'two', 'three'], index is ['a', 'b', 'c'].
+
+ one two three
+ a 1.0 2.0 3.0
+ b 4.0 5.0 6.0
+ c 7.0 8.0 9.0
"""
arr = np.array([[1., 2., 3.],
[4., 5., 6.],
@@ -147,6 +309,13 @@ def frame_of_index_cols():
Columns are ['A', 'B', 'C', 'D', 'E', ('tuple', 'as', 'label')];
'A' & 'B' contain duplicates (but are jointly unique), the rest are unique.
+
+ A B C D E (tuple, as, label)
+ 0 foo one a 0.608477 -0.012500 -1.664297
+ 1 foo two b -0.633460 0.249614 -0.364411
+ 2 foo three c 0.615256 2.154968 -0.834666
+ 3 bar one d 0.234246 1.085675 0.718445
+ 4 bar two e 0.533841 -0.005702 -3.533912
"""
df = DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar'],
'B': ['one', 'two', 'three', 'one', 'two'],
| add concrete examples of dataframe fixtures to docstrings to make it easier when looking for fixtures to reuse.
and also appear when using `pytest --fixtures` and `pytest --fixtures-per-test` so could be an aid to debugging
```
------------------ fixtures used by test_set_index_directly -------------------
----------------- (pandas\tests\frame\test_alter_axes.py:20) ------------------
add_imports
no docstring available
configure_tests
no docstring available
doctest_namespace
Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
float_string_frame
Fixture for DataFrame of floats and strings with index of unique strings
Columns are ['A', 'B', 'C', 'D', 'foo'].
A B C D foo
w3orJvq07g -1.594062 -1.084273 -1.252457 0.356460 bar
PeukuVdmz2 0.109855 -0.955086 -0.809485 0.409747 bar
ahp2KvwiM8 -1.533729 -0.142519 -0.154666 1.302623 bar
3WSJ7BUCGd 2.484964 0.213829 0.034778 -2.327831 bar
khdAmufk0U -0.193480 -0.743518 -0.077987 0.153646 bar
LE2DZiFlrE -0.193566 -1.343194 -0.107321 0.959978 bar
HJXSJhVn7b 0.142590 1.257603 -0.659409 -0.223844 bar
... ... ... ... ... ...
9a1Vypttgw -1.316394 1.601354 0.173596 1.213196 bar
h5d1gVFbEy 0.609475 1.106738 -0.155271 0.294630 bar
mK9LsTQG92 1.303613 0.857040 -1.019153 0.369468 bar
oOLksd9gKH 0.558219 -0.134491 -0.289869 -0.951033 bar
9jgoOjKyHg 0.058270 -0.496110 -0.413212 -0.852659 bar
jZLDHclHAO 0.096298 1.267510 0.549206 -0.005235 bar
lR0nxDp1C2 -2.119350 -0.794384 0.544118 0.145849 bar
[30 rows x 5 columns]
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/26593 | 2019-05-31T14:22:30Z | 2019-06-01T14:09:28Z | 2019-06-01T14:09:28Z | 2019-06-03T11:16:28Z |
CI/DOC: Building documentation with azure | diff --git a/.travis.yml b/.travis.yml
index ce8817133a477..90dd904e6cb1e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -51,14 +51,14 @@ matrix:
# In allow_failures
- dist: trusty
env:
- - JOB="3.6, doc" ENV_FILE="ci/deps/travis-36-doc.yaml" DOC=true
+ - JOB="3.6, doc" ENV_FILE="environment.yml" DOC=true
allow_failures:
- dist: trusty
env:
- JOB="3.6, slow" ENV_FILE="ci/deps/travis-36-slow.yaml" PATTERN="slow"
- dist: trusty
env:
- - JOB="3.6, doc" ENV_FILE="ci/deps/travis-36-doc.yaml" DOC=true
+ - JOB="3.6, doc" ENV_FILE="environment.yml" DOC=true
before_install:
- echo "before_install"
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 17eaee5458af8..9f83917024049 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -15,7 +15,7 @@ jobs:
name: Windows
vmImage: vs2017-win2016
-- job: 'Checks_and_doc'
+- job: 'Checks'
pool:
vmImage: ubuntu-16.04
timeoutInMinutes: 90
@@ -116,3 +116,63 @@ jobs:
fi
displayName: 'Running benchmarks'
condition: true
+
+- job: 'Docs'
+ pool:
+ vmImage: ubuntu-16.04
+ timeoutInMinutes: 90
+ steps:
+ - script: |
+ echo '##vso[task.setvariable variable=CONDA_ENV]pandas-dev'
+ echo '##vso[task.setvariable variable=ENV_FILE]environment.yml'
+ displayName: 'Setting environment variables'
+
+ - script: |
+ export PATH=$HOME/miniconda3/bin:$PATH
+ sudo apt-get install -y libc6-dev-i386
+ ci/setup_env.sh
+ displayName: 'Setup environment and build pandas'
+
+ - script: |
+ export PATH=$HOME/miniconda3/bin:$PATH
+ source activate pandas-dev
+ doc/make.py
+ displayName: 'Build documentation'
+
+ - script: |
+ cd doc/build/html
+ git init
+ touch .nojekyll
+ git add --all .
+ git config user.email "pandas-dev@python.org"
+ git config user.name "pandas-docs-bot"
+ git commit -m "pandas documentation in master"
+ displayName: 'Create git repo for docs build'
+ condition : |
+ and(not(eq(variables['Build.Reason'], 'PullRequest')),
+ eq(variables['Build.SourceBranch'], 'refs/heads/master'))
+
+ # This task to work requires next steps:
+ # 1. Got to "Library > Secure files" in the azure-pipelines dashboard: https://dev.azure.com/pandas-dev/pandas/_library?itemType=SecureFiles
+ # 2. Click on "+ Secure file"
+ # 3. Upload the private key (the name of the file must match with the specified in "sshKeySecureFile" input below, "pandas_docs_key")
+ # 4. Click on file name after it is created, tick the box "Authorize for use in all pipelines" and save
+ # 5. The public key specified in "sshPublicKey" is the pair of the uploaded private key, and needs to be specified as a deploy key of the repo where the docs will be pushed: https://github.com/pandas-dev/pandas-dev.github.io/settings/keys
+ - task: InstallSSHKey@0
+ inputs:
+ hostName: 'github.com'
+ sshPublicKey: 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDHmz3l/EdqrgNxEUKkwDUuUcLv91unig03pYFGO/DMIgCmPdMG96zAgfnESd837Rm0wSSqylwSzkRJt5MV/TpFlcVifDLDQmUhqCeO8Z6dLl/oe35UKmyYICVwcvQTAaHNnYRpKC5IUlTh0JEtw9fGlnp1Ta7U1ENBLbKdpywczElhZu+hOQ892zqOj3CwA+U2329/d6cd7YnqIKoFN9DWT3kS5K6JE4IoBfQEVekIOs23bKjNLvPoOmi6CroAhu/K8j+NCWQjge5eJf2x/yTnIIP1PlEcXoHIr8io517posIx3TBup+CN8bNS1PpDW3jyD3ttl1uoBudjOQrobNnJeR6Rn67DRkG6IhSwr3BWj8alwUG5mTdZzwV5Pa9KZFdIiqX7NoDGg+itsR39QCn0thK8lGRNSR8KrWC1PSjecwelKBO7uQ7rnk/rkrZdBWR4oEA8YgNH8tirUw5WfOr5a0AIaJicKxGKNdMxZt+zmC+bS7F4YCOGIm9KHa43RrKhoGRhRf9fHHHKUPwFGqtWG4ykcUgoamDOURJyepesBAO3FiRE9rLU6ILbB3yEqqoekborHmAJD5vf7PWItW3Q/YQKuk3kkqRcKnexPyzyyq5lUgTi8CxxZdaASIOu294wjBhhdyHlXEkVTNJ9JKkj/obF+XiIIp0cBDsOXY9hDQ== pandas-dev@python.org'
+ sshKeySecureFile: 'pandas_docs_key'
+ displayName: 'Install GitHub ssh deployment key'
+ condition : |
+ and(not(eq(variables['Build.Reason'], 'PullRequest')),
+ eq(variables['Build.SourceBranch'], 'refs/heads/master'))
+
+ - script: |
+ cd doc/build/html
+ git remote add origin git@github.com:pandas-dev/pandas-dev.github.io.git
+ git push origin master -f
+ displayName: 'Publish docs to GitHub pages'
+ condition : |
+ and(not(eq(variables['Build.Reason'], 'PullRequest')),
+ eq(variables['Build.SourceBranch'], 'refs/heads/master'))
diff --git a/ci/deps/travis-36-doc.yaml b/ci/deps/travis-36-doc.yaml
deleted file mode 100644
index 9d6cbd82fdc05..0000000000000
--- a/ci/deps/travis-36-doc.yaml
+++ /dev/null
@@ -1,46 +0,0 @@
-name: pandas-dev
-channels:
- - defaults
- - conda-forge
-dependencies:
- - beautifulsoup4
- - bottleneck
- - cython>=0.28.2
- - fastparquet>=0.2.1
- - gitpython
- - html5lib
- - hypothesis>=3.58.0
- - ipykernel
- - ipython
- - ipywidgets
- - lxml
- - matplotlib
- - nbconvert>=5.4.1
- - nbformat
- - nbsphinx
- - notebook>=5.7.5
- - numexpr
- - numpy
- - numpydoc
- - openpyxl
- - pandoc
- - pyarrow
- - pyqt
- - pytables
- - python-dateutil
- - python-snappy
- - python=3.6.*
- - pytz
- - scipy
- - seaborn
- - sphinx
- - sqlalchemy
- - statsmodels
- - xarray
- - xlrd
- - xlsxwriter
- - xlwt
- # universal
- - pytest>=4.0.2
- - pytest-xdist
- - isort
| - [X] xref #22766, #26574
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26591 | 2019-05-31T12:36:54Z | 2019-06-01T14:12:41Z | 2019-06-01T14:12:40Z | 2019-06-02T15:29:18Z |
remove outdated gtk package from code | diff --git a/doc/source/install.rst b/doc/source/install.rst
index b3b5945cc515e..98443ede2e965 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -281,7 +281,6 @@ Optional Dependencies
`qtpy <https://github.com/spyder-ide/qtpy>`__ (requires PyQt or PySide),
`PyQt5 <https://www.riverbankcomputing.com/software/pyqt/download5>`__,
`PyQt4 <http://www.riverbankcomputing.com/software/pyqt/download>`__,
- `pygtk <http://www.pygtk.org/>`__,
`xsel <http://www.vergenet.net/~conrad/software/xsel/>`__, or
`xclip <https://github.com/astrand/xclip/>`__: necessary to use
:func:`~pandas.read_clipboard`. Most package managers on Linux distributions will have ``xclip`` and/or ``xsel`` immediately available for installation.
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index 88d8ccbbe036e..4aacb6fa1e278 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -3272,7 +3272,7 @@ We can see that we got the same content back, which we had earlier written to th
.. note::
- You may need to install xclip or xsel (with gtk, PyQt5, PyQt4 or qtpy) on Linux to use these methods.
+ You may need to install xclip or xsel (with PyQt5, PyQt4 or qtpy) on Linux to use these methods.
.. _io.pickle:
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 89a9da4a73b35..65ef332b4122c 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -334,6 +334,7 @@ Other API Changes
- The ``arg`` argument in :meth:`pandas.core.groupby.DataFrameGroupBy.agg` has been renamed to ``func`` (:issue:`26089`)
- The ``arg`` argument in :meth:`pandas.core.window._Window.aggregate` has been renamed to ``func`` (:issue:`26372`)
- Most Pandas classes had a ``__bytes__`` method, which was used for getting a python2-style bytestring representation of the object. This method has been removed as a part of dropping Python2 (:issue:`26447`)
+- Removed support of gtk package for clipboards (:issue:`26563`)
.. _whatsnew_0250.deprecations:
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 87db069d94893..9c671b2d3bb34 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2679,7 +2679,7 @@ def to_clipboard(self, excel=True, sep=None, **kwargs):
-----
Requirements for your platform.
- - Linux : `xclip`, or `xsel` (with `gtk` or `PyQt4` modules)
+ - Linux : `xclip`, or `xsel` (with `PyQt4` modules)
- Windows : none
- OS X : none
diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py
index b76a843e3e7f2..2063978c76c5a 100644
--- a/pandas/io/clipboard/__init__.py
+++ b/pandas/io/clipboard/__init__.py
@@ -18,21 +18,19 @@
On Linux, install xclip or xsel via package manager. For example, in Debian:
sudo apt-get install xclip
-Otherwise on Linux, you will need the gtk, qtpy or PyQt modules installed.
+Otherwise on Linux, you will need the qtpy or PyQt modules installed.
qtpy also requires a python-qt-bindings module: PyQt4, PyQt5, PySide, PySide2
-gtk and PyQt4 modules are not available for Python 3,
-and this module does not work with PyGObject yet.
+This module does not work with PyGObject yet.
"""
__version__ = '1.5.27'
import platform
import os
import subprocess
-from .clipboards import (init_osx_clipboard,
- init_gtk_clipboard, init_qt_clipboard,
- init_xclip_clipboard, init_xsel_clipboard,
- init_klipper_clipboard, init_no_clipboard)
+from .clipboards import (
+ init_osx_clipboard, init_qt_clipboard, init_xclip_clipboard,
+ init_xsel_clipboard, init_klipper_clipboard, init_no_clipboard)
from .windows import init_windows_clipboard
# `import qtpy` sys.exit()s if DISPLAY is not in the environment.
@@ -60,14 +58,6 @@ def determine_clipboard():
return init_osx_clipboard()
if HAS_DISPLAY:
# Determine which command/module is installed, if any.
- try:
- # Check if gtk is installed
- import gtk # noqa
- except ImportError:
- pass
- else:
- return init_gtk_clipboard()
-
try:
# qtpy is a small abstraction layer that lets you write
# applications using a single api call to either PyQt or PySide
@@ -104,7 +94,6 @@ def set_clipboard(clipboard):
global copy, paste
clipboard_types = {'osx': init_osx_clipboard,
- 'gtk': init_gtk_clipboard,
'qt': init_qt_clipboard,
'xclip': init_xclip_clipboard,
'xsel': init_xsel_clipboard,
diff --git a/pandas/io/clipboard/clipboards.py b/pandas/io/clipboard/clipboards.py
index 66e2e35bf0c59..52abdeafb5ecc 100644
--- a/pandas/io/clipboard/clipboards.py
+++ b/pandas/io/clipboard/clipboards.py
@@ -22,22 +22,6 @@ def paste_osx():
return copy_osx, paste_osx
-def init_gtk_clipboard():
- import gtk
-
- def copy_gtk(text):
- global cb
- cb = gtk.Clipboard()
- cb.set_text(text)
- cb.store()
-
- def paste_gtk():
- clipboardContents = gtk.Clipboard().wait_for_text()
- return clipboardContents
-
- return copy_gtk, paste_gtk
-
-
def init_qt_clipboard():
# $DISPLAY should exist
diff --git a/pandas/io/clipboards.py b/pandas/io/clipboards.py
index be1256edf7afe..dc30285895dd5 100644
--- a/pandas/io/clipboards.py
+++ b/pandas/io/clipboards.py
@@ -91,7 +91,7 @@ def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover
Notes
-----
Requirements for your platform
- - Linux: xclip, or xsel (with gtk or PyQt4 modules)
+ - Linux: xclip, or xsel (with PyQt4 modules)
- Windows:
- OS X:
"""
| - [x] closes #26563
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26590 | 2019-05-31T12:11:28Z | 2019-06-02T21:09:45Z | 2019-06-02T21:09:45Z | 2019-06-02T21:09:53Z |
Convert Unions to TypeVar | diff --git a/pandas/_typing.py b/pandas/_typing.py
index f5bf0dcd3e220..a2bb168c1e2da 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -1,5 +1,5 @@
from pathlib import Path
-from typing import IO, AnyStr, Type, Union
+from typing import IO, AnyStr, TypeVar, Union
import numpy as np
@@ -11,12 +11,14 @@
from pandas.core.dtypes.generic import (
ABCExtensionArray, ABCIndexClass, ABCSeries, ABCSparseSeries)
-AnyArrayLike = Union[ABCExtensionArray,
- ABCIndexClass,
- ABCSeries,
- ABCSparseSeries,
- np.ndarray]
-ArrayLike = Union[ABCExtensionArray, np.ndarray]
-DatetimeLikeScalar = Type[Union[Period, Timestamp, Timedelta]]
+AnyArrayLike = TypeVar('AnyArrayLike',
+ ABCExtensionArray,
+ ABCIndexClass,
+ ABCSeries,
+ ABCSparseSeries,
+ np.ndarray)
+ArrayLike = TypeVar('ArrayLike', ABCExtensionArray, np.ndarray)
+DatetimeLikeScalar = TypeVar('DatetimeLikeScalar', Period, Timestamp,
+ Timedelta)
Dtype = Union[str, np.dtype, ExtensionDtype]
FilePathOrBuffer = Union[str, Path, IO[AnyStr]]
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index c32f8642dc2ed..c99c09cdac96c 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
import operator
-from typing import Any, Sequence, Union, cast
+from typing import Any, Sequence, Type, Union, cast
import warnings
import numpy as np
@@ -58,7 +58,7 @@ def _get_attributes_dict(self):
return {k: getattr(self, k, None) for k in self._attributes}
@property
- def _scalar_type(self) -> DatetimeLikeScalar:
+ def _scalar_type(self) -> Type[DatetimeLikeScalar]:
"""The scalar associated with this datelike
* PeriodArray : Period
| - [x] closes #26453
- [x] tests passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` | https://api.github.com/repos/pandas-dev/pandas/pulls/26588 | 2019-05-31T08:31:49Z | 2019-06-08T21:55:31Z | 2019-06-08T21:55:31Z | 2019-06-09T03:12:26Z |
Revert test_constructors xfail | diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index f371f4e93a29e..68017786eb6a6 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -15,7 +15,7 @@
import pandas as pd
from pandas import (
Categorical, DataFrame, Index, MultiIndex, RangeIndex, Series, Timedelta,
- Timestamp, compat, date_range, isna)
+ Timestamp, date_range, isna)
from pandas.tests.frame.common import TestData
import pandas.util.testing as tm
@@ -113,7 +113,6 @@ def test_constructor_dtype_list_data(self):
assert df.loc[1, 0] is None
assert df.loc[0, 1] == '2'
- @pytest.mark.xfail(compat.numpy._is_numpy_dev, reason="GH-26546")
def test_constructor_list_frames(self):
# see gh-3243
result = DataFrame([DataFrame()])
| Reverts https://github.com/pandas-dev/pandas/pull/26548
xref https://github.com/numpy/numpy/pull/13663
Closes https://github.com/pandas-dev/pandas/issues/26546
| https://api.github.com/repos/pandas-dev/pandas/pulls/26586 | 2019-05-31T02:56:57Z | 2019-05-31T03:40:37Z | 2019-05-31T03:40:37Z | 2019-05-31T03:40:37Z |
BUG: fix TypeError for invalid integer dates %Y%m%d with errors='ignore' | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 1619ba1a45739..5d30cbe9e2a15 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -529,6 +529,7 @@ Datetimelike
- Bug in :func:`to_datetime` which does not replace the invalid argument with ``NaT`` when error is set to coerce (:issue:`26122`)
- Bug in adding :class:`DateOffset` with nonzero month to :class:`DatetimeIndex` would raise ``ValueError`` (:issue:`26258`)
- Bug in :func:`to_datetime` which raises unhandled ``OverflowError`` when called with mix of invalid dates and ``NaN`` values with ``format='%Y%m%d'`` and ``error='coerce'`` (:issue:`25512`)
+- Bug in :func:`to_datetime` which raises ``TypeError`` for ``format='%Y%m%d'`` when called for invalid integer dates with length >= 6 digits with ``errors='ignore'``
Timedelta
^^^^^^^^^
diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx
index af3d3fa646a12..d93858cff5e05 100644
--- a/pandas/_libs/tslibs/strptime.pyx
+++ b/pandas/_libs/tslibs/strptime.pyx
@@ -140,13 +140,13 @@ def array_strptime(object[:] values, object fmt,
iresult[i] = NPY_NAT
continue
raise ValueError("time data %r does not match "
- "format %r (match)" % (values[i], fmt))
+ "format %r (match)" % (val, fmt))
if len(val) != found.end():
if is_coerce:
iresult[i] = NPY_NAT
continue
raise ValueError("unconverted data remains: %s" %
- values[i][found.end():])
+ val[found.end():])
# search
else:
@@ -156,7 +156,7 @@ def array_strptime(object[:] values, object fmt,
iresult[i] = NPY_NAT
continue
raise ValueError("time data %r does not match format "
- "%r (search)" % (values[i], fmt))
+ "%r (search)" % (val, fmt))
iso_year = -1
year = 1900
diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py
index c507c31ee54dd..ea33e563b31be 100644
--- a/pandas/tests/indexes/datetimes/test_tools.py
+++ b/pandas/tests/indexes/datetimes/test_tools.py
@@ -133,6 +133,25 @@ def test_to_datetime_format_integer(self, cache):
result = to_datetime(s, format='%Y%m', cache=cache)
assert_series_equal(result, expected)
+ @pytest.mark.parametrize('int_date, expected', [
+ # valid date, length == 8
+ [20121030, datetime(2012, 10, 30)],
+ # short valid date, length == 6
+ [199934, datetime(1999, 3, 4)],
+ # long integer date partially parsed to datetime(2012,1,1), length > 8
+ [2012010101, 2012010101],
+ # invalid date partially parsed to datetime(2012,9,9), length == 8
+ [20129930, 20129930],
+ # short integer date partially parsed to datetime(2012,9,9), length < 8
+ [2012993, 2012993],
+ # short invalid date, length == 4
+ [2121, 2121]])
+ def test_int_to_datetime_format_YYYYMMDD_typeerror(self, int_date,
+ expected):
+ # GH 26583
+ result = to_datetime(int_date, format='%Y%m%d', errors='ignore')
+ assert result == expected
+
@pytest.mark.parametrize('cache', [True, False])
def test_to_datetime_format_microsecond(self, cache):
| - [x] closes #26583
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
array_strptime returned TypeError when trying to slice 'too long' integer for the given format %Y%m%d (for example 2121010101).
After parsing date in the first 8 symbols it tried to return the remaining symbols in ValueError message as a slice of integer which in turn caused TypeError.
Converted to string value is now used to make slice for that ValueError message.
In case of 20209911, it tried to parse 20209911 to datetime(2020, 9, 9) and had 11 left unparsed.
| https://api.github.com/repos/pandas-dev/pandas/pulls/26585 | 2019-05-31T02:06:51Z | 2019-06-05T19:06:15Z | 2019-06-05T19:06:14Z | 2019-06-05T19:06:47Z |
Add more specific error message when user passes incorrect matrix format to from_coo | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 1619ba1a45739..95b7b3dce82da 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -692,7 +692,7 @@ Sparse
- Significant speedup in :class:`SparseArray` initialization that benefits most operations, fixing performance regression introduced in v0.20.0 (:issue:`24985`)
- Bug in :class:`SparseFrame` constructor where passing ``None`` as the data would cause ``default_fill_value`` to be ignored (:issue:`16807`)
- Bug in :class:`SparseDataFrame` when adding a column in which the length of values does not match length of index, ``AssertionError`` is raised instead of raising ``ValueError`` (:issue:`25484`)
-
+- Introduce a better error message in :meth:`Series.sparse.from_coo` so it returns a ``TypeError`` for inputs that are not coo matrices (:issue:`26554`)
Other
^^^^^
diff --git a/pandas/core/sparse/scipy_sparse.py b/pandas/core/sparse/scipy_sparse.py
index 7630983421ff9..0dd8958e93c13 100644
--- a/pandas/core/sparse/scipy_sparse.py
+++ b/pandas/core/sparse/scipy_sparse.py
@@ -130,10 +130,19 @@ def _coo_to_sparse_series(A, dense_index: bool = False,
Returns
-------
Series or SparseSeries
+
+ Raises
+ ------
+ TypeError if A is not a coo_matrix
+
"""
from pandas import SparseDtype
- s = Series(A.data, MultiIndex.from_arrays((A.row, A.col)))
+ try:
+ s = Series(A.data, MultiIndex.from_arrays((A.row, A.col)))
+ except AttributeError:
+ raise TypeError('Expected coo_matrix. Got {} instead.'
+ .format(type(A).__name__))
s = s.sort_index()
if sparse_series:
# TODO(SparseSeries): remove this and the sparse_series keyword.
diff --git a/pandas/tests/arrays/sparse/test_accessor.py b/pandas/tests/arrays/sparse/test_accessor.py
index 370d222c1ab4e..d0a188a8aff3c 100644
--- a/pandas/tests/arrays/sparse/test_accessor.py
+++ b/pandas/tests/arrays/sparse/test_accessor.py
@@ -119,3 +119,13 @@ def test_series_from_coo(self, dtype, dense_index):
)
tm.assert_series_equal(result, expected)
+
+ @td.skip_if_no_scipy
+ def test_series_from_coo_incorrect_format_raises(self):
+ # gh-26554
+ import scipy.sparse
+ m = scipy.sparse.csr_matrix(np.array([[0, 1], [0, 0]]))
+ with pytest.raises(TypeError,
+ match='Expected coo_matrix. Got csr_matrix instead.'
+ ):
+ pd.Series.sparse.from_coo(m)
| - [x] closes #26554
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26584 | 2019-05-31T01:31:58Z | 2019-06-02T23:42:55Z | 2019-06-02T23:42:55Z | 2019-06-02T23:43:04Z |
use range in RangeIndex instead of _start etc. | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 461c883f542ab..295452c300931 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -473,6 +473,9 @@ Other Deprecations
the :meth:`SparseArray.to_dense` method instead (:issue:`26421`).
- The functions :func:`pandas.to_datetime` and :func:`pandas.to_timedelta` have deprecated the ``box`` keyword. Instead, use :meth:`to_numpy` or :meth:`Timestamp.to_datetime64` or :meth:`Timedelta.to_timedelta64`. (:issue:`24416`)
- The :meth:`DataFrame.compound` and :meth:`Series.compound` methods are deprecated and will be removed in a future version (:issue:`26405`).
+- The internal attributes ``_start``, ``_stop`` and ``_step`` attributes of :class:`RangeIndex` have been deprecated.
+ Use the public attributes :attr:`~RangeIndex.start`, :attr:`~RangeIndex.stop` and :attr:`~RangeIndex.step` instead (:issue:`26581`).
+
.. _whatsnew_0250.prior_deprecations:
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index b5cd73a81962b..4029e6f4bfdb5 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -1,4 +1,5 @@
""" common type operations """
+from typing import Union
import warnings
import numpy as np
@@ -125,6 +126,34 @@ def ensure_int_or_float(arr: ArrayLike, copy=False) -> np.array:
return arr.astype('float64', copy=copy)
+def ensure_python_int(value: Union[int, np.integer]) -> int:
+ """
+ Ensure that a value is a python int.
+
+ Parameters
+ ----------
+ value: int or numpy.integer
+
+ Returns
+ -------
+ int
+
+ Raises
+ ------
+ TypeError: if the value isn't an int or can't be converted to one.
+ """
+ if not is_scalar(value):
+ raise TypeError("Value needs to be a scalar value, was type {}"
+ .format(type(value)))
+ msg = "Wrong type {} for value {}"
+ try:
+ new_value = int(value)
+ assert (new_value == value)
+ except (TypeError, ValueError, AssertionError):
+ raise TypeError(msg.format(type(value), value))
+ return new_value
+
+
def classes(*klasses):
""" evaluate if the tipo is a subclass of the klasses """
return lambda tipo: issubclass(tipo, klasses)
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py
index b22ed45642cf6..e2c6fba322be0 100644
--- a/pandas/core/dtypes/concat.py
+++ b/pandas/core/dtypes/concat.py
@@ -541,36 +541,37 @@ def _concat_rangeindex_same_dtype(indexes):
"""
from pandas import Int64Index, RangeIndex
- start = step = next = None
+ start = step = next_ = None
# Filter the empty indexes
non_empty_indexes = [obj for obj in indexes if len(obj)]
for obj in non_empty_indexes:
+ rng = obj._range # type: range
if start is None:
# This is set by the first non-empty index
- start = obj._start
- if step is None and len(obj) > 1:
- step = obj._step
+ start = rng.start
+ if step is None and len(rng) > 1:
+ step = rng.step
elif step is None:
# First non-empty index had only one element
- if obj._start == start:
+ if rng.start == start:
return _concat_index_same_dtype(indexes, klass=Int64Index)
- step = obj._start - start
+ step = rng.start - start
- non_consecutive = ((step != obj._step and len(obj) > 1) or
- (next is not None and obj._start != next))
+ non_consecutive = ((step != rng.step and len(rng) > 1) or
+ (next_ is not None and rng.start != next_))
if non_consecutive:
return _concat_index_same_dtype(indexes, klass=Int64Index)
if step is not None:
- next = obj[-1] + step
+ next_ = rng[-1] + step
if non_empty_indexes:
# Get the stop value from "next" or alternatively
# from the last non-empty index
- stop = non_empty_indexes[-1]._stop if next is None else next
+ stop = non_empty_indexes[-1].stop if next_ is None else next_
return RangeIndex(start, stop, step)
# Here all "indexes" had 0 length, i.e. were empty.
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 5957b23535350..48dfa57c47bf6 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2282,7 +2282,7 @@ def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None,
text_col 5 non-null object
float_col 5 non-null float64
dtypes: float64(1), int64(1), object(1)
- memory usage: 200.0+ bytes
+ memory usage: 248.0+ bytes
Prints a summary of columns count and its dtypes but not per column
information:
@@ -2292,7 +2292,7 @@ def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None,
RangeIndex: 5 entries, 0 to 4
Columns: 3 entries, int_col to float_col
dtypes: float64(1), int64(1), object(1)
- memory usage: 200.0+ bytes
+ memory usage: 248.0+ bytes
Pipe output of DataFrame.info to buffer instead of sys.stdout, get
buffer content and writes to a text file:
@@ -2494,7 +2494,7 @@ def memory_usage(self, index=True, deep=False):
4 1 1.0 1.0+0.0j 1 True
>>> df.memory_usage()
- Index 80
+ Index 128
int64 40000
float64 40000
complex128 80000
@@ -2513,7 +2513,7 @@ def memory_usage(self, index=True, deep=False):
The memory footprint of `object` dtype columns is ignored by default:
>>> df.memory_usage(deep=True)
- Index 80
+ Index 128
int64 40000
float64 40000
complex128 80000
@@ -2525,7 +2525,7 @@ def memory_usage(self, index=True, deep=False):
many repeated values.
>>> df['object'].astype('category').memory_usage(deep=True)
- 5168
+ 5216
"""
result = Series([c.memory_usage(index=False, deep=deep)
for col, c in self.iteritems()], index=self.columns)
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index 9401de3346ccd..82fd7342c027c 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -12,7 +12,8 @@
from pandas.core.dtypes import concat as _concat
from pandas.core.dtypes.common import (
- is_int64_dtype, is_integer, is_scalar, is_timedelta64_dtype)
+ ensure_python_int, is_int64_dtype, is_integer, is_scalar,
+ is_timedelta64_dtype)
from pandas.core.dtypes.generic import (
ABCDataFrame, ABCSeries, ABCTimedeltaIndex)
@@ -65,6 +66,7 @@ class RangeIndex(Int64Index):
_typ = 'rangeindex'
_engine_type = libindex.Int64Engine
+ _range = None # type: range
# check whether self._data has benn called
_cached_data = None # type: np.ndarray
@@ -91,39 +93,19 @@ def __new__(cls, start=None, stop=None, step=None,
**dict(start._get_data_as_items()))
# validate the arguments
- def ensure_int(value, field):
- msg = ("RangeIndex(...) must be called with integers,"
- " {value} was passed for {field}")
- if not is_scalar(value):
- raise TypeError(msg.format(value=type(value).__name__,
- field=field))
- try:
- new_value = int(value)
- assert(new_value == value)
- except (TypeError, ValueError, AssertionError):
- raise TypeError(msg.format(value=type(value).__name__,
- field=field))
+ if com._all_none(start, stop, step):
+ raise TypeError("RangeIndex(...) must be called with integers")
- return new_value
+ start = ensure_python_int(start) if start is not None else 0
- if com._all_none(start, stop, step):
- msg = "RangeIndex(...) must be called with integers"
- raise TypeError(msg)
- elif start is None:
- start = 0
- else:
- start = ensure_int(start, 'start')
if stop is None:
- stop = start
- start = 0
+ start, stop = 0, start
else:
- stop = ensure_int(stop, 'stop')
- if step is None:
- step = 1
- elif step == 0:
+ stop = ensure_python_int(stop)
+
+ step = ensure_python_int(step) if step is not None else 1
+ if step == 0:
raise ValueError("Step must not be zero")
- else:
- step = ensure_int(step, 'step')
return cls._simple_new(start, stop, step, name)
@@ -142,7 +124,7 @@ def from_range(cls, data, name=None, dtype=None, **kwargs):
'range, {1} was passed'.format(cls.__name__, repr(data)))
start, stop, step = data.start, data.stop, data.step
- return RangeIndex(start, stop, step, dtype=dtype, name=name, **kwargs)
+ return cls(start, stop, step, dtype=dtype, name=name, **kwargs)
@classmethod
def _simple_new(cls, start, stop=None, step=None, name=None,
@@ -156,20 +138,16 @@ def _simple_new(cls, start, stop=None, step=None, name=None,
if start is None or not is_integer(start):
try:
-
- return RangeIndex(start, stop, step, name=name, **kwargs)
+ return cls(start, stop, step, name=name, **kwargs)
except TypeError:
return Index(start, stop, step, name=name, **kwargs)
- result._start = start
- result._stop = stop or 0
- result._step = step or 1
+ result._range = range(start, stop or 0, step or 1)
+
result.name = name
for k, v in kwargs.items():
setattr(result, k, v)
- result._range = range(result._start, result._stop, result._step)
-
result._reset_identity()
return result
@@ -196,7 +174,7 @@ def _data(self):
triggering the construction.
"""
if self._cached_data is None:
- self._cached_data = np.arange(self._start, self._stop, self._step,
+ self._cached_data = np.arange(self.start, self.stop, self.step,
dtype=np.int64)
return self._cached_data
@@ -206,9 +184,10 @@ def _int64index(self):
def _get_data_as_items(self):
""" return a list of tuples of start, stop, step """
- return [('start', self._start),
- ('stop', self._stop),
- ('step', self._step)]
+ rng = self._range
+ return [('start', rng.start),
+ ('stop', rng.stop),
+ ('step', rng.step)]
def __reduce__(self):
d = self._get_attributes_dict()
@@ -235,39 +214,79 @@ def _format_with_header(self, header, na_rep='NaN', **kwargs):
return header + list(map(pprint_thing, self._range))
# --------------------------------------------------------------------
- @property
+ _deprecation_message = ("RangeIndex.{} is deprecated and will be "
+ "removed in a future version. Use RangeIndex.{} "
+ "instead")
+
+ @cache_readonly
def start(self):
"""
- The value of the `start` parameter (or ``0`` if this was not supplied)
+ The value of the `start` parameter (``0`` if this was not supplied)
"""
# GH 25710
- return self._start
+ return self._range.start
@property
+ def _start(self):
+ """
+ The value of the `start` parameter (``0`` if this was not supplied)
+
+ .. deprecated:: 0.25.0
+ Use ``start`` instead.
+ """
+ warnings.warn(self._deprecation_message.format("_start", "start"),
+ DeprecationWarning, stacklevel=2)
+ return self.start
+
+ @cache_readonly
def stop(self):
"""
The value of the `stop` parameter
"""
- # GH 25710
- return self._stop
+ return self._range.stop
@property
+ def _stop(self):
+ """
+ The value of the `stop` parameter
+
+ .. deprecated:: 0.25.0
+ Use ``stop`` instead.
+ """
+ # GH 25710
+ warnings.warn(self._deprecation_message.format("_stop", "stop"),
+ DeprecationWarning, stacklevel=2)
+ return self.stop
+
+ @cache_readonly
def step(self):
"""
- The value of the `step` parameter (or ``1`` if this was not supplied)
+ The value of the `step` parameter (``1`` if this was not supplied)
"""
# GH 25710
- return self._step
+ return self._range.step
+
+ @property
+ def _step(self):
+ """
+ The value of the `step` parameter (``1`` if this was not supplied)
+
+ .. deprecated:: 0.25.0
+ Use ``step`` instead.
+ """
+ # GH 25710
+ warnings.warn(self._deprecation_message.format("_step", "step"),
+ DeprecationWarning, stacklevel=2)
+ return self.step
@cache_readonly
def nbytes(self):
"""
- Return the number of bytes in the underlying data
- On implementations where this is undetermined (PyPy)
- assume 24 bytes for each value
+ Return the number of bytes in the underlying data.
"""
- return sum(getsizeof(getattr(self, v), 24) for v in
- ['_start', '_stop', '_step'])
+ rng = self._range
+ return getsizeof(rng) + sum(getsizeof(getattr(rng, attr_name))
+ for attr_name in ['start', 'stop', 'step'])
def memory_usage(self, deep=False):
"""
@@ -305,11 +324,11 @@ def is_unique(self):
@cache_readonly
def is_monotonic_increasing(self):
- return self._step > 0 or len(self) <= 1
+ return self._range.step > 0 or len(self) <= 1
@cache_readonly
def is_monotonic_decreasing(self):
- return self._step < 0 or len(self) <= 1
+ return self._range.step < 0 or len(self) <= 1
@property
def has_duplicates(self):
@@ -325,13 +344,13 @@ def get_loc(self, key, method=None, tolerance=None):
return super().get_loc(key, method=method, tolerance=tolerance)
def tolist(self):
- return list(range(self._start, self._stop, self._step))
+ return list(self._range)
@Appender(_index_shared_docs['_shallow_copy'])
def _shallow_copy(self, values=None, **kwargs):
if values is None:
name = kwargs.get("name", self.name)
- return RangeIndex._simple_new(
+ return self._simple_new(
name=name, **dict(self._get_data_as_items()))
else:
kwargs.setdefault('name', self.name)
@@ -342,18 +361,17 @@ def copy(self, name=None, deep=False, dtype=None, **kwargs):
self._validate_dtype(dtype)
if name is None:
name = self.name
- return RangeIndex._simple_new(
- name=name, **dict(self._get_data_as_items()))
+ return self.from_range(self._range, name=name)
def _minmax(self, meth):
no_steps = len(self) - 1
if no_steps == -1:
return np.nan
- elif ((meth == 'min' and self._step > 0) or
- (meth == 'max' and self._step < 0)):
- return self._start
+ elif ((meth == 'min' and self.step > 0) or
+ (meth == 'max' and self.step < 0)):
+ return self.start
- return self._start + self._step * no_steps
+ return self.start + self.step * no_steps
def min(self, axis=None, skipna=True, *args, **kwargs):
"""The minimum value of the RangeIndex"""
@@ -382,7 +400,7 @@ def argsort(self, *args, **kwargs):
"""
nv.validate_argsort(args, kwargs)
- if self._step > 0:
+ if self._range.step > 0:
return np.arange(len(self))
else:
return np.arange(len(self) - 1, -1, -1)
@@ -392,15 +410,7 @@ def equals(self, other):
Determines if two Index objects contain the same elements.
"""
if isinstance(other, RangeIndex):
- ls = len(self)
- lo = len(other)
- return (ls == lo == 0 or
- ls == lo == 1 and
- self._start == other._start or
- ls == lo and
- self._start == other._start and
- self._step == other._step)
-
+ return self._range == other._range
return super().equals(other)
def intersection(self, other, sort=False):
@@ -433,39 +443,40 @@ def intersection(self, other, sort=False):
return super().intersection(other, sort=sort)
if not len(self) or not len(other):
- return RangeIndex._simple_new(None)
+ return self._simple_new(None)
- first = self[::-1] if self._step < 0 else self
- second = other[::-1] if other._step < 0 else other
+ first = self._range[::-1] if self.step < 0 else self._range
+ second = other._range[::-1] if other.step < 0 else other._range
# check whether intervals intersect
# deals with in- and decreasing ranges
- int_low = max(first._start, second._start)
- int_high = min(first._stop, second._stop)
+ int_low = max(first.start, second.start)
+ int_high = min(first.stop, second.stop)
if int_high <= int_low:
- return RangeIndex._simple_new(None)
+ return self._simple_new(None)
# Method hint: linear Diophantine equation
# solve intersection problem
# performance hint: for identical step sizes, could use
# cheaper alternative
- gcd, s, t = first._extended_gcd(first._step, second._step)
+ gcd, s, t = self._extended_gcd(first.step, second.step)
# check whether element sets intersect
- if (first._start - second._start) % gcd:
- return RangeIndex._simple_new(None)
+ if (first.start - second.start) % gcd:
+ return self._simple_new(None)
# calculate parameters for the RangeIndex describing the
# intersection disregarding the lower bounds
- tmp_start = first._start + (second._start - first._start) * \
- first._step // gcd * s
- new_step = first._step * second._step // gcd
- new_index = RangeIndex._simple_new(tmp_start, int_high, new_step)
+ tmp_start = first.start + (second.start - first.start) * \
+ first.step // gcd * s
+ new_step = first.step * second.step // gcd
+ new_index = self._simple_new(tmp_start, int_high, new_step)
# adjust index to limiting interval
- new_index._start = new_index._min_fitting_element(int_low)
+ new_start = new_index._min_fitting_element(int_low)
+ new_index = self._simple_new(new_start, new_index.stop, new_index.step)
- if (self._step < 0 and other._step < 0) is not (new_index._step < 0):
+ if (self.step < 0 and other.step < 0) is not (new_index.step < 0):
new_index = new_index[::-1]
if sort is None:
new_index = new_index.sort_values()
@@ -473,13 +484,13 @@ def intersection(self, other, sort=False):
def _min_fitting_element(self, lower_limit):
"""Returns the smallest element greater than or equal to the limit"""
- no_steps = -(-(lower_limit - self._start) // abs(self._step))
- return self._start + abs(self._step) * no_steps
+ no_steps = -(-(lower_limit - self.start) // abs(self.step))
+ return self.start + abs(self.step) * no_steps
def _max_fitting_element(self, upper_limit):
"""Returns the largest element smaller than or equal to the limit"""
- no_steps = (upper_limit - self._start) // abs(self._step)
- return self._start + abs(self._step) * no_steps
+ no_steps = (upper_limit - self.start) // abs(self.step)
+ return self.start + abs(self.step) * no_steps
def _extended_gcd(self, a, b):
"""
@@ -522,16 +533,16 @@ def _union(self, other, sort):
return super()._union(other, sort=sort)
if isinstance(other, RangeIndex) and sort is None:
- start_s, step_s = self._start, self._step
- end_s = self._start + self._step * (len(self) - 1)
- start_o, step_o = other._start, other._step
- end_o = other._start + other._step * (len(other) - 1)
- if self._step < 0:
+ start_s, step_s = self.start, self.step
+ end_s = self.start + self.step * (len(self) - 1)
+ start_o, step_o = other.start, other.step
+ end_o = other.start + other.step * (len(other) - 1)
+ if self.step < 0:
start_s, step_s, end_s = end_s, -step_s, start_s
- if other._step < 0:
+ if other.step < 0:
start_o, step_o, end_o = end_o, -step_o, start_o
if len(self) == 1 and len(other) == 1:
- step_s = step_o = abs(self._start - other._start)
+ step_s = step_o = abs(self.start - other.start)
elif len(self) == 1:
step_s = step_o
elif len(other) == 1:
@@ -542,21 +553,23 @@ def _union(self, other, sort):
if ((start_s - start_o) % step_s == 0 and
(start_s - end_o) <= step_s and
(start_o - end_s) <= step_s):
- return RangeIndex(start_r, end_r + step_s, step_s)
+ return self.__class__(start_r, end_r + step_s, step_s)
if ((step_s % 2 == 0) and
(abs(start_s - start_o) <= step_s / 2) and
(abs(end_s - end_o) <= step_s / 2)):
- return RangeIndex(start_r, end_r + step_s / 2, step_s / 2)
+ return self.__class__(start_r,
+ end_r + step_s / 2,
+ step_s / 2)
elif step_o % step_s == 0:
if ((start_o - start_s) % step_s == 0 and
(start_o + step_s >= start_s) and
(end_o - step_s <= end_s)):
- return RangeIndex(start_r, end_r + step_s, step_s)
+ return self.__class__(start_r, end_r + step_s, step_s)
elif step_s % step_o == 0:
if ((start_s - start_o) % step_o == 0 and
(start_s + step_o >= start_o) and
(end_s - step_o <= end_o)):
- return RangeIndex(start_r, end_r + step_o, step_o)
+ return self.__class__(start_r, end_r + step_o, step_o)
return self._int64index._union(other, sort=sort)
@Appender(_index_shared_docs['join'])
@@ -576,7 +589,7 @@ def __len__(self):
"""
return the length of the RangeIndex
"""
- return max(0, -(-(self._stop - self._start) // self._step))
+ return len(self._range)
@property
def size(self):
@@ -597,59 +610,15 @@ def __getitem__(self, key):
n = com.cast_scalar_indexer(key)
if n != key:
return super_getitem(key)
- if n < 0:
- n = len(self) + key
- if n < 0 or n > len(self) - 1:
+ try:
+ return self._range[key]
+ except IndexError:
raise IndexError("index {key} is out of bounds for axis 0 "
"with size {size}".format(key=key,
size=len(self)))
- return self._start + n * self._step
-
if isinstance(key, slice):
-
- # This is basically PySlice_GetIndicesEx, but delegation to our
- # super routines if we don't have integers
-
- length = len(self)
-
- # complete missing slice information
- step = 1 if key.step is None else key.step
- if key.start is None:
- start = length - 1 if step < 0 else 0
- else:
- start = key.start
-
- if start < 0:
- start += length
- if start < 0:
- start = -1 if step < 0 else 0
- if start >= length:
- start = length - 1 if step < 0 else length
-
- if key.stop is None:
- stop = -1 if step < 0 else length
- else:
- stop = key.stop
-
- if stop < 0:
- stop += length
- if stop < 0:
- stop = -1
- if stop > length:
- stop = length
-
- # delegate non-integer slices
- if (start != int(start) or
- stop != int(stop) or
- step != int(step)):
- return super_getitem(key)
-
- # convert indexes to values
- start = self._start + self._step * start
- stop = self._start + self._step * stop
- step = self._step * step
-
- return RangeIndex._simple_new(start, stop, step, name=self.name)
+ new_range = self._range[key]
+ return self.from_range(new_range, name=self.name)
# fall back to Int64Index
return super_getitem(key)
@@ -660,17 +629,15 @@ def __floordiv__(self, other):
if is_integer(other) and other != 0:
if (len(self) == 0 or
- self._start % other == 0 and
- self._step % other == 0):
- start = self._start // other
- step = self._step // other
+ self.start % other == 0 and
+ self.step % other == 0):
+ start = self.start // other
+ step = self.step // other
stop = start + len(self) * step
- return RangeIndex._simple_new(
- start, stop, step, name=self.name)
+ return self._simple_new(start, stop, step, name=self.name)
if len(self) == 1:
- start = self._start // other
- return RangeIndex._simple_new(
- start, start + 1, 1, name=self.name)
+ start = self.start // other
+ return self._simple_new(start, start + 1, 1, name=self.name)
return self._int64index // other
@classmethod
@@ -712,7 +679,7 @@ def _evaluate_numeric_binop(self, other):
# apply if we have an override
if step:
with np.errstate(all='ignore'):
- rstep = step(left._step, right)
+ rstep = step(left.step, right)
# we don't have a representable op
# so return a base index
@@ -720,16 +687,13 @@ def _evaluate_numeric_binop(self, other):
raise ValueError
else:
- rstep = left._step
+ rstep = left.step
with np.errstate(all='ignore'):
- rstart = op(left._start, right)
- rstop = op(left._stop, right)
+ rstart = op(left.start, right)
+ rstop = op(left.stop, right)
- result = RangeIndex(rstart,
- rstop,
- rstep,
- **attrs)
+ result = self.__class__(rstart, rstop, rstep, **attrs)
# for compat with numpy / Int64Index
# even if we can represent as a RangeIndex, return
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 8fb6ad3e3ccc5..472d984234275 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -4010,7 +4010,7 @@ def memory_usage(self, index=True, deep=False):
--------
>>> s = pd.Series(range(3))
>>> s.memory_usage()
- 104
+ 152
Not including the index gives the size of the rest of the data, which
is necessarily smaller:
@@ -4024,9 +4024,9 @@ def memory_usage(self, index=True, deep=False):
>>> s.values
array(['a', 'b'], dtype=object)
>>> s.memory_usage()
- 96
+ 144
>>> s.memory_usage(deep=True)
- 212
+ 260
"""
v = super().memory_usage(deep=deep)
if index:
diff --git a/pandas/io/packers.py b/pandas/io/packers.py
index 1309bd1fef421..ead0fbd263ebf 100644
--- a/pandas/io/packers.py
+++ b/pandas/io/packers.py
@@ -367,9 +367,10 @@ def encode(obj):
return {'typ': 'range_index',
'klass': obj.__class__.__name__,
'name': getattr(obj, 'name', None),
- 'start': getattr(obj, '_start', None),
- 'stop': getattr(obj, '_stop', None),
- 'step': getattr(obj, '_step', None)}
+ 'start': obj._range.start,
+ 'stop': obj._range.stop,
+ 'step': obj._range.step,
+ }
elif isinstance(obj, PeriodIndex):
return {'typ': 'period_index',
'klass': obj.__class__.__name__,
diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py
index 477a4e527f278..bca50186827de 100644
--- a/pandas/tests/indexes/test_range.py
+++ b/pandas/tests/indexes/test_range.py
@@ -51,10 +51,8 @@ def test_constructor(self, args, kwargs, start, stop, step, name):
expected = Index(np.arange(start, stop, step, dtype=np.int64),
name=name)
assert isinstance(result, RangeIndex)
- assert result._start == start
- assert result._stop == stop
- assert result._step == step
assert result.name is name
+ assert result._range == range(start, stop, step)
tm.assert_index_equal(result, expected)
def test_constructor_invalid_args(self):
@@ -169,14 +167,19 @@ def test_start_stop_step_attrs(self, index, start, stop, step):
assert index.stop == stop
assert index.step == step
+ def test_deprecated_start_stop_step_attrs(self):
+ # GH 26581
+ idx = self.create_index()
+ for attr_name in ['_start', '_stop', '_step']:
+ with tm.assert_produces_warning(DeprecationWarning):
+ getattr(idx, attr_name)
+
def test_copy(self):
i = RangeIndex(5, name='Foo')
i_copy = i.copy()
assert i_copy is not i
assert i_copy.identical(i)
- assert i_copy._start == 0
- assert i_copy._stop == 5
- assert i_copy._step == 1
+ assert i_copy._range == range(0, 5, 1)
assert i_copy.name == 'Foo'
def test_repr(self):
@@ -243,8 +246,9 @@ def test_dtype(self):
def test_cached_data(self):
# GH 26565
- # Calling RangeIndex._data caches an int64 array of the same length at
- # self._cached_data. This tests whether _cached_data has been set.
+ # Calling RangeIndex._data caches an int64 array of the same length as
+ # self at self._cached_data.
+ # This tests whether _cached_data is being set by various operations.
idx = RangeIndex(0, 100, 10)
assert idx._cached_data is None
@@ -273,7 +277,7 @@ def test_cached_data(self):
df.iloc[5:10]
assert idx._cached_data is None
- # actually calling data._data
+ # actually calling idx._data
assert isinstance(idx._data, np.ndarray)
assert isinstance(idx._cached_data, np.ndarray)
| - [x] xref #26565
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Make RangeIndex use python's ``range`` internally, rather than the three scalars ``_start``, ``_stop`` and ``_step``.
Python3's ``range`` has several nice properties, that were not available in ``xrange`` in Python2. For example it's sliceable, and has ``.index`` and ``count`` methods. These can be used in Pandas, rather than maintaining Pandas-specific code, offering cleaner code and possibly faster operations.
| https://api.github.com/repos/pandas-dev/pandas/pulls/26581 | 2019-05-30T20:37:22Z | 2019-06-05T12:50:34Z | 2019-06-05T12:50:34Z | 2019-06-05T12:59:33Z |
ENH: Named aggregation in SeriesGroupBy.agg | diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst
index 2014dbd9865f3..9895fc606f70d 100644
--- a/doc/source/user_guide/groupby.rst
+++ b/doc/source/user_guide/groupby.rst
@@ -595,7 +595,7 @@ accepts the special syntax in :meth:`GroupBy.agg`, known as "named aggregation",
animals.groupby("kind").agg(
min_height=pd.NamedAgg(column='height', aggfunc='min'),
max_height=pd.NamedAgg(column='height', aggfunc='max'),
- average_weight=pd.NamedAgg(column='height', aggfunc=np.mean),
+ average_weight=pd.NamedAgg(column='weight', aggfunc=np.mean),
)
@@ -606,7 +606,7 @@ accepts the special syntax in :meth:`GroupBy.agg`, known as "named aggregation",
animals.groupby("kind").agg(
min_height=('height', 'min'),
max_height=('height', 'max'),
- average_weight=('height', np.mean),
+ average_weight=('weight', np.mean),
)
@@ -630,6 +630,16 @@ requires additional arguments, partially apply them with :meth:`functools.partia
consistent. To ensure consistent ordering, the keys (and so output columns)
will always be sorted for Python 3.5.
+Named aggregation is also valid for Series groupby aggregations. In this case there's
+no column selection, so the values are just the functions.
+
+.. ipython:: python
+
+ animals.groupby("kind").height.agg(
+ min_height='min',
+ max_height='max',
+ )
+
Applying different functions to DataFrame columns
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index df22a21196dab..9cc44a91cf72b 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -28,7 +28,7 @@ Groupby Aggregation with Relabeling
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Pandas has added special groupby behavior, known as "named aggregation", for naming the
-output columns when applying multiple aggregation functions to specific columns (:issue:`18366`).
+output columns when applying multiple aggregation functions to specific columns (:issue:`18366`, :issue:`26512`).
.. ipython:: python
@@ -39,7 +39,7 @@ output columns when applying multiple aggregation functions to specific columns
animals.groupby("kind").agg(
min_height=pd.NamedAgg(column='height', aggfunc='min'),
max_height=pd.NamedAgg(column='height', aggfunc='max'),
- average_weight=pd.NamedAgg(column='height', aggfunc=np.mean),
+ average_weight=pd.NamedAgg(column='weight', aggfunc=np.mean),
)
Pass the desired columns names as the ``**kwargs`` to ``.agg``. The values of ``**kwargs``
@@ -52,12 +52,26 @@ what the arguments to the function are, but plain tuples are accepted as well.
animals.groupby("kind").agg(
min_height=('height', 'min'),
max_height=('height', 'max'),
- average_weight=('height', np.mean),
+ average_weight=('weight', np.mean),
)
Named aggregation is the recommended replacement for the deprecated "dict-of-dicts"
approach to naming the output of column-specific aggregations (:ref:`whatsnew_0200.api_breaking.deprecate_group_agg_dict`).
+A similar approach is now available for Series groupby objects as well. Because there's no need for
+column selection, the values can just be the functions to apply
+
+.. ipython:: python
+
+ animals.groupby("kind").height.agg(
+ min_height="min",
+ max_height="max",
+ )
+
+
+This type of aggregation is the recommended alternative to the deprecated behavior when passing
+a dict to a Series groupby aggregation (:ref:`whatsnew_0200.api_breaking.deprecate_group_agg_dict`).
+
See :ref:`_groupby.aggregate.named` for more.
.. _whatsnew_0250.enhancements.other:
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 9ded2450693dd..57d14cb4c15d7 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -735,6 +735,17 @@ def _selection_name(self):
min max
1 1 2
2 3 4
+
+ The output column names can be controlled by passing
+ the desired column names and aggregations as keyword arguments.
+
+ >>> s.groupby([1, 1, 2, 2]).agg(
+ ... minimum='min',
+ ... maximum='max',
+ ... )
+ minimum maximum
+ 1 1 2
+ 2 3 4
""")
@Appender(_apply_docs['template']
@@ -749,8 +760,24 @@ def apply(self, func, *args, **kwargs):
klass='Series',
axis='')
@Appender(_shared_docs['aggregate'])
- def aggregate(self, func_or_funcs, *args, **kwargs):
+ def aggregate(self, func_or_funcs=None, *args, **kwargs):
_level = kwargs.pop('_level', None)
+
+ relabeling = func_or_funcs is None
+ columns = None
+ no_arg_message = ("Must provide 'func_or_funcs' or named "
+ "aggregation **kwargs.")
+ if relabeling:
+ columns = list(kwargs)
+ if not PY36:
+ # sort for 3.5 and earlier
+ columns = list(sorted(columns))
+
+ func_or_funcs = [kwargs[col] for col in columns]
+ kwargs = {}
+ if not columns:
+ raise TypeError(no_arg_message)
+
if isinstance(func_or_funcs, str):
return getattr(self, func_or_funcs)(*args, **kwargs)
@@ -759,6 +786,8 @@ def aggregate(self, func_or_funcs, *args, **kwargs):
# but not the class list / tuple itself.
ret = self._aggregate_multiple_funcs(func_or_funcs,
(_level or 0) + 1)
+ if relabeling:
+ ret.columns = columns
else:
cyfunc = self._is_cython_func(func_or_funcs)
if cyfunc and not args and not kwargs:
@@ -793,11 +822,14 @@ def _aggregate_multiple_funcs(self, arg, _level):
# have not shown a higher level one
# GH 15931
if isinstance(self._selected_obj, Series) and _level <= 1:
- warnings.warn(
- ("using a dict on a Series for aggregation\n"
- "is deprecated and will be removed in a future "
- "version"),
- FutureWarning, stacklevel=3)
+ msg = dedent("""\
+ using a dict on a Series for aggregation
+ is deprecated and will be removed in a future version. Use \
+ named aggregation instead.
+
+ >>> grouper.agg(name_1=func_1, name_2=func_2)
+ """)
+ warnings.warn(msg, FutureWarning, stacklevel=3)
columns = list(arg.keys())
arg = arg.items()
@@ -1562,7 +1594,7 @@ def groupby_series(obj, col=None):
def _is_multi_agg_with_relabel(**kwargs):
"""
- Check whether the kwargs pass to .agg look like multi-agg with relabling.
+ Check whether kwargs passed to .agg look like multi-agg with relabeling.
Parameters
----------
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index 9e714a1086037..801b99fed5ce6 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -329,8 +329,41 @@ def test_uint64_type_handling(dtype, how):
tm.assert_frame_equal(result, expected, check_exact=True)
-class TestNamedAggregation:
+class TestNamedAggregationSeries:
+
+ def test_series_named_agg(self):
+ df = pd.Series([1, 2, 3, 4])
+ gr = df.groupby([0, 0, 1, 1])
+ result = gr.agg(a='sum', b='min')
+ expected = pd.DataFrame({'a': [3, 7], 'b': [1, 3]},
+ columns=['a', 'b'], index=[0, 1])
+ tm.assert_frame_equal(result, expected)
+
+ result = gr.agg(b='min', a='sum')
+ # sort for 35 and earlier
+ if compat.PY36:
+ expected = expected[['b', 'a']]
+ tm.assert_frame_equal(result, expected)
+
+ def test_no_args_raises(self):
+ gr = pd.Series([1, 2]).groupby([0, 1])
+ with pytest.raises(TypeError, match='Must provide'):
+ gr.agg()
+
+ # but we do allow this
+ result = gr.agg([])
+ expected = pd.DataFrame()
+ tm.assert_frame_equal(result, expected)
+
+ def test_series_named_agg_duplicates_raises(self):
+ # This is a limitation of the named agg implementation reusing
+ # aggregate_multiple_funcs. It could maybe be lifted in the future.
+ gr = pd.Series([1, 2, 3]).groupby([0, 0, 1])
+ with pytest.raises(SpecificationError):
+ gr.agg(a='sum', b='sum')
+
+class TestNamedAggregationDataFrame:
def test_agg_relabel(self):
df = pd.DataFrame({"group": ['a', 'a', 'b', 'b'],
"A": [0, 1, 2, 3],
diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py
index 8168cf06ffdb1..a061eaa1a2c6f 100644
--- a/pandas/tests/groupby/aggregate/test_other.py
+++ b/pandas/tests/groupby/aggregate/test_other.py
@@ -225,6 +225,7 @@ def test_agg_dict_renaming_deprecation():
with tm.assert_produces_warning(FutureWarning) as w:
df.groupby('A').B.agg({'foo': 'count'})
assert "using a dict on a Series for aggregation" in str(w[0].message)
+ assert "named aggregation instead." in str(w[0].message)
def test_agg_compat():
| ```python
In [4]: animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
...: 'height': [9.1, 6.0, 9.5, 34.0],
...: 'weight': [7.9, 7.5, 9.9, 198.0]})
...: animals.groupby("kind").height.agg(max_height='max')
Out[4]:
max_height
kind
cat 9.5
dog 34.0
```
Closes #26512
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26580 | 2019-05-30T19:14:12Z | 2019-06-10T12:45:05Z | 2019-06-10T12:45:05Z | 2019-06-10T12:45:08Z |
Remove SharedItems from test_excel | diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py
index 7693caf3b31d2..b99f0336fa4c5 100644
--- a/pandas/tests/io/test_excel.py
+++ b/pandas/tests/io/test_excel.py
@@ -26,13 +26,22 @@
from pandas.io.formats.excel import ExcelFormatter
from pandas.io.parsers import read_csv
-_seriesd = tm.getSeriesData()
-_tsd = tm.getTimeSeriesData()
-_frame = DataFrame(_seriesd)[:10]
-_frame2 = DataFrame(_seriesd, columns=['D', 'C', 'B', 'A'])[:10]
-_tsframe = tm.makeTimeDataFrame()[:5]
-_mixed_frame = _frame.copy()
-_mixed_frame['foo'] = 'bar'
+
+@pytest.fixture
+def frame(float_frame):
+ return float_frame[:10]
+
+
+@pytest.fixture
+def frame2(float_frame):
+ float_frame = float_frame.copy()
+ float_frame.columns = ['D', 'C', 'B', 'A']
+ return float_frame[:10]
+
+
+@pytest.fixture
+def tsframe():
+ return tm.makeTimeDataFrame()[:5]
@contextlib.contextmanager
@@ -49,18 +58,8 @@ def ignore_xlrd_time_clock_warning():
yield
-class SharedItems:
-
- @pytest.fixture(autouse=True)
- def setup_method(self, datapath):
- self.frame = _frame.copy()
- self.frame2 = _frame2.copy()
- self.tsframe = _tsframe.copy()
- self.mixed_frame = _mixed_frame.copy()
-
-
@td.skip_if_no('xlrd', '1.0.0')
-class ReadingTestsBase(SharedItems):
+class ReadingTestsBase:
# This is based on ExcelWriterBase
@pytest.fixture(autouse=True, params=['xlrd', None])
@@ -1055,9 +1054,9 @@ class TestXlrdReader(ReadingTestsBase):
"""
@td.skip_if_no("xlwt")
- def test_read_xlrd_book(self, ext):
+ def test_read_xlrd_book(self, ext, frame):
import xlrd
- df = self.frame
+ df = frame
engine = "xlrd"
sheet_name = "SheetA"
@@ -1075,7 +1074,7 @@ def test_read_xlrd_book(self, ext):
tm.assert_frame_equal(df, result)
-class _WriterBase(SharedItems):
+class _WriterBase:
@pytest.fixture(autouse=True)
def set_engine_and_path(self, request, merge_cells, engine, ext):
@@ -1150,75 +1149,79 @@ def test_excel_sheet_by_name_raise(self, *_):
with pytest.raises(xlrd.XLRDError):
pd.read_excel(xl, "0")
- def test_excel_writer_context_manager(self, *_):
+ def test_excel_writer_context_manager(self, frame, frame2, *_):
with ExcelWriter(self.path) as writer:
- self.frame.to_excel(writer, "Data1")
- self.frame2.to_excel(writer, "Data2")
+ frame.to_excel(writer, "Data1")
+ frame2.to_excel(writer, "Data2")
with ExcelFile(self.path) as reader:
found_df = pd.read_excel(reader, "Data1", index_col=0)
found_df2 = pd.read_excel(reader, "Data2", index_col=0)
- tm.assert_frame_equal(found_df, self.frame)
- tm.assert_frame_equal(found_df2, self.frame2)
+ tm.assert_frame_equal(found_df, frame)
+ tm.assert_frame_equal(found_df2, frame2)
- def test_roundtrip(self, merge_cells, engine, ext):
- self.frame['A'][:5] = nan
+ def test_roundtrip(self, merge_cells, engine, ext, frame):
+ frame = frame.copy()
+ frame['A'][:5] = nan
- self.frame.to_excel(self.path, 'test1')
- self.frame.to_excel(self.path, 'test1', columns=['A', 'B'])
- self.frame.to_excel(self.path, 'test1', header=False)
- self.frame.to_excel(self.path, 'test1', index=False)
+ frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', index=False)
# test roundtrip
- self.frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1')
recons = pd.read_excel(self.path, 'test1', index_col=0)
- tm.assert_frame_equal(self.frame, recons)
+ tm.assert_frame_equal(frame, recons)
- self.frame.to_excel(self.path, 'test1', index=False)
+ frame.to_excel(self.path, 'test1', index=False)
recons = pd.read_excel(self.path, 'test1', index_col=None)
- recons.index = self.frame.index
- tm.assert_frame_equal(self.frame, recons)
+ recons.index = frame.index
+ tm.assert_frame_equal(frame, recons)
- self.frame.to_excel(self.path, 'test1', na_rep='NA')
+ frame.to_excel(self.path, 'test1', na_rep='NA')
recons = pd.read_excel(
self.path, 'test1', index_col=0, na_values=['NA'])
- tm.assert_frame_equal(self.frame, recons)
+ tm.assert_frame_equal(frame, recons)
# GH 3611
- self.frame.to_excel(self.path, 'test1', na_rep='88')
+ frame.to_excel(self.path, 'test1', na_rep='88')
recons = pd.read_excel(
self.path, 'test1', index_col=0, na_values=['88'])
- tm.assert_frame_equal(self.frame, recons)
+ tm.assert_frame_equal(frame, recons)
- self.frame.to_excel(self.path, 'test1', na_rep='88')
+ frame.to_excel(self.path, 'test1', na_rep='88')
recons = pd.read_excel(
self.path, 'test1', index_col=0, na_values=[88, 88.0])
- tm.assert_frame_equal(self.frame, recons)
+ tm.assert_frame_equal(frame, recons)
# GH 6573
- self.frame.to_excel(self.path, 'Sheet1')
+ frame.to_excel(self.path, 'Sheet1')
recons = pd.read_excel(self.path, index_col=0)
- tm.assert_frame_equal(self.frame, recons)
+ tm.assert_frame_equal(frame, recons)
- self.frame.to_excel(self.path, '0')
+ frame.to_excel(self.path, '0')
recons = pd.read_excel(self.path, index_col=0)
- tm.assert_frame_equal(self.frame, recons)
+ tm.assert_frame_equal(frame, recons)
# GH 8825 Pandas Series should provide to_excel method
- s = self.frame["A"]
+ s = frame["A"]
s.to_excel(self.path)
recons = pd.read_excel(self.path, index_col=0)
tm.assert_frame_equal(s.to_frame(), recons)
- def test_mixed(self, merge_cells, engine, ext):
- self.mixed_frame.to_excel(self.path, 'test1')
+ def test_mixed(self, merge_cells, engine, ext, frame):
+ mixed_frame = frame.copy()
+ mixed_frame['foo'] = 'bar'
+
+ mixed_frame.to_excel(self.path, 'test1')
reader = ExcelFile(self.path)
recons = pd.read_excel(reader, 'test1', index_col=0)
- tm.assert_frame_equal(self.mixed_frame, recons)
+ tm.assert_frame_equal(mixed_frame, recons)
- def test_ts_frame(self, *_):
- df = tm.makeTimeDataFrame()[:5]
+ def test_ts_frame(self, tsframe, *_):
+ df = tsframe
df.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
@@ -1226,33 +1229,34 @@ def test_ts_frame(self, *_):
recons = pd.read_excel(reader, "test1", index_col=0)
tm.assert_frame_equal(df, recons)
- def test_basics_with_nan(self, merge_cells, engine, ext):
- self.frame['A'][:5] = nan
- self.frame.to_excel(self.path, 'test1')
- self.frame.to_excel(self.path, 'test1', columns=['A', 'B'])
- self.frame.to_excel(self.path, 'test1', header=False)
- self.frame.to_excel(self.path, 'test1', index=False)
+ def test_basics_with_nan(self, merge_cells, engine, ext, frame):
+ frame = frame.copy()
+ frame['A'][:5] = nan
+ frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', index=False)
@pytest.mark.parametrize("np_type", [
np.int8, np.int16, np.int32, np.int64])
def test_int_types(self, merge_cells, engine, ext, np_type):
# Test np.int values read come back as int
# (rather than float which is Excel's format).
- frame = DataFrame(np.random.randint(-10, 10, size=(10, 2)),
- dtype=np_type)
- frame.to_excel(self.path, "test1")
+ df = DataFrame(np.random.randint(-10, 10, size=(10, 2)),
+ dtype=np_type)
+ df.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
recons = pd.read_excel(reader, "test1", index_col=0)
- int_frame = frame.astype(np.int64)
+ int_frame = df.astype(np.int64)
tm.assert_frame_equal(int_frame, recons)
recons2 = pd.read_excel(self.path, "test1", index_col=0)
tm.assert_frame_equal(int_frame, recons2)
# Test with convert_float=False comes back as float.
- float_frame = frame.astype(float)
+ float_frame = df.astype(float)
recons = pd.read_excel(self.path, "test1",
convert_float=False, index_col=0)
tm.assert_frame_equal(recons, float_frame,
@@ -1263,120 +1267,123 @@ def test_int_types(self, merge_cells, engine, ext, np_type):
np.float16, np.float32, np.float64])
def test_float_types(self, merge_cells, engine, ext, np_type):
# Test np.float values read come back as float.
- frame = DataFrame(np.random.random_sample(10), dtype=np_type)
- frame.to_excel(self.path, "test1")
+ df = DataFrame(np.random.random_sample(10), dtype=np_type)
+ df.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
recons = pd.read_excel(reader, "test1", index_col=0).astype(np_type)
- tm.assert_frame_equal(frame, recons, check_dtype=False)
+ tm.assert_frame_equal(df, recons, check_dtype=False)
@pytest.mark.parametrize("np_type", [np.bool8, np.bool_])
def test_bool_types(self, merge_cells, engine, ext, np_type):
# Test np.bool values read come back as float.
- frame = (DataFrame([1, 0, True, False], dtype=np_type))
- frame.to_excel(self.path, "test1")
+ df = (DataFrame([1, 0, True, False], dtype=np_type))
+ df.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
recons = pd.read_excel(reader, "test1", index_col=0).astype(np_type)
- tm.assert_frame_equal(frame, recons)
+ tm.assert_frame_equal(df, recons)
def test_inf_roundtrip(self, *_):
- frame = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)])
- frame.to_excel(self.path, "test1")
+ df = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)])
+ df.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
recons = pd.read_excel(reader, "test1", index_col=0)
- tm.assert_frame_equal(frame, recons)
+ tm.assert_frame_equal(df, recons)
- def test_sheets(self, merge_cells, engine, ext):
- self.frame['A'][:5] = nan
+ def test_sheets(self, merge_cells, engine, ext, frame, tsframe):
+ frame = frame.copy()
+ frame['A'][:5] = nan
- self.frame.to_excel(self.path, 'test1')
- self.frame.to_excel(self.path, 'test1', columns=['A', 'B'])
- self.frame.to_excel(self.path, 'test1', header=False)
- self.frame.to_excel(self.path, 'test1', index=False)
+ frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', index=False)
# Test writing to separate sheets
writer = ExcelWriter(self.path)
- self.frame.to_excel(writer, 'test1')
- self.tsframe.to_excel(writer, 'test2')
+ frame.to_excel(writer, 'test1')
+ tsframe.to_excel(writer, 'test2')
writer.save()
reader = ExcelFile(self.path)
recons = pd.read_excel(reader, 'test1', index_col=0)
- tm.assert_frame_equal(self.frame, recons)
+ tm.assert_frame_equal(frame, recons)
recons = pd.read_excel(reader, 'test2', index_col=0)
- tm.assert_frame_equal(self.tsframe, recons)
+ tm.assert_frame_equal(tsframe, recons)
assert 2 == len(reader.sheet_names)
assert 'test1' == reader.sheet_names[0]
assert 'test2' == reader.sheet_names[1]
- def test_colaliases(self, merge_cells, engine, ext):
- self.frame['A'][:5] = nan
+ def test_colaliases(self, merge_cells, engine, ext, frame, frame2):
+ frame = frame.copy()
+ frame['A'][:5] = nan
- self.frame.to_excel(self.path, 'test1')
- self.frame.to_excel(self.path, 'test1', columns=['A', 'B'])
- self.frame.to_excel(self.path, 'test1', header=False)
- self.frame.to_excel(self.path, 'test1', index=False)
+ frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', index=False)
# column aliases
col_aliases = Index(['AA', 'X', 'Y', 'Z'])
- self.frame2.to_excel(self.path, 'test1', header=col_aliases)
+ frame2.to_excel(self.path, 'test1', header=col_aliases)
reader = ExcelFile(self.path)
rs = pd.read_excel(reader, 'test1', index_col=0)
- xp = self.frame2.copy()
+ xp = frame2.copy()
xp.columns = col_aliases
tm.assert_frame_equal(xp, rs)
- def test_roundtrip_indexlabels(self, merge_cells, engine, ext):
- self.frame['A'][:5] = nan
+ def test_roundtrip_indexlabels(self, merge_cells, engine, ext, frame):
+ frame = frame.copy()
+ frame['A'][:5] = nan
- self.frame.to_excel(self.path, 'test1')
- self.frame.to_excel(self.path, 'test1', columns=['A', 'B'])
- self.frame.to_excel(self.path, 'test1', header=False)
- self.frame.to_excel(self.path, 'test1', index=False)
+ frame.to_excel(self.path, 'test1')
+ frame.to_excel(self.path, 'test1', columns=['A', 'B'])
+ frame.to_excel(self.path, 'test1', header=False)
+ frame.to_excel(self.path, 'test1', index=False)
# test index_label
- frame = (DataFrame(np.random.randn(10, 2)) >= 0)
- frame.to_excel(self.path, 'test1',
- index_label=['test'],
- merge_cells=merge_cells)
+ df = (DataFrame(np.random.randn(10, 2)) >= 0)
+ df.to_excel(self.path, 'test1',
+ index_label=['test'],
+ merge_cells=merge_cells)
reader = ExcelFile(self.path)
recons = pd.read_excel(
reader, 'test1', index_col=0).astype(np.int64)
- frame.index.names = ['test']
- assert frame.index.names == recons.index.names
-
- frame = (DataFrame(np.random.randn(10, 2)) >= 0)
- frame.to_excel(self.path,
- 'test1',
- index_label=['test', 'dummy', 'dummy2'],
- merge_cells=merge_cells)
+ df.index.names = ['test']
+ assert df.index.names == recons.index.names
+
+ df = (DataFrame(np.random.randn(10, 2)) >= 0)
+ df.to_excel(self.path,
+ 'test1',
+ index_label=['test', 'dummy', 'dummy2'],
+ merge_cells=merge_cells)
reader = ExcelFile(self.path)
recons = pd.read_excel(
reader, 'test1', index_col=0).astype(np.int64)
- frame.index.names = ['test']
- assert frame.index.names == recons.index.names
-
- frame = (DataFrame(np.random.randn(10, 2)) >= 0)
- frame.to_excel(self.path,
- 'test1',
- index_label='test',
- merge_cells=merge_cells)
+ df.index.names = ['test']
+ assert df.index.names == recons.index.names
+
+ df = (DataFrame(np.random.randn(10, 2)) >= 0)
+ df.to_excel(self.path,
+ 'test1',
+ index_label='test',
+ merge_cells=merge_cells)
reader = ExcelFile(self.path)
recons = pd.read_excel(
reader, 'test1', index_col=0).astype(np.int64)
- frame.index.names = ['test']
- tm.assert_frame_equal(frame, recons.astype(bool))
+ df.index.names = ['test']
+ tm.assert_frame_equal(df, recons.astype(bool))
- self.frame.to_excel(self.path,
- 'test1',
- columns=['A', 'B', 'C', 'D'],
- index=False, merge_cells=merge_cells)
+ frame.to_excel(self.path,
+ 'test1',
+ columns=['A', 'B', 'C', 'D'],
+ index=False, merge_cells=merge_cells)
# take 'A' and 'B' as indexes (same row as cols 'C', 'D')
- df = self.frame.copy()
+ df = frame.copy()
df = df.set_index(['A', 'B'])
reader = ExcelFile(self.path)
@@ -1395,17 +1402,17 @@ def test_excel_roundtrip_indexname(self, merge_cells, engine, ext):
tm.assert_frame_equal(result, df)
assert result.index.name == 'foo'
- def test_excel_roundtrip_datetime(self, merge_cells, *_):
+ def test_excel_roundtrip_datetime(self, merge_cells, tsframe, *_):
# datetime.date, not sure what to test here exactly
- tsf = self.tsframe.copy()
+ tsf = tsframe.copy()
- tsf.index = [x.date() for x in self.tsframe.index]
+ tsf.index = [x.date() for x in tsframe.index]
tsf.to_excel(self.path, "test1", merge_cells=merge_cells)
reader = ExcelFile(self.path)
recons = pd.read_excel(reader, "test1", index_col=0)
- tm.assert_frame_equal(self.tsframe, recons)
+ tm.assert_frame_equal(tsframe, recons)
def test_excel_date_datetime_format(self, merge_cells, engine, ext):
# see gh-4133
@@ -1450,14 +1457,14 @@ def test_to_excel_interval_no_labels(self, *_):
# see gh-19242
#
# Test writing Interval without labels.
- frame = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
- dtype=np.int64)
- expected = frame.copy()
+ df = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
+ dtype=np.int64)
+ expected = df.copy()
- frame["new"] = pd.cut(frame[0], 10)
+ df["new"] = pd.cut(df[0], 10)
expected["new"] = pd.cut(expected[0], 10).astype(str)
- frame.to_excel(self.path, "test1")
+ df.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
recons = pd.read_excel(reader, "test1", index_col=0)
@@ -1467,15 +1474,15 @@ def test_to_excel_interval_labels(self, *_):
# see gh-19242
#
# Test writing Interval with labels.
- frame = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
- dtype=np.int64)
- expected = frame.copy()
- intervals = pd.cut(frame[0], 10, labels=["A", "B", "C", "D", "E",
- "F", "G", "H", "I", "J"])
- frame["new"] = intervals
+ df = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
+ dtype=np.int64)
+ expected = df.copy()
+ intervals = pd.cut(df[0], 10, labels=["A", "B", "C", "D", "E",
+ "F", "G", "H", "I", "J"])
+ df["new"] = intervals
expected["new"] = pd.Series(list(intervals))
- frame.to_excel(self.path, "test1")
+ df.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
recons = pd.read_excel(reader, "test1", index_col=0)
@@ -1485,23 +1492,23 @@ def test_to_excel_timedelta(self, *_):
# see gh-19242, gh-9155
#
# Test writing timedelta to xls.
- frame = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
- columns=["A"], dtype=np.int64)
- expected = frame.copy()
+ df = DataFrame(np.random.randint(-10, 10, size=(20, 1)),
+ columns=["A"], dtype=np.int64)
+ expected = df.copy()
- frame["new"] = frame["A"].apply(lambda x: timedelta(seconds=x))
+ df["new"] = df["A"].apply(lambda x: timedelta(seconds=x))
expected["new"] = expected["A"].apply(
lambda x: timedelta(seconds=x).total_seconds() / float(86400))
- frame.to_excel(self.path, "test1")
+ df.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
recons = pd.read_excel(reader, "test1", index_col=0)
tm.assert_frame_equal(expected, recons)
- def test_to_excel_periodindex(self, merge_cells, engine, ext):
- frame = self.tsframe
- xp = frame.resample('M', kind='period').mean()
+ def test_to_excel_periodindex(
+ self, merge_cells, engine, ext, tsframe):
+ xp = tsframe.resample('M', kind='period').mean()
xp.to_excel(self.path, 'sht1')
@@ -1509,8 +1516,7 @@ def test_to_excel_periodindex(self, merge_cells, engine, ext):
rs = pd.read_excel(reader, 'sht1', index_col=0)
tm.assert_frame_equal(xp, rs.to_period('M'))
- def test_to_excel_multiindex(self, merge_cells, engine, ext):
- frame = self.frame
+ def test_to_excel_multiindex(self, merge_cells, engine, ext, frame):
arrays = np.arange(len(frame.index) * 2).reshape(2, -1)
new_index = MultiIndex.from_arrays(arrays,
names=['first', 'second'])
@@ -1526,21 +1532,21 @@ def test_to_excel_multiindex(self, merge_cells, engine, ext):
tm.assert_frame_equal(frame, df)
# GH13511
- def test_to_excel_multiindex_nan_label(self, merge_cells, engine, ext):
- frame = pd.DataFrame({'A': [None, 2, 3],
- 'B': [10, 20, 30],
- 'C': np.random.sample(3)})
- frame = frame.set_index(['A', 'B'])
-
- frame.to_excel(self.path, merge_cells=merge_cells)
- df = pd.read_excel(self.path, index_col=[0, 1])
- tm.assert_frame_equal(frame, df)
+ def test_to_excel_multiindex_nan_label(
+ self, merge_cells, engine, ext):
+ df = pd.DataFrame({'A': [None, 2, 3],
+ 'B': [10, 20, 30],
+ 'C': np.random.sample(3)})
+ df = df.set_index(['A', 'B'])
+
+ df.to_excel(self.path, merge_cells=merge_cells)
+ df1 = pd.read_excel(self.path, index_col=[0, 1])
+ tm.assert_frame_equal(df, df1)
# Test for Issue 11328. If column indices are integers, make
# sure they are handled correctly for either setting of
# merge_cells
- def test_to_excel_multiindex_cols(self, merge_cells, engine, ext):
- frame = self.frame
+ def test_to_excel_multiindex_cols(self, merge_cells, engine, ext, frame):
arrays = np.arange(len(frame.index) * 2).reshape(2, -1)
new_index = MultiIndex.from_arrays(arrays,
names=['first', 'second'])
@@ -1563,9 +1569,9 @@ def test_to_excel_multiindex_cols(self, merge_cells, engine, ext):
frame.columns = [".".join(map(str, q)) for q in zip(*fm)]
tm.assert_frame_equal(frame, df)
- def test_to_excel_multiindex_dates(self, merge_cells, engine, ext):
+ def test_to_excel_multiindex_dates(
+ self, merge_cells, engine, ext, tsframe):
# try multiindex with dates
- tsframe = self.tsframe.copy()
new_index = [tsframe.index, np.arange(len(tsframe.index))]
tsframe.index = MultiIndex.from_arrays(new_index)
| Pretty big step towards logically partitioning tests in this module - replaced SharedItems and instance attributes with fixtures. Should make subsequent test reorg easier
@simonjayhawkins | https://api.github.com/repos/pandas-dev/pandas/pulls/26579 | 2019-05-30T18:57:20Z | 2019-06-05T12:59:13Z | 2019-06-05T12:59:12Z | 2020-01-16T00:34:49Z |
TST: update tests\plotting\test_frame.py message check for mpl 3.1.0 | diff --git a/pandas/plotting/_compat.py b/pandas/plotting/_compat.py
index 4077bef8f36f5..36bbe0f4ec174 100644
--- a/pandas/plotting/_compat.py
+++ b/pandas/plotting/_compat.py
@@ -17,3 +17,4 @@ def inner():
_mpl_ge_2_2_3 = _mpl_version('2.2.3', operator.ge)
_mpl_ge_3_0_0 = _mpl_version('3.0.0', operator.ge)
+_mpl_ge_3_1_0 = _mpl_version('3.1.0', operator.ge)
diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py
index aede84ac831a6..f42f86540e46b 100644
--- a/pandas/tests/plotting/test_frame.py
+++ b/pandas/tests/plotting/test_frame.py
@@ -23,6 +23,7 @@
from pandas.io.formats.printing import pprint_thing
import pandas.plotting as plotting
+from pandas.plotting._compat import _mpl_ge_3_1_0
@td.skip_if_no_mpl
@@ -68,7 +69,11 @@ def test_plot(self):
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
df = DataFrame({'x': [1, 2], 'y': [3, 4]})
- with pytest.raises(AttributeError, match='Unknown property blarg'):
+ if _mpl_ge_3_1_0():
+ msg = "'Line2D' object has no property 'blarg'"
+ else:
+ msg = "Unknown property blarg"
+ with pytest.raises(AttributeError, match=msg):
df.plot.line(blarg=True)
df = DataFrame(np.random.rand(10, 3),
| new error message for df.plot.line
https://travis-ci.org/pandas-dev/pandas/jobs/539282780 | https://api.github.com/repos/pandas-dev/pandas/pulls/26577 | 2019-05-30T17:09:13Z | 2019-05-30T19:51:04Z | 2019-05-30T19:51:04Z | 2019-05-30T21:54:40Z |
PERF/CI: fix benchmark import error + run asv check on all builds | diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py
index 0c1d861ce0839..5b76eeba115a4 100644
--- a/asv_bench/benchmarks/frame_methods.py
+++ b/asv_bench/benchmarks/frame_methods.py
@@ -96,6 +96,8 @@ def time_dict_rename_both_axes(self):
class Iteration:
+ # mem_itertuples_* benchmarks are slow
+ timeout = 120
def setup(self):
N = 1000
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py
index 4dfce079dd09c..3097ada6d2022 100644
--- a/asv_bench/benchmarks/groupby.py
+++ b/asv_bench/benchmarks/groupby.py
@@ -1,12 +1,11 @@
from functools import partial
from itertools import product
from string import ascii_letters
-import warnings
import numpy as np
from pandas import (
- Categorical, DataFrame, MultiIndex, Series, TimeGrouper, Timestamp,
+ Categorical, DataFrame, MultiIndex, Series, Timestamp,
date_range, period_range)
import pandas.util.testing as tm
@@ -301,10 +300,6 @@ def setup(self):
def time_multi_size(self):
self.df.groupby(['key1', 'key2']).size()
- def time_dt_timegrouper_size(self):
- with warnings.catch_warnings(record=True):
- self.df.groupby(TimeGrouper(key='dates', freq='M')).size()
-
def time_category_size(self):
self.draws.groupby(self.cats).size()
diff --git a/asv_bench/benchmarks/io/parsers.py b/asv_bench/benchmarks/io/parsers.py
index 493955d394443..edba0358c821a 100644
--- a/asv_bench/benchmarks/io/parsers.py
+++ b/asv_bench/benchmarks/io/parsers.py
@@ -1,7 +1,11 @@
import numpy as np
-from pandas._libs.tslibs.parsing import (
- _concat_date_cols, _does_string_look_like_datetime)
+try:
+ from pandas._libs.tslibs.parsing import (
+ _concat_date_cols, _does_string_look_like_datetime)
+except ImportError:
+ # Avoid whole benchmark suite import failure on asv (currently 0.4)
+ pass
class DoesStringLookLikeDatetime(object):
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index eee38dadfab90..17eaee5458af8 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -97,10 +97,11 @@ jobs:
- script: |
export PATH=$HOME/miniconda3/bin:$PATH
source activate pandas-dev
+ cd asv_bench
+ asv check -E existing
git remote add upstream https://github.com/pandas-dev/pandas.git
git fetch upstream
if git diff upstream/master --name-only | grep -q "^asv_bench/"; then
- cd asv_bench
asv machine --yes
ASV_OUTPUT="$(asv dev)"
if [[ $(echo "$ASV_OUTPUT" | grep "failed") ]]; then
| Fix benchmark suite import error on master and 0.23.
Run `asv check` on all commits to lint the benchmark suite.
Also, fixed a timeout error that appears on newer asv versions,
which have an updated asizeof.py module. | https://api.github.com/repos/pandas-dev/pandas/pulls/26575 | 2019-05-30T14:31:41Z | 2019-05-30T19:16:58Z | 2019-05-30T19:16:58Z | 2019-05-30T19:17:06Z |
DOC: sparse doc fixups | diff --git a/doc/source/user_guide/sparse.rst b/doc/source/user_guide/sparse.rst
index 8fed29d7a6316..09ed895a847ff 100644
--- a/doc/source/user_guide/sparse.rst
+++ b/doc/source/user_guide/sparse.rst
@@ -269,7 +269,7 @@ have no replacement.
Interaction with scipy.sparse
-----------------------------
-Use :meth:`DataFrame.sparse.from_coo` to create a ``DataFrame`` with sparse values from a sparse matrix.
+Use :meth:`DataFrame.sparse.from_spmatrix` to create a ``DataFrame`` with sparse values from a sparse matrix.
.. versionadded:: 0.25.0
diff --git a/doc/source/whatsnew/v0.16.0.rst b/doc/source/whatsnew/v0.16.0.rst
index 1e4ec682f0504..2cb09325c9466 100644
--- a/doc/source/whatsnew/v0.16.0.rst
+++ b/doc/source/whatsnew/v0.16.0.rst
@@ -92,6 +92,7 @@ Interaction with scipy.sparse
Added :meth:`SparseSeries.to_coo` and :meth:`SparseSeries.from_coo` methods (:issue:`8048`) for converting to and from ``scipy.sparse.coo_matrix`` instances (see :ref:`here <sparse.scipysparse>`). For example, given a SparseSeries with MultiIndex we can convert to a `scipy.sparse.coo_matrix` by specifying the row and column labels as index levels:
.. ipython:: python
+ :okwarning:
s = pd.Series([3.0, np.nan, 1.0, 3.0, np.nan, np.nan])
s.index = pd.MultiIndex.from_tuples([(1, 2, 'a', 0),
@@ -121,6 +122,7 @@ The from_coo method is a convenience method for creating a ``SparseSeries``
from a ``scipy.sparse.coo_matrix``:
.. ipython:: python
+ :okwarning:
from scipy import sparse
A = sparse.coo_matrix(([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])),
diff --git a/doc/source/whatsnew/v0.18.1.rst b/doc/source/whatsnew/v0.18.1.rst
index f099ccf284bc2..069395c2e0f36 100644
--- a/doc/source/whatsnew/v0.18.1.rst
+++ b/doc/source/whatsnew/v0.18.1.rst
@@ -394,6 +394,7 @@ used in the ``pandas`` implementation (:issue:`12644`, :issue:`12638`, :issue:`1
An example of this signature augmentation is illustrated below:
.. ipython:: python
+ :okwarning:
sp = pd.SparseDataFrame([1, 2, 3])
sp
@@ -409,6 +410,7 @@ Previous behaviour:
New behaviour:
.. ipython:: python
+ :okwarning:
np.cumsum(sp, axis=0)
diff --git a/doc/source/whatsnew/v0.19.0.rst b/doc/source/whatsnew/v0.19.0.rst
index 29eeb415e2f6d..de29a1eb93709 100644
--- a/doc/source/whatsnew/v0.19.0.rst
+++ b/doc/source/whatsnew/v0.19.0.rst
@@ -1236,6 +1236,7 @@ Operators now preserve dtypes
- Sparse data structure now can preserve ``dtype`` after arithmetic ops (:issue:`13848`)
.. ipython:: python
+ :okwarning:
s = pd.SparseSeries([0, 2, 0, 1], fill_value=0, dtype=np.int64)
s.dtype
@@ -1245,6 +1246,7 @@ Operators now preserve dtypes
- Sparse data structure now support ``astype`` to convert internal ``dtype`` (:issue:`13900`)
.. ipython:: python
+ :okwarning:
s = pd.SparseSeries([1., 0., 2., 0.], fill_value=0)
s
diff --git a/doc/source/whatsnew/v0.20.0.rst b/doc/source/whatsnew/v0.20.0.rst
index 741aa6ca143bb..6a88a5810eca4 100644
--- a/doc/source/whatsnew/v0.20.0.rst
+++ b/doc/source/whatsnew/v0.20.0.rst
@@ -339,6 +339,7 @@ See the :ref:`documentation <sparse.scipysparse>` for more information. (:issue:
All sparse formats are supported, but matrices that are not in :mod:`COOrdinate <scipy.sparse>` format will be converted, copying data as needed.
.. ipython:: python
+ :okwarning:
from scipy.sparse import csr_matrix
arr = np.random.random(size=(1000, 5))
diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py
index fa3cd781eaf88..bf1cec7571f4d 100644
--- a/pandas/core/sparse/frame.py
+++ b/pandas/core/sparse/frame.py
@@ -42,7 +42,7 @@ class SparseDataFrame(DataFrame):
DataFrame containing sparse floating point data in the form of SparseSeries
objects
- .. deprectaed:: 0.25.0
+ .. deprecated:: 0.25.0
Use a DataFrame with sparse values instead.
diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py
index e4f8579a398dd..3f95acdbfb42c 100644
--- a/pandas/core/sparse/series.py
+++ b/pandas/core/sparse/series.py
@@ -46,7 +46,7 @@
class SparseSeries(Series):
"""Data structure for labeled, sparse floating point data
- .. deprectaed:: 0.25.0
+ .. deprecated:: 0.25.0
Use a Series with sparse values instead.
| https://api.github.com/repos/pandas-dev/pandas/pulls/26571 | 2019-05-30T11:29:20Z | 2019-06-01T14:35:26Z | 2019-06-01T14:35:26Z | 2019-06-02T15:26:33Z | |
PERF: don't call RangeIndex._data unnecessarily | diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py
index 896a20bae2069..78fe2ae966896 100644
--- a/asv_bench/benchmarks/index_object.py
+++ b/asv_bench/benchmarks/index_object.py
@@ -94,6 +94,12 @@ def time_min(self):
def time_min_trivial(self):
self.idx_inc.min()
+ def time_get_loc_inc(self):
+ self.idx_inc.get_loc(900000)
+
+ def time_get_loc_dec(self):
+ self.idx_dec.get_loc(100000)
+
class IndexAppend:
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index a62cac7a94bbd..1bd5d1ea9d922 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -393,6 +393,7 @@ Performance Improvements
- Improved performance of :meth:`Series.searchsorted`. The speedup is especially large when the dtype is
int8/int16/int32 and the searched key is within the integer bounds for the dtype (:issue:`22034`)
- Improved performance of :meth:`pandas.core.groupby.GroupBy.quantile` (:issue:`20405`)
+- Improved performance when slicing :class:`RangeIndex` (:issue:`26565`)
- Improved performance of :meth:`read_csv` by faster tokenizing and faster parsing of small float numbers (:issue:`25784`)
- Improved performance of :meth:`read_csv` by faster parsing of N/A and boolean values (:issue:`25804`)
- Improved performance of :meth:`IntervalIndex.is_monotonic`, :meth:`IntervalIndex.is_monotonic_increasing` and :meth:`IntervalIndex.is_monotonic_decreasing` by removing conversion to :class:`MultiIndex` (:issue:`24813`)
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index ea14a4c789cd3..9401de3346ccd 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -22,6 +22,8 @@
from pandas.core.indexes.base import Index, _index_shared_docs
from pandas.core.indexes.numeric import Int64Index
+from pandas.io.formats.printing import pprint_thing
+
class RangeIndex(Int64Index):
"""
@@ -64,6 +66,8 @@ class RangeIndex(Int64Index):
_typ = 'rangeindex'
_engine_type = libindex.Int64Engine
+ # check whether self._data has benn called
+ _cached_data = None # type: np.ndarray
# --------------------------------------------------------------------
# Constructors
@@ -164,6 +168,8 @@ def _simple_new(cls, start, stop=None, step=None, name=None,
for k, v in kwargs.items():
setattr(result, k, v)
+ result._range = range(result._start, result._stop, result._step)
+
result._reset_identity()
return result
@@ -180,9 +186,19 @@ def _constructor(self):
""" return the class to use for construction """
return Int64Index
- @cache_readonly
+ @property
def _data(self):
- return np.arange(self._start, self._stop, self._step, dtype=np.int64)
+ """
+ An int array that for performance reasons is created only when needed.
+
+ The constructed array is saved in ``_cached_data``. This allows us to
+ check if the array has been created without accessing ``_data`` and
+ triggering the construction.
+ """
+ if self._cached_data is None:
+ self._cached_data = np.arange(self._start, self._stop, self._step,
+ dtype=np.int64)
+ return self._cached_data
@cache_readonly
def _int64index(self):
@@ -215,6 +231,9 @@ def _format_data(self, name=None):
# we are formatting thru the attributes
return None
+ def _format_with_header(self, header, na_rep='NaN', **kwargs):
+ return header + list(map(pprint_thing, self._range))
+
# --------------------------------------------------------------------
@property
def start(self):
@@ -296,6 +315,15 @@ def is_monotonic_decreasing(self):
def has_duplicates(self):
return False
+ @Appender(_index_shared_docs['get_loc'])
+ def get_loc(self, key, method=None, tolerance=None):
+ if is_integer(key) and method is None and tolerance is None:
+ try:
+ return self._range.index(key)
+ except ValueError:
+ raise KeyError(key)
+ return super().get_loc(key, method=method, tolerance=tolerance)
+
def tolist(self):
return list(range(self._start, self._stop, self._step))
diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py
index b2c330015081c..477a4e527f278 100644
--- a/pandas/tests/indexes/test_range.py
+++ b/pandas/tests/indexes/test_range.py
@@ -241,6 +241,42 @@ def test_view(self):
def test_dtype(self):
assert self.index.dtype == np.int64
+ def test_cached_data(self):
+ # GH 26565
+ # Calling RangeIndex._data caches an int64 array of the same length at
+ # self._cached_data. This tests whether _cached_data has been set.
+ idx = RangeIndex(0, 100, 10)
+
+ assert idx._cached_data is None
+
+ repr(idx)
+ assert idx._cached_data is None
+
+ str(idx)
+ assert idx._cached_data is None
+
+ idx.get_loc(20)
+ assert idx._cached_data is None
+
+ df = pd.DataFrame({'a': range(10)}, index=idx)
+
+ df.loc[50]
+ assert idx._cached_data is None
+
+ with pytest.raises(KeyError):
+ df.loc[51]
+ assert idx._cached_data is None
+
+ df.loc[10:50]
+ assert idx._cached_data is None
+
+ df.iloc[5:10]
+ assert idx._cached_data is None
+
+ # actually calling data._data
+ assert isinstance(idx._data, np.ndarray)
+ assert isinstance(idx._cached_data, np.ndarray)
+
def test_is_monotonic(self):
assert self.index.is_monotonic is True
assert self.index.is_monotonic_increasing is True
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
I've looked into ``RangeIndex`` and found that the index type creates and caches a int64 array if/when ``RangeIndex._data`` property is being called. This basically means that in many cases, a ``RangeIndex`` has the same memory consumption and the same speed as an ``Int64Index``.
This PR improves on that situation by giving ``RangeIndex`` custom ``.get_loc`` and ``._format_with_header`` methods. This avoids the calls to ``._data`` in some cases, which helps on the speed and memory consumption (see performance improvements below). There are probably other case where ``RangeIndex._data`` can be avoided, which I'll investigate over the coming days.
```python
>>> %timeit pd.RangeIndex(1_000_000).get_loc(900_000)
8.95 ms ± 485 µs per loop # master
4.31 µs ± 303 ns per loop # this PR
>>> rng = pd.RangeIndex(1_000_000)
>>> %timeit rng.get_loc(900_000)
17.3 µs ± 392 ns per loop # master
547 ns ± 8.26 ns per loop # this PR. get_loc is now lightningly fast
>>> df = pd.DataFrame({'a': range(1_000_000)})
>>> %timeit df.loc[800_000: 900_000]
132 µs ± 5.79 µs per loop # master
89 µs ± 2.95 µs per loop # this PR
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/26565 | 2019-05-29T19:50:55Z | 2019-06-01T17:03:59Z | 2019-06-01T17:03:59Z | 2019-06-01T17:28:14Z |
Provide ExtensionDtype.construct_from_string by default | diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py
index 42aa6a055acca..29337b7f76131 100644
--- a/pandas/core/arrays/integer.py
+++ b/pandas/core/arrays/integer.py
@@ -78,17 +78,6 @@ def construct_array_type(cls):
"""
return IntegerArray
- @classmethod
- def construct_from_string(cls, string):
- """
- Construction from a string, raise a TypeError if not
- possible
- """
- if string == cls.name:
- return cls()
- raise TypeError("Cannot construct a '{}' from "
- "'{}'".format(cls, string))
-
def integer_array(values, dtype=None, copy=False):
"""
diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index da8908ec39095..0a0ba69659570 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -172,17 +172,27 @@ def construct_array_type(cls):
raise NotImplementedError
@classmethod
- def construct_from_string(cls, string):
- """
- Attempt to construct this type from a string.
+ def construct_from_string(cls, string: str):
+ r"""
+ Construct this type from a string.
+
+ This is useful mainly for data types that accept parameters.
+ For example, a period dtype accepts a frequency parameter that
+ can be set as ``period[H]`` (where H means hourly frequency).
+
+ By default, in the abstract class, just the name of the type is
+ expected. But subclasses can overwrite this method to accept
+ parameters.
Parameters
----------
string : str
+ The name of the type, for example ``category``.
Returns
-------
- self : instance of 'cls'
+ ExtensionDtype
+ Instance of the dtype.
Raises
------
@@ -191,21 +201,26 @@ def construct_from_string(cls, string):
Examples
--------
- If the extension dtype can be constructed without any arguments,
- the following may be an adequate implementation.
+ For extension dtypes with arguments the following may be an
+ adequate implementation.
>>> @classmethod
- ... def construct_from_string(cls, string)
- ... if string == cls.name:
- ... return cls()
+ ... def construct_from_string(cls, string):
+ ... pattern = re.compile(r"^my_type\[(?P<arg_name>.+)\]$")
+ ... match = pattern.match(string)
+ ... if match:
+ ... return cls(**match.groupdict())
... else:
... raise TypeError("Cannot construct a '{}' from "
- ... "'{}'".format(cls, string))
+ ... "'{}'".format(cls.__name__, string))
"""
- raise AbstractMethodError(cls)
+ if string != cls.name:
+ raise TypeError("Cannot construct a '{}' from '{}'".format(
+ cls.__name__, string))
+ return cls()
@classmethod
- def is_dtype(cls, dtype):
+ def is_dtype(cls, dtype) -> bool:
"""Check if we match 'dtype'.
Parameters
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index 32047c3fbb5e1..a56ee72cf1910 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -440,19 +440,6 @@ def construct_array_type(cls):
from pandas import Categorical
return Categorical
- @classmethod
- def construct_from_string(cls, string):
- """
- attempt to construct this type from a string, raise a TypeError if
- it's not possible """
- try:
- if string == 'category':
- return cls()
- else:
- raise TypeError("cannot construct a CategoricalDtype")
- except AttributeError:
- pass
-
@staticmethod
def validate_ordered(ordered):
"""
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index 79ebfcc30a7e4..cf368f9980d72 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -82,7 +82,7 @@ def test_equality(self):
def test_construction_from_string(self):
result = CategoricalDtype.construct_from_string('category')
assert is_dtype_equal(self.dtype, result)
- msg = "cannot construct a CategoricalDtype"
+ msg = "Cannot construct a 'CategoricalDtype' from 'foo'"
with pytest.raises(TypeError, match=msg):
CategoricalDtype.construct_from_string('foo')
diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py
index e9d1f183812cc..7b9dedceb00d4 100644
--- a/pandas/tests/extension/base/dtype.py
+++ b/pandas/tests/extension/base/dtype.py
@@ -1,6 +1,7 @@
import warnings
import numpy as np
+import pytest
import pandas as pd
@@ -89,3 +90,16 @@ def test_check_dtype(self, data):
def test_hashable(self, dtype):
hash(dtype) # no error
+
+ def test_str(self, dtype):
+ assert str(dtype) == dtype.name
+
+ def test_eq(self, dtype):
+ assert dtype == dtype.name
+ assert dtype != 'anonther_type'
+
+ def test_construct_from_string(self, dtype):
+ dtype_instance = dtype.__class__.construct_from_string(dtype.name)
+ assert isinstance(dtype_instance, dtype.__class__)
+ with pytest.raises(TypeError):
+ dtype.__class__.construct_from_string('another_type')
| - [ ] closes #xxxx
- [X] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
I think it makes sense to provide a standard `construct_from_string` by default, instead of forcing subclasses of `ExtensionDtype` to implement it.
This way we can define a simple dtype with:
```python
class SimpleDtype(pandas.core.dtypes.dtypes.ExtensionDtype):
name = 'simple'
@property
def type(self):
return object
```
instead of:
```python
class SimpleDtype(pandas.core.dtypes.dtypes.ExtensionDtype):
name = 'simple'
@property
def type(self):
return object
@classmethod
def construct_from_string(cls, string):
if string != cls.name:
raise TypeError("Cannot construct a '{}' from '{}'".format(
cls.__name__, string))
return cls()
```
CC: @TomAugspurger | https://api.github.com/repos/pandas-dev/pandas/pulls/26562 | 2019-05-29T16:26:27Z | 2019-06-06T14:28:26Z | 2019-06-06T14:28:26Z | 2019-06-11T07:51:54Z |
BUG: ignore errors for invalid dates in to_datetime() with errors=coerce (#25512) | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 32faf7115f0fd..e81bc57317c89 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -359,6 +359,7 @@ Datetimelike
- Bug in :class:`Series` and :class:`DataFrame` repr where ``np.datetime64('NaT')`` and ``np.timedelta64('NaT')`` with ``dtype=object`` would be represented as ``NaN`` (:issue:`25445`)
- Bug in :func:`to_datetime` which does not replace the invalid argument with ``NaT`` when error is set to coerce (:issue:`26122`)
- Bug in adding :class:`DateOffset` with nonzero month to :class:`DatetimeIndex` would raise ``ValueError`` (:issue:`26258`)
+- Bug in :func:`to_datetime` which raises unhandled ``OverflowError`` when called with mix of invalid dates and ``NaN`` values with ``format='%Y%m%d'`` and ``error='coerce'`` (:issue:`25512`)
Timedelta
^^^^^^^^^
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 817d539d4ad6f..a39b65ab72aa8 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -775,21 +775,21 @@ def calc_with_mask(carg, mask):
# try intlike / strings that are ints
try:
return calc(arg.astype(np.int64))
- except ValueError:
+ except (ValueError, OverflowError):
pass
# a float with actual np.nan
try:
carg = arg.astype(np.float64)
return calc_with_mask(carg, notna(carg))
- except ValueError:
+ except (ValueError, OverflowError):
pass
# string with NaN-like
try:
mask = ~algorithms.isin(arg, list(tslib.nat_strings))
return calc_with_mask(arg, mask)
- except ValueError:
+ except (ValueError, OverflowError):
pass
return None
diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py
index d62d8d1276fec..c507c31ee54dd 100644
--- a/pandas/tests/indexes/datetimes/test_tools.py
+++ b/pandas/tests/indexes/datetimes/test_tools.py
@@ -96,6 +96,25 @@ def test_to_datetime_format_YYYYMMDD(self, cache):
result = pd.to_datetime(s, format='%Y%m%d', errors='coerce',
cache=cache)
expected = Series(['20121231', '20141231', 'NaT'], dtype='M8[ns]')
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("input_s, expected", [
+ # NaN before strings with invalid date values
+ [Series(['19801222', np.nan, '20010012', '10019999']),
+ Series([Timestamp('19801222'), np.nan, np.nan, np.nan])],
+ # NaN after strings with invalid date values
+ [Series(['19801222', '20010012', '10019999', np.nan]),
+ Series([Timestamp('19801222'), np.nan, np.nan, np.nan])],
+ # NaN before integers with invalid date values
+ [Series([20190813, np.nan, 20010012, 20019999]),
+ Series([Timestamp('20190813'), np.nan, np.nan, np.nan])],
+ # NaN after integers with invalid date values
+ [Series([20190813, 20010012, np.nan, 20019999]),
+ Series([Timestamp('20190813'), np.nan, np.nan, np.nan])]])
+ def test_to_datetime_format_YYYYMMDD_overflow(self, input_s, expected):
+ # GH 25512
+ # format='%Y%m%d', errors='coerce'
+ result = pd.to_datetime(input_s, format='%Y%m%d', errors='coerce')
assert_series_equal(result, expected)
@pytest.mark.parametrize('cache', [True, False])
| - [x] closes #25512
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
parsing.try_parse_year_month_day() in _attempt_YYYYMMDD() throws not only ValueError but also OverFlowError for incorrect dates. So handling of this error was added.
| https://api.github.com/repos/pandas-dev/pandas/pulls/26561 | 2019-05-29T11:20:50Z | 2019-06-01T14:45:07Z | 2019-06-01T14:45:07Z | 2019-06-01T14:45:56Z |
TST/CLN: Fixturize tests/frame/test_quantile.py | diff --git a/pandas/tests/frame/test_quantile.py b/pandas/tests/frame/test_quantile.py
index a5771839e0997..9ccbd290923ba 100644
--- a/pandas/tests/frame/test_quantile.py
+++ b/pandas/tests/frame/test_quantile.py
@@ -3,24 +3,24 @@
import pandas as pd
from pandas import DataFrame, Series, Timestamp
-from pandas.tests.frame.common import TestData
import pandas.util.testing as tm
from pandas.util.testing import assert_frame_equal, assert_series_equal
-class TestDataFrameQuantile(TestData):
+class TestDataFrameQuantile:
- def test_quantile(self):
+ def test_quantile(self, datetime_frame):
from numpy import percentile
- q = self.tsframe.quantile(0.1, axis=0)
- assert q['A'] == percentile(self.tsframe['A'], 10)
- tm.assert_index_equal(q.index, self.tsframe.columns)
+ df = datetime_frame
+ q = df.quantile(0.1, axis=0)
+ assert q['A'] == percentile(df['A'], 10)
+ tm.assert_index_equal(q.index, df.columns)
- q = self.tsframe.quantile(0.9, axis=1)
+ q = df.quantile(0.9, axis=1)
assert (q['2000-01-17'] ==
- percentile(self.tsframe.loc['2000-01-17'], 90))
- tm.assert_index_equal(q.index, self.tsframe.index)
+ percentile(df.loc['2000-01-17'], 90))
+ tm.assert_index_equal(q.index, df.index)
# test degenerate case
q = DataFrame({'x': [], 'y': []}).quantile(0.1, axis=0)
@@ -99,18 +99,6 @@ def test_quantile_axis_parameter(self):
def test_quantile_interpolation(self):
# see gh-10174
- from numpy import percentile
-
- # interpolation = linear (default case)
- q = self.tsframe.quantile(0.1, axis=0, interpolation='linear')
- assert q['A'] == percentile(self.tsframe['A'], 10)
- q = self.intframe.quantile(0.1)
- assert q['A'] == percentile(self.intframe['A'], 10)
-
- # test with and without interpolation keyword
- q1 = self.intframe.quantile(0.1)
- assert q1['A'] == np.percentile(self.intframe['A'], 10)
- tm.assert_series_equal(q, q1)
# interpolation method other than default linear
df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3])
@@ -155,6 +143,28 @@ def test_quantile_interpolation(self):
index=[.25, .5], columns=['a', 'b', 'c'])
assert_frame_equal(result, expected)
+ def test_quantile_interpolation_datetime(self, datetime_frame):
+ # see gh-10174
+
+ # interpolation = linear (default case)
+ df = datetime_frame
+ q = df.quantile(0.1, axis=0, interpolation='linear')
+ assert q['A'] == np.percentile(df['A'], 10)
+
+ def test_quantile_interpolation_int(self, int_frame):
+ # see gh-10174
+
+ df = int_frame
+ # interpolation = linear (default case)
+ q = df.quantile(0.1)
+ assert q['A'] == np.percentile(df['A'], 10)
+
+ # test with and without interpolation keyword
+ # TODO: q1 is not different from q
+ q1 = df.quantile(0.1)
+ assert q1['A'] == np.percentile(df['A'], 10)
+ tm.assert_series_equal(q, q1)
+
def test_quantile_multi(self):
df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]],
columns=['a', 'b', 'c'])
@@ -214,11 +224,11 @@ def test_quantile_datetime(self):
# result = df[['a', 'c']].quantile(.5)
# result = df[['a', 'c']].quantile([.5])
- def test_quantile_invalid(self):
+ def test_quantile_invalid(self, datetime_frame):
msg = 'percentiles should all be in the interval \\[0, 1\\]'
for invalid in [-1, 2, [0.5, -1], [0.5, 2]]:
with pytest.raises(ValueError, match=msg):
- self.tsframe.quantile(invalid)
+ datetime_frame.quantile(invalid)
def test_quantile_box(self):
df = DataFrame({'A': [pd.Timestamp('2011-01-01'),
| - xref #22471
- passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/26556 | 2019-05-29T07:29:18Z | 2019-06-01T14:48:37Z | 2019-06-01T14:48:37Z | 2019-06-01T14:48:43Z |
Remove Unnecessary Subclasses from test_excel | diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 3af6be7a371e7..24412b26b021b 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -591,7 +591,7 @@ class ExcelWriter(metaclass=abc.ABCMeta):
def __new__(cls, path, engine=None, **kwargs):
# only switch class if generic(ExcelWriter)
- if issubclass(cls, ExcelWriter):
+ if cls is ExcelWriter:
if engine is None or (isinstance(engine, str) and
engine == 'auto'):
if isinstance(path, str):
diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py
index 100de227aa97c..8b871caae58a6 100644
--- a/pandas/tests/io/test_excel.py
+++ b/pandas/tests/io/test_excel.py
@@ -2065,11 +2065,10 @@ def test_path_local_path(self, merge_cells, engine, ext):
@td.skip_if_no('openpyxl')
-@pytest.mark.parametrize("merge_cells,ext,engine", [
- (None, '.xlsx', 'openpyxl')])
-class TestOpenpyxlTests(_WriterBase):
+@pytest.mark.parametrize("ext", ['.xlsx'])
+class TestOpenpyxlTests:
- def test_to_excel_styleconverter(self, merge_cells, ext, engine):
+ def test_to_excel_styleconverter(self, ext):
from openpyxl import styles
hstyle = {
@@ -2123,7 +2122,7 @@ def test_to_excel_styleconverter(self, merge_cells, ext, engine):
assert kw['number_format'] == number_format
assert kw['protection'] == protection
- def test_write_cells_merge_styled(self, merge_cells, ext, engine):
+ def test_write_cells_merge_styled(self, ext):
from pandas.io.formats.excel import ExcelCell
sheet_name = 'merge_styled'
@@ -2157,7 +2156,7 @@ def test_write_cells_merge_styled(self, merge_cells, ext, engine):
@pytest.mark.parametrize("mode,expected", [
('w', ['baz']), ('a', ['foo', 'bar', 'baz'])])
- def test_write_append_mode(self, merge_cells, ext, engine, mode, expected):
+ def test_write_append_mode(self, ext, mode, expected):
import openpyxl
df = DataFrame([1], columns=['baz'])
@@ -2169,7 +2168,7 @@ def test_write_append_mode(self, merge_cells, ext, engine, mode, expected):
wb.worksheets[1]['A1'].value = 'bar'
wb.save(f)
- writer = ExcelWriter(f, engine=engine, mode=mode)
+ writer = ExcelWriter(f, engine='openpyxl', mode=mode)
df.to_excel(writer, sheet_name='baz', index=False)
writer.save()
@@ -2182,12 +2181,11 @@ def test_write_append_mode(self, merge_cells, ext, engine, mode, expected):
@td.skip_if_no('xlwt')
-@pytest.mark.parametrize("merge_cells,ext,engine", [
- (None, '.xls', 'xlwt')])
-class TestXlwtTests(_WriterBase):
+@pytest.mark.parametrize("ext,", ['.xls'])
+class TestXlwtTests:
def test_excel_raise_error_on_multiindex_columns_and_no_index(
- self, merge_cells, ext, engine):
+ self, ext):
# MultiIndex as columns is not yet implemented 9794
cols = MultiIndex.from_tuples([('site', ''),
('2014', 'height'),
@@ -2197,8 +2195,7 @@ def test_excel_raise_error_on_multiindex_columns_and_no_index(
with ensure_clean(ext) as path:
df.to_excel(path, index=False)
- def test_excel_multiindex_columns_and_index_true(self, merge_cells, ext,
- engine):
+ def test_excel_multiindex_columns_and_index_true(self, ext):
cols = MultiIndex.from_tuples([('site', ''),
('2014', 'height'),
('2014', 'weight')])
@@ -2206,7 +2203,7 @@ def test_excel_multiindex_columns_and_index_true(self, merge_cells, ext,
with ensure_clean(ext) as path:
df.to_excel(path, index=True)
- def test_excel_multiindex_index(self, merge_cells, ext, engine):
+ def test_excel_multiindex_index(self, ext):
# MultiIndex as index works so assert no error #9794
cols = MultiIndex.from_tuples([('site', ''),
('2014', 'height'),
@@ -2215,7 +2212,7 @@ def test_excel_multiindex_index(self, merge_cells, ext, engine):
with ensure_clean(ext) as path:
df.to_excel(path, index=False)
- def test_to_excel_styleconverter(self, merge_cells, ext, engine):
+ def test_to_excel_styleconverter(self, ext):
import xlwt
hstyle = {"font": {"bold": True},
@@ -2234,21 +2231,20 @@ def test_to_excel_styleconverter(self, merge_cells, ext, engine):
assert xlwt.Alignment.HORZ_CENTER == xls_style.alignment.horz
assert xlwt.Alignment.VERT_TOP == xls_style.alignment.vert
- def test_write_append_mode_raises(self, merge_cells, ext, engine):
+ def test_write_append_mode_raises(self, ext):
msg = "Append mode is not supported with xlwt!"
with ensure_clean(ext) as f:
with pytest.raises(ValueError, match=msg):
- ExcelWriter(f, engine=engine, mode='a')
+ ExcelWriter(f, engine='xlwt', mode='a')
@td.skip_if_no('xlsxwriter')
-@pytest.mark.parametrize("merge_cells,ext,engine", [
- (None, '.xlsx', 'xlsxwriter')])
-class TestXlsxWriterTests(_WriterBase):
+@pytest.mark.parametrize("ext", ['.xlsx'])
+class TestXlsxWriterTests:
@td.skip_if_no('openpyxl')
- def test_column_format(self, merge_cells, ext, engine):
+ def test_column_format(self, ext):
# Test that column formats are applied to cells. Test for issue #9167.
# Applicable to xlsxwriter only.
with warnings.catch_warnings():
@@ -2292,12 +2288,12 @@ def test_column_format(self, merge_cells, ext, engine):
assert read_num_format == num_format
- def test_write_append_mode_raises(self, merge_cells, ext, engine):
+ def test_write_append_mode_raises(self, ext):
msg = "Append mode is not supported with xlsxwriter!"
with ensure_clean(ext) as f:
with pytest.raises(ValueError, match=msg):
- ExcelWriter(f, engine=engine, mode='a')
+ ExcelWriter(f, engine='xlsxwriter', mode='a')
class TestExcelWriterEngineTests:
| More cleanup... | https://api.github.com/repos/pandas-dev/pandas/pulls/26553 | 2019-05-29T05:14:28Z | 2019-05-30T01:49:17Z | 2019-05-30T01:49:17Z | 2019-05-30T01:49:20Z |
xfail constructor test for numpydev | diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py
index bd871c47fa08b..3499d631376d8 100644
--- a/pandas/compat/numpy/__init__.py
+++ b/pandas/compat/numpy/__init__.py
@@ -12,6 +12,7 @@
_np_version_under1p15 = _nlv < LooseVersion('1.15')
_np_version_under1p16 = _nlv < LooseVersion('1.16')
_np_version_under1p17 = _nlv < LooseVersion('1.17')
+_is_numpy_dev = '.dev' in str(_nlv)
if _nlv < '1.13.3':
@@ -64,5 +65,6 @@ def np_array_datetime64_compat(arr, *args, **kwargs):
'_np_version_under1p14',
'_np_version_under1p15',
'_np_version_under1p16',
- '_np_version_under1p17'
+ '_np_version_under1p17',
+ '_is_numpy_dev'
]
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 68017786eb6a6..f371f4e93a29e 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -15,7 +15,7 @@
import pandas as pd
from pandas import (
Categorical, DataFrame, Index, MultiIndex, RangeIndex, Series, Timedelta,
- Timestamp, date_range, isna)
+ Timestamp, compat, date_range, isna)
from pandas.tests.frame.common import TestData
import pandas.util.testing as tm
@@ -113,6 +113,7 @@ def test_constructor_dtype_list_data(self):
assert df.loc[1, 0] is None
assert df.loc[0, 1] == '2'
+ @pytest.mark.xfail(compat.numpy._is_numpy_dev, reason="GH-26546")
def test_constructor_list_frames(self):
# see gh-3243
result = DataFrame([DataFrame()])
| xref #26546. It seems like that will be fixed upstream, which will require new wheels. xfailing for now.
When fixed and new wheels are available, this will fail again, but we can merge PRs in the meantime. | https://api.github.com/repos/pandas-dev/pandas/pulls/26548 | 2019-05-28T17:05:01Z | 2019-05-28T20:21:42Z | 2019-05-28T20:21:41Z | 2019-05-28T20:21:52Z |
CI: unary operator expected error in log files | diff --git a/ci/setup_env.sh b/ci/setup_env.sh
index e2667558a63d7..8f73bb228e2bd 100755
--- a/ci/setup_env.sh
+++ b/ci/setup_env.sh
@@ -118,12 +118,12 @@ echo "conda list"
conda list
# Install DB for Linux
-if [ ${TRAVIS_OS_NAME} == "linux" ]; then
+if [ "${TRAVIS_OS_NAME}" == "linux" ]; then
echo "installing dbs"
mysql -e 'create database pandas_nosetest;'
psql -c 'create database pandas_nosetest;' -U postgres
else
- echo "not using dbs on non-linux"
+ echo "not using dbs on non-linux Travis builds or Azure Pipelines"
fi
echo "done"
| fix error in azure log
```
ci/setup_env.sh: line 121: [: ==: unary operator expected
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/26547 | 2019-05-28T13:57:11Z | 2019-05-29T10:17:25Z | 2019-05-29T10:17:25Z | 2019-05-29T10:18:52Z |
Fixturize Test Excel | diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py
index 100de227aa97c..6db3d1d4ab34d 100644
--- a/pandas/tests/io/test_excel.py
+++ b/pandas/tests/io/test_excel.py
@@ -22,7 +22,7 @@
from pandas.io.common import URLError
from pandas.io.excel import (
ExcelFile, ExcelWriter, _OpenpyxlWriter, _XlsxWriter, _XlwtWriter,
- read_excel, register_writer)
+ register_writer)
from pandas.io.formats.excel import ExcelFormatter
from pandas.io.parsers import read_csv
@@ -53,7 +53,6 @@ class SharedItems:
@pytest.fixture(autouse=True)
def setup_method(self, datapath):
- self.dirpath = datapath("io", "data")
self.frame = _frame.copy()
self.frame2 = _frame2.copy()
self.tsframe = _tsframe.copy()
@@ -65,135 +64,85 @@ class ReadingTestsBase(SharedItems):
# This is based on ExcelWriterBase
@pytest.fixture(autouse=True, params=['xlrd', None])
- def set_engine(self, request):
- func_name = "get_exceldf"
- old_func = getattr(self, func_name)
- new_func = partial(old_func, engine=request.param)
- setattr(self, func_name, new_func)
- yield
- setattr(self, func_name, old_func)
-
- def get_csv_refdf(self, basename):
+ def cd_and_set_engine(self, request, datapath, monkeypatch):
"""
- Obtain the reference data from read_csv with the Python engine.
-
- Parameters
- ----------
-
- basename : str
- File base name, excluding file extension.
-
- Returns
- -------
-
- dfref : DataFrame
+ Change directory and set engine for read_excel calls.
"""
- pref = os.path.join(self.dirpath, basename + '.csv')
- dfref = read_csv(pref, index_col=0, parse_dates=True, engine='python')
- return dfref
+ func = partial(pd.read_excel, engine=request.param)
+ monkeypatch.chdir(datapath("io", "data"))
+ monkeypatch.setattr(pd, 'read_excel', func)
- def get_excelfile(self, basename, ext):
+ @pytest.fixture
+ def df_ref(self):
"""
- Return test data ExcelFile instance.
-
- Parameters
- ----------
-
- basename : str
- File base name, excluding file extension.
-
- Returns
- -------
-
- excel : io.excel.ExcelFile
- """
- return ExcelFile(os.path.join(self.dirpath, basename + ext))
-
- def get_exceldf(self, basename, ext, *args, **kwds):
- """
- Return test data DataFrame.
-
- Parameters
- ----------
-
- basename : str
- File base name, excluding file extension.
-
- Returns
- -------
-
- df : DataFrame
+ Obtain the reference data from read_csv with the Python engine.
"""
- pth = os.path.join(self.dirpath, basename + ext)
- return read_excel(pth, *args, **kwds)
+ df_ref = read_csv('test1.csv', index_col=0,
+ parse_dates=True, engine='python')
+ return df_ref
@td.skip_if_no("xlrd", "1.0.1") # see gh-22682
- def test_usecols_int(self, ext):
-
- df_ref = self.get_csv_refdf("test1")
+ def test_usecols_int(self, ext, df_ref):
df_ref = df_ref.reindex(columns=["A", "B", "C"])
# usecols as int
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
with ignore_xlrd_time_clock_warning():
- df1 = self.get_exceldf("test1", ext, "Sheet1",
- index_col=0, usecols=3)
+ df1 = pd.read_excel("test1" + ext, "Sheet1",
+ index_col=0, usecols=3)
# usecols as int
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
with ignore_xlrd_time_clock_warning():
- df2 = self.get_exceldf("test1", ext, "Sheet2", skiprows=[1],
- index_col=0, usecols=3)
+ df2 = pd.read_excel("test1" + ext, "Sheet2", skiprows=[1],
+ index_col=0, usecols=3)
# TODO add index to xls file)
tm.assert_frame_equal(df1, df_ref, check_names=False)
tm.assert_frame_equal(df2, df_ref, check_names=False)
@td.skip_if_no('xlrd', '1.0.1') # GH-22682
- def test_usecols_list(self, ext):
+ def test_usecols_list(self, ext, df_ref):
- dfref = self.get_csv_refdf('test1')
- dfref = dfref.reindex(columns=['B', 'C'])
- df1 = self.get_exceldf('test1', ext, 'Sheet1', index_col=0,
- usecols=[0, 2, 3])
- df2 = self.get_exceldf('test1', ext, 'Sheet2', skiprows=[1],
- index_col=0, usecols=[0, 2, 3])
+ df_ref = df_ref.reindex(columns=['B', 'C'])
+ df1 = pd.read_excel('test1' + ext, 'Sheet1', index_col=0,
+ usecols=[0, 2, 3])
+ df2 = pd.read_excel('test1' + ext, 'Sheet2', skiprows=[1],
+ index_col=0, usecols=[0, 2, 3])
# TODO add index to xls file)
- tm.assert_frame_equal(df1, dfref, check_names=False)
- tm.assert_frame_equal(df2, dfref, check_names=False)
+ tm.assert_frame_equal(df1, df_ref, check_names=False)
+ tm.assert_frame_equal(df2, df_ref, check_names=False)
@td.skip_if_no('xlrd', '1.0.1') # GH-22682
- def test_usecols_str(self, ext):
+ def test_usecols_str(self, ext, df_ref):
- dfref = self.get_csv_refdf('test1')
-
- df1 = dfref.reindex(columns=['A', 'B', 'C'])
- df2 = self.get_exceldf('test1', ext, 'Sheet1', index_col=0,
- usecols='A:D')
- df3 = self.get_exceldf('test1', ext, 'Sheet2', skiprows=[1],
- index_col=0, usecols='A:D')
+ df1 = df_ref.reindex(columns=['A', 'B', 'C'])
+ df2 = pd.read_excel('test1' + ext, 'Sheet1', index_col=0,
+ usecols='A:D')
+ df3 = pd.read_excel('test1' + ext, 'Sheet2', skiprows=[1],
+ index_col=0, usecols='A:D')
# TODO add index to xls, read xls ignores index name ?
tm.assert_frame_equal(df2, df1, check_names=False)
tm.assert_frame_equal(df3, df1, check_names=False)
- df1 = dfref.reindex(columns=['B', 'C'])
- df2 = self.get_exceldf('test1', ext, 'Sheet1', index_col=0,
- usecols='A,C,D')
- df3 = self.get_exceldf('test1', ext, 'Sheet2', skiprows=[1],
- index_col=0, usecols='A,C,D')
+ df1 = df_ref.reindex(columns=['B', 'C'])
+ df2 = pd.read_excel('test1' + ext, 'Sheet1', index_col=0,
+ usecols='A,C,D')
+ df3 = pd.read_excel('test1' + ext, 'Sheet2', skiprows=[1],
+ index_col=0, usecols='A,C,D')
# TODO add index to xls file
tm.assert_frame_equal(df2, df1, check_names=False)
tm.assert_frame_equal(df3, df1, check_names=False)
- df1 = dfref.reindex(columns=['B', 'C'])
- df2 = self.get_exceldf('test1', ext, 'Sheet1', index_col=0,
- usecols='A,C:D')
- df3 = self.get_exceldf('test1', ext, 'Sheet2', skiprows=[1],
- index_col=0, usecols='A,C:D')
+ df1 = df_ref.reindex(columns=['B', 'C'])
+ df2 = pd.read_excel('test1' + ext, 'Sheet1', index_col=0,
+ usecols='A,C:D')
+ df3 = pd.read_excel('test1' + ext, 'Sheet2', skiprows=[1],
+ index_col=0, usecols='A,C:D')
tm.assert_frame_equal(df2, df1, check_names=False)
tm.assert_frame_equal(df3, df1, check_names=False)
@@ -202,50 +151,52 @@ def test_usecols_str(self, ext):
[1, 0, 3], [1, 3, 0],
[3, 0, 1], [3, 1, 0],
])
- def test_usecols_diff_positional_int_columns_order(self, ext, usecols):
- expected = self.get_csv_refdf("test1")[["A", "C"]]
- result = self.get_exceldf("test1", ext, "Sheet1",
- index_col=0, usecols=usecols)
+ def test_usecols_diff_positional_int_columns_order(
+ self, ext, usecols, df_ref):
+ expected = df_ref[["A", "C"]]
+ result = pd.read_excel("test1" + ext, "Sheet1",
+ index_col=0, usecols=usecols)
tm.assert_frame_equal(result, expected, check_names=False)
@pytest.mark.parametrize("usecols", [
["B", "D"], ["D", "B"]
])
- def test_usecols_diff_positional_str_columns_order(self, ext, usecols):
- expected = self.get_csv_refdf("test1")[["B", "D"]]
+ def test_usecols_diff_positional_str_columns_order(
+ self, ext, usecols, df_ref):
+ expected = df_ref[["B", "D"]]
expected.index = range(len(expected))
- result = self.get_exceldf("test1", ext, "Sheet1", usecols=usecols)
+ result = pd.read_excel("test1" + ext, "Sheet1", usecols=usecols)
tm.assert_frame_equal(result, expected, check_names=False)
- def test_read_excel_without_slicing(self, ext):
- expected = self.get_csv_refdf("test1")
- result = self.get_exceldf("test1", ext, "Sheet1", index_col=0)
+ def test_read_excel_without_slicing(self, ext, df_ref):
+ expected = df_ref
+ result = pd.read_excel("test1" + ext, "Sheet1", index_col=0)
tm.assert_frame_equal(result, expected, check_names=False)
- def test_usecols_excel_range_str(self, ext):
- expected = self.get_csv_refdf("test1")[["C", "D"]]
- result = self.get_exceldf("test1", ext, "Sheet1",
- index_col=0, usecols="A,D:E")
+ def test_usecols_excel_range_str(self, ext, df_ref):
+ expected = df_ref[["C", "D"]]
+ result = pd.read_excel("test1" + ext, "Sheet1",
+ index_col=0, usecols="A,D:E")
tm.assert_frame_equal(result, expected, check_names=False)
def test_usecols_excel_range_str_invalid(self, ext):
msg = "Invalid column name: E1"
with pytest.raises(ValueError, match=msg):
- self.get_exceldf("test1", ext, "Sheet1", usecols="D:E1")
+ pd.read_excel("test1" + ext, "Sheet1", usecols="D:E1")
def test_index_col_label_error(self, ext):
msg = "list indices must be integers.*, not str"
with pytest.raises(TypeError, match=msg):
- self.get_exceldf("test1", ext, "Sheet1", index_col=["A"],
- usecols=["A", "C"])
+ pd.read_excel("test1" + ext, "Sheet1", index_col=["A"],
+ usecols=["A", "C"])
def test_index_col_empty(self, ext):
# see gh-9208
- result = self.get_exceldf("test1", ext, "Sheet3",
- index_col=["A", "B", "C"])
+ result = pd.read_excel("test1" + ext, "Sheet3",
+ index_col=["A", "B", "C"])
expected = DataFrame(columns=["D", "E", "F"],
index=MultiIndex(levels=[[]] * 3,
codes=[[]] * 3,
@@ -255,8 +206,7 @@ def test_index_col_empty(self, ext):
@pytest.mark.parametrize("index_col", [None, 2])
def test_index_col_with_unnamed(self, ext, index_col):
# see gh-18792
- result = self.get_exceldf("test1", ext, "Sheet4",
- index_col=index_col)
+ result = pd.read_excel("test1" + ext, "Sheet4", index_col=index_col)
expected = DataFrame([["i1", "a", "x"], ["i2", "b", "y"]],
columns=["Unnamed: 0", "col1", "col2"])
if index_col:
@@ -269,54 +219,54 @@ def test_usecols_pass_non_existent_column(self, ext):
"columns expected but not found: " + r"\['E'\]")
with pytest.raises(ValueError, match=msg):
- self.get_exceldf("test1", ext, usecols=["E"])
+ pd.read_excel("test1" + ext, usecols=["E"])
def test_usecols_wrong_type(self, ext):
msg = ("'usecols' must either be list-like of "
"all strings, all unicode, all integers or a callable.")
with pytest.raises(ValueError, match=msg):
- self.get_exceldf("test1", ext, usecols=["E1", 0])
+ pd.read_excel("test1" + ext, usecols=["E1", 0])
def test_excel_stop_iterator(self, ext):
- parsed = self.get_exceldf('test2', ext, 'Sheet1')
+ parsed = pd.read_excel('test2' + ext, 'Sheet1')
expected = DataFrame([['aaaa', 'bbbbb']], columns=['Test', 'Test1'])
tm.assert_frame_equal(parsed, expected)
def test_excel_cell_error_na(self, ext):
- parsed = self.get_exceldf('test3', ext, 'Sheet1')
+ parsed = pd.read_excel('test3' + ext, 'Sheet1')
expected = DataFrame([[np.nan]], columns=['Test'])
tm.assert_frame_equal(parsed, expected)
def test_excel_passes_na(self, ext):
- excel = self.get_excelfile('test4', ext)
+ excel = ExcelFile('test4' + ext)
- parsed = read_excel(excel, 'Sheet1', keep_default_na=False,
- na_values=['apple'])
+ parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=False,
+ na_values=['apple'])
expected = DataFrame([['NA'], [1], ['NA'], [np.nan], ['rabbit']],
columns=['Test'])
tm.assert_frame_equal(parsed, expected)
- parsed = read_excel(excel, 'Sheet1', keep_default_na=True,
- na_values=['apple'])
+ parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=True,
+ na_values=['apple'])
expected = DataFrame([[np.nan], [1], [np.nan], [np.nan], ['rabbit']],
columns=['Test'])
tm.assert_frame_equal(parsed, expected)
# 13967
- excel = self.get_excelfile('test5', ext)
+ excel = ExcelFile('test5' + ext)
- parsed = read_excel(excel, 'Sheet1', keep_default_na=False,
- na_values=['apple'])
+ parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=False,
+ na_values=['apple'])
expected = DataFrame([['1.#QNAN'], [1], ['nan'], [np.nan], ['rabbit']],
columns=['Test'])
tm.assert_frame_equal(parsed, expected)
- parsed = read_excel(excel, 'Sheet1', keep_default_na=True,
- na_values=['apple'])
+ parsed = pd.read_excel(excel, 'Sheet1', keep_default_na=True,
+ na_values=['apple'])
expected = DataFrame([[np.nan], [1], [np.nan], [np.nan], ['rabbit']],
columns=['Test'])
tm.assert_frame_equal(parsed, expected)
@@ -325,34 +275,33 @@ def test_excel_passes_na(self, ext):
@pytest.mark.parametrize('arg', ['sheet', 'sheetname', 'parse_cols'])
def test_unexpected_kwargs_raises(self, ext, arg):
# gh-17964
- excel = self.get_excelfile('test1', ext)
+ excel = ExcelFile('test1' + ext)
kwarg = {arg: 'Sheet1'}
msg = "unexpected keyword argument `{}`".format(arg)
with pytest.raises(TypeError, match=msg):
- read_excel(excel, **kwarg)
+ pd.read_excel(excel, **kwarg)
@td.skip_if_no('xlrd', '1.0.1') # GH-22682
- def test_excel_table_sheet_by_index(self, ext):
+ def test_excel_table_sheet_by_index(self, ext, df_ref):
- excel = self.get_excelfile('test1', ext)
- dfref = self.get_csv_refdf('test1')
+ excel = ExcelFile('test1' + ext)
- df1 = read_excel(excel, 0, index_col=0)
- df2 = read_excel(excel, 1, skiprows=[1], index_col=0)
- tm.assert_frame_equal(df1, dfref, check_names=False)
- tm.assert_frame_equal(df2, dfref, check_names=False)
+ df1 = pd.read_excel(excel, 0, index_col=0)
+ df2 = pd.read_excel(excel, 1, skiprows=[1], index_col=0)
+ tm.assert_frame_equal(df1, df_ref, check_names=False)
+ tm.assert_frame_equal(df2, df_ref, check_names=False)
df1 = excel.parse(0, index_col=0)
df2 = excel.parse(1, skiprows=[1], index_col=0)
- tm.assert_frame_equal(df1, dfref, check_names=False)
- tm.assert_frame_equal(df2, dfref, check_names=False)
+ tm.assert_frame_equal(df1, df_ref, check_names=False)
+ tm.assert_frame_equal(df2, df_ref, check_names=False)
- df3 = read_excel(excel, 0, index_col=0, skipfooter=1)
+ df3 = pd.read_excel(excel, 0, index_col=0, skipfooter=1)
tm.assert_frame_equal(df3, df1.iloc[:-1])
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
- df4 = read_excel(excel, 0, index_col=0, skip_footer=1)
+ df4 = pd.read_excel(excel, 0, index_col=0, skip_footer=1)
tm.assert_frame_equal(df3, df4)
df3 = excel.parse(0, index_col=0, skipfooter=1)
@@ -360,21 +309,18 @@ def test_excel_table_sheet_by_index(self, ext):
import xlrd
with pytest.raises(xlrd.XLRDError):
- read_excel(excel, 'asdf')
-
- def test_excel_table(self, ext):
+ pd.read_excel(excel, 'asdf')
- dfref = self.get_csv_refdf('test1')
+ def test_excel_table(self, ext, df_ref):
- df1 = self.get_exceldf('test1', ext, 'Sheet1', index_col=0)
- df2 = self.get_exceldf('test1', ext, 'Sheet2', skiprows=[1],
- index_col=0)
+ df1 = pd.read_excel('test1' + ext, 'Sheet1', index_col=0)
+ df2 = pd.read_excel('test1' + ext, 'Sheet2', skiprows=[1],
+ index_col=0)
# TODO add index to file
- tm.assert_frame_equal(df1, dfref, check_names=False)
- tm.assert_frame_equal(df2, dfref, check_names=False)
+ tm.assert_frame_equal(df1, df_ref, check_names=False)
+ tm.assert_frame_equal(df2, df_ref, check_names=False)
- df3 = self.get_exceldf('test1', ext, 'Sheet1', index_col=0,
- skipfooter=1)
+ df3 = pd.read_excel('test1' + ext, 'Sheet1', index_col=0, skipfooter=1)
tm.assert_frame_equal(df3, df1.iloc[:-1])
def test_reader_special_dtypes(self, ext):
@@ -393,32 +339,32 @@ def test_reader_special_dtypes(self, ext):
basename = 'test_types'
# should read in correctly and infer types
- actual = self.get_exceldf(basename, ext, 'Sheet1')
+ actual = pd.read_excel(basename + ext, 'Sheet1')
tm.assert_frame_equal(actual, expected)
# if not coercing number, then int comes in as float
float_expected = expected.copy()
float_expected["IntCol"] = float_expected["IntCol"].astype(float)
float_expected.loc[float_expected.index[1], "Str2Col"] = 3.0
- actual = self.get_exceldf(basename, ext, 'Sheet1', convert_float=False)
+ actual = pd.read_excel(basename + ext, 'Sheet1', convert_float=False)
tm.assert_frame_equal(actual, float_expected)
# check setting Index (assuming xls and xlsx are the same here)
for icol, name in enumerate(expected.columns):
- actual = self.get_exceldf(basename, ext, 'Sheet1', index_col=icol)
+ actual = pd.read_excel(basename + ext, 'Sheet1', index_col=icol)
exp = expected.set_index(name)
tm.assert_frame_equal(actual, exp)
# convert_float and converters should be different but both accepted
expected["StrCol"] = expected["StrCol"].apply(str)
- actual = self.get_exceldf(
- basename, ext, 'Sheet1', converters={"StrCol": str})
+ actual = pd.read_excel(basename + ext, 'Sheet1',
+ converters={"StrCol": str})
tm.assert_frame_equal(actual, expected)
no_convert_float = float_expected.copy()
no_convert_float["StrCol"] = no_convert_float["StrCol"].apply(str)
- actual = self.get_exceldf(basename, ext, 'Sheet1', convert_float=False,
- converters={"StrCol": str})
+ actual = pd.read_excel(basename + ext, 'Sheet1', convert_float=False,
+ converters={"StrCol": str})
tm.assert_frame_equal(actual, no_convert_float)
# GH8212 - support for converters and missing values
@@ -441,14 +387,13 @@ def test_reader_converters(self, ext):
# should read in correctly and set types of single cells (not array
# dtypes)
- actual = self.get_exceldf(basename, ext, 'Sheet1',
- converters=converters)
+ actual = pd.read_excel(basename + ext, 'Sheet1', converters=converters)
tm.assert_frame_equal(actual, expected)
def test_reader_dtype(self, ext):
# GH 8212
basename = 'testdtype'
- actual = self.get_exceldf(basename, ext)
+ actual = pd.read_excel(basename + ext)
expected = DataFrame({
'a': [1, 2, 3, 4],
@@ -459,10 +404,10 @@ def test_reader_dtype(self, ext):
tm.assert_frame_equal(actual, expected)
- actual = self.get_exceldf(basename, ext,
- dtype={'a': 'float64',
- 'b': 'float32',
- 'c': str})
+ actual = pd.read_excel(basename + ext,
+ dtype={'a': 'float64',
+ 'b': 'float32',
+ 'c': str})
expected['a'] = expected['a'].astype('float64')
expected['b'] = expected['b'].astype('float32')
@@ -470,7 +415,7 @@ def test_reader_dtype(self, ext):
tm.assert_frame_equal(actual, expected)
with pytest.raises(ValueError):
- self.get_exceldf(basename, ext, dtype={'d': 'int64'})
+ pd.read_excel(basename + ext, dtype={'d': 'int64'})
@pytest.mark.parametrize("dtype,expected", [
(None,
@@ -496,7 +441,7 @@ def test_reader_dtype_str(self, ext, dtype, expected):
# see gh-20377
basename = "testdtype"
- actual = self.get_exceldf(basename, ext, dtype=dtype)
+ actual = pd.read_excel(basename + ext, dtype=dtype)
tm.assert_frame_equal(actual, expected)
def test_reading_all_sheets(self, ext):
@@ -504,7 +449,7 @@ def test_reading_all_sheets(self, ext):
# Ensure a dict is returned.
# See PR #9450
basename = 'test_multisheet'
- dfs = self.get_exceldf(basename, ext, sheet_name=None)
+ dfs = pd.read_excel(basename + ext, sheet_name=None)
# ensure this is not alphabetical to test order preservation
expected_keys = ['Charlie', 'Alpha', 'Beta']
tm.assert_contains_all(expected_keys, dfs.keys())
@@ -521,7 +466,7 @@ def test_reading_multiple_specific_sheets(self, ext):
basename = 'test_multisheet'
# Explicitly request duplicates. Only the set should be returned.
expected_keys = [2, 'Charlie', 'Charlie']
- dfs = self.get_exceldf(basename, ext, sheet_name=expected_keys)
+ dfs = pd.read_excel(basename + ext, sheet_name=expected_keys)
expected_keys = list(set(expected_keys))
tm.assert_contains_all(expected_keys, dfs.keys())
assert len(expected_keys) == len(dfs.keys())
@@ -531,18 +476,18 @@ def test_reading_all_sheets_with_blank(self, ext):
# In the case where some sheets are blank.
# Issue #11711
basename = 'blank_with_header'
- dfs = self.get_exceldf(basename, ext, sheet_name=None)
+ dfs = pd.read_excel(basename + ext, sheet_name=None)
expected_keys = ['Sheet1', 'Sheet2', 'Sheet3']
tm.assert_contains_all(expected_keys, dfs.keys())
# GH6403
def test_read_excel_blank(self, ext):
- actual = self.get_exceldf('blank', ext, 'Sheet1')
+ actual = pd.read_excel('blank' + ext, 'Sheet1')
tm.assert_frame_equal(actual, DataFrame())
def test_read_excel_blank_with_header(self, ext):
expected = DataFrame(columns=['col_1', 'col_2'])
- actual = self.get_exceldf('blank_with_header', ext, 'Sheet1')
+ actual = pd.read_excel('blank_with_header' + ext, 'Sheet1')
tm.assert_frame_equal(actual, expected)
def test_date_conversion_overflow(self, ext):
@@ -552,11 +497,11 @@ def test_date_conversion_overflow(self, ext):
[1e+20, 'Timothy Brown']],
columns=['DateColWithBigInt', 'StringCol'])
- result = self.get_exceldf('testdateoverflow', ext)
+ result = pd.read_excel('testdateoverflow' + ext)
tm.assert_frame_equal(result, expected)
@td.skip_if_no("xlrd", "1.0.1") # see gh-22682
- def test_sheet_name_and_sheetname(self, ext):
+ def test_sheet_name_and_sheetname(self, ext, df_ref):
# gh-10559: Minor improvement: Change "sheet_name" to "sheetname"
# gh-10969: DOC: Consistent var names (sheetname vs sheet_name)
# gh-12604: CLN GH10559 Rename sheetname variable to sheet_name
@@ -565,14 +510,13 @@ def test_sheet_name_and_sheetname(self, ext):
filename = "test1"
sheet_name = "Sheet1"
- df_ref = self.get_csv_refdf(filename)
- df1 = self.get_exceldf(filename, ext,
- sheet_name=sheet_name, index_col=0) # doc
+ df1 = pd.read_excel(filename + ext,
+ sheet_name=sheet_name, index_col=0) # doc
with ignore_xlrd_time_clock_warning():
- df2 = self.get_exceldf(filename, ext, index_col=0,
- sheet_name=sheet_name)
+ df2 = pd.read_excel(filename + ext, index_col=0,
+ sheet_name=sheet_name)
- excel = self.get_excelfile(filename, ext)
+ excel = ExcelFile(filename + ext)
df1_parse = excel.parse(sheet_name=sheet_name, index_col=0) # doc
df2_parse = excel.parse(index_col=0,
sheet_name=sheet_name)
@@ -584,55 +528,53 @@ def test_sheet_name_and_sheetname(self, ext):
def test_excel_read_buffer(self, ext):
- pth = os.path.join(self.dirpath, 'test1' + ext)
- expected = read_excel(pth, 'Sheet1', index_col=0)
+ pth = 'test1' + ext
+ expected = pd.read_excel(pth, 'Sheet1', index_col=0)
with open(pth, 'rb') as f:
- actual = read_excel(f, 'Sheet1', index_col=0)
+ actual = pd.read_excel(f, 'Sheet1', index_col=0)
tm.assert_frame_equal(expected, actual)
with open(pth, 'rb') as f:
xls = ExcelFile(f)
- actual = read_excel(xls, 'Sheet1', index_col=0)
+ actual = pd.read_excel(xls, 'Sheet1', index_col=0)
tm.assert_frame_equal(expected, actual)
def test_bad_engine_raises(self, ext):
bad_engine = 'foo'
with pytest.raises(ValueError, match="Unknown engine: foo"):
- read_excel('', engine=bad_engine)
+ pd.read_excel('', engine=bad_engine)
@tm.network
def test_read_from_http_url(self, ext):
url = ('https://raw.github.com/pandas-dev/pandas/master/'
'pandas/tests/io/data/test1' + ext)
- url_table = read_excel(url)
- local_table = self.get_exceldf('test1', ext)
+ url_table = pd.read_excel(url)
+ local_table = pd.read_excel('test1' + ext)
tm.assert_frame_equal(url_table, local_table)
@td.skip_if_not_us_locale
def test_read_from_s3_url(self, ext, s3_resource):
# Bucket "pandas-test" created in tests/io/conftest.py
- file_name = os.path.join(self.dirpath, 'test1' + ext)
-
- with open(file_name, "rb") as f:
+ with open('test1' + ext, "rb") as f:
s3_resource.Bucket("pandas-test").put_object(Key="test1" + ext,
Body=f)
url = ('s3://pandas-test/test1' + ext)
- url_table = read_excel(url)
- local_table = self.get_exceldf('test1', ext)
+ url_table = pd.read_excel(url)
+ local_table = pd.read_excel('test1' + ext)
tm.assert_frame_equal(url_table, local_table)
@pytest.mark.slow
# ignore warning from old xlrd
@pytest.mark.filterwarnings("ignore:This metho:PendingDeprecationWarning")
- def test_read_from_file_url(self, ext):
+ def test_read_from_file_url(self, ext, datapath):
# FILE
- localtable = os.path.join(self.dirpath, 'test1' + ext)
- local_table = read_excel(localtable)
+ localtable = os.path.join(datapath("io", "data"), 'test1' + ext)
+ local_table = pd.read_excel(localtable)
try:
- url_table = read_excel('file://localhost/' + localtable)
+ url_table = pd.read_excel('file://localhost/' + localtable)
except URLError:
# fails on some systems
import platform
@@ -646,11 +588,11 @@ def test_read_from_pathlib_path(self, ext):
# GH12655
from pathlib import Path
- str_path = os.path.join(self.dirpath, 'test1' + ext)
- expected = read_excel(str_path, 'Sheet1', index_col=0)
+ str_path = 'test1' + ext
+ expected = pd.read_excel(str_path, 'Sheet1', index_col=0)
- path_obj = Path(self.dirpath, 'test1' + ext)
- actual = read_excel(path_obj, 'Sheet1', index_col=0)
+ path_obj = Path('test1' + ext)
+ actual = pd.read_excel(path_obj, 'Sheet1', index_col=0)
tm.assert_frame_equal(expected, actual)
@@ -660,22 +602,20 @@ def test_read_from_py_localpath(self, ext):
# GH12655
from py.path import local as LocalPath
- str_path = os.path.join(self.dirpath, 'test1' + ext)
- expected = read_excel(str_path, 'Sheet1', index_col=0)
+ str_path = os.path.join('test1' + ext)
+ expected = pd.read_excel(str_path, 'Sheet1', index_col=0)
- abs_dir = os.path.abspath(self.dirpath)
- path_obj = LocalPath(abs_dir).join('test1' + ext)
- actual = read_excel(path_obj, 'Sheet1', index_col=0)
+ path_obj = LocalPath().join('test1' + ext)
+ actual = pd.read_excel(path_obj, 'Sheet1', index_col=0)
tm.assert_frame_equal(expected, actual)
def test_reader_closes_file(self, ext):
- pth = os.path.join(self.dirpath, 'test1' + ext)
- f = open(pth, 'rb')
+ f = open('test1' + ext, 'rb')
with ExcelFile(f) as xlsx:
# parses okay
- read_excel(xlsx, 'Sheet1', index_col=0)
+ pd.read_excel(xlsx, 'Sheet1', index_col=0)
assert f.closed
@@ -694,16 +634,16 @@ def test_reader_seconds(self, ext):
time(16, 37, 0, 900000),
time(18, 20, 54)]})
- actual = self.get_exceldf('times_1900', ext, 'Sheet1')
+ actual = pd.read_excel('times_1900' + ext, 'Sheet1')
tm.assert_frame_equal(actual, expected)
- actual = self.get_exceldf('times_1904', ext, 'Sheet1')
+ actual = pd.read_excel('times_1904' + ext, 'Sheet1')
tm.assert_frame_equal(actual, expected)
def test_read_excel_multiindex(self, ext):
# see gh-4679
mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]])
- mi_file = os.path.join(self.dirpath, "testmultiindex" + ext)
+ mi_file = "testmultiindex" + ext
# "mi_column" sheet
expected = DataFrame([[1, 2.5, pd.Timestamp("2015-01-01"), True],
@@ -712,34 +652,37 @@ def test_read_excel_multiindex(self, ext):
[4, 5.5, pd.Timestamp("2015-01-04"), True]],
columns=mi)
- actual = read_excel(mi_file, "mi_column", header=[0, 1], index_col=0)
+ actual = pd.read_excel(
+ mi_file, "mi_column", header=[0, 1], index_col=0)
tm.assert_frame_equal(actual, expected)
# "mi_index" sheet
expected.index = mi
expected.columns = ["a", "b", "c", "d"]
- actual = read_excel(mi_file, "mi_index", index_col=[0, 1])
+ actual = pd.read_excel(mi_file, "mi_index", index_col=[0, 1])
tm.assert_frame_equal(actual, expected, check_names=False)
# "both" sheet
expected.columns = mi
- actual = read_excel(mi_file, "both", index_col=[0, 1], header=[0, 1])
+ actual = pd.read_excel(
+ mi_file, "both", index_col=[0, 1], header=[0, 1])
tm.assert_frame_equal(actual, expected, check_names=False)
# "mi_index_name" sheet
expected.columns = ["a", "b", "c", "d"]
expected.index = mi.set_names(["ilvl1", "ilvl2"])
- actual = read_excel(mi_file, "mi_index_name", index_col=[0, 1])
+ actual = pd.read_excel(
+ mi_file, "mi_index_name", index_col=[0, 1])
tm.assert_frame_equal(actual, expected)
# "mi_column_name" sheet
expected.index = list(range(4))
expected.columns = mi.set_names(["c1", "c2"])
- actual = read_excel(mi_file, "mi_column_name",
- header=[0, 1], index_col=0)
+ actual = pd.read_excel(mi_file, "mi_column_name",
+ header=[0, 1], index_col=0)
tm.assert_frame_equal(actual, expected)
# see gh-11317
@@ -747,29 +690,29 @@ def test_read_excel_multiindex(self, ext):
expected.columns = mi.set_levels(
[1, 2], level=1).set_names(["c1", "c2"])
- actual = read_excel(mi_file, "name_with_int",
- index_col=0, header=[0, 1])
+ actual = pd.read_excel(mi_file, "name_with_int",
+ index_col=0, header=[0, 1])
tm.assert_frame_equal(actual, expected)
# "both_name" sheet
expected.columns = mi.set_names(["c1", "c2"])
expected.index = mi.set_names(["ilvl1", "ilvl2"])
- actual = read_excel(mi_file, "both_name",
- index_col=[0, 1], header=[0, 1])
+ actual = pd.read_excel(mi_file, "both_name",
+ index_col=[0, 1], header=[0, 1])
tm.assert_frame_equal(actual, expected)
# "both_skiprows" sheet
- actual = read_excel(mi_file, "both_name_skiprows", index_col=[0, 1],
- header=[0, 1], skiprows=2)
+ actual = pd.read_excel(mi_file, "both_name_skiprows", index_col=[0, 1],
+ header=[0, 1], skiprows=2)
tm.assert_frame_equal(actual, expected)
def test_read_excel_multiindex_header_only(self, ext):
# see gh-11733.
#
# Don't try to parse a header name if there isn't one.
- mi_file = os.path.join(self.dirpath, "testmultiindex" + ext)
- result = read_excel(mi_file, "index_col_none", header=[0, 1])
+ mi_file = "testmultiindex" + ext
+ result = pd.read_excel(mi_file, "index_col_none", header=[0, 1])
exp_columns = MultiIndex.from_product([("A", "B"), ("key", "val")])
expected = DataFrame([[1, 2, 3, 4]] * 2, columns=exp_columns)
@@ -778,7 +721,6 @@ def test_read_excel_multiindex_header_only(self, ext):
def test_excel_old_index_format(self, ext):
# see gh-4679
filename = "test_index_name_pre17" + ext
- in_file = os.path.join(self.dirpath, filename)
# We detect headers to determine if index names exist, so
# that "index" name in the "names" version of the data will
@@ -801,12 +743,12 @@ def test_excel_old_index_format(self, ext):
expected = pd.DataFrame(data, index=si, columns=columns)
- actual = pd.read_excel(in_file, "single_names", index_col=0)
+ actual = pd.read_excel(filename, "single_names", index_col=0)
tm.assert_frame_equal(actual, expected)
expected.index = mi
- actual = pd.read_excel(in_file, "multi_names", index_col=[0, 1])
+ actual = pd.read_excel(filename, "multi_names", index_col=[0, 1])
tm.assert_frame_equal(actual, expected)
# The analogous versions of the "names" version data
@@ -828,31 +770,28 @@ def test_excel_old_index_format(self, ext):
expected = pd.DataFrame(data, index=si, columns=columns)
- actual = pd.read_excel(in_file, "single_no_names", index_col=0)
+ actual = pd.read_excel(filename, "single_no_names", index_col=0)
tm.assert_frame_equal(actual, expected)
expected.index = mi
- actual = pd.read_excel(in_file, "multi_no_names", index_col=[0, 1])
+ actual = pd.read_excel(filename, "multi_no_names", index_col=[0, 1])
tm.assert_frame_equal(actual, expected, check_names=False)
def test_read_excel_bool_header_arg(self, ext):
# GH 6114
for arg in [True, False]:
with pytest.raises(TypeError):
- pd.read_excel(os.path.join(self.dirpath, 'test1' + ext),
- header=arg)
+ pd.read_excel('test1' + ext, header=arg)
def test_read_excel_chunksize(self, ext):
# GH 8011
with pytest.raises(NotImplementedError):
- pd.read_excel(os.path.join(self.dirpath, 'test1' + ext),
- chunksize=100)
+ pd.read_excel('test1' + ext, chunksize=100)
def test_read_excel_skiprows_list(self, ext):
# GH 4903
- actual = pd.read_excel(os.path.join(self.dirpath,
- 'testskiprows' + ext),
+ actual = pd.read_excel('testskiprows' + ext,
'skiprows_list', skiprows=[0, 2])
expected = DataFrame([[1, 2.5, pd.Timestamp('2015-01-01'), True],
[2, 3.5, pd.Timestamp('2015-01-02'), False],
@@ -861,41 +800,35 @@ def test_read_excel_skiprows_list(self, ext):
columns=['a', 'b', 'c', 'd'])
tm.assert_frame_equal(actual, expected)
- actual = pd.read_excel(os.path.join(self.dirpath,
- 'testskiprows' + ext),
+ actual = pd.read_excel('testskiprows' + ext,
'skiprows_list', skiprows=np.array([0, 2]))
tm.assert_frame_equal(actual, expected)
def test_read_excel_nrows(self, ext):
# GH 16645
num_rows_to_pull = 5
- actual = pd.read_excel(os.path.join(self.dirpath, 'test1' + ext),
- nrows=num_rows_to_pull)
- expected = pd.read_excel(os.path.join(self.dirpath,
- 'test1' + ext))
+ actual = pd.read_excel('test1' + ext, nrows=num_rows_to_pull)
+ expected = pd.read_excel('test1' + ext)
expected = expected[:num_rows_to_pull]
tm.assert_frame_equal(actual, expected)
def test_read_excel_nrows_greater_than_nrows_in_file(self, ext):
# GH 16645
- expected = pd.read_excel(os.path.join(self.dirpath,
- 'test1' + ext))
+ expected = pd.read_excel('test1' + ext)
num_records_in_file = len(expected)
num_rows_to_pull = num_records_in_file + 10
- actual = pd.read_excel(os.path.join(self.dirpath, 'test1' + ext),
- nrows=num_rows_to_pull)
+ actual = pd.read_excel('test1' + ext, nrows=num_rows_to_pull)
tm.assert_frame_equal(actual, expected)
def test_read_excel_nrows_non_integer_parameter(self, ext):
# GH 16645
msg = "'nrows' must be an integer >=0"
with pytest.raises(ValueError, match=msg):
- pd.read_excel(os.path.join(self.dirpath, 'test1' + ext),
- nrows='5')
+ pd.read_excel('test1' + ext, nrows='5')
def test_read_excel_squeeze(self, ext):
# GH 12157
- f = os.path.join(self.dirpath, 'test_squeeze' + ext)
+ f = 'test_squeeze' + ext
actual = pd.read_excel(f, 'two_columns', index_col=0, squeeze=True)
expected = pd.Series([2, 3, 4], [4, 5, 6], name='b')
@@ -934,7 +867,7 @@ def test_read_one_empty_col_no_header(self, ext, header, expected):
with ensure_clean(ext) as path:
df.to_excel(path, filename, index=False, header=False)
- result = read_excel(path, filename, usecols=[0], header=header)
+ result = pd.read_excel(path, filename, usecols=[0], header=header)
tm.assert_frame_equal(result, expected)
@@ -955,7 +888,7 @@ def test_read_one_empty_col_with_header(self, ext, header, expected):
with ensure_clean(ext) as path:
df.to_excel(path, 'with_header', index=False, header=True)
- result = read_excel(path, filename, usecols=[0], header=header)
+ result = pd.read_excel(path, filename, usecols=[0], header=header)
tm.assert_frame_equal(result, expected)
@@ -976,10 +909,10 @@ def test_set_column_names_in_parameter(self, ext):
refdf.columns = ['A', 'B']
with ExcelFile(pth) as reader:
- xlsdf_no_head = read_excel(reader, 'Data_no_head',
- header=None, names=['A', 'B'])
- xlsdf_with_head = read_excel(reader, 'Data_with_head',
- index_col=None, names=['A', 'B'])
+ xlsdf_no_head = pd.read_excel(reader, 'Data_no_head',
+ header=None, names=['A', 'B'])
+ xlsdf_with_head = pd.read_excel(
+ reader, 'Data_with_head', index_col=None, names=['A', 'B'])
tm.assert_frame_equal(xlsdf_no_head, refdf)
tm.assert_frame_equal(xlsdf_with_head, refdf)
@@ -1005,7 +938,7 @@ def tdf(col_sheet_name):
for sheetname, df in dfs.items():
df.to_excel(ew, sheetname)
- dfs_returned = read_excel(pth, sheet_name=sheets, index_col=0)
+ dfs_returned = pd.read_excel(pth, sheet_name=sheets, index_col=0)
for s in sheets:
tm.assert_frame_equal(dfs[s], dfs_returned[s])
@@ -1101,15 +1034,15 @@ def test_read_excel_parse_dates(self, ext):
with ensure_clean(ext) as pth:
df2.to_excel(pth)
- res = read_excel(pth, index_col=0)
+ res = pd.read_excel(pth, index_col=0)
tm.assert_frame_equal(df2, res)
- res = read_excel(pth, parse_dates=["date_strings"], index_col=0)
+ res = pd.read_excel(pth, parse_dates=["date_strings"], index_col=0)
tm.assert_frame_equal(df, res)
date_parser = lambda x: pd.datetime.strptime(x, "%m/%d/%Y")
- res = read_excel(pth, parse_dates=["date_strings"],
- date_parser=date_parser, index_col=0)
+ res = pd.read_excel(pth, parse_dates=["date_strings"],
+ date_parser=date_parser, index_col=0)
tm.assert_frame_equal(df, res)
@@ -1134,11 +1067,11 @@ def test_read_xlrd_book(self, ext):
book = xlrd.open_workbook(pth)
with ExcelFile(book, engine=engine) as xl:
- result = read_excel(xl, sheet_name, index_col=0)
+ result = pd.read_excel(xl, sheet_name, index_col=0)
tm.assert_frame_equal(df, result)
- result = read_excel(book, sheet_name=sheet_name,
- engine=engine, index_col=0)
+ result = pd.read_excel(book, sheet_name=sheet_name,
+ engine=engine, index_col=0)
tm.assert_frame_equal(df, result)
@@ -1192,12 +1125,12 @@ def test_excel_sheet_by_name_raise(self, *_):
gt.to_excel(self.path)
xl = ExcelFile(self.path)
- df = read_excel(xl, 0, index_col=0)
+ df = pd.read_excel(xl, 0, index_col=0)
tm.assert_frame_equal(gt, df)
with pytest.raises(xlrd.XLRDError):
- read_excel(xl, "0")
+ pd.read_excel(xl, "0")
def test_excel_writer_context_manager(self, *_):
with ExcelWriter(self.path) as writer:
@@ -1205,8 +1138,8 @@ def test_excel_writer_context_manager(self, *_):
self.frame2.to_excel(writer, "Data2")
with ExcelFile(self.path) as reader:
- found_df = read_excel(reader, "Data1", index_col=0)
- found_df2 = read_excel(reader, "Data2", index_col=0)
+ found_df = pd.read_excel(reader, "Data1", index_col=0)
+ found_df2 = pd.read_excel(reader, "Data2", index_col=0)
tm.assert_frame_equal(found_df, self.frame)
tm.assert_frame_equal(found_df2, self.frame2)
@@ -1221,47 +1154,49 @@ def test_roundtrip(self, merge_cells, engine, ext):
# test roundtrip
self.frame.to_excel(self.path, 'test1')
- recons = read_excel(self.path, 'test1', index_col=0)
+ recons = pd.read_excel(self.path, 'test1', index_col=0)
tm.assert_frame_equal(self.frame, recons)
self.frame.to_excel(self.path, 'test1', index=False)
- recons = read_excel(self.path, 'test1', index_col=None)
+ recons = pd.read_excel(self.path, 'test1', index_col=None)
recons.index = self.frame.index
tm.assert_frame_equal(self.frame, recons)
self.frame.to_excel(self.path, 'test1', na_rep='NA')
- recons = read_excel(self.path, 'test1', index_col=0, na_values=['NA'])
+ recons = pd.read_excel(
+ self.path, 'test1', index_col=0, na_values=['NA'])
tm.assert_frame_equal(self.frame, recons)
# GH 3611
self.frame.to_excel(self.path, 'test1', na_rep='88')
- recons = read_excel(self.path, 'test1', index_col=0, na_values=['88'])
+ recons = pd.read_excel(
+ self.path, 'test1', index_col=0, na_values=['88'])
tm.assert_frame_equal(self.frame, recons)
self.frame.to_excel(self.path, 'test1', na_rep='88')
- recons = read_excel(self.path, 'test1', index_col=0,
- na_values=[88, 88.0])
+ recons = pd.read_excel(
+ self.path, 'test1', index_col=0, na_values=[88, 88.0])
tm.assert_frame_equal(self.frame, recons)
# GH 6573
self.frame.to_excel(self.path, 'Sheet1')
- recons = read_excel(self.path, index_col=0)
+ recons = pd.read_excel(self.path, index_col=0)
tm.assert_frame_equal(self.frame, recons)
self.frame.to_excel(self.path, '0')
- recons = read_excel(self.path, index_col=0)
+ recons = pd.read_excel(self.path, index_col=0)
tm.assert_frame_equal(self.frame, recons)
# GH 8825 Pandas Series should provide to_excel method
s = self.frame["A"]
s.to_excel(self.path)
- recons = read_excel(self.path, index_col=0)
+ recons = pd.read_excel(self.path, index_col=0)
tm.assert_frame_equal(s.to_frame(), recons)
def test_mixed(self, merge_cells, engine, ext):
self.mixed_frame.to_excel(self.path, 'test1')
reader = ExcelFile(self.path)
- recons = read_excel(reader, 'test1', index_col=0)
+ recons = pd.read_excel(reader, 'test1', index_col=0)
tm.assert_frame_equal(self.mixed_frame, recons)
def test_ts_frame(self, *_):
@@ -1270,7 +1205,7 @@ def test_ts_frame(self, *_):
df.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
- recons = read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, "test1", index_col=0)
tm.assert_frame_equal(df, recons)
def test_basics_with_nan(self, merge_cells, engine, ext):
@@ -1290,18 +1225,18 @@ def test_int_types(self, merge_cells, engine, ext, np_type):
frame.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
- recons = read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, "test1", index_col=0)
int_frame = frame.astype(np.int64)
tm.assert_frame_equal(int_frame, recons)
- recons2 = read_excel(self.path, "test1", index_col=0)
+ recons2 = pd.read_excel(self.path, "test1", index_col=0)
tm.assert_frame_equal(int_frame, recons2)
# Test with convert_float=False comes back as float.
float_frame = frame.astype(float)
- recons = read_excel(self.path, "test1",
- convert_float=False, index_col=0)
+ recons = pd.read_excel(self.path, "test1",
+ convert_float=False, index_col=0)
tm.assert_frame_equal(recons, float_frame,
check_index_type=False,
check_column_type=False)
@@ -1314,7 +1249,7 @@ def test_float_types(self, merge_cells, engine, ext, np_type):
frame.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
- recons = read_excel(reader, "test1", index_col=0).astype(np_type)
+ recons = pd.read_excel(reader, "test1", index_col=0).astype(np_type)
tm.assert_frame_equal(frame, recons, check_dtype=False)
@@ -1325,7 +1260,7 @@ def test_bool_types(self, merge_cells, engine, ext, np_type):
frame.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
- recons = read_excel(reader, "test1", index_col=0).astype(np_type)
+ recons = pd.read_excel(reader, "test1", index_col=0).astype(np_type)
tm.assert_frame_equal(frame, recons)
@@ -1334,7 +1269,7 @@ def test_inf_roundtrip(self, *_):
frame.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
- recons = read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, "test1", index_col=0)
tm.assert_frame_equal(frame, recons)
@@ -1352,9 +1287,9 @@ def test_sheets(self, merge_cells, engine, ext):
self.tsframe.to_excel(writer, 'test2')
writer.save()
reader = ExcelFile(self.path)
- recons = read_excel(reader, 'test1', index_col=0)
+ recons = pd.read_excel(reader, 'test1', index_col=0)
tm.assert_frame_equal(self.frame, recons)
- recons = read_excel(reader, 'test2', index_col=0)
+ recons = pd.read_excel(reader, 'test2', index_col=0)
tm.assert_frame_equal(self.tsframe, recons)
assert 2 == len(reader.sheet_names)
assert 'test1' == reader.sheet_names[0]
@@ -1372,7 +1307,7 @@ def test_colaliases(self, merge_cells, engine, ext):
col_aliases = Index(['AA', 'X', 'Y', 'Z'])
self.frame2.to_excel(self.path, 'test1', header=col_aliases)
reader = ExcelFile(self.path)
- rs = read_excel(reader, 'test1', index_col=0)
+ rs = pd.read_excel(reader, 'test1', index_col=0)
xp = self.frame2.copy()
xp.columns = col_aliases
tm.assert_frame_equal(xp, rs)
@@ -1391,9 +1326,8 @@ def test_roundtrip_indexlabels(self, merge_cells, engine, ext):
index_label=['test'],
merge_cells=merge_cells)
reader = ExcelFile(self.path)
- recons = read_excel(reader, 'test1',
- index_col=0,
- ).astype(np.int64)
+ recons = pd.read_excel(
+ reader, 'test1', index_col=0).astype(np.int64)
frame.index.names = ['test']
assert frame.index.names == recons.index.names
@@ -1403,9 +1337,8 @@ def test_roundtrip_indexlabels(self, merge_cells, engine, ext):
index_label=['test', 'dummy', 'dummy2'],
merge_cells=merge_cells)
reader = ExcelFile(self.path)
- recons = read_excel(reader, 'test1',
- index_col=0,
- ).astype(np.int64)
+ recons = pd.read_excel(
+ reader, 'test1', index_col=0).astype(np.int64)
frame.index.names = ['test']
assert frame.index.names == recons.index.names
@@ -1415,9 +1348,8 @@ def test_roundtrip_indexlabels(self, merge_cells, engine, ext):
index_label='test',
merge_cells=merge_cells)
reader = ExcelFile(self.path)
- recons = read_excel(reader, 'test1',
- index_col=0,
- ).astype(np.int64)
+ recons = pd.read_excel(
+ reader, 'test1', index_col=0).astype(np.int64)
frame.index.names = ['test']
tm.assert_frame_equal(frame, recons.astype(bool))
@@ -1430,7 +1362,7 @@ def test_roundtrip_indexlabels(self, merge_cells, engine, ext):
df = df.set_index(['A', 'B'])
reader = ExcelFile(self.path)
- recons = read_excel(reader, 'test1', index_col=[0, 1])
+ recons = pd.read_excel(reader, 'test1', index_col=[0, 1])
tm.assert_frame_equal(df, recons, check_less_precise=True)
def test_excel_roundtrip_indexname(self, merge_cells, engine, ext):
@@ -1440,8 +1372,7 @@ def test_excel_roundtrip_indexname(self, merge_cells, engine, ext):
df.to_excel(self.path, merge_cells=merge_cells)
xf = ExcelFile(self.path)
- result = read_excel(xf, xf.sheet_names[0],
- index_col=0)
+ result = pd.read_excel(xf, xf.sheet_names[0], index_col=0)
tm.assert_frame_equal(result, df)
assert result.index.name == 'foo'
@@ -1454,7 +1385,7 @@ def test_excel_roundtrip_datetime(self, merge_cells, *_):
tsf.to_excel(self.path, "test1", merge_cells=merge_cells)
reader = ExcelFile(self.path)
- recons = read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, "test1", index_col=0)
tm.assert_frame_equal(self.tsframe, recons)
@@ -1488,8 +1419,8 @@ def test_excel_date_datetime_format(self, merge_cells, engine, ext):
reader1 = ExcelFile(self.path)
reader2 = ExcelFile(filename2)
- rs1 = read_excel(reader1, "test1", index_col=0)
- rs2 = read_excel(reader2, "test1", index_col=0)
+ rs1 = pd.read_excel(reader1, "test1", index_col=0)
+ rs2 = pd.read_excel(reader2, "test1", index_col=0)
tm.assert_frame_equal(rs1, rs2)
@@ -1511,7 +1442,7 @@ def test_to_excel_interval_no_labels(self, *_):
frame.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
- recons = read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, "test1", index_col=0)
tm.assert_frame_equal(expected, recons)
def test_to_excel_interval_labels(self, *_):
@@ -1529,7 +1460,7 @@ def test_to_excel_interval_labels(self, *_):
frame.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
- recons = read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, "test1", index_col=0)
tm.assert_frame_equal(expected, recons)
def test_to_excel_timedelta(self, *_):
@@ -1547,7 +1478,7 @@ def test_to_excel_timedelta(self, *_):
frame.to_excel(self.path, "test1")
reader = ExcelFile(self.path)
- recons = read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, "test1", index_col=0)
tm.assert_frame_equal(expected, recons)
def test_to_excel_periodindex(self, merge_cells, engine, ext):
@@ -1557,7 +1488,7 @@ def test_to_excel_periodindex(self, merge_cells, engine, ext):
xp.to_excel(self.path, 'sht1')
reader = ExcelFile(self.path)
- rs = read_excel(reader, 'sht1', index_col=0)
+ rs = pd.read_excel(reader, 'sht1', index_col=0)
tm.assert_frame_equal(xp, rs.to_period('M'))
def test_to_excel_multiindex(self, merge_cells, engine, ext):
@@ -1573,7 +1504,7 @@ def test_to_excel_multiindex(self, merge_cells, engine, ext):
# round trip
frame.to_excel(self.path, 'test1', merge_cells=merge_cells)
reader = ExcelFile(self.path)
- df = read_excel(reader, 'test1', index_col=[0, 1])
+ df = pd.read_excel(reader, 'test1', index_col=[0, 1])
tm.assert_frame_equal(frame, df)
# GH13511
@@ -1584,7 +1515,7 @@ def test_to_excel_multiindex_nan_label(self, merge_cells, engine, ext):
frame = frame.set_index(['A', 'B'])
frame.to_excel(self.path, merge_cells=merge_cells)
- df = read_excel(self.path, index_col=[0, 1])
+ df = pd.read_excel(self.path, index_col=[0, 1])
tm.assert_frame_equal(frame, df)
# Test for Issue 11328. If column indices are integers, make
@@ -1607,8 +1538,7 @@ def test_to_excel_multiindex_cols(self, merge_cells, engine, ext):
# round trip
frame.to_excel(self.path, 'test1', merge_cells=merge_cells)
reader = ExcelFile(self.path)
- df = read_excel(reader, 'test1', header=header,
- index_col=[0, 1])
+ df = pd.read_excel(reader, 'test1', header=header, index_col=[0, 1])
if not merge_cells:
fm = frame.columns.format(sparsify=False,
adjoin=False, names=False)
@@ -1624,8 +1554,7 @@ def test_to_excel_multiindex_dates(self, merge_cells, engine, ext):
tsframe.index.names = ['time', 'foo']
tsframe.to_excel(self.path, 'test1', merge_cells=merge_cells)
reader = ExcelFile(self.path)
- recons = read_excel(reader, 'test1',
- index_col=[0, 1])
+ recons = pd.read_excel(reader, 'test1', index_col=[0, 1])
tm.assert_frame_equal(tsframe, recons)
assert recons.index.names == ('time', 'foo')
@@ -1647,7 +1576,7 @@ def test_to_excel_multiindex_no_write_index(self, merge_cells, engine,
# Read it back in.
reader = ExcelFile(self.path)
- frame3 = read_excel(reader, 'test1')
+ frame3 = pd.read_excel(reader, 'test1')
# Test that it is the same as the initial frame.
tm.assert_frame_equal(frame1, frame3)
@@ -1659,7 +1588,7 @@ def test_to_excel_float_format(self, *_):
df.to_excel(self.path, "test1", float_format="%.2f")
reader = ExcelFile(self.path)
- result = read_excel(reader, "test1", index_col=0)
+ result = pd.read_excel(reader, "test1", index_col=0)
expected = DataFrame([[0.12, 0.23, 0.57],
[12.32, 123123.20, 321321.20]],
@@ -1675,8 +1604,8 @@ def test_to_excel_output_encoding(self, merge_cells, engine, ext):
with ensure_clean("__tmp_to_excel_float_format__." + ext) as filename:
df.to_excel(filename, sheet_name="TestSheet", encoding="utf8")
- result = read_excel(filename, "TestSheet",
- encoding="utf8", index_col=0)
+ result = pd.read_excel(filename, "TestSheet",
+ encoding="utf8", index_col=0)
tm.assert_frame_equal(result, df)
def test_to_excel_unicode_filename(self, merge_cells, engine, ext):
@@ -1694,7 +1623,7 @@ def test_to_excel_unicode_filename(self, merge_cells, engine, ext):
df.to_excel(filename, "test1", float_format="%.2f")
reader = ExcelFile(filename)
- result = read_excel(reader, "test1", index_col=0)
+ result = pd.read_excel(reader, "test1", index_col=0)
expected = DataFrame([[0.12, 0.23, 0.57],
[12.32, 123123.20, 321321.20]],
@@ -1812,7 +1741,7 @@ def roundtrip(data, header=True, parser_hdr=0, index=True):
merge_cells=merge_cells, index=index)
xf = ExcelFile(self.path)
- return read_excel(xf, xf.sheet_names[0], header=parser_hdr)
+ return pd.read_excel(xf, xf.sheet_names[0], header=parser_hdr)
# Basic test.
parser_header = 0 if use_headers else None
@@ -1860,12 +1789,12 @@ def test_duplicated_columns(self, *_):
columns=["A", "B", "B.1"])
# By default, we mangle.
- result = read_excel(self.path, "test1", index_col=0)
+ result = pd.read_excel(self.path, "test1", index_col=0)
tm.assert_frame_equal(result, expected)
# Explicitly, we pass in the parameter.
- result = read_excel(self.path, "test1", index_col=0,
- mangle_dupe_cols=True)
+ result = pd.read_excel(self.path, "test1", index_col=0,
+ mangle_dupe_cols=True)
tm.assert_frame_equal(result, expected)
# see gh-11007, gh-10970
@@ -1873,21 +1802,22 @@ def test_duplicated_columns(self, *_):
columns=["A", "B", "A", "B"])
df.to_excel(self.path, "test1")
- result = read_excel(self.path, "test1", index_col=0)
+ result = pd.read_excel(self.path, "test1", index_col=0)
expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]],
columns=["A", "B", "A.1", "B.1"])
tm.assert_frame_equal(result, expected)
# see gh-10982
df.to_excel(self.path, "test1", index=False, header=False)
- result = read_excel(self.path, "test1", header=None)
+ result = pd.read_excel(self.path, "test1", header=None)
expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
tm.assert_frame_equal(result, expected)
msg = "Setting mangle_dupe_cols=False is not supported yet"
with pytest.raises(ValueError, match=msg):
- read_excel(self.path, "test1", header=None, mangle_dupe_cols=False)
+ pd.read_excel(
+ self.path, "test1", header=None, mangle_dupe_cols=False)
def test_swapped_columns(self, merge_cells, engine, ext):
# Test for issue #5427.
@@ -1895,7 +1825,7 @@ def test_swapped_columns(self, merge_cells, engine, ext):
'B': [2, 2, 2]})
write_frame.to_excel(self.path, 'test1', columns=['B', 'A'])
- read_frame = read_excel(self.path, 'test1', header=0)
+ read_frame = pd.read_excel(self.path, 'test1', header=0)
tm.assert_series_equal(write_frame['A'], read_frame['A'])
tm.assert_series_equal(write_frame['B'], read_frame['B'])
@@ -1910,7 +1840,7 @@ def test_invalid_columns(self, *_):
write_frame.to_excel(self.path, "test1", columns=["B", "C"])
expected = write_frame.reindex(columns=["B", "C"])
- read_frame = read_excel(self.path, "test1", index_col=0)
+ read_frame = pd.read_excel(self.path, "test1", index_col=0)
tm.assert_frame_equal(expected, read_frame)
with pytest.raises(KeyError):
@@ -1919,7 +1849,7 @@ def test_invalid_columns(self, *_):
def test_comment_arg(self, *_):
# see gh-18735
#
- # Test the comment argument functionality to read_excel.
+ # Test the comment argument functionality to pd.read_excel.
# Create file to read in.
df = DataFrame({"A": ["one", "#one", "one"],
@@ -1927,18 +1857,18 @@ def test_comment_arg(self, *_):
df.to_excel(self.path, "test_c")
# Read file without comment arg.
- result1 = read_excel(self.path, "test_c", index_col=0)
+ result1 = pd.read_excel(self.path, "test_c", index_col=0)
result1.iloc[1, 0] = None
result1.iloc[1, 1] = None
result1.iloc[2, 1] = None
- result2 = read_excel(self.path, "test_c", comment="#", index_col=0)
+ result2 = pd.read_excel(self.path, "test_c", comment="#", index_col=0)
tm.assert_frame_equal(result1, result2)
def test_comment_default(self, merge_cells, engine, ext):
# Re issue #18735
- # Test the comment argument default to read_excel
+ # Test the comment argument default to pd.read_excel
# Create file to read in
df = DataFrame({'A': ['one', '#one', 'one'],
@@ -1946,8 +1876,8 @@ def test_comment_default(self, merge_cells, engine, ext):
df.to_excel(self.path, 'test_c')
# Read file with default and explicit comment=None
- result1 = read_excel(self.path, 'test_c')
- result2 = read_excel(self.path, 'test_c', comment=None)
+ result1 = pd.read_excel(self.path, 'test_c')
+ result2 = pd.read_excel(self.path, 'test_c', comment=None)
tm.assert_frame_equal(result1, result2)
def test_comment_used(self, *_):
@@ -1963,19 +1893,19 @@ def test_comment_used(self, *_):
# Test read_frame_comment against manually produced expected output.
expected = DataFrame({"A": ["one", None, "one"],
"B": ["two", None, None]})
- result = read_excel(self.path, "test_c", comment="#", index_col=0)
+ result = pd.read_excel(self.path, "test_c", comment="#", index_col=0)
tm.assert_frame_equal(result, expected)
def test_comment_empty_line(self, merge_cells, engine, ext):
# Re issue #18735
- # Test that read_excel ignores commented lines at the end of file
+ # Test that pd.read_excel ignores commented lines at the end of file
df = DataFrame({'a': ['1', '#2'], 'b': ['2', '3']})
df.to_excel(self.path, index=False)
# Test that all-comment lines at EoF are ignored
expected = DataFrame({'a': [1], 'b': [2]})
- result = read_excel(self.path, comment='#')
+ result = pd.read_excel(self.path, comment='#')
tm.assert_frame_equal(result, expected)
def test_datetimes(self, merge_cells, engine, ext):
@@ -1995,7 +1925,7 @@ def test_datetimes(self, merge_cells, engine, ext):
write_frame = DataFrame({'A': datetimes})
write_frame.to_excel(self.path, 'Sheet1')
- read_frame = read_excel(self.path, 'Sheet1', header=0)
+ read_frame = pd.read_excel(self.path, 'Sheet1', header=0)
tm.assert_series_equal(write_frame['A'], read_frame['A'])
@@ -2010,7 +1940,7 @@ def test_bytes_io(self, merge_cells, engine, ext):
writer.save()
bio.seek(0)
- reread_df = read_excel(bio, index_col=0)
+ reread_df = pd.read_excel(bio, index_col=0)
tm.assert_frame_equal(df, reread_df)
def test_write_lists_dict(self, *_):
@@ -2019,7 +1949,7 @@ def test_write_lists_dict(self, *_):
"numeric": [1, 2, 3.0],
"str": ["apple", "banana", "cherry"]})
df.to_excel(self.path, "Sheet1")
- read = read_excel(self.path, "Sheet1", header=0, index_col=0)
+ read = pd.read_excel(self.path, "Sheet1", header=0, index_col=0)
expected = df.copy()
expected.mixed = expected.mixed.apply(str)
@@ -2033,8 +1963,8 @@ def test_true_and_false_value_options(self, *_):
expected = df.replace({"foo": True, "bar": False})
df.to_excel(self.path)
- read_frame = read_excel(self.path, true_values=["foo"],
- false_values=["bar"], index_col=0)
+ read_frame = pd.read_excel(self.path, true_values=["foo"],
+ false_values=["bar"], index_col=0)
tm.assert_frame_equal(read_frame, expected)
def test_freeze_panes(self, *_):
@@ -2042,7 +1972,7 @@ def test_freeze_panes(self, *_):
expected = DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"])
expected.to_excel(self.path, "Sheet1", freeze_panes=(1, 1))
- result = read_excel(self.path, index_col=0)
+ result = pd.read_excel(self.path, index_col=0)
tm.assert_frame_equal(result, expected)
def test_path_path_lib(self, merge_cells, engine, ext):
| Continued simplification of this module by moving towards pytest idiom. Here I have eliminated any test instance methods and replaced with fixtures
| https://api.github.com/repos/pandas-dev/pandas/pulls/26543 | 2019-05-28T06:55:14Z | 2019-05-30T01:02:01Z | 2019-05-30T01:02:01Z | 2019-05-30T01:48:43Z |
CLN: pd.options.html.border | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 32faf7115f0fd..276812a564e03 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -315,6 +315,7 @@ Removal of prior version deprecations/changes
- Removed the previously deprecated ``sheetname`` keyword in :func:`read_excel` (:issue:`16442`, :issue:`20938`)
- Removed the previously deprecated ``TimeGrouper`` (:issue:`16942`)
- Removed the previously deprecated ``parse_cols`` keyword in :func:`read_excel` (:issue:`16488`)
+- Removed the previously deprecated ``pd.options.html.border`` (:issue:`16970`)
.. _whatsnew_0250.performance:
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index dc63b15cf9c13..7eb2b413822d9 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -185,11 +185,6 @@ def use_numexpr_cb(key):
for the DataFrame HTML repr.
"""
-pc_html_border_deprecation_warning = """\
-html.border has been deprecated, use display.html.border instead
-(currently both are identical)
-"""
-
pc_html_use_mathjax_doc = """\
: boolean
When True, Jupyter notebook will process table contents using MathJax,
@@ -363,14 +358,6 @@ def is_terminal():
cf.register_option('html.use_mathjax', True, pc_html_use_mathjax_doc,
validator=is_bool)
-with cf.config_prefix('html'):
- cf.register_option('border', 1, pc_html_border_doc,
- validator=is_int)
-
-cf.deprecate_option('html.border', msg=pc_html_border_deprecation_warning,
- rkey='display.html.border')
-
-
tc_sim_interactive_doc = """
: boolean
Whether to simulate interactive mode for purposes of testing
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 7cf200506e853..963da247fcaa5 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2160,7 +2160,7 @@ def to_html(self, buf=None, columns=None, col_space=None, header=True,
Whether the generated HTML is for IPython Notebook.
border : int
A ``border=border`` attribute is included in the opening
- `<table>` tag. Default ``pd.options.html.border``.
+ `<table>` tag. Default ``pd.options.display.html.border``.
.. versionadded:: 0.19.0
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 1c1acebb8f8f7..765b31f294bcb 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -729,7 +729,7 @@ def to_html(self, classes=None, notebook=False, border=None):
Whether the generated HTML is for IPython Notebook.
border : int
A ``border=border`` attribute is included in the opening
- ``<table>`` tag. Default ``pd.options.html.border``.
+ ``<table>`` tag. Default ``pd.options.display.html.border``.
.. versionadded:: 0.19.0
"""
diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py
index eb71dd4c6914c..9666bc4977587 100644
--- a/pandas/tests/io/formats/test_to_html.py
+++ b/pandas/tests/io/formats/test_to_html.py
@@ -244,12 +244,6 @@ def test_to_html_border(option, result, expected):
assert expected in result
-def test_display_option_warning():
- with tm.assert_produces_warning(FutureWarning,
- check_stacklevel=False):
- pd.options.html.border
-
-
@pytest.mark.parametrize('biggie_df_fixture', ['mixed'], indirect=True)
def test_to_html(biggie_df_fixture):
# TODO: split this test
| - [x] xref #6581
- [x] tests passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26540 | 2019-05-27T18:01:47Z | 2019-05-27T18:44:00Z | 2019-05-27T18:44:00Z | 2019-05-27T18:44:03Z |
Add reader for SPSS (.sav) files | diff --git a/LICENSES/HAVEN_LICENSE b/LICENSES/HAVEN_LICENSE
new file mode 100644
index 0000000000000..2f444cb44d505
--- /dev/null
+++ b/LICENSES/HAVEN_LICENSE
@@ -0,0 +1,2 @@
+YEAR: 2013-2016
+COPYRIGHT HOLDER: Hadley Wickham; RStudio; and Evan Miller
diff --git a/LICENSES/HAVEN_MIT b/LICENSES/HAVEN_MIT
new file mode 100644
index 0000000000000..b03d0e640627a
--- /dev/null
+++ b/LICENSES/HAVEN_MIT
@@ -0,0 +1,32 @@
+Based on http://opensource.org/licenses/MIT
+
+This is a template. Complete and ship as file LICENSE the following 2
+lines (only)
+
+YEAR:
+COPYRIGHT HOLDER:
+
+and specify as
+
+License: MIT + file LICENSE
+
+Copyright (c) <YEAR>, <COPYRIGHT HOLDER>
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/ci/deps/azure-macos-35.yaml b/ci/deps/azure-macos-35.yaml
index 8ed48b46b5b5a..24c753e16d98d 100644
--- a/ci/deps/azure-macos-35.yaml
+++ b/ci/deps/azure-macos-35.yaml
@@ -23,6 +23,7 @@ dependencies:
- xlsxwriter
- xlwt
- pip:
+ - pyreadstat
# universal
- pytest==4.5.0
- pytest-xdist
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index 04e4f74f85e4d..5bdc29e0eec80 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -30,3 +30,4 @@ dependencies:
- pytest-mock
- moto
- hypothesis>=3.58.0
+ - pyreadstat
diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml
index 722a35111ab01..c9a8c274fb144 100644
--- a/ci/deps/travis-37.yaml
+++ b/ci/deps/travis-37.yaml
@@ -19,5 +19,6 @@ dependencies:
- hypothesis>=3.58.0
- s3fs
- pip
+ - pyreadstat
- pip:
- moto
diff --git a/doc/source/install.rst b/doc/source/install.rst
index db31d75e3013e..1c1f0c1d4cf8e 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -285,6 +285,7 @@ pandas-gbq 0.8.0 Google Big Query access
psycopg2 PostgreSQL engine for sqlalchemy
pyarrow 0.9.0 Parquet and feather reading / writing
pymysql MySQL engine for sqlalchemy
+pyreadstat SPSS files (.sav) reading
qtpy Clipboard I/O
s3fs 0.0.8 Amazon S3 access
xarray 0.8.2 pandas-like API for N-dimensional data
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 78d3d8fcb3d01..66279347d17ed 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -99,6 +99,7 @@ Other Enhancements
- Error message for missing required imports now includes the original import error's text (:issue:`23868`)
- :class:`DatetimeIndex` and :class:`TimedeltaIndex` now have a ``mean`` method (:issue:`24757`)
- :meth:`DataFrame.describe` now formats integer percentiles without decimal point (:issue:`26660`)
+- Added support for reading SPSS .sav files using :func:`read_spss` (:issue:`26537`)
.. _whatsnew_0250.api_breaking:
diff --git a/environment.yml b/environment.yml
index 7db2ec72ccb3b..de9bd67dd9f06 100644
--- a/environment.yml
+++ b/environment.yml
@@ -79,3 +79,5 @@ dependencies:
- xlrd # pandas.read_excel, DataFrame.to_excel, pandas.ExcelWriter, pandas.ExcelFile
- xlsxwriter # pandas.read_excel, DataFrame.to_excel, pandas.ExcelWriter, pandas.ExcelFile
- xlwt # pandas.read_excel, DataFrame.to_excel, pandas.ExcelWriter, pandas.ExcelFile
+ - pip:
+ - pyreadstat # pandas.read_spss
diff --git a/pandas/__init__.py b/pandas/__init__.py
index a2fa14be83998..b95c312f12eed 100644
--- a/pandas/__init__.py
+++ b/pandas/__init__.py
@@ -105,7 +105,7 @@
# misc
read_clipboard, read_parquet, read_feather, read_gbq,
- read_html, read_json, read_stata, read_sas)
+ read_html, read_json, read_stata, read_sas, read_spss)
from pandas.util._tester import test
import pandas.testing
diff --git a/pandas/io/api.py b/pandas/io/api.py
index 8c8d7cf73b37a..725e82604ca7f 100644
--- a/pandas/io/api.py
+++ b/pandas/io/api.py
@@ -16,5 +16,6 @@
from pandas.io.pickle import read_pickle, to_pickle
from pandas.io.pytables import HDFStore, read_hdf
from pandas.io.sas import read_sas
+from pandas.io.spss import read_spss
from pandas.io.sql import read_sql, read_sql_query, read_sql_table
from pandas.io.stata import read_stata
diff --git a/pandas/io/spss.py b/pandas/io/spss.py
new file mode 100644
index 0000000000000..b1b92fc2b8439
--- /dev/null
+++ b/pandas/io/spss.py
@@ -0,0 +1,41 @@
+from pathlib import Path
+from typing import Optional, Sequence, Union
+
+from pandas.compat._optional import import_optional_dependency
+
+from pandas.api.types import is_list_like
+from pandas.core.api import DataFrame
+
+
+def read_spss(path: Union[str, Path],
+ usecols: Optional[Sequence[str]] = None,
+ convert_categoricals: bool = True) -> DataFrame:
+ """
+ Load an SPSS file from the file path, returning a DataFrame.
+
+ .. versionadded 0.25.0
+
+ Parameters
+ ----------
+ path : string or Path
+ File path
+ usecols : list-like, optional
+ Return a subset of the columns. If None, return all columns.
+ convert_categoricals : bool, default is True
+ Convert categorical columns into pd.Categorical.
+
+ Returns
+ -------
+ DataFrame
+ """
+ pyreadstat = import_optional_dependency("pyreadstat")
+
+ if usecols is not None:
+ if not is_list_like(usecols):
+ raise TypeError("usecols must be list-like.")
+ else:
+ usecols = list(usecols) # pyreadstat requires a list
+
+ df, _ = pyreadstat.read_sav(path, usecols=usecols,
+ apply_value_formats=convert_categoricals)
+ return df
diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py
index aa42484bf9513..b57c7a0cf0625 100644
--- a/pandas/tests/api/test_api.py
+++ b/pandas/tests/api/test_api.py
@@ -81,7 +81,7 @@ class TestPDApi(Base):
'read_gbq', 'read_hdf', 'read_html', 'read_json',
'read_msgpack', 'read_pickle', 'read_sas', 'read_sql',
'read_sql_query', 'read_sql_table', 'read_stata',
- 'read_table', 'read_feather', 'read_parquet']
+ 'read_table', 'read_feather', 'read_parquet', 'read_spss']
# top-level to_* funcs
funcs_to = ['to_datetime', 'to_msgpack',
diff --git a/pandas/tests/io/data/labelled-num-na.sav b/pandas/tests/io/data/labelled-num-na.sav
new file mode 100755
index 0000000000000..fbe6ee7767240
Binary files /dev/null and b/pandas/tests/io/data/labelled-num-na.sav differ
diff --git a/pandas/tests/io/data/labelled-num.sav b/pandas/tests/io/data/labelled-num.sav
new file mode 100755
index 0000000000000..bfab052089d7e
Binary files /dev/null and b/pandas/tests/io/data/labelled-num.sav differ
diff --git a/pandas/tests/io/data/labelled-str.sav b/pandas/tests/io/data/labelled-str.sav
new file mode 100755
index 0000000000000..b96a9c00fcec1
Binary files /dev/null and b/pandas/tests/io/data/labelled-str.sav differ
diff --git a/pandas/tests/io/data/umlauts.sav b/pandas/tests/io/data/umlauts.sav
new file mode 100755
index 0000000000000..e99cf1267bebe
Binary files /dev/null and b/pandas/tests/io/data/umlauts.sav differ
diff --git a/pandas/tests/io/test_spss.py b/pandas/tests/io/test_spss.py
new file mode 100644
index 0000000000000..b9f58f9bf6cf6
--- /dev/null
+++ b/pandas/tests/io/test_spss.py
@@ -0,0 +1,74 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas.util import testing as tm
+
+pyreadstat = pytest.importorskip("pyreadstat")
+
+
+def test_spss_labelled_num(datapath):
+ # test file from the Haven project (https://haven.tidyverse.org/)
+ fname = datapath("io", "data", "labelled-num.sav")
+
+ df = pd.read_spss(fname, convert_categoricals=True)
+ expected = pd.DataFrame({"VAR00002": "This is one"}, index=[0])
+ expected["VAR00002"] = pd.Categorical(expected["VAR00002"])
+ tm.assert_frame_equal(df, expected)
+
+ df = pd.read_spss(fname, convert_categoricals=False)
+ expected = pd.DataFrame({"VAR00002": 1.0}, index=[0])
+ tm.assert_frame_equal(df, expected)
+
+
+def test_spss_labelled_num_na(datapath):
+ # test file from the Haven project (https://haven.tidyverse.org/)
+ fname = datapath("io", "data", "labelled-num-na.sav")
+
+ df = pd.read_spss(fname, convert_categoricals=True)
+ expected = pd.DataFrame({"VAR00002": ["This is one", None]})
+ expected["VAR00002"] = pd.Categorical(expected["VAR00002"])
+ tm.assert_frame_equal(df, expected)
+
+ df = pd.read_spss(fname, convert_categoricals=False)
+ expected = pd.DataFrame({"VAR00002": [1.0, np.nan]})
+ tm.assert_frame_equal(df, expected)
+
+
+def test_spss_labelled_str(datapath):
+ # test file from the Haven project (https://haven.tidyverse.org/)
+ fname = datapath("io", "data", "labelled-str.sav")
+
+ df = pd.read_spss(fname, convert_categoricals=True)
+ expected = pd.DataFrame({"gender": ["Male", "Female"]})
+ expected["gender"] = pd.Categorical(expected["gender"])
+ tm.assert_frame_equal(df, expected)
+
+ df = pd.read_spss(fname, convert_categoricals=False)
+ expected = pd.DataFrame({"gender": ["M", "F"]})
+ tm.assert_frame_equal(df, expected)
+
+
+def test_spss_umlauts(datapath):
+ # test file from the Haven project (https://haven.tidyverse.org/)
+ fname = datapath("io", "data", "umlauts.sav")
+
+ df = pd.read_spss(fname, convert_categoricals=True)
+ expected = pd.DataFrame({"var1": ["the ä umlaut",
+ "the ü umlaut",
+ "the ä umlaut",
+ "the ö umlaut"]})
+ expected["var1"] = pd.Categorical(expected["var1"])
+ tm.assert_frame_equal(df, expected)
+
+ df = pd.read_spss(fname, convert_categoricals=False)
+ expected = pd.DataFrame({"var1": [1.0, 2.0, 1.0, 3.0]})
+ tm.assert_frame_equal(df, expected)
+
+
+def test_spss_usecols(datapath):
+ # usecols must be list-like
+ fname = datapath("io", "data", "labelled-num.sav")
+
+ with pytest.raises(TypeError, match="usecols must be list-like."):
+ pd.read_spss(fname, usecols="VAR00002")
diff --git a/requirements-dev.txt b/requirements-dev.txt
index b40aa86e946b6..169af7da5e037 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -52,4 +52,5 @@ sqlalchemy
xarray
xlrd
xlsxwriter
-xlwt
\ No newline at end of file
+xlwt
+pyreadstat
\ No newline at end of file
| - [x] closes #5768 (at least the reading part, this PR does not cover writing SPSS files)
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
I haven't added a test yet because I wanted to ask which test .sav file I should use (and where to put it). Also, there's no whatsnew entry yet - in which section should this entry go (and I assume it will be out for 0.25.0, so I'll have to change 0.24.3 to 0.25.0 in the docstring).
This PR adds the capability to load SPSS .sav files with `df = pd.io.read_spss("spss_file.sav")`. Currently, there are two optional arguments: `usecols` (should be self-explanatory, let me know if you don't want me to handle a simple `str`) and `categorical`, which maps to the `apply_value_formats` parameter in `read_sav`. With `categorical=True`, a categorical columns is created with the labels from the .sav file. If `False`, numbers will be used.
A few open questions:
- Which additional optional arguments should be made available? [Pyreadstat](https://github.com/Roche/pyreadstat/blob/master/pyreadstat/pyreadstat.pyx#L208-L244) has `dates_as_pandas_datetime`, `encoding`, and `user_missing` which I haven't mapped yet.
- Should the function be called `read_spss` or `read_sav`? SPSS files have the extension `sav`, but the R haven package has a function `read_spss` (which is why I'd prefer `read_spss`).
- Are there any additional meta information bits that could be used/integrated into the data frame? `pyreadstat.read_sav` returns a dataframe and meta-information separately, which I think we shouldn't do in pandas. | https://api.github.com/repos/pandas-dev/pandas/pulls/26537 | 2019-05-27T11:49:42Z | 2019-06-16T14:30:39Z | 2019-06-16T14:30:39Z | 2019-07-19T13:19:30Z |
Add typing annotation to assert_index_equal | diff --git a/pandas/util/testing.py b/pandas/util/testing.py
index 92d450140a891..107c17c5253fb 100644
--- a/pandas/util/testing.py
+++ b/pandas/util/testing.py
@@ -12,6 +12,7 @@
import string
import tempfile
import traceback
+from typing import Union, cast
import warnings
import zipfile
@@ -515,9 +516,14 @@ def equalContents(arr1, arr2):
return frozenset(arr1) == frozenset(arr2)
-def assert_index_equal(left, right, exact='equiv', check_names=True,
- check_less_precise=False, check_exact=True,
- check_categorical=True, obj='Index'):
+def assert_index_equal(left: Index,
+ right: Index,
+ exact: Union[bool, str] = 'equiv',
+ check_names: bool = True,
+ check_less_precise: Union[bool, int] = False,
+ check_exact: bool = True,
+ check_categorical: bool = True,
+ obj: str = 'Index') -> None:
"""Check that left and right Index are equal.
Parameters
@@ -588,6 +594,9 @@ def _get_ilevel_values(index, level):
# MultiIndex special comparison for little-friendly error messages
if left.nlevels > 1:
+ left = cast(MultiIndex, left)
+ right = cast(MultiIndex, right)
+
for level in range(left.nlevels):
# cannot use get_level_values here because it can change dtype
llevel = _get_ilevel_values(left, level)
| - xref #26302
- passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/26535 | 2019-05-27T07:39:24Z | 2019-06-08T21:45:50Z | 2019-06-08T21:45:50Z | 2019-06-08T21:45:55Z |
DOC: fix broken link for .iloc | diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 3c7a286c8a4f8..93e56834b62f6 100755
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1940,7 +1940,7 @@ class _iLocIndexer(_LocationIndexer):
out-of-bounds, except *slice* indexers which allow out-of-bounds
indexing (this conforms with python/numpy *slice* semantics).
- See more at ref:`Selection by Position <indexing.integer>`.
+ See more at :ref:`Selection by Position <indexing.integer>`.
See Also
--------
| https://api.github.com/repos/pandas-dev/pandas/pulls/26533 | 2019-05-26T18:13:38Z | 2019-05-27T15:04:17Z | 2019-05-27T15:04:17Z | 2019-05-27T15:09:36Z | |
Docstring GL01 GL02 fixes | diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py
index 4353e0b3edd08..b092541da93e6 100644
--- a/pandas/core/accessor.py
+++ b/pandas/core/accessor.py
@@ -196,7 +196,7 @@ def decorator(accessor):
return decorator
-_doc = """\
+_doc = """
Register a custom accessor on %(klass)s objects.
Parameters
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index c079b860bb924..155638aca5560 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -196,7 +196,7 @@ def contains(cat, key, container):
return any(loc_ in container for loc_ in loc)
-_codes_doc = """\
+_codes_doc = """
The category codes of this categorical.
Level codes are an array if integer which are the positions of the real
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 4f628eff43167..71f4cbae7c58d 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -987,7 +987,7 @@ def __array__(self, dtype=None):
result[i] = Interval(left[i], right[i], closed)
return result
- _interval_shared_docs['to_tuples'] = """\
+ _interval_shared_docs['to_tuples'] = """
Return an %(return_type)s of tuples of the form (left, right)
Parameters
@@ -1002,7 +1002,7 @@ def __array__(self, dtype=None):
-------
tuples: %(return_type)s
%(examples)s\
- """
+ """
@Appender(_interval_shared_docs['to_tuples'] % dict(
return_type='ndarray',
diff --git a/pandas/core/base.py b/pandas/core/base.py
index e4274e48d3227..ab9d8b9d778e5 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -638,8 +638,8 @@ def _is_builtin_func(self, arg):
class IndexOpsMixin:
- """ common ops mixin to support a unified interface / docs for Series /
- Index
+ """
+ Common ops mixin to support a unified interface / docs for Series / Index
"""
# ndarray compatibility
@@ -656,8 +656,8 @@ def transpose(self, *args, **kwargs):
nv.validate_transpose(args, kwargs)
return self
- T = property(transpose, doc="Return the transpose, which is by "
- "definition self.")
+ T = property(transpose, doc="""\nReturn the transpose, which is by
+ definition self.\n""")
@property
def _is_homogeneous_type(self):
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py
index 8f6c271af4a58..ef4639a3afe4c 100644
--- a/pandas/core/computation/eval.py
+++ b/pandas/core/computation/eval.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
-"""Top level ``eval`` module.
+"""
+Top level ``eval`` module.
"""
import tokenize
@@ -15,7 +16,8 @@
def _check_engine(engine):
- """Make sure a valid engine is passed.
+ """
+ Make sure a valid engine is passed.
Parameters
----------
@@ -31,7 +33,6 @@ def _check_engine(engine):
Returns
-------
string engine
-
"""
from pandas.core.computation.check import _NUMEXPR_INSTALLED
@@ -60,7 +61,8 @@ def _check_engine(engine):
def _check_parser(parser):
- """Make sure a valid parser is passed.
+ """
+ Make sure a valid parser is passed.
Parameters
----------
@@ -88,7 +90,8 @@ def _check_resolvers(resolvers):
def _check_expression(expr):
- """Make sure an expression is not an empty string
+ """
+ Make sure an expression is not an empty string
Parameters
----------
@@ -105,7 +108,8 @@ def _check_expression(expr):
def _convert_expression(expr):
- """Convert an object to an expression.
+ """
+ Convert an object to an expression.
Thus function converts an object to an expression (a unicode string) and
checks to make sure it isn't empty after conversion. This is used to
@@ -155,7 +159,8 @@ def _check_for_locals(expr, stack_level, parser):
def eval(expr, parser='pandas', engine=None, truediv=True,
local_dict=None, global_dict=None, resolvers=(), level=0,
target=None, inplace=False):
- """Evaluate a Python expression as a string using various backends.
+ """
+ Evaluate a Python expression as a string using various backends.
The following arithmetic operations are supported: ``+``, ``-``, ``*``,
``/``, ``**``, ``%``, ``//`` (python engine only) along with the following
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index a56ee72cf1910..7fe8ce7d71683 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -631,12 +631,16 @@ def __init__(self, unit="ns", tz=None):
@property
def unit(self):
- """The precision of the datetime data."""
+ """
+ The precision of the datetime data.
+ """
return self._unit
@property
def tz(self):
- """The timezone."""
+ """
+ The timezone.
+ """
return self._tz
@classmethod
@@ -777,7 +781,9 @@ def __new__(cls, freq=None):
@property
def freq(self):
- """The frequency object of this PeriodDtype."""
+ """
+ The frequency object of this PeriodDtype.
+ """
return self._freq
@classmethod
@@ -944,7 +950,9 @@ def __new__(cls, subtype=None):
@property
def subtype(self):
- """The dtype of the Interval bounds."""
+ """
+ The dtype of the Interval bounds.
+ """
return self._subtype
@classmethod
diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py
index 63cb4d85ca308..02ee777bbe7f3 100644
--- a/pandas/core/dtypes/inference.py
+++ b/pandas/core/dtypes/inference.py
@@ -427,7 +427,8 @@ def is_named_tuple(obj):
def is_hashable(obj):
- """Return True if hash(obj) will succeed, False otherwise.
+ """
+ Return True if hash(obj) will succeed, False otherwise.
Some types will pass a test against collections.abc.Hashable but fail when
they are actually hashed with hash().
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 903fd7ffe706a..fd890dcf9cd93 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1832,7 +1832,8 @@ def __iter__(self):
# can we get a better explanation of this?
def keys(self):
- """Get the 'info axis' (see Indexing for more)
+ """
+ Get the 'info axis' (see Indexing for more)
This is index for Series, columns for DataFrame.
@@ -1844,7 +1845,8 @@ def keys(self):
return self._info_axis
def iteritems(self):
- """Iterate over (label, values) on info axis
+ """
+ Iterate over (label, values) on info axis
This is index for Series, columns for DataFrame and so on.
"""
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 2b190c53da53d..43950f2f503c8 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -172,7 +172,7 @@ class providing the base-class of operations.
{examples}
""")
-_pipe_template = """\
+_pipe_template = """
Apply a function `func` with arguments to this %(klass)s object and return
the function's result.
@@ -223,7 +223,8 @@ class providing the base-class of operations.
Examples
--------
-%(examples)s"""
+%(examples)s
+"""
_transform_template = """
Call function producing a like-indexed %(klass)s on each group and
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 24fcb32d09d27..d5467134f1413 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -769,7 +769,8 @@ def _find_non_overlapping_monotonic_bounds(self, key):
return start, stop
def get_loc(self, key, method=None):
- """Get integer location, slice or boolean mask for requested label.
+ """
+ Get integer location, slice or boolean mask for requested label.
Parameters
----------
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 9217b388ce86b..0d31276102b3a 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1119,7 +1119,7 @@ def _set_names(self, names, level=None, validate=True):
self.levels[l].rename(name, inplace=True)
names = property(fset=_set_names, fget=_get_names,
- doc="Names of levels in MultiIndex")
+ doc="""\nNames of levels in MultiIndex\n""")
@Appender(_index_shared_docs['_get_grouper_for_level'])
def _get_grouper_for_level(self, mapper, level):
@@ -1773,12 +1773,16 @@ def remove_unused_levels(self):
@property
def nlevels(self):
- """Integer number of levels in this MultiIndex."""
+ """
+ Integer number of levels in this MultiIndex.
+ """
return len(self.levels)
@property
def levshape(self):
- """A tuple with the length of each level."""
+ """
+ A tuple with the length of each level.
+ """
return tuple(len(x) for x in self.levels)
def __reduce__(self):
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 7f4827be6dff7..6a21adb1d16ae 100755
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1311,7 +1311,8 @@ def _get_slice_axis(self, slice_obj, axis=None):
class _IXIndexer(_NDFrameIndexer):
- """A primarily label-location based indexer, with integer position
+ """
+ A primarily label-location based indexer, with integer position
fallback.
Warning: Starting in 0.20.0, the .ix indexer is deprecated, in
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 874973846a006..d1d99d28e59b6 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -204,8 +204,7 @@ def _assure_grouper(self):
>>> df.resample('2D').pipe(lambda x: x.max() - x.min())
A
2012-08-02 1
- 2012-08-04 1
- """)
+ 2012-08-04 1""")
@Appender(_pipe_template)
def pipe(self, func, *args, **kwargs):
return super().pipe(func, *args, **kwargs)
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 1a80b35629356..d21ad58e752c2 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -133,7 +133,8 @@ def merge_ordered(left, right, on=None,
left_by=None, right_by=None,
fill_method=None, suffixes=('_x', '_y'),
how='outer'):
- """Perform merge with optional filling/interpolation designed for ordered
+ """
+ Perform merge with optional filling/interpolation designed for ordered
data like time series data. Optionally perform group-wise merge (see
examples)
@@ -240,7 +241,8 @@ def merge_asof(left, right, on=None,
tolerance=None,
allow_exact_matches=True,
direction='backward'):
- """Perform an asof merge. This is similar to a left-join except that we
+ """
+ Perform an asof merge. This is similar to a left-join except that we
match on nearest key rather than equal keys.
Both DataFrames must be sorted by the key.
| - [X] closes #24071 and also includes requested fixes from #25324
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26526 | 2019-05-26T11:04:55Z | 2019-06-21T02:10:49Z | 2019-06-21T02:10:49Z | 2019-06-21T02:10:54Z |
CLN: remove StringMixin from code base, except in core.computation | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 0f7f6fe399256..11f705e88179d 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -32,7 +32,6 @@
to_datetime)
from pandas.core.arrays.categorical import Categorical
from pandas.core.arrays.sparse import BlockIndex, IntIndex
-from pandas.core.base import StringMixin
import pandas.core.common as com
from pandas.core.computation.pytables import Expr, maybe_expression
from pandas.core.index import ensure_index
@@ -398,7 +397,7 @@ def _is_metadata_of(group, parent_group):
return False
-class HDFStore(StringMixin):
+class HDFStore:
"""
Dict-like IO interface for storing pandas objects in PyTables
@@ -520,7 +519,7 @@ def __contains__(self, key):
def __len__(self):
return len(self.groups())
- def __str__(self):
+ def __repr__(self):
return '{type}\nFile path: {path}\n'.format(
type=type(self), path=pprint_thing(self._path))
@@ -1519,7 +1518,7 @@ def get_result(self, coordinates=False):
return results
-class IndexCol(StringMixin):
+class IndexCol:
""" an index column description class
@@ -1587,7 +1586,7 @@ def set_table(self, table):
self.table = table
return self
- def __str__(self):
+ def __repr__(self):
temp = tuple(
map(pprint_thing,
(self.name,
@@ -1881,7 +1880,7 @@ def __init__(self, values=None, kind=None, typ=None,
self.set_data(data)
self.set_metadata(metadata)
- def __str__(self):
+ def __repr__(self):
temp = tuple(
map(pprint_thing,
(self.name,
@@ -2286,7 +2285,7 @@ def get_attr(self):
pass
-class Fixed(StringMixin):
+class Fixed:
""" represent an object in my store
facilitate read/write of various types of objects
@@ -2336,7 +2335,7 @@ def pandas_type(self):
def format_type(self):
return 'fixed'
- def __str__(self):
+ def __repr__(self):
""" return a pretty representation of myself """
self.infer_axes()
s = self.shape
@@ -3077,8 +3076,8 @@ def table_type_short(self):
def format_type(self):
return 'table'
- def __str__(self):
- """ return a pretty representatgion of myself """
+ def __repr__(self):
+ """ return a pretty representation of myself """
self.infer_axes()
dc = ",dc->[{columns}]".format(columns=(','.join(
self.data_columns) if len(self.data_columns) else ''))
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 27ddc4ef6f594..d8dfd15477974 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -31,7 +31,6 @@
from pandas import (
Categorical, DatetimeIndex, NaT, Timestamp, concat, isna, to_datetime,
to_timedelta)
-from pandas.core.base import StringMixin
from pandas.core.frame import DataFrame
from pandas.core.series import Series
@@ -712,7 +711,7 @@ def generate_value_label(self, byteorder, encoding):
return bio.read()
-class StataMissingValue(StringMixin):
+class StataMissingValue:
"""
An observation's missing value.
| - [x] xref #25725 & #26495
- [ ] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Removes use of ``StringMixin`` from pandas.io StringMixin is now only used in pandas.core.computation.
I haven't been able to remove this class from core.computation. If I do, I get an error about setting an attribute:
```python
# assumes that resolvers are going from outermost scope to inner
if isinstance(local_dict, Scope):
resolvers += tuple(local_dict.resolvers.maps)
self.resolvers = DeepChainMap(*resolvers)
E AttributeError: 'Scope' object has no attribute 'resolvers'
pandas\core\computation\scope.py:134: AttributeError
```
I've looked into this and can't understand why this happens. From the looks of it, I should be able to set that atribute here, but it jusr doesn't work. I'd appreciate any hint.
I'll keep loking into removing it completely, but don't know if I'll crack that part. | https://api.github.com/repos/pandas-dev/pandas/pulls/26523 | 2019-05-25T16:58:59Z | 2019-05-26T14:31:44Z | 2019-05-26T14:31:44Z | 2019-05-26T15:30:36Z |
CLN: Remove deprecated parse_cols from read_excel | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index c51441f701a45..32faf7115f0fd 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -313,8 +313,8 @@ Removal of prior version deprecations/changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Removed ``Panel`` (:issue:`25047`, :issue:`25191`, :issue:`25231`)
- Removed the previously deprecated ``sheetname`` keyword in :func:`read_excel` (:issue:`16442`, :issue:`20938`)
-- Removed previously deprecated ``TimeGrouper`` (:issue:`16942`)
--
+- Removed the previously deprecated ``TimeGrouper`` (:issue:`16942`)
+- Removed the previously deprecated ``parse_cols`` keyword in :func:`read_excel` (:issue:`16488`)
.. _whatsnew_0250.performance:
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index a0d51e85aa4f3..3af6be7a371e7 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -64,12 +64,6 @@
those columns will be combined into a ``MultiIndex``. If a
subset of data is selected with ``usecols``, index_col
is based on the subset.
-parse_cols : int or list, default None
- Alias of `usecols`.
-
- .. deprecated:: 0.21.0
- Use `usecols` instead.
-
usecols : int, str, list-like, or callable default None
Return a subset of the columns.
@@ -260,14 +254,12 @@
@Appender(_read_excel_doc)
-@deprecate_kwarg("parse_cols", "usecols")
@deprecate_kwarg("skip_footer", "skipfooter")
def read_excel(io,
sheet_name=0,
header=0,
names=None,
index_col=None,
- parse_cols=None,
usecols=None,
squeeze=False,
dtype=None,
@@ -290,7 +282,7 @@ def read_excel(io,
mangle_dupe_cols=True,
**kwds):
- for arg in ('sheet', 'sheetname'):
+ for arg in ('sheet', 'sheetname', 'parse_cols'):
if arg in kwds:
raise TypeError("read_excel() got an unexpected keyword argument "
"`{}`".format(arg))
diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py
index 44ce3111c3a1e..100de227aa97c 100644
--- a/pandas/tests/io/test_excel.py
+++ b/pandas/tests/io/test_excel.py
@@ -147,17 +147,9 @@ def test_usecols_int(self, ext):
df2 = self.get_exceldf("test1", ext, "Sheet2", skiprows=[1],
index_col=0, usecols=3)
- # parse_cols instead of usecols, usecols as int
- with tm.assert_produces_warning(FutureWarning,
- check_stacklevel=False):
- with ignore_xlrd_time_clock_warning():
- df3 = self.get_exceldf("test1", ext, "Sheet2", skiprows=[1],
- index_col=0, parse_cols=3)
-
# TODO add index to xls file)
tm.assert_frame_equal(df1, df_ref, check_names=False)
tm.assert_frame_equal(df2, df_ref, check_names=False)
- tm.assert_frame_equal(df3, df_ref, check_names=False)
@td.skip_if_no('xlrd', '1.0.1') # GH-22682
def test_usecols_list(self, ext):
@@ -169,15 +161,9 @@ def test_usecols_list(self, ext):
df2 = self.get_exceldf('test1', ext, 'Sheet2', skiprows=[1],
index_col=0, usecols=[0, 2, 3])
- with tm.assert_produces_warning(FutureWarning):
- with ignore_xlrd_time_clock_warning():
- df3 = self.get_exceldf('test1', ext, 'Sheet2', skiprows=[1],
- index_col=0, parse_cols=[0, 2, 3])
-
# TODO add index to xls file)
tm.assert_frame_equal(df1, dfref, check_names=False)
tm.assert_frame_equal(df2, dfref, check_names=False)
- tm.assert_frame_equal(df3, dfref, check_names=False)
@td.skip_if_no('xlrd', '1.0.1') # GH-22682
def test_usecols_str(self, ext):
@@ -190,15 +176,9 @@ def test_usecols_str(self, ext):
df3 = self.get_exceldf('test1', ext, 'Sheet2', skiprows=[1],
index_col=0, usecols='A:D')
- with tm.assert_produces_warning(FutureWarning):
- with ignore_xlrd_time_clock_warning():
- df4 = self.get_exceldf('test1', ext, 'Sheet2', skiprows=[1],
- index_col=0, parse_cols='A:D')
-
# TODO add index to xls, read xls ignores index name ?
tm.assert_frame_equal(df2, df1, check_names=False)
tm.assert_frame_equal(df3, df1, check_names=False)
- tm.assert_frame_equal(df4, df1, check_names=False)
df1 = dfref.reindex(columns=['B', 'C'])
df2 = self.get_exceldf('test1', ext, 'Sheet1', index_col=0,
@@ -342,7 +322,7 @@ def test_excel_passes_na(self, ext):
tm.assert_frame_equal(parsed, expected)
@td.skip_if_no('xlrd', '1.0.1') # GH-22682
- @pytest.mark.parametrize('arg', ['sheet', 'sheetname'])
+ @pytest.mark.parametrize('arg', ['sheet', 'sheetname', 'parse_cols'])
def test_unexpected_kwargs_raises(self, ext, arg):
# gh-17964
excel = self.get_excelfile('test1', ext)
| - [x] xref #6581
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26522 | 2019-05-25T16:37:42Z | 2019-05-25T18:40:15Z | 2019-05-25T18:40:15Z | 2019-05-26T02:50:12Z |
Issue/26506 Provides correct desciption in docstring that get_indexer methods are not yet supported | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index eff7ff2c9f347..caf881ef069e6 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -52,6 +52,7 @@
_index_doc_kwargs = dict(klass='Index', inplace='',
target_klass='Index',
+ raises_section='',
unique='Index', duplicated='np.ndarray')
_index_shared_docs = dict()
@@ -2787,7 +2788,7 @@ def get_loc(self, key, method=None, tolerance=None):
Integers from 0 to n - 1 indicating that the index at these
positions matches the corresponding target values. Missing values
in the target are marked by -1.
-
+ %(raises_section)s
Examples
--------
>>> index = pd.Index(['c', 'a', 'b'])
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 87216dcc7b957..a3b162a91ed19 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -8,7 +8,7 @@
from pandas._libs import Timedelta, Timestamp
from pandas._libs.interval import Interval, IntervalMixin, IntervalTree
-from pandas.util._decorators import Appender, cache_readonly
+from pandas.util._decorators import Appender, Substitution, cache_readonly
from pandas.util._exceptions import rewrite_exception
from pandas.core.dtypes.cast import (
@@ -805,7 +805,15 @@ def get_value(self, series, key):
loc = self.get_loc(key)
return series.iloc[loc]
- @Appender(_index_shared_docs['get_indexer'] % _index_doc_kwargs)
+ @Substitution(**dict(_index_doc_kwargs,
+ **{'raises_section': textwrap.dedent("""
+ Raises
+ ------
+ NotImplementedError
+ If any method argument other than the default of
+ None is specified as these are not yet implemented.
+ """)}))
+ @Appender(_index_shared_docs['get_indexer'])
def get_indexer(self, target, method=None, limit=None, tolerance=None):
self._check_method(method)
| - [x] fixes docstring for #26506 until implementation is ready
- [x] 46585 tests passed - none added as documentation change only
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
```
$ git diff upstream/master -u -- "*.py" | flake8 --diff && echo yes
yes
```
- [x] whatsnew entry
Provides correct desciption in docstring that Interval.get_indexer using any method other than default are not yet supported
| https://api.github.com/repos/pandas-dev/pandas/pulls/26519 | 2019-05-25T01:58:28Z | 2019-05-30T01:27:47Z | 2019-05-30T01:27:47Z | 2019-05-30T01:28:19Z |
Fix type annotations in pandas.core.indexes.period | diff --git a/mypy.ini b/mypy.ini
index 3df8fd13a2a75..eea6a3b551677 100644
--- a/mypy.ini
+++ b/mypy.ini
@@ -7,6 +7,3 @@ ignore_errors=True
[mypy-pandas.core.indexes.datetimelike]
ignore_errors=True
-
-[mypy-pandas.core.indexes.period]
-ignore_errors=True
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 044951ceda502..64272431cf703 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -80,7 +80,7 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
Parameters
----------
- data : array-like (1-dimensional), optional
+ data : array-like (1d integer np.ndarray or PeriodArray), optional
Optional period-like data to construct index with
copy : bool
Make a copy of input ndarray
@@ -168,7 +168,7 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
_is_numeric_dtype = False
_infer_as_myclass = True
- _data = None # type: PeriodArray
+ _data = None
_engine_type = libindex.PeriodEngine
| - [x] closes #26517
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/26518 | 2019-05-25T00:10:42Z | 2019-05-29T12:40:41Z | 2019-05-29T12:40:40Z | 2019-05-29T16:44:54Z |
MAINT: port numpy#13188 for np_datetime simplification | diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime.c b/pandas/_libs/tslibs/src/datetime/np_datetime.c
index 87866d804503e..a8a47e2e90f93 100644
--- a/pandas/_libs/tslibs/src/datetime/np_datetime.c
+++ b/pandas/_libs/tslibs/src/datetime/np_datetime.c
@@ -498,6 +498,27 @@ npy_datetime npy_datetimestruct_to_datetime(NPY_DATETIMEUNIT base,
return ret;
}
+/*
+ * Port numpy#13188 https://github.com/numpy/numpy/pull/13188/
+ *
+ * Computes the python `ret, d = divmod(d, unit)`.
+ *
+ * Note that GCC is smart enough at -O2 to eliminate the `if(*d < 0)` branch
+ * for subsequent calls to this command - it is able to deduce that `*d >= 0`.
+ */
+npy_int64 extract_unit(npy_datetime *d, npy_datetime unit) {
+ assert(unit > 0);
+ npy_int64 div = *d / unit;
+ npy_int64 mod = *d % unit;
+ if (mod < 0) {
+ mod += unit;
+ div -= 1;
+ }
+ assert(mod >= 0);
+ *d = mod;
+ return div;
+}
+
/*
* Converts a datetime based on the given metadata into a datetimestruct
*/
@@ -522,13 +543,8 @@ void pandas_datetime_to_datetimestruct(npy_datetime dt,
break;
case NPY_FR_M:
- if (dt >= 0) {
- out->year = 1970 + dt / 12;
- out->month = dt % 12 + 1;
- } else {
- out->year = 1969 + (dt + 1) / 12;
- out->month = 12 + (dt + 1) % 12;
- }
+ out->year = 1970 + extract_unit(&dt, 12);
+ out->month = dt + 1;
break;
case NPY_FR_W:
@@ -543,167 +559,105 @@ void pandas_datetime_to_datetimestruct(npy_datetime dt,
case NPY_FR_h:
perday = 24LL;
- if (dt >= 0) {
- set_datetimestruct_days(dt / perday, out);
- dt = dt % perday;
- } else {
- set_datetimestruct_days(
- dt / perday - (dt % perday == 0 ? 0 : 1), out);
- dt = (perday - 1) + (dt + 1) % perday;
- }
+ set_datetimestruct_days(extract_unit(&dt, perday), out);
out->hour = dt;
break;
case NPY_FR_m:
perday = 24LL * 60;
- if (dt >= 0) {
- set_datetimestruct_days(dt / perday, out);
- dt = dt % perday;
- } else {
- set_datetimestruct_days(
- dt / perday - (dt % perday == 0 ? 0 : 1), out);
- dt = (perday - 1) + (dt + 1) % perday;
- }
- out->hour = dt / 60;
- out->min = dt % 60;
+ set_datetimestruct_days(extract_unit(&dt, perday), out);
+ out->hour = (int)extract_unit(&dt, 60);
+ out->min = (int)dt;
break;
case NPY_FR_s:
perday = 24LL * 60 * 60;
- if (dt >= 0) {
- set_datetimestruct_days(dt / perday, out);
- dt = dt % perday;
- } else {
- set_datetimestruct_days(
- dt / perday - (dt % perday == 0 ? 0 : 1), out);
- dt = (perday - 1) + (dt + 1) % perday;
- }
- out->hour = dt / (60 * 60);
- out->min = (dt / 60) % 60;
- out->sec = dt % 60;
+ set_datetimestruct_days(extract_unit(&dt, perday), out);
+ out->hour = (int)extract_unit(&dt, 60 * 60);
+ out->min = (int)extract_unit(&dt, 60);
+ out->sec = (int)dt;
break;
case NPY_FR_ms:
perday = 24LL * 60 * 60 * 1000;
- if (dt >= 0) {
- set_datetimestruct_days(dt / perday, out);
- dt = dt % perday;
- } else {
- set_datetimestruct_days(
- dt / perday - (dt % perday == 0 ? 0 : 1), out);
- dt = (perday - 1) + (dt + 1) % perday;
- }
- out->hour = dt / (60 * 60 * 1000LL);
- out->min = (dt / (60 * 1000LL)) % 60;
- out->sec = (dt / 1000LL) % 60;
- out->us = (dt % 1000LL) * 1000;
+ set_datetimestruct_days(extract_unit(&dt, perday), out);
+ out->hour = (int)extract_unit(&dt, 1000LL * 60 * 60);
+ out->min = (int)extract_unit(&dt, 1000LL * 60);
+ out->sec = (int)extract_unit(&dt, 1000LL);
+ out->us = (int)(dt * 1000);
break;
case NPY_FR_us:
perday = 24LL * 60LL * 60LL * 1000LL * 1000LL;
- if (dt >= 0) {
- set_datetimestruct_days(dt / perday, out);
- dt = dt % perday;
- } else {
- set_datetimestruct_days(
- dt / perday - (dt % perday == 0 ? 0 : 1), out);
- dt = (perday - 1) + (dt + 1) % perday;
- }
- out->hour = dt / (60 * 60 * 1000000LL);
- out->min = (dt / (60 * 1000000LL)) % 60;
- out->sec = (dt / 1000000LL) % 60;
- out->us = dt % 1000000LL;
+ set_datetimestruct_days(extract_unit(&dt, perday), out);
+ out->hour = (int)extract_unit(&dt, 1000LL * 1000 * 60 * 60);
+ out->min = (int)extract_unit(&dt, 1000LL * 1000 * 60);
+ out->sec = (int)extract_unit(&dt, 1000LL * 1000);
+ out->us = (int)dt;
break;
case NPY_FR_ns:
perday = 24LL * 60LL * 60LL * 1000LL * 1000LL * 1000LL;
- if (dt >= 0) {
- set_datetimestruct_days(dt / perday, out);
- dt = dt % perday;
- } else {
- set_datetimestruct_days(
- dt / perday - (dt % perday == 0 ? 0 : 1), out);
- dt = (perday - 1) + (dt + 1) % perday;
- }
- out->hour = dt / (60 * 60 * 1000000000LL);
- out->min = (dt / (60 * 1000000000LL)) % 60;
- out->sec = (dt / 1000000000LL) % 60;
- out->us = (dt / 1000LL) % 1000000LL;
- out->ps = (dt % 1000LL) * 1000;
+ set_datetimestruct_days(extract_unit(&dt, perday), out);
+ out->hour = (int)extract_unit(&dt, 1000LL * 1000 * 1000 * 60 * 60);
+ out->min = (int)extract_unit(&dt, 1000LL * 1000 * 1000 * 60);
+ out->sec = (int)extract_unit(&dt, 1000LL * 1000 * 1000);
+ out->us = (int)extract_unit(&dt, 1000LL);
+ out->ps = (int)(dt * 1000);
break;
case NPY_FR_ps:
perday = 24LL * 60 * 60 * 1000 * 1000 * 1000 * 1000;
- if (dt >= 0) {
- set_datetimestruct_days(dt / perday, out);
- dt = dt % perday;
- } else {
- set_datetimestruct_days(
- dt / perday - (dt % perday == 0 ? 0 : 1), out);
- dt = (perday - 1) + (dt + 1) % perday;
- }
- out->hour = dt / (60 * 60 * 1000000000000LL);
- out->min = (dt / (60 * 1000000000000LL)) % 60;
- out->sec = (dt / 1000000000000LL) % 60;
- out->us = (dt / 1000000LL) % 1000000LL;
- out->ps = dt % 1000000LL;
+ set_datetimestruct_days(extract_unit(&dt, perday), out);
+ out->hour = (int)extract_unit(&dt, 1000LL * 1000 * 1000 * 60 * 60);
+ out->min = (int)extract_unit(&dt, 1000LL * 1000 * 1000 * 60);
+ out->sec = (int)extract_unit(&dt, 1000LL * 1000 * 1000);
+ out->us = (int)extract_unit(&dt, 1000LL);
+ out->ps = (int)(dt * 1000);
break;
case NPY_FR_fs:
/* entire range is only +- 2.6 hours */
- if (dt >= 0) {
- out->hour = dt / (60 * 60 * 1000000000000000LL);
- out->min = (dt / (60 * 1000000000000000LL)) % 60;
- out->sec = (dt / 1000000000000000LL) % 60;
- out->us = (dt / 1000000000LL) % 1000000LL;
- out->ps = (dt / 1000LL) % 1000000LL;
- out->as = (dt % 1000LL) * 1000;
- } else {
- npy_datetime minutes;
-
- minutes = dt / (60 * 1000000000000000LL);
- dt = dt % (60 * 1000000000000000LL);
- if (dt < 0) {
- dt += (60 * 1000000000000000LL);
- --minutes;
- }
- /* Offset the negative minutes */
- add_minutes_to_datetimestruct(out, minutes);
- out->sec = (dt / 1000000000000000LL) % 60;
- out->us = (dt / 1000000000LL) % 1000000LL;
- out->ps = (dt / 1000LL) % 1000000LL;
- out->as = (dt % 1000LL) * 1000;
+ out->hour = (int)extract_unit(&dt, 1000LL * 1000 * 1000 * 1000 *
+ 1000 * 60 * 60);
+ if (out->hour < 0) {
+ out->year = 1969;
+ out->month = 12;
+ out->day = 31;
+ out->hour += 24;
+ assert(out->hour >= 0);
}
+ out->min = (int)extract_unit(&dt, 1000LL * 1000 * 1000 * 1000 *
+ 1000 * 60);
+ out->sec = (int)extract_unit(&dt, 1000LL * 1000 * 1000 * 1000 *
+ 1000);
+ out->us = (int)extract_unit(&dt, 1000LL * 1000 * 1000);
+ out->ps = (int)extract_unit(&dt, 1000LL);
+ out->as = (int)(dt * 1000);
break;
case NPY_FR_as:
/* entire range is only +- 9.2 seconds */
- if (dt >= 0) {
- out->sec = (dt / 1000000000000000000LL) % 60;
- out->us = (dt / 1000000000000LL) % 1000000LL;
- out->ps = (dt / 1000000LL) % 1000000LL;
- out->as = dt % 1000000LL;
- } else {
- npy_datetime seconds;
-
- seconds = dt / 1000000000000000000LL;
- dt = dt % 1000000000000000000LL;
- if (dt < 0) {
- dt += 1000000000000000000LL;
- --seconds;
- }
- /* Offset the negative seconds */
- add_seconds_to_datetimestruct(out, seconds);
- out->us = (dt / 1000000000000LL) % 1000000LL;
- out->ps = (dt / 1000000LL) % 1000000LL;
- out->as = dt % 1000000LL;
+ out->sec = (int)extract_unit(&dt, 1000LL * 1000 * 1000 * 1000 *
+ 1000 * 1000);
+ if (out->sec < 0) {
+ out->year = 1969;
+ out->month = 12;
+ out->day = 31;
+ out->hour = 23;
+ out->min = 59;
+ out->sec += 60;
+ assert(out->sec >= 0);
}
+ out->us = (int)extract_unit(&dt, 1000LL * 1000 * 1000 * 1000);
+ out->ps = (int)extract_unit(&dt, 1000LL * 1000);
+ out->as = (int)dt;
break;
default:
| Bring numpy changes about emulating the behavior of python's divmod to
pandas.
- [x] closes #26500
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/26516 | 2019-05-24T21:43:24Z | 2019-05-26T17:57:48Z | 2019-05-26T17:57:48Z | 2019-05-26T17:57:59Z |
BUG: fix categorical comparison with missing values (#26504 ) | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 89a9da4a73b35..6604199930bc5 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -414,7 +414,7 @@ Categorical
^^^^^^^^^^^
- Bug in :func:`DataFrame.at` and :func:`Series.at` that would raise exception if the index was a :class:`CategoricalIndex` (:issue:`20629`)
--
+- Fixed bug in comparison of ordered :class:`Categorical` that contained missing values with a scalar which sometimes incorrectly resulted in True (:issue:`26504`)
-
Datetimelike
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 89b86c66d7b05..44bb44457bc25 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -89,18 +89,23 @@ def f(self, other):
else:
other_codes = other._codes
- na_mask = (self._codes == -1) | (other_codes == -1)
+ mask = (self._codes == -1) | (other_codes == -1)
f = getattr(self._codes, op)
ret = f(other_codes)
- if na_mask.any():
+ if mask.any():
# In other series, the leads to False, so do that here too
- ret[na_mask] = False
+ ret[mask] = False
return ret
if is_scalar(other):
if other in self.categories:
i = self.categories.get_loc(other)
- return getattr(self._codes, op)(i)
+ ret = getattr(self._codes, op)(i)
+
+ # check for NaN in self
+ mask = (self._codes == -1)
+ ret[mask] = False
+ return ret
else:
if op == '__eq__':
return np.repeat(False, len(self))
diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py
index dc6e1a5bc36b3..a443408bf9479 100644
--- a/pandas/tests/arrays/categorical/test_operators.py
+++ b/pandas/tests/arrays/categorical/test_operators.py
@@ -1,4 +1,5 @@
import operator
+import warnings
import numpy as np
import pytest
@@ -17,7 +18,6 @@ def test_categories_none_comparisons(self):
tm.assert_categorical_equal(factor, self.factor)
def test_comparisons(self):
-
result = self.factor[self.factor == 'a']
expected = self.factor[np.asarray(self.factor) == 'a']
tm.assert_categorical_equal(result, expected)
@@ -186,6 +186,36 @@ def test_comparison_with_unknown_scalars(self):
tm.assert_numpy_array_equal(cat != 4,
np.array([True, True, True]))
+ def test_comparison_of_ordered_categorical_with_nan_to_scalar(
+ self, compare_operators_no_eq_ne):
+ # https://github.com/pandas-dev/pandas/issues/26504
+ # BUG: fix ordered categorical comparison with missing values (#26504 )
+ # and following comparisons with scalars in categories with missing
+ # values should be evaluated as False
+
+ cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
+ scalar = 2
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", RuntimeWarning)
+ expected = getattr(np.array(cat),
+ compare_operators_no_eq_ne)(scalar)
+ actual = getattr(cat, compare_operators_no_eq_ne)(scalar)
+ tm.assert_numpy_array_equal(actual, expected)
+
+ def test_comparison_of_ordered_categorical_with_nan_to_listlike(
+ self, compare_operators_no_eq_ne):
+ # https://github.com/pandas-dev/pandas/issues/26504
+ # and following comparisons of missing values in ordered Categorical
+ # with listlike should be evaluated as False
+
+ cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
+ other = Categorical([2, 2, 2, 2], categories=[1, 2, 3], ordered=True)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", RuntimeWarning)
+ expected = getattr(np.array(cat), compare_operators_no_eq_ne)(2)
+ actual = getattr(cat, compare_operators_no_eq_ne)(other)
+ tm.assert_numpy_array_equal(actual, expected)
+
@pytest.mark.parametrize('data,reverse,base', [
(list("abc"), list("cba"), list("bbb")),
([1, 2, 3], [3, 2, 1], [2, 2, 2])]
| - [x] closes #26504
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
This PR fixes issues comparison of ordered categorical with missing values evaluates to True(#26504 ). Now making comparison with missing values always gives False. The missing values could be introduced when constructing a Categorical with values that don't fall in with the categories provided. | https://api.github.com/repos/pandas-dev/pandas/pulls/26514 | 2019-05-24T19:31:13Z | 2019-06-01T14:51:27Z | 2019-06-01T14:51:27Z | 2019-06-01T14:51:33Z |
CLN: Remove StringMixin from PandasObject | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 1fff30525853d..483091c939d0c 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -213,6 +213,20 @@ are returned. (:issue:`21521`)
df.groupby("a").ffill()
+``__str__`` methods now call ``__repr__`` rather than vica-versa
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Pandas has until now mostly defined string representations in a Pandas objects's
+``__str__``/``__unicode__``/``__bytes__`` methods, and called ``__str__`` from the ``__repr__``
+method, if a specific ``__repr__`` method is not found. This is not needed for Python3.
+In Pandas 0.25, the string representations of Pandas objects are now generally
+defined in ``__repr__``, and calls to ``__str__`` in general now pass the call on to
+the ``__repr__``, if a specific ``__str__`` method doesn't exist, as is standard for Python.
+This change is backward compatible for direct usage of Pandas, but if you subclass
+Pandas objects *and* give your subclasses specific ``__str__``/``__repr__`` methods,
+you may have to adjust your ``__str__``/``__repr__`` methods (:issue:`26495`).
+
+
.. _whatsnew_0250.api_breaking.deps:
Increased minimum versions for dependencies
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index d25ccd1b158be..0fa705369908a 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -2022,7 +2022,7 @@ def _get_repr(self, length=True, na_rep='NaN', footer=True):
result = formatter.to_string()
return str(result)
- def __str__(self):
+ def __repr__(self):
"""
String representation.
"""
@@ -2037,10 +2037,6 @@ def __str__(self):
return result
- def __repr__(self):
- # We want to bypass the ExtensionArray.__repr__
- return str(self)
-
def _maybe_coerce_indexer(self, indexer):
"""
return an indexer coerced to the codes dtype
diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py
index 7a66e0ff33cc7..b0236cb393c1c 100644
--- a/pandas/core/arrays/sparse.py
+++ b/pandas/core/arrays/sparse.py
@@ -1831,7 +1831,7 @@ def _add_comparison_ops(cls):
# ----------
# Formatting
# -----------
- def __str__(self):
+ def __repr__(self):
return '{self}\nFill: {fill}\n{index}'.format(
self=printing.pprint_thing(self),
fill=printing.pprint_thing(self.fill_value),
diff --git a/pandas/core/base.py b/pandas/core/base.py
index f7837c60c0b82..3f59871fb5b38 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -55,7 +55,7 @@ def __repr__(self):
return str(self)
-class PandasObject(StringMixin, DirNamesMixin):
+class PandasObject(DirNamesMixin):
"""baseclass for various pandas objects"""
@@ -64,7 +64,7 @@ def _constructor(self):
"""class constructor (for this class it's just `__class__`"""
return self.__class__
- def __str__(self):
+ def __repr__(self):
"""
Return a string representation for a particular object.
"""
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 6bfa63012689d..e619cda453e0b 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -610,7 +610,7 @@ def _info_repr(self):
return info_repr_option and not (self._repr_fits_horizontal_() and
self._repr_fits_vertical_())
- def __str__(self):
+ def __repr__(self):
"""
Return a string representation for a particular DataFrame.
"""
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 623e2b4863029..76c73fc40977c 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2022,7 +2022,7 @@ def __setstate__(self, state):
# ----------------------------------------------------------------------
# Rendering Methods
- def __str__(self):
+ def __repr__(self):
# string representation based upon iterating over self
# (since, by definition, `PandasContainers` are iterable)
prepr = '[%s]' % ','.join(map(pprint_thing, self))
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 4e9e3b4963b6d..aa04b7505afe4 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -373,8 +373,8 @@ def __init__(self, obj, keys=None, axis=0, level=None,
def __len__(self):
return len(self.groups)
- def __str__(self):
- # TODO: Better str/repr for GroupBy object
+ def __repr__(self):
+ # TODO: Better repr for GroupBy object
return object.__repr__(self)
def _assure_grouper(self):
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index eff7ff2c9f347..a4544e79e2dfa 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -932,7 +932,7 @@ def __deepcopy__(self, memo=None):
# --------------------------------------------------------------------
# Rendering Methods
- def __str__(self):
+ def __repr__(self):
"""
Return a string representation for this object.
"""
diff --git a/pandas/core/indexes/frozen.py b/pandas/core/indexes/frozen.py
index 60e4253e3101b..aeb0fa119ab33 100644
--- a/pandas/core/indexes/frozen.py
+++ b/pandas/core/indexes/frozen.py
@@ -149,7 +149,7 @@ def values(self):
arr = self.view(np.ndarray).copy()
return arr
- def __str__(self):
+ def __repr__(self):
"""
Return a string representation for this object.
"""
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 0ac87c653cfff..f86ef40a97299 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -233,8 +233,7 @@ def make_block_same_class(self, values, placement=None, ndim=None,
return make_block(values, placement=placement, ndim=ndim,
klass=self.__class__, dtype=dtype)
- def __str__(self):
-
+ def __repr__(self):
# don't want to print out all of the items here
name = pprint_thing(self.__class__.__name__)
if self._is_single_block:
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 96a672b60da70..0b63588c9f5d9 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -291,7 +291,7 @@ def _post_setstate(self):
def __len__(self):
return len(self.items)
- def __str__(self):
+ def __repr__(self):
output = pprint_thing(self.__class__.__name__)
for i, ax in enumerate(self.axes):
if i == 0:
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index b6b957c543df6..c65a73bd0d3f0 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -340,7 +340,7 @@ def _compare_constructor(self, other, func):
# ----------------------------------------------------------------------
# Magic methods
- def __str__(self):
+ def __repr__(self):
"""
Return a string representation for a particular Panel.
"""
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 5b59fd6e7b38d..55b5bdcbf53f4 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1384,7 +1384,7 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False):
# ----------------------------------------------------------------------
# Rendering Methods
- def __str__(self):
+ def __repr__(self):
"""
Return a string representation for a particular Series.
"""
diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py
index ae1c94e136475..eac59e2c0f5eb 100644
--- a/pandas/core/sparse/series.py
+++ b/pandas/core/sparse/series.py
@@ -217,9 +217,8 @@ def as_sparse_array(self, kind=None, fill_value=None, copy=False):
return SparseArray(self.values, sparse_index=self.sp_index,
fill_value=fill_value, kind=kind, copy=copy)
- def __str__(self):
- # currently, unicode is same as repr...fixes infinite loop
- series_rep = Series.__str__(self)
+ def __repr__(self):
+ series_rep = Series.__repr__(self)
rep = '{series}\n{index!r}'.format(series=series_rep,
index=self.sp_index)
return rep
diff --git a/pandas/core/window.py b/pandas/core/window.py
index deb64f1fb089d..d51e12035c829 100644
--- a/pandas/core/window.py
+++ b/pandas/core/window.py
@@ -157,7 +157,7 @@ def _get_window(self, other=None):
def _window_type(self):
return self.__class__.__name__
- def __str__(self):
+ def __repr__(self):
"""
Provide a nice str repr of our rolling object.
"""
| - [x] closes #26495
- [ ] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Addresses #26495. In addition to the use of StringMixin in PandasObject, StringMixin is also used in core.computation and the io.pytables. I'd like to tackle those in a different PR, as there is some funkyness there (calls that depend on frame depth etc.)
| https://api.github.com/repos/pandas-dev/pandas/pulls/26505 | 2019-05-23T16:36:03Z | 2019-05-24T15:29:33Z | 2019-05-24T15:29:33Z | 2019-05-25T07:32:31Z |
DOC: fix SyntaxError in doc build on Windows | diff --git a/doc/source/conf.py b/doc/source/conf.py
index e7d358c7961ab..971aa04ba866a 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -319,7 +319,7 @@
pd.options.display.max_rows = 15
import os
- os.chdir('{}')
+ os.chdir(r'{}')
""".format(os.path.dirname(os.path.dirname(__file__)))
| i'm getting this error for most files during doc build on Windows...
```
>>>-------------------------------------------------------------------------
Exception in C:\Users\simon\OneDrive\code\pandas-simonjayhawkins\doc\source\development\contributing.rst at block ending on line None
Specify :okexcept: as an option in the ipython:: block to suppress this message
File "<ipython-input-1-9cb881b1c9b0>", line 1
os.chdir('C:\Users\simon\OneDrive\code\pandas-simonjayhawkins\doc')
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
<<<-------------------------------------------------------------------------
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/26499 | 2019-05-22T22:46:53Z | 2019-05-23T13:04:57Z | 2019-05-23T13:04:57Z | 2019-05-24T06:32:59Z |
DOC: Fixed redirects in various parts of the documentation | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index d25ccd1b158be..230602612ac66 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -272,7 +272,8 @@ class Categorical(ExtensionArray, PandasObject):
Notes
-----
See the `user guide
- <http://pandas.pydata.org/pandas-docs/stable/categorical.html>`_ for more.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html>`_
+ for more.
Examples
--------
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 94b9dc8ebab55..4f628eff43167 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -95,7 +95,7 @@
Notes
-----
See the `user guide
-<http://pandas.pydata.org/pandas-docs/stable/advanced.html#intervalindex>`_
+<http://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#intervalindex>`_
for more.
%(examples)s\
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py
index f8488b7a153e3..b22ed45642cf6 100644
--- a/pandas/core/dtypes/concat.py
+++ b/pandas/core/dtypes/concat.py
@@ -244,7 +244,7 @@ def union_categoricals(to_union, sort_categories=False, ignore_order=False):
-----
To learn more about categories, see `link
- <http://pandas.pydata.org/pandas-docs/stable/categorical.html#unioning>`__
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#unioning>`__
Examples
--------
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 623e2b4863029..bf3f89c8cab45 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3328,8 +3328,8 @@ def _check_setitem_copy(self, stacklevel=4, t='setting', force=False):
"A value is trying to be set on a copy of a slice from a "
"DataFrame\n\n"
"See the caveats in the documentation: "
- "http://pandas.pydata.org/pandas-docs/stable/"
- "indexing.html#indexing-view-versus-copy"
+ "http://pandas.pydata.org/pandas-docs/stable/user_guide/"
+ "indexing.html#returning-a-view-versus-a-copy"
)
else:
@@ -3338,8 +3338,8 @@ def _check_setitem_copy(self, stacklevel=4, t='setting', force=False):
"DataFrame.\n"
"Try using .loc[row_indexer,col_indexer] = value "
"instead\n\nSee the caveats in the documentation: "
- "http://pandas.pydata.org/pandas-docs/stable/"
- "indexing.html#indexing-view-versus-copy"
+ "http://pandas.pydata.org/pandas-docs/stable/user_guide/"
+ "indexing.html#returning-a-view-versus-a-copy"
)
if value == 'raise':
@@ -7762,7 +7762,7 @@ def asfreq(self, freq, method=None, how=None, normalize=False,
Notes
-----
To learn more about the frequency strings, please see `this link
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
Examples
--------
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 4e9e3b4963b6d..8640a837beacb 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -218,7 +218,7 @@ class providing the base-class of operations.
Notes
-----
See more `here
-<http://pandas.pydata.org/pandas-docs/stable/groupby.html#piping-function-calls>`_
+<http://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#piping-function-calls>`_
Examples
--------
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py
index 04d407ebc670d..febfdc7bdf908 100644
--- a/pandas/core/groupby/grouper.py
+++ b/pandas/core/groupby/grouper.py
@@ -49,7 +49,7 @@ class Grouper:
This will groupby the specified frequency if the target selection
(via key or level) is a datetime-like object. For full specification
of available frequencies, please see `here
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`_.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`_.
axis : number/name of the axis, defaults to 0
sort : boolean, default to False
whether to sort the resulting labels
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 7fd537fb9989a..c769b6a09b6ef 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -215,7 +215,7 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):
Notes
-----
To learn more about the frequency strings, please see `this link
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
Creating a DatetimeIndex based on `start`, `periods`, and `end` has
been deprecated in favor of :func:`date_range`.
@@ -1375,7 +1375,7 @@ def date_range(start=None, end=None, periods=None, freq=None, tz=None,
``start`` and ``end`` (closed on both sides).
To learn more about the frequency strings, please see `this link
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
Examples
--------
@@ -1531,7 +1531,7 @@ def bdate_range(start=None, end=None, periods=None, freq='B', tz=None,
desired.
To learn more about the frequency strings, please see `this link
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
Examples
--------
@@ -1603,7 +1603,7 @@ def cdate_range(start=None, end=None, periods=None, freq='C', tz=None,
must be specified.
To learn more about the frequency strings, please see `this link
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
Returns
-------
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 87216dcc7b957..44e1efbafcef3 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -1190,7 +1190,7 @@ def interval_range(start=None, end=None, periods=None, freq=None,
``start`` and ``end``, inclusively.
To learn more about datetime-like frequency strings, please see `this link
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
Examples
--------
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index f1553d9db835f..ec2cc70d1a352 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -182,7 +182,8 @@ class MultiIndex(Index):
Notes
-----
See the `user guide
- <http://pandas.pydata.org/pandas-docs/stable/advanced.html>`_ for more.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html>`_
+ for more.
Examples
--------
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 044951ceda502..c041431f7aee7 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -939,7 +939,7 @@ def period_range(start=None, end=None, periods=None, freq=None, name=None):
must be specified.
To learn more about the frequency strings, please see `this link
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
Examples
--------
diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index 6ae17e62b49c6..0574a4b41c920 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -141,7 +141,7 @@ class TimedeltaIndex(DatetimeIndexOpsMixin, dtl.TimelikeOps, Int64Index,
Notes
-----
To learn more about the frequency strings, please see `this link
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
Creating a TimedeltaIndex based on `start`, `periods`, and `end` has
been deprecated in favor of :func:`timedelta_range`.
@@ -730,7 +730,7 @@ def timedelta_range(start=None, end=None, periods=None, freq=None,
``start`` and ``end`` (closed on both sides).
To learn more about the frequency strings, please see `this link
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
Examples
--------
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 3c7a286c8a4f8..49fe588363126 100755
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1266,7 +1266,7 @@ def _validate_read_indexer(self, key, indexer, axis, raise_missing=False):
KeyError in the future, you can use .reindex() as an alternative.
See the documentation here:
- https://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike""") # noqa
+ https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike""") # noqa
if not (ax.is_categorical() or ax.is_interval()):
warnings.warn(_missing_key_warning,
@@ -1415,7 +1415,7 @@ class _IXIndexer(_NDFrameIndexer):
.iloc for positional indexing
See the documentation here:
- http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated""") # noqa
+ http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#ix-indexer-is-deprecated""") # noqa
def __init__(self, name, obj):
warnings.warn(self._ix_deprecation_warning,
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index ee3ed3899a55f..4523a6ad48f19 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -100,7 +100,7 @@ def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
A walkthrough of how this method fits in with other tools for combining
pandas objects can be found `here
- <http://pandas.pydata.org/pandas-docs/stable/merging.html>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html>`__.
Examples
--------
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 817d539d4ad6f..0756bdb3777ec 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -533,7 +533,7 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False,
dtype: datetime64[ns]
If a date does not meet the `timestamp limitations
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html
#timeseries-timestamp-limits>`_, passing errors='ignore'
will return the original input instead of raising any exception.
diff --git a/pandas/core/window.py b/pandas/core/window.py
index deb64f1fb089d..62fcbe91ae4fb 100644
--- a/pandas/core/window.py
+++ b/pandas/core/window.py
@@ -462,7 +462,7 @@ class Window(_Window):
See the notes below for further information.
on : str, optional
For a DataFrame, column on which to calculate
- the rolling window, rather than the index
+ the rolling window, rather than the index.
axis : int or str, default 0
closed : str, default None
Make the interval closed on the 'right', 'left', 'both' or
@@ -488,7 +488,7 @@ class Window(_Window):
changed to the center of the window by setting ``center=True``.
To learn more about the offsets & frequency strings, please see `this link
- <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.
The recognized win_types are:
@@ -2188,7 +2188,7 @@ class EWM(_Rolling):
(if adjust is True), and 1-alpha and alpha (if adjust is False).
More details can be found at
- http://pandas.pydata.org/pandas-docs/stable/computation.html#exponentially-weighted-windows
+ http://pandas.pydata.org/pandas-docs/stable/user_guide/computation.html#exponentially-weighted-windows
Examples
--------
diff --git a/pandas/io/json/json.py b/pandas/io/json/json.py
index ee9d9e000d7e3..20bed9bff7383 100644
--- a/pandas/io/json/json.py
+++ b/pandas/io/json/json.py
@@ -330,8 +330,8 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=None,
chunksize : integer, default None
Return JsonReader object for iteration.
- See the `line-delimted json docs
- <http://pandas.pydata.org/pandas-docs/stable/io.html#io-jsonl>`_
+ See the `line-delimited json docs
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#line-delimited-json>`_
for more information on ``chunksize``.
This can only be passed if `lines=True`.
If this is None, the file will be read into memory all at once.
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index c65c11e840c27..bcbdd80865360 100755
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -58,7 +58,7 @@
into chunks.
Additional help can be found in the online docs for
-`IO Tools <http://pandas.pydata.org/pandas-docs/stable/io.html>`_.
+`IO Tools <http://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_.
Parameters
----------
@@ -753,7 +753,7 @@ def read_fwf(filepath_or_buffer: FilePathOrBuffer,
into chunks.
Additional help can be found in the `online docs for IO Tools
- <http://pandas.pydata.org/pandas-docs/stable/io.html>`_.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_.
Parameters
----------
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 0f7f6fe399256..74f2f9f7fdc00 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -868,8 +868,8 @@ def put(self, key, value, format=None, append=False, **kwargs):
This will force Table format, append the input data to the
existing.
data_columns : list of columns to create as data columns, or True to
- use all columns. See
- `here <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__ # noqa
+ use all columns. See `here
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#query-via-data-columns>`__.
encoding : default None, provide an encoding for strings
dropna : boolean, default False, do not write an ALL nan row to
the store settable by the option 'io.hdf.dropna_table'
@@ -950,7 +950,7 @@ def append(self, key, value, format=None, append=True, columns=None,
List of columns to create as indexed data columns for on-disk
queries, or True to use all columns. By default only the axes
of the object are indexed. See `here
- <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__.
+ <http://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#query-via-data-columns>`__.
min_itemsize : dict of columns that specify minimum string sizes
nan_rep : string to use as string nan represenation
chunksize : size to chunk the writing
| Links in the docs to part way down a page were being sent to the top of the page due to a generic redirect from pandas.pydata.org/pandas-doc/stable/... -> pandas.pydata.org/pandas-doc/stable/user_guide/... . These links have been change to go straight to the .../user_guide/... version of the page to ensure the link goes to the correct part of the docs.
For example, the link within the `chunksize` parameter of pandas.read_json() currently goes to the top of the IO Tools page, when the relevant section is the 'Line delimited json' heading about half way down. | https://api.github.com/repos/pandas-dev/pandas/pulls/26497 | 2019-05-22T21:00:45Z | 2019-05-31T12:41:11Z | 2019-05-31T12:41:11Z | 2019-06-03T19:32:49Z |
DOC: Highlighted role of index alignment in DataFrame.dot(other) (#26… | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 6bfa63012689d..7d501e8095921 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -944,7 +944,9 @@ def dot(self, other):
Notes
-----
The dimensions of DataFrame and other must be compatible in order to
- compute the matrix multiplication.
+ compute the matrix multiplication. In addition, the column names of
+ DataFrame and the index of other must contain the same values, as they
+ will be aligned prior to the multiplication.
The dot method for Series computes the inner product, instead of the
matrix product here.
@@ -982,6 +984,14 @@ def dot(self, other):
0 1
0 1 4
1 2 2
+
+ Note how shuffling of the objects does not change the result.
+
+ >>> s2 = s.reindex([1, 0, 2, 3])
+ >>> df.dot(s2)
+ 0 -4
+ 1 5
+ dtype: int64
"""
if isinstance(other, (Series, DataFrame)):
common = self.columns.union(other.index)
| …480)
- [X] closes #26480
- [X] tests passed
Added note highlighting that column names of DataFrame and index of other need to same.
Added example showing that reshuffling of objects does not change which elements are multiplied with which. | https://api.github.com/repos/pandas-dev/pandas/pulls/26496 | 2019-05-22T20:45:53Z | 2019-05-23T16:46:21Z | 2019-05-23T16:46:20Z | 2019-05-25T12:56:50Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.