title stringlengths 1 185 | diff stringlengths 0 32.2M | body stringlengths 0 123k β | url stringlengths 57 58 | created_at stringlengths 20 20 | closed_at stringlengths 20 20 | merged_at stringlengths 20 20 β | updated_at stringlengths 20 20 |
|---|---|---|---|---|---|---|---|
BUG: Don't supply name to Series when using 'size' with agg/apply | diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 00b49c2f4f951..9ec0f7dca3b84 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -842,7 +842,7 @@ def apply_str(self) -> FrameOrSeriesUnion:
# Special-cased because DataFrame.size returns a single scalar
obj = self.obj
value = obj.shape[self.axis]
- return obj._constructor_sliced(value, index=self.agg_axis, name="size")
+ return obj._constructor_sliced(value, index=self.agg_axis)
return super().apply_str()
diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py
index 2511f6fc2563c..14266a2c29a7f 100644
--- a/pandas/tests/apply/test_frame_apply.py
+++ b/pandas/tests/apply/test_frame_apply.py
@@ -1279,9 +1279,9 @@ def test_size_as_str(how, axis):
# on the columns
result = getattr(df, how)("size", axis=axis)
if axis == 0 or axis == "index":
- expected = Series(df.shape[0], index=df.columns, name="size")
+ expected = Series(df.shape[0], index=df.columns)
else:
- expected = Series(df.shape[1], index=df.index, name="size")
+ expected = Series(df.shape[1], index=df.index)
tm.assert_series_equal(result, expected)
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
Ref: https://github.com/pandas-dev/pandas/pull/39935#discussion_r651989373
Doing e.g.
print(DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}).apply('sum'))
print(DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}).agg('sum'))
produce a Series with `name=None`. This was introduced in 1.3, so does not need a whatsnew. | https://api.github.com/repos/pandas-dev/pandas/pulls/42046 | 2021-06-16T02:12:25Z | 2021-06-16T11:09:06Z | 2021-06-16T11:09:06Z | 2021-06-16T11:40:22Z |
Backport PR #42030 on branch 1.3.x (Regression raising Error when having dup cols with single dtype for read csv) | diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index 7d7074988e5f0..e5e61e409c320 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -108,6 +108,7 @@ from pandas.core.dtypes.common import (
is_object_dtype,
)
from pandas.core.dtypes.dtypes import CategoricalDtype
+from pandas.core.dtypes.inference import is_dict_like
cdef:
float64_t INF = <float64_t>np.inf
@@ -689,6 +690,7 @@ cdef class TextReader:
count = counts.get(name, 0)
if (
self.dtype is not None
+ and is_dict_like(self.dtype)
and self.dtype.get(old_name) is not None
and self.dtype.get(name) is None
):
diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index 670868c6f4261..af25a4166d5a6 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -25,6 +25,7 @@
)
from pandas.core.dtypes.common import is_integer
+from pandas.core.dtypes.inference import is_dict_like
from pandas.io.parsers.base_parser import (
ParserBase,
@@ -424,6 +425,7 @@ def _infer_columns(self):
cur_count = counts[col]
if (
self.dtype is not None
+ and is_dict_like(self.dtype)
and self.dtype.get(old_col) is not None
and self.dtype.get(col) is None
):
diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
index 59fd3de60e0bf..bc20f1d1eea5f 100644
--- a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
+++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
@@ -248,3 +248,12 @@ def test_dtype_mangle_dup_cols(all_parsers, dtypes, exp_value):
result = parser.read_csv(StringIO(data), dtype={"a": str, **dtypes})
expected = DataFrame({"a": ["1"], "a.1": [exp_value]})
tm.assert_frame_equal(result, expected)
+
+
+def test_dtype_mangle_dup_cols_single_dtype(all_parsers):
+ # GH#42022
+ parser = all_parsers
+ data = """a,a\n1,1"""
+ result = parser.read_csv(StringIO(data), dtype=str)
+ expected = DataFrame({"a": ["1"], "a.1": ["1"]})
+ tm.assert_frame_equal(result, expected)
| Backport PR #42030: Regression raising Error when having dup cols with single dtype for read csv | https://api.github.com/repos/pandas-dev/pandas/pulls/42045 | 2021-06-16T01:46:13Z | 2021-06-16T08:02:39Z | 2021-06-16T08:02:39Z | 2021-06-16T08:02:39Z |
BUG: MultiIndex.reindex with level and EA dtype | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 166ea2f0d4164..9859f12a34621 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -167,7 +167,7 @@ Missing
MultiIndex
^^^^^^^^^^
--
+- Bug in :meth:`MultiIndex.reindex` when passing a ``level`` that corresponds to an ``ExtensionDtype`` level (:issue:`42043`)
-
I/O
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 02961bc98ec61..af5d704549c50 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -2503,9 +2503,7 @@ def reindex(
target = ibase.ensure_has_len(target)
if len(target) == 0 and not isinstance(target, Index):
idx = self.levels[level]
- attrs = idx._get_attributes_dict()
- attrs.pop("freq", None) # don't preserve freq
- target = type(idx)._simple_new(np.empty(0, dtype=idx.dtype), **attrs)
+ target = idx[:0]
else:
target = ensure_index(target)
target, indexer, _ = self._join_level(
diff --git a/pandas/tests/indexes/multi/test_reindex.py b/pandas/tests/indexes/multi/test_reindex.py
index 38ff6efec40c9..d9c77c5bdcd60 100644
--- a/pandas/tests/indexes/multi/test_reindex.py
+++ b/pandas/tests/indexes/multi/test_reindex.py
@@ -84,6 +84,13 @@ def test_reindex_lvl_preserves_type_if_target_is_empty_list_or_array():
assert idx.reindex([], level=0)[0].levels[0].dtype.type == np.int64
assert idx.reindex([], level=1)[0].levels[1].dtype.type == np.object_
+ # case with EA levels
+ cat = pd.Categorical(["foo", "bar"])
+ dti = pd.date_range("2016-01-01", periods=2, tz="US/Pacific")
+ mi = MultiIndex.from_product([cat, dti])
+ assert mi.reindex([], level=0)[0].levels[0].dtype == cat.dtype
+ assert mi.reindex([], level=1)[0].levels[1].dtype == dti.dtype
+
def test_reindex_base(idx):
idx = idx
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
Preliminary to a pretty nice de-duplication. | https://api.github.com/repos/pandas-dev/pandas/pulls/42043 | 2021-06-16T00:50:09Z | 2021-06-17T17:47:22Z | 2021-06-17T17:47:22Z | 2021-06-17T18:52:38Z |
REF: de-duplicate CategoricalIndex._get_indexer | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 4de95079f6480..69d53b04cf9f6 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -5167,6 +5167,7 @@ def set_value(self, arr, key, value):
def get_indexer_non_unique(self, target) -> tuple[np.ndarray, np.ndarray]:
# both returned ndarrays are np.intp
target = ensure_index(target)
+ target = self._maybe_cast_listlike_indexer(target)
if not self._should_compare(target) and not is_interval_dtype(self.dtype):
# IntervalIndex get special treatment bc numeric scalars can be
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 1bda05f3ce5df..2ebc39664ad60 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -12,17 +12,12 @@
from pandas._libs import index as libindex
from pandas._typing import (
- ArrayLike,
Dtype,
DtypeObj,
)
-from pandas.util._decorators import (
- Appender,
- doc,
-)
+from pandas.util._decorators import doc
from pandas.core.dtypes.common import (
- ensure_platform_int,
is_categorical_dtype,
is_scalar,
)
@@ -41,7 +36,6 @@
import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import (
Index,
- _index_shared_docs,
maybe_extract_name,
)
from pandas.core.indexes.extension import (
@@ -492,38 +486,9 @@ def _maybe_cast_indexer(self, key) -> int:
return -1
raise
- def _get_indexer(
- self,
- target: Index,
- method: str | None = None,
- limit: int | None = None,
- tolerance=None,
- ) -> np.ndarray:
- # returned ndarray is np.intp
-
- if self.equals(target):
- return np.arange(len(self), dtype="intp")
-
- return self._get_indexer_non_unique(target._values)[0]
-
- @Appender(_index_shared_docs["get_indexer_non_unique"] % _index_doc_kwargs)
- def get_indexer_non_unique(self, target) -> tuple[np.ndarray, np.ndarray]:
- # both returned ndarrays are np.intp
- target = ibase.ensure_index(target)
- return self._get_indexer_non_unique(target._values)
-
- def _get_indexer_non_unique(
- self, values: ArrayLike
- ) -> tuple[np.ndarray, np.ndarray]:
- # both returned ndarrays are np.intp
- """
- get_indexer_non_unique but after unrapping the target Index object.
- """
- # Note: we use engine.get_indexer_non_unique for get_indexer in addition
- # to get_indexer_non_unique because, even if `target` is unique, any
- # non-category entries in it will be encoded as -1 so `codes` may
- # not be unique.
-
+ def _maybe_cast_listlike_indexer(self, values) -> CategoricalIndex:
+ if isinstance(values, CategoricalIndex):
+ values = values._data
if isinstance(values, Categorical):
# Indexing on codes is more efficient if categories are the same,
# so we can apply some optimizations based on the degree of
@@ -532,9 +497,9 @@ def _get_indexer_non_unique(
codes = cat._codes
else:
codes = self.categories.get_indexer(values)
-
- indexer, missing = self._engine.get_indexer_non_unique(codes)
- return ensure_platform_int(indexer), ensure_platform_int(missing)
+ codes = codes.astype(self.codes.dtype, copy=False)
+ cat = self._data._from_backing_data(codes)
+ return type(self)._simple_new(cat)
# --------------------------------------------------------------------
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index df7fae0763c42..aeef37dfb9af6 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -45,6 +45,7 @@
from pandas.core.arrays import (
DatetimeArray,
+ ExtensionArray,
PeriodArray,
TimedeltaArray,
)
@@ -595,7 +596,12 @@ def _maybe_cast_listlike_indexer(self, keyarr):
try:
res = self._data._validate_listlike(keyarr, allow_object=True)
except (ValueError, TypeError):
- res = com.asarray_tuplesafe(keyarr)
+ if not isinstance(keyarr, ExtensionArray):
+ # e.g. we don't want to cast DTA to ndarray[object]
+ res = com.asarray_tuplesafe(keyarr)
+ # TODO: com.asarray_tuplesafe shouldn't cast e.g. DatetimeArray
+ else:
+ res = keyarr
return Index(res, dtype=res.dtype)
| https://api.github.com/repos/pandas-dev/pandas/pulls/42042 | 2021-06-16T00:45:10Z | 2021-06-16T13:09:51Z | 2021-06-16T13:09:51Z | 2021-06-16T14:10:41Z | |
Backport PR #41266 on branch 1.3.x (API: make `hide_columns` and `hide_index` have a consistent signature and function in `Styler`) | diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index c5aba539bd2dd..e4f0825d24828 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -31,7 +31,10 @@
from pandas.util._decorators import doc
import pandas as pd
-from pandas import RangeIndex
+from pandas import (
+ IndexSlice,
+ RangeIndex,
+)
from pandas.api.types import is_list_like
from pandas.core import generic
import pandas.core.common as com
@@ -682,7 +685,7 @@ def to_latex(
self.data.columns = RangeIndex(stop=len(self.data.columns))
numeric_cols = self.data._get_numeric_data().columns.to_list()
self.data.columns = _original_columns
- column_format = "" if self.hidden_index else "l" * self.data.index.nlevels
+ column_format = "" if self.hide_index_ else "l" * self.data.index.nlevels
for ci, _ in enumerate(self.data.columns):
if ci not in self.hidden_columns:
column_format += (
@@ -926,7 +929,7 @@ def _copy(self, deepcopy: bool = False) -> Styler:
)
styler.uuid = self.uuid
- styler.hidden_index = self.hidden_index
+ styler.hide_index_ = self.hide_index_
if deepcopy:
styler.ctx = copy.deepcopy(self.ctx)
@@ -965,7 +968,7 @@ def clear(self) -> None:
self.cell_context.clear()
self._todo.clear()
- self.hidden_index = False
+ self.hide_index_ = False
self.hidden_columns = []
# self.format and self.table_styles may be dependent on user
# input in self.__init__()
@@ -1096,7 +1099,7 @@ def _applymap(
) -> Styler:
func = partial(func, **kwargs) # applymap doesn't take kwargs?
if subset is None:
- subset = pd.IndexSlice[:]
+ subset = IndexSlice[:]
subset = non_reducing_slice(subset)
result = self.data.loc[subset].applymap(func)
self._update_ctx(result)
@@ -1511,37 +1514,169 @@ def set_na_rep(self, na_rep: str) -> StylerRenderer:
self.na_rep = na_rep
return self.format(na_rep=na_rep, precision=self.precision)
- def hide_index(self) -> Styler:
+ def hide_index(self, subset: Subset | None = None) -> Styler:
"""
- Hide any indices from rendering.
+ Hide the entire index, or specific keys in the index from rendering.
+
+ This method has dual functionality:
+
+ - if ``subset`` is ``None`` then the entire index will be hidden whilst
+ displaying all data-rows.
+ - if a ``subset`` is given then those specific rows will be hidden whilst the
+ index itself remains visible.
+
+ .. versionchanged:: 1.3.0
+
+ Parameters
+ ----------
+ subset : label, array-like, IndexSlice, optional
+ A valid 1d input or single key along the index axis within
+ `DataFrame.loc[<subset>, :]`, to limit ``data`` to *before* applying
+ the function.
Returns
-------
self : Styler
+
+ See Also
+ --------
+ Styler.hide_columns: Hide the entire column headers row, or specific columns.
+
+ Examples
+ --------
+ Simple application hiding specific rows:
+
+ >>> df = pd.DataFrame([[1,2], [3,4], [5,6]], index=["a", "b", "c"])
+ >>> df.style.hide_index(["a", "b"])
+ 0 1
+ c 5 6
+
+ Hide the index and retain the data values:
+
+ >>> midx = pd.MultiIndex.from_product([["x", "y"], ["a", "b", "c"]])
+ >>> df = pd.DataFrame(np.random.randn(6,6), index=midx, columns=midx)
+ >>> df.style.format("{:.1f}").hide_index()
+ x y
+ a b c a b c
+ 0.1 0.0 0.4 1.3 0.6 -1.4
+ 0.7 1.0 1.3 1.5 -0.0 -0.2
+ 1.4 -0.8 1.6 -0.2 -0.4 -0.3
+ 0.4 1.0 -0.2 -0.8 -1.2 1.1
+ -0.6 1.2 1.8 1.9 0.3 0.3
+ 0.8 0.5 -0.3 1.2 2.2 -0.8
+
+ Hide specific rows but retain the index:
+
+ >>> df.style.format("{:.1f}").hide_index(subset=(slice(None), ["a", "c"]))
+ x y
+ a b c a b c
+ x b 0.7 1.0 1.3 1.5 -0.0 -0.2
+ y b -0.6 1.2 1.8 1.9 0.3 0.3
+
+ Hide specific rows and the index:
+
+ >>> df.style.format("{:.1f}").hide_index(subset=(slice(None), ["a", "c"]))
+ ... .hide_index()
+ x y
+ a b c a b c
+ 0.7 1.0 1.3 1.5 -0.0 -0.2
+ -0.6 1.2 1.8 1.9 0.3 0.3
"""
- self.hidden_index = True
+ if subset is None:
+ self.hide_index_ = True
+ else:
+ subset_ = IndexSlice[subset, :] # new var so mypy reads not Optional
+ subset = non_reducing_slice(subset_)
+ hide = self.data.loc[subset]
+ hrows = self.index.get_indexer_for(hide.index)
+ # error: Incompatible types in assignment (expression has type
+ # "ndarray", variable has type "Sequence[int]")
+ self.hidden_rows = hrows # type: ignore[assignment]
return self
- def hide_columns(self, subset: Subset) -> Styler:
+ def hide_columns(self, subset: Subset | None = None) -> Styler:
"""
- Hide columns from rendering.
+ Hide the column headers or specific keys in the columns from rendering.
+
+ This method has dual functionality:
+
+ - if ``subset`` is ``None`` then the entire column headers row will be hidden
+ whilst the data-values remain visible.
+ - if a ``subset`` is given then those specific columns, including the
+ data-values will be hidden, whilst the column headers row remains visible.
+
+ .. versionchanged:: 1.3.0
Parameters
----------
- subset : label, array-like, IndexSlice
- A valid 1d input or single key along the appropriate axis within
- `DataFrame.loc[]`, to limit ``data`` to *before* applying the function.
+ subset : label, array-like, IndexSlice, optional
+ A valid 1d input or single key along the columns axis within
+ `DataFrame.loc[:, <subset>]`, to limit ``data`` to *before* applying
+ the function.
Returns
-------
self : Styler
+
+ See Also
+ --------
+ Styler.hide_index: Hide the entire index, or specific keys in the index.
+
+ Examples
+ --------
+ Simple application hiding specific columns:
+
+ >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "b", "c"])
+ >>> df.style.hide_columns(["a", "b"])
+ c
+ 0 3
+ 1 6
+
+ Hide column headers and retain the data values:
+
+ >>> midx = pd.MultiIndex.from_product([["x", "y"], ["a", "b", "c"]])
+ >>> df = pd.DataFrame(np.random.randn(6,6), index=midx, columns=midx)
+ >>> df.style.format("{:.1f}").hide_columns()
+ x d 0.1 0.0 0.4 1.3 0.6 -1.4
+ e 0.7 1.0 1.3 1.5 -0.0 -0.2
+ f 1.4 -0.8 1.6 -0.2 -0.4 -0.3
+ y d 0.4 1.0 -0.2 -0.8 -1.2 1.1
+ e -0.6 1.2 1.8 1.9 0.3 0.3
+ f 0.8 0.5 -0.3 1.2 2.2 -0.8
+
+ Hide specific columns but retain the column headers:
+
+ >>> df.style.format("{:.1f}").hide_columns(subset=(slice(None), ["a", "c"]))
+ x y
+ b b
+ x a 0.0 0.6
+ b 1.0 -0.0
+ c -0.8 -0.4
+ y a 1.0 -1.2
+ b 1.2 0.3
+ c 0.5 2.2
+
+ Hide specific columns and the column headers:
+
+ >>> df.style.format("{:.1f}").hide_columns(subset=(slice(None), ["a", "c"]))
+ ... .hide_columns()
+ x a 0.0 0.6
+ b 1.0 -0.0
+ c -0.8 -0.4
+ y a 1.0 -1.2
+ b 1.2 0.3
+ c 0.5 2.2
"""
- subset = non_reducing_slice(subset)
- hidden_df = self.data.loc[subset]
- hcols = self.columns.get_indexer_for(hidden_df.columns)
- # error: Incompatible types in assignment (expression has type
- # "ndarray", variable has type "Sequence[int]")
- self.hidden_columns = hcols # type: ignore[assignment]
+ if subset is None:
+ self.hide_columns_ = True
+ else:
+ subset_ = IndexSlice[:, subset] # new var so mypy reads not Optional
+ subset = non_reducing_slice(subset_)
+ hide = self.data.loc[subset]
+ hcols = self.columns.get_indexer_for(hide.columns)
+ # error: Incompatible types in assignment (expression has type
+ # "ndarray", variable has type "Sequence[int]")
+ self.hidden_columns = hcols # type: ignore[assignment]
return self
# -----------------------------------------------------------------------
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index 7686d8a340c37..514597d27a92b 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -97,7 +97,9 @@ def __init__(
self.cell_ids = cell_ids
# add rendering variables
- self.hidden_index: bool = False
+ self.hide_index_: bool = False # bools for hiding col/row headers
+ self.hide_columns_: bool = False
+ self.hidden_rows: Sequence[int] = [] # sequence for specific hidden rows/cols
self.hidden_columns: Sequence[int] = []
self.ctx: DefaultDict[tuple[int, int], CSSList] = defaultdict(list)
self.cell_context: DefaultDict[tuple[int, int], str] = defaultdict(str)
@@ -297,55 +299,56 @@ def _translate_header(
head = []
# 1) column headers
- for r in range(self.data.columns.nlevels):
- index_blanks = [
- _element("th", blank_class, blank_value, not self.hidden_index)
- ] * (self.data.index.nlevels - 1)
-
- name = self.data.columns.names[r]
- column_name = [
- _element(
- "th",
- f"{blank_class if name is None else index_name_class} level{r}",
- name if name is not None else blank_value,
- not self.hidden_index,
- )
- ]
-
- if clabels:
- column_headers = [
+ if not self.hide_columns_:
+ for r in range(self.data.columns.nlevels):
+ index_blanks = [
+ _element("th", blank_class, blank_value, not self.hide_index_)
+ ] * (self.data.index.nlevels - 1)
+
+ name = self.data.columns.names[r]
+ column_name = [
_element(
"th",
- f"{col_heading_class} level{r} col{c}",
- value,
- _is_visible(c, r, col_lengths),
- attributes=(
- f'colspan="{col_lengths.get((r, c), 0)}"'
- if col_lengths.get((r, c), 0) > 1
- else ""
- ),
+ f"{blank_class if name is None else index_name_class} level{r}",
+ name if name is not None else blank_value,
+ not self.hide_index_,
)
- for c, value in enumerate(clabels[r])
]
- if len(self.data.columns) > max_cols:
- # add an extra column with `...` value to indicate trimming
- column_headers.append(
+ if clabels:
+ column_headers = [
_element(
"th",
- f"{col_heading_class} level{r} {trimmed_col_class}",
- "...",
- True,
- attributes="",
+ f"{col_heading_class} level{r} col{c}",
+ value,
+ _is_visible(c, r, col_lengths),
+ attributes=(
+ f'colspan="{col_lengths.get((r, c), 0)}"'
+ if col_lengths.get((r, c), 0) > 1
+ else ""
+ ),
)
- )
- head.append(index_blanks + column_name + column_headers)
+ for c, value in enumerate(clabels[r])
+ ]
+
+ if len(self.data.columns) > max_cols:
+ # add an extra column with `...` value to indicate trimming
+ column_headers.append(
+ _element(
+ "th",
+ f"{col_heading_class} level{r} {trimmed_col_class}",
+ "...",
+ True,
+ attributes="",
+ )
+ )
+ head.append(index_blanks + column_name + column_headers)
# 2) index names
if (
self.data.index.names
and com.any_not_none(*self.data.index.names)
- and not self.hidden_index
+ and not self.hide_index_
):
index_names = [
_element(
@@ -411,7 +414,9 @@ def _translate_body(
The associated HTML elements needed for template rendering.
"""
# for sparsifying a MultiIndex
- idx_lengths = _get_level_lengths(self.index, sparsify_index, max_rows)
+ idx_lengths = _get_level_lengths(
+ self.index, sparsify_index, max_rows, self.hidden_rows
+ )
rlabels = self.data.index.tolist()[:max_rows] # slice to allow trimming
if self.data.index.nlevels == 1:
@@ -425,7 +430,7 @@ def _translate_body(
"th",
f"{row_heading_class} level{c} {trimmed_row_class}",
"...",
- not self.hidden_index,
+ not self.hide_index_,
attributes="",
)
for c in range(self.data.index.nlevels)
@@ -462,7 +467,7 @@ def _translate_body(
"th",
f"{row_heading_class} level{c} row{r}",
value,
- (_is_visible(r, c, idx_lengths) and not self.hidden_index),
+ (_is_visible(r, c, idx_lengths) and not self.hide_index_),
id=f"level{c}_row{r}",
attributes=(
f'rowspan="{idx_lengths.get((c, r), 0)}"'
@@ -496,7 +501,7 @@ def _translate_body(
"td",
f"{data_class} row{r} col{c}{cls}",
value,
- (c not in self.hidden_columns),
+ (c not in self.hidden_columns and r not in self.hidden_rows),
attributes="",
display_value=self._display_funcs[(r, c)](value),
)
@@ -527,7 +532,7 @@ def _translate_latex(self, d: dict) -> None:
d["head"] = [[col for col in row if col["is_visible"]] for row in d["head"]]
body = []
for r, row in enumerate(d["body"]):
- if self.hidden_index:
+ if self.hide_index_:
row_body_headers = []
else:
row_body_headers = [
@@ -842,7 +847,13 @@ def _get_level_lengths(
last_label = j
lengths[(i, last_label)] = 0
elif j not in hidden_elements:
- lengths[(i, last_label)] += 1
+ if lengths[(i, last_label)] == 0:
+ # if the previous iteration was first-of-kind but hidden then offset
+ last_label = j
+ lengths[(i, last_label)] = 1
+ else:
+ # else add to previous iteration
+ lengths[(i, last_label)] += 1
non_zero_lengths = {
element: length for element, length in lengths.items() if length >= 1
diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py
index 281170ab6c7cb..0516aa6029487 100644
--- a/pandas/tests/io/formats/style/test_style.py
+++ b/pandas/tests/io/formats/style/test_style.py
@@ -221,7 +221,7 @@ def test_copy(self, do_changes, do_render):
[{"selector": "th", "props": [("foo", "bar")]}]
)
self.styler.set_table_attributes('class="foo" data-bar')
- self.styler.hidden_index = not self.styler.hidden_index
+ self.styler.hide_index_ = not self.styler.hide_index_
self.styler.hide_columns("A")
classes = DataFrame(
[["favorite-val red", ""], [None, "blue my-val"]],
@@ -292,7 +292,7 @@ def test_copy(self, do_changes, do_render):
"table_styles",
"table_attributes",
"cell_ids",
- "hidden_index",
+ "hide_index_",
"hidden_columns",
"cell_context",
]
@@ -317,7 +317,7 @@ def test_clear(self):
assert len(s._todo) > 0
assert s.tooltips
assert len(s.cell_context) > 0
- assert s.hidden_index is True
+ assert s.hide_index_ is True
assert len(s.hidden_columns) > 0
s = s._compute()
@@ -331,7 +331,7 @@ def test_clear(self):
assert len(s._todo) == 0
assert not s.tooltips
assert len(s.cell_context) == 0
- assert s.hidden_index is False
+ assert s.hide_index_ is False
assert len(s.hidden_columns) == 0
def test_render(self):
@@ -1127,6 +1127,14 @@ def test_mi_sparse_column_names(self):
]
assert head == expected
+ def test_hide_column_headers(self):
+ ctx = self.styler.hide_columns()._translate(True, True)
+ assert len(ctx["head"]) == 0 # no header entries with an unnamed index
+
+ self.df.index.name = "some_name"
+ ctx = self.df.style.hide_columns()._translate(True, True)
+ assert len(ctx["head"]) == 1 # only a single row for index names: no col heads
+
def test_hide_single_index(self):
# GH 14194
# single unnamed index
@@ -1195,7 +1203,7 @@ def test_hide_columns_single_level(self):
assert not ctx["body"][0][1]["is_visible"] # col A, row 1
assert not ctx["body"][1][2]["is_visible"] # col B, row 1
- def test_hide_columns_mult_levels(self):
+ def test_hide_columns_index_mult_levels(self):
# GH 14194
# setup dataframe with multiple column levels and indices
i1 = MultiIndex.from_arrays(
@@ -1227,7 +1235,8 @@ def test_hide_columns_mult_levels(self):
# hide first column only
ctx = df.style.hide_columns([("b", 0)])._translate(True, True)
- assert ctx["head"][0][2]["is_visible"] # b
+ assert not ctx["head"][0][2]["is_visible"] # b
+ assert ctx["head"][0][3]["is_visible"] # b
assert not ctx["head"][1][2]["is_visible"] # 0
assert not ctx["body"][1][2]["is_visible"] # 3
assert ctx["body"][1][3]["is_visible"]
@@ -1243,6 +1252,18 @@ def test_hide_columns_mult_levels(self):
assert ctx["body"][1][2]["is_visible"]
assert ctx["body"][1][2]["display_value"] == 3
+ # hide top row level, which hides both rows
+ ctx = df.style.hide_index("a")._translate(True, True)
+ for i in [0, 1, 2, 3]:
+ assert not ctx["body"][0][i]["is_visible"]
+ assert not ctx["body"][1][i]["is_visible"]
+
+ # hide first row only
+ ctx = df.style.hide_index(("a", 0))._translate(True, True)
+ for i in [0, 1, 2, 3]:
+ assert not ctx["body"][0][i]["is_visible"]
+ assert ctx["body"][1][i]["is_visible"]
+
def test_pipe(self):
def set_caption_from_template(styler, a, b):
return styler.set_caption(f"Dataframe with a = {a} and b = {b}")
| Backport PR #41266: API: make `hide_columns` and `hide_index` have a consistent signature and function in `Styler` | https://api.github.com/repos/pandas-dev/pandas/pulls/42041 | 2021-06-16T00:23:01Z | 2021-06-16T08:00:55Z | 2021-06-16T08:00:55Z | 2021-06-16T08:00:55Z |
Backport PR #40731 on branch 1.3.x (ENH: `Styler.to_latex` conversion from CSS) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 414794dd6a56e..e20342976aad7 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -136,7 +136,7 @@ which has been revised and improved (:issue:`39720`, :issue:`39317`, :issue:`404
- Many features of the :class:`.Styler` class are now either partially or fully usable on a DataFrame with a non-unique indexes or columns (:issue:`41143`)
- One has greater control of the display through separate sparsification of the index or columns using the :ref:`new styler options <options.available>`, which are also usable via :func:`option_context` (:issue:`41142`)
- Added the option ``styler.render.max_elements`` to avoid browser overload when styling large DataFrames (:issue:`40712`)
- - Added the method :meth:`.Styler.to_latex` (:issue:`21673`)
+ - Added the method :meth:`.Styler.to_latex` (:issue:`21673`), which also allows some limited CSS conversion (:issue:`40731`)
- Added the method :meth:`.Styler.to_html` (:issue:`13379`)
.. _whatsnew_130.enhancements.dataframe_honors_copy_with_dict:
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index c5aba539bd2dd..e646b9cbacc3d 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -426,6 +426,7 @@ def to_latex(
multicol_align: str = "r",
siunitx: bool = False,
encoding: str | None = None,
+ convert_css: bool = False,
):
r"""
Write Styler to a file, buffer or string in LaTeX format.
@@ -482,6 +483,10 @@ def to_latex(
Set to ``True`` to structure LaTeX compatible with the {siunitx} package.
encoding : str, default "utf-8"
Character encoding setting.
+ convert_css : bool, default False
+ Convert simple cell-styles from CSS to LaTeX format. Any CSS not found in
+ conversion table is dropped. A style can be forced by adding option
+ `--latex`. See notes.
Returns
-------
@@ -661,6 +666,45 @@ def to_latex(
& ix2 & \$3 & 4.400 & CATS \\
L1 & ix3 & \$2 & 6.600 & COWS \\
\end{tabular}
+
+ **CSS Conversion**
+
+ This method can convert a Styler constructured with HTML-CSS to LaTeX using
+ the following limited conversions.
+
+ ================== ==================== ============= ==========================
+ CSS Attribute CSS value LaTeX Command LaTeX Options
+ ================== ==================== ============= ==========================
+ font-weight | bold | bfseries
+ | bolder | bfseries
+ font-style | italic | itshape
+ | oblique | slshape
+ background-color | red cellcolor | {red}--lwrap
+ | #fe01ea | [HTML]{FE01EA}--lwrap
+ | #f0e | [HTML]{FF00EE}--lwrap
+ | rgb(128,255,0) | [rgb]{0.5,1,0}--lwrap
+ | rgba(128,0,0,0.5) | [rgb]{0.5,0,0}--lwrap
+ | rgb(25%,255,50%) | [rgb]{0.25,1,0.5}--lwrap
+ color | red color | {red}
+ | #fe01ea | [HTML]{FE01EA}
+ | #f0e | [HTML]{FF00EE}
+ | rgb(128,255,0) | [rgb]{0.5,1,0}
+ | rgba(128,0,0,0.5) | [rgb]{0.5,0,0}
+ | rgb(25%,255,50%) | [rgb]{0.25,1,0.5}
+ ================== ==================== ============= ==========================
+
+ It is also possible to add user-defined LaTeX only styles to a HTML-CSS Styler
+ using the ``--latex`` flag, and to add LaTeX parsing options that the
+ converter will detect within a CSS-comment.
+
+ >>> df = pd.DataFrame([[1]])
+ >>> df.style.set_properties(
+ ... **{"font-weight": "bold /* --dwrap */", "Huge": "--latex--rwrap"}
+ ... ).to_latex(css_convert=True)
+ \begin{tabular}{lr}
+ {} & {0} \\
+ 0 & {\bfseries}{\Huge{1}} \\
+ \end{tabular}
"""
table_selectors = (
[style["selector"] for style in self.table_styles]
@@ -740,6 +784,7 @@ def to_latex(
sparse_columns=sparse_columns,
multirow_align=multirow_align,
multicol_align=multicol_align,
+ convert_css=convert_css,
)
return save_to_buffer(latex, buf=buf, encoding=encoding)
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index 7686d8a340c37..5aeeb40879d07 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -2,6 +2,7 @@
from collections import defaultdict
from functools import partial
+import re
from typing import (
Any,
Callable,
@@ -1253,7 +1254,9 @@ def _parse_latex_table_styles(table_styles: CSSStyles, selector: str) -> str | N
return None
-def _parse_latex_cell_styles(latex_styles: CSSList, display_value: str) -> str:
+def _parse_latex_cell_styles(
+ latex_styles: CSSList, display_value: str, convert_css: bool = False
+) -> str:
r"""
Mutate the ``display_value`` string including LaTeX commands from ``latex_styles``.
@@ -1279,6 +1282,8 @@ def _parse_latex_cell_styles(latex_styles: CSSList, display_value: str) -> str:
For example for styles:
`[('c1', 'o1--wrap'), ('c2', 'o2')]` this returns: `{\c1o1 \c2o2{display_value}}
"""
+ if convert_css:
+ latex_styles = _parse_latex_css_conversion(latex_styles)
for (command, options) in latex_styles[::-1]: # in reverse for most recent style
formatter = {
"--wrap": f"{{\\{command}--to_parse {display_value}}}",
@@ -1351,6 +1356,82 @@ def _parse_latex_options_strip(value: str | int | float, arg: str) -> str:
return str(value).replace(arg, "").replace("/*", "").replace("*/", "").strip()
+def _parse_latex_css_conversion(styles: CSSList) -> CSSList:
+ """
+ Convert CSS (attribute,value) pairs to equivalent LaTeX (command,options) pairs.
+
+ Ignore conversion if tagged with `--latex` option, skipped if no conversion found.
+ """
+
+ def font_weight(value, arg):
+ if value == "bold" or value == "bolder":
+ return "bfseries", f"{arg}"
+ return None
+
+ def font_style(value, arg):
+ if value == "italic":
+ return "itshape", f"{arg}"
+ elif value == "oblique":
+ return "slshape", f"{arg}"
+ return None
+
+ def color(value, user_arg, command, comm_arg):
+ """
+ CSS colors have 5 formats to process:
+
+ - 6 digit hex code: "#ff23ee" --> [HTML]{FF23EE}
+ - 3 digit hex code: "#f0e" --> [HTML]{FF00EE}
+ - rgba: rgba(128, 255, 0, 0.5) --> [rgb]{0.502, 1.000, 0.000}
+ - rgb: rgb(128, 255, 0,) --> [rbg]{0.502, 1.000, 0.000}
+ - string: red --> {red}
+
+ Additionally rgb or rgba can be expressed in % which is also parsed.
+ """
+ arg = user_arg if user_arg != "" else comm_arg
+
+ if value[0] == "#" and len(value) == 7: # color is hex code
+ return command, f"[HTML]{{{value[1:].upper()}}}{arg}"
+ if value[0] == "#" and len(value) == 4: # color is short hex code
+ val = f"{value[1].upper()*2}{value[2].upper()*2}{value[3].upper()*2}"
+ return command, f"[HTML]{{{val}}}{arg}"
+ elif value[:3] == "rgb": # color is rgb or rgba
+ r = re.findall("(?<=\\()[0-9\\s%]+(?=,)", value)[0].strip()
+ r = float(r[:-1]) / 100 if "%" in r else int(r) / 255
+ g = re.findall("(?<=,)[0-9\\s%]+(?=,)", value)[0].strip()
+ g = float(g[:-1]) / 100 if "%" in g else int(g) / 255
+ if value[3] == "a": # color is rgba
+ b = re.findall("(?<=,)[0-9\\s%]+(?=,)", value)[1].strip()
+ else: # color is rgb
+ b = re.findall("(?<=,)[0-9\\s%]+(?=\\))", value)[0].strip()
+ b = float(b[:-1]) / 100 if "%" in b else int(b) / 255
+ return command, f"[rgb]{{{r:.3f}, {g:.3f}, {b:.3f}}}{arg}"
+ else:
+ return command, f"{{{value}}}{arg}" # color is likely string-named
+
+ CONVERTED_ATTRIBUTES: dict[str, Callable] = {
+ "font-weight": font_weight,
+ "background-color": partial(color, command="cellcolor", comm_arg="--lwrap"),
+ "color": partial(color, command="color", comm_arg=""),
+ "font-style": font_style,
+ }
+
+ latex_styles: CSSList = []
+ for (attribute, value) in styles:
+ if isinstance(value, str) and "--latex" in value:
+ # return the style without conversion but drop '--latex'
+ latex_styles.append((attribute, value.replace("--latex", "")))
+ if attribute in CONVERTED_ATTRIBUTES.keys():
+ arg = ""
+ for x in ["--wrap", "--nowrap", "--lwrap", "--dwrap", "--rwrap"]:
+ if x in str(value):
+ arg, value = x, _parse_latex_options_strip(value, x)
+ break
+ latex_style = CONVERTED_ATTRIBUTES[attribute](value, arg)
+ if latex_style is not None:
+ latex_styles.extend([latex_style])
+ return latex_styles
+
+
def _escape_latex(s):
r"""
Replace the characters ``&``, ``%``, ``$``, ``#``, ``_``, ``{``, ``}``,
diff --git a/pandas/io/formats/templates/latex.tpl b/pandas/io/formats/templates/latex.tpl
index 66fe99642850f..fe081676d87af 100644
--- a/pandas/io/formats/templates/latex.tpl
+++ b/pandas/io/formats/templates/latex.tpl
@@ -39,7 +39,7 @@
{% endif %}
{% for row in body %}
{% for c in row %}{% if not loop.first %} & {% endif %}
- {%- if c.type == 'th' %}{{parse_header(c, multirow_align, multicol_align)}}{% else %}{{parse_cell(c.cellstyle, c.display_value)}}{% endif %}
+ {%- if c.type == 'th' %}{{parse_header(c, multirow_align, multicol_align)}}{% else %}{{parse_cell(c.cellstyle, c.display_value, convert_css)}}{% endif %}
{%- endfor %} \\
{% endfor %}
{% set bottomrule = parse_table(table_styles, 'bottomrule') %}
diff --git a/pandas/tests/io/formats/style/test_to_latex.py b/pandas/tests/io/formats/style/test_to_latex.py
index 97347bddaa187..91ac652e1f652 100644
--- a/pandas/tests/io/formats/style/test_to_latex.py
+++ b/pandas/tests/io/formats/style/test_to_latex.py
@@ -12,6 +12,7 @@
from pandas.io.formats.style import Styler
from pandas.io.formats.style_render import (
_parse_latex_cell_styles,
+ _parse_latex_css_conversion,
_parse_latex_header_span,
_parse_latex_table_styles,
_parse_latex_table_wrapping,
@@ -443,3 +444,48 @@ def test_parse_latex_table_wrapping(styler):
def test_short_caption(styler):
result = styler.to_latex(caption=("full cap", "short cap"))
assert "\\caption[short cap]{full cap}" in result
+
+
+@pytest.mark.parametrize(
+ "css, expected",
+ [
+ ([("color", "red")], [("color", "{red}")]), # test color and input format types
+ (
+ [("color", "rgb(128, 128, 128 )")],
+ [("color", "[rgb]{0.502, 0.502, 0.502}")],
+ ),
+ (
+ [("color", "rgb(128, 50%, 25% )")],
+ [("color", "[rgb]{0.502, 0.500, 0.250}")],
+ ),
+ (
+ [("color", "rgba(128,128,128,1)")],
+ [("color", "[rgb]{0.502, 0.502, 0.502}")],
+ ),
+ ([("color", "#FF00FF")], [("color", "[HTML]{FF00FF}")]),
+ ([("color", "#F0F")], [("color", "[HTML]{FF00FF}")]),
+ ([("font-weight", "bold")], [("bfseries", "")]), # test font-weight and types
+ ([("font-weight", "bolder")], [("bfseries", "")]),
+ ([("font-weight", "normal")], []),
+ ([("background-color", "red")], [("cellcolor", "{red}--lwrap")]),
+ (
+ [("background-color", "#FF00FF")], # test background-color command and wrap
+ [("cellcolor", "[HTML]{FF00FF}--lwrap")],
+ ),
+ ([("font-style", "italic")], [("itshape", "")]), # test font-style and types
+ ([("font-style", "oblique")], [("slshape", "")]),
+ ([("font-style", "normal")], []),
+ ([("color", "red /*--dwrap*/")], [("color", "{red}--dwrap")]), # css comments
+ ([("background-color", "red /* --dwrap */")], [("cellcolor", "{red}--dwrap")]),
+ ],
+)
+def test_parse_latex_css_conversion(css, expected):
+ result = _parse_latex_css_conversion(css)
+ assert result == expected
+
+
+def test_parse_latex_css_conversion_option():
+ css = [("command", "option--latex--wrap")]
+ expected = [("command", "option--wrap")]
+ result = _parse_latex_css_conversion(css)
+ assert result == expected
| Backport PR #40731: ENH: `Styler.to_latex` conversion from CSS | https://api.github.com/repos/pandas-dev/pandas/pulls/42040 | 2021-06-16T00:20:19Z | 2021-06-16T08:00:26Z | 2021-06-16T08:00:26Z | 2021-06-16T08:00:26Z |
Backport PR #41933 on branch 1.3.x (BUG: CategoricalIndex.get_loc(np.nan)) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 414794dd6a56e..2129025b2c071 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -1014,6 +1014,7 @@ Indexing
- Bug in :meth:`DataFrame.loc.__setitem__` when setting-with-expansion incorrectly raising when the index in the expanding axis contained duplicates (:issue:`40096`)
- Bug in :meth:`DataFrame.loc.__getitem__` with :class:`MultiIndex` casting to float when at least one index column has float dtype and we retrieve a scalar (:issue:`41369`)
- Bug in :meth:`DataFrame.loc` incorrectly matching non-Boolean index elements (:issue:`20432`)
+- Bug in indexing with ``np.nan`` on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` incorrectly raising ``KeyError`` when ``np.nan`` keys are present (:issue:`41933`)
- Bug in :meth:`Series.__delitem__` with ``ExtensionDtype`` incorrectly casting to ``ndarray`` (:issue:`40386`)
- Bug in :meth:`DataFrame.loc` returning a :class:`MultiIndex` in the wrong order if an indexer has duplicates (:issue:`40978`)
- Bug in :meth:`DataFrame.__setitem__` raising a ``TypeError`` when using a ``str`` subclass as the column name with a :class:`DatetimeIndex` (:issue:`37366`)
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 228f58d47b8ed..1bda05f3ce5df 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -483,7 +483,14 @@ def _reindex_non_unique( # type: ignore[override]
# Indexing Methods
def _maybe_cast_indexer(self, key) -> int:
- return self._data._unbox_scalar(key)
+ # GH#41933: we have to do this instead of self._data._validate_scalar
+ # because this will correctly get partial-indexing on Interval categories
+ try:
+ return self._data._unbox_scalar(key)
+ except KeyError:
+ if is_valid_na_for_dtype(key, self.categories.dtype):
+ return -1
+ raise
def _get_indexer(
self,
diff --git a/pandas/tests/indexes/categorical/test_indexing.py b/pandas/tests/indexes/categorical/test_indexing.py
index 0e0849fdb8dcf..b4a42cf137495 100644
--- a/pandas/tests/indexes/categorical/test_indexing.py
+++ b/pandas/tests/indexes/categorical/test_indexing.py
@@ -198,6 +198,13 @@ def test_get_loc_nonmonotonic_nonunique(self):
expected = np.array([False, True, False, True], dtype=bool)
tm.assert_numpy_array_equal(result, expected)
+ def test_get_loc_nan(self):
+ # GH#41933
+ ci = CategoricalIndex(["A", "B", np.nan])
+ res = ci.get_loc(np.nan)
+
+ assert res == 2
+
class TestGetIndexer:
def test_get_indexer_base(self):
diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py
index cd49620f45fae..23f7192724540 100644
--- a/pandas/tests/indexing/test_categorical.py
+++ b/pandas/tests/indexing/test_categorical.py
@@ -540,3 +540,16 @@ def test_loc_getitem_with_non_string_categories(self, idx_values, ordered):
result.loc[sl, "A"] = ["qux", "qux2"]
expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx)
tm.assert_frame_equal(result, expected)
+
+ def test_getitem_categorical_with_nan(self):
+ # GH#41933
+ ci = CategoricalIndex(["A", "B", np.nan])
+
+ ser = Series(range(3), index=ci)
+
+ assert ser[np.nan] == 2
+ assert ser.loc[np.nan] == 2
+
+ df = DataFrame(ser)
+ assert df.loc[np.nan, 0] == 2
+ assert df.loc[np.nan][0] == 2
| Backport PR #41933: BUG: CategoricalIndex.get_loc(np.nan) | https://api.github.com/repos/pandas-dev/pandas/pulls/42039 | 2021-06-16T00:11:44Z | 2021-06-16T08:00:04Z | 2021-06-16T08:00:03Z | 2021-06-16T08:00:04Z |
Backport PR #41846 on branch 1.3.x (BUG: DataFrame.at with CategoricalIndex) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 414794dd6a56e..a202c6fe56642 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -1015,6 +1015,7 @@ Indexing
- Bug in :meth:`DataFrame.loc.__getitem__` with :class:`MultiIndex` casting to float when at least one index column has float dtype and we retrieve a scalar (:issue:`41369`)
- Bug in :meth:`DataFrame.loc` incorrectly matching non-Boolean index elements (:issue:`20432`)
- Bug in :meth:`Series.__delitem__` with ``ExtensionDtype`` incorrectly casting to ``ndarray`` (:issue:`40386`)
+- Bug in :meth:`DataFrame.at` with a :class:`CategoricalIndex` returning incorrect results when passed integer keys (:issue:`41846`)
- Bug in :meth:`DataFrame.loc` returning a :class:`MultiIndex` in the wrong order if an indexer has duplicates (:issue:`40978`)
- Bug in :meth:`DataFrame.__setitem__` raising a ``TypeError`` when using a ``str`` subclass as the column name with a :class:`DatetimeIndex` (:issue:`37366`)
- Bug in :meth:`PeriodIndex.get_loc` failing to raise a ``KeyError`` when given a :class:`Period` with a mismatched ``freq`` (:issue:`41670`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 91b9bdd564676..2edad9f6626bb 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -158,6 +158,7 @@
from pandas.core.indexers import check_key_length
from pandas.core.indexes import base as ibase
from pandas.core.indexes.api import (
+ CategoricalIndex,
DatetimeIndex,
Index,
PeriodIndex,
@@ -3553,6 +3554,11 @@ def _get_value(self, index, col, takeable: bool = False) -> Scalar:
Returns
-------
scalar
+
+ Notes
+ -----
+ Assumes that index and columns both have ax._index_as_unique;
+ caller is responsible for checking.
"""
if takeable:
series = self._ixs(col, axis=1)
@@ -3561,20 +3567,21 @@ def _get_value(self, index, col, takeable: bool = False) -> Scalar:
series = self._get_item_cache(col)
engine = self.index._engine
+ if isinstance(self.index, CategoricalIndex):
+ # Trying to use the engine fastpath may give incorrect results
+ # if our categories are integers that dont match our codes
+ col = self.columns.get_loc(col)
+ index = self.index.get_loc(index)
+ return self._get_value(index, col, takeable=True)
+
try:
loc = engine.get_loc(index)
return series._values[loc]
- except KeyError:
- # GH 20629
- if self.index.nlevels > 1:
- # partial indexing forbidden
- raise
-
- # we cannot handle direct indexing
- # use positional
- col = self.columns.get_loc(col)
- index = self.index.get_loc(index)
- return self._get_value(index, col, takeable=True)
+ except AttributeError:
+ # IntervalTree has no get_loc
+ col = self.columns.get_loc(col)
+ index = self.index.get_loc(index)
+ return self._get_value(index, col, takeable=True)
def __setitem__(self, key, value):
key = com.apply_if_callable(key, self)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 3707e141bc447..d62dcdba92bc7 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -916,8 +916,7 @@ def __getitem__(self, key):
key = tuple(list(x) if is_iterator(x) else x for x in key)
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
if self._is_scalar_access(key):
- with suppress(KeyError, IndexError, AttributeError):
- # AttributeError for IntervalTree get_value
+ with suppress(KeyError, IndexError):
return self.obj._get_value(*key, takeable=self._takeable)
return self._getitem_tuple(key)
else:
@@ -1004,7 +1003,7 @@ def _is_scalar_access(self, key: tuple) -> bool:
# should not be considered scalar
return False
- if not ax.is_unique:
+ if not ax._index_as_unique:
return False
return True
diff --git a/pandas/tests/indexing/test_at.py b/pandas/tests/indexing/test_at.py
index 77cfb94bf4629..23d2bee612243 100644
--- a/pandas/tests/indexing/test_at.py
+++ b/pandas/tests/indexing/test_at.py
@@ -8,6 +8,7 @@
from pandas import (
CategoricalDtype,
+ CategoricalIndex,
DataFrame,
Series,
Timestamp,
@@ -141,3 +142,16 @@ def test_at_getitem_mixed_index_no_fallback(self):
ser.at[0]
with pytest.raises(KeyError, match="^4$"):
ser.at[4]
+
+ def test_at_categorical_integers(self):
+ # CategoricalIndex with integer categories that don't happen to match
+ # the Categorical's codes
+ ci = CategoricalIndex([3, 4])
+
+ arr = np.arange(4).reshape(2, 2)
+ frame = DataFrame(arr, index=ci)
+
+ for df in [frame, frame.T]:
+ for key in [0, 1]:
+ with pytest.raises(KeyError, match=str(key)):
+ df.at[key, key]
| Backport PR #41846: BUG: DataFrame.at with CategoricalIndex | https://api.github.com/repos/pandas-dev/pandas/pulls/42038 | 2021-06-16T00:03:38Z | 2021-06-16T07:59:40Z | 2021-06-16T07:59:40Z | 2021-06-16T07:59:41Z |
Backport PR #42006 on branch 1.3.x (DEP: move pkg_resources back inline in function (delayed import)) | diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index 00d87b707580d..302d5ede0ae86 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -7,8 +7,6 @@
Sequence,
)
-import pkg_resources
-
from pandas._config import get_option
from pandas._typing import IndexLabel
@@ -1745,6 +1743,8 @@ def _load_backend(backend: str) -> types.ModuleType:
types.ModuleType
The imported backend.
"""
+ import pkg_resources
+
if backend == "matplotlib":
# Because matplotlib is an optional dependency and first-party backend,
# we need to attempt an import here to raise an ImportError if needed.
| Backport PR #42006: DEP: move pkg_resources back inline in function (delayed import) | https://api.github.com/repos/pandas-dev/pandas/pulls/42037 | 2021-06-15T23:53:02Z | 2021-06-16T07:59:17Z | 2021-06-16T07:59:17Z | 2021-06-16T07:59:18Z |
Backport PR #41974 on branch 1.3.x (BUG: UInt64Index.where with int64 value) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 414794dd6a56e..37f560807f1ca 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -948,6 +948,8 @@ Numeric
- Bug in :meth:`Series.count` would result in an ``int32`` result on 32-bit platforms when argument ``level=None`` (:issue:`40908`)
- Bug in :class:`Series` and :class:`DataFrame` reductions with methods ``any`` and ``all`` not returning Boolean results for object data (:issue:`12863`, :issue:`35450`, :issue:`27709`)
- Bug in :meth:`Series.clip` would fail if the Series contains NA values and has nullable int or float as a data type (:issue:`40851`)
+- Bug in :meth:`UInt64Index.where` and :meth:`UInt64Index.putmask` with an ``np.int64`` dtype ``other`` incorrectly raising ``TypeError`` (:issue:`41974`)
+
Conversion
^^^^^^^^^^
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py
index ea2d5d9eec6ac..ce93cdff09ae0 100644
--- a/pandas/core/indexes/numeric.py
+++ b/pandas/core/indexes/numeric.py
@@ -370,6 +370,16 @@ class UInt64Index(IntegerIndex):
_default_dtype = np.dtype(np.uint64)
_dtype_validation_metadata = (is_unsigned_integer_dtype, "unsigned integer")
+ def _validate_fill_value(self, value):
+ # e.g. np.array([1]) we want np.array([1], dtype=np.uint64)
+ # see test_where_uin64
+ super()._validate_fill_value(value)
+ if hasattr(value, "dtype") and is_signed_integer_dtype(value.dtype):
+ if (value >= 0).all():
+ return value.astype(self.dtype)
+ raise TypeError
+ return value
+
class Float64Index(NumericIndex):
_index_descr_args = {
diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py
index 5f2f8f75045bb..540dbde609470 100644
--- a/pandas/tests/indexes/numeric/test_indexing.py
+++ b/pandas/tests/indexes/numeric/test_indexing.py
@@ -376,6 +376,19 @@ def test_where(self, klass, index):
result = index.where(klass(cond))
tm.assert_index_equal(result, expected)
+ def test_where_uin64(self):
+ idx = UInt64Index([0, 6, 2])
+ mask = np.array([False, True, False])
+ other = np.array([1], dtype=np.int64)
+
+ expected = UInt64Index([1, 6, 1])
+
+ result = idx.where(mask, other)
+ tm.assert_index_equal(result, expected)
+
+ result = idx.putmask(~mask, other)
+ tm.assert_index_equal(result, expected)
+
class TestTake:
@pytest.mark.parametrize("klass", [Float64Index, Int64Index, UInt64Index])
| Backport PR #41974: BUG: UInt64Index.where with int64 value | https://api.github.com/repos/pandas-dev/pandas/pulls/42036 | 2021-06-15T23:49:11Z | 2021-06-16T07:58:51Z | 2021-06-16T07:58:51Z | 2021-06-16T07:58:51Z |
Backport PR #41964 on branch 1.3.x (Bug in melt raising Error with dup columns as value vars) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 414794dd6a56e..d71a6197a02cd 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -1155,6 +1155,7 @@ Reshaping
- Bug in :func:`to_datetime` raising an error when the input sequence contained unhashable items (:issue:`39756`)
- Bug in :meth:`Series.explode` preserving the index when ``ignore_index`` was ``True`` and values were scalars (:issue:`40487`)
- Bug in :func:`to_datetime` raising a ``ValueError`` when :class:`Series` contains ``None`` and ``NaT`` and has more than 50 elements (:issue:`39882`)
+- Bug in :meth:`DataFrame.melt` raising ``InvalidIndexError`` when :class:`DataFrame` has duplicate columns used as ``value_vars`` (:issue:`41951`)
Sparse
^^^^^^
diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py
index 6a0fad9ee729b..56814b7692292 100644
--- a/pandas/core/reshape/melt.py
+++ b/pandas/core/reshape/melt.py
@@ -21,6 +21,7 @@
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.missing import notna
+import pandas.core.algorithms as algos
from pandas.core.arrays import Categorical
import pandas.core.common as com
from pandas.core.indexes.api import (
@@ -106,7 +107,7 @@ def melt(
id_vars + value_vars
)
else:
- idx = frame.columns.get_indexer(id_vars + value_vars)
+ idx = algos.unique(frame.columns.get_indexer_for(id_vars + value_vars))
frame = frame.iloc[:, idx]
else:
frame = frame.copy()
diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py
index a950c648838ff..4972cb34aac69 100644
--- a/pandas/tests/reshape/test_melt.py
+++ b/pandas/tests/reshape/test_melt.py
@@ -403,6 +403,15 @@ def test_ignore_index_name_and_type(self):
tm.assert_frame_equal(result, expected)
+ def test_melt_with_duplicate_columns(self):
+ # GH#41951
+ df = DataFrame([["id", 2, 3]], columns=["a", "b", "b"])
+ result = df.melt(id_vars=["a"], value_vars=["b"])
+ expected = DataFrame(
+ [["id", "b", 2], ["id", "b", 3]], columns=["a", "variable", "value"]
+ )
+ tm.assert_frame_equal(result, expected)
+
class TestLreshape:
def test_pairs(self):
| Backport PR #41964: Bug in melt raising Error with dup columns as value vars | https://api.github.com/repos/pandas-dev/pandas/pulls/42035 | 2021-06-15T23:34:33Z | 2021-06-16T07:58:18Z | 2021-06-16T07:58:18Z | 2021-06-16T07:58:19Z |
Backport PR #41982 on branch 1.3.x (TST: fix xpass for M1 Mac) | diff --git a/pandas/tests/indexes/numeric/test_numeric.py b/pandas/tests/indexes/numeric/test_numeric.py
index 9572aeaf41c91..de75f1dffde56 100644
--- a/pandas/tests/indexes/numeric/test_numeric.py
+++ b/pandas/tests/indexes/numeric/test_numeric.py
@@ -2,6 +2,10 @@
import pytest
from pandas._libs.tslibs import Timestamp
+from pandas.compat import (
+ is_platform_arm,
+ is_platform_mac,
+)
import pandas as pd
from pandas import (
@@ -531,7 +535,10 @@ def test_constructor(self, dtype):
res = Index([1, 2 ** 63 + 1], dtype=dtype)
tm.assert_index_equal(res, idx)
- @pytest.mark.xfail(reason="https://github.com/numpy/numpy/issues/19146")
+ @pytest.mark.xfail(
+ not (is_platform_arm and is_platform_mac()),
+ reason="https://github.com/numpy/numpy/issues/19146",
+ )
def test_constructor_does_not_cast_to_float(self):
# https://github.com/numpy/numpy/issues/19146
values = [0, np.iinfo(np.uint64).max]
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index 17a6d9216ca92..77ca482936298 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -6,7 +6,10 @@
import numpy as np
import pytest
-from pandas.compat import is_platform_arm
+from pandas.compat import (
+ is_platform_arm,
+ is_platform_mac,
+)
from pandas.errors import UnsupportedFunctionCall
from pandas import (
@@ -1073,7 +1076,7 @@ def test_rolling_sem(frame_or_series):
tm.assert_series_equal(result, expected)
-@pytest.mark.xfail(is_platform_arm(), reason="GH 41740")
+@pytest.mark.xfail(is_platform_arm() and not is_platform_mac(), reason="GH 38921")
@pytest.mark.parametrize(
("func", "third_value", "values"),
[
| Backport PR #41982: TST: fix xpass for M1 Mac | https://api.github.com/repos/pandas-dev/pandas/pulls/42034 | 2021-06-15T23:33:32Z | 2021-06-16T01:44:38Z | 2021-06-16T01:44:38Z | 2021-06-16T08:10:59Z |
Backport PR #42017 on branch 1.3.x (DOC: Fix wrongly associated docstring of Series.str.isspace) | diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 323cb6bd9fedd..d3cdcec9da8f1 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -3005,7 +3005,7 @@ def casefold(self):
"isdigit", docstring=_shared_docs["ismethods"] % _doc_args["isdigit"]
)
isspace = _map_and_wrap(
- "isspace", docstring=_shared_docs["ismethods"] % _doc_args["isalnum"]
+ "isspace", docstring=_shared_docs["ismethods"] % _doc_args["isspace"]
)
islower = _map_and_wrap(
"islower", docstring=_shared_docs["ismethods"] % _doc_args["islower"]
| Backport PR #42017: DOC: Fix wrongly associated docstring of Series.str.isspace | https://api.github.com/repos/pandas-dev/pandas/pulls/42033 | 2021-06-15T22:40:39Z | 2021-06-16T01:45:52Z | 2021-06-16T01:45:52Z | 2021-06-16T01:45:52Z |
Backport PR #42023 on branch 1.3.x (CI: pin fsspec) | diff --git a/ci/deps/actions-37-db.yaml b/ci/deps/actions-37-db.yaml
index e568f8615a8df..a9e4113bf9d18 100644
--- a/ci/deps/actions-37-db.yaml
+++ b/ci/deps/actions-37-db.yaml
@@ -16,7 +16,7 @@ dependencies:
- botocore>=1.11
- dask
- fastparquet>=0.4.0
- - fsspec>=0.7.4
+ - fsspec>=0.7.4, <2021.6.0
- gcsfs>=0.6.0
- geopandas
- html5lib
diff --git a/ci/deps/actions-37.yaml b/ci/deps/actions-37.yaml
index 0effe6f80df86..2272f8470e209 100644
--- a/ci/deps/actions-37.yaml
+++ b/ci/deps/actions-37.yaml
@@ -14,7 +14,7 @@ dependencies:
# pandas dependencies
- botocore>=1.11
- - fsspec>=0.7.4
+ - fsspec>=0.7.4, <2021.6.0
- numpy=1.19
- python-dateutil
- nomkl
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index 5cbc029f8c03d..4df55813ea21c 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -15,7 +15,7 @@ dependencies:
# pandas dependencies
- beautifulsoup4
- bottleneck
- - fsspec>=0.8.0
+ - fsspec>=0.8.0, <2021.6.0
- gcsfs>=0.6.0
- html5lib
- jinja2
diff --git a/environment.yml b/environment.yml
index 788b88ef16ad6..2c06c321fdbc4 100644
--- a/environment.yml
+++ b/environment.yml
@@ -106,7 +106,7 @@ dependencies:
- pyqt>=5.9.2 # pandas.read_clipboard
- pytables>=3.5.1 # pandas.read_hdf, DataFrame.to_hdf
- s3fs>=0.4.0 # file IO when using 's3://...' path
- - fsspec>=0.7.4 # for generic remote file operations
+ - fsspec>=0.7.4, <2021.6.0 # for generic remote file operations
- gcsfs>=0.6.0 # file IO when using 'gcs://...' path
- sqlalchemy # pandas.read_sql, DataFrame.to_sql
- xarray # DataFrame.to_xarray
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 332059341df48..a0d4c8e02acf6 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -70,7 +70,7 @@ python-snappy
pyqt5>=5.9.2
tables>=3.5.1
s3fs>=0.4.0
-fsspec>=0.7.4
+fsspec>=0.7.4, <2021.6.0
gcsfs>=0.6.0
sqlalchemy
xarray
| Backport PR #42023: CI: pin fsspec | https://api.github.com/repos/pandas-dev/pandas/pulls/42032 | 2021-06-15T22:27:56Z | 2021-06-15T23:32:37Z | 2021-06-15T23:32:37Z | 2021-06-15T23:32:43Z |
PERF: groupsort_indexer contiguity | diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx
index 172f2bfb49160..adfe4de1263ed 100644
--- a/pandas/_libs/algos.pyx
+++ b/pandas/_libs/algos.pyx
@@ -217,8 +217,8 @@ def groupsort_indexer(const intp_t[:] index, Py_ssize_t ngroups):
This is a reverse of the label factorization process.
"""
cdef:
- Py_ssize_t i, loc, label, n
- ndarray[intp_t] indexer, where, counts
+ Py_ssize_t i, label, n
+ intp_t[::1] indexer, where, counts
counts = np.zeros(ngroups + 1, dtype=np.intp)
n = len(index)
@@ -241,7 +241,7 @@ def groupsort_indexer(const intp_t[:] index, Py_ssize_t ngroups):
indexer[where[label]] = i
where[label] += 1
- return indexer, counts
+ return indexer.base, counts.base
cdef inline Py_ssize_t swap(numeric *a, numeric *b) nogil:
| Some low-hanging fruit
```
In [1]: import numpy as np
...: import pandas._libs.algos as libalgos
...:
...: np.random.seed(0)
...: inds = np.random.randint(0, 100, 500000)
...: ngroups = inds.max() + 1
In [2]: %timeit libalgos.groupsort_indexer(inds, ngroups)
```
`1.06 ms Β± 11.3 Β΅s per loop (mean Β± std. dev. of 7 runs, 1000 loops each) # this pr`
` 1.2 ms Β± 39.1 Β΅s per loop (mean Β± std. dev. of 7 runs, 1000 loops each) # master`
| https://api.github.com/repos/pandas-dev/pandas/pulls/42031 | 2021-06-15T21:50:27Z | 2021-07-28T01:31:16Z | 2021-07-28T01:31:16Z | 2021-07-28T01:54:30Z |
Regression raising Error when having dup cols with single dtype for read csv | diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index 7d7074988e5f0..e5e61e409c320 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -108,6 +108,7 @@ from pandas.core.dtypes.common import (
is_object_dtype,
)
from pandas.core.dtypes.dtypes import CategoricalDtype
+from pandas.core.dtypes.inference import is_dict_like
cdef:
float64_t INF = <float64_t>np.inf
@@ -689,6 +690,7 @@ cdef class TextReader:
count = counts.get(name, 0)
if (
self.dtype is not None
+ and is_dict_like(self.dtype)
and self.dtype.get(old_name) is not None
and self.dtype.get(name) is None
):
diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index 670868c6f4261..af25a4166d5a6 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -25,6 +25,7 @@
)
from pandas.core.dtypes.common import is_integer
+from pandas.core.dtypes.inference import is_dict_like
from pandas.io.parsers.base_parser import (
ParserBase,
@@ -424,6 +425,7 @@ def _infer_columns(self):
cur_count = counts[col]
if (
self.dtype is not None
+ and is_dict_like(self.dtype)
and self.dtype.get(old_col) is not None
and self.dtype.get(col) is None
):
diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
index 59fd3de60e0bf..bc20f1d1eea5f 100644
--- a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
+++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
@@ -248,3 +248,12 @@ def test_dtype_mangle_dup_cols(all_parsers, dtypes, exp_value):
result = parser.read_csv(StringIO(data), dtype={"a": str, **dtypes})
expected = DataFrame({"a": ["1"], "a.1": [exp_value]})
tm.assert_frame_equal(result, expected)
+
+
+def test_dtype_mangle_dup_cols_single_dtype(all_parsers):
+ # GH#42022
+ parser = all_parsers
+ data = """a,a\n1,1"""
+ result = parser.read_csv(StringIO(data), dtype=str)
+ expected = DataFrame({"a": ["1"], "a.1": ["1"]})
+ tm.assert_frame_equal(result, expected)
| - [x] closes #42022
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
regression on master, so no whatsnew | https://api.github.com/repos/pandas-dev/pandas/pulls/42030 | 2021-06-15T21:26:44Z | 2021-06-16T01:46:05Z | 2021-06-16T01:46:04Z | 2021-06-16T08:45:50Z |
Backport PR #41972 on branch 1.3.x (PERF: indexing on UInt64Index with int64s) | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index eaba30012a5b8..96ddf9ce76f53 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -5303,6 +5303,13 @@ def _maybe_promote(self, other: Index) -> tuple[Index, Index]:
if not is_object_dtype(self.dtype):
return self.astype("object"), other.astype("object")
+ elif self.dtype.kind == "u" and other.dtype.kind == "i":
+ # GH#41873
+ if other.min() >= 0:
+ # lookup min as it may be cached
+ # TODO: may need itemsize check if we have non-64-bit Indexes
+ return self, other.astype(self.dtype)
+
if not is_object_dtype(self.dtype) and is_object_dtype(other.dtype):
# Reverse op so we dont need to re-implement on the subclasses
other, self = other._maybe_promote(self)
| Backport PR #41972: PERF: indexing on UInt64Index with int64s | https://api.github.com/repos/pandas-dev/pandas/pulls/42029 | 2021-06-15T21:06:06Z | 2021-06-15T22:26:50Z | 2021-06-15T22:26:50Z | 2021-06-15T22:26:50Z |
Backport PR #41958 on branch 1.3.x (REGR: Series[dt64/td64].astype(string)) | diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 37e83ddb0ffed..51a947f79ede2 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -716,6 +716,14 @@ cpdef ndarray[object] ensure_string_array(
Py_ssize_t i = 0, n = len(arr)
if hasattr(arr, "to_numpy"):
+
+ if hasattr(arr, "dtype") and arr.dtype.kind in ["m", "M"]:
+ # dtype check to exclude DataFrame
+ # GH#41409 TODO: not a great place for this
+ out = arr.astype(str).astype(object)
+ out[arr.isna()] = na_value
+ return out
+
arr = arr.to_numpy()
elif not isinstance(arr, np.ndarray):
arr = np.array(arr, dtype="object")
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index 881f8db305240..bd71f0a0716b4 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -632,13 +632,9 @@ def test_astype_tz_object_conversion(self, tz):
result = result.astype({"tz": "datetime64[ns, Europe/London]"})
tm.assert_frame_equal(result, expected)
- def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture, request):
+ def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture):
+ # GH#41409
tz = tz_naive_fixture
- if tz is None:
- mark = pytest.mark.xfail(
- reason="GH#36153 uses ndarray formatting instead of DTA formatting"
- )
- request.node.add_marker(mark)
dti = date_range("2016-01-01", periods=3, tz=tz)
dta = dti._data
@@ -660,6 +656,15 @@ def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture, request)
alt = obj.astype(str)
assert np.all(alt.iloc[1:] == result.iloc[1:])
+ def test_astype_td64_to_string(self, frame_or_series):
+ # GH#41409
+ tdi = pd.timedelta_range("1 Day", periods=3)
+ obj = frame_or_series(tdi)
+
+ expected = frame_or_series(["1 days", "2 days", "3 days"], dtype="string")
+ result = obj.astype("string")
+ tm.assert_equal(result, expected)
+
def test_astype_bytes(self):
# GH#39474
result = DataFrame(["foo", "bar", "baz"]).astype(bytes)
| Backport PR #41958: REGR: Series[dt64/td64].astype(string) | https://api.github.com/repos/pandas-dev/pandas/pulls/42028 | 2021-06-15T21:04:49Z | 2021-06-15T22:27:36Z | 2021-06-15T22:27:36Z | 2021-06-15T22:27:36Z |
Backport PR #42024 on branch 1.3.x (TST: Reduce number of numba tests run) | diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py
index 24b28356a3099..5382f5f9202c0 100644
--- a/pandas/tests/window/conftest.py
+++ b/pandas/tests/window/conftest.py
@@ -90,13 +90,17 @@ def parallel(request):
return request.param
-@pytest.fixture(params=[True, False])
+# Can parameterize nogil & nopython over True | False, but limiting per
+# https://github.com/pandas-dev/pandas/pull/41971#issuecomment-860607472
+
+
+@pytest.fixture(params=[False])
def nogil(request):
"""nogil keyword argument for numba.jit"""
return request.param
-@pytest.fixture(params=[True, False])
+@pytest.fixture(params=[True])
def nopython(request):
"""nopython keyword argument for numba.jit"""
return request.param
| Backport PR #42024: TST: Reduce number of numba tests run | https://api.github.com/repos/pandas-dev/pandas/pulls/42027 | 2021-06-15T20:46:56Z | 2021-06-15T22:27:22Z | 2021-06-15T22:27:22Z | 2021-06-15T22:27:22Z |
Backport PR #41968 on branch 1.3.x (DOC: 1.3.0 release notes addition and doc fix) | diff --git a/doc/source/reference/style.rst b/doc/source/reference/style.rst
index 5a2ff803f0323..ae3647185f93d 100644
--- a/doc/source/reference/style.rst
+++ b/doc/source/reference/style.rst
@@ -34,7 +34,6 @@ Style application
Styler.apply
Styler.applymap
- Styler.where
Styler.format
Styler.set_td_classes
Styler.set_table_styles
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index bc75d948ba4ce..414794dd6a56e 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -812,6 +812,7 @@ Other Deprecations
- Using ``.astype`` to convert between ``datetime64[ns]`` dtype and :class:`DatetimeTZDtype` is deprecated and will raise in a future version, use ``obj.tz_localize`` or ``obj.dt.tz_localize`` instead (:issue:`38622`)
- Deprecated casting ``datetime.date`` objects to ``datetime64`` when used as ``fill_value`` in :meth:`DataFrame.unstack`, :meth:`DataFrame.shift`, :meth:`Series.shift`, and :meth:`DataFrame.reindex`, pass ``pd.Timestamp(dateobj)`` instead (:issue:`39767`)
- Deprecated :meth:`.Styler.set_na_rep` and :meth:`.Styler.set_precision` in favour of :meth:`.Styler.format` with ``na_rep`` and ``precision`` as existing and new input arguments respectively (:issue:`40134`, :issue:`40425`)
+- Deprecated :meth:`.Styler.where` in favour of using an alternative formulation with :meth:`Styler.applymap` (:issue:`40821`)
- Deprecated allowing partial failure in :meth:`Series.transform` and :meth:`DataFrame.transform` when ``func`` is list-like or dict-like and raises anything but ``TypeError``; ``func`` raising anything but a ``TypeError`` will raise in a future version (:issue:`40211`)
- Deprecated arguments ``error_bad_lines`` and ``warn_bad_lines`` in :meth:`read_csv` and :meth:`read_table` in favor of argument ``on_bad_lines`` (:issue:`15122`)
- Deprecated support for ``np.ma.mrecords.MaskedRecords`` in the :class:`DataFrame` constructor, pass ``{name: data[name] for name in data.dtype.names}`` instead (:issue:`40363`)
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 93c3843b36846..c5aba539bd2dd 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -1206,12 +1206,14 @@ def where(
recommend using instead.
The example:
+
>>> df = pd.DataFrame([[1, 2], [3, 4]])
>>> def cond(v, limit=4):
... return v > 1 and v != limit
>>> df.style.where(cond, value='color:green;', other='color:red;')
should be refactored to:
+
>>> def style_func(v, value, other, limit=4):
... cond = v > 1 and v != limit
... return value if cond else other
| Backport PR #41968: DOC: 1.3.0 release notes addition and doc fix | https://api.github.com/repos/pandas-dev/pandas/pulls/42025 | 2021-06-15T19:44:49Z | 2021-06-15T20:54:26Z | 2021-06-15T20:54:26Z | 2021-06-15T20:54:26Z |
TST: Reduce number of numba tests run | diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py
index 24b28356a3099..5382f5f9202c0 100644
--- a/pandas/tests/window/conftest.py
+++ b/pandas/tests/window/conftest.py
@@ -90,13 +90,17 @@ def parallel(request):
return request.param
-@pytest.fixture(params=[True, False])
+# Can parameterize nogil & nopython over True | False, but limiting per
+# https://github.com/pandas-dev/pandas/pull/41971#issuecomment-860607472
+
+
+@pytest.fixture(params=[False])
def nogil(request):
"""nogil keyword argument for numba.jit"""
return request.param
-@pytest.fixture(params=[True, False])
+@pytest.fixture(params=[True])
def nopython(request):
"""nopython keyword argument for numba.jit"""
return request.param
| - xref https://github.com/pandas-dev/pandas/pull/41971#issuecomment-860607472
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/42024 | 2021-06-15T19:38:49Z | 2021-06-15T20:46:48Z | 2021-06-15T20:46:48Z | 2021-06-15T21:06:12Z |
CI: pin fsspec | diff --git a/ci/deps/actions-37-db.yaml b/ci/deps/actions-37-db.yaml
index e568f8615a8df..a9e4113bf9d18 100644
--- a/ci/deps/actions-37-db.yaml
+++ b/ci/deps/actions-37-db.yaml
@@ -16,7 +16,7 @@ dependencies:
- botocore>=1.11
- dask
- fastparquet>=0.4.0
- - fsspec>=0.7.4
+ - fsspec>=0.7.4, <2021.6.0
- gcsfs>=0.6.0
- geopandas
- html5lib
diff --git a/ci/deps/actions-37.yaml b/ci/deps/actions-37.yaml
index 0effe6f80df86..2272f8470e209 100644
--- a/ci/deps/actions-37.yaml
+++ b/ci/deps/actions-37.yaml
@@ -14,7 +14,7 @@ dependencies:
# pandas dependencies
- botocore>=1.11
- - fsspec>=0.7.4
+ - fsspec>=0.7.4, <2021.6.0
- numpy=1.19
- python-dateutil
- nomkl
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index 5cbc029f8c03d..4df55813ea21c 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -15,7 +15,7 @@ dependencies:
# pandas dependencies
- beautifulsoup4
- bottleneck
- - fsspec>=0.8.0
+ - fsspec>=0.8.0, <2021.6.0
- gcsfs>=0.6.0
- html5lib
- jinja2
diff --git a/environment.yml b/environment.yml
index 788b88ef16ad6..2c06c321fdbc4 100644
--- a/environment.yml
+++ b/environment.yml
@@ -106,7 +106,7 @@ dependencies:
- pyqt>=5.9.2 # pandas.read_clipboard
- pytables>=3.5.1 # pandas.read_hdf, DataFrame.to_hdf
- s3fs>=0.4.0 # file IO when using 's3://...' path
- - fsspec>=0.7.4 # for generic remote file operations
+ - fsspec>=0.7.4, <2021.6.0 # for generic remote file operations
- gcsfs>=0.6.0 # file IO when using 'gcs://...' path
- sqlalchemy # pandas.read_sql, DataFrame.to_sql
- xarray # DataFrame.to_xarray
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 332059341df48..a0d4c8e02acf6 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -70,7 +70,7 @@ python-snappy
pyqt5>=5.9.2
tables>=3.5.1
s3fs>=0.4.0
-fsspec>=0.7.4
+fsspec>=0.7.4, <2021.6.0
gcsfs>=0.6.0
sqlalchemy
xarray
| Hopefully fixes new Windows py37_np17 failures | https://api.github.com/repos/pandas-dev/pandas/pulls/42023 | 2021-06-15T18:26:09Z | 2021-06-15T22:27:48Z | 2021-06-15T22:27:47Z | 2021-06-17T10:38:26Z |
BUG: passing str to GroupBy.apply | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 68f1c78688b1d..8d96d49daba4f 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -256,6 +256,7 @@ Plotting
Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
+- Fixed bug in :meth:`SeriesGroupBy.apply` where passing an unrecognized string argument failed to raise ``TypeError`` when the underlying ``Series`` is empty (:issue:`42021`)
- Bug in :meth:`Series.rolling.apply`, :meth:`DataFrame.rolling.apply`, :meth:`Series.expanding.apply` and :meth:`DataFrame.expanding.apply` with ``engine="numba"`` where ``*args`` were being cached with the user passed function (:issue:`42287`)
-
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index d3a86fa5950ed..aad43e4f96b81 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1242,7 +1242,17 @@ def f(g):
raise ValueError(
"func must be a callable if args or kwargs are supplied"
)
+ elif isinstance(func, str):
+ if hasattr(self, func):
+ res = getattr(self, func)
+ if callable(res):
+ return res()
+ return res
+
+ else:
+ raise TypeError(f"apply func should be callable, not '{func}'")
else:
+
f = func
# ignore SettingWithCopy here in case the user mutates
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 0181481b29c44..bcdb6817c0321 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -1770,13 +1770,9 @@ def test_empty_groupby(columns, keys, values, method, op, request):
isinstance(values, Categorical)
and not isinstance(columns, list)
and op in ["sum", "prod"]
- and method != "apply"
):
# handled below GH#41291
pass
- elif isinstance(values, Categorical) and len(keys) == 1 and method == "apply":
- mark = pytest.mark.xfail(raises=TypeError, match="'str' object is not callable")
- request.node.add_marker(mark)
elif (
isinstance(values, Categorical)
and len(keys) == 1
@@ -1808,21 +1804,16 @@ def test_empty_groupby(columns, keys, values, method, op, request):
isinstance(values, Categorical)
and len(keys) == 2
and op in ["min", "max", "sum"]
- and method != "apply"
):
mark = pytest.mark.xfail(
raises=AssertionError, match="(DataFrame|Series) are different"
)
request.node.add_marker(mark)
- elif (
- isinstance(values, pd.core.arrays.BooleanArray)
- and op in ["sum", "prod"]
- and method != "apply"
- ):
+ elif isinstance(values, pd.core.arrays.BooleanArray) and op in ["sum", "prod"]:
# We expect to get Int64 back for these
override_dtype = "Int64"
- if isinstance(values[0], bool) and op in ("prod", "sum") and method != "apply":
+ if isinstance(values[0], bool) and op in ("prod", "sum"):
# sum/product of bools is an integer
override_dtype = "int64"
@@ -1846,66 +1837,62 @@ def get_result():
# i.e. SeriesGroupBy
if op in ["prod", "sum"]:
# ops that require more than just ordered-ness
- if method != "apply":
- # FIXME: apply goes through different code path
- if df.dtypes[0].kind == "M":
- # GH#41291
- # datetime64 -> prod and sum are invalid
- msg = "datetime64 type does not support"
- with pytest.raises(TypeError, match=msg):
- get_result()
-
- return
- elif isinstance(values, Categorical):
- # GH#41291
- msg = "category type does not support"
- with pytest.raises(TypeError, match=msg):
- get_result()
-
- return
+ if df.dtypes[0].kind == "M":
+ # GH#41291
+ # datetime64 -> prod and sum are invalid
+ msg = "datetime64 type does not support"
+ with pytest.raises(TypeError, match=msg):
+ get_result()
+
+ return
+ elif isinstance(values, Categorical):
+ # GH#41291
+ msg = "category type does not support"
+ with pytest.raises(TypeError, match=msg):
+ get_result()
+
+ return
else:
# ie. DataFrameGroupBy
if op in ["prod", "sum"]:
# ops that require more than just ordered-ness
- if method != "apply":
- # FIXME: apply goes through different code path
- if df.dtypes[0].kind == "M":
- # GH#41291
- # datetime64 -> prod and sum are invalid
- result = get_result()
-
- # with numeric_only=True, these are dropped, and we get
- # an empty DataFrame back
- expected = df.set_index(keys)[[]]
- tm.assert_equal(result, expected)
- return
-
- elif isinstance(values, Categorical):
- # GH#41291
- # Categorical doesn't implement sum or prod
- result = get_result()
-
- # with numeric_only=True, these are dropped, and we get
- # an empty DataFrame back
- expected = df.set_index(keys)[[]]
- if len(keys) != 1 and op == "prod":
- # TODO: why just prod and not sum?
- # Categorical is special without 'observed=True'
- lev = Categorical([0], dtype=values.dtype)
- mi = MultiIndex.from_product([lev, lev], names=["A", "B"])
- expected = DataFrame([], columns=[], index=mi)
-
- tm.assert_equal(result, expected)
- return
-
- elif df.dtypes[0] == object:
- # FIXME: the test is actually wrong here, xref #41341
- result = get_result()
- # In this case we have list-of-list, will raise TypeError,
- # and subsequently be dropped as nuisance columns
- expected = df.set_index(keys)[[]]
- tm.assert_equal(result, expected)
- return
+ if df.dtypes[0].kind == "M":
+ # GH#41291
+ # datetime64 -> prod and sum are invalid
+ result = get_result()
+
+ # with numeric_only=True, these are dropped, and we get
+ # an empty DataFrame back
+ expected = df.set_index(keys)[[]]
+ tm.assert_equal(result, expected)
+ return
+
+ elif isinstance(values, Categorical):
+ # GH#41291
+ # Categorical doesn't implement sum or prod
+ result = get_result()
+
+ # with numeric_only=True, these are dropped, and we get
+ # an empty DataFrame back
+ expected = df.set_index(keys)[[]]
+ if len(keys) != 1 and op == "prod":
+ # TODO: why just prod and not sum?
+ # Categorical is special without 'observed=True'
+ lev = Categorical([0], dtype=values.dtype)
+ mi = MultiIndex.from_product([lev, lev], names=["A", "B"])
+ expected = DataFrame([], columns=[], index=mi)
+
+ tm.assert_equal(result, expected)
+ return
+
+ elif df.dtypes[0] == object:
+ # FIXME: the test is actually wrong here, xref #41341
+ result = get_result()
+ # In this case we have list-of-list, will raise TypeError,
+ # and subsequently be dropped as nuisance columns
+ expected = df.set_index(keys)[[]]
+ tm.assert_equal(result, expected)
+ return
result = get_result()
expected = df.set_index(keys)[columns]
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/42021 | 2021-06-15T17:25:53Z | 2021-07-17T14:18:16Z | 2021-07-17T14:18:16Z | 2021-07-17T18:47:28Z |
Backport PR #41990 on branch 1.3.x (CI: troubleshoot py310 build) | diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx
index 03f4ce273de6e..c2b9c723b7c72 100644
--- a/pandas/_libs/algos.pyx
+++ b/pandas/_libs/algos.pyx
@@ -1030,9 +1030,9 @@ def rank_1d(
if rank_t is object:
nan_fill_val = Infinity()
elif rank_t is int64_t:
- nan_fill_val = np.iinfo(np.int64).max
+ nan_fill_val = util.INT64_MAX
elif rank_t is uint64_t:
- nan_fill_val = np.iinfo(np.uint64).max
+ nan_fill_val = util.UINT64_MAX
else:
nan_fill_val = np.inf
order = (masked_vals, mask, labels)
@@ -1393,7 +1393,7 @@ def rank_2d(
# int64 and datetimelike
else:
- nan_value = np.iinfo(np.int64).max
+ nan_value = util.INT64_MAX
else:
if rank_t is object:
diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi
index 3f4623638c70e..077d2e60cc3a4 100644
--- a/pandas/_libs/lib.pyi
+++ b/pandas/_libs/lib.pyi
@@ -25,6 +25,9 @@ class NoDefault(Enum): ...
no_default: NoDefault
+i8max: int
+u8max: int
+
def item_from_zerodim(val: object) -> object: ...
def infer_dtype(value: object, skipna: bool = True) -> str: ...
def is_iterator(obj: object) -> bool: ...
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 0aec7e5e5a363..37e83ddb0ffed 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -118,6 +118,10 @@ cdef:
float64_t NaN = <float64_t>np.NaN
+# python-visible
+i8max = <int64_t>INT64_MAX
+u8max = <uint64_t>UINT64_MAX
+
@cython.wraparound(False)
@cython.boundscheck(False)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index f26cf113f7d5e..7dcc83f76db75 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1092,18 +1092,19 @@ def checked_add_with_arr(
# it is negative, we then check whether its sum with the element in
# 'arr' exceeds np.iinfo(np.int64).min. If so, we have an overflow
# error as well.
+ i8max = lib.i8max
+ i8min = iNaT
+
mask1 = b2 > 0
mask2 = b2 < 0
if not mask1.any():
- to_raise = ((np.iinfo(np.int64).min - b2 > arr) & not_nan).any()
+ to_raise = ((i8min - b2 > arr) & not_nan).any()
elif not mask2.any():
- to_raise = ((np.iinfo(np.int64).max - b2 < arr) & not_nan).any()
+ to_raise = ((i8max - b2 < arr) & not_nan).any()
else:
- to_raise = (
- (np.iinfo(np.int64).max - b2[mask1] < arr[mask1]) & not_nan[mask1]
- ).any() or (
- (np.iinfo(np.int64).min - b2[mask2] > arr[mask2]) & not_nan[mask2]
+ to_raise = ((i8max - b2[mask1] < arr[mask1]) & not_nan[mask1]).any() or (
+ (i8min - b2[mask2] > arr[mask2]) & not_nan[mask2]
).any()
if to_raise:
diff --git a/pandas/core/arrays/_ranges.py b/pandas/core/arrays/_ranges.py
index cac9fcd40fa52..3909875e5660a 100644
--- a/pandas/core/arrays/_ranges.py
+++ b/pandas/core/arrays/_ranges.py
@@ -6,6 +6,7 @@
import numpy as np
+from pandas._libs.lib import i8max
from pandas._libs.tslibs import (
BaseOffset,
OutOfBoundsDatetime,
@@ -103,7 +104,7 @@ def _generate_range_overflow_safe(
# GH#14187 raise instead of incorrectly wrapping around
assert side in ["start", "end"]
- i64max = np.uint64(np.iinfo(np.int64).max)
+ i64max = np.uint64(i8max)
msg = f"Cannot generate range with {side}={endpoint} and periods={periods}"
with np.errstate(over="raise"):
@@ -180,7 +181,7 @@ def _generate_range_overflow_safe_signed(
# error: Incompatible types in assignment (expression has type
# "unsignedinteger[_64Bit]", variable has type "signedinteger[_64Bit]")
result = np.uint64(endpoint) + np.uint64(addend) # type: ignore[assignment]
- i64max = np.uint64(np.iinfo(np.int64).max)
+ i64max = np.uint64(i8max)
assert result > i64max
if result <= i64max + np.uint64(stride):
# error: Incompatible return value type (got "unsignedinteger", expected
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index ecdf2624c8ec1..c34944985f2b6 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -205,7 +205,7 @@ def _get_fill_value(
else:
if fill_value_typ == "+inf":
# need the max int here
- return np.iinfo(np.int64).max
+ return lib.i8max
else:
return iNaT
@@ -376,7 +376,7 @@ def _wrap_results(result, dtype: np.dtype, fill_value=None):
result = np.nan
# raise if we have a timedelta64[ns] which is too large
- if np.fabs(result) > np.iinfo(np.int64).max:
+ if np.fabs(result) > lib.i8max:
raise ValueError("overflow in timedelta operation")
result = Timedelta(result, unit="ns")
@@ -1758,7 +1758,7 @@ def na_accum_func(values: ArrayLike, accum_func, *, skipna: bool) -> ArrayLike:
if accum_func == np.minimum.accumulate:
# Note: the accum_func comparison fails as an "is" comparison
y = values.view("i8")
- y[mask] = np.iinfo(np.int64).max
+ y[mask] = lib.i8max
changed = True
else:
y = values
diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py
index 8531f93fba321..712e9785f47f7 100644
--- a/pandas/core/sorting.py
+++ b/pandas/core/sorting.py
@@ -40,8 +40,6 @@
from pandas import MultiIndex
from pandas.core.indexes.base import Index
-_INT64_MAX = np.iinfo(np.int64).max
-
def get_indexer_indexer(
target: Index,
@@ -133,7 +131,7 @@ def _int64_cut_off(shape) -> int:
acc = 1
for i, mul in enumerate(shape):
acc *= int(mul)
- if not acc < _INT64_MAX:
+ if not acc < lib.i8max:
return i
return len(shape)
@@ -153,7 +151,7 @@ def maybe_lift(lab, size) -> tuple[np.ndarray, int]:
labels = list(labels)
# Iteratively process all the labels in chunks sized so less
- # than _INT64_MAX unique int ids will be required for each chunk
+ # than lib.i8max unique int ids will be required for each chunk
while True:
# how many levels can be done without overflow:
nlev = _int64_cut_off(lshape)
@@ -215,7 +213,7 @@ def is_int64_overflow_possible(shape) -> bool:
for x in shape:
the_prod *= int(x)
- return the_prod >= _INT64_MAX
+ return the_prod >= lib.i8max
def decons_group_index(comp_labels, shape):
diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py
index fb5002648b6a5..962728b2f38c4 100644
--- a/pandas/core/util/hashing.py
+++ b/pandas/core/util/hashing.py
@@ -14,6 +14,7 @@
import numpy as np
+from pandas._libs import lib
from pandas._libs.hashing import hash_object_array
from pandas._typing import (
ArrayLike,
@@ -244,7 +245,7 @@ def _hash_categorical(cat: Categorical, encoding: str, hash_key: str) -> np.ndar
result = np.zeros(len(mask), dtype="uint64")
if mask.any():
- result[mask] = np.iinfo(np.uint64).max
+ result[mask] = lib.u8max
return result
diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py
index 8b42bca8b8a0c..4aa2f62fe85a0 100644
--- a/pandas/tests/scalar/timedelta/test_timedelta.py
+++ b/pandas/tests/scalar/timedelta/test_timedelta.py
@@ -4,6 +4,7 @@
import numpy as np
import pytest
+from pandas._libs import lib
from pandas._libs.tslibs import (
NaT,
iNaT,
@@ -391,8 +392,7 @@ def test_round_implementation_bounds(self):
"method", [Timedelta.round, Timedelta.floor, Timedelta.ceil]
)
def test_round_sanity(self, method, n, request):
- iinfo = np.iinfo(np.int64)
- val = np.random.randint(iinfo.min + 1, iinfo.max, dtype=np.int64)
+ val = np.random.randint(iNaT + 1, lib.i8max, dtype=np.int64)
td = Timedelta(val)
assert method(td, "ns") == td
@@ -552,8 +552,8 @@ def test_implementation_limits(self):
# GH 12727
# timedelta limits correspond to int64 boundaries
- assert min_td.value == np.iinfo(np.int64).min + 1
- assert max_td.value == np.iinfo(np.int64).max
+ assert min_td.value == iNaT + 1
+ assert max_td.value == lib.i8max
# Beyond lower limit, a NAT before the Overflow
assert (min_td - Timedelta(1, "ns")) is NaT
diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py
index aab0b2e6d31ef..366c0f7cf2f74 100644
--- a/pandas/tests/scalar/timestamp/test_unary_ops.py
+++ b/pandas/tests/scalar/timestamp/test_unary_ops.py
@@ -6,11 +6,13 @@
import pytz
from pytz import utc
+from pandas._libs import lib
from pandas._libs.tslibs import (
NaT,
Timedelta,
Timestamp,
conversion,
+ iNaT,
to_offset,
)
from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
@@ -279,8 +281,7 @@ def test_round_implementation_bounds(self):
"method", [Timestamp.round, Timestamp.floor, Timestamp.ceil]
)
def test_round_sanity(self, method, n):
- iinfo = np.iinfo(np.int64)
- val = np.random.randint(iinfo.min + 1, iinfo.max, dtype=np.int64)
+ val = np.random.randint(iNaT + 1, lib.i8max, dtype=np.int64)
ts = Timestamp(val)
def checker(res, ts, nanos):
| Backport PR #41990: CI: troubleshoot py310 build | https://api.github.com/repos/pandas-dev/pandas/pulls/42019 | 2021-06-15T13:17:18Z | 2021-06-15T16:07:17Z | 2021-06-15T16:07:17Z | 2021-06-15T16:07:17Z |
Backport PR #41954 on branch 1.3.x (DOC: more cleanup of 1.3 release notes) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index dd95f9088e3da..bc75d948ba4ce 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -637,7 +637,7 @@ If installed, we now require:
+-----------------+-----------------+----------+---------+
| pytest (dev) | 6.0 | | X |
+-----------------+-----------------+----------+---------+
-| mypy (dev) | 0.800 | | X |
+| mypy (dev) | 0.812 | | X |
+-----------------+-----------------+----------+---------+
| setuptools | 38.6.0 | | X |
+-----------------+-----------------+----------+---------+
@@ -714,64 +714,6 @@ Build
Deprecations
~~~~~~~~~~~~
-- Deprecated allowing scalars to be passed to the :class:`Categorical` constructor (:issue:`38433`)
-- Deprecated constructing :class:`CategoricalIndex` without passing list-like data (:issue:`38944`)
-- Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`, :issue:`21311`, :issue:`22315`, :issue:`26974`)
-- Deprecated the :meth:`astype` method of datetimelike (``timedelta64[ns]``, ``datetime64[ns]``, ``Datetime64TZDtype``, ``PeriodDtype``) to convert to integer dtypes, use ``values.view(...)`` instead (:issue:`38544`)
-- Deprecated :meth:`MultiIndex.is_lexsorted` and :meth:`MultiIndex.lexsort_depth`, use :meth:`MultiIndex.is_monotonic_increasing` instead (:issue:`32259`)
-- Deprecated keyword ``try_cast`` in :meth:`Series.where`, :meth:`Series.mask`, :meth:`DataFrame.where`, :meth:`DataFrame.mask`; cast results manually if desired (:issue:`38836`)
-- Deprecated comparison of :class:`Timestamp` objects with ``datetime.date`` objects. Instead of e.g. ``ts <= mydate`` use ``ts <= pd.Timestamp(mydate)`` or ``ts.date() <= mydate`` (:issue:`36131`)
-- Deprecated :attr:`Rolling.win_type` returning ``"freq"`` (:issue:`38963`)
-- Deprecated :attr:`Rolling.is_datetimelike` (:issue:`38963`)
-- Deprecated :class:`DataFrame` indexer for :meth:`Series.__setitem__` and :meth:`DataFrame.__setitem__` (:issue:`39004`)
-- Deprecated :meth:`ExponentialMovingWindow.vol` (:issue:`39220`)
-- Using ``.astype`` to convert between ``datetime64[ns]`` dtype and :class:`DatetimeTZDtype` is deprecated and will raise in a future version, use ``obj.tz_localize`` or ``obj.dt.tz_localize`` instead (:issue:`38622`)
-- Deprecated casting ``datetime.date`` objects to ``datetime64`` when used as ``fill_value`` in :meth:`DataFrame.unstack`, :meth:`DataFrame.shift`, :meth:`Series.shift`, and :meth:`DataFrame.reindex`, pass ``pd.Timestamp(dateobj)`` instead (:issue:`39767`)
-- Deprecated :meth:`.Styler.set_na_rep` and :meth:`.Styler.set_precision` in favour of :meth:`.Styler.format` with ``na_rep`` and ``precision`` as existing and new input arguments respectively (:issue:`40134`, :issue:`40425`)
-- Deprecated allowing partial failure in :meth:`Series.transform` and :meth:`DataFrame.transform` when ``func`` is list-like or dict-like and raises anything but ``TypeError``; ``func`` raising anything but a ``TypeError`` will raise in a future version (:issue:`40211`)
-- Deprecated arguments ``error_bad_lines`` and ``warn_bad_lines`` in :meth:`read_csv` and :meth:`read_table` in favor of argument ``on_bad_lines`` (:issue:`15122`)
-- Deprecated support for ``np.ma.mrecords.MaskedRecords`` in the :class:`DataFrame` constructor, pass ``{name: data[name] for name in data.dtype.names}`` instead (:issue:`40363`)
-- Deprecated using :func:`merge`, :meth:`DataFrame.merge`, and :meth:`DataFrame.join` on a different number of levels (:issue:`34862`)
-- Deprecated the use of ``**kwargs`` in :class:`.ExcelWriter`; use the keyword argument ``engine_kwargs`` instead (:issue:`40430`)
-- Deprecated the ``level`` keyword for :class:`DataFrame` and :class:`Series` aggregations; use groupby instead (:issue:`39983`)
-- Deprecated the ``inplace`` parameter of :meth:`Categorical.remove_categories`, :meth:`Categorical.add_categories`, :meth:`Categorical.reorder_categories`, :meth:`Categorical.rename_categories`, :meth:`Categorical.set_categories` and will be removed in a future version (:issue:`37643`)
-- Deprecated :func:`merge` producing duplicated columns through the ``suffixes`` keyword and already existing columns (:issue:`22818`)
-- Deprecated setting :attr:`Categorical._codes`, create a new :class:`Categorical` with the desired codes instead (:issue:`40606`)
-- Deprecated the ``convert_float`` optional argument in :func:`read_excel` and :meth:`ExcelFile.parse` (:issue:`41127`)
-- Deprecated behavior of :meth:`DatetimeIndex.union` with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`)
-- Deprecated using ``usecols`` with out of bounds indices for :func:`read_csv` with ``engine="c"`` (:issue:`25623`)
-- Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`)
-- Deprecated behavior of :class:`DataFrame` constructor when a ``dtype`` is passed and the data cannot be cast to that dtype. In a future version, this will raise instead of being silently ignored (:issue:`24435`)
-- Deprecated the :attr:`Timestamp.freq` attribute. For the properties that use it (``is_month_start``, ``is_month_end``, ``is_quarter_start``, ``is_quarter_end``, ``is_year_start``, ``is_year_end``), when you have a ``freq``, use e.g. ``freq.is_month_start(ts)`` (:issue:`15146`)
-- Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`, :issue:`33401`)
-- Deprecated behavior of :class:`Series` construction with large-integer values and small-integer dtype silently overflowing; use ``Series(data).astype(dtype)`` instead (:issue:`41734`)
-- Deprecated behavior of :class:`DataFrame` construction with floating data and integer dtype casting even when lossy; in a future version this will remain floating, matching :class:`Series` behavior (:issue:`41770`)
-- Deprecated inference of ``timedelta64[ns]``, ``datetime64[ns]``, or ``DatetimeTZDtype`` dtypes in :class:`Series` construction when data containing strings is passed and no ``dtype`` is passed (:issue:`33558`)
-- In a future version, constructing :class:`Series` or :class:`DataFrame` with ``datetime64[ns]`` data and ``DatetimeTZDtype`` will treat the data as wall-times instead of as UTC times (matching DatetimeIndex behavior). To treat the data as UTC times, use ``pd.Series(data).dt.tz_localize("UTC").dt.tz_convert(dtype.tz)`` or ``pd.Series(data.view("int64"), dtype=dtype)`` (:issue:`33401`)
-- Deprecated passing lists as ``key`` to :meth:`DataFrame.xs` and :meth:`Series.xs` (:issue:`41760`)
-- Deprecated passing arguments as positional for all of the following, with exceptions noted (:issue:`41485`):
- - :func:`concat` (other than ``objs``)
- - :func:`read_csv` (other than ``filepath_or_buffer``)
- - :func:`read_table` (other than ``filepath_or_buffer``)
- - :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``upper`` and ``lower``)
- - :meth:`DataFrame.drop_duplicates` (except for ``subset``), :meth:`Series.drop_duplicates`, :meth:`Index.drop_duplicates` and :meth:`MultiIndex.drop_duplicates`
- - :meth:`DataFrame.drop` (other than ``labels``) and :meth:`Series.drop`
- - :meth:`DataFrame.dropna` and :meth:`Series.dropna`
- - :meth:`DataFrame.ffill`, :meth:`Series.ffill`, :meth:`DataFrame.bfill`, and :meth:`Series.bfill`
- - :meth:`DataFrame.fillna` and :meth:`Series.fillna` (apart from ``value``)
- - :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (other than ``method``)
- - :meth:`DataFrame.mask` and :meth:`Series.mask` (other than ``cond`` and ``other``)
- - :meth:`DataFrame.reset_index` (other than ``level``) and :meth:`Series.reset_index`
- - :meth:`DataFrame.set_axis` and :meth:`Series.set_axis` (other than ``labels``)
- - :meth:`DataFrame.set_index` (other than ``keys``)
- - :meth:`DataFrame.sort_index` and :meth:`Series.sort_index`
- - :meth:`DataFrame.sort_values` (other than ``by``) and :meth:`Series.sort_values`
- - :meth:`DataFrame.where` and :meth:`Series.where` (other than ``cond`` and ``other``)
- - :meth:`Index.set_names` and :meth:`MultiIndex.set_names` (except for ``names``)
- - :meth:`MultiIndex.codes` (except for ``codes``)
- - :meth:`MultiIndex.set_levels` (except for ``levels``)
- - :meth:`Resampler.interpolate` (other than ``method``)
-
.. _whatsnew_130.deprecations.nuisance_columns:
@@ -852,6 +794,70 @@ For example:
1 2
2 12
+.. _whatsnew_130.deprecations.other:
+
+Other Deprecations
+^^^^^^^^^^^^^^^^^^
+- Deprecated allowing scalars to be passed to the :class:`Categorical` constructor (:issue:`38433`)
+- Deprecated constructing :class:`CategoricalIndex` without passing list-like data (:issue:`38944`)
+- Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`, :issue:`21311`, :issue:`22315`, :issue:`26974`)
+- Deprecated the :meth:`astype` method of datetimelike (``timedelta64[ns]``, ``datetime64[ns]``, ``Datetime64TZDtype``, ``PeriodDtype``) to convert to integer dtypes, use ``values.view(...)`` instead (:issue:`38544`)
+- Deprecated :meth:`MultiIndex.is_lexsorted` and :meth:`MultiIndex.lexsort_depth`, use :meth:`MultiIndex.is_monotonic_increasing` instead (:issue:`32259`)
+- Deprecated keyword ``try_cast`` in :meth:`Series.where`, :meth:`Series.mask`, :meth:`DataFrame.where`, :meth:`DataFrame.mask`; cast results manually if desired (:issue:`38836`)
+- Deprecated comparison of :class:`Timestamp` objects with ``datetime.date`` objects. Instead of e.g. ``ts <= mydate`` use ``ts <= pd.Timestamp(mydate)`` or ``ts.date() <= mydate`` (:issue:`36131`)
+- Deprecated :attr:`Rolling.win_type` returning ``"freq"`` (:issue:`38963`)
+- Deprecated :attr:`Rolling.is_datetimelike` (:issue:`38963`)
+- Deprecated :class:`DataFrame` indexer for :meth:`Series.__setitem__` and :meth:`DataFrame.__setitem__` (:issue:`39004`)
+- Deprecated :meth:`ExponentialMovingWindow.vol` (:issue:`39220`)
+- Using ``.astype`` to convert between ``datetime64[ns]`` dtype and :class:`DatetimeTZDtype` is deprecated and will raise in a future version, use ``obj.tz_localize`` or ``obj.dt.tz_localize`` instead (:issue:`38622`)
+- Deprecated casting ``datetime.date`` objects to ``datetime64`` when used as ``fill_value`` in :meth:`DataFrame.unstack`, :meth:`DataFrame.shift`, :meth:`Series.shift`, and :meth:`DataFrame.reindex`, pass ``pd.Timestamp(dateobj)`` instead (:issue:`39767`)
+- Deprecated :meth:`.Styler.set_na_rep` and :meth:`.Styler.set_precision` in favour of :meth:`.Styler.format` with ``na_rep`` and ``precision`` as existing and new input arguments respectively (:issue:`40134`, :issue:`40425`)
+- Deprecated allowing partial failure in :meth:`Series.transform` and :meth:`DataFrame.transform` when ``func`` is list-like or dict-like and raises anything but ``TypeError``; ``func`` raising anything but a ``TypeError`` will raise in a future version (:issue:`40211`)
+- Deprecated arguments ``error_bad_lines`` and ``warn_bad_lines`` in :meth:`read_csv` and :meth:`read_table` in favor of argument ``on_bad_lines`` (:issue:`15122`)
+- Deprecated support for ``np.ma.mrecords.MaskedRecords`` in the :class:`DataFrame` constructor, pass ``{name: data[name] for name in data.dtype.names}`` instead (:issue:`40363`)
+- Deprecated using :func:`merge`, :meth:`DataFrame.merge`, and :meth:`DataFrame.join` on a different number of levels (:issue:`34862`)
+- Deprecated the use of ``**kwargs`` in :class:`.ExcelWriter`; use the keyword argument ``engine_kwargs`` instead (:issue:`40430`)
+- Deprecated the ``level`` keyword for :class:`DataFrame` and :class:`Series` aggregations; use groupby instead (:issue:`39983`)
+- Deprecated the ``inplace`` parameter of :meth:`Categorical.remove_categories`, :meth:`Categorical.add_categories`, :meth:`Categorical.reorder_categories`, :meth:`Categorical.rename_categories`, :meth:`Categorical.set_categories` and will be removed in a future version (:issue:`37643`)
+- Deprecated :func:`merge` producing duplicated columns through the ``suffixes`` keyword and already existing columns (:issue:`22818`)
+- Deprecated setting :attr:`Categorical._codes`, create a new :class:`Categorical` with the desired codes instead (:issue:`40606`)
+- Deprecated the ``convert_float`` optional argument in :func:`read_excel` and :meth:`ExcelFile.parse` (:issue:`41127`)
+- Deprecated behavior of :meth:`DatetimeIndex.union` with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`)
+- Deprecated using ``usecols`` with out of bounds indices for :func:`read_csv` with ``engine="c"`` (:issue:`25623`)
+- Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`)
+- Deprecated behavior of :class:`DataFrame` constructor when a ``dtype`` is passed and the data cannot be cast to that dtype. In a future version, this will raise instead of being silently ignored (:issue:`24435`)
+- Deprecated the :attr:`Timestamp.freq` attribute. For the properties that use it (``is_month_start``, ``is_month_end``, ``is_quarter_start``, ``is_quarter_end``, ``is_year_start``, ``is_year_end``), when you have a ``freq``, use e.g. ``freq.is_month_start(ts)`` (:issue:`15146`)
+- Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`, :issue:`33401`)
+- Deprecated behavior of :class:`Series` construction with large-integer values and small-integer dtype silently overflowing; use ``Series(data).astype(dtype)`` instead (:issue:`41734`)
+- Deprecated behavior of :class:`DataFrame` construction with floating data and integer dtype casting even when lossy; in a future version this will remain floating, matching :class:`Series` behavior (:issue:`41770`)
+- Deprecated inference of ``timedelta64[ns]``, ``datetime64[ns]``, or ``DatetimeTZDtype`` dtypes in :class:`Series` construction when data containing strings is passed and no ``dtype`` is passed (:issue:`33558`)
+- In a future version, constructing :class:`Series` or :class:`DataFrame` with ``datetime64[ns]`` data and ``DatetimeTZDtype`` will treat the data as wall-times instead of as UTC times (matching DatetimeIndex behavior). To treat the data as UTC times, use ``pd.Series(data).dt.tz_localize("UTC").dt.tz_convert(dtype.tz)`` or ``pd.Series(data.view("int64"), dtype=dtype)`` (:issue:`33401`)
+- Deprecated passing lists as ``key`` to :meth:`DataFrame.xs` and :meth:`Series.xs` (:issue:`41760`)
+- Deprecated passing arguments as positional for all of the following, with exceptions noted (:issue:`41485`):
+
+ - :func:`concat` (other than ``objs``)
+ - :func:`read_csv` (other than ``filepath_or_buffer``)
+ - :func:`read_table` (other than ``filepath_or_buffer``)
+ - :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``upper`` and ``lower``)
+ - :meth:`DataFrame.drop_duplicates` (except for ``subset``), :meth:`Series.drop_duplicates`, :meth:`Index.drop_duplicates` and :meth:`MultiIndex.drop_duplicates`
+ - :meth:`DataFrame.drop` (other than ``labels``) and :meth:`Series.drop`
+ - :meth:`DataFrame.dropna` and :meth:`Series.dropna`
+ - :meth:`DataFrame.ffill`, :meth:`Series.ffill`, :meth:`DataFrame.bfill`, and :meth:`Series.bfill`
+ - :meth:`DataFrame.fillna` and :meth:`Series.fillna` (apart from ``value``)
+ - :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (other than ``method``)
+ - :meth:`DataFrame.mask` and :meth:`Series.mask` (other than ``cond`` and ``other``)
+ - :meth:`DataFrame.reset_index` (other than ``level``) and :meth:`Series.reset_index`
+ - :meth:`DataFrame.set_axis` and :meth:`Series.set_axis` (other than ``labels``)
+ - :meth:`DataFrame.set_index` (other than ``keys``)
+ - :meth:`DataFrame.sort_index` and :meth:`Series.sort_index`
+ - :meth:`DataFrame.sort_values` (other than ``by``) and :meth:`Series.sort_values`
+ - :meth:`DataFrame.where` and :meth:`Series.where` (other than ``cond`` and ``other``)
+ - :meth:`Index.set_names` and :meth:`MultiIndex.set_names` (except for ``names``)
+ - :meth:`MultiIndex.codes` (except for ``codes``)
+ - :meth:`MultiIndex.set_levels` (except for ``levels``)
+ - :meth:`Resampler.interpolate` (other than ``method``)
+
+
.. ---------------------------------------------------------------------------
| Backport PR #41954: DOC: more cleanup of 1.3 release notes | https://api.github.com/repos/pandas-dev/pandas/pulls/42018 | 2021-06-15T13:11:26Z | 2021-06-15T14:54:58Z | 2021-06-15T14:54:58Z | 2021-06-15T14:54:59Z |
DOC: Fix wrongly associated docstring of Series.str.isspace | diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 323cb6bd9fedd..d3cdcec9da8f1 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -3005,7 +3005,7 @@ def casefold(self):
"isdigit", docstring=_shared_docs["ismethods"] % _doc_args["isdigit"]
)
isspace = _map_and_wrap(
- "isspace", docstring=_shared_docs["ismethods"] % _doc_args["isalnum"]
+ "isspace", docstring=_shared_docs["ismethods"] % _doc_args["isspace"]
)
islower = _map_and_wrap(
"islower", docstring=_shared_docs["ismethods"] % _doc_args["islower"]
| cc @simonjayhawkins
- [ ] closes #42015
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/42017 | 2021-06-15T11:11:25Z | 2021-06-15T22:40:31Z | 2021-06-15T22:40:31Z | 2021-06-16T11:09:48Z |
BUG: `Styler.apply` consistently manages Series return objects aligning labels. | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 84fdc4600dc63..74f69ef73b822 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -365,6 +365,8 @@ Styler
- Minor bug in :class:`.Styler` where the ``uuid`` at initialization maintained a floating underscore (:issue:`43037`)
- Bug in :meth:`.Styler.to_html` where the ``Styler`` object was updated if the ``to_html`` method was called with some args (:issue:`43034`)
- Bug in :meth:`.Styler.copy` where ``uuid`` was not previously copied (:issue:`40675`)
+- Bug in :meth:`Styler.apply` where functions which returned Series objects were not correctly handled in terms of aligning their index labels (:issue:`13657`, :issue:`42014`)
+-
Other
^^^^^
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index eff0bd9637859..81bd14629cfd3 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -1024,7 +1024,7 @@ def _update_ctx(self, attrs: DataFrame) -> None:
for cn in attrs.columns:
for rn, c in attrs[[cn]].itertuples():
- if not c:
+ if not c or pd.isna(c):
continue
css_list = maybe_convert_css_to_tuples(c)
i, j = self.index.get_loc(rn), self.columns.get_loc(cn)
@@ -1148,9 +1148,10 @@ def _apply(
subset = slice(None) if subset is None else subset
subset = non_reducing_slice(subset)
data = self.data.loc[subset]
- if axis is not None:
- result = data.apply(func, axis=axis, result_type="expand", **kwargs)
- result.columns = data.columns
+ if axis in [0, "index"]:
+ result = data.apply(func, axis=0, **kwargs)
+ elif axis in [1, "columns"]:
+ result = data.T.apply(func, axis=0, **kwargs).T # see GH 42005
else:
result = func(data, **kwargs)
if not isinstance(result, DataFrame):
@@ -1166,19 +1167,28 @@ def _apply(
f"Expected shape: {data.shape}"
)
result = DataFrame(result, index=data.index, columns=data.columns)
- elif not (
- result.index.equals(data.index) and result.columns.equals(data.columns)
- ):
- raise ValueError(
- f"Result of {repr(func)} must have identical "
- f"index and columns as the input"
- )
- if result.shape != data.shape:
+ if isinstance(result, Series):
raise ValueError(
- f"Function {repr(func)} returned the wrong shape.\n"
- f"Result has shape: {result.shape}\n"
- f"Expected shape: {data.shape}"
+ f"Function {repr(func)} resulted in the apply method collapsing to a "
+ f"Series.\nUsually, this is the result of the function returning a "
+ f"single value, instead of list-like."
+ )
+ msg = (
+ f"Function {repr(func)} created invalid {{0}} labels.\nUsually, this is "
+ f"the result of the function returning a "
+ f"{'Series' if axis is not None else 'DataFrame'} which contains invalid "
+ f"labels, or returning an incorrectly shaped, list-like object which "
+ f"cannot be mapped to labels, possibly due to applying the function along "
+ f"the wrong axis.\n"
+ f"Result {{0}} has shape: {{1}}\n"
+ f"Expected {{0}} shape: {{2}}"
+ )
+ if not all(result.index.isin(data.index)):
+ raise ValueError(msg.format("index", result.index.shape, data.index.shape))
+ if not all(result.columns.isin(data.columns)):
+ raise ValueError(
+ msg.format("columns", result.columns.shape, data.columns.shape)
)
self._update_ctx(result)
return self
@@ -1198,14 +1208,17 @@ def apply(
Parameters
----------
func : function
- ``func`` should take a Series if ``axis`` in [0,1] and return an object
- of same length, also with identical index if the object is a Series.
+ ``func`` should take a Series if ``axis`` in [0,1] and return a list-like
+ object of same length, or a Series, not necessarily of same length, with
+ valid index labels considering ``subset``.
``func`` should take a DataFrame if ``axis`` is ``None`` and return either
- an ndarray with the same shape or a DataFrame with identical columns and
- index.
+ an ndarray with the same shape or a DataFrame, not necessarily of the same
+ shape, with valid index and columns labels considering ``subset``.
.. versionchanged:: 1.3.0
+ .. versionchanged:: 1.4.0
+
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
@@ -1260,6 +1273,13 @@ def apply(
>>> df.style.apply(highlight_max, color='red', subset=(slice(0,5,2), "A"))
... # doctest: +SKIP
+ Using a function which returns a Series / DataFrame of unequal length but
+ containing valid index labels
+
+ >>> df = pd.DataFrame([[1, 2], [3, 4], [4, 6]], index=["A1", "A2", "Total"])
+ >>> total_style = pd.Series("font-weight: bold;", index=["Total"])
+ >>> df.style.apply(lambda s: total_style) # doctest: +SKIP
+
See `Table Visualization <../../user_guide/style.ipynb>`_ user guide for
more details.
"""
diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py
index a69d65a57bca0..5022a1eaa2c6e 100644
--- a/pandas/tests/io/formats/style/test_style.py
+++ b/pandas/tests/io/formats/style/test_style.py
@@ -550,6 +550,40 @@ def test_apply_axis(self):
result._compute()
assert result.ctx == expected
+ @pytest.mark.parametrize("axis", [0, 1])
+ def test_apply_series_return(self, axis):
+ # GH 42014
+ df = DataFrame([[1, 2], [3, 4]], index=["X", "Y"], columns=["X", "Y"])
+
+ # test Series return where len(Series) < df.index or df.columns but labels OK
+ func = lambda s: pd.Series(["color: red;"], index=["Y"])
+ result = df.style.apply(func, axis=axis)._compute().ctx
+ assert result[(1, 1)] == [("color", "red")]
+ assert result[(1 - axis, axis)] == [("color", "red")]
+
+ # test Series return where labels align but different order
+ func = lambda s: pd.Series(["color: red;", "color: blue;"], index=["Y", "X"])
+ result = df.style.apply(func, axis=axis)._compute().ctx
+ assert result[(0, 0)] == [("color", "blue")]
+ assert result[(1, 1)] == [("color", "red")]
+ assert result[(1 - axis, axis)] == [("color", "red")]
+ assert result[(axis, 1 - axis)] == [("color", "blue")]
+
+ @pytest.mark.parametrize("index", [False, True])
+ @pytest.mark.parametrize("columns", [False, True])
+ def test_apply_dataframe_return(self, index, columns):
+ # GH 42014
+ df = DataFrame([[1, 2], [3, 4]], index=["X", "Y"], columns=["X", "Y"])
+ idxs = ["X", "Y"] if index else ["Y"]
+ cols = ["X", "Y"] if columns else ["Y"]
+ df_styles = DataFrame("color: red;", index=idxs, columns=cols)
+ result = df.style.apply(lambda x: df_styles, axis=None)._compute().ctx
+
+ assert result[(1, 1)] == [("color", "red")] # (Y,Y) styles always present
+ assert (result[(0, 1)] == [("color", "red")]) is index # (X,Y) only if index
+ assert (result[(1, 0)] == [("color", "red")]) is columns # (Y,X) only if cols
+ assert (result[(0, 0)] == [("color", "red")]) is (index and columns) # (X,X)
+
@pytest.mark.parametrize(
"slice_",
[
@@ -794,24 +828,28 @@ def test_export(self):
style2.to_html()
def test_bad_apply_shape(self):
- df = DataFrame([[1, 2], [3, 4]])
- msg = "returned the wrong shape"
- with pytest.raises(ValueError, match=msg):
- df.style._apply(lambda x: "x", subset=pd.IndexSlice[[0, 1], :])
+ df = DataFrame([[1, 2], [3, 4]], index=["A", "B"], columns=["X", "Y"])
+ msg = "resulted in the apply method collapsing to a Series."
with pytest.raises(ValueError, match=msg):
- df.style._apply(lambda x: [""], subset=pd.IndexSlice[[0, 1], :])
+ df.style._apply(lambda x: "x")
- with pytest.raises(ValueError, match=msg):
+ msg = "created invalid {} labels"
+ with pytest.raises(ValueError, match=msg.format("index")):
+ df.style._apply(lambda x: [""])
+
+ with pytest.raises(ValueError, match=msg.format("index")):
df.style._apply(lambda x: ["", "", "", ""])
- with pytest.raises(ValueError, match=msg):
- df.style._apply(lambda x: ["", "", ""], subset=1)
+ with pytest.raises(ValueError, match=msg.format("index")):
+ df.style._apply(lambda x: pd.Series(["a:v;", ""], index=["A", "C"]), axis=0)
- msg = "Length mismatch: Expected axis has 3 elements"
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(ValueError, match=msg.format("columns")):
df.style._apply(lambda x: ["", "", ""], axis=1)
+ with pytest.raises(ValueError, match=msg.format("columns")):
+ df.style._apply(lambda x: pd.Series(["a:v;", ""], index=["X", "Z"]), axis=1)
+
msg = "returned ndarray with wrong shape"
with pytest.raises(ValueError, match=msg):
df.style._apply(lambda x: np.array([[""], [""]]), axis=None)
@@ -828,12 +866,13 @@ def f(x):
with pytest.raises(TypeError, match=msg):
df.style._apply(f, axis=None)
- def test_apply_bad_labels(self):
+ @pytest.mark.parametrize("axis", ["index", "columns"])
+ def test_apply_bad_labels(self, axis):
def f(x):
- return DataFrame(index=[1, 2], columns=["a", "b"])
+ return DataFrame(**{axis: ["bad", "labels"]})
df = DataFrame([[1, 2], [3, 4]])
- msg = "must have identical index and columns as the input"
+ msg = f"created invalid {axis} labels."
with pytest.raises(ValueError, match=msg):
df.style._apply(f, axis=None)
| - [x] closes #13657
This issue is due to the asymmetric application of `DataFrame.apply` (#42005).
**The bug** is that when using `Styler.apply` the treatment of Series return objects is applied for `axis=0` and overwritten for `axis=1`.
```python
df = pd.DataFrame([[1,2],[3,4]], index=["X", "Y"], columns=["X", "Y"])
s = df.style
def series_ret(s):
return pd.Series(["color:red;", "color:blue;"], index=["Y", "X"]) # note X-Y order
```
| Command | Current Behaviour | New Behaviour |
| ------------ | ------------------------- | ---------------------- |
| `s.apply(series_ret, axis=0)` | ![][image5] | ![][image5] |
| `s.apply(series_ret, axis=1)` | ![][image6] | ![][image7] |
Also the application has been expanded to **allow** (for axis=0 | 1) Series return objects that are **not** the same size, or (for axis=None) DataFrame return objects that are **not** the same size, if they contain only relevant index labels. This allows for more flexible user defined functions. Potentially it also increases performance by not having to loop over labels that no longer exist.
```python
def series_ret(s):
return pd.Series(["color:red;"], index=["Y"]) # note only returning 1 element
def array_ret(s):
return ["color:red;"]
def ser_no_idx_ret(s):
return pd.Series(["color:red;", "color:blue;"]) # note returning a Series of right shape with no index
```
| Command | Current Behaviour | New Behaviour |
| ------------ | ------------------------- | ---------------------- |
| `s.apply(series_ret, axis=0)` | `ValueError: Function returned the wrong shape.` | ![][image1] |
| `s.apply(series_ret, axis=1)` | `ValueError: Length mismatch: Expected axis has 1 elements, new values have 2 elements` | ![][image2] |
| `s.apply(array_ret, axis=0)` | `ValueError: Function returned the wrong shape.` | `ValueError: Function created invalid index labels. Usually, this is the result of the function returning a Series which contains invalid labels, or returning an incorrectly shaped, list-like object which cannot be mapped to labels, possibly due to applying the function along the wrong axis.` |
| `s.apply(array_ret, axis=1)` |`ValueError: Length mismatch: Expected axis has 1 elements, new values have 2 elements` |`ValueError: Function created invalid index labels. Usually, this is the result of the function returning a Series which contains invalid labels, or returning an incorrectly shaped, list-like object which cannot be mapped to labels, possibly due to applying the function along the wrong axis.` |
| `s.apply(ser_no_idx_ret, axis=0)` | `KeyError: 0` | `ValueError: Function created invalid index labels. Usually, this is the result of the function returning a Series which contains invalid labels, or returning an incorrectly shaped, list-like object which cannot be mapped to labels, possibly due to applying the function along the wrong axis.` |
| `s.apply(ser_no_idx_ret, axis=1)` | ![][image6] |`ValueError: Function created invalid index labels. Usually, this is the result of the function returning a Series which contains invalid labels, or returning an incorrectly shaped, list-like object which cannot be mapped to labels, possibly due to applying the function along the wrong axis.` |
Note all errors do report the shapes, I just didn't include in the table for brevity.
### Edge Cases
The edge case here is that if a user has a DataFrame with a default range index (or a DataFrame with some indexes the same as those in default, e.g. 0 or 1) then even returning arrays of the wrong size may work, since `DataFrame.apply` assigns them to a RangeIndex.
To be consistent with the above this should raise, but it is impossible to hook into the return value of the user-defined function and determine if it is a Series (where non-matching shapes are OK) or list-like (where matching shapes should be enforced)
```python
df = pd.DataFrame([[1,2],[3,4]])
s = df.style
```
| Command | Current Behaviour | New Behaviour |
| ------------ | ------------------------- | ---------------------- |
| `s.apply(array_ret, axis=0)` | `ValueError: Function returned the wrong shape.` | ![][image3] |
| `s.apply(array_ret, axis=1)` | `ValueError: Length mismatch: Expected axis has 1 elements, new values have 2 elements` | ![][image4] |
### ASV
Benchmarks unchanged.
[image1]: https://user-images.githubusercontent.com/24256554/122002332-e59b5580-cdb1-11eb-85c2-993c7e20bdfc.png
[image2]: https://user-images.githubusercontent.com/24256554/122002344-e9c77300-cdb1-11eb-8a01-f50ec660b300.png
[image3]: https://user-images.githubusercontent.com/24256554/122004954-57c16980-cdb5-11eb-8ba4-ec14b1a6b06f.png
[image4]: https://user-images.githubusercontent.com/24256554/122005013-69a30c80-cdb5-11eb-900c-0d4be813cb58.png
[image5]: https://user-images.githubusercontent.com/24256554/122006522-3497b980-cdb7-11eb-892e-f34c80e3c7ff.png
[image6]: https://user-images.githubusercontent.com/24256554/122006532-36fa1380-cdb7-11eb-8b08-f89d6991536c.png
[image7]: https://user-images.githubusercontent.com/24256554/122006816-93f5c980-cdb7-11eb-8aff-09b658c594d9.png
| https://api.github.com/repos/pandas-dev/pandas/pulls/42014 | 2021-06-15T07:22:49Z | 2021-08-19T21:41:49Z | 2021-08-19T21:41:49Z | 2021-08-20T05:31:08Z |
Backport PR #41971 on branch 1.3.x (CI: mark window online test slow) | diff --git a/pandas/tests/window/test_online.py b/pandas/tests/window/test_online.py
index c7580650926da..461c62c07326d 100644
--- a/pandas/tests/window/test_online.py
+++ b/pandas/tests/window/test_online.py
@@ -22,6 +22,7 @@ def test_invalid_update(self):
):
online_ewm.mean(update=df.head(1))
+ @pytest.mark.slow
@pytest.mark.parametrize(
"obj", [DataFrame({"a": range(5), "b": range(5)}), Series(range(5), name="foo")]
)
| Backport PR #41971: CI: mark window online test slow | https://api.github.com/repos/pandas-dev/pandas/pulls/42010 | 2021-06-15T01:12:58Z | 2021-06-15T10:10:22Z | 2021-06-15T10:10:22Z | 2021-06-15T10:10:23Z |
ENH: Clarify error message when reindexing fails (#42000) | diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst
index dc66303a44f53..862aef8ceab34 100644
--- a/doc/source/user_guide/indexing.rst
+++ b/doc/source/user_guide/indexing.rst
@@ -701,7 +701,7 @@ Having a duplicated index will raise for a ``.reindex()``:
.. code-block:: ipython
In [17]: s.reindex(labels)
- ValueError: cannot reindex from a duplicate axis
+ ValueError: cannot reindex on an axis with duplicate labels
Generally, you can intersect the desired labels with the current
axis, and then reindex.
@@ -717,7 +717,7 @@ However, this would *still* raise if your resulting index is duplicated.
In [41]: labels = ['a', 'd']
In [42]: s.loc[s.index.intersection(labels)].reindex(labels)
- ValueError: cannot reindex from a duplicate axis
+ ValueError: cannot reindex on an axis with duplicate labels
.. _indexing.basics.partial_setting:
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 4de95079f6480..ec58a0487c5f6 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -3715,7 +3715,7 @@ def _validate_can_reindex(self, indexer: np.ndarray) -> None:
"""
# trying to reindex on an axis with duplicates
if not self._index_as_unique and len(indexer):
- raise ValueError("cannot reindex from a duplicate axis")
+ raise ValueError("cannot reindex on an axis with duplicate labels")
def reindex(
self, target, method=None, level=None, limit=None, tolerance=None
diff --git a/pandas/tests/frame/indexing/test_getitem.py b/pandas/tests/frame/indexing/test_getitem.py
index 073e7b0357124..71e8f84b4ad01 100644
--- a/pandas/tests/frame/indexing/test_getitem.py
+++ b/pandas/tests/frame/indexing/test_getitem.py
@@ -299,7 +299,7 @@ def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self, df_dup_col
# boolean with the duplicate raises
df = df_dup_cols
- msg = "cannot reindex from a duplicate axis"
+ msg = "cannot reindex on an axis with duplicate labels"
with pytest.raises(ValueError, match=msg):
df[df.A > 6]
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 62d7535159f13..25682330fe19a 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -68,7 +68,7 @@ def test_setitem_error_msmgs(self):
index=Index(["a", "b", "c", "a"], name="foo"),
name="fiz",
)
- msg = "cannot reindex from a duplicate axis"
+ msg = "cannot reindex on an axis with duplicate labels"
with pytest.raises(ValueError, match=msg):
df["newcol"] = ser
diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py
index 84992982a104a..d0765084adfa9 100644
--- a/pandas/tests/frame/methods/test_reindex.py
+++ b/pandas/tests/frame/methods/test_reindex.py
@@ -658,7 +658,7 @@ def test_reindex_dups(self):
tm.assert_frame_equal(result, expected)
# reindex fails
- msg = "cannot reindex from a duplicate axis"
+ msg = "cannot reindex on an axis with duplicate labels"
with pytest.raises(ValueError, match=msg):
df.reindex(index=list(range(len(df))))
@@ -668,7 +668,7 @@ def test_reindex_with_duplicate_columns(self):
df = DataFrame(
[[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"]
)
- msg = "cannot reindex from a duplicate axis"
+ msg = "cannot reindex on an axis with duplicate labels"
with pytest.raises(ValueError, match=msg):
df.reindex(columns=["bar"])
with pytest.raises(ValueError, match=msg):
@@ -942,7 +942,7 @@ def test_reindex_with_categoricalindex(self):
index=CategoricalIndex(list("aabbca"), dtype=CDT(list("cabe")), name="B"),
)
# passed duplicate indexers are not allowed
- msg = "cannot reindex from a duplicate axis"
+ msg = "cannot reindex on an axis with duplicate labels"
with pytest.raises(ValueError, match=msg):
df2.reindex(["a", "b"])
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index 5594659fb4b03..318289a51f781 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -692,7 +692,7 @@ def test_asfreq_non_unique():
rng2 = rng.repeat(2).values
ts = Series(np.random.randn(len(rng2)), index=rng2)
- msg = "cannot reindex from a duplicate axis"
+ msg = "cannot reindex on an axis with duplicate labels"
with pytest.raises(ValueError, match=msg):
ts.asfreq("B")
| - [x] closes #42000
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/42007 | 2021-06-14T18:41:30Z | 2021-06-16T09:34:33Z | 2021-06-16T09:34:33Z | 2021-06-16T09:34:44Z |
DEP: move pkg_resources back inline in function (delayed import) | diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index 00d87b707580d..302d5ede0ae86 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -7,8 +7,6 @@
Sequence,
)
-import pkg_resources
-
from pandas._config import get_option
from pandas._typing import IndexLabel
@@ -1745,6 +1743,8 @@ def _load_backend(backend: str) -> types.ModuleType:
types.ModuleType
The imported backend.
"""
+ import pkg_resources
+
if backend == "matplotlib":
# Because matplotlib is an optional dependency and first-party backend,
# we need to attempt an import here to raise an ImportError if needed.
| xref https://github.com/pandas-dev/pandas/issues/40169#issuecomment-860900794, fixup of #41503 | https://api.github.com/repos/pandas-dev/pandas/pulls/42006 | 2021-06-14T18:36:09Z | 2021-06-15T23:52:54Z | 2021-06-15T23:52:54Z | 2021-06-15T23:53:08Z |
Backport PR #41987 on branch 1.3.x (TST: Un-xfail tests on numpy-dev) | diff --git a/pandas/tests/frame/methods/test_to_records.py b/pandas/tests/frame/methods/test_to_records.py
index ba8fe25401e8c..2c96cf291c154 100644
--- a/pandas/tests/frame/methods/test_to_records.py
+++ b/pandas/tests/frame/methods/test_to_records.py
@@ -3,8 +3,6 @@
import numpy as np
import pytest
-from pandas.compat import is_numpy_dev
-
from pandas import (
CategoricalDtype,
DataFrame,
@@ -173,28 +171,20 @@ def test_to_records_with_categorical(self):
),
),
# Pass in a type instance.
- pytest.param(
+ (
{"column_dtypes": str},
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
dtype=[("index", "<i8"), ("A", "<U"), ("B", "<U"), ("C", "<U")],
),
- marks=pytest.mark.xfail(
- is_numpy_dev,
- reason="https://github.com/numpy/numpy/issues/19078",
- ),
),
# Pass in a dtype instance.
- pytest.param(
+ (
{"column_dtypes": np.dtype("unicode")},
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
dtype=[("index", "<i8"), ("A", "<U"), ("B", "<U"), ("C", "<U")],
),
- marks=pytest.mark.xfail(
- is_numpy_dev,
- reason="https://github.com/numpy/numpy/issues/19078",
- ),
),
# Pass in a dictionary (name-only).
(
| Backport PR #41987: TST: Un-xfail tests on numpy-dev | https://api.github.com/repos/pandas-dev/pandas/pulls/42004 | 2021-06-14T16:32:22Z | 2021-06-15T00:39:50Z | 2021-06-15T00:39:50Z | 2021-06-15T00:39:50Z |
ENH: `Styler.apply(map)_index` made compatible with `Styler.to_excel` | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 964f4b83866c9..0632387bd19b7 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -72,8 +72,8 @@ Styler
:class:`.Styler` has been further developed in 1.4.0. The following enhancements have been made:
- - Styling and formatting of indexes has been added, with :meth:`.Styler.apply_index`, :meth:`.Styler.applymap_index` and :meth:`.Styler.format_index`. These mirror the signature of the methods already used to style and format data values, and work with both HTML and LaTeX format (:issue:`41893`, :issue:`43101`).
- - :meth:`.Styler.bar` introduces additional arguments to control alignment, display and colors (:issue:`26070`, :issue:`36419`, :issue:`43662`), and it also validates the input arguments ``width`` and ``height`` (:issue:`42511`).
+ - Styling and formatting of indexes has been added, with :meth:`.Styler.apply_index`, :meth:`.Styler.applymap_index` and :meth:`.Styler.format_index`. These mirror the signature of the methods already used to style and format data values, and work with both HTML, LaTeX and Excel format (:issue:`41893`, :issue:`43101`, :issue:`41993`, :issue:`41995`).
+ - :meth:`.Styler.bar` introduces additional arguments to control alignment and display (:issue:`26070`, :issue:`36419`), and it also validates the input arguments ``width`` and ``height`` (:issue:`42511`).
- :meth:`.Styler.to_latex` introduces keyword argument ``environment``, which also allows a specific "longtable" entry through a separate jinja2 template (:issue:`41866`).
- :meth:`.Styler.to_html` introduces keyword arguments ``sparse_index``, ``sparse_columns``, ``bold_headers``, ``caption``, ``max_rows`` and ``max_columns`` (:issue:`41946`, :issue:`43149`, :issue:`42972`).
- Keyword arguments ``level`` and ``names`` added to :meth:`.Styler.hide_index` and :meth:`.Styler.hide_columns` for additional control of visibility of MultiIndexes and index names (:issue:`25475`, :issue:`43404`, :issue:`43346`)
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index 0c625e8a68db0..7f2905d9a63b9 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -7,6 +7,7 @@
import itertools
import re
from typing import (
+ Any,
Callable,
Hashable,
Iterable,
@@ -70,6 +71,26 @@ def __init__(
self.mergeend = mergeend
+class CssExcelCell(ExcelCell):
+ def __init__(
+ self,
+ row: int,
+ col: int,
+ val,
+ style: dict | None,
+ css_styles: dict[tuple[int, int], list[tuple[str, Any]]] | None,
+ css_row: int,
+ css_col: int,
+ css_converter: Callable | None,
+ **kwargs,
+ ):
+ if css_styles and css_converter:
+ css = ";".join(a + ":" + str(v) for (a, v) in css_styles[css_row, css_col])
+ style = css_converter(css)
+
+ return super().__init__(row=row, col=col, val=val, style=style, **kwargs)
+
+
class CSSToExcelConverter:
"""
A callable for converting CSS declarations to ExcelWriter styles
@@ -472,12 +493,14 @@ def __init__(
self.na_rep = na_rep
if not isinstance(df, DataFrame):
self.styler = df
+ self.styler._compute() # calculate applied styles
df = df.data
if style_converter is None:
style_converter = CSSToExcelConverter()
- self.style_converter = style_converter
+ self.style_converter: Callable | None = style_converter
else:
self.styler = None
+ self.style_converter = None
self.df = df
if cols is not None:
@@ -567,22 +590,35 @@ def _format_header_mi(self) -> Iterable[ExcelCell]:
):
values = levels.take(level_codes)
for i, span_val in spans.items():
- spans_multiple_cells = span_val > 1
- yield ExcelCell(
+ mergestart, mergeend = None, None
+ if span_val > 1:
+ mergestart, mergeend = lnum, coloffset + i + span_val
+ yield CssExcelCell(
row=lnum,
col=coloffset + i + 1,
val=values[i],
style=self.header_style,
- mergestart=lnum if spans_multiple_cells else None,
- mergeend=(
- coloffset + i + span_val if spans_multiple_cells else None
- ),
+ css_styles=getattr(self.styler, "ctx_columns", None),
+ css_row=lnum,
+ css_col=i,
+ css_converter=self.style_converter,
+ mergestart=mergestart,
+ mergeend=mergeend,
)
else:
# Format in legacy format with dots to indicate levels.
for i, values in enumerate(zip(*level_strs)):
v = ".".join(map(pprint_thing, values))
- yield ExcelCell(lnum, coloffset + i + 1, v, self.header_style)
+ yield CssExcelCell(
+ row=lnum,
+ col=coloffset + i + 1,
+ val=v,
+ style=self.header_style,
+ css_styles=getattr(self.styler, "ctx_columns", None),
+ css_row=lnum,
+ css_col=i,
+ css_converter=self.style_converter,
+ )
self.rowcounter = lnum
@@ -607,8 +643,15 @@ def _format_header_regular(self) -> Iterable[ExcelCell]:
colnames = self.header
for colindex, colname in enumerate(colnames):
- yield ExcelCell(
- self.rowcounter, colindex + coloffset, colname, self.header_style
+ yield CssExcelCell(
+ row=self.rowcounter,
+ col=colindex + coloffset,
+ val=colname,
+ style=self.header_style,
+ css_styles=getattr(self.styler, "ctx_columns", None),
+ css_row=0,
+ css_col=colindex,
+ css_converter=self.style_converter,
)
def _format_header(self) -> Iterable[ExcelCell]:
@@ -668,8 +711,16 @@ def _format_regular_rows(self) -> Iterable[ExcelCell]:
index_values = self.df.index.to_timestamp()
for idx, idxval in enumerate(index_values):
- yield ExcelCell(self.rowcounter + idx, 0, idxval, self.header_style)
-
+ yield CssExcelCell(
+ row=self.rowcounter + idx,
+ col=0,
+ val=idxval,
+ style=self.header_style,
+ css_styles=getattr(self.styler, "ctx_index", None),
+ css_row=idx,
+ css_col=0,
+ css_converter=self.style_converter,
+ )
coloffset = 1
else:
coloffset = 0
@@ -721,18 +772,21 @@ def _format_hierarchical_rows(self) -> Iterable[ExcelCell]:
)
for i, span_val in spans.items():
- spans_multiple_cells = span_val > 1
- yield ExcelCell(
+ mergestart, mergeend = None, None
+ if span_val > 1:
+ mergestart = self.rowcounter + i + span_val - 1
+ mergeend = gcolidx
+ yield CssExcelCell(
row=self.rowcounter + i,
col=gcolidx,
val=values[i],
style=self.header_style,
- mergestart=(
- self.rowcounter + i + span_val - 1
- if spans_multiple_cells
- else None
- ),
- mergeend=gcolidx if spans_multiple_cells else None,
+ css_styles=getattr(self.styler, "ctx_index", None),
+ css_row=i,
+ css_col=gcolidx,
+ css_converter=self.style_converter,
+ mergestart=mergestart,
+ mergeend=mergeend,
)
gcolidx += 1
@@ -740,11 +794,15 @@ def _format_hierarchical_rows(self) -> Iterable[ExcelCell]:
# Format hierarchical rows with non-merged values.
for indexcolvals in zip(*self.df.index):
for idx, indexcolval in enumerate(indexcolvals):
- yield ExcelCell(
+ yield CssExcelCell(
row=self.rowcounter + idx,
col=gcolidx,
val=indexcolval,
style=self.header_style,
+ css_styles=getattr(self.styler, "ctx_index", None),
+ css_row=idx,
+ css_col=gcolidx,
+ css_converter=self.style_converter,
)
gcolidx += 1
@@ -756,22 +814,20 @@ def _has_aliases(self) -> bool:
return is_list_like(self.header)
def _generate_body(self, coloffset: int) -> Iterable[ExcelCell]:
- if self.styler is None:
- styles = None
- else:
- styles = self.styler._compute().ctx
- if not styles:
- styles = None
- xlstyle = None
-
# Write the body of the frame data series by series.
for colidx in range(len(self.columns)):
series = self.df.iloc[:, colidx]
for i, val in enumerate(series):
- if styles is not None:
- css = ";".join([a + ":" + str(v) for (a, v) in styles[i, colidx]])
- xlstyle = self.style_converter(css)
- yield ExcelCell(self.rowcounter + i, colidx + coloffset, val, xlstyle)
+ yield CssExcelCell(
+ row=self.rowcounter + i,
+ col=colidx + coloffset,
+ val=val,
+ style=None,
+ css_styles=getattr(self.styler, "ctx", None),
+ css_row=i,
+ css_col=colidx,
+ css_converter=self.style_converter,
+ )
def get_formatted_cells(self) -> Iterable[ExcelCell]:
for cell in itertools.chain(self._format_header(), self._format_body()):
diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py
index ed996d32cf2fb..8a142aebd719d 100644
--- a/pandas/tests/io/excel/test_style.py
+++ b/pandas/tests/io/excel/test_style.py
@@ -7,163 +7,161 @@
from pandas.io.excel import ExcelWriter
from pandas.io.formats.excel import ExcelFormatter
+pytest.importorskip("jinja2")
+# jinja2 is currently required for Styler.__init__(). Technically Styler.to_excel
+# could compute styles and render to excel without jinja2, since there is no
+# 'template' file, but this needs the import error to delayed until render time.
+
+
+def assert_equal_cell_styles(cell1, cell2):
+ # TODO: should find a better way to check equality
+ assert cell1.alignment.__dict__ == cell2.alignment.__dict__
+ assert cell1.border.__dict__ == cell2.border.__dict__
+ assert cell1.fill.__dict__ == cell2.fill.__dict__
+ assert cell1.font.__dict__ == cell2.font.__dict__
+ assert cell1.number_format == cell2.number_format
+ assert cell1.protection.__dict__ == cell2.protection.__dict__
+
@pytest.mark.parametrize(
"engine",
- [
- pytest.param(
- "xlwt",
- marks=pytest.mark.xfail(
- reason="xlwt does not support openpyxl-compatible style dicts"
- ),
- ),
- "xlsxwriter",
- "openpyxl",
- ],
+ ["xlsxwriter", "openpyxl"],
)
-def test_styler_to_excel(request, engine):
- def style(df):
- # TODO: RGB colors not supported in xlwt
- return DataFrame(
- [
- ["font-weight: bold", "", ""],
- ["", "color: blue", ""],
- ["", "", "text-decoration: underline"],
- ["border-style: solid", "", ""],
- ["", "font-style: italic", ""],
- ["", "", "text-align: right"],
- ["background-color: red", "", ""],
- ["number-format: 0%", "", ""],
- ["", "", ""],
- ["", "", ""],
- ["", "", ""],
- ],
- index=df.index,
- columns=df.columns,
- )
-
- def assert_equal_style(cell1, cell2, engine):
- if engine in ["xlsxwriter", "openpyxl"]:
- request.node.add_marker(
- pytest.mark.xfail(
- reason=(
- f"GH25351: failing on some attribute comparisons in {engine}"
- )
- )
- )
- # TODO: should find a better way to check equality
- assert cell1.alignment.__dict__ == cell2.alignment.__dict__
- assert cell1.border.__dict__ == cell2.border.__dict__
- assert cell1.fill.__dict__ == cell2.fill.__dict__
- assert cell1.font.__dict__ == cell2.font.__dict__
- assert cell1.number_format == cell2.number_format
- assert cell1.protection.__dict__ == cell2.protection.__dict__
-
- def custom_converter(css):
- # use bold iff there is custom style attached to the cell
- if css.strip(" \n;"):
- return {"font": {"bold": True}}
- return {}
-
- pytest.importorskip("jinja2")
+def test_styler_to_excel_unstyled(engine):
+ # compare DataFrame.to_excel and Styler.to_excel when no styles applied
pytest.importorskip(engine)
-
- # Prepare spreadsheets
-
- df = DataFrame(np.random.randn(11, 3))
- with tm.ensure_clean(".xlsx" if engine != "xlwt" else ".xls") as path:
+ df = DataFrame(np.random.randn(2, 2))
+ with tm.ensure_clean(".xlsx") as path:
with ExcelWriter(path, engine=engine) as writer:
- df.to_excel(writer, sheet_name="frame")
+ df.to_excel(writer, sheet_name="dataframe")
df.style.to_excel(writer, sheet_name="unstyled")
- styled = df.style.apply(style, axis=None)
- styled.to_excel(writer, sheet_name="styled")
- ExcelFormatter(styled, style_converter=custom_converter).write(
- writer, sheet_name="custom"
- )
- if engine not in ("openpyxl", "xlsxwriter"):
- # For other engines, we only smoke test
- return
- openpyxl = pytest.importorskip("openpyxl")
+ openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl
wb = openpyxl.load_workbook(path)
- # (1) compare DataFrame.to_excel and Styler.to_excel when unstyled
- n_cells = 0
- for col1, col2 in zip(wb["frame"].columns, wb["unstyled"].columns):
+ for col1, col2 in zip(wb["dataframe"].columns, wb["unstyled"].columns):
assert len(col1) == len(col2)
for cell1, cell2 in zip(col1, col2):
assert cell1.value == cell2.value
- assert_equal_style(cell1, cell2, engine)
- n_cells += 1
+ assert_equal_cell_styles(cell1, cell2)
+
+
+shared_style_params = [
+ (
+ "background-color: #111222",
+ ["fill", "fgColor", "rgb"],
+ {"xlsxwriter": "FF111222", "openpyxl": "00111222"},
+ ),
+ (
+ "color: #111222",
+ ["font", "color", "value"],
+ {"xlsxwriter": "FF111222", "openpyxl": "00111222"},
+ ),
+ ("font-family: Arial;", ["font", "name"], "arial"),
+ ("font-weight: bold;", ["font", "b"], True),
+ ("font-style: italic;", ["font", "i"], True),
+ ("text-decoration: underline;", ["font", "u"], "single"),
+ ("number-format: $??,???.00;", ["number_format"], "$??,???.00"),
+ ("text-align: left;", ["alignment", "horizontal"], "left"),
+ (
+ "vertical-align: bottom;",
+ ["alignment", "vertical"],
+ {"xlsxwriter": None, "openpyxl": "bottom"}, # xlsxwriter Fails
+ ),
+]
- # ensure iteration actually happened:
- assert n_cells == (11 + 1) * (3 + 1)
- # (2) check styling with default converter
+@pytest.mark.parametrize(
+ "engine",
+ ["xlsxwriter", "openpyxl"],
+)
+@pytest.mark.parametrize("css, attrs, expected", shared_style_params)
+def test_styler_to_excel_basic(engine, css, attrs, expected):
+ pytest.importorskip(engine)
+ df = DataFrame(np.random.randn(1, 1))
+ styler = df.style.applymap(lambda x: css)
- # TODO: openpyxl (as at 2.4) prefixes colors with 00, xlsxwriter with FF
- alpha = "00" if engine == "openpyxl" else "FF"
+ with tm.ensure_clean(".xlsx") as path:
+ with ExcelWriter(path, engine=engine) as writer:
+ df.to_excel(writer, sheet_name="dataframe")
+ styler.to_excel(writer, sheet_name="styled")
- n_cells = 0
- for col1, col2 in zip(wb["frame"].columns, wb["styled"].columns):
- assert len(col1) == len(col2)
- for cell1, cell2 in zip(col1, col2):
- ref = f"{cell2.column}{cell2.row:d}"
- # TODO: this isn't as strong a test as ideal; we should
- # confirm that differences are exclusive
- if ref == "B2":
- assert not cell1.font.bold
- assert cell2.font.bold
- elif ref == "C3":
- assert cell1.font.color.rgb != cell2.font.color.rgb
- assert cell2.font.color.rgb == alpha + "0000FF"
- elif ref == "D4":
- assert cell1.font.underline != cell2.font.underline
- assert cell2.font.underline == "single"
- elif ref == "B5":
- assert not cell1.border.left.style
- assert (
- cell2.border.top.style
- == cell2.border.right.style
- == cell2.border.bottom.style
- == cell2.border.left.style
- == "medium"
- )
- elif ref == "C6":
- assert not cell1.font.italic
- assert cell2.font.italic
- elif ref == "D7":
- assert cell1.alignment.horizontal != cell2.alignment.horizontal
- assert cell2.alignment.horizontal == "right"
- elif ref == "B8":
- assert cell1.fill.fgColor.rgb != cell2.fill.fgColor.rgb
- assert cell1.fill.patternType != cell2.fill.patternType
- assert cell2.fill.fgColor.rgb == alpha + "FF0000"
- assert cell2.fill.patternType == "solid"
- elif ref == "B9":
- assert cell1.number_format == "General"
- assert cell2.number_format == "0%"
- else:
- assert_equal_style(cell1, cell2, engine)
+ openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl
+ wb = openpyxl.load_workbook(path)
- assert cell1.value == cell2.value
- n_cells += 1
+ # test unstyled data cell does not have expected styles
+ # test styled cell has expected styles
+ u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2)
+ for attr in attrs:
+ u_cell, s_cell = getattr(u_cell, attr), getattr(s_cell, attr)
- assert n_cells == (11 + 1) * (3 + 1)
+ if isinstance(expected, dict):
+ assert u_cell is None or u_cell != expected[engine]
+ assert s_cell == expected[engine]
+ else:
+ assert u_cell is None or u_cell != expected
+ assert s_cell == expected
- # (3) check styling with custom converter
- n_cells = 0
- for col1, col2 in zip(wb["frame"].columns, wb["custom"].columns):
- assert len(col1) == len(col2)
- for cell1, cell2 in zip(col1, col2):
- ref = f"{cell2.column}{cell2.row:d}"
- if ref in ("B2", "C3", "D4", "B5", "C6", "D7", "B8", "B9"):
- assert not cell1.font.bold
- assert cell2.font.bold
- else:
- assert_equal_style(cell1, cell2, engine)
- assert cell1.value == cell2.value
- n_cells += 1
+@pytest.mark.parametrize(
+ "engine",
+ ["xlsxwriter", "openpyxl"],
+)
+@pytest.mark.parametrize("css, attrs, expected", shared_style_params)
+def test_styler_to_excel_basic_indexes(engine, css, attrs, expected):
+ pytest.importorskip(engine)
+ df = DataFrame(np.random.randn(1, 1))
+
+ styler = df.style
+ styler.applymap_index(lambda x: css, axis=0)
+ styler.applymap_index(lambda x: css, axis=1)
+
+ null_styler = df.style
+ null_styler.applymap(lambda x: "null: css;")
+ null_styler.applymap_index(lambda x: "null: css;", axis=0)
+ null_styler.applymap_index(lambda x: "null: css;", axis=1)
+
+ with tm.ensure_clean(".xlsx") as path:
+ with ExcelWriter(path, engine=engine) as writer:
+ null_styler.to_excel(writer, sheet_name="null_styled")
+ styler.to_excel(writer, sheet_name="styled")
+
+ openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl
+ wb = openpyxl.load_workbook(path)
+
+ # test null styled index cells does not have expected styles
+ # test styled cell has expected styles
+ ui_cell, si_cell = wb["null_styled"].cell(2, 1), wb["styled"].cell(2, 1)
+ uc_cell, sc_cell = wb["null_styled"].cell(1, 2), wb["styled"].cell(1, 2)
+ for attr in attrs:
+ ui_cell, si_cell = getattr(ui_cell, attr), getattr(si_cell, attr)
+ uc_cell, sc_cell = getattr(uc_cell, attr), getattr(sc_cell, attr)
+
+ if isinstance(expected, dict):
+ assert ui_cell is None or ui_cell != expected[engine]
+ assert si_cell == expected[engine]
+ assert uc_cell is None or uc_cell != expected[engine]
+ assert sc_cell == expected[engine]
+ else:
+ assert ui_cell is None or ui_cell != expected
+ assert si_cell == expected
+ assert uc_cell is None or uc_cell != expected
+ assert sc_cell == expected
+
+
+def test_styler_custom_converter():
+ openpyxl = pytest.importorskip("openpyxl")
+
+ def custom_converter(css):
+ return {"font": {"color": {"rgb": "111222"}}}
- assert n_cells == (11 + 1) * (3 + 1)
+ df = DataFrame(np.random.randn(1, 1))
+ styler = df.style.applymap(lambda x: "color: #888999")
+ with tm.ensure_clean(".xlsx") as path:
+ with ExcelWriter(path, engine="openpyxl") as writer:
+ ExcelFormatter(styler, style_converter=custom_converter).write(
+ writer, sheet_name="custom"
+ )
+
+ wb = openpyxl.load_workbook(path)
+ assert wb["custom"].cell(2, 2).font.color.value == "00111222"
| This is a follow-on to #41893.
It makes the new `Styler.apply_index` and `Styler.applymap_index` methods compatible with `Styler.to_excel`. If the methods are not used the output reverts to the old format.

**MultiIndex Case**
```python
midx = pd.MultiIndex.from_product([['ix', 'jy'], [0, 1], ['x3', 'z4']])
df = pd.DataFrame([np.arange(8)], columns=midx)
def highlight_x(s):
return ["background-color: yellow;" if 'x' in v else "" for v in s]
df.style.apply_index(highlight_x, axis="columns", level=[0, 2]).to_excel("mi_test.xlsx")
```

# NOTE on TESTS
The tests for styler_to_excel were broken and were xfailed out of production in 2019. Since they dont work I have replaced them with some other, cleaner, tests and add tests relevant to this PR also.
Closes #25351
| https://api.github.com/repos/pandas-dev/pandas/pulls/41995 | 2021-06-14T09:01:41Z | 2021-10-19T00:44:24Z | 2021-10-19T00:44:23Z | 2021-10-19T05:31:41Z |
ENH: `Styler.apply(map)_index` made compatible with `Styler.to_latex` | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index ef7ff2d24009e..89b7950c5faf4 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -38,7 +38,7 @@ Other enhancements
- :meth:`Series.ewm`, :meth:`DataFrame.ewm`, now support a ``method`` argument with a ``'table'`` option that performs the windowing operation over an entire :class:`DataFrame`. See :ref:`Window Overview <window.overview>` for performance and functional benefits (:issue:`42273`)
- Added ``sparse_index`` and ``sparse_columns`` keyword arguments to :meth:`.Styler.to_html` (:issue:`41946`)
- Added keyword argument ``environment`` to :meth:`.Styler.to_latex` also allowing a specific "longtable" entry with a separate jinja2 template (:issue:`41866`)
-- :meth:`.Styler.apply_index` and :meth:`.Styler.applymap_index` added to allow conditional styling of index and column header values (:issue:`41893`)
+- :meth:`.Styler.apply_index` and :meth:`.Styler.applymap_index` added to allow conditional styling of index and column header values for HTML and LaTeX (:issue:`41893`)
- :meth:`.GroupBy.cummin` and :meth:`.GroupBy.cummax` now support the argument ``skipna`` (:issue:`34047`)
-
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index c45519bf31ff2..aa58b3abbd06c 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -570,7 +570,14 @@ def _translate_latex(self, d: dict) -> None:
- Remove hidden indexes or reinsert missing th elements if part of multiindex
or multirow sparsification (so that \multirow and \multicol work correctly).
"""
- d["head"] = [[col for col in row if col["is_visible"]] for row in d["head"]]
+ d["head"] = [
+ [
+ {**col, "cellstyle": self.ctx_columns[r, c - self.index.nlevels]}
+ for c, col in enumerate(row)
+ if col["is_visible"]
+ ]
+ for r, row in enumerate(d["head"])
+ ]
body = []
for r, row in enumerate(d["body"]):
if all(self.hide_index_):
@@ -582,8 +589,9 @@ def _translate_latex(self, d: dict) -> None:
"display_value": col["display_value"]
if col["is_visible"]
else "",
+ "cellstyle": self.ctx_index[r, c] if col["is_visible"] else [],
}
- for col in row
+ for c, col in enumerate(row)
if col["type"] == "th"
]
@@ -1378,26 +1386,21 @@ def _parse_latex_header_span(
>>> _parse_latex_header_span(cell, 't', 'c')
'\\multicolumn{3}{c}{text}'
"""
+ display_val = _parse_latex_cell_styles(cell["cellstyle"], cell["display_value"])
if "attributes" in cell:
attrs = cell["attributes"]
if 'colspan="' in attrs:
colspan = attrs[attrs.find('colspan="') + 9 :] # len('colspan="') = 9
colspan = int(colspan[: colspan.find('"')])
- return (
- f"\\multicolumn{{{colspan}}}{{{multicol_align}}}"
- f"{{{cell['display_value']}}}"
- )
+ return f"\\multicolumn{{{colspan}}}{{{multicol_align}}}{{{display_val}}}"
elif 'rowspan="' in attrs:
rowspan = attrs[attrs.find('rowspan="') + 9 :]
rowspan = int(rowspan[: rowspan.find('"')])
- return (
- f"\\multirow[{multirow_align}]{{{rowspan}}}{{*}}"
- f"{{{cell['display_value']}}}"
- )
+ return f"\\multirow[{multirow_align}]{{{rowspan}}}{{*}}{{{display_val}}}"
if wrap:
- return f"{{{cell['display_value']}}}"
+ return f"{{{display_val}}}"
else:
- return cell["display_value"]
+ return display_val
def _parse_latex_options_strip(value: str | int | float, arg: str) -> str:
diff --git a/pandas/tests/io/formats/style/test_to_latex.py b/pandas/tests/io/formats/style/test_to_latex.py
index 501d9b43ff106..ac164f2de9fb2 100644
--- a/pandas/tests/io/formats/style/test_to_latex.py
+++ b/pandas/tests/io/formats/style/test_to_latex.py
@@ -414,17 +414,20 @@ def test_parse_latex_cell_styles_braces(wrap_arg, expected):
def test_parse_latex_header_span():
- cell = {"attributes": 'colspan="3"', "display_value": "text"}
+ cell = {"attributes": 'colspan="3"', "display_value": "text", "cellstyle": []}
expected = "\\multicolumn{3}{Y}{text}"
assert _parse_latex_header_span(cell, "X", "Y") == expected
- cell = {"attributes": 'rowspan="5"', "display_value": "text"}
+ cell = {"attributes": 'rowspan="5"', "display_value": "text", "cellstyle": []}
expected = "\\multirow[X]{5}{*}{text}"
assert _parse_latex_header_span(cell, "X", "Y") == expected
- cell = {"display_value": "text"}
+ cell = {"display_value": "text", "cellstyle": []}
assert _parse_latex_header_span(cell, "X", "Y") == "text"
+ cell = {"display_value": "text", "cellstyle": [("bfseries", "--rwrap")]}
+ assert _parse_latex_header_span(cell, "X", "Y") == "\\bfseries{text}"
+
def test_parse_latex_table_wrapping(styler):
styler.set_table_styles(
@@ -635,3 +638,40 @@ def test_longtable_caption_label(styler, caption, cap_exp, label, lab_exp):
assert expected in styler.to_latex(
environment="longtable", caption=caption, label=label
)
+
+
+@pytest.mark.parametrize("index", [True, False])
+@pytest.mark.parametrize("columns", [True, False])
+def test_apply_map_header_render_mi(df, index, columns):
+ cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])
+ ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
+ df.loc[2, :] = [2, -2.22, "de"]
+ df = df.astype({"A": int})
+ df.index, df.columns = ridx, cidx
+ styler = df.style
+
+ func = lambda v: "bfseries: --rwrap" if "A" in v or "Z" in v or "c" in v else None
+
+ if index:
+ styler.applymap_index(func, axis="index")
+ if columns:
+ styler.applymap_index(func, axis="columns")
+
+ result = styler.to_latex()
+
+ expected_index = dedent(
+ """\
+ \\multirow[c]{2}{*}{\\bfseries{A}} & a & 0 & -0.610000 & ab \\\\
+ & b & 1 & -1.220000 & cd \\\\
+ B & \\bfseries{c} & 2 & -2.220000 & de \\\\
+ """
+ )
+ assert (expected_index in result) is index
+
+ expected_columns = dedent(
+ """\
+ {} & {} & \\multicolumn{2}{r}{\\bfseries{Z}} & {Y} \\\\
+ {} & {} & {a} & {b} & {\\bfseries{c}} \\\\
+ """
+ )
+ assert (expected_columns in result) is columns
| This is a follow-on to #41893.
It makes the new `Styler.apply_index` and `Styler.applymap_index` methods compatible with `Styler.to_latex`.

| https://api.github.com/repos/pandas-dev/pandas/pulls/41993 | 2021-06-14T07:30:25Z | 2021-08-12T15:52:05Z | 2021-08-12T15:52:05Z | 2021-08-12T17:02:45Z |
CI: troubleshoot py310 build | diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx
index 03f4ce273de6e..c2b9c723b7c72 100644
--- a/pandas/_libs/algos.pyx
+++ b/pandas/_libs/algos.pyx
@@ -1030,9 +1030,9 @@ def rank_1d(
if rank_t is object:
nan_fill_val = Infinity()
elif rank_t is int64_t:
- nan_fill_val = np.iinfo(np.int64).max
+ nan_fill_val = util.INT64_MAX
elif rank_t is uint64_t:
- nan_fill_val = np.iinfo(np.uint64).max
+ nan_fill_val = util.UINT64_MAX
else:
nan_fill_val = np.inf
order = (masked_vals, mask, labels)
@@ -1393,7 +1393,7 @@ def rank_2d(
# int64 and datetimelike
else:
- nan_value = np.iinfo(np.int64).max
+ nan_value = util.INT64_MAX
else:
if rank_t is object:
diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi
index 3f4623638c70e..077d2e60cc3a4 100644
--- a/pandas/_libs/lib.pyi
+++ b/pandas/_libs/lib.pyi
@@ -25,6 +25,9 @@ class NoDefault(Enum): ...
no_default: NoDefault
+i8max: int
+u8max: int
+
def item_from_zerodim(val: object) -> object: ...
def infer_dtype(value: object, skipna: bool = True) -> str: ...
def is_iterator(obj: object) -> bool: ...
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 0aec7e5e5a363..37e83ddb0ffed 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -118,6 +118,10 @@ cdef:
float64_t NaN = <float64_t>np.NaN
+# python-visible
+i8max = <int64_t>INT64_MAX
+u8max = <uint64_t>UINT64_MAX
+
@cython.wraparound(False)
@cython.boundscheck(False)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index f26cf113f7d5e..7dcc83f76db75 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1092,18 +1092,19 @@ def checked_add_with_arr(
# it is negative, we then check whether its sum with the element in
# 'arr' exceeds np.iinfo(np.int64).min. If so, we have an overflow
# error as well.
+ i8max = lib.i8max
+ i8min = iNaT
+
mask1 = b2 > 0
mask2 = b2 < 0
if not mask1.any():
- to_raise = ((np.iinfo(np.int64).min - b2 > arr) & not_nan).any()
+ to_raise = ((i8min - b2 > arr) & not_nan).any()
elif not mask2.any():
- to_raise = ((np.iinfo(np.int64).max - b2 < arr) & not_nan).any()
+ to_raise = ((i8max - b2 < arr) & not_nan).any()
else:
- to_raise = (
- (np.iinfo(np.int64).max - b2[mask1] < arr[mask1]) & not_nan[mask1]
- ).any() or (
- (np.iinfo(np.int64).min - b2[mask2] > arr[mask2]) & not_nan[mask2]
+ to_raise = ((i8max - b2[mask1] < arr[mask1]) & not_nan[mask1]).any() or (
+ (i8min - b2[mask2] > arr[mask2]) & not_nan[mask2]
).any()
if to_raise:
diff --git a/pandas/core/arrays/_ranges.py b/pandas/core/arrays/_ranges.py
index cac9fcd40fa52..3909875e5660a 100644
--- a/pandas/core/arrays/_ranges.py
+++ b/pandas/core/arrays/_ranges.py
@@ -6,6 +6,7 @@
import numpy as np
+from pandas._libs.lib import i8max
from pandas._libs.tslibs import (
BaseOffset,
OutOfBoundsDatetime,
@@ -103,7 +104,7 @@ def _generate_range_overflow_safe(
# GH#14187 raise instead of incorrectly wrapping around
assert side in ["start", "end"]
- i64max = np.uint64(np.iinfo(np.int64).max)
+ i64max = np.uint64(i8max)
msg = f"Cannot generate range with {side}={endpoint} and periods={periods}"
with np.errstate(over="raise"):
@@ -180,7 +181,7 @@ def _generate_range_overflow_safe_signed(
# error: Incompatible types in assignment (expression has type
# "unsignedinteger[_64Bit]", variable has type "signedinteger[_64Bit]")
result = np.uint64(endpoint) + np.uint64(addend) # type: ignore[assignment]
- i64max = np.uint64(np.iinfo(np.int64).max)
+ i64max = np.uint64(i8max)
assert result > i64max
if result <= i64max + np.uint64(stride):
# error: Incompatible return value type (got "unsignedinteger", expected
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index ecdf2624c8ec1..c34944985f2b6 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -205,7 +205,7 @@ def _get_fill_value(
else:
if fill_value_typ == "+inf":
# need the max int here
- return np.iinfo(np.int64).max
+ return lib.i8max
else:
return iNaT
@@ -376,7 +376,7 @@ def _wrap_results(result, dtype: np.dtype, fill_value=None):
result = np.nan
# raise if we have a timedelta64[ns] which is too large
- if np.fabs(result) > np.iinfo(np.int64).max:
+ if np.fabs(result) > lib.i8max:
raise ValueError("overflow in timedelta operation")
result = Timedelta(result, unit="ns")
@@ -1758,7 +1758,7 @@ def na_accum_func(values: ArrayLike, accum_func, *, skipna: bool) -> ArrayLike:
if accum_func == np.minimum.accumulate:
# Note: the accum_func comparison fails as an "is" comparison
y = values.view("i8")
- y[mask] = np.iinfo(np.int64).max
+ y[mask] = lib.i8max
changed = True
else:
y = values
diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py
index 8531f93fba321..712e9785f47f7 100644
--- a/pandas/core/sorting.py
+++ b/pandas/core/sorting.py
@@ -40,8 +40,6 @@
from pandas import MultiIndex
from pandas.core.indexes.base import Index
-_INT64_MAX = np.iinfo(np.int64).max
-
def get_indexer_indexer(
target: Index,
@@ -133,7 +131,7 @@ def _int64_cut_off(shape) -> int:
acc = 1
for i, mul in enumerate(shape):
acc *= int(mul)
- if not acc < _INT64_MAX:
+ if not acc < lib.i8max:
return i
return len(shape)
@@ -153,7 +151,7 @@ def maybe_lift(lab, size) -> tuple[np.ndarray, int]:
labels = list(labels)
# Iteratively process all the labels in chunks sized so less
- # than _INT64_MAX unique int ids will be required for each chunk
+ # than lib.i8max unique int ids will be required for each chunk
while True:
# how many levels can be done without overflow:
nlev = _int64_cut_off(lshape)
@@ -215,7 +213,7 @@ def is_int64_overflow_possible(shape) -> bool:
for x in shape:
the_prod *= int(x)
- return the_prod >= _INT64_MAX
+ return the_prod >= lib.i8max
def decons_group_index(comp_labels, shape):
diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py
index fb5002648b6a5..962728b2f38c4 100644
--- a/pandas/core/util/hashing.py
+++ b/pandas/core/util/hashing.py
@@ -14,6 +14,7 @@
import numpy as np
+from pandas._libs import lib
from pandas._libs.hashing import hash_object_array
from pandas._typing import (
ArrayLike,
@@ -244,7 +245,7 @@ def _hash_categorical(cat: Categorical, encoding: str, hash_key: str) -> np.ndar
result = np.zeros(len(mask), dtype="uint64")
if mask.any():
- result[mask] = np.iinfo(np.uint64).max
+ result[mask] = lib.u8max
return result
diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py
index 8b42bca8b8a0c..4aa2f62fe85a0 100644
--- a/pandas/tests/scalar/timedelta/test_timedelta.py
+++ b/pandas/tests/scalar/timedelta/test_timedelta.py
@@ -4,6 +4,7 @@
import numpy as np
import pytest
+from pandas._libs import lib
from pandas._libs.tslibs import (
NaT,
iNaT,
@@ -391,8 +392,7 @@ def test_round_implementation_bounds(self):
"method", [Timedelta.round, Timedelta.floor, Timedelta.ceil]
)
def test_round_sanity(self, method, n, request):
- iinfo = np.iinfo(np.int64)
- val = np.random.randint(iinfo.min + 1, iinfo.max, dtype=np.int64)
+ val = np.random.randint(iNaT + 1, lib.i8max, dtype=np.int64)
td = Timedelta(val)
assert method(td, "ns") == td
@@ -552,8 +552,8 @@ def test_implementation_limits(self):
# GH 12727
# timedelta limits correspond to int64 boundaries
- assert min_td.value == np.iinfo(np.int64).min + 1
- assert max_td.value == np.iinfo(np.int64).max
+ assert min_td.value == iNaT + 1
+ assert max_td.value == lib.i8max
# Beyond lower limit, a NAT before the Overflow
assert (min_td - Timedelta(1, "ns")) is NaT
diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py
index aab0b2e6d31ef..366c0f7cf2f74 100644
--- a/pandas/tests/scalar/timestamp/test_unary_ops.py
+++ b/pandas/tests/scalar/timestamp/test_unary_ops.py
@@ -6,11 +6,13 @@
import pytz
from pytz import utc
+from pandas._libs import lib
from pandas._libs.tslibs import (
NaT,
Timedelta,
Timestamp,
conversion,
+ iNaT,
to_offset,
)
from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
@@ -279,8 +281,7 @@ def test_round_implementation_bounds(self):
"method", [Timestamp.round, Timestamp.floor, Timestamp.ceil]
)
def test_round_sanity(self, method, n):
- iinfo = np.iinfo(np.int64)
- val = np.random.randint(iinfo.min + 1, iinfo.max, dtype=np.int64)
+ val = np.random.randint(iNaT + 1, lib.i8max, dtype=np.int64)
ts = Timestamp(val)
def checker(res, ts, nanos):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41990 | 2021-06-14T01:52:48Z | 2021-06-15T13:17:09Z | 2021-06-15T13:17:09Z | 2022-12-29T21:21:25Z |
DEPS: drop Python 3.7 and NumPy 1.17 from tests (#41678) | diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml
index 4b700c48979f7..54a55cc78914d 100644
--- a/.github/workflows/database.yml
+++ b/.github/workflows/database.yml
@@ -19,7 +19,7 @@ env:
COVERAGE: true
jobs:
- Linux_py37_IO:
+ Linux_py38_IO:
runs-on: ubuntu-latest
defaults:
run:
@@ -27,7 +27,7 @@ jobs:
strategy:
matrix:
- ENV_FILE: [ci/deps/actions-37-db-min.yaml, ci/deps/actions-37-db.yaml]
+ ENV_FILE: [ci/deps/actions-38-db-min.yaml, ci/deps/actions-38-db.yaml]
fail-fast: false
concurrency:
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index e831bd0f8c181..42a8c0052246a 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -25,14 +25,13 @@ jobs:
strategy:
matrix:
settings: [
- [actions-37-minimum_versions.yaml, "not slow and not network and not clipboard", "", "", "", "", ""],
- [actions-37.yaml, "not slow and not network and not clipboard", "", "", "", "", ""],
- [actions-37-locale_slow.yaml, "slow", "language-pack-it xsel", "it_IT.utf8", "it_IT.utf8", "", ""],
- [actions-37-slow.yaml, "slow", "", "", "", "", ""],
+ [actions-38-minimum_versions.yaml, "not slow and not network and not clipboard", "", "", "", "", ""],
+ [actions-38-locale_slow.yaml, "slow", "language-pack-it xsel", "it_IT.utf8", "it_IT.utf8", "", ""],
[actions-38.yaml, "not slow and not network and not clipboard", "", "", "", "", ""],
[actions-38-slow.yaml, "slow", "", "", "", "", ""],
[actions-38-locale.yaml, "not slow and not network", "language-pack-zh-hans xsel", "zh_CN.utf8", "zh_CN.utf8", "", ""],
- [actions-38-numpydev.yaml, "not slow and not network", "xsel", "", "", "deprecate", "-W error"],
+ [actions-39-slow.yaml, "slow", "", "", "", "", ""],
+ [actions-39-numpydev.yaml, "not slow and not network", "xsel", "", "", "deprecate", "-W error"],
[actions-39.yaml, "not slow and not network and not clipboard", "", "", "", "", ""]
]
fail-fast: false
diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml
index 0c2e30a74bbdb..22029eb2f7481 100644
--- a/.github/workflows/sdist.yml
+++ b/.github/workflows/sdist.yml
@@ -23,7 +23,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- python-version: ["3.7", "3.8", "3.9"]
+ python-version: ["3.8", "3.9"]
steps:
- uses: actions/checkout@v2
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 5ba4471c8d303..98a32d4e6af2c 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -29,7 +29,7 @@ jobs:
name: Windows
vmImage: vs2017-win2016
-- job: py37_32bit
+- job: py38_32bit
pool:
vmImage: ubuntu-18.04
@@ -38,7 +38,7 @@ jobs:
docker pull quay.io/pypa/manylinux2014_i686
docker run -v $(pwd):/pandas quay.io/pypa/manylinux2014_i686 \
/bin/bash -xc "cd pandas && \
- /opt/python/cp37-cp37m/bin/python -m venv ~/virtualenvs/pandas-dev && \
+ /opt/python/cp38-cp38/bin/python -m venv ~/virtualenvs/pandas-dev && \
. ~/virtualenvs/pandas-dev/bin/activate && \
python -m pip install --no-deps -U pip wheel setuptools && \
pip install cython numpy python-dateutil pytz pytest pytest-xdist hypothesis pytest-azurepipelines && \
@@ -52,4 +52,4 @@ jobs:
inputs:
testResultsFiles: '**/test-*.xml'
failTaskOnFailedTests: true
- testRunTitle: 'Publish test results for Python 3.7-32 bit full Linux'
+ testRunTitle: 'Publish test results for Python 3.8-32 bit full Linux'
diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml
index 2caacf3a07290..8b0167e52b813 100644
--- a/ci/azure/posix.yml
+++ b/ci/azure/posix.yml
@@ -9,9 +9,9 @@ jobs:
strategy:
matrix:
${{ if eq(parameters.name, 'macOS') }}:
- py37_macos:
- ENV_FILE: ci/deps/azure-macos-37.yaml
- CONDA_PY: "37"
+ py38_macos:
+ ENV_FILE: ci/deps/azure-macos-38.yaml
+ CONDA_PY: "38"
PATTERN: "not slow and not network"
steps:
diff --git a/ci/azure/windows.yml b/ci/azure/windows.yml
index 7c088622f9638..05ba7c57ad6c4 100644
--- a/ci/azure/windows.yml
+++ b/ci/azure/windows.yml
@@ -8,15 +8,15 @@ jobs:
vmImage: ${{ parameters.vmImage }}
strategy:
matrix:
- py37_np17:
- ENV_FILE: ci/deps/azure-windows-37.yaml
- CONDA_PY: "37"
- PATTERN: "not slow and not network"
- PYTEST_WORKERS: 2 # GH-42236
-
py38_np18:
ENV_FILE: ci/deps/azure-windows-38.yaml
CONDA_PY: "38"
+ PATTERN: "not slow and not network"
+ PYTEST_WORKERS: 2 # GH-42236
+
+ py39:
+ ENV_FILE: ci/deps/azure-windows-39.yaml
+ CONDA_PY: "39"
PATTERN: "not slow and not network and not high_memory"
PYTEST_WORKERS: 2 # GH-42236
@@ -25,26 +25,22 @@ jobs:
Write-Host "##vso[task.prependpath]$env:CONDA\Scripts"
Write-Host "##vso[task.prependpath]$HOME/miniconda3/bin"
displayName: 'Add conda to PATH'
-
- script: conda update -q -n base conda
displayName: 'Update conda'
- bash: |
conda env create -q --file ci\\deps\\azure-windows-$(CONDA_PY).yaml
displayName: 'Create anaconda environment'
-
- bash: |
source activate pandas-dev
conda list
python setup.py build_ext -q -j 4
python -m pip install --no-build-isolation -e .
displayName: 'Build'
-
- bash: |
source activate pandas-dev
ci/run_tests.sh
displayName: 'Test'
-
- task: PublishTestResults@2
condition: succeededOrFailed()
inputs:
diff --git a/ci/deps/actions-37-locale_slow.yaml b/ci/deps/actions-37-locale_slow.yaml
deleted file mode 100644
index c6eb3b00a63ac..0000000000000
--- a/ci/deps/actions-37-locale_slow.yaml
+++ /dev/null
@@ -1,30 +0,0 @@
-name: pandas-dev
-channels:
- - defaults
- - conda-forge
-dependencies:
- - python=3.7.*
-
- # tools
- - cython>=0.29.21
- - pytest>=6.0
- - pytest-cov
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
-
- # pandas dependencies
- - beautifulsoup4=4.6.0
- - bottleneck=1.2.*
- - lxml
- - matplotlib=3.0.0
- - numpy=1.17.*
- - openpyxl=3.0.0
- - python-dateutil
- - python-blosc
- - pytz=2017.3
- - scipy
- - sqlalchemy=1.3.0
- - xlrd=1.2.0
- - xlsxwriter=1.0.2
- - xlwt=1.3.0
- - html5lib=1.0.1
diff --git a/ci/deps/actions-37-minimum_versions.yaml b/ci/deps/actions-37-minimum_versions.yaml
deleted file mode 100644
index b97601d18917c..0000000000000
--- a/ci/deps/actions-37-minimum_versions.yaml
+++ /dev/null
@@ -1,31 +0,0 @@
-name: pandas-dev
-channels:
- - conda-forge
-dependencies:
- - python=3.7.1
-
- # tools
- - cython=0.29.21
- - pytest>=6.0
- - pytest-cov
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
- - psutil
-
- # pandas dependencies
- - beautifulsoup4=4.6.0
- - bottleneck=1.2.1
- - jinja2=2.10
- - numba=0.46.0
- - numexpr=2.7.0
- - numpy=1.17.3
- - openpyxl=3.0.0
- - pytables=3.5.1
- - python-dateutil=2.7.3
- - pytz=2017.3
- - pyarrow=0.17.0
- - scipy=1.2
- - xlrd=1.2.0
- - xlsxwriter=1.0.2
- - xlwt=1.3.0
- - html5lib=1.0.1
diff --git a/ci/deps/actions-37.yaml b/ci/deps/actions-37.yaml
deleted file mode 100644
index 2272f8470e209..0000000000000
--- a/ci/deps/actions-37.yaml
+++ /dev/null
@@ -1,28 +0,0 @@
-name: pandas-dev
-channels:
- - defaults
- - conda-forge
-dependencies:
- - python=3.7.*
-
- # tools
- - cython>=0.29.21
- - pytest>=6.0
- - pytest-cov
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
-
- # pandas dependencies
- - botocore>=1.11
- - fsspec>=0.7.4, <2021.6.0
- - numpy=1.19
- - python-dateutil
- - nomkl
- - pyarrow
- - pytz
- - s3fs>=0.4.0
- - moto>=1.3.14
- - flask
- - tabulate
- - pyreadstat
- - pip
diff --git a/ci/deps/actions-37-db-min.yaml b/ci/deps/actions-38-db-min.yaml
similarity index 66%
rename from ci/deps/actions-37-db-min.yaml
rename to ci/deps/actions-38-db-min.yaml
index cae4361ca37a7..c93f791b7dba7 100644
--- a/ci/deps/actions-37-db-min.yaml
+++ b/ci/deps/actions-38-db-min.yaml
@@ -2,14 +2,14 @@ name: pandas-dev
channels:
- conda-forge
dependencies:
- - python=3.7.*
+ - python=3.8
# tools
- cython>=0.29.21
- pytest>=6.0
- pytest-cov
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
# required
- numpy<1.20 # GH#39541 compat for pyarrow<3
@@ -18,31 +18,30 @@ dependencies:
# optional
- beautifulsoup4
- - blosc=1.17.0
+ - blosc=1.20.1
- python-blosc
- fastparquet=0.4.0
- html5lib
- ipython
- jinja2
- - lxml=4.3.0
+ - lxml=4.5.0
- matplotlib
- nomkl
- numexpr
- openpyxl
- pandas-gbq
- - google-cloud-bigquery>=1.27.2 # GH 36436
- protobuf>=3.12.4
- pyarrow=0.17.1 # GH 38803
- - pytables>=3.5.1
+ - pytables>=3.6.1
- scipy
- - xarray=0.12.3
- - xlrd<2.0
+ - xarray=0.15.1
+ - xlrd
- xlsxwriter
- xlwt
- moto
- flask
# sql
- - psycopg2=2.7
- - pymysql=0.8.1
- - sqlalchemy=1.3.0
+ - psycopg2=2.8.4
+ - pymysql=0.10.1
+ - sqlalchemy=1.3.11
diff --git a/ci/deps/actions-37-db.yaml b/ci/deps/actions-38-db.yaml
similarity index 84%
rename from ci/deps/actions-37-db.yaml
rename to ci/deps/actions-38-db.yaml
index a9e4113bf9d18..b4495fa6887f4 100644
--- a/ci/deps/actions-37-db.yaml
+++ b/ci/deps/actions-38-db.yaml
@@ -2,13 +2,13 @@ name: pandas-dev
channels:
- conda-forge
dependencies:
- - python=3.7.*
+ - python=3.8
# tools
- cython>=0.29.21
- pytest>=6.0
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
- pytest-cov>=2.10.1 # this is only needed in the coverage build, ref: GH 35737
# pandas dependencies
@@ -25,11 +25,10 @@ dependencies:
- flask
- nomkl
- numexpr
- - numpy=1.17.*
+ - numpy=1.18
- odfpy
- openpyxl
- pandas-gbq
- - google-cloud-bigquery>=1.27.2 # GH 36436
- psycopg2
- pyarrow>=0.17.0
- pymysql
@@ -43,7 +42,7 @@ dependencies:
- sqlalchemy
- statsmodels
- xarray
- - xlrd<2.0
+ - xlrd
- xlsxwriter
- xlwt
- pip
diff --git a/ci/deps/actions-38-locale.yaml b/ci/deps/actions-38-locale.yaml
index 34a6860936550..28584de509f34 100644
--- a/ci/deps/actions-38-locale.yaml
+++ b/ci/deps/actions-38-locale.yaml
@@ -2,15 +2,15 @@ name: pandas-dev
channels:
- conda-forge
dependencies:
- - python=3.8.*
+ - python=3.8
# tools
- cython>=0.29.21
- pytest>=6.0
- pytest-cov
- - pytest-xdist>=1.21
+ - pytest-xdist>=1.31
- pytest-asyncio>=0.12.0
- - hypothesis>=3.58.0
+ - hypothesis>=5.5.3
# pandas dependencies
- beautifulsoup4
@@ -31,7 +31,7 @@ dependencies:
- pytz
- scipy
- xarray
- - xlrd<2.0
+ - xlrd
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/actions-38-locale_slow.yaml b/ci/deps/actions-38-locale_slow.yaml
new file mode 100644
index 0000000000000..e7276027f2a41
--- /dev/null
+++ b/ci/deps/actions-38-locale_slow.yaml
@@ -0,0 +1,30 @@
+name: pandas-dev
+channels:
+ - defaults
+ - conda-forge
+dependencies:
+ - python=3.8
+
+ # tools
+ - cython>=0.29.21
+ - pytest>=6.0
+ - pytest-cov
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
+
+ # pandas dependencies
+ - beautifulsoup4=4.8.2
+ - bottleneck=1.3.1
+ - lxml
+ - matplotlib=3.3.2
+ - numpy=1.18
+ - openpyxl=3.0.2
+ - python-dateutil
+ - python-blosc
+ - pytz=2020.1
+ - scipy
+ - sqlalchemy=1.3.11
+ - xlrd=2.0.1
+ - xlsxwriter=1.2.2
+ - xlwt=1.3.0
+ - html5lib=1.1
diff --git a/ci/deps/actions-38-minimum_versions.yaml b/ci/deps/actions-38-minimum_versions.yaml
new file mode 100644
index 0000000000000..d666bc3b555f5
--- /dev/null
+++ b/ci/deps/actions-38-minimum_versions.yaml
@@ -0,0 +1,31 @@
+name: pandas-dev
+channels:
+ - conda-forge
+dependencies:
+ - python=3.8.0
+
+ # tools
+ - cython=0.29.21
+ - pytest>=6.0
+ - pytest-cov
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
+ - psutil
+
+ # pandas dependencies
+ - beautifulsoup4=4.8.2
+ - bottleneck=1.3.1
+ - jinja2=2.11
+ - numba=0.50.1
+ - numexpr=2.7.1
+ - numpy=1.18.5
+ - openpyxl=3.0.2
+ - pytables=3.6.1
+ - python-dateutil=2.8.1
+ - pytz=2020.1
+ - pyarrow=0.17.0
+ - scipy=1.4.1
+ - xlrd=2.0.1
+ - xlsxwriter=1.2.2
+ - xlwt=1.3.0
+ - html5lib=1.1
diff --git a/ci/deps/actions-38-slow.yaml b/ci/deps/actions-38-slow.yaml
index c464b30e02203..08900a31fe27c 100644
--- a/ci/deps/actions-38-slow.yaml
+++ b/ci/deps/actions-38-slow.yaml
@@ -2,14 +2,14 @@ name: pandas-dev
channels:
- conda-forge
dependencies:
- - python=3.8.*
+ - python=3.8
# tools
- cython>=0.29.21
- pytest>=6.0
- pytest-cov
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
# pandas dependencies
- beautifulsoup4
@@ -30,7 +30,7 @@ dependencies:
- moto>=1.3.14
- scipy
- sqlalchemy
- - xlrd>=2.0
+ - xlrd
- xlsxwriter
- xlwt
- moto
diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml
index 11daa92046eb4..86b038ff7d4b6 100644
--- a/ci/deps/actions-38.yaml
+++ b/ci/deps/actions-38.yaml
@@ -3,14 +3,14 @@ channels:
- defaults
- conda-forge
dependencies:
- - python=3.8.*
+ - python=3.8
# tools
- cython>=0.29.21
- pytest>=6.0
- pytest-cov
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
# pandas dependencies
- numpy
diff --git a/ci/deps/actions-38-numpydev.yaml b/ci/deps/actions-39-numpydev.yaml
similarity index 84%
rename from ci/deps/actions-38-numpydev.yaml
rename to ci/deps/actions-39-numpydev.yaml
index 6eed2daac0c3b..466ca6215f46a 100644
--- a/ci/deps/actions-38-numpydev.yaml
+++ b/ci/deps/actions-39-numpydev.yaml
@@ -2,13 +2,13 @@ name: pandas-dev
channels:
- defaults
dependencies:
- - python=3.8.*
+ - python=3.9
# tools
- pytest>=6.0
- pytest-cov
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
# pandas dependencies
- pytz
diff --git a/ci/deps/actions-37-slow.yaml b/ci/deps/actions-39-slow.yaml
similarity index 84%
rename from ci/deps/actions-37-slow.yaml
rename to ci/deps/actions-39-slow.yaml
index 76eb7ba5693e9..cacafc2518b19 100644
--- a/ci/deps/actions-37-slow.yaml
+++ b/ci/deps/actions-39-slow.yaml
@@ -3,14 +3,14 @@ channels:
- defaults
- conda-forge
dependencies:
- - python=3.7.*
+ - python=3.9
# tools
- cython>=0.29.21
- pytest>=6.0
- pytest-cov
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
# pandas dependencies
- beautifulsoup4
@@ -31,9 +31,8 @@ dependencies:
- moto>=1.3.14
- scipy
- sqlalchemy
- - xlrd<2.0
+ - xlrd
- xlsxwriter
- - xlwt
- moto
- flask
- numba
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml
index b74f1af8ee0f6..2d6d58b59ba3c 100644
--- a/ci/deps/actions-39.yaml
+++ b/ci/deps/actions-39.yaml
@@ -2,14 +2,14 @@ name: pandas-dev
channels:
- conda-forge
dependencies:
- - python=3.9.*
+ - python=3.9
# tools
- cython>=0.29.21
- pytest>=6.0
- pytest-cov
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
# pandas dependencies
- numpy
diff --git a/ci/deps/azure-macos-37.yaml b/ci/deps/azure-macos-38.yaml
similarity index 73%
rename from ci/deps/azure-macos-37.yaml
rename to ci/deps/azure-macos-38.yaml
index 43e1055347f17..029d088362aa9 100644
--- a/ci/deps/azure-macos-37.yaml
+++ b/ci/deps/azure-macos-38.yaml
@@ -3,12 +3,12 @@ channels:
- defaults
- conda-forge
dependencies:
- - python=3.7.*
+ - python=3.8
# tools
- pytest>=6.0
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
- pytest-azurepipelines
# pandas dependencies
@@ -17,17 +17,17 @@ dependencies:
- html5lib
- jinja2
- lxml
- - matplotlib=2.2.3
+ - matplotlib=3.3.2
- nomkl
- numexpr
- - numpy=1.17.3
+ - numpy=1.18.5
- openpyxl
- pyarrow=0.17
- pytables
- - python-dateutil==2.7.3
+ - python-dateutil==2.8.1
- pytz
- xarray
- - xlrd<2.0
+ - xlrd
- xlsxwriter
- xlwt
- pip
diff --git a/ci/deps/azure-windows-38.yaml b/ci/deps/azure-windows-38.yaml
index 70aa46e8a5851..c56496bce7d6c 100644
--- a/ci/deps/azure-windows-38.yaml
+++ b/ci/deps/azure-windows-38.yaml
@@ -3,13 +3,13 @@ channels:
- conda-forge
- defaults
dependencies:
- - python=3.8.*
+ - python=3.8
# tools
- cython>=0.29.21
- pytest>=6.0
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
- pytest-azurepipelines
# pandas dependencies
@@ -18,19 +18,19 @@ dependencies:
- fastparquet>=0.4.0
- flask
- fsspec>=0.8.0, <2021.6.0
- - matplotlib=3.1.3
+ - matplotlib=3.3.2
- moto>=1.3.14
- numba
- numexpr
- - numpy=1.18.*
+ - numpy=1.18
- openpyxl
- jinja2
- - pyarrow>=0.17.0
+ - pyarrow=0.17.0
- pytables
- python-dateutil
- pytz
- s3fs>=0.4.0
- scipy
- - xlrd<2.0
+ - xlrd
- xlsxwriter
- xlwt
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-39.yaml
similarity index 75%
rename from ci/deps/azure-windows-37.yaml
rename to ci/deps/azure-windows-39.yaml
index 4df55813ea21c..aaf86b7310eb2 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-39.yaml
@@ -3,37 +3,37 @@ channels:
- defaults
- conda-forge
dependencies:
- - python=3.7.*
+ - python=3.9
# tools
- cython>=0.29.21
- pytest>=6.0
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
- pytest-azurepipelines
# pandas dependencies
- beautifulsoup4
- bottleneck
- fsspec>=0.8.0, <2021.6.0
- - gcsfs>=0.6.0
+ - gcsfs
- html5lib
- jinja2
- lxml
- - matplotlib=2.2.*
+ - matplotlib
- moto>=1.3.14
- flask
- numexpr
- - numpy=1.17.*
+ - numpy
- openpyxl
- - pyarrow=0.17.0
+ # - pyarrow GH 42370
- pytables
- python-dateutil
- pytz
- s3fs>=0.4.2
- scipy
- sqlalchemy
- - xlrd>=2.0
+ - xlrd
- xlsxwriter
- xlwt
- pyreadstat
diff --git a/ci/deps/circle-37-arm64.yaml b/ci/deps/circle-38-arm64.yaml
similarity index 78%
rename from ci/deps/circle-37-arm64.yaml
rename to ci/deps/circle-38-arm64.yaml
index 995ebda1f97e7..17fe5b4b7b77b 100644
--- a/ci/deps/circle-37-arm64.yaml
+++ b/ci/deps/circle-38-arm64.yaml
@@ -2,13 +2,13 @@ name: pandas-dev
channels:
- conda-forge
dependencies:
- - python=3.7.*
+ - python=3.8
# tools
- cython>=0.29.21
- pytest>=6.0
- - pytest-xdist>=1.21
- - hypothesis>=3.58.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
# pandas dependencies
- botocore>=1.11
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index 88e54421daa11..6c245a0668394 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -20,7 +20,7 @@ Instructions for installing from source,
Python version support
----------------------
-Officially Python 3.7.1 and above, 3.8, and 3.9.
+Officially Python 3.8, and 3.9.
Installing pandas
-----------------
@@ -221,9 +221,9 @@ Dependencies
================================================================ ==========================
Package Minimum supported version
================================================================ ==========================
-`NumPy <https://numpy.org>`__ 1.17.3
-`python-dateutil <https://dateutil.readthedocs.io/en/stable/>`__ 2.7.3
-`pytz <https://pypi.org/project/pytz/>`__ 2017.3
+`NumPy <https://numpy.org>`__ 1.18.5
+`python-dateutil <https://dateutil.readthedocs.io/en/stable/>`__ 2.8.1
+`pytz <https://pypi.org/project/pytz/>`__ 2020.1
================================================================ ==========================
.. _install.recommended_dependencies:
@@ -233,11 +233,11 @@ Recommended dependencies
* `numexpr <https://github.com/pydata/numexpr>`__: for accelerating certain numerical operations.
``numexpr`` uses multiple cores as well as smart chunking and caching to achieve large speedups.
- If installed, must be Version 2.7.0 or higher.
+ If installed, must be Version 2.7.1 or higher.
* `bottleneck <https://github.com/pydata/bottleneck>`__: for accelerating certain types of ``nan``
evaluations. ``bottleneck`` uses specialized cython routines to achieve large speedups. If installed,
- must be Version 1.2.1 or higher.
+ must be Version 1.3.1 or higher.
.. note::
@@ -263,8 +263,8 @@ Visualization
Dependency Minimum Version Notes
========================= ================== =============================================================
setuptools 38.6.0 Utils for entry points of plotting backend
-matplotlib 2.2.3 Plotting library
-Jinja2 2.10 Conditional formatting with DataFrame.style
+matplotlib 3.3.2 Plotting library
+Jinja2 2.11 Conditional formatting with DataFrame.style
tabulate 0.8.7 Printing in Markdown-friendly format (see `tabulate`_)
========================= ================== =============================================================
@@ -274,10 +274,10 @@ Computation
========================= ================== =============================================================
Dependency Minimum Version Notes
========================= ================== =============================================================
-SciPy 1.12.0 Miscellaneous statistical functions
-numba 0.46.0 Alternative execution engine for rolling operations
+SciPy 1.14.1 Miscellaneous statistical functions
+numba 0.50.1 Alternative execution engine for rolling operations
(see :ref:`Enhancing Performance <enhancingperf.numba>`)
-xarray 0.12.3 pandas-like API for N-dimensional data
+xarray 0.15.1 pandas-like API for N-dimensional data
========================= ================== =============================================================
Excel files
@@ -286,10 +286,10 @@ Excel files
========================= ================== =============================================================
Dependency Minimum Version Notes
========================= ================== =============================================================
-xlrd 1.2.0 Reading Excel
+xlrd 2.0.1 Reading Excel
xlwt 1.3.0 Writing Excel
-xlsxwriter 1.0.2 Writing Excel
-openpyxl 3.0.0 Reading / writing for xlsx files
+xlsxwriter 1.2.2 Writing Excel
+openpyxl 3.0.2 Reading / writing for xlsx files
pyxlsb 1.0.6 Reading for xlsb files
========================= ================== =============================================================
@@ -299,9 +299,9 @@ HTML
========================= ================== =============================================================
Dependency Minimum Version Notes
========================= ================== =============================================================
-BeautifulSoup4 4.6.0 HTML parser for read_html
-html5lib 1.0.1 HTML parser for read_html
-lxml 4.3.0 HTML parser for read_html
+BeautifulSoup4 4.8.2 HTML parser for read_html
+html5lib 1.1 HTML parser for read_html
+lxml 4.5.0 HTML parser for read_html
========================= ================== =============================================================
One of the following combinations of libraries is needed to use the
@@ -334,7 +334,7 @@ XML
========================= ================== =============================================================
Dependency Minimum Version Notes
========================= ================== =============================================================
-lxml 4.3.0 XML parser for read_xml and tree builder for to_xml
+lxml 4.5.0 XML parser for read_xml and tree builder for to_xml
========================= ================== =============================================================
SQL databases
@@ -343,9 +343,9 @@ SQL databases
========================= ================== =============================================================
Dependency Minimum Version Notes
========================= ================== =============================================================
-SQLAlchemy 1.3.0 SQL support for databases other than sqlite
-psycopg2 2.7 PostgreSQL engine for sqlalchemy
-pymysql 0.8.1 MySQL engine for sqlalchemy
+SQLAlchemy 1.3.11 SQL support for databases other than sqlite
+psycopg2 2.8.4 PostgreSQL engine for sqlalchemy
+pymysql 0.10.1 MySQL engine for sqlalchemy
========================= ================== =============================================================
Other data sources
@@ -354,8 +354,8 @@ Other data sources
========================= ================== =============================================================
Dependency Minimum Version Notes
========================= ================== =============================================================
-PyTables 3.5.1 HDF5-based reading / writing
-blosc 1.17.0 Compression for HDF5
+PyTables 3.6.1 HDF5-based reading / writing
+blosc 1.20.1 Compression for HDF5
zlib Compression for HDF5
fastparquet 0.4.0 Parquet reading / writing
pyarrow 0.17.0 Parquet, ORC, and feather reading / writing
@@ -385,7 +385,7 @@ Dependency Minimum Version Notes
========================= ================== =============================================================
fsspec 0.7.4 Handling files aside from simple local and HTTP
gcsfs 0.6.0 Google Cloud Storage access
-pandas-gbq 0.12.0 Google Big Query access
+pandas-gbq 0.14.0 Google Big Query access
s3fs 0.4.0 Amazon S3 access
========================= ================== =============================================================
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 06f89ba62c3e4..f6f60e66b57c6 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -68,7 +68,21 @@ If installed, we now require:
+-----------------+-----------------+----------+---------+
| Package | Minimum Version | Required | Changed |
+=================+=================+==========+=========+
-| | | X | X |
+| numpy | 1.18.5 | X | X |
++-----------------+-----------------+----------+---------+
+| pytz | 2020.1 | X | X |
++-----------------+-----------------+----------+---------+
+| python-dateutil | 2.8.1 | X | X |
++-----------------+-----------------+----------+---------+
+| bottleneck | 1.3.1 | | X |
++-----------------+-----------------+----------+---------+
+| numexpr | 2.7.1 | | X |
++-----------------+-----------------+----------+---------+
+| pytest (dev) | 6.0 | | |
++-----------------+-----------------+----------+---------+
+| mypy (dev) | 0.910 | | X |
++-----------------+-----------------+----------+---------+
+| setuptools | 38.6.0 | | |
+-----------------+-----------------+----------+---------+
For `optional libraries <https://pandas.pydata.org/docs/getting_started/install.html>`_ the general recommendation is to use the latest version.
@@ -78,7 +92,45 @@ Optional libraries below the lowest tested version may still work, but are not c
+-----------------+-----------------+---------+
| Package | Minimum Version | Changed |
+=================+=================+=========+
-| | | X |
+| beautifulsoup4 | 4.8.2 | X |
++-----------------+-----------------+---------+
+| fastparquet | 0.4.0 | |
++-----------------+-----------------+---------+
+| fsspec | 0.7.4 | |
++-----------------+-----------------+---------+
+| gcsfs | 0.6.0 | |
++-----------------+-----------------+---------+
+| lxml | 4.5.0 | X |
++-----------------+-----------------+---------+
+| matplotlib | 3.3.2 | X |
++-----------------+-----------------+---------+
+| numba | 0.50.1 | X |
++-----------------+-----------------+---------+
+| openpyxl | 3.0.2 | X |
++-----------------+-----------------+---------+
+| pyarrow | 0.17.0 | |
++-----------------+-----------------+---------+
+| pymysql | 0.10.1 | X |
++-----------------+-----------------+---------+
+| pytables | 3.6.1 | X |
++-----------------+-----------------+---------+
+| s3fs | 0.4.0 | |
++-----------------+-----------------+---------+
+| scipy | 1.4.1 | X |
++-----------------+-----------------+---------+
+| sqlalchemy | 1.3.11 | X |
++-----------------+-----------------+---------+
+| tabulate | 0.8.7 | |
++-----------------+-----------------+---------+
+| xarray | 0.15.1 | X |
++-----------------+-----------------+---------+
+| xlrd | 2.0.1 | X |
++-----------------+-----------------+---------+
+| xlsxwriter | 1.2.2 | X |
++-----------------+-----------------+---------+
+| xlwt | 1.3.0 | |
++-----------------+-----------------+---------+
+| pandas-gbq | 0.14.0 | X |
+-----------------+-----------------+---------+
See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more.
diff --git a/environment.yml b/environment.yml
index 956f3e8dbff74..9396210da3635 100644
--- a/environment.yml
+++ b/environment.yml
@@ -3,9 +3,9 @@ channels:
- conda-forge
dependencies:
# required
- - numpy>=1.17.3
+ - numpy>=1.18.5
- python=3.8
- - python-dateutil>=2.7.3
+ - python-dateutil>=2.8.1
- pytz
# benchmarks
@@ -55,12 +55,12 @@ dependencies:
# testing
- boto3
- botocore>=1.11
- - hypothesis>=3.82
+ - hypothesis>=5.5.3
- moto # mock S3
- flask
- - pytest>=5.0.1
+ - pytest>=6.0
- pytest-cov
- - pytest-xdist>=1.21
+ - pytest-xdist>=1.31
- pytest-asyncio
- pytest-instafail
@@ -71,24 +71,24 @@ dependencies:
# unused (required indirectly may be?)
- ipywidgets
- nbformat
- - notebook>=5.7.5
+ - notebook>=6.0.3
- pip
# optional
- blosc
- - bottleneck>=1.2.1
+ - bottleneck>=1.3.1
- ipykernel
- ipython>=7.11.1
- jinja2 # pandas.Styler
- - matplotlib>=2.2.2 # pandas.plotting, Series.plot, DataFrame.plot
- - numexpr>=2.7.0
- - scipy>=1.2
- - numba>=0.46.0
+ - matplotlib>=3.3.2 # pandas.plotting, Series.plot, DataFrame.plot
+ - numexpr>=2.7.1
+ - scipy>=1.4.1
+ - numba>=0.50.1
# optional for io
# ---------------
# pd.read_html
- - beautifulsoup4>=4.6.0
+ - beautifulsoup4>=4.8.2
- html5lib
- lxml
@@ -99,12 +99,11 @@ dependencies:
- xlwt
- odfpy
- - fastparquet>=0.3.2 # pandas.read_parquet, DataFrame.to_parquet
+ - fastparquet>=0.4.0 # pandas.read_parquet, DataFrame.to_parquet
- pyarrow>=0.17.0 # pandas.read_parquet, DataFrame.to_parquet, pandas.read_feather, DataFrame.to_feather
- python-snappy # required by pyarrow
- - pyqt>=5.9.2 # pandas.read_clipboard
- - pytables>=3.5.1 # pandas.read_hdf, DataFrame.to_hdf
+ - pytables>=3.6.1 # pandas.read_hdf, DataFrame.to_hdf
- s3fs>=0.4.0 # file IO when using 's3://...' path
- fsspec>=0.7.4, <2021.6.0 # for generic remote file operations
- gcsfs>=0.6.0 # file IO when using 'gcs://...' path
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index 941c59592dbbd..651729cd0ad44 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -10,30 +10,30 @@
# Update install.rst when updating versions!
VERSIONS = {
- "bs4": "4.6.0",
- "bottleneck": "1.2.1",
+ "bs4": "4.8.2",
+ "bottleneck": "1.3.1",
"fsspec": "0.7.4",
"fastparquet": "0.4.0",
"gcsfs": "0.6.0",
- "lxml.etree": "4.3.0",
- "matplotlib": "2.2.3",
- "numexpr": "2.7.0",
- "odfpy": "1.3.0",
- "openpyxl": "3.0.0",
- "pandas_gbq": "0.12.0",
+ "lxml.etree": "4.5.0",
+ "matplotlib": "3.3.2",
+ "numexpr": "2.7.1",
+ "odfpy": "1.4.1",
+ "openpyxl": "3.0.2",
+ "pandas_gbq": "0.14.0",
"pyarrow": "0.17.0",
"pytest": "6.0",
"pyxlsb": "1.0.6",
"s3fs": "0.4.0",
- "scipy": "1.2.0",
- "sqlalchemy": "1.3.0",
- "tables": "3.5.1",
+ "scipy": "1.4.1",
+ "sqlalchemy": "1.3.11",
+ "tables": "3.6.1",
"tabulate": "0.8.7",
- "xarray": "0.12.3",
- "xlrd": "1.2.0",
+ "xarray": "0.15.1",
+ "xlrd": "2.0.1",
"xlwt": "1.3.0",
- "xlsxwriter": "1.0.2",
- "numba": "0.46.0",
+ "xlsxwriter": "1.2.2",
+ "numba": "0.50.1",
}
# A mapping from import name to package name (on PyPI) for packages where
diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py
index 619713f28ee2d..4632626c40236 100644
--- a/pandas/compat/numpy/__init__.py
+++ b/pandas/compat/numpy/__init__.py
@@ -13,7 +13,7 @@
np_version_under1p19 = _nlv < Version("1.19")
np_version_under1p20 = _nlv < Version("1.20")
is_numpy_dev = _nlv.dev is not None
-_min_numpy_ver = "1.17.3"
+_min_numpy_ver = "1.18.5"
if _nlv < Version(_min_numpy_ver):
diff --git a/pyproject.toml b/pyproject.toml
index 86b255ab6bf58..5deb92281475b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -22,7 +22,7 @@ requires = [
# build-backend = "setuptools.build_meta"
[tool.black]
-target-version = ['py37', 'py38', 'py39']
+target-version = ['py38', 'py39']
exclude = '''
(
asv_bench/env
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 03c7b7ef41b70..3bf9084f55419 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -1,8 +1,8 @@
# This file is auto-generated from environment.yml, do not modify.
# See that file for comments about the need/usage of each dependency.
-numpy>=1.17.3
-python-dateutil>=2.7.3
+numpy>=1.18.5
+python-dateutil>=2.8.1
pytz
asv
cython>=0.29.21
@@ -33,30 +33,30 @@ pyyaml
requests
boto3
botocore>=1.11
-hypothesis>=3.82
+hypothesis>=5.5.3
moto
flask
-pytest>=5.0.1
+pytest>=6.0
pytest-cov
-pytest-xdist>=1.21
+pytest-xdist>=1.31
pytest-asyncio
pytest-instafail
seaborn
statsmodels
ipywidgets
nbformat
-notebook>=5.7.5
+notebook>=6.0.3
pip
blosc
-bottleneck>=1.2.1
+bottleneck>=1.3.1
ipykernel
ipython>=7.11.1
jinja2
-matplotlib>=2.2.2
-numexpr>=2.7.0
-scipy>=1.2
-numba>=0.46.0
-beautifulsoup4>=4.6.0
+matplotlib>=3.3.2
+numexpr>=2.7.1
+scipy>=1.4.1
+numba>=0.50.1
+beautifulsoup4>=4.8.2
html5lib
lxml
openpyxl
@@ -64,11 +64,10 @@ xlrd
xlsxwriter
xlwt
odfpy
-fastparquet>=0.3.2
+fastparquet>=0.4.0
pyarrow>=0.17.0
python-snappy
-pyqt5>=5.9.2
-tables>=3.5.1
+tables>=3.6.1
s3fs>=0.4.0
fsspec>=0.7.4, <2021.6.0
gcsfs>=0.6.0
diff --git a/setup.cfg b/setup.cfg
index d278deac66f43..9df220280c59f 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -19,7 +19,6 @@ classifiers =
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3 :: Only
- Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Programming Language :: Python :: 3.9
Topic :: Scientific/Engineering
@@ -31,10 +30,10 @@ project_urls =
[options]
packages = find:
install_requires =
- numpy>=1.17.3
- python-dateutil>=2.7.3
- pytz>=2017.3
-python_requires = >=3.7.1
+ numpy>=1.18.5
+ python-dateutil>=2.8.1
+ pytz>=2020.1
+python_requires = >=3.8
include_package_data = True
zip_safe = False
@@ -44,9 +43,9 @@ pandas_plotting_backends =
[options.extras_require]
test =
- hypothesis>=3.58
+ hypothesis>=5.5.3
pytest>=6.0
- pytest-xdist
+ pytest-xdist>=1.31
[options.package_data]
* = templates/*, _libs/**/*.dll
| closes #41678
Most of the new minimum support versions were released between Oct 14, 2019, Python 3.8's initial release date, and June/July 2020. | https://api.github.com/repos/pandas-dev/pandas/pulls/41989 | 2021-06-13T22:22:56Z | 2021-07-04T21:44:01Z | 2021-07-04T21:44:01Z | 2021-08-05T10:22:23Z |
BUG: nan-objects lookup fails with Python3.10 | diff --git a/pandas/_libs/src/klib/khash_python.h b/pandas/_libs/src/klib/khash_python.h
index 87c6283c19a2f..c8e1ca5ebb4d3 100644
--- a/pandas/_libs/src/klib/khash_python.h
+++ b/pandas/_libs/src/klib/khash_python.h
@@ -251,12 +251,105 @@ int PANDAS_INLINE pyobject_cmp(PyObject* a, PyObject* b) {
}
-khint32_t PANDAS_INLINE kh_python_hash_func(PyObject* key){
+Py_hash_t PANDAS_INLINE _Pandas_HashDouble(double val) {
+ //Since Python3.10, nan is no longer has hash 0
+ if (Py_IS_NAN(val)) {
+ return 0;
+ }
+#if PY_VERSION_HEX < 0x030A0000
+ return _Py_HashDouble(val);
+#else
+ return _Py_HashDouble(NULL, val);
+#endif
+}
+
+
+Py_hash_t PANDAS_INLINE floatobject_hash(PyFloatObject* key) {
+ return _Pandas_HashDouble(PyFloat_AS_DOUBLE(key));
+}
+
+
+// replaces _Py_HashDouble with _Pandas_HashDouble
+Py_hash_t PANDAS_INLINE complexobject_hash(PyComplexObject* key) {
+ Py_uhash_t realhash = (Py_uhash_t)_Pandas_HashDouble(key->cval.real);
+ Py_uhash_t imaghash = (Py_uhash_t)_Pandas_HashDouble(key->cval.imag);
+ if (realhash == (Py_uhash_t)-1 || imaghash == (Py_uhash_t)-1) {
+ return -1;
+ }
+ Py_uhash_t combined = realhash + _PyHASH_IMAG * imaghash;
+ if (combined == (Py_uhash_t)-1) {
+ return -2;
+ }
+ return (Py_hash_t)combined;
+}
+
+
+khint32_t PANDAS_INLINE kh_python_hash_func(PyObject* key);
+
+//we could use any hashing algorithm, this is the original CPython's for tuples
+
+#if SIZEOF_PY_UHASH_T > 4
+#define _PandasHASH_XXPRIME_1 ((Py_uhash_t)11400714785074694791ULL)
+#define _PandasHASH_XXPRIME_2 ((Py_uhash_t)14029467366897019727ULL)
+#define _PandasHASH_XXPRIME_5 ((Py_uhash_t)2870177450012600261ULL)
+#define _PandasHASH_XXROTATE(x) ((x << 31) | (x >> 33)) /* Rotate left 31 bits */
+#else
+#define _PandasHASH_XXPRIME_1 ((Py_uhash_t)2654435761UL)
+#define _PandasHASH_XXPRIME_2 ((Py_uhash_t)2246822519UL)
+#define _PandasHASH_XXPRIME_5 ((Py_uhash_t)374761393UL)
+#define _PandasHASH_XXROTATE(x) ((x << 13) | (x >> 19)) /* Rotate left 13 bits */
+#endif
+
+Py_hash_t PANDAS_INLINE tupleobject_hash(PyTupleObject* key) {
+ Py_ssize_t i, len = Py_SIZE(key);
+ PyObject **item = key->ob_item;
+
+ Py_uhash_t acc = _PandasHASH_XXPRIME_5;
+ for (i = 0; i < len; i++) {
+ Py_uhash_t lane = kh_python_hash_func(item[i]);
+ if (lane == (Py_uhash_t)-1) {
+ return -1;
+ }
+ acc += lane * _PandasHASH_XXPRIME_2;
+ acc = _PandasHASH_XXROTATE(acc);
+ acc *= _PandasHASH_XXPRIME_1;
+ }
+
+ /* Add input length, mangled to keep the historical value of hash(()). */
+ acc += len ^ (_PandasHASH_XXPRIME_5 ^ 3527539UL);
+
+ if (acc == (Py_uhash_t)-1) {
+ return 1546275796;
+ }
+ return acc;
+}
+
+
+khint32_t PANDAS_INLINE kh_python_hash_func(PyObject* key) {
+ Py_hash_t hash;
// For PyObject_Hash holds:
// hash(0.0) == 0 == hash(-0.0)
- // hash(X) == 0 if X is a NaN-value
- // so it is OK to use it directly for doubles
- Py_hash_t hash = PyObject_Hash(key);
+ // yet for different nan-objects different hash-values
+ // are possible
+ if (PyFloat_CheckExact(key)) {
+ // we cannot use kh_float64_hash_func
+ // becase float(k) == k holds for any int-object k
+ // and kh_float64_hash_func doesn't respect it
+ hash = floatobject_hash((PyFloatObject*)key);
+ }
+ else if (PyComplex_CheckExact(key)) {
+ // we cannot use kh_complex128_hash_func
+ // becase complex(k,0) == k holds for any int-object k
+ // and kh_complex128_hash_func doesn't respect it
+ hash = complexobject_hash((PyComplexObject*)key);
+ }
+ else if (PyTuple_CheckExact(key)) {
+ hash = tupleobject_hash((PyTupleObject*)key);
+ }
+ else {
+ hash = PyObject_Hash(key);
+ }
+
if (hash == -1) {
PyErr_Clear();
return 0;
diff --git a/pandas/tests/libs/test_hashtable.py b/pandas/tests/libs/test_hashtable.py
index 0edcebdc069f4..a1a43fa6ef300 100644
--- a/pandas/tests/libs/test_hashtable.py
+++ b/pandas/tests/libs/test_hashtable.py
@@ -339,6 +339,29 @@ def test_unique(self, table_type, dtype):
assert np.all(np.isnan(unique)) and len(unique) == 1
+def test_unique_for_nan_objects_floats():
+ table = ht.PyObjectHashTable()
+ keys = np.array([float("nan") for i in range(50)], dtype=np.object_)
+ unique = table.unique(keys)
+ assert len(unique) == 1
+
+
+def test_unique_for_nan_objects_complex():
+ table = ht.PyObjectHashTable()
+ keys = np.array([complex(float("nan"), 1.0) for i in range(50)], dtype=np.object_)
+ unique = table.unique(keys)
+ assert len(unique) == 1
+
+
+def test_unique_for_nan_objects_tuple():
+ table = ht.PyObjectHashTable()
+ keys = np.array(
+ [1] + [(1.0, (float("nan"), 1.0)) for i in range(50)], dtype=np.object_
+ )
+ unique = table.unique(keys)
+ assert len(unique) == 2
+
+
def get_ht_function(fun_name, type_suffix):
return getattr(ht, fun_name)
@@ -497,3 +520,11 @@ def test_ismember_tuple_with_nans():
result = isin(values, comps)
expected = np.array([True, False], dtype=np.bool_)
tm.assert_numpy_array_equal(result, expected)
+
+
+def test_float_complex_int_are_equal_as_objects():
+ values = ["a", 5, 5.0, 5.0 + 0j]
+ comps = list(range(129))
+ result = isin(values, comps)
+ expected = np.array([False, True, True, True], dtype=np.bool_)
+ tm.assert_numpy_array_equal(result, expected)
| - [x] closes #41953
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
This builds upon #41952, which should be integrated first.
We no longer can assume that the CPython's hash function for elements with NaN (float, complex, tuple) will do the right thing (see https://github.com/python/cpython/commit/a07da09ad5bd7d234ccd084a3a0933c290d1b592) and thus need to replace the default CPython's hash-function with our own, similar to the way we handle equality-operator.
We need to use old CPython hash functions for `float` and `complex`, because we would like to keep the equivalency `int(k)==float(k)==complex(k, 0.0)`.
We have more freedom with tuple's hash-function, but still use CPython's implementation, so we get old hash-values.
| https://api.github.com/repos/pandas-dev/pandas/pulls/41988 | 2021-06-13T20:13:41Z | 2021-06-17T19:05:36Z | 2021-06-17T19:05:36Z | 2021-06-17T19:06:14Z |
TST: Un-xfail tests on numpy-dev | diff --git a/pandas/tests/frame/methods/test_to_records.py b/pandas/tests/frame/methods/test_to_records.py
index ba8fe25401e8c..2c96cf291c154 100644
--- a/pandas/tests/frame/methods/test_to_records.py
+++ b/pandas/tests/frame/methods/test_to_records.py
@@ -3,8 +3,6 @@
import numpy as np
import pytest
-from pandas.compat import is_numpy_dev
-
from pandas import (
CategoricalDtype,
DataFrame,
@@ -173,28 +171,20 @@ def test_to_records_with_categorical(self):
),
),
# Pass in a type instance.
- pytest.param(
+ (
{"column_dtypes": str},
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
dtype=[("index", "<i8"), ("A", "<U"), ("B", "<U"), ("C", "<U")],
),
- marks=pytest.mark.xfail(
- is_numpy_dev,
- reason="https://github.com/numpy/numpy/issues/19078",
- ),
),
# Pass in a dtype instance.
- pytest.param(
+ (
{"column_dtypes": np.dtype("unicode")},
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
dtype=[("index", "<i8"), ("A", "<U"), ("B", "<U"), ("C", "<U")],
),
- marks=pytest.mark.xfail(
- is_numpy_dev,
- reason="https://github.com/numpy/numpy/issues/19078",
- ),
),
# Pass in a dictionary (name-only).
(
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
Makes 3.8 npdev green. | https://api.github.com/repos/pandas-dev/pandas/pulls/41987 | 2021-06-13T19:05:06Z | 2021-06-14T16:31:45Z | 2021-06-14T16:31:45Z | 2021-06-17T11:36:01Z |
DOC: update array-like parameters if scalars accepted | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index bf6887ed27005..df9f3d07ce7fd 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -531,7 +531,7 @@ def factorize_array(
mask: np.ndarray | None = None,
) -> tuple[npt.NDArray[np.intp], np.ndarray]:
"""
- Factorize an array-like to codes and uniques.
+ Factorize a numpy array to codes and uniques.
This doesn't do any coercion of types or unboxing before factorization.
@@ -910,7 +910,7 @@ def duplicated(
Parameters
----------
- values : ndarray-like
+ values : nd.array, ExtensionArray or Series
Array over which to check for duplicate values.
keep : {'first', 'last', False}, default 'first'
- ``first`` : Mark duplicates as ``True`` except for the first
@@ -1412,8 +1412,8 @@ def take(
Parameters
----------
- arr : sequence
- Non array-likes (sequences without a dtype) are coerced
+ arr : array-like or scalar value
+ Non array-likes (sequences/scalars without a dtype) are coerced
to an ndarray.
indices : sequence of integers
Indices to be taken.
@@ -1523,11 +1523,11 @@ def searchsorted(arr, value, side="left", sorter=None) -> np.ndarray:
Parameters
----------
- arr: array-like
+ arr: np.ndarray, ExtensionArray, Series
Input array. If `sorter` is None, then it must be sorted in
ascending order, otherwise `sorter` must be an array of indices
that sort it.
- value : array-like
+ value : array-like or scalar
Values to insert into `arr`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given.
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 86a9eb9c4c32a..b362769f50fa8 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -826,8 +826,8 @@ def searchsorted(self, value, side="left", sorter=None):
Parameters
----------
- value : array-like
- Values to insert into `self`.
+ value : array-like, list or scalar
+ Value(s) to insert into `self`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given.
If 'right', return the last such index. If there is no suitable
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 18c79ccc56bad..b1cfcbd69a30b 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -226,7 +226,7 @@ class SparseArray(OpsMixin, PandasObject, ExtensionArray):
Parameters
----------
- data : array-like
+ data : array-like or scalar
A dense array of values to store in the SparseArray. This may contain
`fill_value`.
sparse_index : SparseIndex, optional
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 430f1b57f0b87..9665b8b6af6ac 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -1137,7 +1137,7 @@ def factorize(self, sort: bool = False, na_sentinel: int | None = -1):
Parameters
----------
- value : array-like
+ value : array-like or scalar
Values to insert into `self`.
side : {{'left', 'right'}}, optional
If 'left', the index of the first suitable location found is given.
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index bda7584449983..08287cc296006 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -162,7 +162,7 @@ def is_object_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array-like or dtype to check.
Returns
@@ -316,7 +316,7 @@ def is_datetime64_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array-like or dtype to check.
Returns
@@ -349,7 +349,7 @@ def is_datetime64tz_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array-like or dtype to check.
Returns
@@ -390,7 +390,7 @@ def is_timedelta64_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array-like or dtype to check.
Returns
@@ -424,7 +424,7 @@ def is_period_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array-like or dtype to check.
Returns
@@ -460,7 +460,7 @@ def is_interval_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array-like or dtype to check.
Returns
@@ -498,7 +498,7 @@ def is_categorical_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array-like or dtype to check.
Returns
@@ -534,7 +534,7 @@ def is_string_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -635,7 +635,7 @@ def is_any_int_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -680,7 +680,7 @@ def is_integer_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -732,7 +732,7 @@ def is_signed_integer_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -784,7 +784,7 @@ def is_unsigned_integer_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -828,7 +828,7 @@ def is_int64_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -878,7 +878,7 @@ def is_datetime64_any_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -920,7 +920,7 @@ def is_datetime64_ns_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -970,7 +970,7 @@ def is_timedelta64_ns_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -999,7 +999,7 @@ def is_datetime_or_timedelta_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -1039,7 +1039,7 @@ def is_numeric_v_string_like(a: ArrayLike, b):
Parameters
----------
- a : array-like
+ a : array-like, scalar
The first object to check.
b : array-like, scalar
The second object to check.
@@ -1146,7 +1146,7 @@ def needs_i8_conversion(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -1190,7 +1190,7 @@ def is_numeric_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -1234,7 +1234,7 @@ def is_float_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -1266,7 +1266,7 @@ def is_bool_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -1337,7 +1337,7 @@ def is_extension_type(arr) -> bool:
Parameters
----------
- arr : array-like
+ arr : array-like, scalar
The array-like to check.
Returns
@@ -1489,7 +1489,7 @@ def is_complex_dtype(arr_or_dtype) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
@@ -1546,7 +1546,7 @@ def get_dtype(arr_or_dtype) -> DtypeObj:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array-like or dtype object whose dtype we want to extract.
Returns
@@ -1580,7 +1580,7 @@ def _is_dtype_type(arr_or_dtype, condition) -> bool:
Parameters
----------
- arr_or_dtype : array-like
+ arr_or_dtype : array-like or dtype
The array-like or dtype object whose dtype we want to extract.
condition : callable[Union[np.dtype, ExtensionDtypeType]]
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index d369624d30cdf..ac54038c271db 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -6129,7 +6129,7 @@ def drop(self, labels, errors: str_t = "raise") -> Index:
Parameters
----------
- labels : array-like
+ labels : array-like or scalar
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and existing labels are dropped.
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 139eef5b05d11..ec2e49f560fe4 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -897,7 +897,7 @@ def setitem(self, indexer, value):
Parameters
----------
- indexer : tuple, list-like, array-like, slice
+ indexer : tuple, list-like, array-like, slice, int
The subset of self.values to set
value : object
The value being set
@@ -1461,7 +1461,7 @@ def setitem(self, indexer, value):
Parameters
----------
- indexer : tuple, list-like, array-like, slice
+ indexer : tuple, list-like, array-like, slice, int
The subset of self.values to set
value : object
The value being set
| - [x] based on discussion in #41807
- [x] tests added / passed
- N/A since only doc changes
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- N/A since only doc changes
- [x] whatsnew entry
- Not needed
Based on discussion, I went through all docstrings that had the regex `":.*array-like"` and added a scalar as an accepted argument where appropriate.
| https://api.github.com/repos/pandas-dev/pandas/pulls/41985 | 2021-06-13T17:53:39Z | 2021-07-14T23:47:06Z | 2021-07-14T23:47:05Z | 2021-07-19T12:00:54Z |
Backport PR #41966 on branch 1.3.x (CI: activate azure pipelines/github actions on 1.3.x) | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a5a802c678e20..a62942c7cd948 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -7,6 +7,7 @@ on:
branches:
- master
- 1.2.x
+ - 1.3.x
env:
ENV_FILE: environment.yml
diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml
index 292598dfcab73..d2aa76a3e6110 100644
--- a/.github/workflows/database.yml
+++ b/.github/workflows/database.yml
@@ -7,6 +7,7 @@ on:
branches:
- master
- 1.2.x
+ - 1.3.x
paths-ignore:
- "doc/**"
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index cb7d3fb5cabcf..fa5cf8ead57bd 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -7,6 +7,7 @@ on:
branches:
- master
- 1.2.x
+ - 1.3.x
paths-ignore:
- "doc/**"
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 956feaef5f83e..5ba4471c8d303 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -4,6 +4,7 @@ trigger:
include:
- master
- 1.2.x
+ - 1.3.x
paths:
exclude:
- 'doc/*'
@@ -11,6 +12,7 @@ trigger:
pr:
- master
- 1.2.x
+- 1.3.x
variables:
PYTEST_WORKERS: auto
| Backport PR #41966: CI: activate azure pipelines/github actions on 1.3.x | https://api.github.com/repos/pandas-dev/pandas/pulls/41984 | 2021-06-13T16:52:39Z | 2021-06-13T19:26:09Z | 2021-06-13T19:26:09Z | 2021-06-13T19:26:09Z |
Backport PR #41981 on branch 1.3.x (BLD: Update MANIFEST.in) | diff --git a/MANIFEST.in b/MANIFEST.in
index 1880e6a7208e2..f616fad6b1557 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -44,9 +44,8 @@ global-exclude *.c
global-exclude *.cpp
global-exclude *.h
-global-exclude *.py[codx]
-global-exclude *.px[di]
-global-exclude *.pxi.in
+global-exclude *.py[ocd]
+global-exclude *.pxi
# GH 39321
# csv_dir_path fixture checks the existence of the directory
@@ -56,3 +55,6 @@ prune pandas/tests/io/parser/data
include versioneer.py
include pandas/_version.py
include pandas/io/formats/templates/*.tpl
+
+graft pandas/_libs/src
+graft pandas/_libs/tslibs/src
| Backport PR #41981: BLD: Update MANIFEST.in | https://api.github.com/repos/pandas-dev/pandas/pulls/41983 | 2021-06-13T16:39:43Z | 2021-06-13T16:51:58Z | 2021-06-13T16:51:58Z | 2021-06-13T16:51:58Z |
TST: fix xpass for M1 Mac | diff --git a/pandas/tests/indexes/numeric/test_numeric.py b/pandas/tests/indexes/numeric/test_numeric.py
index 9572aeaf41c91..de75f1dffde56 100644
--- a/pandas/tests/indexes/numeric/test_numeric.py
+++ b/pandas/tests/indexes/numeric/test_numeric.py
@@ -2,6 +2,10 @@
import pytest
from pandas._libs.tslibs import Timestamp
+from pandas.compat import (
+ is_platform_arm,
+ is_platform_mac,
+)
import pandas as pd
from pandas import (
@@ -531,7 +535,10 @@ def test_constructor(self, dtype):
res = Index([1, 2 ** 63 + 1], dtype=dtype)
tm.assert_index_equal(res, idx)
- @pytest.mark.xfail(reason="https://github.com/numpy/numpy/issues/19146")
+ @pytest.mark.xfail(
+ not (is_platform_arm and is_platform_mac()),
+ reason="https://github.com/numpy/numpy/issues/19146",
+ )
def test_constructor_does_not_cast_to_float(self):
# https://github.com/numpy/numpy/issues/19146
values = [0, np.iinfo(np.uint64).max]
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index 17a6d9216ca92..77ca482936298 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -6,7 +6,10 @@
import numpy as np
import pytest
-from pandas.compat import is_platform_arm
+from pandas.compat import (
+ is_platform_arm,
+ is_platform_mac,
+)
from pandas.errors import UnsupportedFunctionCall
from pandas import (
@@ -1073,7 +1076,7 @@ def test_rolling_sem(frame_or_series):
tm.assert_series_equal(result, expected)
-@pytest.mark.xfail(is_platform_arm(), reason="GH 41740")
+@pytest.mark.xfail(is_platform_arm() and not is_platform_mac(), reason="GH 38921")
@pytest.mark.parametrize(
("func", "third_value", "values"),
[
| xref #38921
xref https://github.com/numpy/numpy/issues/19146 | https://api.github.com/repos/pandas-dev/pandas/pulls/41982 | 2021-06-13T14:41:44Z | 2021-06-15T23:33:23Z | 2021-06-15T23:33:23Z | 2021-06-18T02:23:08Z |
BLD: Update MANIFEST.in | diff --git a/MANIFEST.in b/MANIFEST.in
index 1880e6a7208e2..f616fad6b1557 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -44,9 +44,8 @@ global-exclude *.c
global-exclude *.cpp
global-exclude *.h
-global-exclude *.py[codx]
-global-exclude *.px[di]
-global-exclude *.pxi.in
+global-exclude *.py[ocd]
+global-exclude *.pxi
# GH 39321
# csv_dir_path fixture checks the existence of the directory
@@ -56,3 +55,6 @@ prune pandas/tests/io/parser/data
include versioneer.py
include pandas/_version.py
include pandas/io/formats/templates/*.tpl
+
+graft pandas/_libs/src
+graft pandas/_libs/tslibs/src
| xref https://github.com/pandas-dev/pandas/pull/41977#issuecomment-860171367 | https://api.github.com/repos/pandas-dev/pandas/pulls/41981 | 2021-06-13T11:25:41Z | 2021-06-13T16:39:13Z | 2021-06-13T16:39:13Z | 2021-06-13T16:39:18Z |
REF: Refactor assert_index_equal | diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index 1942e07d1b562..a29767153b021 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -314,18 +314,16 @@ def _check_types(left, right, obj="Index") -> None:
return
assert_class_equal(left, right, exact=exact, obj=obj)
+ assert_attr_equal("inferred_type", left, right, obj=obj)
# Skip exact dtype checking when `check_categorical` is False
- if check_categorical:
- assert_attr_equal("dtype", left, right, obj=obj)
- if is_categorical_dtype(left.dtype) and is_categorical_dtype(right.dtype):
+ if is_categorical_dtype(left.dtype) and is_categorical_dtype(right.dtype):
+ if check_categorical:
+ assert_attr_equal("dtype", left, right, obj=obj)
assert_index_equal(left.categories, right.categories, exact=exact)
+ return
- # allow string-like to have different inferred_types
- if left.inferred_type in ("string"):
- assert right.inferred_type in ("string")
- else:
- assert_attr_equal("inferred_type", left, right, obj=obj)
+ assert_attr_equal("dtype", left, right, obj=obj)
def _get_ilevel_values(index, level):
# accept level number only
@@ -437,6 +435,8 @@ def assert_class_equal(left, right, exact: bool | str = True, obj="Input"):
"""
Checks classes are equal.
"""
+ from pandas.core.indexes.numeric import NumericIndex
+
__tracebackhide__ = True
def repr_class(x):
@@ -446,17 +446,16 @@ def repr_class(x):
return type(x).__name__
+ if type(left) == type(right):
+ return
+
if exact == "equiv":
- if type(left) != type(right):
- # allow equivalence of Int64Index/RangeIndex
- types = {type(left).__name__, type(right).__name__}
- if len(types - {"Int64Index", "RangeIndex"}):
- msg = f"{obj} classes are not equivalent"
- raise_assert_detail(obj, msg, repr_class(left), repr_class(right))
- elif exact:
- if type(left) != type(right):
- msg = f"{obj} classes are different"
- raise_assert_detail(obj, msg, repr_class(left), repr_class(right))
+ # accept equivalence of NumericIndex (sub-)classes
+ if isinstance(left, NumericIndex) and isinstance(right, NumericIndex):
+ return
+
+ msg = f"{obj} classes are different"
+ raise_assert_detail(obj, msg, repr_class(left), repr_class(right))
def assert_attr_equal(attr: str, left, right, obj: str = "Attributes"):
diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py
index 1778b6fb9d832..8211b52fed650 100644
--- a/pandas/tests/util/test_assert_index_equal.py
+++ b/pandas/tests/util/test_assert_index_equal.py
@@ -58,15 +58,30 @@ def test_index_equal_length_mismatch(check_exact):
tm.assert_index_equal(idx1, idx2, check_exact=check_exact)
-def test_index_equal_class_mismatch(check_exact):
- msg = """Index are different
+@pytest.mark.parametrize("exact", [False, "equiv"])
+def test_index_equal_class(exact):
+ idx1 = Index([0, 1, 2])
+ idx2 = RangeIndex(3)
+
+ tm.assert_index_equal(idx1, idx2, exact=exact)
+
+
+@pytest.mark.parametrize(
+ "idx_values, msg_str",
+ [
+ [[1, 2, 3.0], "Float64Index\\(\\[1\\.0, 2\\.0, 3\\.0\\], dtype='float64'\\)"],
+ [range(3), "RangeIndex\\(start=0, stop=3, step=1\\)"],
+ ],
+)
+def test_index_equal_class_mismatch(check_exact, idx_values, msg_str):
+ msg = f"""Index are different
Index classes are different
\\[left\\]: Int64Index\\(\\[1, 2, 3\\], dtype='int64'\\)
-\\[right\\]: Float64Index\\(\\[1\\.0, 2\\.0, 3\\.0\\], dtype='float64'\\)"""
+\\[right\\]: {msg_str}"""
idx1 = Index([1, 2, 3])
- idx2 = Index([1, 2, 3.0])
+ idx2 = Index(idx_values)
with pytest.raises(AssertionError, match=msg):
tm.assert_index_equal(idx1, idx2, exact=True, check_exact=check_exact)
| There are currently some issues in `_check_dtypes` in `assert_index_equal` related to #41153:
* `assert_attr_equal("dtype", left, right, obj=obj)` currently isn't run if `check_categorical` is False (even if the indexes are not CategoricalIndexes)
* `assert_class_equal` with `exact='equiv'` should not be restricted to accept equivalence of `Int64Index` and `RangeIndex`, but should accept equivalence of all subclasses of `NumericIndex` (in preparation for #41153).
So, comparing numeric indexes with `assert_index_equal(idx1, idx2, exact="equiv")` we should for otherwise equal content have:
* RangeIndex and Int64Index should pass, because they're both numeric indexes and have the same dtype
* Int64Index and Float64Index should fail, because even though they're both numeric indexes, they have different dtypes
* Int64Index and NumericIndex[int64] should pass, because they're both numeric indexes and have the same dtype
* RangeIndex and NumericIndex[int64] should pass, because they're both numeric indexes and have the same dtype
* Float64Index and NumericIndex[int64] should fail, because even though they're both numeric indexes, they have different dtypes
Conversely, with `exact=True` class comparison should be strict, so:
* RangeIndex and Int64Index should fail, because they're different classes, even though they have the same dtype
* Int64Index and NumericIndex[int64] should fail, because they're different classes, even though they have the same dtype
* etc.
This refactoring does not change behaviour in master, but will make #41153 easier. | https://api.github.com/repos/pandas-dev/pandas/pulls/41980 | 2021-06-13T09:44:51Z | 2021-06-18T01:46:49Z | 2021-06-18T01:46:49Z | 2021-06-18T05:22:27Z |
Backport PR #41977 on branch 1.3.x (BLD: ignore multiple types of file in wheel) | diff --git a/MANIFEST.in b/MANIFEST.in
index d0d93f2cdba8c..1880e6a7208e2 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -17,18 +17,19 @@ global-exclude *.h5
global-exclude *.html
global-exclude *.json
global-exclude *.jsonl
+global-exclude *.msgpack
global-exclude *.pdf
global-exclude *.pickle
global-exclude *.png
global-exclude *.pptx
-global-exclude *.pyc
-global-exclude *.pyd
global-exclude *.ods
global-exclude *.odt
+global-exclude *.orc
global-exclude *.sas7bdat
global-exclude *.sav
global-exclude *.so
global-exclude *.xls
+global-exclude *.xlsb
global-exclude *.xlsm
global-exclude *.xlsx
global-exclude *.xpt
@@ -39,6 +40,14 @@ global-exclude .DS_Store
global-exclude .git*
global-exclude \#*
+global-exclude *.c
+global-exclude *.cpp
+global-exclude *.h
+
+global-exclude *.py[codx]
+global-exclude *.px[di]
+global-exclude *.pxi.in
+
# GH 39321
# csv_dir_path fixture checks the existence of the directory
# exclude the whole directory to avoid running related tests in sdist
| Backport PR #41977: BLD: ignore multiple types of file in wheel | https://api.github.com/repos/pandas-dev/pandas/pulls/41979 | 2021-06-13T05:39:23Z | 2021-06-13T07:38:13Z | 2021-06-13T07:38:13Z | 2021-06-13T07:38:13Z |
BLD: ignore multiple types of file in wheel | diff --git a/MANIFEST.in b/MANIFEST.in
index d0d93f2cdba8c..1880e6a7208e2 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -17,18 +17,19 @@ global-exclude *.h5
global-exclude *.html
global-exclude *.json
global-exclude *.jsonl
+global-exclude *.msgpack
global-exclude *.pdf
global-exclude *.pickle
global-exclude *.png
global-exclude *.pptx
-global-exclude *.pyc
-global-exclude *.pyd
global-exclude *.ods
global-exclude *.odt
+global-exclude *.orc
global-exclude *.sas7bdat
global-exclude *.sav
global-exclude *.so
global-exclude *.xls
+global-exclude *.xlsb
global-exclude *.xlsm
global-exclude *.xlsx
global-exclude *.xpt
@@ -39,6 +40,14 @@ global-exclude .DS_Store
global-exclude .git*
global-exclude \#*
+global-exclude *.c
+global-exclude *.cpp
+global-exclude *.h
+
+global-exclude *.py[codx]
+global-exclude *.px[di]
+global-exclude *.pxi.in
+
# GH 39321
# csv_dir_path fixture checks the existence of the directory
# exclude the whole directory to avoid running related tests in sdist
| xref #40169
| https://api.github.com/repos/pandas-dev/pandas/pulls/41977 | 2021-06-13T00:51:30Z | 2021-06-13T05:38:49Z | 2021-06-13T05:38:49Z | 2021-06-18T02:23:24Z |
REF: De-duplicate MultiIndex._get_indexer | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 96ddf9ce76f53..4de95079f6480 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -3497,6 +3497,13 @@ def _get_fill_indexer(
self, target: Index, method: str_t, limit: int | None = None, tolerance=None
) -> np.ndarray:
+ if self._is_multi:
+ # TODO: get_indexer_with_fill docstring says values must be _sorted_
+ # but that doesn't appear to be enforced
+ return self._engine.get_indexer_with_fill(
+ target=target._values, values=self._values, method=method, limit=limit
+ )
+
target_values = target._get_engine_target()
if self.is_monotonic_increasing and target.is_monotonic_increasing:
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 4dff63ea22e00..02961bc98ec61 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -2672,18 +2672,9 @@ def _get_indexer(
# TODO: explicitly raise here? we only have one test that
# gets here, and it is checking that we raise with method="nearest"
- if method == "pad" or method == "backfill":
- # TODO: get_indexer_with_fill docstring says values must be _sorted_
- # but that doesn't appear to be enforced
- indexer = self._engine.get_indexer_with_fill(
- target=target._values, values=self._values, method=method, limit=limit
- )
- else:
- indexer = self._engine.get_indexer(target._values)
-
# Note: we only get here (in extant tests at least) with
# target.nlevels == self.nlevels
- return ensure_platform_int(indexer)
+ return super()._get_indexer(target, method, limit, tolerance)
def get_slice_bound(
self, label: Hashable | Sequence[Hashable], side: str, kind: str | None = None
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41976 | 2021-06-12T23:08:01Z | 2021-06-15T23:48:23Z | 2021-06-15T23:48:23Z | 2021-06-16T00:21:47Z |
BUG: UInt64Index.where with int64 value | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index bc75d948ba4ce..1e5065748c631 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -947,6 +947,8 @@ Numeric
- Bug in :meth:`Series.count` would result in an ``int32`` result on 32-bit platforms when argument ``level=None`` (:issue:`40908`)
- Bug in :class:`Series` and :class:`DataFrame` reductions with methods ``any`` and ``all`` not returning Boolean results for object data (:issue:`12863`, :issue:`35450`, :issue:`27709`)
- Bug in :meth:`Series.clip` would fail if the Series contains NA values and has nullable int or float as a data type (:issue:`40851`)
+- Bug in :meth:`UInt64Index.where` and :meth:`UInt64Index.putmask` with an ``np.int64`` dtype ``other`` incorrectly raising ``TypeError`` (:issue:`41974`)
+
Conversion
^^^^^^^^^^
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py
index ea2d5d9eec6ac..ce93cdff09ae0 100644
--- a/pandas/core/indexes/numeric.py
+++ b/pandas/core/indexes/numeric.py
@@ -370,6 +370,16 @@ class UInt64Index(IntegerIndex):
_default_dtype = np.dtype(np.uint64)
_dtype_validation_metadata = (is_unsigned_integer_dtype, "unsigned integer")
+ def _validate_fill_value(self, value):
+ # e.g. np.array([1]) we want np.array([1], dtype=np.uint64)
+ # see test_where_uin64
+ super()._validate_fill_value(value)
+ if hasattr(value, "dtype") and is_signed_integer_dtype(value.dtype):
+ if (value >= 0).all():
+ return value.astype(self.dtype)
+ raise TypeError
+ return value
+
class Float64Index(NumericIndex):
_index_descr_args = {
diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py
index 5f2f8f75045bb..540dbde609470 100644
--- a/pandas/tests/indexes/numeric/test_indexing.py
+++ b/pandas/tests/indexes/numeric/test_indexing.py
@@ -376,6 +376,19 @@ def test_where(self, klass, index):
result = index.where(klass(cond))
tm.assert_index_equal(result, expected)
+ def test_where_uin64(self):
+ idx = UInt64Index([0, 6, 2])
+ mask = np.array([False, True, False])
+ other = np.array([1], dtype=np.int64)
+
+ expected = UInt64Index([1, 6, 1])
+
+ result = idx.where(mask, other)
+ tm.assert_index_equal(result, expected)
+
+ result = idx.putmask(~mask, other)
+ tm.assert_index_equal(result, expected)
+
class TestTake:
@pytest.mark.parametrize("klass", [Float64Index, Int64Index, UInt64Index])
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41974 | 2021-06-12T21:11:03Z | 2021-06-15T23:49:03Z | 2021-06-15T23:49:03Z | 2021-06-16T00:26:00Z |
PERF: indexing on UInt64Index with int64s | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index eaba30012a5b8..96ddf9ce76f53 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -5303,6 +5303,13 @@ def _maybe_promote(self, other: Index) -> tuple[Index, Index]:
if not is_object_dtype(self.dtype):
return self.astype("object"), other.astype("object")
+ elif self.dtype.kind == "u" and other.dtype.kind == "i":
+ # GH#41873
+ if other.min() >= 0:
+ # lookup min as it may be cached
+ # TODO: may need itemsize check if we have non-64-bit Indexes
+ return self, other.astype(self.dtype)
+
if not is_object_dtype(self.dtype) and is_object_dtype(other.dtype):
# Reverse op so we dont need to re-implement on the subclasses
other, self = other._maybe_promote(self)
| - [x] closes #41873
- [ ] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41972 | 2021-06-12T20:08:10Z | 2021-06-15T21:05:57Z | 2021-06-15T21:05:57Z | 2021-06-15T21:44:19Z |
CI: mark window online test slow | diff --git a/pandas/tests/window/test_online.py b/pandas/tests/window/test_online.py
index c7580650926da..461c62c07326d 100644
--- a/pandas/tests/window/test_online.py
+++ b/pandas/tests/window/test_online.py
@@ -22,6 +22,7 @@ def test_invalid_update(self):
):
online_ewm.mean(update=df.head(1))
+ @pytest.mark.slow
@pytest.mark.parametrize(
"obj", [DataFrame({"a": range(5), "b": range(5)}), Series(range(5), name="foo")]
)
| Seems like the new online tests added increase test runtime a lot, making failures like https://dev.azure.com/pandas-dev/pandas/_build/results?buildId=61437&view=logs&j=404760ec-14d3-5d48-e580-13034792878f&t=f81e4cc8-d61a-5fb8-36be-36768e5c561a and
https://dev.azure.com/pandas-dev/pandas/_build/results?buildId=61437&view=logs&j=404760ec-14d3-5d48-e580-13034792878f&t=f81e4cc8-d61a-5fb8-36be-36768e5c561a
more common. Slowest durations showing this are below, have marked these as slow as a potential solution
```
============================ slowest 30 durations =============================
99.91s call pandas/tests/resample/test_base.py::test_resample_interpolate[period_range-pi-_index_start1-_index_end1]
47.56s call pandas/tests/resample/test_period_index.py::TestPeriodIndex::test_weekly_upsample[end-D-FRI]
47.36s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-True-True-True-obj1]
45.55s teardown pandas/tests/window/test_rolling.py::test_rolling_zero_window
30.25s call pandas/tests/tslibs/test_timezones.py::test_cache_keys_are_distinct_for_pytz_vs_dateutil[America/Argentina/San_Luis]
28.37s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-True-True-True-obj0]
23.03s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-False-True-True-obj1]
23.00s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-True-False-True-obj1]
20.95s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-True-False-True-obj0]
20.30s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-False-True-True-obj0]
19.94s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-True-True-False-obj1]
19.81s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-False-True-False-obj0]
19.37s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-True-False-False-obj1]
19.25s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-True-False-False-obj0]
18.13s call pandas/tests/test_sorting.py::TestSorting::test_int64_overflow_moar
18.10s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-True-True-False-obj0]
18.07s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-False-True-False-obj1]
17.17s call pandas/tests/window/test_numba.py::TestEngine::test_numba_vs_cython_apply[True-False-False-False-True]
17.16s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-False-False-True-obj1]
16.84s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[False-True-True-False-True-obj1]
16.75s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-False-False-True-obj0]
16.48s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[False-True-True-True-True-obj1]
16.47s setup pandas/tests/io/test_fsspec.py::test_from_s3_csv
16.36s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[False-True-False-True-True-obj1]
15.93s call pandas/tests/io/test_compression.py::test_with_missing_lzma
15.83s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[False-True-False-False-True-obj1]
15.13s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-False-False-False-obj1]
14.46s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[False-True-True-True-True-obj0]
14.14s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[True-True-False-False-False-obj0]
14.00s call pandas/tests/window/test_online.py::TestEWM::test_online_vs_non_online_mean[False-True-False-True-False-obj0]
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/41971 | 2021-06-12T19:43:59Z | 2021-06-15T01:12:49Z | 2021-06-15T01:12:48Z | 2021-06-15T04:52:36Z |
ENH: nullables use Kleene logic for any/all reductions | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 7b10a0f39bdbd..6fd84bf29e9c5 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -123,6 +123,7 @@ Other enhancements
- Methods that relied on hashmap based algos such as :meth:`DataFrameGroupBy.value_counts`, :meth:`DataFrameGroupBy.count` and :func:`factorize` ignored imaginary component for complex numbers (:issue:`17927`)
- Add :meth:`Series.str.removeprefix` and :meth:`Series.str.removesuffix` introduced in Python 3.9 to remove pre-/suffixes from string-type :class:`Series` (:issue:`36944`)
- Attempting to write into a file in missing parent directory with :meth:`DataFrame.to_csv`, :meth:`DataFrame.to_html`, :meth:`DataFrame.to_excel`, :meth:`DataFrame.to_feather`, :meth:`DataFrame.to_parquet`, :meth:`DataFrame.to_stata`, :meth:`DataFrame.to_json`, :meth:`DataFrame.to_pickle`, and :meth:`DataFrame.to_xml` now explicitly mentions missing parent directory, the same is true for :class:`Series` counterparts (:issue:`24306`)
+- :meth:`IntegerArray.all` , :meth:`IntegerArray.any`, :meth:`FloatingArray.any`, and :meth:`FloatingArray.all` use Kleene logic (:issue:`41967`)
- Added support for nullable boolean and integer types in :meth:`DataFrame.to_stata`, :class:`~pandas.io.stata.StataWriter`, :class:`~pandas.io.stata.StataWriter117`, and :class:`~pandas.io.stata.StataWriterUTF8` (:issue:`40855`)
-
diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py
index 9769183700f27..66fc840f9821d 100644
--- a/pandas/core/arrays/boolean.py
+++ b/pandas/core/arrays/boolean.py
@@ -21,7 +21,6 @@
npt,
type_t,
)
-from pandas.compat.numpy import function as nv
from pandas.core.dtypes.common import (
is_bool_dtype,
@@ -310,6 +309,9 @@ class BooleanArray(BaseMaskedArray):
# The value used to fill '_data' to avoid upcasting
_internal_fill_value = False
+ # Fill values used for any/all
+ _truthy_value = True
+ _falsey_value = False
_TRUE_VALUES = {"True", "TRUE", "true", "1", "1.0"}
_FALSE_VALUES = {"False", "FALSE", "false", "0", "0.0"}
@@ -490,141 +492,6 @@ def _values_for_argsort(self) -> np.ndarray:
data[self._mask] = -1
return data
- def any(self, *, skipna: bool = True, **kwargs):
- """
- Return whether any element is True.
-
- Returns False unless there is at least one element that is True.
- By default, NAs are skipped. If ``skipna=False`` is specified and
- missing values are present, similar :ref:`Kleene logic <boolean.kleene>`
- is used as for logical operations.
-
- Parameters
- ----------
- skipna : bool, default True
- Exclude NA values. If the entire array is NA and `skipna` is
- True, then the result will be False, as for an empty array.
- If `skipna` is False, the result will still be True if there is
- at least one element that is True, otherwise NA will be returned
- if there are NA's present.
- **kwargs : any, default None
- Additional keywords have no effect but might be accepted for
- compatibility with NumPy.
-
- Returns
- -------
- bool or :attr:`pandas.NA`
-
- See Also
- --------
- numpy.any : Numpy version of this method.
- BooleanArray.all : Return whether all elements are True.
-
- Examples
- --------
- The result indicates whether any element is True (and by default
- skips NAs):
-
- >>> pd.array([True, False, True]).any()
- True
- >>> pd.array([True, False, pd.NA]).any()
- True
- >>> pd.array([False, False, pd.NA]).any()
- False
- >>> pd.array([], dtype="boolean").any()
- False
- >>> pd.array([pd.NA], dtype="boolean").any()
- False
-
- With ``skipna=False``, the result can be NA if this is logically
- required (whether ``pd.NA`` is True or False influences the result):
-
- >>> pd.array([True, False, pd.NA]).any(skipna=False)
- True
- >>> pd.array([False, False, pd.NA]).any(skipna=False)
- <NA>
- """
- kwargs.pop("axis", None)
- nv.validate_any((), kwargs)
-
- values = self._data.copy()
- np.putmask(values, self._mask, False)
- result = values.any()
- if skipna:
- return result
- else:
- if result or len(self) == 0 or not self._mask.any():
- return result
- else:
- return self.dtype.na_value
-
- def all(self, *, skipna: bool = True, **kwargs):
- """
- Return whether all elements are True.
-
- Returns True unless there is at least one element that is False.
- By default, NAs are skipped. If ``skipna=False`` is specified and
- missing values are present, similar :ref:`Kleene logic <boolean.kleene>`
- is used as for logical operations.
-
- Parameters
- ----------
- skipna : bool, default True
- Exclude NA values. If the entire array is NA and `skipna` is
- True, then the result will be True, as for an empty array.
- If `skipna` is False, the result will still be False if there is
- at least one element that is False, otherwise NA will be returned
- if there are NA's present.
- **kwargs : any, default None
- Additional keywords have no effect but might be accepted for
- compatibility with NumPy.
-
- Returns
- -------
- bool or :attr:`pandas.NA`
-
- See Also
- --------
- numpy.all : Numpy version of this method.
- BooleanArray.any : Return whether any element is True.
-
- Examples
- --------
- The result indicates whether any element is True (and by default
- skips NAs):
-
- >>> pd.array([True, True, pd.NA]).all()
- True
- >>> pd.array([True, False, pd.NA]).all()
- False
- >>> pd.array([], dtype="boolean").all()
- True
- >>> pd.array([pd.NA], dtype="boolean").all()
- True
-
- With ``skipna=False``, the result can be NA if this is logically
- required (whether ``pd.NA`` is True or False influences the result):
-
- >>> pd.array([True, True, pd.NA]).all(skipna=False)
- <NA>
- >>> pd.array([True, False, pd.NA]).all(skipna=False)
- False
- """
- kwargs.pop("axis", None)
- nv.validate_all((), kwargs)
-
- values = self._data.copy()
- np.putmask(values, self._mask, True)
- result = values.all()
-
- if skipna:
- return result
- else:
- if not result or len(self) == 0 or not self._mask.any():
- return result
- else:
- return self.dtype.na_value
-
def _logical_method(self, other, op):
assert op.__name__ in {"or_", "ror_", "and_", "rand_", "xor", "rxor"}
@@ -753,13 +620,6 @@ def _arith_method(self, other, op):
return self._maybe_mask_result(result, mask, other, op_name)
- def _reduce(self, name: str, *, skipna: bool = True, **kwargs):
-
- if name in {"any", "all"}:
- return getattr(self, name)(skipna=skipna, **kwargs)
-
- return super()._reduce(name, skipna=skipna, **kwargs)
-
def _maybe_mask_result(self, result, mask, other, op_name: str):
"""
Parameters
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py
index 25b4076bd23c6..066f6ebdfcaa6 100644
--- a/pandas/core/arrays/floating.py
+++ b/pandas/core/arrays/floating.py
@@ -245,6 +245,9 @@ class FloatingArray(NumericArray):
# The value used to fill '_data' to avoid upcasting
_internal_fill_value = 0.0
+ # Fill values used for any/all
+ _truthy_value = 1.0
+ _falsey_value = 0.0
@cache_readonly
def dtype(self) -> FloatingDtype:
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py
index e62a2f95b0340..078adeb11d3fb 100644
--- a/pandas/core/arrays/integer.py
+++ b/pandas/core/arrays/integer.py
@@ -307,6 +307,9 @@ class IntegerArray(NumericArray):
# The value used to fill '_data' to avoid upcasting
_internal_fill_value = 1
+ # Fill values used for any/all
+ _truthy_value = 1
+ _falsey_value = 0
@cache_readonly
def dtype(self) -> _IntegerDtype:
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index e40d8b74c768c..23b9eeff03d4c 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -64,7 +64,7 @@
if TYPE_CHECKING:
from pandas import Series
from pandas.core.arrays import BooleanArray
-
+from pandas.compat.numpy import function as nv
BaseMaskedArrayT = TypeVar("BaseMaskedArrayT", bound="BaseMaskedArray")
@@ -115,6 +115,9 @@ class BaseMaskedArray(OpsMixin, ExtensionArray):
# The value used to fill '_data' to avoid upcasting
_internal_fill_value: Scalar
+ # Fill values used for any/all
+ _truthy_value = Scalar # bool(_truthy_value) = True
+ _falsey_value = Scalar # bool(_falsey_value) = False
def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False):
# values is supposed to already be validated in the subclass
@@ -518,6 +521,9 @@ def value_counts(self, dropna: bool = True) -> Series:
return Series(counts, index=index)
def _reduce(self, name: str, *, skipna: bool = True, **kwargs):
+ if name in {"any", "all"}:
+ return getattr(self, name)(skipna=skipna, **kwargs)
+
data = self._data
mask = self._mask
@@ -537,3 +543,156 @@ def _reduce(self, name: str, *, skipna: bool = True, **kwargs):
return libmissing.NA
return result
+
+ def any(self, *, skipna: bool = True, **kwargs):
+ """
+ Return whether any element is truthy.
+
+ Returns False unless there is at least one element that is truthy.
+ By default, NAs are skipped. If ``skipna=False`` is specified and
+ missing values are present, similar :ref:`Kleene logic <boolean.kleene>`
+ is used as for logical operations.
+
+ .. versionchanged:: 1.4.0
+
+ Parameters
+ ----------
+ skipna : bool, default True
+ Exclude NA values. If the entire array is NA and `skipna` is
+ True, then the result will be False, as for an empty array.
+ If `skipna` is False, the result will still be True if there is
+ at least one element that is truthy, otherwise NA will be returned
+ if there are NA's present.
+ **kwargs : any, default None
+ Additional keywords have no effect but might be accepted for
+ compatibility with NumPy.
+
+ Returns
+ -------
+ bool or :attr:`pandas.NA`
+
+ See Also
+ --------
+ numpy.any : Numpy version of this method.
+ BaseMaskedArray.all : Return whether all elements are truthy.
+
+ Examples
+ --------
+ The result indicates whether any element is truthy (and by default
+ skips NAs):
+
+ >>> pd.array([True, False, True]).any()
+ True
+ >>> pd.array([True, False, pd.NA]).any()
+ True
+ >>> pd.array([False, False, pd.NA]).any()
+ False
+ >>> pd.array([], dtype="boolean").any()
+ False
+ >>> pd.array([pd.NA], dtype="boolean").any()
+ False
+ >>> pd.array([pd.NA], dtype="Float64").any()
+ False
+
+ With ``skipna=False``, the result can be NA if this is logically
+ required (whether ``pd.NA`` is True or False influences the result):
+
+ >>> pd.array([True, False, pd.NA]).any(skipna=False)
+ True
+ >>> pd.array([1, 0, pd.NA]).any(skipna=False)
+ True
+ >>> pd.array([False, False, pd.NA]).any(skipna=False)
+ <NA>
+ >>> pd.array([0, 0, pd.NA]).any(skipna=False)
+ <NA>
+ """
+ kwargs.pop("axis", None)
+ nv.validate_any((), kwargs)
+
+ values = self._data.copy()
+ np.putmask(values, self._mask, self._falsey_value)
+ result = values.any()
+ if skipna:
+ return result
+ else:
+ if result or len(self) == 0 or not self._mask.any():
+ return result
+ else:
+ return self.dtype.na_value
+
+ def all(self, *, skipna: bool = True, **kwargs):
+ """
+ Return whether all elements are truthy.
+
+ Returns True unless there is at least one element that is falsey.
+ By default, NAs are skipped. If ``skipna=False`` is specified and
+ missing values are present, similar :ref:`Kleene logic <boolean.kleene>`
+ is used as for logical operations.
+
+ .. versionchanged:: 1.4.0
+
+ Parameters
+ ----------
+ skipna : bool, default True
+ Exclude NA values. If the entire array is NA and `skipna` is
+ True, then the result will be True, as for an empty array.
+ If `skipna` is False, the result will still be False if there is
+ at least one element that is falsey, otherwise NA will be returned
+ if there are NA's present.
+ **kwargs : any, default None
+ Additional keywords have no effect but might be accepted for
+ compatibility with NumPy.
+
+ Returns
+ -------
+ bool or :attr:`pandas.NA`
+
+ See Also
+ --------
+ numpy.all : Numpy version of this method.
+ BooleanArray.any : Return whether any element is truthy.
+
+ Examples
+ --------
+ The result indicates whether all elements are truthy (and by default
+ skips NAs):
+
+ >>> pd.array([True, True, pd.NA]).all()
+ True
+ >>> pd.array([1, 1, pd.NA]).all()
+ True
+ >>> pd.array([True, False, pd.NA]).all()
+ False
+ >>> pd.array([], dtype="boolean").all()
+ True
+ >>> pd.array([pd.NA], dtype="boolean").all()
+ True
+ >>> pd.array([pd.NA], dtype="Float64").all()
+ True
+
+ With ``skipna=False``, the result can be NA if this is logically
+ required (whether ``pd.NA`` is True or False influences the result):
+
+ >>> pd.array([True, True, pd.NA]).all(skipna=False)
+ <NA>
+ >>> pd.array([1, 1, pd.NA]).all(skipna=False)
+ <NA>
+ >>> pd.array([True, False, pd.NA]).all(skipna=False)
+ False
+ >>> pd.array([1, 0, pd.NA]).all(skipna=False)
+ False
+ """
+ kwargs.pop("axis", None)
+ nv.validate_all((), kwargs)
+
+ values = self._data.copy()
+ np.putmask(values, self._mask, self._truthy_value)
+ result = values.all()
+
+ if skipna:
+ return result
+ else:
+ if not result or len(self) == 0 or not self._mask.any():
+ return result
+ else:
+ return self.dtype.na_value
diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py
index 395540993dc15..2ee26e139f3a6 100644
--- a/pandas/tests/extension/test_boolean.py
+++ b/pandas/tests/extension/test_boolean.py
@@ -381,6 +381,7 @@ def check_reduce(self, s, op_name, skipna):
tm.assert_almost_equal(result, expected)
+@pytest.mark.skip(reason="Tested in tests/reductions/test_reductions.py")
class TestBooleanReduce(base.BaseBooleanReduceTests):
pass
diff --git a/pandas/tests/extension/test_floating.py b/pandas/tests/extension/test_floating.py
index 617dfc694741e..f4d3243b5129f 100644
--- a/pandas/tests/extension/test_floating.py
+++ b/pandas/tests/extension/test_floating.py
@@ -211,6 +211,7 @@ def check_reduce(self, s, op_name, skipna):
tm.assert_almost_equal(result, expected)
+@pytest.mark.skip(reason="Tested in tests/reductions/test_reductions.py")
class TestBooleanReduce(base.BaseBooleanReduceTests):
pass
diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py
index 2305edc1e1327..2cf4f8e415770 100644
--- a/pandas/tests/extension/test_integer.py
+++ b/pandas/tests/extension/test_integer.py
@@ -243,6 +243,7 @@ def check_reduce(self, s, op_name, skipna):
tm.assert_almost_equal(result, expected)
+@pytest.mark.skip(reason="Tested in tests/reductions/test_reductions.py")
class TestBooleanReduce(base.BaseBooleanReduceTests):
pass
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index 513b9af18d2b6..62aae33134f60 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -964,6 +964,7 @@ def test_any_all_object_dtype_missing(self, data, bool_agg_func):
expected = bool_agg_func == "any" and None not in data
assert result == expected
+ @pytest.mark.parametrize("dtype", ["boolean", "Int64", "UInt64", "Float64"])
@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.parametrize(
@@ -971,18 +972,19 @@ def test_any_all_object_dtype_missing(self, data, bool_agg_func):
# [skipna=True/any, skipna=True/all]]
"data,expected_data",
[
- ([False, False, False], [[False, False], [False, False]]),
- ([True, True, True], [[True, True], [True, True]]),
+ ([0, 0, 0], [[False, False], [False, False]]),
+ ([1, 1, 1], [[True, True], [True, True]]),
([pd.NA, pd.NA, pd.NA], [[pd.NA, pd.NA], [False, True]]),
- ([False, pd.NA, False], [[pd.NA, False], [False, False]]),
- ([True, pd.NA, True], [[True, pd.NA], [True, True]]),
- ([True, pd.NA, False], [[True, False], [True, False]]),
+ ([0, pd.NA, 0], [[pd.NA, False], [False, False]]),
+ ([1, pd.NA, 1], [[True, pd.NA], [True, True]]),
+ ([1, pd.NA, 0], [[True, False], [True, False]]),
],
)
- def test_any_all_boolean_kleene_logic(
- self, bool_agg_func, skipna, data, expected_data
+ def test_any_all_nullable_kleene_logic(
+ self, bool_agg_func, skipna, data, dtype, expected_data
):
- ser = Series(data, dtype="boolean")
+ # GH-37506, GH-41967
+ ser = Series(data, dtype=dtype)
expected = expected_data[skipna][bool_agg_func == "all"]
result = getattr(ser, bool_agg_func)(skipna=skipna)
| - [x] xref #41967
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
This gives consistency for nullable dtype treatment across `.any/.all` and the groupby versions which already used Kleene logic. Diff looks big, but this is just moving `BooleanArray.any` and `BooleanArray.all` to `BaseMaskedArray` | https://api.github.com/repos/pandas-dev/pandas/pulls/41970 | 2021-06-12T19:19:37Z | 2021-09-21T14:09:19Z | 2021-09-21T14:09:19Z | 2021-09-21T20:59:42Z |
BUG: stacklevel for multidimensional indexing warning #31479 | diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py
index ed4b1a3fbb39c..ef9b48911dfa1 100644
--- a/pandas/core/indexers.py
+++ b/pandas/core/indexers.py
@@ -13,6 +13,7 @@
AnyArrayLike,
ArrayLike,
)
+from pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.common import (
is_array_like,
@@ -375,7 +376,7 @@ def deprecate_ndim_indexing(result, stacklevel: int = 3):
"is deprecated and will be removed in a future "
"version. Convert to a numpy array before indexing instead.",
FutureWarning,
- stacklevel=stacklevel,
+ stacklevel=find_stack_level(),
)
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index cef756b709f70..54050e4a49b84 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -724,13 +724,10 @@ def test_engine_reference_cycle(self, simple_index):
assert len(gc.get_referrers(index)) == nrefs_pre
def test_getitem_2d_deprecated(self, simple_index):
- # GH#30588
+ # GH#30588, GH#31479
idx = simple_index
msg = "Support for multi-dimensional indexing"
- check = not isinstance(idx, (RangeIndex, CategoricalIndex))
- with tm.assert_produces_warning(
- FutureWarning, match=msg, check_stacklevel=check
- ):
+ with tm.assert_produces_warning(FutureWarning, match=msg):
res = idx[:, None]
assert isinstance(res, np.ndarray), type(res)
| - [x] closes #31479
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41969 | 2021-06-12T17:59:57Z | 2021-06-15T23:48:02Z | 2021-06-15T23:48:02Z | 2021-06-16T00:30:28Z |
DOC: 1.3.0 release notes addition and doc fix | diff --git a/doc/source/reference/style.rst b/doc/source/reference/style.rst
index 5a2ff803f0323..ae3647185f93d 100644
--- a/doc/source/reference/style.rst
+++ b/doc/source/reference/style.rst
@@ -34,7 +34,6 @@ Style application
Styler.apply
Styler.applymap
- Styler.where
Styler.format
Styler.set_td_classes
Styler.set_table_styles
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index bc75d948ba4ce..414794dd6a56e 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -812,6 +812,7 @@ Other Deprecations
- Using ``.astype`` to convert between ``datetime64[ns]`` dtype and :class:`DatetimeTZDtype` is deprecated and will raise in a future version, use ``obj.tz_localize`` or ``obj.dt.tz_localize`` instead (:issue:`38622`)
- Deprecated casting ``datetime.date`` objects to ``datetime64`` when used as ``fill_value`` in :meth:`DataFrame.unstack`, :meth:`DataFrame.shift`, :meth:`Series.shift`, and :meth:`DataFrame.reindex`, pass ``pd.Timestamp(dateobj)`` instead (:issue:`39767`)
- Deprecated :meth:`.Styler.set_na_rep` and :meth:`.Styler.set_precision` in favour of :meth:`.Styler.format` with ``na_rep`` and ``precision`` as existing and new input arguments respectively (:issue:`40134`, :issue:`40425`)
+- Deprecated :meth:`.Styler.where` in favour of using an alternative formulation with :meth:`Styler.applymap` (:issue:`40821`)
- Deprecated allowing partial failure in :meth:`Series.transform` and :meth:`DataFrame.transform` when ``func`` is list-like or dict-like and raises anything but ``TypeError``; ``func`` raising anything but a ``TypeError`` will raise in a future version (:issue:`40211`)
- Deprecated arguments ``error_bad_lines`` and ``warn_bad_lines`` in :meth:`read_csv` and :meth:`read_table` in favor of argument ``on_bad_lines`` (:issue:`15122`)
- Deprecated support for ``np.ma.mrecords.MaskedRecords`` in the :class:`DataFrame` constructor, pass ``{name: data[name] for name in data.dtype.names}`` instead (:issue:`40363`)
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 93c3843b36846..c5aba539bd2dd 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -1206,12 +1206,14 @@ def where(
recommend using instead.
The example:
+
>>> df = pd.DataFrame([[1, 2], [3, 4]])
>>> def cond(v, limit=4):
... return v > 1 and v != limit
>>> df.style.where(cond, value='color:green;', other='color:red;')
should be refactored to:
+
>>> def style_func(v, value, other, limit=4):
... cond = v > 1 and v != limit
... return value if cond else other
| https://api.github.com/repos/pandas-dev/pandas/pulls/41968 | 2021-06-12T17:43:34Z | 2021-06-15T19:44:39Z | 2021-06-15T19:44:38Z | 2021-06-16T13:22:17Z | |
CI: activate azure pipelines/github actions on 1.3.x | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a5a802c678e20..a62942c7cd948 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -7,6 +7,7 @@ on:
branches:
- master
- 1.2.x
+ - 1.3.x
env:
ENV_FILE: environment.yml
diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml
index 292598dfcab73..d2aa76a3e6110 100644
--- a/.github/workflows/database.yml
+++ b/.github/workflows/database.yml
@@ -7,6 +7,7 @@ on:
branches:
- master
- 1.2.x
+ - 1.3.x
paths-ignore:
- "doc/**"
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index cb7d3fb5cabcf..fa5cf8ead57bd 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -7,6 +7,7 @@ on:
branches:
- master
- 1.2.x
+ - 1.3.x
paths-ignore:
- "doc/**"
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 956feaef5f83e..5ba4471c8d303 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -4,6 +4,7 @@ trigger:
include:
- master
- 1.2.x
+ - 1.3.x
paths:
exclude:
- 'doc/*'
@@ -11,6 +12,7 @@ trigger:
pr:
- master
- 1.2.x
+- 1.3.x
variables:
PYTEST_WORKERS: auto
| This is milestoned 1.4 since the config is on master. (and we don't want the autobackport) | https://api.github.com/repos/pandas-dev/pandas/pulls/41966 | 2021-06-12T13:08:38Z | 2021-06-13T07:50:54Z | 2021-06-13T07:50:54Z | 2021-06-13T16:54:02Z |
Bug in melt raising Error with dup columns as value vars | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index dd95f9088e3da..1814420cf4f24 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -1148,6 +1148,7 @@ Reshaping
- Bug in :func:`to_datetime` raising an error when the input sequence contained unhashable items (:issue:`39756`)
- Bug in :meth:`Series.explode` preserving the index when ``ignore_index`` was ``True`` and values were scalars (:issue:`40487`)
- Bug in :func:`to_datetime` raising a ``ValueError`` when :class:`Series` contains ``None`` and ``NaT`` and has more than 50 elements (:issue:`39882`)
+- Bug in :meth:`DataFrame.melt` raising ``InvalidIndexError`` when :class:`DataFrame` has duplicate columns used as ``value_vars`` (:issue:`41951`)
Sparse
^^^^^^
diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py
index 6a0fad9ee729b..56814b7692292 100644
--- a/pandas/core/reshape/melt.py
+++ b/pandas/core/reshape/melt.py
@@ -21,6 +21,7 @@
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.missing import notna
+import pandas.core.algorithms as algos
from pandas.core.arrays import Categorical
import pandas.core.common as com
from pandas.core.indexes.api import (
@@ -106,7 +107,7 @@ def melt(
id_vars + value_vars
)
else:
- idx = frame.columns.get_indexer(id_vars + value_vars)
+ idx = algos.unique(frame.columns.get_indexer_for(id_vars + value_vars))
frame = frame.iloc[:, idx]
else:
frame = frame.copy()
diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py
index a950c648838ff..4972cb34aac69 100644
--- a/pandas/tests/reshape/test_melt.py
+++ b/pandas/tests/reshape/test_melt.py
@@ -403,6 +403,15 @@ def test_ignore_index_name_and_type(self):
tm.assert_frame_equal(result, expected)
+ def test_melt_with_duplicate_columns(self):
+ # GH#41951
+ df = DataFrame([["id", 2, 3]], columns=["a", "b", "b"])
+ result = df.melt(id_vars=["a"], value_vars=["b"])
+ expected = DataFrame(
+ [["id", "b", 2], ["id", "b", 3]], columns=["a", "variable", "value"]
+ )
+ tm.assert_frame_equal(result, expected)
+
class TestLreshape:
def test_pairs(self):
| - [x] closes #41951
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
@simonjayhawkins I think this changed in May last year, so probably not woth backporting? | https://api.github.com/repos/pandas-dev/pandas/pulls/41964 | 2021-06-12T10:49:11Z | 2021-06-15T23:34:25Z | 2021-06-15T23:34:24Z | 2021-06-18T10:43:11Z |
Backport PR #41924: PERF: fix regression in reductions for boolean/integer data | diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 20adcee924a15..d42497c3a8322 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -231,7 +231,8 @@ def _maybe_get_mask(
"""
if mask is None:
if is_bool_dtype(values.dtype) or is_integer_dtype(values.dtype):
- return np.broadcast_to(False, values.shape)
+ # Boolean data cannot contain nulls, so signal via mask being None
+ return None
if skipna or needs_i8_conversion(values.dtype):
mask = isna(values)
@@ -1376,8 +1377,15 @@ def _maybe_null_out(
Dtype
The product of all elements on a given axis. ( NaNs are treated as 1)
"""
- if mask is not None and axis is not None and getattr(result, "ndim", False):
- null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0
+ if axis is not None and isinstance(result, np.ndarray):
+ if mask is not None:
+ null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0
+ else:
+ # we have no nulls, kept mask=None in _maybe_get_mask
+ below_count = shape[axis] - min_count < 0
+ new_shape = shape[:axis] + shape[axis + 1 :]
+ null_mask = np.broadcast_to(below_count, new_shape)
+
if np.any(null_mask):
if is_numeric_dtype(result):
if np.iscomplexobj(result):
| Backport PR #41924 | https://api.github.com/repos/pandas-dev/pandas/pulls/41963 | 2021-06-12T07:29:50Z | 2021-06-12T13:20:48Z | 2021-06-12T13:20:48Z | 2021-06-12T13:20:56Z |
CI: enable auto-cancel for GitHub Actions | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a5a802c678e20..cfdae016836f1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2,7 +2,8 @@ name: CI
on:
push:
- branches: [master]
+ branches:
+ - master
pull_request:
branches:
- master
@@ -20,6 +21,10 @@ jobs:
run:
shell: bash -l {0}
+ concurrency:
+ group: ${{ github.ref }}-checks
+ cancel-in-progress: true
+
steps:
- name: Checkout
uses: actions/checkout@v2
@@ -93,8 +98,12 @@ jobs:
web_and_docs:
name: Web and docs
runs-on: ubuntu-latest
- steps:
+ concurrency:
+ group: ${{ github.ref }}-web-docs
+ cancel-in-progress: true
+
+ steps:
- name: Checkout
uses: actions/checkout@v2
with:
@@ -148,8 +157,11 @@ jobs:
strategy:
matrix:
pattern: ["not slow and not network and not clipboard", "slow"]
- steps:
+ concurrency:
+ group: ${{ github.ref }}-data_manager-${{ matrix.pattern }}
+ cancel-in-progress: true
+ steps:
- name: Checkout
uses: actions/checkout@v2
with:
diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml
index 292598dfcab73..1d163719cd42b 100644
--- a/.github/workflows/database.yml
+++ b/.github/workflows/database.yml
@@ -2,7 +2,8 @@ name: Database
on:
push:
- branches: [master]
+ branches:
+ - master
pull_request:
branches:
- master
@@ -28,6 +29,10 @@ jobs:
ENV_FILE: [ci/deps/actions-37-db-min.yaml, ci/deps/actions-37-db.yaml]
fail-fast: false
+ concurrency:
+ group: ${{ github.ref }}-${{ matrix.ENV_FILE }}
+ cancel-in-progress: true
+
services:
mysql:
image: mysql
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index cb7d3fb5cabcf..67ea0e79d04e3 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -2,7 +2,8 @@ name: Posix
on:
push:
- branches: [master]
+ branches:
+ - master
pull_request:
branches:
- master
@@ -43,6 +44,9 @@ jobs:
LC_ALL: ${{ matrix.settings[4] }}
PANDAS_TESTING_MODE: ${{ matrix.settings[5] }}
TEST_ARGS: ${{ matrix.settings[6] }}
+ concurrency:
+ group: ${{ github.ref }}-${{ matrix.settings[0] }}
+ cancel-in-progress: true
steps:
- name: Checkout
diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml
index 723347913ac38..dcb33b21a8ae1 100644
--- a/.github/workflows/pre-commit.yml
+++ b/.github/workflows/pre-commit.yml
@@ -3,11 +3,15 @@ name: pre-commit
on:
pull_request:
push:
- branches: [master]
+ branches:
+ - master
jobs:
pre-commit:
runs-on: ubuntu-latest
+ concurrency:
+ group: ${{ github.ref }}-pre-commit
+ cancel-in-progress: true
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index 38b1aa9ae7047..8ccf89c73704c 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -16,6 +16,10 @@ jobs:
name: actions-310-dev
timeout-minutes: 60
+ concurrency:
+ group: ${{ github.ref }}-dev
+ cancel-in-progress: true
+
steps:
- uses: actions/checkout@v2
with:
| https://api.github.com/repos/pandas-dev/pandas/pulls/41962 | 2021-06-12T02:20:32Z | 2021-06-15T23:36:11Z | 2021-06-15T23:36:11Z | 2021-06-18T02:23:36Z | |
REF: avoid accessing index._engine in set_with_engine | diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index fbfee9a1f524c..d9eaaa763fde8 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -34,7 +34,6 @@
Dtype,
DtypeObj,
)
-from pandas.errors import InvalidIndexError
from pandas.util._decorators import (
cache_readonly,
doc,
@@ -658,8 +657,7 @@ def get_loc(self, key, method=None, tolerance=None):
-------
loc : int
"""
- if not is_scalar(key):
- raise InvalidIndexError(key)
+ self._check_indexing_error(key)
orig_key = key
if is_valid_na_for_dtype(key, self.dtype):
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 072ab7dff8e5b..232ca9068abc6 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -613,9 +613,7 @@ def get_loc(
0
"""
self._check_indexing_method(method)
-
- if not is_scalar(key):
- raise InvalidIndexError(key)
+ self._check_indexing_error(key)
if isinstance(key, Interval):
if self.closed != key.closed:
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index c1104b80a0a7a..1e705282bd816 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -27,14 +27,12 @@
Dtype,
DtypeObj,
)
-from pandas.errors import InvalidIndexError
from pandas.util._decorators import doc
from pandas.core.dtypes.common import (
is_datetime64_any_dtype,
is_float,
is_integer,
- is_scalar,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import PeriodDtype
@@ -411,9 +409,7 @@ def get_loc(self, key, method=None, tolerance=None):
"""
orig_key = key
- if not is_scalar(key):
- raise InvalidIndexError(key)
-
+ self._check_indexing_error(key)
if isinstance(key, str):
try:
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index 746246172b967..8bef105c783c8 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -385,6 +385,7 @@ def get_loc(self, key, method=None, tolerance=None):
return self._range.index(new_key)
except ValueError as err:
raise KeyError(key) from err
+ self._check_indexing_error(key)
raise KeyError(key)
return super().get_loc(key, method=method, tolerance=tolerance)
diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index c60ab06dd08f3..bc21b567dba26 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -13,7 +13,6 @@
DtypeObj,
Optional,
)
-from pandas.errors import InvalidIndexError
from pandas.core.dtypes.common import (
TD64NS_DTYPE,
@@ -170,8 +169,7 @@ def get_loc(self, key, method=None, tolerance=None):
-------
loc : int, slice, or ndarray[int]
"""
- if not is_scalar(key):
- raise InvalidIndexError(key)
+ self._check_indexing_error(key)
try:
key = self._data._validate_scalar(key, unbox=False)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 59ea6710ea6cd..3d974cbec4286 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1072,7 +1072,7 @@ def __setitem__(self, key, value) -> None:
# GH#12862 adding a new key to the Series
self.loc[key] = value
- except TypeError as err:
+ except (InvalidIndexError, TypeError) as err:
if isinstance(key, tuple) and not isinstance(self.index, MultiIndex):
raise KeyError(
"key of type tuple not found and not a MultiIndex"
@@ -1094,8 +1094,7 @@ def __setitem__(self, key, value) -> None:
self._maybe_update_cacher()
def _set_with_engine(self, key, value) -> None:
- # fails with AttributeError for IntervalIndex
- loc = self.index._engine.get_loc(key)
+ loc = self.index.get_loc(key)
# error: Argument 1 to "validate_numeric_casting" has incompatible type
# "Union[dtype, ExtensionDtype]"; expected "dtype"
validate_numeric_casting(self.dtype, value) # type: ignore[arg-type]
@@ -1112,6 +1111,9 @@ def _set_with(self, key, value):
if is_scalar(key):
key = [key]
+ elif is_iterator(key):
+ # Without this, the call to infer_dtype will consume the generator
+ key = list(key)
if isinstance(key, Index):
key_type = key.inferred_type
diff --git a/pandas/tests/indexes/test_indexing.py b/pandas/tests/indexes/test_indexing.py
index 379c766b94d6c..5f6d0155ae6cf 100644
--- a/pandas/tests/indexes/test_indexing.py
+++ b/pandas/tests/indexes/test_indexing.py
@@ -26,6 +26,7 @@
IntervalIndex,
MultiIndex,
PeriodIndex,
+ RangeIndex,
Series,
TimedeltaIndex,
UInt64Index,
@@ -181,6 +182,27 @@ def test_get_value(self, index):
tm.assert_almost_equal(result, values[67])
+class TestGetLoc:
+ def test_get_loc_non_hashable(self, index):
+ # MultiIndex and Index raise TypeError, others InvalidIndexError
+
+ with pytest.raises((TypeError, InvalidIndexError), match="slice"):
+ index.get_loc(slice(0, 1))
+
+ def test_get_loc_generator(self, index):
+
+ exc = KeyError
+ if isinstance(
+ index,
+ (DatetimeIndex, TimedeltaIndex, PeriodIndex, RangeIndex, IntervalIndex),
+ ):
+ # TODO: make these more consistent?
+ exc = InvalidIndexError
+ with pytest.raises(exc, match="generator object"):
+ # MultiIndex specifically checks for generator; others for scalar
+ index.get_loc(x for x in range(5))
+
+
class TestGetIndexer:
def test_get_indexer_base(self, index):
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index c945bd6b95ee1..fd4690a05da05 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -113,15 +113,6 @@ def test_setitem_ndarray_3d(self, index, frame_or_series, indexer_sli):
if indexer_sli is tm.iloc:
err = ValueError
msg = f"Cannot set values with ndim > {obj.ndim}"
- elif (
- isinstance(index, pd.IntervalIndex)
- and indexer_sli is tm.setitem
- and obj.ndim == 1
- ):
- err = AttributeError
- msg = (
- "'pandas._libs.interval.IntervalTree' object has no attribute 'get_loc'"
- )
else:
err = ValueError
msg = "|".join(
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
orthogonal but related to #41956 | https://api.github.com/repos/pandas-dev/pandas/pulls/41959 | 2021-06-11T23:29:00Z | 2021-06-16T00:05:21Z | 2021-06-16T00:05:21Z | 2021-06-16T00:24:39Z |
REGR: Series[dt64/td64].astype(string) | diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 37e83ddb0ffed..51a947f79ede2 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -716,6 +716,14 @@ cpdef ndarray[object] ensure_string_array(
Py_ssize_t i = 0, n = len(arr)
if hasattr(arr, "to_numpy"):
+
+ if hasattr(arr, "dtype") and arr.dtype.kind in ["m", "M"]:
+ # dtype check to exclude DataFrame
+ # GH#41409 TODO: not a great place for this
+ out = arr.astype(str).astype(object)
+ out[arr.isna()] = na_value
+ return out
+
arr = arr.to_numpy()
elif not isinstance(arr, np.ndarray):
arr = np.array(arr, dtype="object")
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index 881f8db305240..bd71f0a0716b4 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -632,13 +632,9 @@ def test_astype_tz_object_conversion(self, tz):
result = result.astype({"tz": "datetime64[ns, Europe/London]"})
tm.assert_frame_equal(result, expected)
- def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture, request):
+ def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture):
+ # GH#41409
tz = tz_naive_fixture
- if tz is None:
- mark = pytest.mark.xfail(
- reason="GH#36153 uses ndarray formatting instead of DTA formatting"
- )
- request.node.add_marker(mark)
dti = date_range("2016-01-01", periods=3, tz=tz)
dta = dti._data
@@ -660,6 +656,15 @@ def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture, request)
alt = obj.astype(str)
assert np.all(alt.iloc[1:] == result.iloc[1:])
+ def test_astype_td64_to_string(self, frame_or_series):
+ # GH#41409
+ tdi = pd.timedelta_range("1 Day", periods=3)
+ obj = frame_or_series(tdi)
+
+ expected = frame_or_series(["1 days", "2 days", "3 days"], dtype="string")
+ result = obj.astype("string")
+ tm.assert_equal(result, expected)
+
def test_astype_bytes(self):
# GH#39474
result = DataFrame(["foo", "bar", "baz"]).astype(bytes)
| - [x] closes #41409
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
This surfaces another bug in `StringArray.__getitem__` that I haven't looked into yet. | https://api.github.com/repos/pandas-dev/pandas/pulls/41958 | 2021-06-11T23:15:36Z | 2021-06-15T21:04:41Z | 2021-06-15T21:04:40Z | 2021-06-15T21:43:58Z |
REF: avoid accessing ._engine in Series/DataFrame | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 2edad9f6626bb..00f6213110e76 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -158,7 +158,6 @@
from pandas.core.indexers import check_key_length
from pandas.core.indexes import base as ibase
from pandas.core.indexes.api import (
- CategoricalIndex,
DatetimeIndex,
Index,
PeriodIndex,
@@ -3557,8 +3556,8 @@ def _get_value(self, index, col, takeable: bool = False) -> Scalar:
Notes
-----
- Assumes that index and columns both have ax._index_as_unique;
- caller is responsible for checking.
+ Assumes that both `self.index._index_as_unique` and
+ `self.columns._index_as_unique`; Caller is responsible for checking.
"""
if takeable:
series = self._ixs(col, axis=1)
@@ -3567,21 +3566,17 @@ def _get_value(self, index, col, takeable: bool = False) -> Scalar:
series = self._get_item_cache(col)
engine = self.index._engine
- if isinstance(self.index, CategoricalIndex):
- # Trying to use the engine fastpath may give incorrect results
- # if our categories are integers that dont match our codes
- col = self.columns.get_loc(col)
- index = self.index.get_loc(index)
- return self._get_value(index, col, takeable=True)
+ if not isinstance(self.index, MultiIndex):
+ # CategoricalIndex: Trying to use the engine fastpath may give incorrect
+ # results if our categories are integers that dont match our codes
+ # IntervalIndex: IntervalTree has no get_loc
+ row = self.index.get_loc(index)
+ return series._values[row]
- try:
- loc = engine.get_loc(index)
- return series._values[loc]
- except AttributeError:
- # IntervalTree has no get_loc
- col = self.columns.get_loc(col)
- index = self.index.get_loc(index)
- return self._get_value(index, col, takeable=True)
+ # For MultiIndex going through engine effectively restricts us to
+ # same-length tuples; see test_get_set_value_no_partial_indexing
+ loc = engine.get_loc(index)
+ return series._values[loc]
def __setitem__(self, key, value):
key = com.apply_if_callable(key, self)
@@ -3816,8 +3811,7 @@ def _set_value(
return
series = self._get_item_cache(col)
- engine = self.index._engine
- loc = engine.get_loc(index)
+ loc = self.index.get_loc(index)
validate_numeric_casting(series.dtype, value)
series._values[loc] = value
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index d62dcdba92bc7..0fd2eedae2da9 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -916,8 +916,7 @@ def __getitem__(self, key):
key = tuple(list(x) if is_iterator(x) else x for x in key)
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
if self._is_scalar_access(key):
- with suppress(KeyError, IndexError):
- return self.obj._get_value(*key, takeable=self._takeable)
+ return self.obj._get_value(*key, takeable=self._takeable)
return self._getitem_tuple(key)
else:
# we by definition only have the 0th axis
@@ -2187,7 +2186,7 @@ class _ScalarAccessIndexer(NDFrameIndexerBase):
Access scalars quickly.
"""
- def _convert_key(self, key, is_setter: bool = False):
+ def _convert_key(self, key):
raise AbstractMethodError(self)
def __getitem__(self, key):
@@ -2211,7 +2210,7 @@ def __setitem__(self, key, value):
if not isinstance(key, tuple):
key = _tuplify(self.ndim, key)
- key = list(self._convert_key(key, is_setter=True))
+ key = list(self._convert_key(key))
if len(key) != self.ndim:
raise ValueError("Not enough indexers for scalar access (setting)!")
@@ -2222,7 +2221,7 @@ def __setitem__(self, key, value):
class _AtIndexer(_ScalarAccessIndexer):
_takeable = False
- def _convert_key(self, key, is_setter: bool = False):
+ def _convert_key(self, key):
"""
Require they keys to be the same type as the index. (so we don't
fallback)
@@ -2233,10 +2232,6 @@ def _convert_key(self, key, is_setter: bool = False):
if self.ndim == 1 and len(key) > 1:
key = (key,)
- # allow arbitrary setting
- if is_setter:
- return list(key)
-
return key
@property
@@ -2271,7 +2266,7 @@ def __setitem__(self, key, value):
class _iAtIndexer(_ScalarAccessIndexer):
_takeable = True
- def _convert_key(self, key, is_setter: bool = False):
+ def _convert_key(self, key):
"""
Require integer args. (and convert to label arguments)
"""
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index fc07c14f1e179..b04a2c86a79d7 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -596,7 +596,7 @@ def test_iloc_getitem_labelled_frame(self):
assert result == exp
# out-of-bounds exception
- msg = "single positional indexer is out-of-bounds"
+ msg = "index 5 is out of bounds for axis 0 with size 4"
with pytest.raises(IndexError, match=msg):
df.iloc[10, 5]
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index fd4690a05da05..7243f2cddfec6 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -518,7 +518,7 @@ def test_string_slice_empty(self):
with pytest.raises(KeyError, match="'2011'"):
df["2011"]
- with pytest.raises(KeyError, match="'2011'"):
+ with pytest.raises(KeyError, match="^0$"):
df.loc["2011", 0]
def test_astype_assignment(self):
| sits on top of #41846 | https://api.github.com/repos/pandas-dev/pandas/pulls/41956 | 2021-06-11T19:54:49Z | 2021-06-17T17:39:52Z | 2021-06-17T17:39:52Z | 2021-06-17T18:51:40Z |
CLN: Replace FrameOrSeriesUnion annotation by DataFrame | Series | diff --git a/pandas/_typing.py b/pandas/_typing.py
index 12d23786c3387..906b77319406f 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -101,12 +101,6 @@
]
Timezone = Union[str, tzinfo]
-# FrameOrSeriesUnion means either a DataFrame or a Series. E.g.
-# `def func(a: FrameOrSeriesUnion) -> FrameOrSeriesUnion: ...` means that if a Series
-# is passed in, either a Series or DataFrame is returned, and if a DataFrame is passed
-# in, either a DataFrame or a Series is returned.
-FrameOrSeriesUnion = Union["DataFrame", "Series"]
-
# FrameOrSeries is stricter and ensures that the same subclass of NDFrame always is
# used. E.g. `def func(a: FrameOrSeries) -> FrameOrSeries: ...` means that if a
# Series is passed into a function, a Series is always returned and if a DataFrame is
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index f26cf113f7d5e..f727b7b15c8b1 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -29,7 +29,6 @@
AnyArrayLike,
ArrayLike,
DtypeObj,
- FrameOrSeriesUnion,
Scalar,
)
from pandas.util._decorators import doc
@@ -1211,7 +1210,7 @@ def __init__(self, obj, n: int, keep: str):
if self.keep not in ("first", "last", "all"):
raise ValueError('keep must be either "first", "last" or "all"')
- def compute(self, method: str) -> FrameOrSeriesUnion:
+ def compute(self, method: str) -> DataFrame | Series:
raise NotImplementedError
def nlargest(self):
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 388c1881afed7..f2e60f43d2a54 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -25,7 +25,6 @@
AggObjType,
Axis,
FrameOrSeries,
- FrameOrSeriesUnion,
)
from pandas.util._decorators import cache_readonly
@@ -137,10 +136,10 @@ def f(x):
self.f: AggFuncType = f
@abc.abstractmethod
- def apply(self) -> FrameOrSeriesUnion:
+ def apply(self) -> DataFrame | Series:
pass
- def agg(self) -> FrameOrSeriesUnion | None:
+ def agg(self) -> DataFrame | Series | None:
"""
Provide an implementation for the aggregators.
@@ -171,7 +170,7 @@ def agg(self) -> FrameOrSeriesUnion | None:
# caller can react
return None
- def transform(self) -> FrameOrSeriesUnion:
+ def transform(self) -> DataFrame | Series:
"""
Transform a DataFrame or Series.
@@ -252,7 +251,7 @@ def transform_dict_like(self, func):
func = self.normalize_dictlike_arg("transform", obj, func)
- results: dict[Hashable, FrameOrSeriesUnion] = {}
+ results: dict[Hashable, DataFrame | Series] = {}
failed_names = []
all_type_errors = True
for name, how in func.items():
@@ -283,7 +282,7 @@ def transform_dict_like(self, func):
)
return concat(results, axis=1)
- def transform_str_or_callable(self, func) -> FrameOrSeriesUnion:
+ def transform_str_or_callable(self, func) -> DataFrame | Series:
"""
Compute transform in the case of a string or callable func
"""
@@ -305,7 +304,7 @@ def transform_str_or_callable(self, func) -> FrameOrSeriesUnion:
except Exception:
return func(obj, *args, **kwargs)
- def agg_list_like(self) -> FrameOrSeriesUnion:
+ def agg_list_like(self) -> DataFrame | Series:
"""
Compute aggregation in the case of a list-like argument.
@@ -399,7 +398,7 @@ def agg_list_like(self) -> FrameOrSeriesUnion:
)
return concatenated.reindex(full_ordered_index, copy=False)
- def agg_dict_like(self) -> FrameOrSeriesUnion:
+ def agg_dict_like(self) -> DataFrame | Series:
"""
Compute aggregation in the case of a dict-like argument.
@@ -467,7 +466,7 @@ def agg_dict_like(self) -> FrameOrSeriesUnion:
return result
- def apply_str(self) -> FrameOrSeriesUnion:
+ def apply_str(self) -> DataFrame | Series:
"""
Compute apply in case of a string.
@@ -492,7 +491,7 @@ def apply_str(self) -> FrameOrSeriesUnion:
raise ValueError(f"Operation {f} does not support axis=1")
return self._try_aggregate_string_function(obj, f, *self.args, **self.kwargs)
- def apply_multiple(self) -> FrameOrSeriesUnion:
+ def apply_multiple(self) -> DataFrame | Series:
"""
Compute apply in case of a list-like or dict-like.
@@ -504,7 +503,7 @@ def apply_multiple(self) -> FrameOrSeriesUnion:
return self.obj.aggregate(self.f, self.axis, *self.args, **self.kwargs)
def normalize_dictlike_arg(
- self, how: str, obj: FrameOrSeriesUnion, func: AggFuncTypeDict
+ self, how: str, obj: DataFrame | Series, func: AggFuncTypeDict
) -> AggFuncTypeDict:
"""
Handler for dict-like argument.
@@ -617,7 +616,7 @@ def series_generator(self) -> Iterator[Series]:
@abc.abstractmethod
def wrap_results_for_axis(
self, results: ResType, res_index: Index
- ) -> FrameOrSeriesUnion:
+ ) -> DataFrame | Series:
pass
# ---------------------------------------------------------------
@@ -638,7 +637,7 @@ def values(self):
def dtypes(self) -> Series:
return self.obj.dtypes
- def apply(self) -> FrameOrSeriesUnion:
+ def apply(self) -> DataFrame | Series:
"""compute the results"""
# dispatch to agg
if is_list_like(self.f):
@@ -812,7 +811,7 @@ def apply_series_generator(self) -> tuple[ResType, Index]:
return results, res_index
- def wrap_results(self, results: ResType, res_index: Index) -> FrameOrSeriesUnion:
+ def wrap_results(self, results: ResType, res_index: Index) -> DataFrame | Series:
from pandas import Series
# see if we can infer the results
@@ -835,7 +834,7 @@ def wrap_results(self, results: ResType, res_index: Index) -> FrameOrSeriesUnion
return result
- def apply_str(self) -> FrameOrSeriesUnion:
+ def apply_str(self) -> DataFrame | Series:
# Caller is responsible for checking isinstance(self.f, str)
# TODO: GH#39993 - Avoid special-casing by replacing with lambda
if self.f == "size":
@@ -866,7 +865,7 @@ def result_columns(self) -> Index:
def wrap_results_for_axis(
self, results: ResType, res_index: Index
- ) -> FrameOrSeriesUnion:
+ ) -> DataFrame | Series:
"""return the results for the rows"""
if self.result_type == "reduce":
@@ -949,9 +948,9 @@ def result_columns(self) -> Index:
def wrap_results_for_axis(
self, results: ResType, res_index: Index
- ) -> FrameOrSeriesUnion:
+ ) -> DataFrame | Series:
"""return the results for the columns"""
- result: FrameOrSeriesUnion
+ result: DataFrame | Series
# we have requested to expand
if self.result_type == "expand":
@@ -1005,7 +1004,7 @@ def __init__(
kwargs=kwargs,
)
- def apply(self) -> FrameOrSeriesUnion:
+ def apply(self) -> DataFrame | Series:
obj = self.obj
if len(obj) == 0:
@@ -1056,7 +1055,7 @@ def apply_empty_result(self) -> Series:
obj, method="apply"
)
- def apply_standard(self) -> FrameOrSeriesUnion:
+ def apply_standard(self) -> DataFrame | Series:
f = self.f
obj = self.obj
diff --git a/pandas/core/describe.py b/pandas/core/describe.py
index dfb18b2c40698..0fd7838ab5acc 100644
--- a/pandas/core/describe.py
+++ b/pandas/core/describe.py
@@ -22,7 +22,6 @@
from pandas._libs.tslibs import Timestamp
from pandas._typing import (
FrameOrSeries,
- FrameOrSeriesUnion,
Hashable,
)
from pandas.util._validators import validate_percentile
@@ -107,12 +106,12 @@ class NDFrameDescriberAbstract(ABC):
Whether to treat datetime dtypes as numeric.
"""
- def __init__(self, obj: FrameOrSeriesUnion, datetime_is_numeric: bool):
+ def __init__(self, obj: DataFrame | Series, datetime_is_numeric: bool):
self.obj = obj
self.datetime_is_numeric = datetime_is_numeric
@abstractmethod
- def describe(self, percentiles: Sequence[float]) -> FrameOrSeriesUnion:
+ def describe(self, percentiles: Sequence[float]) -> DataFrame | Series:
"""Do describe either series or dataframe.
Parameters
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 91b9bdd564676..57b2e701fce35 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -58,7 +58,6 @@
FillnaOptions,
FloatFormatType,
FormattersType,
- FrameOrSeriesUnion,
Frequency,
IndexKeyFunc,
IndexLabel,
@@ -1362,7 +1361,7 @@ def dot(self, other: Series) -> Series:
def dot(self, other: DataFrame | Index | ArrayLike) -> DataFrame:
...
- def dot(self, other: AnyArrayLike | FrameOrSeriesUnion) -> FrameOrSeriesUnion:
+ def dot(self, other: AnyArrayLike | DataFrame | Series) -> DataFrame | Series:
"""
Compute the matrix multiplication between the DataFrame and other.
@@ -1478,13 +1477,13 @@ def __matmul__(self, other: Series) -> Series:
@overload
def __matmul__(
- self, other: AnyArrayLike | FrameOrSeriesUnion
- ) -> FrameOrSeriesUnion:
+ self, other: AnyArrayLike | DataFrame | Series
+ ) -> DataFrame | Series:
...
def __matmul__(
- self, other: AnyArrayLike | FrameOrSeriesUnion
- ) -> FrameOrSeriesUnion:
+ self, other: AnyArrayLike | DataFrame | Series
+ ) -> DataFrame | Series:
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
@@ -8401,8 +8400,8 @@ def _gotitem(
self,
key: IndexLabel,
ndim: int,
- subset: FrameOrSeriesUnion | None = None,
- ) -> FrameOrSeriesUnion:
+ subset: DataFrame | Series | None = None,
+ ) -> DataFrame | Series:
"""
Sub-classes to define. Return a sliced object.
@@ -8931,7 +8930,7 @@ def append(
def join(
self,
- other: FrameOrSeriesUnion,
+ other: DataFrame | Series,
on: IndexLabel | None = None,
how: str = "left",
lsuffix: str = "",
@@ -9061,7 +9060,7 @@ def join(
def _join_compat(
self,
- other: FrameOrSeriesUnion,
+ other: DataFrame | Series,
on: IndexLabel | None = None,
how: str = "left",
lsuffix: str = "",
@@ -9131,7 +9130,7 @@ def _join_compat(
@Appender(_merge_doc, indents=2)
def merge(
self,
- right: FrameOrSeriesUnion,
+ right: DataFrame | Series,
how: str = "inner",
on: IndexLabel | None = None,
left_on: IndexLabel | None = None,
@@ -10724,7 +10723,7 @@ def _from_nested_dict(data) -> collections.defaultdict:
return new_data
-def _reindex_for_setitem(value: FrameOrSeriesUnion, index: Index) -> ArrayLike:
+def _reindex_for_setitem(value: DataFrame | Series, index: Index) -> ArrayLike:
# reindex if necessary
if value.index.equals(index) or not len(index):
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 69f992f840c7c..d50e921347f98 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -33,7 +33,6 @@
from pandas._typing import (
ArrayLike,
FrameOrSeries,
- FrameOrSeriesUnion,
Manager2D,
)
from pandas.util._decorators import (
@@ -296,7 +295,7 @@ def _aggregate_multiple_funcs(self, arg) -> DataFrame:
arg = zip(columns, arg)
- results: dict[base.OutputKey, FrameOrSeriesUnion] = {}
+ results: dict[base.OutputKey, DataFrame | Series] = {}
for idx, (name, func) in enumerate(arg):
key = base.OutputKey(label=name, position=idx)
@@ -422,7 +421,7 @@ def _wrap_applied_output(
keys: Index,
values: list[Any] | None,
not_indexed_same: bool = False,
- ) -> FrameOrSeriesUnion:
+ ) -> DataFrame | Series:
"""
Wrap the output of SeriesGroupBy.apply into the expected result.
@@ -1191,7 +1190,7 @@ def _wrap_applied_output_series(
not_indexed_same: bool,
first_not_none,
key_index,
- ) -> FrameOrSeriesUnion:
+ ) -> DataFrame | Series:
# this is to silence a DeprecationWarning
# TODO: Remove when default dtype of empty Series is object
kwargs = first_not_none._construct_axes_dict()
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index f694dcce809ea..90a641a246eb2 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -45,7 +45,6 @@ class providing the base-class of operations.
ArrayLike,
F,
FrameOrSeries,
- FrameOrSeriesUnion,
IndexLabel,
Scalar,
T,
@@ -728,7 +727,7 @@ def pipe(
plot = property(GroupByPlot)
@final
- def get_group(self, name, obj=None) -> FrameOrSeriesUnion:
+ def get_group(self, name, obj=None) -> DataFrame | Series:
"""
Construct DataFrame from group with provided name.
@@ -1267,8 +1266,8 @@ def f(g):
@final
def _python_apply_general(
- self, f: F, data: FrameOrSeriesUnion
- ) -> FrameOrSeriesUnion:
+ self, f: F, data: DataFrame | Series
+ ) -> DataFrame | Series:
"""
Apply function f in python space
@@ -1786,7 +1785,7 @@ def sem(self, ddof: int = 1):
@final
@Substitution(name="groupby")
@Appender(_common_see_also)
- def size(self) -> FrameOrSeriesUnion:
+ def size(self) -> DataFrame | Series:
"""
Compute group sizes.
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index ea34bc75b4e31..4952fd5582fdb 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -15,7 +15,6 @@
import numpy as np
-from pandas._typing import FrameOrSeriesUnion
from pandas.util._decorators import (
cache_readonly,
deprecate_nonkeyword_arguments,
@@ -83,7 +82,7 @@ def concat(
verify_integrity: bool = False,
sort: bool = False,
copy: bool = True,
-) -> FrameOrSeriesUnion:
+) -> DataFrame | Series:
...
@@ -99,7 +98,7 @@ def concat(
verify_integrity: bool = False,
sort: bool = False,
copy: bool = True,
-) -> FrameOrSeriesUnion:
+) -> DataFrame | Series:
"""
Concatenate pandas objects along a particular axis with optional set logic
along the other axes.
@@ -454,7 +453,7 @@ def __init__(
if self._is_frame and axis == 1:
name = 0
# mypy needs to know sample is not an NDFrame
- sample = cast("FrameOrSeriesUnion", sample)
+ sample = cast("DataFrame | Series", sample)
obj = sample._constructor({name: obj})
self.objs.append(obj)
@@ -474,8 +473,8 @@ def __init__(
self.new_axes = self._get_new_axes()
def get_result(self):
- cons: type[FrameOrSeriesUnion]
- sample: FrameOrSeriesUnion
+ cons: type[DataFrame | Series]
+ sample: DataFrame | Series
# series only
if self._is_series:
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index 51556fda6da04..d96f2628088a5 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -14,7 +14,6 @@
AggFuncType,
AggFuncTypeBase,
AggFuncTypeDict,
- FrameOrSeriesUnion,
IndexLabel,
)
from pandas.util._decorators import (
@@ -254,7 +253,7 @@ def __internal_pivot_table(
def _add_margins(
- table: FrameOrSeriesUnion,
+ table: DataFrame | Series,
data,
values,
rows,
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 59ea6710ea6cd..5173e98ab8136 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -39,7 +39,6 @@
Dtype,
DtypeObj,
FillnaOptions,
- FrameOrSeriesUnion,
IndexKeyFunc,
NpDtype,
SingleManager,
@@ -3022,7 +3021,7 @@ def compare(
align_axis: Axis = 1,
keep_shape: bool = False,
keep_equal: bool = False,
- ) -> FrameOrSeriesUnion:
+ ) -> DataFrame | Series:
return super().compare(
other=other,
align_axis=align_axis,
@@ -4178,7 +4177,7 @@ def aggregate(self, func=None, axis=0, *args, **kwargs):
)
def transform(
self, func: AggFuncType, axis: Axis = 0, *args, **kwargs
- ) -> FrameOrSeriesUnion:
+ ) -> DataFrame | Series:
# Validate axis argument
self._get_axis_number(axis)
result = SeriesApply(
@@ -4192,7 +4191,7 @@ def apply(
convert_dtype: bool = True,
args: tuple[Any, ...] = (),
**kwargs,
- ) -> FrameOrSeriesUnion:
+ ) -> DataFrame | Series:
"""
Invoke function on values of Series.
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 323cb6bd9fedd..73317cc39c2af 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -13,10 +13,7 @@
import numpy as np
import pandas._libs.lib as lib
-from pandas._typing import (
- DtypeObj,
- FrameOrSeriesUnion,
-)
+from pandas._typing import DtypeObj
from pandas.util._decorators import Appender
from pandas.core.dtypes.common import (
@@ -39,7 +36,11 @@
from pandas.core.base import NoNewAttributesMixin
if TYPE_CHECKING:
- from pandas import Index
+ from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ )
_shared_docs: dict[str, str] = {}
_cpython_optimized_encoders = (
@@ -2314,7 +2315,7 @@ def findall(self, pat, flags=0):
@forbid_nonstring_types(["bytes"])
def extract(
self, pat: str, flags: int = 0, expand: bool = True
- ) -> FrameOrSeriesUnion | Index:
+ ) -> DataFrame | Series | Index:
r"""
Extract capture groups in the regex `pat` as columns in a DataFrame.
diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py
index fb5002648b6a5..03a66225a846f 100644
--- a/pandas/core/util/hashing.py
+++ b/pandas/core/util/hashing.py
@@ -15,10 +15,7 @@
import numpy as np
from pandas._libs.hashing import hash_object_array
-from pandas._typing import (
- ArrayLike,
- FrameOrSeriesUnion,
-)
+from pandas._typing import ArrayLike
from pandas.core.dtypes.common import (
is_categorical_dtype,
@@ -34,6 +31,7 @@
if TYPE_CHECKING:
from pandas import (
Categorical,
+ DataFrame,
Index,
MultiIndex,
Series,
@@ -77,7 +75,7 @@ def combine_hash_arrays(arrays: Iterator[np.ndarray], num_items: int) -> np.ndar
def hash_pandas_object(
- obj: Index | FrameOrSeriesUnion,
+ obj: Index | DataFrame | Series,
index: bool = True,
encoding: str = "utf8",
hash_key: str | None = _default_hash_key,
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py
index c1d532d94eb83..664089fa37b83 100644
--- a/pandas/core/window/ewm.py
+++ b/pandas/core/window/ewm.py
@@ -3,6 +3,7 @@
import datetime
from functools import partial
from textwrap import dedent
+from typing import TYPE_CHECKING
import warnings
import numpy as np
@@ -12,9 +13,12 @@
from pandas._typing import (
Axis,
FrameOrSeries,
- FrameOrSeriesUnion,
TimedeltaConvertibleTypes,
)
+
+if TYPE_CHECKING:
+ from pandas import DataFrame, Series
+
from pandas.compat.numpy import function as nv
from pandas.util._decorators import doc
@@ -558,7 +562,7 @@ def var_func(values, begin, end, min_periods):
)
def cov(
self,
- other: FrameOrSeriesUnion | None = None,
+ other: DataFrame | Series | None = None,
pairwise: bool | None = None,
bias: bool = False,
**kwargs,
@@ -625,7 +629,7 @@ def cov_func(x, y):
)
def corr(
self,
- other: FrameOrSeriesUnion | None = None,
+ other: DataFrame | Series | None = None,
pairwise: bool | None = None,
**kwargs,
):
@@ -761,7 +765,7 @@ def std(self, bias: bool = False, *args, **kwargs):
def corr(
self,
- other: FrameOrSeriesUnion | None = None,
+ other: DataFrame | Series | None = None,
pairwise: bool | None = None,
**kwargs,
):
@@ -769,7 +773,7 @@ def corr(
def cov(
self,
- other: FrameOrSeriesUnion | None = None,
+ other: DataFrame | Series | None = None,
pairwise: bool | None = None,
bias: bool = False,
**kwargs,
diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py
index 02cf31cad7b8d..eedb6930bad66 100644
--- a/pandas/core/window/expanding.py
+++ b/pandas/core/window/expanding.py
@@ -2,6 +2,7 @@
from textwrap import dedent
from typing import (
+ TYPE_CHECKING,
Any,
Callable,
)
@@ -9,8 +10,11 @@
from pandas._typing import (
Axis,
FrameOrSeries,
- FrameOrSeriesUnion,
)
+
+if TYPE_CHECKING:
+ from pandas import DataFrame, Series
+
from pandas.compat.numpy import function as nv
from pandas.util._decorators import doc
@@ -591,7 +595,7 @@ def quantile(
)
def cov(
self,
- other: FrameOrSeriesUnion | None = None,
+ other: DataFrame | Series | None = None,
pairwise: bool | None = None,
ddof: int = 1,
**kwargs,
@@ -656,7 +660,7 @@ def cov(
)
def corr(
self,
- other: FrameOrSeriesUnion | None = None,
+ other: DataFrame | Series | None = None,
pairwise: bool | None = None,
ddof: int = 1,
**kwargs,
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 2d5f148a6437a..31951b3f29a82 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -28,7 +28,6 @@
ArrayLike,
Axis,
FrameOrSeries,
- FrameOrSeriesUnion,
)
from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
@@ -408,7 +407,7 @@ def _apply_series(
def _apply_blockwise(
self, homogeneous_func: Callable[..., ArrayLike], name: str | None = None
- ) -> FrameOrSeriesUnion:
+ ) -> DataFrame | Series:
"""
Apply the given function to the DataFrame broken down into homogeneous
sub-frames.
@@ -443,7 +442,7 @@ def hfunc2d(values: ArrayLike) -> ArrayLike:
def _apply_tablewise(
self, homogeneous_func: Callable[..., ArrayLike], name: str | None = None
- ) -> FrameOrSeriesUnion:
+ ) -> DataFrame | Series:
"""
Apply the given function to the DataFrame across the entire object
"""
@@ -460,11 +459,11 @@ def _apply_tablewise(
def _apply_pairwise(
self,
- target: FrameOrSeriesUnion,
- other: FrameOrSeriesUnion | None,
+ target: DataFrame | Series,
+ other: DataFrame | Series | None,
pairwise: bool | None,
- func: Callable[[FrameOrSeriesUnion, FrameOrSeriesUnion], FrameOrSeriesUnion],
- ) -> FrameOrSeriesUnion:
+ func: Callable[[DataFrame | Series, DataFrame | Series], DataFrame | Series],
+ ) -> DataFrame | Series:
"""
Apply the given pairwise function given 2 pandas objects (DataFrame/Series)
"""
@@ -639,11 +638,11 @@ def _apply(
def _apply_pairwise(
self,
- target: FrameOrSeriesUnion,
- other: FrameOrSeriesUnion | None,
+ target: DataFrame | Series,
+ other: DataFrame | Series | None,
pairwise: bool | None,
- func: Callable[[FrameOrSeriesUnion, FrameOrSeriesUnion], FrameOrSeriesUnion],
- ) -> FrameOrSeriesUnion:
+ func: Callable[[DataFrame | Series, DataFrame | Series], DataFrame | Series],
+ ) -> DataFrame | Series:
"""
Apply the given pairwise function given 2 pandas objects (DataFrame/Series)
"""
@@ -1379,7 +1378,7 @@ def quantile(self, quantile: float, interpolation: str = "linear", **kwargs):
def cov(
self,
- other: FrameOrSeriesUnion | None = None,
+ other: DataFrame | Series | None = None,
pairwise: bool | None = None,
ddof: int = 1,
**kwargs,
@@ -1417,7 +1416,7 @@ def cov_func(x, y):
def corr(
self,
- other: FrameOrSeriesUnion | None = None,
+ other: DataFrame | Series | None = None,
pairwise: bool | None = None,
ddof: int = 1,
**kwargs,
@@ -2159,7 +2158,7 @@ def quantile(self, quantile: float, interpolation: str = "linear", **kwargs):
)
def cov(
self,
- other: FrameOrSeriesUnion | None = None,
+ other: DataFrame | Series | None = None,
pairwise: bool | None = None,
ddof: int = 1,
**kwargs,
@@ -2284,7 +2283,7 @@ def cov(
)
def corr(
self,
- other: FrameOrSeriesUnion | None = None,
+ other: DataFrame | Series | None = None,
pairwise: bool | None = None,
ddof: int = 1,
**kwargs,
diff --git a/pandas/io/formats/info.py b/pandas/io/formats/info.py
index e014d7d63a35f..64a59778a54f3 100644
--- a/pandas/io/formats/info.py
+++ b/pandas/io/formats/info.py
@@ -16,10 +16,7 @@
from pandas._config import get_option
-from pandas._typing import (
- Dtype,
- FrameOrSeriesUnion,
-)
+from pandas._typing import Dtype
from pandas.core.indexes.api import Index
@@ -27,7 +24,10 @@
from pandas.io.formats.printing import pprint_thing
if TYPE_CHECKING:
- from pandas.core.frame import DataFrame
+ from pandas.core.frame import (
+ DataFrame,
+ Series,
+ )
def _put_str(s: str | Dtype, space: int) -> str:
@@ -110,7 +110,7 @@ class BaseInfo(ABC):
values.
"""
- data: FrameOrSeriesUnion
+ data: DataFrame | Series
memory_usage: bool | str
@property
@@ -413,7 +413,7 @@ def get_lines(self) -> list[str]:
"""Product in a form of list of lines (strings)."""
@property
- def data(self) -> FrameOrSeriesUnion:
+ def data(self) -> DataFrame | Series:
return self.info.data
@property
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 93c3843b36846..6732a4517ec3e 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -23,7 +23,6 @@
Axis,
FilePathOrBuffer,
FrameOrSeries,
- FrameOrSeriesUnion,
IndexLabel,
Scalar,
)
@@ -171,7 +170,7 @@ class Styler(StylerRenderer):
def __init__(
self,
- data: FrameOrSeriesUnion,
+ data: DataFrame | Series,
precision: int | None = None,
table_styles: CSSStyles | None = None,
uuid: str | None = None,
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index 7686d8a340c37..f20c8dcfbca8b 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -20,10 +20,7 @@
from pandas._config import get_option
from pandas._libs import lib
-from pandas._typing import (
- FrameOrSeriesUnion,
- TypedDict,
-)
+from pandas._typing import TypedDict
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.generic import ABCSeries
@@ -70,7 +67,7 @@ class StylerRenderer:
def __init__(
self,
- data: FrameOrSeriesUnion,
+ data: DataFrame | Series,
uuid: str | None = None,
uuid_len: int = 5,
table_styles: CSSStyles | None = None,
@@ -1159,7 +1156,7 @@ def _pseudo_css(self, uuid: str, name: str, row: int, col: int, text: str):
},
]
- def _translate(self, styler_data: FrameOrSeriesUnion, uuid: str, d: dict):
+ def _translate(self, styler_data: DataFrame | Series, uuid: str, d: dict):
"""
Mutate the render dictionary to allow for tooltips:
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index 77582c46977c1..fdeda868fdb5e 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -21,7 +21,6 @@
from pandas._typing import (
CompressionOptions,
DtypeArg,
- FrameOrSeriesUnion,
IndexLabel,
JSONSerializable,
StorageOptions,
@@ -863,7 +862,7 @@ def __init__(
self.convert_dates = convert_dates
self.date_unit = date_unit
self.keep_default_dates = keep_default_dates
- self.obj: FrameOrSeriesUnion | None = None
+ self.obj: DataFrame | Series | None = None
def check_keys_split(self, decoded):
"""
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 208b8a008ffe6..3d0a1fe867d21 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -40,7 +40,6 @@
ArrayLike,
DtypeArg,
FrameOrSeries,
- FrameOrSeriesUnion,
Shape,
)
from pandas.compat._optional import import_optional_dependency
@@ -2593,7 +2592,7 @@ class Fixed:
pandas_kind: str
format_type: str = "fixed" # GH#30962 needed by dask
- obj_type: type[FrameOrSeriesUnion]
+ obj_type: type[DataFrame | Series]
ndim: int
encoding: str
parent: HDFStore
@@ -3363,7 +3362,7 @@ def is_multi_index(self) -> bool:
return isinstance(self.levels, list)
def validate_multiindex(
- self, obj: FrameOrSeriesUnion
+ self, obj: DataFrame | Series
) -> tuple[DataFrame, list[Hashable]]:
"""
validate that we can store the multi-index; reset and return the
@@ -4500,7 +4499,7 @@ class AppendableFrameTable(AppendableTable):
pandas_kind = "frame_table"
table_type = "appendable_frame"
ndim = 2
- obj_type: type[FrameOrSeriesUnion] = DataFrame
+ obj_type: type[DataFrame | Series] = DataFrame
@property
def is_transposed(self) -> bool:
diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py
index 3b9c5eae70b42..3cd312b06020d 100644
--- a/pandas/plotting/_matplotlib/timeseries.py
+++ b/pandas/plotting/_matplotlib/timeseries.py
@@ -16,7 +16,6 @@
to_offset,
)
from pandas._libs.tslibs.dtypes import FreqGroup
-from pandas._typing import FrameOrSeriesUnion
from pandas.core.dtypes.generic import (
ABCDatetimeIndex,
@@ -40,6 +39,7 @@
from matplotlib.axes import Axes
from pandas import (
+ DataFrame,
DatetimeIndex,
Index,
Series,
@@ -210,7 +210,7 @@ def _get_freq(ax: Axes, series: Series):
return freq, ax_freq
-def use_dynamic_x(ax: Axes, data: FrameOrSeriesUnion) -> bool:
+def use_dynamic_x(ax: Axes, data: DataFrame | Series) -> bool:
freq = _get_index_freq(data.index)
ax_freq = _get_ax_freq(ax)
diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py
index 9bfa24b6371ab..9d509d02c2e4f 100644
--- a/pandas/plotting/_matplotlib/tools.py
+++ b/pandas/plotting/_matplotlib/tools.py
@@ -13,8 +13,6 @@
import matplotlib.ticker as ticker
import numpy as np
-from pandas._typing import FrameOrSeriesUnion
-
from pandas.core.dtypes.common import is_list_like
from pandas.core.dtypes.generic import (
ABCDataFrame,
@@ -31,6 +29,11 @@
from matplotlib.lines import Line2D
from matplotlib.table import Table
+ from pandas import (
+ DataFrame,
+ Series,
+ )
+
def do_adjust_figure(fig: Figure):
"""Whether fig has constrained_layout enabled."""
@@ -55,7 +58,7 @@ def format_date_labels(ax: Axes, rot):
def table(
- ax, data: FrameOrSeriesUnion, rowLabels=None, colLabels=None, **kwargs
+ ax, data: DataFrame | Series, rowLabels=None, colLabels=None, **kwargs
) -> Table:
if isinstance(data, ABCSeries):
data = data.to_frame()
| - [x] closes #40876
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41955 | 2021-06-11T18:16:38Z | 2021-07-04T10:06:54Z | 2021-07-04T10:06:53Z | 2021-07-04T17:47:26Z |
DOC: more cleanup of 1.3 release notes | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index e2b923812a211..45018569a3a04 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -636,7 +636,7 @@ If installed, we now require:
+-----------------+-----------------+----------+---------+
| pytest (dev) | 6.0 | | X |
+-----------------+-----------------+----------+---------+
-| mypy (dev) | 0.800 | | X |
+| mypy (dev) | 0.812 | | X |
+-----------------+-----------------+----------+---------+
| setuptools | 38.6.0 | | X |
+-----------------+-----------------+----------+---------+
@@ -713,64 +713,6 @@ Build
Deprecations
~~~~~~~~~~~~
-- Deprecated allowing scalars to be passed to the :class:`Categorical` constructor (:issue:`38433`)
-- Deprecated constructing :class:`CategoricalIndex` without passing list-like data (:issue:`38944`)
-- Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`, :issue:`21311`, :issue:`22315`, :issue:`26974`)
-- Deprecated the :meth:`astype` method of datetimelike (``timedelta64[ns]``, ``datetime64[ns]``, ``Datetime64TZDtype``, ``PeriodDtype``) to convert to integer dtypes, use ``values.view(...)`` instead (:issue:`38544`)
-- Deprecated :meth:`MultiIndex.is_lexsorted` and :meth:`MultiIndex.lexsort_depth`, use :meth:`MultiIndex.is_monotonic_increasing` instead (:issue:`32259`)
-- Deprecated keyword ``try_cast`` in :meth:`Series.where`, :meth:`Series.mask`, :meth:`DataFrame.where`, :meth:`DataFrame.mask`; cast results manually if desired (:issue:`38836`)
-- Deprecated comparison of :class:`Timestamp` objects with ``datetime.date`` objects. Instead of e.g. ``ts <= mydate`` use ``ts <= pd.Timestamp(mydate)`` or ``ts.date() <= mydate`` (:issue:`36131`)
-- Deprecated :attr:`Rolling.win_type` returning ``"freq"`` (:issue:`38963`)
-- Deprecated :attr:`Rolling.is_datetimelike` (:issue:`38963`)
-- Deprecated :class:`DataFrame` indexer for :meth:`Series.__setitem__` and :meth:`DataFrame.__setitem__` (:issue:`39004`)
-- Deprecated :meth:`ExponentialMovingWindow.vol` (:issue:`39220`)
-- Using ``.astype`` to convert between ``datetime64[ns]`` dtype and :class:`DatetimeTZDtype` is deprecated and will raise in a future version, use ``obj.tz_localize`` or ``obj.dt.tz_localize`` instead (:issue:`38622`)
-- Deprecated casting ``datetime.date`` objects to ``datetime64`` when used as ``fill_value`` in :meth:`DataFrame.unstack`, :meth:`DataFrame.shift`, :meth:`Series.shift`, and :meth:`DataFrame.reindex`, pass ``pd.Timestamp(dateobj)`` instead (:issue:`39767`)
-- Deprecated :meth:`.Styler.set_na_rep` and :meth:`.Styler.set_precision` in favour of :meth:`.Styler.format` with ``na_rep`` and ``precision`` as existing and new input arguments respectively (:issue:`40134`, :issue:`40425`)
-- Deprecated allowing partial failure in :meth:`Series.transform` and :meth:`DataFrame.transform` when ``func`` is list-like or dict-like and raises anything but ``TypeError``; ``func`` raising anything but a ``TypeError`` will raise in a future version (:issue:`40211`)
-- Deprecated arguments ``error_bad_lines`` and ``warn_bad_lines`` in :meth:`read_csv` and :meth:`read_table` in favor of argument ``on_bad_lines`` (:issue:`15122`)
-- Deprecated support for ``np.ma.mrecords.MaskedRecords`` in the :class:`DataFrame` constructor, pass ``{name: data[name] for name in data.dtype.names}`` instead (:issue:`40363`)
-- Deprecated using :func:`merge`, :meth:`DataFrame.merge`, and :meth:`DataFrame.join` on a different number of levels (:issue:`34862`)
-- Deprecated the use of ``**kwargs`` in :class:`.ExcelWriter`; use the keyword argument ``engine_kwargs`` instead (:issue:`40430`)
-- Deprecated the ``level`` keyword for :class:`DataFrame` and :class:`Series` aggregations; use groupby instead (:issue:`39983`)
-- Deprecated the ``inplace`` parameter of :meth:`Categorical.remove_categories`, :meth:`Categorical.add_categories`, :meth:`Categorical.reorder_categories`, :meth:`Categorical.rename_categories`, :meth:`Categorical.set_categories` and will be removed in a future version (:issue:`37643`)
-- Deprecated :func:`merge` producing duplicated columns through the ``suffixes`` keyword and already existing columns (:issue:`22818`)
-- Deprecated setting :attr:`Categorical._codes`, create a new :class:`Categorical` with the desired codes instead (:issue:`40606`)
-- Deprecated the ``convert_float`` optional argument in :func:`read_excel` and :meth:`ExcelFile.parse` (:issue:`41127`)
-- Deprecated behavior of :meth:`DatetimeIndex.union` with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`)
-- Deprecated using ``usecols`` with out of bounds indices for :func:`read_csv` with ``engine="c"`` (:issue:`25623`)
-- Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`)
-- Deprecated behavior of :class:`DataFrame` constructor when a ``dtype`` is passed and the data cannot be cast to that dtype. In a future version, this will raise instead of being silently ignored (:issue:`24435`)
-- Deprecated the :attr:`Timestamp.freq` attribute. For the properties that use it (``is_month_start``, ``is_month_end``, ``is_quarter_start``, ``is_quarter_end``, ``is_year_start``, ``is_year_end``), when you have a ``freq``, use e.g. ``freq.is_month_start(ts)`` (:issue:`15146`)
-- Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`, :issue:`33401`)
-- Deprecated behavior of :class:`Series` construction with large-integer values and small-integer dtype silently overflowing; use ``Series(data).astype(dtype)`` instead (:issue:`41734`)
-- Deprecated behavior of :class:`DataFrame` construction with floating data and integer dtype casting even when lossy; in a future version this will remain floating, matching :class:`Series` behavior (:issue:`41770`)
-- Deprecated inference of ``timedelta64[ns]``, ``datetime64[ns]``, or ``DatetimeTZDtype`` dtypes in :class:`Series` construction when data containing strings is passed and no ``dtype`` is passed (:issue:`33558`)
-- In a future version, constructing :class:`Series` or :class:`DataFrame` with ``datetime64[ns]`` data and ``DatetimeTZDtype`` will treat the data as wall-times instead of as UTC times (matching DatetimeIndex behavior). To treat the data as UTC times, use ``pd.Series(data).dt.tz_localize("UTC").dt.tz_convert(dtype.tz)`` or ``pd.Series(data.view("int64"), dtype=dtype)`` (:issue:`33401`)
-- Deprecated passing lists as ``key`` to :meth:`DataFrame.xs` and :meth:`Series.xs` (:issue:`41760`)
-- Deprecated passing arguments as positional for all of the following, with exceptions noted (:issue:`41485`):
- - :func:`concat` (other than ``objs``)
- - :func:`read_csv` (other than ``filepath_or_buffer``)
- - :func:`read_table` (other than ``filepath_or_buffer``)
- - :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``upper`` and ``lower``)
- - :meth:`DataFrame.drop_duplicates` (except for ``subset``), :meth:`Series.drop_duplicates`, :meth:`Index.drop_duplicates` and :meth:`MultiIndex.drop_duplicates`
- - :meth:`DataFrame.drop` (other than ``labels``) and :meth:`Series.drop`
- - :meth:`DataFrame.dropna` and :meth:`Series.dropna`
- - :meth:`DataFrame.ffill`, :meth:`Series.ffill`, :meth:`DataFrame.bfill`, and :meth:`Series.bfill`
- - :meth:`DataFrame.fillna` and :meth:`Series.fillna` (apart from ``value``)
- - :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (other than ``method``)
- - :meth:`DataFrame.mask` and :meth:`Series.mask` (other than ``cond`` and ``other``)
- - :meth:`DataFrame.reset_index` (other than ``level``) and :meth:`Series.reset_index`
- - :meth:`DataFrame.set_axis` and :meth:`Series.set_axis` (other than ``labels``)
- - :meth:`DataFrame.set_index` (other than ``keys``)
- - :meth:`DataFrame.sort_index` and :meth:`Series.sort_index`
- - :meth:`DataFrame.sort_values` (other than ``by``) and :meth:`Series.sort_values`
- - :meth:`DataFrame.where` and :meth:`Series.where` (other than ``cond`` and ``other``)
- - :meth:`Index.set_names` and :meth:`MultiIndex.set_names` (except for ``names``)
- - :meth:`MultiIndex.codes` (except for ``codes``)
- - :meth:`MultiIndex.set_levels` (except for ``levels``)
- - :meth:`Resampler.interpolate` (other than ``method``)
-
.. _whatsnew_130.deprecations.nuisance_columns:
@@ -851,6 +793,70 @@ For example:
1 2
2 12
+.. _whatsnew_130.deprecations.other:
+
+Other Deprecations
+^^^^^^^^^^^^^^^^^^
+- Deprecated allowing scalars to be passed to the :class:`Categorical` constructor (:issue:`38433`)
+- Deprecated constructing :class:`CategoricalIndex` without passing list-like data (:issue:`38944`)
+- Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`, :issue:`21311`, :issue:`22315`, :issue:`26974`)
+- Deprecated the :meth:`astype` method of datetimelike (``timedelta64[ns]``, ``datetime64[ns]``, ``Datetime64TZDtype``, ``PeriodDtype``) to convert to integer dtypes, use ``values.view(...)`` instead (:issue:`38544`)
+- Deprecated :meth:`MultiIndex.is_lexsorted` and :meth:`MultiIndex.lexsort_depth`, use :meth:`MultiIndex.is_monotonic_increasing` instead (:issue:`32259`)
+- Deprecated keyword ``try_cast`` in :meth:`Series.where`, :meth:`Series.mask`, :meth:`DataFrame.where`, :meth:`DataFrame.mask`; cast results manually if desired (:issue:`38836`)
+- Deprecated comparison of :class:`Timestamp` objects with ``datetime.date`` objects. Instead of e.g. ``ts <= mydate`` use ``ts <= pd.Timestamp(mydate)`` or ``ts.date() <= mydate`` (:issue:`36131`)
+- Deprecated :attr:`Rolling.win_type` returning ``"freq"`` (:issue:`38963`)
+- Deprecated :attr:`Rolling.is_datetimelike` (:issue:`38963`)
+- Deprecated :class:`DataFrame` indexer for :meth:`Series.__setitem__` and :meth:`DataFrame.__setitem__` (:issue:`39004`)
+- Deprecated :meth:`ExponentialMovingWindow.vol` (:issue:`39220`)
+- Using ``.astype`` to convert between ``datetime64[ns]`` dtype and :class:`DatetimeTZDtype` is deprecated and will raise in a future version, use ``obj.tz_localize`` or ``obj.dt.tz_localize`` instead (:issue:`38622`)
+- Deprecated casting ``datetime.date`` objects to ``datetime64`` when used as ``fill_value`` in :meth:`DataFrame.unstack`, :meth:`DataFrame.shift`, :meth:`Series.shift`, and :meth:`DataFrame.reindex`, pass ``pd.Timestamp(dateobj)`` instead (:issue:`39767`)
+- Deprecated :meth:`.Styler.set_na_rep` and :meth:`.Styler.set_precision` in favour of :meth:`.Styler.format` with ``na_rep`` and ``precision`` as existing and new input arguments respectively (:issue:`40134`, :issue:`40425`)
+- Deprecated allowing partial failure in :meth:`Series.transform` and :meth:`DataFrame.transform` when ``func`` is list-like or dict-like and raises anything but ``TypeError``; ``func`` raising anything but a ``TypeError`` will raise in a future version (:issue:`40211`)
+- Deprecated arguments ``error_bad_lines`` and ``warn_bad_lines`` in :meth:`read_csv` and :meth:`read_table` in favor of argument ``on_bad_lines`` (:issue:`15122`)
+- Deprecated support for ``np.ma.mrecords.MaskedRecords`` in the :class:`DataFrame` constructor, pass ``{name: data[name] for name in data.dtype.names}`` instead (:issue:`40363`)
+- Deprecated using :func:`merge`, :meth:`DataFrame.merge`, and :meth:`DataFrame.join` on a different number of levels (:issue:`34862`)
+- Deprecated the use of ``**kwargs`` in :class:`.ExcelWriter`; use the keyword argument ``engine_kwargs`` instead (:issue:`40430`)
+- Deprecated the ``level`` keyword for :class:`DataFrame` and :class:`Series` aggregations; use groupby instead (:issue:`39983`)
+- Deprecated the ``inplace`` parameter of :meth:`Categorical.remove_categories`, :meth:`Categorical.add_categories`, :meth:`Categorical.reorder_categories`, :meth:`Categorical.rename_categories`, :meth:`Categorical.set_categories` and will be removed in a future version (:issue:`37643`)
+- Deprecated :func:`merge` producing duplicated columns through the ``suffixes`` keyword and already existing columns (:issue:`22818`)
+- Deprecated setting :attr:`Categorical._codes`, create a new :class:`Categorical` with the desired codes instead (:issue:`40606`)
+- Deprecated the ``convert_float`` optional argument in :func:`read_excel` and :meth:`ExcelFile.parse` (:issue:`41127`)
+- Deprecated behavior of :meth:`DatetimeIndex.union` with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`)
+- Deprecated using ``usecols`` with out of bounds indices for :func:`read_csv` with ``engine="c"`` (:issue:`25623`)
+- Deprecated special treatment of lists with first element a Categorical in the :class:`DataFrame` constructor; pass as ``pd.DataFrame({col: categorical, ...})`` instead (:issue:`38845`)
+- Deprecated behavior of :class:`DataFrame` constructor when a ``dtype`` is passed and the data cannot be cast to that dtype. In a future version, this will raise instead of being silently ignored (:issue:`24435`)
+- Deprecated the :attr:`Timestamp.freq` attribute. For the properties that use it (``is_month_start``, ``is_month_end``, ``is_quarter_start``, ``is_quarter_end``, ``is_year_start``, ``is_year_end``), when you have a ``freq``, use e.g. ``freq.is_month_start(ts)`` (:issue:`15146`)
+- Deprecated construction of :class:`Series` or :class:`DataFrame` with ``DatetimeTZDtype`` data and ``datetime64[ns]`` dtype. Use ``Series(data).dt.tz_localize(None)`` instead (:issue:`41555`, :issue:`33401`)
+- Deprecated behavior of :class:`Series` construction with large-integer values and small-integer dtype silently overflowing; use ``Series(data).astype(dtype)`` instead (:issue:`41734`)
+- Deprecated behavior of :class:`DataFrame` construction with floating data and integer dtype casting even when lossy; in a future version this will remain floating, matching :class:`Series` behavior (:issue:`41770`)
+- Deprecated inference of ``timedelta64[ns]``, ``datetime64[ns]``, or ``DatetimeTZDtype`` dtypes in :class:`Series` construction when data containing strings is passed and no ``dtype`` is passed (:issue:`33558`)
+- In a future version, constructing :class:`Series` or :class:`DataFrame` with ``datetime64[ns]`` data and ``DatetimeTZDtype`` will treat the data as wall-times instead of as UTC times (matching DatetimeIndex behavior). To treat the data as UTC times, use ``pd.Series(data).dt.tz_localize("UTC").dt.tz_convert(dtype.tz)`` or ``pd.Series(data.view("int64"), dtype=dtype)`` (:issue:`33401`)
+- Deprecated passing lists as ``key`` to :meth:`DataFrame.xs` and :meth:`Series.xs` (:issue:`41760`)
+- Deprecated passing arguments as positional for all of the following, with exceptions noted (:issue:`41485`):
+
+ - :func:`concat` (other than ``objs``)
+ - :func:`read_csv` (other than ``filepath_or_buffer``)
+ - :func:`read_table` (other than ``filepath_or_buffer``)
+ - :meth:`DataFrame.clip` and :meth:`Series.clip` (other than ``upper`` and ``lower``)
+ - :meth:`DataFrame.drop_duplicates` (except for ``subset``), :meth:`Series.drop_duplicates`, :meth:`Index.drop_duplicates` and :meth:`MultiIndex.drop_duplicates`
+ - :meth:`DataFrame.drop` (other than ``labels``) and :meth:`Series.drop`
+ - :meth:`DataFrame.dropna` and :meth:`Series.dropna`
+ - :meth:`DataFrame.ffill`, :meth:`Series.ffill`, :meth:`DataFrame.bfill`, and :meth:`Series.bfill`
+ - :meth:`DataFrame.fillna` and :meth:`Series.fillna` (apart from ``value``)
+ - :meth:`DataFrame.interpolate` and :meth:`Series.interpolate` (other than ``method``)
+ - :meth:`DataFrame.mask` and :meth:`Series.mask` (other than ``cond`` and ``other``)
+ - :meth:`DataFrame.reset_index` (other than ``level``) and :meth:`Series.reset_index`
+ - :meth:`DataFrame.set_axis` and :meth:`Series.set_axis` (other than ``labels``)
+ - :meth:`DataFrame.set_index` (other than ``keys``)
+ - :meth:`DataFrame.sort_index` and :meth:`Series.sort_index`
+ - :meth:`DataFrame.sort_values` (other than ``by``) and :meth:`Series.sort_values`
+ - :meth:`DataFrame.where` and :meth:`Series.where` (other than ``cond`` and ``other``)
+ - :meth:`Index.set_names` and :meth:`MultiIndex.set_names` (except for ``names``)
+ - :meth:`MultiIndex.codes` (except for ``codes``)
+ - :meth:`MultiIndex.set_levels` (except for ``levels``)
+ - :meth:`Resampler.interpolate` (other than ``method``)
+
+
.. ---------------------------------------------------------------------------
| and fixes https://github.com/pandas-dev/pandas/pull/41908#issuecomment-858571515 | https://api.github.com/repos/pandas-dev/pandas/pulls/41954 | 2021-06-11T16:32:25Z | 2021-06-15T13:11:02Z | 2021-06-15T13:11:02Z | 2021-06-15T13:11:10Z |
BUG: take nans correctly into consideration in complex and tuple | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 1a5a9980e5e96..cadc5615cd654 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -1033,6 +1033,7 @@ Missing
- Bug in :meth:`DataFrame.fillna` not accepting a dictionary for the ``downcast`` keyword (:issue:`40809`)
- Bug in :func:`isna` not returning a copy of the mask for nullable types, causing any subsequent mask modification to change the original array (:issue:`40935`)
- Bug in :class:`DataFrame` construction with float data containing ``NaN`` and an integer ``dtype`` casting instead of retaining the ``NaN`` (:issue:`26919`)
+- Bug in :meth:`Series.isin` and :meth:`MultiIndex.isin` didn't treat all nans as equivalent if they were in tuples (:issue:`41836`)
MultiIndex
^^^^^^^^^^
diff --git a/pandas/_libs/src/klib/khash_python.h b/pandas/_libs/src/klib/khash_python.h
index aee018262e3a6..87c6283c19a2f 100644
--- a/pandas/_libs/src/klib/khash_python.h
+++ b/pandas/_libs/src/klib/khash_python.h
@@ -163,18 +163,90 @@ KHASH_MAP_INIT_COMPLEX128(complex128, size_t)
#define kh_exist_complex128(h, k) (kh_exist(h, k))
+// NaN-floats should be in the same equivalency class, see GH 22119
+int PANDAS_INLINE floatobject_cmp(PyFloatObject* a, PyFloatObject* b){
+ return (
+ Py_IS_NAN(PyFloat_AS_DOUBLE(a)) &&
+ Py_IS_NAN(PyFloat_AS_DOUBLE(b))
+ )
+ ||
+ ( PyFloat_AS_DOUBLE(a) == PyFloat_AS_DOUBLE(b) );
+}
+
+
+// NaNs should be in the same equivalency class, see GH 41836
+// PyObject_RichCompareBool for complexobjects has a different behavior
+// needs to be replaced
+int PANDAS_INLINE complexobject_cmp(PyComplexObject* a, PyComplexObject* b){
+ return (
+ Py_IS_NAN(a->cval.real) &&
+ Py_IS_NAN(b->cval.real) &&
+ Py_IS_NAN(a->cval.imag) &&
+ Py_IS_NAN(b->cval.imag)
+ )
+ ||
+ (
+ Py_IS_NAN(a->cval.real) &&
+ Py_IS_NAN(b->cval.real) &&
+ a->cval.imag == b->cval.imag
+ )
+ ||
+ (
+ a->cval.real == b->cval.real &&
+ Py_IS_NAN(a->cval.imag) &&
+ Py_IS_NAN(b->cval.imag)
+ )
+ ||
+ (
+ a->cval.real == b->cval.real &&
+ a->cval.imag == b->cval.imag
+ );
+}
+
+int PANDAS_INLINE pyobject_cmp(PyObject* a, PyObject* b);
+
+
+// replacing PyObject_RichCompareBool (NaN!=NaN) with pyobject_cmp (NaN==NaN),
+// which treats NaNs as equivalent
+// see GH 41836
+int PANDAS_INLINE tupleobject_cmp(PyTupleObject* a, PyTupleObject* b){
+ Py_ssize_t i;
+
+ if (Py_SIZE(a) != Py_SIZE(b)) {
+ return 0;
+ }
+
+ for (i = 0; i < Py_SIZE(a); ++i) {
+ if (!pyobject_cmp(PyTuple_GET_ITEM(a, i), PyTuple_GET_ITEM(b, i))) {
+ return 0;
+ }
+ }
+ return 1;
+}
+
+
int PANDAS_INLINE pyobject_cmp(PyObject* a, PyObject* b) {
+ if (Py_TYPE(a) == Py_TYPE(b)) {
+ // special handling for some built-in types which could have NaNs
+ // as we would like to have them equivalent, but the usual
+ // PyObject_RichCompareBool would return False
+ if (PyFloat_CheckExact(a)) {
+ return floatobject_cmp((PyFloatObject*)a, (PyFloatObject*)b);
+ }
+ if (PyComplex_CheckExact(a)) {
+ return complexobject_cmp((PyComplexObject*)a, (PyComplexObject*)b);
+ }
+ if (PyTuple_CheckExact(a)) {
+ return tupleobject_cmp((PyTupleObject*)a, (PyTupleObject*)b);
+ }
+ // frozenset isn't yet supported
+ }
+
int result = PyObject_RichCompareBool(a, b, Py_EQ);
if (result < 0) {
PyErr_Clear();
return 0;
}
- if (result == 0) { // still could be two NaNs
- return PyFloat_CheckExact(a) &&
- PyFloat_CheckExact(b) &&
- Py_IS_NAN(PyFloat_AS_DOUBLE(a)) &&
- Py_IS_NAN(PyFloat_AS_DOUBLE(b));
- }
return result;
}
diff --git a/pandas/tests/indexes/multi/test_isin.py b/pandas/tests/indexes/multi/test_isin.py
index 97eb34e28764b..695458273d16e 100644
--- a/pandas/tests/indexes/multi/test_isin.py
+++ b/pandas/tests/indexes/multi/test_isin.py
@@ -1,14 +1,11 @@
import numpy as np
import pytest
-from pandas.compat import PYPY
-
from pandas import MultiIndex
import pandas._testing as tm
-@pytest.mark.skipif(not PYPY, reason="tuples cmp recursively on PyPy")
-def test_isin_nan_pypy():
+def test_isin_nan():
idx = MultiIndex.from_arrays([["foo", "bar"], [1.0, np.nan]])
tm.assert_numpy_array_equal(idx.isin([("bar", np.nan)]), np.array([False, True]))
tm.assert_numpy_array_equal(
@@ -31,15 +28,6 @@ def test_isin():
assert result.dtype == np.bool_
-@pytest.mark.skipif(PYPY, reason="tuples cmp recursively on PyPy")
-def test_isin_nan_not_pypy():
- idx = MultiIndex.from_arrays([["foo", "bar"], [1.0, np.nan]])
- tm.assert_numpy_array_equal(idx.isin([("bar", np.nan)]), np.array([False, False]))
- tm.assert_numpy_array_equal(
- idx.isin([("bar", float("nan"))]), np.array([False, False])
- )
-
-
def test_isin_level_kwarg():
idx = MultiIndex.from_arrays([["qux", "baz", "foo", "bar"], np.arange(4)])
diff --git a/pandas/tests/libs/test_hashtable.py b/pandas/tests/libs/test_hashtable.py
index aeff591e3f0dc..0edcebdc069f4 100644
--- a/pandas/tests/libs/test_hashtable.py
+++ b/pandas/tests/libs/test_hashtable.py
@@ -8,6 +8,7 @@
import pandas as pd
import pandas._testing as tm
+from pandas.core.algorithms import isin
@contextmanager
@@ -178,6 +179,67 @@ def test_no_reallocation(self, table_type, dtype):
assert n_buckets_start == clean_table.get_state()["n_buckets"]
+class TestPyObjectHashTableWithNans:
+ def test_nan_float(self):
+ nan1 = float("nan")
+ nan2 = float("nan")
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+
+ def test_nan_complex_both(self):
+ nan1 = complex(float("nan"), float("nan"))
+ nan2 = complex(float("nan"), float("nan"))
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+
+ def test_nan_complex_real(self):
+ nan1 = complex(float("nan"), 1)
+ nan2 = complex(float("nan"), 1)
+ other = complex(float("nan"), 2)
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+ with pytest.raises(KeyError, match=None) as error:
+ table.get_item(other)
+ assert str(error.value) == str(other)
+
+ def test_nan_complex_imag(self):
+ nan1 = complex(1, float("nan"))
+ nan2 = complex(1, float("nan"))
+ other = complex(2, float("nan"))
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+ with pytest.raises(KeyError, match=None) as error:
+ table.get_item(other)
+ assert str(error.value) == str(other)
+
+ def test_nan_in_tuple(self):
+ nan1 = (float("nan"),)
+ nan2 = (float("nan"),)
+ assert nan1[0] is not nan2[0]
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+
+ def test_nan_in_nested_tuple(self):
+ nan1 = (1, (2, (float("nan"),)))
+ nan2 = (1, (2, (float("nan"),)))
+ other = (1, 2)
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+ with pytest.raises(KeyError, match=None) as error:
+ table.get_item(other)
+ assert str(error.value) == str(other)
+
+
def test_get_labels_groupby_for_Int64(writable):
table = ht.Int64HashTable()
vals = np.array([1, 2, -1, 2, 1, -1], dtype=np.int64)
@@ -426,3 +488,12 @@ def test_mode(self, dtype, type_suffix):
values = np.array([42, np.nan, np.nan, np.nan], dtype=dtype)
assert mode(values, True) == 42
assert np.isnan(mode(values, False))
+
+
+def test_ismember_tuple_with_nans():
+ # GH-41836
+ values = [("a", float("nan")), ("b", 1)]
+ comps = [("a", float("nan"))]
+ result = isin(values, comps)
+ expected = np.array([True, False], dtype=np.bool_)
+ tm.assert_numpy_array_equal(result, expected)
| - [x] closes #41836
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
NaNs as Float are already handled correctly (all nans are the same equavalency class), this PR adds similar functionality for complex and tuple.
It doesn't handle `frozenset` (see also discussion in #41836) because it would require to duplicate a lot of code/internal details from setobject. | https://api.github.com/repos/pandas-dev/pandas/pulls/41952 | 2021-06-11T15:06:58Z | 2021-06-16T22:15:37Z | 2021-06-16T22:15:36Z | 2021-06-16T22:15:53Z |
DOC: fix link to pickle in msgpack section | diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index dbefd1f20d2e3..c2b030d732ba9 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -31,7 +31,6 @@ The pandas I/O API is a set of top level ``reader`` functions accessed like
binary;`Feather Format <https://github.com/wesm/feather>`__;:ref:`read_feather<io.feather>`;:ref:`to_feather<io.feather>`
binary;`Parquet Format <https://parquet.apache.org/>`__;:ref:`read_parquet<io.parquet>`;:ref:`to_parquet<io.parquet>`
binary;`ORC Format <https://orc.apache.org/>`__;:ref:`read_orc<io.orc>`;
- binary;`Msgpack <https://msgpack.org/>`__;:ref:`read_msgpack<io.msgpack>`;:ref:`to_msgpack<io.msgpack>`
binary;`Stata <https://en.wikipedia.org/wiki/Stata>`__;:ref:`read_stata<io.stata_reader>`;:ref:`to_stata<io.stata_writer>`
binary;`SAS <https://en.wikipedia.org/wiki/SAS_(software)>`__;:ref:`read_sas<io.sas_reader>`;
binary;`SPSS <https://en.wikipedia.org/wiki/SPSS>`__;:ref:`read_spss<io.spss_reader>`;
@@ -4010,7 +4009,7 @@ msgpack
-------
pandas support for ``msgpack`` has been removed in version 1.0.0. It is
-recommended to use :ref:`pickle <io.pickle` instead.
+recommended to use :ref:`pickle <io.pickle>` instead.
Alternatively, you can also the Arrow IPC serialization format for on-the-wire
transmission of pandas objects. For documentation on pyarrow, see
| That failed the doc build. In addition also removed the msgpack row in the table at the top of the page, since those functions don't exist anymore. | https://api.github.com/repos/pandas-dev/pandas/pulls/41950 | 2021-06-11T12:22:09Z | 2021-06-11T14:33:27Z | 2021-06-11T14:33:27Z | 2021-06-11T14:37:41Z |
CI: use pyarrow 0.17.1 instead of 0.17.0 for py37_macos build | diff --git a/ci/deps/azure-macos-37.yaml b/ci/deps/azure-macos-37.yaml
index 63e858eac433f..43e1055347f17 100644
--- a/ci/deps/azure-macos-37.yaml
+++ b/ci/deps/azure-macos-37.yaml
@@ -22,7 +22,7 @@ dependencies:
- numexpr
- numpy=1.17.3
- openpyxl
- - pyarrow=0.17.0
+ - pyarrow=0.17
- pytables
- python-dateutil==2.7.3
- pytz
| Closes #41937 | https://api.github.com/repos/pandas-dev/pandas/pulls/41948 | 2021-06-11T11:30:36Z | 2021-06-11T23:56:04Z | 2021-06-11T23:56:04Z | 2021-06-12T08:31:36Z |
ENH: `sparse_columns` and `sparse_index` added to `Styler.to_html` | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 432dd46000eb3..62f1d9aef3e13 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -35,6 +35,7 @@ Other enhancements
- Additional options added to :meth:`.Styler.bar` to control alignment and display, with keyword only arguments (:issue:`26070`, :issue:`36419`)
- :meth:`Styler.bar` now validates the input argument ``width`` and ``height`` (:issue:`42511`)
- :meth:`Series.ewm`, :meth:`DataFrame.ewm`, now support a ``method`` argument with a ``'table'`` option that performs the windowing operation over an entire :class:`DataFrame`. See :ref:`Window Overview <window.overview>` for performance and functional benefits (:issue:`42273`)
+- Added ``sparse_index`` and ``sparse_columns`` keyword arguments to :meth:`.Styler.to_html` (:issue:`41946`)
- Added keyword argument ``environment`` to :meth:`.Styler.to_latex` also allowing a specific "longtable" entry with a separate jinja2 template (:issue:`41866`)
-
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 9dade82e9809c..af1c0ca34ec0f 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -476,8 +476,8 @@ def to_latex(
Defaults to ``pandas.options.styler.sparse.index`` value.
sparse_columns : bool, optional
Whether to sparsify the display of a hierarchical index. Setting to False
- will display each explicit level element in a hierarchical key for each row.
- Defaults to ``pandas.options.styler.sparse.columns`` value.
+ will display each explicit level element in a hierarchical key for each
+ column. Defaults to ``pandas.options.styler.sparse.columns`` value.
multirow_align : {"c", "t", "b"}
If sparsifying hierarchical MultiIndexes whether to align text centrally,
at the top or bottom.
@@ -815,6 +815,8 @@ def to_html(
*,
table_uuid: str | None = None,
table_attributes: str | None = None,
+ sparse_index: bool | None = None,
+ sparse_columns: bool | None = None,
encoding: str | None = None,
doctype_html: bool = False,
exclude_styles: bool = False,
@@ -840,6 +842,18 @@ def to_html(
``<table .. <table_attributes> >``
If not given defaults to Styler's preexisting value.
+ sparse_index : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each row.
+ Defaults to ``pandas.options.styler.sparse.index`` value.
+
+ .. versionadded:: 1.4.0
+ sparse_columns : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each
+ column. Defaults to ``pandas.options.styler.sparse.columns`` value.
+
+ .. versionadded:: 1.4.0
encoding : str, optional
Character encoding setting for file output, and HTML meta tags,
defaults to "utf-8" if None.
@@ -866,8 +880,15 @@ def to_html(
if table_attributes:
self.set_table_attributes(table_attributes)
+ if sparse_index is None:
+ sparse_index = get_option("styler.sparse.index")
+ if sparse_columns is None:
+ sparse_columns = get_option("styler.sparse.columns")
+
# Build HTML string..
- html = self.render(
+ html = self._render_html(
+ sparse_index=sparse_index,
+ sparse_columns=sparse_columns,
exclude_styles=exclude_styles,
encoding=encoding if encoding else "utf-8",
doctype_html=doctype_html,
diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py
index 4e71cb4c46626..2657370bf8258 100644
--- a/pandas/tests/io/formats/style/test_html.py
+++ b/pandas/tests/io/formats/style/test_html.py
@@ -6,6 +6,7 @@
from pandas import (
DataFrame,
MultiIndex,
+ option_context,
)
jinja2 = pytest.importorskip("jinja2")
@@ -429,3 +430,24 @@ def test_sticky_levels(styler_mi, index, columns):
def test_sticky_raises(styler):
with pytest.raises(ValueError, match="`axis` must be"):
styler.set_sticky(axis="bad")
+
+
+@pytest.mark.parametrize(
+ "sparse_index, sparse_columns",
+ [(True, True), (True, False), (False, True), (False, False)],
+)
+def test_sparse_options(sparse_index, sparse_columns):
+ cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])
+ ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])
+ df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=ridx, columns=cidx)
+ styler = df.style
+
+ default_html = styler.to_html() # defaults under pd.options to (True , True)
+
+ with option_context(
+ "styler.sparse.index", sparse_index, "styler.sparse.columns", sparse_columns
+ ):
+ html1 = styler.to_html()
+ assert (html1 == default_html) is (sparse_index and sparse_columns)
+ html2 = styler.to_html(sparse_index=sparse_index, sparse_columns=sparse_columns)
+ assert html1 == html2
| Checks an item off the list in #41693
| https://api.github.com/repos/pandas-dev/pandas/pulls/41946 | 2021-06-11T09:53:35Z | 2021-07-28T23:01:05Z | 2021-07-28T23:01:05Z | 2021-07-29T14:59:15Z |
TYP: make numpy.typing available from pandas._typing | diff --git a/pandas/_typing.py b/pandas/_typing.py
index a9852dd4b13cf..ccf7699fb0b4b 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -42,6 +42,8 @@
final,
)
+ import numpy.typing as npt
+
from pandas._libs import (
Period,
Timedelta,
@@ -73,6 +75,7 @@
from pandas.io.formats.format import EngFormatter
from pandas.tseries.offsets import DateOffset
else:
+ npt: Any = None
# typing.final does not exist until py38
final = lambda x: x
# typing.TypedDict does not exist until py38
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 0acbb0c34266f..d61b818195d08 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -63,13 +63,13 @@
IndexKeyFunc,
IndexLabel,
Level,
- NpDtype,
PythonFuncType,
Renamer,
Scalar,
StorageOptions,
Suffixes,
ValueKeyFunc,
+ npt,
)
from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
@@ -1593,7 +1593,7 @@ def from_dict(
def to_numpy(
self,
- dtype: NpDtype | None = None,
+ dtype: npt.DTypeLike | None = None,
copy: bool = False,
na_value=lib.no_default,
) -> np.ndarray:
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index adc722e770cff..1f9bcf52cb938 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -46,7 +46,6 @@
JSONSerializable,
Level,
Manager,
- NpDtype,
RandomState,
Renamer,
StorageOptions,
@@ -55,6 +54,7 @@
TimestampConvertibleTypes,
ValueKeyFunc,
final,
+ npt,
)
from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
@@ -1988,7 +1988,7 @@ def empty(self) -> bool_t:
# GH#23114 Ensure ndarray.__op__(DataFrame) returns NotImplemented
__array_priority__ = 1000
- def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
+ def __array__(self, dtype: npt.DTypeLike | None = None) -> np.ndarray:
return np.asarray(self._values, dtype=dtype)
def __array_wrap__(
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 48f0b7f7f964b..f1358be043d27 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -22,9 +22,9 @@
from pandas._libs.internals import BlockPlacement
from pandas._typing import (
ArrayLike,
- Dtype,
DtypeObj,
Shape,
+ npt,
type_t,
)
from pandas.errors import PerformanceWarning
@@ -1385,7 +1385,7 @@ def to_dict(self, copy: bool = True):
def as_array(
self,
transpose: bool = False,
- dtype: Dtype | None = None,
+ dtype: npt.DTypeLike | None = None,
copy: bool = False,
na_value=lib.no_default,
) -> np.ndarray:
@@ -1425,17 +1425,21 @@ def as_array(
# error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no
# attribute "to_numpy"
arr = blk.values.to_numpy( # type: ignore[union-attr]
- dtype=dtype, na_value=na_value
+ # pandas/core/internals/managers.py:1428: error: Argument "dtype" to
+ # "to_numpy" of "ExtensionArray" has incompatible type
+ # "Optional[Union[dtype[Any], None, type, _SupportsDType, str,
+ # Union[Tuple[Any, int], Tuple[Any, Union[SupportsIndex,
+ # Sequence[SupportsIndex]]], List[Any], _DTypeDict, Tuple[Any,
+ # Any]]]]"; expected "Optional[Union[ExtensionDtype, Union[str,
+ # dtype[Any]], Type[str], Type[float], Type[int], Type[complex],
+ # Type[bool], Type[object]]]"
+ dtype=dtype, # type: ignore[arg-type]
+ na_value=na_value,
).reshape(blk.shape)
else:
arr = np.asarray(blk.get_values())
if dtype:
- # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has
- # incompatible type "Union[ExtensionDtype, str, dtype[Any],
- # Type[object]]"; expected "Union[dtype[Any], None, type,
- # _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int,
- # Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]"
- arr = arr.astype(dtype, copy=False) # type: ignore[arg-type]
+ arr = arr.astype(dtype, copy=False)
else:
arr = self._interleave(dtype=dtype, na_value=na_value)
# The underlying data was copied within _interleave
@@ -1450,7 +1454,9 @@ def as_array(
return arr.transpose() if transpose else arr
def _interleave(
- self, dtype: Dtype | None = None, na_value=lib.no_default
+ self,
+ dtype: npt.DTypeLike | ExtensionDtype | None = None,
+ na_value=lib.no_default,
) -> np.ndarray:
"""
Return ndarray from blocks with specified item order
@@ -1485,7 +1491,16 @@ def _interleave(
# error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no
# attribute "to_numpy"
arr = blk.values.to_numpy( # type: ignore[union-attr]
- dtype=dtype, na_value=na_value
+ # pandas/core/internals/managers.py:1485: error: Argument "dtype" to
+ # "to_numpy" of "ExtensionArray" has incompatible type
+ # "Union[dtype[Any], None, type, _SupportsDType, str, Tuple[Any,
+ # Union[SupportsIndex, Sequence[SupportsIndex]]], List[Any],
+ # _DTypeDict, Tuple[Any, Any], ExtensionDtype]"; expected
+ # "Optional[Union[ExtensionDtype, Union[str, dtype[Any]], Type[str],
+ # Type[float], Type[int], Type[complex], Type[bool], Type[object]]]"
+ # [arg-type]
+ dtype=dtype, # type: ignore[arg-type]
+ na_value=na_value,
)
else:
# error: Argument 1 to "get_values" of "Block" has incompatible type
diff --git a/pandas/core/series.py b/pandas/core/series.py
index c20e09e9eac5d..def938861a775 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -41,10 +41,10 @@
FillnaOptions,
FrameOrSeriesUnion,
IndexKeyFunc,
- NpDtype,
SingleManager,
StorageOptions,
ValueKeyFunc,
+ npt,
)
from pandas.compat.numpy import function as nv
from pandas.errors import InvalidIndexError
@@ -808,7 +808,7 @@ def view(self, dtype: Dtype | None = None) -> Series:
# NDArray Compat
_HANDLED_TYPES = (Index, ExtensionArray, np.ndarray)
- def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
+ def __array__(self, dtype: npt.DTypeLike | None = None) -> np.ndarray:
"""
Return the values as a NumPy array.
| xref https://github.com/pandas-dev/pandas/issues/41807#issuecomment-859372500
this does not update the `__array__` to `to_numpy` methods of EA, see https://github.com/pandas-dev/pandas/pull/41185#issuecomment-852469918 but does need a couple of ignores till that is done.
(we are removing 3 anyway, so a net reduction in ignores :smile:, and reducing false positives for users)
| https://api.github.com/repos/pandas-dev/pandas/pulls/41945 | 2021-06-11T09:51:13Z | 2021-06-25T22:16:43Z | 2021-06-25T22:16:43Z | 2021-07-02T19:12:48Z |
[ArrayManager] Enable pytables IO by falling back to BlockManager | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 0eae6ea5d6b7b..208b8a008ffe6 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -86,7 +86,10 @@
)
from pandas.core.construction import extract_array
from pandas.core.indexes.api import ensure_index
-from pandas.core.internals import BlockManager
+from pandas.core.internals import (
+ ArrayManager,
+ BlockManager,
+)
from pandas.io.common import stringify_path
from pandas.io.formats.printing import (
@@ -3206,6 +3209,11 @@ def read(
def write(self, obj, **kwargs):
super().write(obj, **kwargs)
+
+ # TODO(ArrayManager) HDFStore relies on accessing the blocks
+ if isinstance(obj._mgr, ArrayManager):
+ obj = obj._as_manager("block")
+
data = obj._mgr
if not data.is_consolidated():
data = data.consolidate()
@@ -4015,6 +4023,10 @@ def _get_blocks_and_items(
):
# Helper to clarify non-state-altering parts of _create_axes
+ # TODO(ArrayManager) HDFStore relies on accessing the blocks
+ if isinstance(frame._mgr, ArrayManager):
+ frame = frame._as_manager("block")
+
def get_blk_items(mgr):
return [mgr.items.take(blk.mgr_locs) for blk in mgr.blocks]
diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py
index 2569eb0c9e786..719b54a57a6c7 100644
--- a/pandas/tests/io/pytables/test_append.py
+++ b/pandas/tests/io/pytables/test_append.py
@@ -25,7 +25,7 @@
ensure_clean_store,
)
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
@pytest.mark.filterwarnings("ignore:object name:tables.exceptions.NaturalNameWarning")
@@ -714,6 +714,10 @@ def check(obj, comparator):
tm.assert_frame_equal(store.select("df2"), df)
+# TODO(ArrayManager) currently we rely on falling back to BlockManager, but
+# the conversion from AM->BM converts the invalid object dtype column into
+# a datetime64 column no longer raising an error
+@td.skip_array_manager_not_yet_implemented
def test_append_raise(setup_path):
with ensure_clean_store(setup_path) as store:
diff --git a/pandas/tests/io/pytables/test_categorical.py b/pandas/tests/io/pytables/test_categorical.py
index 0b3d56ebf959e..d2348ca8e314d 100644
--- a/pandas/tests/io/pytables/test_categorical.py
+++ b/pandas/tests/io/pytables/test_categorical.py
@@ -1,8 +1,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas import (
Categorical,
DataFrame,
@@ -19,7 +17,6 @@
pytestmark = [
pytest.mark.single,
- td.skip_array_manager_not_yet_implemented,
# pytables https://github.com/PyTables/PyTables/issues/822
pytest.mark.filterwarnings(
"ignore:a closed node found in the registry:UserWarning"
diff --git a/pandas/tests/io/pytables/test_compat.py b/pandas/tests/io/pytables/test_compat.py
index 4688d7d2be40a..c7200385aa998 100644
--- a/pandas/tests/io/pytables/test_compat.py
+++ b/pandas/tests/io/pytables/test_compat.py
@@ -1,15 +1,11 @@
import pytest
-import pandas.util._test_decorators as td
-
import pandas as pd
import pandas._testing as tm
from pandas.tests.io.pytables.common import ensure_clean_path
tables = pytest.importorskip("tables")
-pytestmark = td.skip_array_manager_not_yet_implemented
-
@pytest.fixture
def pytables_hdf5_file():
diff --git a/pandas/tests/io/pytables/test_complex.py b/pandas/tests/io/pytables/test_complex.py
index 6cfe80ae5c87c..f3a43f669b1d5 100644
--- a/pandas/tests/io/pytables/test_complex.py
+++ b/pandas/tests/io/pytables/test_complex.py
@@ -3,8 +3,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
import pandas as pd
from pandas import (
DataFrame,
@@ -18,9 +16,6 @@
from pandas.io.pytables import read_hdf
-# TODO(ArrayManager) HDFStore relies on accessing the blocks
-pytestmark = td.skip_array_manager_not_yet_implemented
-
def test_complex_fixed(setup_path):
df = DataFrame(
diff --git a/pandas/tests/io/pytables/test_errors.py b/pandas/tests/io/pytables/test_errors.py
index 30b07fb572324..2ae330e5139be 100644
--- a/pandas/tests/io/pytables/test_errors.py
+++ b/pandas/tests/io/pytables/test_errors.py
@@ -6,8 +6,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas import (
CategoricalIndex,
DataFrame,
@@ -27,7 +25,7 @@
_maybe_adjust_name,
)
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
def test_pass_spec_to_storer(setup_path):
diff --git a/pandas/tests/io/pytables/test_file_handling.py b/pandas/tests/io/pytables/test_file_handling.py
index 943b1bb06b1f3..88e2b5f080282 100644
--- a/pandas/tests/io/pytables/test_file_handling.py
+++ b/pandas/tests/io/pytables/test_file_handling.py
@@ -4,7 +4,6 @@
import pytest
from pandas.compat import is_platform_little_endian
-import pandas.util._test_decorators as td
from pandas import (
DataFrame,
@@ -27,7 +26,7 @@
Term,
)
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
def test_mode(setup_path):
diff --git a/pandas/tests/io/pytables/test_keys.py b/pandas/tests/io/pytables/test_keys.py
index 1dc2c9411ed7b..02b79bd0fdbc1 100644
--- a/pandas/tests/io/pytables/test_keys.py
+++ b/pandas/tests/io/pytables/test_keys.py
@@ -1,7 +1,5 @@
import pytest
-import pandas.util._test_decorators as td
-
from pandas import (
DataFrame,
HDFStore,
@@ -13,7 +11,7 @@
tables,
)
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
def test_keys(setup_path):
diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py
index 20278914a4838..4f8c7c84a9fcc 100644
--- a/pandas/tests/io/pytables/test_put.py
+++ b/pandas/tests/io/pytables/test_put.py
@@ -29,7 +29,7 @@
)
from pandas.util import _test_decorators as td
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
def test_format_type(setup_path):
diff --git a/pandas/tests/io/pytables/test_pytables_missing.py b/pandas/tests/io/pytables/test_pytables_missing.py
index fe474b7503e60..9adb0a6d227da 100644
--- a/pandas/tests/io/pytables/test_pytables_missing.py
+++ b/pandas/tests/io/pytables/test_pytables_missing.py
@@ -5,8 +5,6 @@
import pandas as pd
import pandas._testing as tm
-pytestmark = td.skip_array_manager_not_yet_implemented
-
@td.skip_if_installed("tables")
def test_pytables_raises():
diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py
index 5d1deb45eba8b..1c9e63c66aadb 100644
--- a/pandas/tests/io/pytables/test_read.py
+++ b/pandas/tests/io/pytables/test_read.py
@@ -25,7 +25,7 @@
from pandas.io.pytables import TableIterator
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
def test_read_missing_key_close_store(setup_path):
diff --git a/pandas/tests/io/pytables/test_retain_attributes.py b/pandas/tests/io/pytables/test_retain_attributes.py
index c6e2904f7e670..16772d03c6d26 100644
--- a/pandas/tests/io/pytables/test_retain_attributes.py
+++ b/pandas/tests/io/pytables/test_retain_attributes.py
@@ -3,7 +3,6 @@
import pytest
from pandas._libs.tslibs import Timestamp
-import pandas.util._test_decorators as td
from pandas import (
DataFrame,
@@ -18,7 +17,7 @@
ensure_clean_store,
)
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
def test_retain_index_attributes(setup_path):
diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py
index ce075943efe8a..97edc3cdffdf7 100644
--- a/pandas/tests/io/pytables/test_round_trip.py
+++ b/pandas/tests/io/pytables/test_round_trip.py
@@ -30,7 +30,7 @@
_default_compressor = "blosc"
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
def test_conv_read_write(setup_path):
diff --git a/pandas/tests/io/pytables/test_select.py b/pandas/tests/io/pytables/test_select.py
index fc19a3bd63c74..56d48945d5852 100644
--- a/pandas/tests/io/pytables/test_select.py
+++ b/pandas/tests/io/pytables/test_select.py
@@ -4,7 +4,6 @@
import pytest
from pandas._libs.tslibs import Timestamp
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -28,7 +27,7 @@
from pandas.io.pytables import Term
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
def test_select_columns_in_where(setup_path):
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index c61864bbc0a76..856a2ca15ec4a 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -10,8 +10,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
import pandas as pd
from pandas import (
DataFrame,
@@ -42,8 +40,7 @@
read_hdf,
)
-# TODO(ArrayManager) HDFStore relies on accessing the blocks
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
def test_context(setup_path):
diff --git a/pandas/tests/io/pytables/test_subclass.py b/pandas/tests/io/pytables/test_subclass.py
index 05c9f0c650986..75b04f332e054 100644
--- a/pandas/tests/io/pytables/test_subclass.py
+++ b/pandas/tests/io/pytables/test_subclass.py
@@ -1,7 +1,5 @@
import numpy as np
-import pandas.util._test_decorators as td
-
from pandas import (
DataFrame,
Series,
@@ -14,8 +12,6 @@
read_hdf,
)
-pytestmark = td.skip_array_manager_not_yet_implemented
-
class TestHDFStoreSubclass:
# GH 33748
diff --git a/pandas/tests/io/pytables/test_time_series.py b/pandas/tests/io/pytables/test_time_series.py
index 181f63563665b..5e42dbde4b9f1 100644
--- a/pandas/tests/io/pytables/test_time_series.py
+++ b/pandas/tests/io/pytables/test_time_series.py
@@ -3,8 +3,6 @@
import numpy as np
import pytest
-import pandas.util._test_decorators as td
-
from pandas import (
DataFrame,
Series,
@@ -12,7 +10,7 @@
)
from pandas.tests.io.pytables.common import ensure_clean_store
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = pytest.mark.single
def test_store_datetime_fractional_secs(setup_path):
diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py
index 4aa6f94ca38e9..36fa79d0bb7e3 100644
--- a/pandas/tests/io/pytables/test_timezones.py
+++ b/pandas/tests/io/pytables/test_timezones.py
@@ -24,9 +24,6 @@
ensure_clean_store,
)
-# TODO(ArrayManager) HDFStore relies on accessing the blocks
-pytestmark = td.skip_array_manager_not_yet_implemented
-
def _compare_with_tz(a, b):
tm.assert_frame_equal(a, b)
| This doesn't "fix" anything, but by falling back for now to the BlockManager-specific implementation of `to_hdf` writer, this avoids failures when using ArrayManager, which should make it easier to test it. | https://api.github.com/repos/pandas-dev/pandas/pulls/41944 | 2021-06-11T09:03:05Z | 2021-06-11T11:20:52Z | 2021-06-11T11:20:52Z | 2021-06-11T11:52:12Z |
DEPR: positional indexing on Series __getitem__/__setitem__ | diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst
index 34965a2a6d711..7335f1cb066ce 100644
--- a/doc/source/user_guide/basics.rst
+++ b/doc/source/user_guide/basics.rst
@@ -1364,7 +1364,7 @@ We illustrate these fill methods on a simple Series:
rng = pd.date_range("1/3/2000", periods=8)
ts = pd.Series(np.random.randn(8), index=rng)
- ts2 = ts[[0, 3, 6]]
+ ts2 = ts.iloc[[0, 3, 6]]
ts
ts2
diff --git a/doc/source/user_guide/cookbook.rst b/doc/source/user_guide/cookbook.rst
index 36c4604f772a3..c7278c604ca02 100644
--- a/doc/source/user_guide/cookbook.rst
+++ b/doc/source/user_guide/cookbook.rst
@@ -546,7 +546,7 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to
def MyCust(x):
if len(x) > 2:
- return x[1] * 1.234
+ return x.iloc[1] * 1.234
return pd.NaT
mhc = {"Mean": np.mean, "Max": np.max, "Custom": MyCust}
diff --git a/doc/source/user_guide/dsintro.rst b/doc/source/user_guide/dsintro.rst
index 01ec336f7aae5..4b0829e4a23b9 100644
--- a/doc/source/user_guide/dsintro.rst
+++ b/doc/source/user_guide/dsintro.rst
@@ -102,15 +102,15 @@ However, operations such as slicing will also slice the index.
.. ipython:: python
- s[0]
- s[:3]
+ s.iloc[0]
+ s.iloc[:3]
s[s > s.median()]
- s[[4, 3, 1]]
+ s.iloc[[4, 3, 1]]
np.exp(s)
.. note::
- We will address array-based indexing like ``s[[4, 3, 1]]``
+ We will address array-based indexing like ``s.iloc[[4, 3, 1]]``
in :ref:`section on indexing <indexing>`.
Like a NumPy array, a pandas :class:`Series` has a single :attr:`~Series.dtype`.
@@ -201,7 +201,7 @@ labels.
.. ipython:: python
- s[1:] + s[:-1]
+ s.iloc[1:] + s.iloc[:-1]
The result of an operation between unaligned :class:`Series` will have the **union** of
the indexes involved. If a label is not found in one :class:`Series` or the other, the
diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst
index a17d0eba294b2..6ea4c213e85c8 100644
--- a/doc/source/user_guide/missing_data.rst
+++ b/doc/source/user_guide/missing_data.rst
@@ -368,7 +368,7 @@ Index aware interpolation is available via the ``method`` keyword:
.. ipython:: python
:suppress:
- ts2 = ts[[0, 1, 30, 60, 99]]
+ ts2 = ts.iloc[[0, 1, 30, 60, 99]]
.. ipython:: python
@@ -443,7 +443,7 @@ Compare several methods:
ser = pd.Series(np.arange(1, 10.1, 0.25) ** 2 + np.random.randn(37))
missing = np.array([4, 13, 14, 15, 16, 17, 18, 20, 29])
- ser[missing] = np.nan
+ ser.iloc[missing] = np.nan
methods = ["linear", "quadratic", "cubic"]
df = pd.DataFrame({m: ser.interpolate(method=m) for m in methods})
diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst
index 3519ac2d64f71..97be46e338c09 100644
--- a/doc/source/user_guide/timeseries.rst
+++ b/doc/source/user_guide/timeseries.rst
@@ -777,7 +777,7 @@ regularity will result in a ``DatetimeIndex``, although frequency is lost:
.. ipython:: python
- ts2[[0, 2, 6]].index
+ ts2.iloc[[0, 2, 6]].index
.. _timeseries.components:
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index ab14891b40151..f31ab02725394 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -55,7 +55,7 @@ For example:
pi = dti.to_period("D")
ser_monotonic = pd.Series(np.arange(30), index=pi)
shuffler = list(range(0, 30, 2)) + list(range(1, 31, 2))
- ser = ser_monotonic[shuffler]
+ ser = ser_monotonic.iloc[shuffler]
ser
.. ipython:: python
diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index e1ac9e3309de7..e287dc5cda1ce 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -264,7 +264,7 @@ Deprecations
- 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`)
--
+- Deprecated positional indexing on :class:`Series` with :meth:`Series.__getitem__` and :meth:`Series.__setitem__`, in a future version ``ser[item]`` will *always* interpret ``item`` as a label, not a position (:issue:`50617`)
.. ---------------------------------------------------------------------------
.. _whatsnew_210.performance:
diff --git a/pandas/conftest.py b/pandas/conftest.py
index 86f0121dd00a9..90377c53b447b 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -746,7 +746,7 @@ def series_with_multilevel_index() -> Series:
index = MultiIndex.from_tuples(tuples)
data = np.random.randn(8)
ser = Series(data, index=index)
- ser[3] = np.NaN
+ ser.iloc[3] = np.NaN
return ser
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 0c2adb89a2422..503640c23c4ae 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -1437,7 +1437,7 @@ def relabel_result(
com.get_callable_name(f) if not isinstance(f, str) else f for f in fun
]
col_idx_order = Index(s.index).get_indexer(fun)
- s = s[col_idx_order]
+ s = s.iloc[col_idx_order]
# assign the new user-provided "named aggregation" as index names, and reindex
# it based on the whole user-provided names.
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 52bbafffe5340..79e385024aee1 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6528,8 +6528,8 @@ def copy(self, deep: bool_t | None = True) -> Self:
Updates to the data shared by shallow copy and original is reflected
in both; deep copy remains unchanged.
- >>> s[0] = 3
- >>> shallow[1] = 4
+ >>> s.iloc[0] = 3
+ >>> shallow.iloc[1] = 4
>>> s
a 3
b 4
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 8a05a8c5e9af4..38bf6c34bf9c9 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1905,7 +1905,7 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str):
pass
elif self._is_scalar_access(indexer) and is_object_dtype(
- self.obj.dtypes[ilocs[0]]
+ self.obj.dtypes._values[ilocs[0]]
):
# We are setting nested data, only possible for object dtype data
self._setitem_single_column(indexer[1], value, pi)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 569a95aff1de8..bea71808254b8 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -973,6 +973,15 @@ def __getitem__(self, key):
key = unpack_1tuple(key)
if is_integer(key) and self.index._should_fallback_to_positional:
+ warnings.warn(
+ # GH#50617
+ "Series.__getitem__ treating keys as positions is deprecated. "
+ "In a future version, integer keys will always be treated "
+ "as labels (consistent with DataFrame behavior). To access "
+ "a value by position, use `ser.iloc[pos]`",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return self._values[key]
elif key_is_scalar:
@@ -1035,6 +1044,15 @@ def _get_with(self, key):
if not self.index._should_fallback_to_positional:
return self.loc[key]
else:
+ warnings.warn(
+ # GH#50617
+ "Series.__getitem__ treating keys as positions is deprecated. "
+ "In a future version, integer keys will always be treated "
+ "as labels (consistent with DataFrame behavior). To access "
+ "a value by position, use `ser.iloc[pos]`",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
return self.iloc[key]
# handle the dup indexing case GH#4246
@@ -1136,6 +1154,15 @@ def __setitem__(self, key, value) -> None:
# positional setter
# can't use _mgr.setitem_inplace yet bc could have *both*
# KeyError and then ValueError, xref GH#45070
+ warnings.warn(
+ # GH#50617
+ "Series.__setitem__ treating keys as positions is deprecated. "
+ "In a future version, integer keys will always be treated "
+ "as labels (consistent with DataFrame behavior). To set "
+ "a value by position, use `ser.iloc[pos] = value`",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
self._set_values(key, value)
else:
# GH#12862 adding a new key to the Series
@@ -1211,6 +1238,15 @@ def _set_with(self, key, value) -> None:
key_type = lib.infer_dtype(key, skipna=False)
if key_type == "integer":
+ warnings.warn(
+ # GH#50617
+ "Series.__setitem__ treating keys as positions is deprecated. "
+ "In a future version, integer keys will always be treated "
+ "as labels (consistent with DataFrame behavior). To set "
+ "a value by position, use `ser.iloc[pos] = value`",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
self._set_values(key, value)
else:
self._set_labels(key, value)
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index fbadda0a4128f..d62830ffe3ea1 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -2637,7 +2637,7 @@ def _prepare_pandas(self, data: DataFrame) -> None:
)
for key in self._convert_dates:
new_type = _convert_datetime_to_stata_type(self._convert_dates[key])
- dtypes[key] = np.dtype(new_type)
+ dtypes.iloc[key] = np.dtype(new_type)
# Verify object arrays are strings and encode to bytes
self._encode_strings()
diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py
index 5a2574e62b41e..80292ac6641ac 100644
--- a/pandas/tests/apply/test_frame_apply.py
+++ b/pandas/tests/apply/test_frame_apply.py
@@ -1385,7 +1385,7 @@ def sum_div2(s):
def test_apply_getitem_axis_1():
# GH 13427
df = DataFrame({"a": [0, 1, 2], "b": [1, 2, 3]})
- result = df[["a", "a"]].apply(lambda x: x[0] + x[1], axis=1)
+ result = df[["a", "a"]].apply(lambda x: x.iloc[0] + x.iloc[1], axis=1)
expected = Series([0, 2, 4])
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py
index 8e211c60ee654..f9b4ba295f3a0 100644
--- a/pandas/tests/copy_view/test_indexing.py
+++ b/pandas/tests/copy_view/test_indexing.py
@@ -802,7 +802,17 @@ def test_series_subset_set_with_indexer(
s_orig = s.copy()
subset = s[:]
- indexer_si(subset)[indexer] = 0
+ warn = None
+ msg = "Series.__setitem__ treating keys as positions is deprecated"
+ if (
+ indexer_si is tm.setitem
+ and isinstance(indexer, np.ndarray)
+ and indexer.dtype.kind == "i"
+ ):
+ warn = FutureWarning
+
+ with tm.assert_produces_warning(warn, match=msg):
+ indexer_si(subset)[indexer] = 0
expected = Series([0, 0, 3], index=["a", "b", "c"])
tm.assert_series_equal(subset, expected)
diff --git a/pandas/tests/copy_view/test_interp_fillna.py b/pandas/tests/copy_view/test_interp_fillna.py
index 91c6b96767142..576d3a9cdedde 100644
--- a/pandas/tests/copy_view/test_interp_fillna.py
+++ b/pandas/tests/copy_view/test_interp_fillna.py
@@ -287,7 +287,7 @@ def test_fillna_ea_noop_shares_memory(
if using_copy_on_write:
assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
assert not df2._mgr._has_no_reference(1)
- elif isinstance(df.dtypes[0], ArrowDtype):
+ elif isinstance(df.dtypes.iloc[0], ArrowDtype):
# arrow is immutable, so no-ops do not need to copy underlying array
assert np.shares_memory(get_array(df, "b"), get_array(df2, "b"))
else:
@@ -317,7 +317,7 @@ def test_fillna_inplace_ea_noop_shares_memory(
assert np.shares_memory(get_array(df, "b"), get_array(view, "b"))
assert not df._mgr._has_no_reference(1)
assert not view._mgr._has_no_reference(1)
- elif isinstance(df.dtypes[0], ArrowDtype):
+ elif isinstance(df.dtypes.iloc[0], ArrowDtype):
# arrow is immutable, so no-ops do not need to copy underlying array
assert np.shares_memory(get_array(df, "b"), get_array(view, "b"))
else:
diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py
index 890dc0a1a43a3..2736d134950bc 100644
--- a/pandas/tests/extension/base/getitem.py
+++ b/pandas/tests/extension/base/getitem.py
@@ -330,9 +330,11 @@ def test_get(self, data):
result = s.get("Z")
assert result is None
- assert s.get(4) == s.iloc[4]
- assert s.get(-1) == s.iloc[-1]
- assert s.get(len(s)) is None
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert s.get(4) == s.iloc[4]
+ assert s.get(-1) == s.iloc[-1]
+ assert s.get(len(s)) is None
# GH 21257
s = pd.Series(data)
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index 224abbcef27df..6ac1faad060ef 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -454,7 +454,7 @@ def test_setitem_corner(self, float_frame):
# set existing column
dm["A"] = "bar"
- assert "bar" == dm["A"][0]
+ assert "bar" == dm["A"].iloc[0]
dm = DataFrame(index=np.arange(3))
dm["A"] = 1
diff --git a/pandas/tests/frame/methods/test_map.py b/pandas/tests/frame/methods/test_map.py
index 53cae2d079217..7ef51ebc4b6a3 100644
--- a/pandas/tests/frame/methods/test_map.py
+++ b/pandas/tests/frame/methods/test_map.py
@@ -19,7 +19,7 @@ def test_map(float_frame):
float_frame.map(type)
# GH 465: function returning tuples
- result = float_frame.map(lambda x: (x, x))["A"][0]
+ result = float_frame.map(lambda x: (x, x))["A"].iloc[0]
assert isinstance(result, tuple)
diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py
index ad89ccd6e3c60..1619b79f64514 100644
--- a/pandas/tests/frame/methods/test_replace.py
+++ b/pandas/tests/frame/methods/test_replace.py
@@ -614,8 +614,8 @@ def test_replace_mixed3(self):
result = df.replace(3, df.mean().to_dict())
expected = df.copy().astype("float64")
m = df.mean()
- expected.iloc[0, 0] = m[0]
- expected.iloc[1, 1] = m[1]
+ expected.iloc[0, 0] = m.iloc[0]
+ expected.iloc[1, 1] = m.iloc[1]
tm.assert_frame_equal(result, expected)
def test_replace_nullable_int_with_string_doesnt_cast(self):
@@ -1072,7 +1072,7 @@ def test_replace_period(self):
assert set(df.fname.values) == set(d["fname"].keys())
expected = DataFrame({"fname": [d["fname"][k] for k in df.fname.values]})
- assert expected.dtypes[0] == "Period[M]"
+ assert expected.dtypes.iloc[0] == "Period[M]"
result = df.replace(d)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_values.py b/pandas/tests/frame/methods/test_values.py
index 5728a849262ee..8c2253820db31 100644
--- a/pandas/tests/frame/methods/test_values.py
+++ b/pandas/tests/frame/methods/test_values.py
@@ -38,9 +38,9 @@ def test_values_mixed_dtypes(self, float_frame, float_string_frame):
for j, value in enumerate(row):
col = frame_cols[j]
if np.isnan(value):
- assert np.isnan(frame[col][i])
+ assert np.isnan(frame[col].iloc[i])
else:
- assert value == frame[col][i]
+ assert value == frame[col].iloc[i]
# mixed type
arr = float_string_frame[["foo", "A"]].values
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py
index 096f6fe83ea88..dd8a71f6c10b1 100644
--- a/pandas/tests/frame/test_reductions.py
+++ b/pandas/tests/frame/test_reductions.py
@@ -611,16 +611,16 @@ def test_operators_timedelta64(self):
# min
result = diffs.min()
- assert result[0] == diffs.loc[0, "A"]
- assert result[1] == diffs.loc[0, "B"]
+ assert result.iloc[0] == diffs.loc[0, "A"]
+ assert result.iloc[1] == diffs.loc[0, "B"]
result = diffs.min(axis=1)
assert (result == diffs.loc[0, "B"]).all()
# max
result = diffs.max()
- assert result[0] == diffs.loc[2, "A"]
- assert result[1] == diffs.loc[2, "B"]
+ assert result.iloc[0] == diffs.loc[2, "A"]
+ assert result.iloc[1] == diffs.loc[2, "B"]
result = diffs.max(axis=1)
assert (result == diffs["A"]).all()
diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index 889c44522f7bb..bca4675e6b3e0 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -1075,7 +1075,7 @@ def test_stack_full_multiIndex(self):
),
columns=Index(["B", "C"], name="Upper"),
)
- expected["B"] = expected["B"].astype(df.dtypes[0])
+ expected["B"] = expected["B"].astype(df.dtypes.iloc[0])
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("ordered", [False, True])
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 7bda7c575d994..3236b165e9444 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -1344,11 +1344,11 @@ def convert_force_pure(x):
result = grouped.agg(convert_fast)
assert result.dtype == np.object_
- assert isinstance(result[0], Decimal)
+ assert isinstance(result.iloc[0], Decimal)
result = grouped.agg(convert_force_pure)
assert result.dtype == np.object_
- assert isinstance(result[0], Decimal)
+ assert isinstance(result.iloc[0], Decimal)
def test_groupby_dtype_inference_empty():
@@ -1967,8 +1967,8 @@ def get_categorical_invalid_expected():
expected = DataFrame([], columns=[], index=idx)
return expected
- is_per = isinstance(df.dtypes[0], pd.PeriodDtype)
- is_dt64 = df.dtypes[0].kind == "M"
+ is_per = isinstance(df.dtypes.iloc[0], pd.PeriodDtype)
+ is_dt64 = df.dtypes.iloc[0].kind == "M"
is_cat = isinstance(values, Categorical)
if isinstance(values, Categorical) and not values.ordered and op in ["min", "max"]:
diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py
index f13dfcd5c20bd..139190962895d 100644
--- a/pandas/tests/indexes/datetimes/test_misc.py
+++ b/pandas/tests/indexes/datetimes/test_misc.py
@@ -50,8 +50,8 @@ def test_datetimeindex_accessors(self):
assert dti.dayofyear[0] == 1
assert dti.dayofyear[120] == 121
- assert dti.isocalendar().week[0] == 1
- assert dti.isocalendar().week[120] == 18
+ assert dti.isocalendar().week.iloc[0] == 1
+ assert dti.isocalendar().week.iloc[120] == 18
assert dti.quarter[0] == 1
assert dti.quarter[120] == 2
diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py
index f030f4101512e..28c9c07a9c9ef 100644
--- a/pandas/tests/indexes/datetimes/test_partial_slicing.py
+++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py
@@ -379,7 +379,7 @@ def test_partial_slice_requires_monotonicity(self):
# Disallowed since 2.0 (GH 37819)
ser = Series(np.arange(10), date_range("2014-01-01", periods=10))
- nonmonotonic = ser[[3, 5, 4]]
+ nonmonotonic = ser.iloc[[3, 5, 4]]
timestamp = Timestamp("2014-01-10")
with pytest.raises(
KeyError, match="Value based partial slicing on non-monotonic"
diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py
index 1f704cfa064d8..bf81d2cde98e7 100644
--- a/pandas/tests/indexes/period/test_partial_slicing.py
+++ b/pandas/tests/indexes/period/test_partial_slicing.py
@@ -39,7 +39,7 @@ def test_getitem_periodindex_quarter_string(self):
pi = PeriodIndex(["2Q05", "3Q05", "4Q05", "1Q06", "2Q06"], freq="Q")
ser = Series(np.random.rand(len(pi)), index=pi).cumsum()
# Todo: fix these accessors!
- assert ser["05Q4"] == ser[2]
+ assert ser["05Q4"] == ser.iloc[2]
def test_pindex_slice_index(self):
pi = period_range(start="1/1/10", end="12/31/12", freq="M")
@@ -160,7 +160,7 @@ def test_partial_slice_doesnt_require_monotonicity(self):
ser_montonic = Series(np.arange(30), index=pi)
shuffler = list(range(0, 30, 2)) + list(range(1, 31, 2))
- ser = ser_montonic[shuffler]
+ ser = ser_montonic.iloc[shuffler]
nidx = ser.index
# Manually identified locations of year==2014
@@ -173,7 +173,7 @@ def test_partial_slice_doesnt_require_monotonicity(self):
result = nidx.get_loc("2014")
tm.assert_numpy_array_equal(result, indexer_2014)
- expected = ser[indexer_2014]
+ expected = ser.iloc[indexer_2014]
result = ser.loc["2014"]
tm.assert_series_equal(result, expected)
@@ -187,7 +187,7 @@ def test_partial_slice_doesnt_require_monotonicity(self):
result = nidx.get_loc("May 2015")
tm.assert_numpy_array_equal(result, indexer_may2015)
- expected = ser[indexer_may2015]
+ expected = ser.iloc[indexer_may2015]
result = ser.loc["May 2015"]
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py
index 86d6246437ea1..2c39729097487 100644
--- a/pandas/tests/indexing/test_coercion.py
+++ b/pandas/tests/indexing/test_coercion.py
@@ -116,9 +116,11 @@ def test_setitem_index_object(self, val, exp_dtype):
if exp_dtype is IndexError:
temp = obj.copy()
+ warn_msg = "Series.__setitem__ treating keys as positions is deprecated"
msg = "index 5 is out of bounds for axis 0 with size 4"
with pytest.raises(exp_dtype, match=msg):
- temp[5] = 5
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ temp[5] = 5
else:
exp_index = pd.Index(list("abcd") + [val])
self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py
index 3b622d7b4703a..0bcc2aa75d78a 100644
--- a/pandas/tests/indexing/test_floats.py
+++ b/pandas/tests/indexing/test_floats.py
@@ -86,7 +86,10 @@ def test_scalar_non_numeric_series_fallback(self, index_func):
# fallsback to position selection, series only
i = index_func(5)
s = Series(np.arange(len(i)), index=i)
- s[3]
+
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ s[3]
with pytest.raises(KeyError, match="^3.0$"):
s[3.0]
@@ -113,7 +116,9 @@ def test_scalar_with_mixed(self, indexer_sl):
if indexer_sl is not tm.loc:
# __getitem__ falls back to positional
- result = s3[1]
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = s3[1]
expected = 2
assert result == expected
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index bfa9a6497b3d5..3dec187a54439 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -775,7 +775,8 @@ def test_iloc_mask(self):
for idx in [None, "index", "locs"]:
mask = (df.nums > 2).values
if idx:
- mask = Series(mask, list(reversed(getattr(df, idx))))
+ mask_index = getattr(df, idx)[::-1]
+ mask = Series(mask, list(mask_index))
for method in ["", ".loc", ".iloc"]:
try:
if method:
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index b4cb7abbd418f..21036598f46df 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -71,6 +71,10 @@ def test_setitem_ndarray_1d_2(self):
with pytest.raises(ValueError, match=msg):
df[2:5] = np.arange(1, 4) * 1j
+ @pytest.mark.filterwarnings(
+ "ignore:Series.__getitem__ treating keys as positions is deprecated:"
+ "FutureWarning"
+ )
def test_getitem_ndarray_3d(
self, index, frame_or_series, indexer_sli, using_array_manager
):
@@ -113,6 +117,10 @@ def test_getitem_ndarray_3d(
with pytest.raises(potential_errors, match=msg):
idxr[nd3]
+ @pytest.mark.filterwarnings(
+ "ignore:Series.__setitem__ treating keys as positions is deprecated:"
+ "FutureWarning"
+ )
def test_setitem_ndarray_3d(self, index, frame_or_series, indexer_sli):
# GH 25567
obj = gen_obj(frame_or_series, index)
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index 3aab884f06131..19421345087fc 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -3026,7 +3026,7 @@ def test_loc_getitem(self, string_series, datetime_series):
def test_loc_getitem_not_monotonic(self, datetime_series):
d1, d2 = datetime_series.index[[5, 15]]
- ts2 = datetime_series[::2][[1, 2, 0]]
+ ts2 = datetime_series[::2].iloc[[1, 2, 0]]
msg = r"Timestamp\('2000-01-10 00:00:00'\)"
with pytest.raises(KeyError, match=msg):
@@ -3184,7 +3184,7 @@ def test_loc_setitem(self, string_series):
result.loc[inds] = 5
expected = string_series.copy()
- expected[[3, 4, 7]] = 5
+ expected.iloc[[3, 4, 7]] = 5
tm.assert_series_equal(result, expected)
result.iloc[5:10] = 10
diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py
index 163951a6ebc45..2461f937c9eff 100644
--- a/pandas/tests/io/pytables/test_round_trip.py
+++ b/pandas/tests/io/pytables/test_round_trip.py
@@ -217,7 +217,7 @@ def test_table_values_dtypes_roundtrip(setup_path):
df1 = DataFrame(np.array([[1], [2], [3]], dtype="f4"), columns=["A"])
store.append("df_f4", df1)
tm.assert_series_equal(df1.dtypes, store["df_f4"].dtypes)
- assert df1.dtypes[0] == "float32"
+ assert df1.dtypes.iloc[0] == "float32"
# check with mixed dtypes
df1 = DataFrame(
diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py
index b5e040e05e8f7..ff81d0125144e 100644
--- a/pandas/tests/io/test_clipboard.py
+++ b/pandas/tests/io/test_clipboard.py
@@ -316,7 +316,7 @@ def test_read_clipboard_infer_excel(self, request, mock_clipboard):
df = read_clipboard(**clip_kwargs)
# excel data is parsed correctly
- assert df.iloc[1][1] == "Harry Carney"
+ assert df.iloc[1, 1] == "Harry Carney"
# having diff tab counts doesn't trigger it
text = dedent(
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 77e7e6f8d6c41..a864903d9c6d1 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -262,7 +262,7 @@ def create_and_load_types(conn, types_data: list[dict], dialect: str):
def check_iris_frame(frame: DataFrame):
- pytype = frame.dtypes[0].type
+ pytype = frame.dtypes.iloc[0].type
row = frame.iloc[0]
assert issubclass(pytype, np.floating)
tm.equalContents(row.values, [5.1, 3.5, 1.4, 0.2, "Iris-setosa"])
diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py
index 753f0341af7fc..1b0a1d740677b 100644
--- a/pandas/tests/io/test_stata.py
+++ b/pandas/tests/io/test_stata.py
@@ -2091,7 +2091,7 @@ def test_iterator_value_labels():
with read_stata(path, chunksize=100) as reader:
for j, chunk in enumerate(reader):
for i in range(2):
- tm.assert_index_equal(chunk.dtypes[i].categories, expected)
+ tm.assert_index_equal(chunk.dtypes.iloc[i].categories, expected)
tm.assert_frame_equal(chunk, df.iloc[j * 100 : (j + 1) * 100])
diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py
index 8fc4170a8562c..dacc0cbea7c9e 100644
--- a/pandas/tests/plotting/test_datetimelike.py
+++ b/pandas/tests/plotting/test_datetimelike.py
@@ -235,7 +235,7 @@ def test_line_plot_inferred_freq(self, freq):
ser = Series(ser.values, Index(np.asarray(ser.index)))
_check_plot_works(ser.plot, ser.index.inferred_freq)
- ser = ser[[0, 3, 5, 6]]
+ ser = ser.iloc[[0, 3, 5, 6]]
_check_plot_works(ser.plot)
def test_fake_inferred_business(self):
@@ -299,7 +299,7 @@ def test_irreg_hf(self):
def test_irregular_datetime64_repr_bug(self):
ser = tm.makeTimeSeries()
- ser = ser[[0, 1, 2, 7]]
+ ser = ser.iloc[[0, 1, 2, 7]]
_, ax = self.plt.subplots()
@@ -539,7 +539,7 @@ def test_gaps(self):
# irregular
ts = tm.makeTimeSeries()
- ts = ts[[0, 1, 2, 5, 7, 9, 12, 15, 20]]
+ ts = ts.iloc[[0, 1, 2, 5, 7, 9, 12, 15, 20]]
ts.iloc[2:5] = np.nan
_, ax = self.plt.subplots()
ax = ts.plot(ax=ax)
@@ -679,7 +679,7 @@ def test_secondary_bar_frame(self):
def test_mixed_freq_regular_first(self):
# TODO
s1 = tm.makeTimeSeries()
- s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]]
+ s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15]]
# it works!
_, ax = self.plt.subplots()
@@ -700,7 +700,7 @@ def test_mixed_freq_regular_first(self):
def test_mixed_freq_irregular_first(self):
s1 = tm.makeTimeSeries()
- s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]]
+ s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15]]
_, ax = self.plt.subplots()
s2.plot(style="g", ax=ax)
s1.plot(ax=ax)
@@ -792,7 +792,7 @@ def test_mixed_freq_lf_first(self):
def test_mixed_freq_irreg_period(self):
ts = tm.makeTimeSeries()
- irreg = ts[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]]
+ irreg = ts.iloc[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]]
rng = period_range("1/3/2000", periods=30, freq="B")
ps = Series(np.random.randn(len(rng)), rng)
_, ax = self.plt.subplots()
@@ -1246,7 +1246,7 @@ def test_irregular_ts_shared_ax_xlim(self):
from pandas.plotting._matplotlib.converter import DatetimeConverter
ts = tm.makeTimeSeries()[:20]
- ts_irregular = ts[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]]
+ ts_irregular = ts.iloc[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]]
# plot the left section of the irregular series, then the right section
_, ax = self.plt.subplots()
@@ -1310,7 +1310,7 @@ def test_secondary_y_irregular_ts_xlim(self):
from pandas.plotting._matplotlib.converter import DatetimeConverter
ts = tm.makeTimeSeries()[:20]
- ts_irregular = ts[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]]
+ ts_irregular = ts.iloc[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]]
_, ax = self.plt.subplots()
ts_irregular[:5].plot(ax=ax)
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index cbf530e995c43..389db2d36474d 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -111,7 +111,7 @@ def test_custom_grouper_df(index, unit):
(
"right",
lambda s: Series(
- [s[0], s[1:6].mean(), s[6:11].mean(), s[11:].mean()],
+ [s.iloc[0], s[1:6].mean(), s[6:11].mean(), s[11:].mean()],
index=date_range("1/1/2000", periods=4, freq="5min", name="index"),
),
),
@@ -164,7 +164,7 @@ def test_resample_basic_grouper(series, unit):
s.index = s.index.as_unit(unit)
result = s.resample("5Min").last()
grouper = Grouper(freq=Minute(5), closed="left", label="left")
- expected = s.groupby(grouper).agg(lambda x: x[-1])
+ expected = s.groupby(grouper).agg(lambda x: x.iloc[-1])
tm.assert_series_equal(result, expected)
@@ -227,7 +227,7 @@ def test_resample_how_ohlc(series, unit):
def _ohlc(group):
if isna(group).all():
return np.repeat(np.nan, 4)
- return [group[0], group.max(), group.min(), group[-1]]
+ return [group.iloc[0], group.max(), group.min(), group.iloc[-1]]
expected = DataFrame(
s.groupby(grouplist).agg(_ohlc).values.tolist(),
@@ -460,8 +460,8 @@ def test_resample_upsample(unit):
# to minutely, by padding
result = s.resample("Min").ffill()
assert len(result) == 12961
- assert result[0] == s[0]
- assert result[-1] == s[-1]
+ assert result.iloc[0] == s.iloc[0]
+ assert result.iloc[-1] == s.iloc[-1]
assert result.index.name == "index"
@@ -534,23 +534,23 @@ def test_resample_ohlc(series, unit):
s.index = s.index.as_unit(unit)
grouper = Grouper(freq=Minute(5))
- expect = s.groupby(grouper).agg(lambda x: x[-1])
+ expect = s.groupby(grouper).agg(lambda x: x.iloc[-1])
result = s.resample("5Min").ohlc()
assert len(result) == len(expect)
assert len(result.columns) == 4
xs = result.iloc[-2]
- assert xs["open"] == s[-6]
+ assert xs["open"] == s.iloc[-6]
assert xs["high"] == s[-6:-1].max()
assert xs["low"] == s[-6:-1].min()
- assert xs["close"] == s[-2]
+ assert xs["close"] == s.iloc[-2]
xs = result.iloc[0]
- assert xs["open"] == s[0]
+ assert xs["open"] == s.iloc[0]
assert xs["high"] == s[:5].max()
assert xs["low"] == s[:5].min()
- assert xs["close"] == s[4]
+ assert xs["close"] == s.iloc[4]
def test_resample_ohlc_result(unit):
@@ -688,14 +688,14 @@ def test_ohlc_5min(unit):
def _ohlc(group):
if isna(group).all():
return np.repeat(np.nan, 4)
- return [group[0], group.max(), group.min(), group[-1]]
+ return [group.iloc[0], group.max(), group.min(), group.iloc[-1]]
rng = date_range("1/1/2000 00:00:00", "1/1/2000 5:59:50", freq="10s").as_unit(unit)
ts = Series(np.random.randn(len(rng)), index=rng)
resampled = ts.resample("5min", closed="right", label="right").ohlc()
- assert (resampled.loc["1/1/2000 00:00"] == ts[0]).all()
+ assert (resampled.loc["1/1/2000 00:00"] == ts.iloc[0]).all()
exp = _ohlc(ts[1:31])
assert (resampled.loc["1/1/2000 00:05"] == exp).all()
@@ -713,8 +713,8 @@ def test_downsample_non_unique(unit):
expected = ts.groupby(lambda x: x.month).mean()
assert len(result) == 2
- tm.assert_almost_equal(result[0], expected[1])
- tm.assert_almost_equal(result[1], expected[2])
+ tm.assert_almost_equal(result.iloc[0], expected[1])
+ tm.assert_almost_equal(result.iloc[1], expected[2])
def test_asfreq_non_unique(unit):
@@ -1318,7 +1318,7 @@ def test_resample_consistency(unit):
i30 = date_range("2002-02-02", periods=4, freq="30T").as_unit(unit)
s = Series(np.arange(4.0), index=i30)
- s[2] = np.NaN
+ s.iloc[2] = np.NaN
# Upsample by factor 3 with reindex() and resample() methods:
i10 = date_range(i30[0], i30[-1], freq="10T").as_unit(unit)
diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py
index 17277b0c74568..9c3ccd96a8d59 100644
--- a/pandas/tests/resample/test_period_index.py
+++ b/pandas/tests/resample/test_period_index.py
@@ -535,7 +535,7 @@ def test_closed_left_corner(self):
np.random.randn(21),
index=date_range(start="1/1/2012 9:30", freq="1min", periods=21),
)
- s[0] = np.nan
+ s.iloc[0] = np.nan
result = s.resample("10min", closed="left", label="right").mean()
exp = s[1:].resample("10min", closed="left", label="right").mean()
@@ -657,7 +657,7 @@ def test_all_values_single_bin(self):
s = Series(np.random.randn(len(index)), index=index)
result = s.resample("A").mean()
- tm.assert_almost_equal(result[0], s.mean())
+ tm.assert_almost_equal(result.iloc[0], s.mean())
def test_evenly_divisible_with_no_extra_bins(self):
# 4076
diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py
index 8b6e757c0a46a..79e024ef84c90 100644
--- a/pandas/tests/resample/test_timedelta.py
+++ b/pandas/tests/resample/test_timedelta.py
@@ -147,7 +147,7 @@ def test_resample_timedelta_edge_case(start, end, freq, resample_freq):
expected_index = timedelta_range(freq=resample_freq, start=start, end=end)
tm.assert_index_equal(result.index, expected_index)
assert result.index.freq == expected_index.freq
- assert not np.isnan(result[-1])
+ assert not np.isnan(result.iloc[-1])
@pytest.mark.parametrize("duplicates", [True, False])
diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py
index 330d0f6a89c71..5a715fcda97f8 100644
--- a/pandas/tests/series/accessors/test_dt_accessor.py
+++ b/pandas/tests/series/accessors/test_dt_accessor.py
@@ -243,7 +243,7 @@ def test_dt_namespace_accessor_index_and_values(self):
exp = Series(np.array([0, 1, 2], dtype="int32"), index=index, name="xxx")
tm.assert_series_equal(ser.dt.second, exp)
- exp = Series([ser[0]] * 3, index=index, name="xxx")
+ exp = Series([ser.iloc[0]] * 3, index=index, name="xxx")
tm.assert_series_equal(ser.dt.normalize(), exp)
def test_dt_accessor_limited_display_api(self):
diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py
index 64da669343147..f47e344336a8b 100644
--- a/pandas/tests/series/indexing/test_datetime.py
+++ b/pandas/tests/series/indexing/test_datetime.py
@@ -35,7 +35,9 @@ def test_fancy_getitem():
s = Series(np.arange(len(dti)), index=dti)
- assert s[48] == 48
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert s[48] == 48
assert s["1/2/2009"] == 48
assert s["2009-1-2"] == 48
assert s[datetime(2009, 1, 2)] == 48
@@ -53,10 +55,13 @@ def test_fancy_setitem():
)
s = Series(np.arange(len(dti)), index=dti)
- s[48] = -1
- assert s[48] == -1
+
+ msg = "Series.__setitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ s[48] = -1
+ assert s.iloc[48] == -1
s["1/2/2009"] = -2
- assert s[48] == -2
+ assert s.iloc[48] == -2
s["1/2/2009":"2009-06-05"] = -3
assert (s[48:54] == -3).all()
@@ -77,25 +82,25 @@ def test_getitem_setitem_datetime_tz(tz_source):
# also test Timestamp tz handling, GH #2789
result = ts.copy()
result["1990-01-01 09:00:00+00:00"] = 0
- result["1990-01-01 09:00:00+00:00"] = ts[4]
+ result["1990-01-01 09:00:00+00:00"] = ts.iloc[4]
tm.assert_series_equal(result, ts)
result = ts.copy()
result["1990-01-01 03:00:00-06:00"] = 0
- result["1990-01-01 03:00:00-06:00"] = ts[4]
+ result["1990-01-01 03:00:00-06:00"] = ts.iloc[4]
tm.assert_series_equal(result, ts)
# repeat with datetimes
result = ts.copy()
result[datetime(1990, 1, 1, 9, tzinfo=tzget("UTC"))] = 0
- result[datetime(1990, 1, 1, 9, tzinfo=tzget("UTC"))] = ts[4]
+ result[datetime(1990, 1, 1, 9, tzinfo=tzget("UTC"))] = ts.iloc[4]
tm.assert_series_equal(result, ts)
result = ts.copy()
dt = Timestamp(1990, 1, 1, 3).tz_localize(tzget("US/Central"))
dt = dt.to_pydatetime()
result[dt] = 0
- result[dt] = ts[4]
+ result[dt] = ts.iloc[4]
tm.assert_series_equal(result, ts)
@@ -106,12 +111,12 @@ def test_getitem_setitem_datetimeindex():
ts = Series(np.random.randn(N), index=rng)
result = ts["1990-01-01 04:00:00"]
- expected = ts[4]
+ expected = ts.iloc[4]
assert result == expected
result = ts.copy()
result["1990-01-01 04:00:00"] = 0
- result["1990-01-01 04:00:00"] = ts[4]
+ result["1990-01-01 04:00:00"] = ts.iloc[4]
tm.assert_series_equal(result, ts)
result = ts["1990-01-01 04:00:00":"1990-01-01 07:00:00"]
@@ -148,7 +153,7 @@ def test_getitem_setitem_datetimeindex():
# GH#36148 as of 2.0 we do not ignore tzawareness mismatch in indexing,
# so setting it as a new key casts to object rather than matching
# rng[4]
- result[naive] = ts[4]
+ result[naive] = ts.iloc[4]
assert result.index.dtype == object
tm.assert_index_equal(result.index[:-1], rng.astype(object))
assert result.index[-1] == naive
@@ -183,7 +188,7 @@ def test_getitem_setitem_datetimeindex():
tm.assert_series_equal(result, expected)
result = ts[ts.index[4]]
- expected = ts[4]
+ expected = ts.iloc[4]
assert result == expected
result = ts[ts.index[4:8]]
@@ -212,12 +217,12 @@ def test_getitem_setitem_periodindex():
ts = Series(np.random.randn(N), index=rng)
result = ts["1990-01-01 04"]
- expected = ts[4]
+ expected = ts.iloc[4]
assert result == expected
result = ts.copy()
result["1990-01-01 04"] = 0
- result["1990-01-01 04"] = ts[4]
+ result["1990-01-01 04"] = ts.iloc[4]
tm.assert_series_equal(result, ts)
result = ts["1990-01-01 04":"1990-01-01 07"]
@@ -237,7 +242,7 @@ def test_getitem_setitem_periodindex():
# GH 2782
result = ts[ts.index[4]]
- expected = ts[4]
+ expected = ts.iloc[4]
assert result == expected
result = ts[ts.index[4:8]]
@@ -290,7 +295,7 @@ def test_indexing_with_duplicate_datetimeindex(
if total > 1:
tm.assert_series_equal(result, expected)
else:
- tm.assert_almost_equal(result, expected[0])
+ tm.assert_almost_equal(result, expected.iloc[0])
cp = ts.copy()
cp[date] = 0
diff --git a/pandas/tests/series/indexing/test_get.py b/pandas/tests/series/indexing/test_get.py
index b78f545b2a010..e64a91d9ca581 100644
--- a/pandas/tests/series/indexing/test_get.py
+++ b/pandas/tests/series/indexing/test_get.py
@@ -144,7 +144,6 @@ def test_get_with_default():
# GH#7725
d0 = ["a", "b", "c", "d"]
d1 = np.arange(4, dtype="int64")
- others = ["e", 10]
for data, index in ((d0, d1), (d1, d0)):
s = Series(data, index=index)
@@ -152,9 +151,17 @@ def test_get_with_default():
assert s.get(i) == d
assert s.get(i, d) == d
assert s.get(i, "z") == d
- for other in others:
- assert s.get(other, "z") == "z"
- assert s.get(other, other) == other
+
+ assert s.get("e", "z") == "z"
+ assert s.get("e", "e") == "e"
+
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ warn = None
+ if index is d0:
+ warn = FutureWarning
+ with tm.assert_produces_warning(warn, match=msg):
+ assert s.get(10, "z") == "z"
+ assert s.get(10, 10) == 10
@pytest.mark.parametrize(
@@ -187,9 +194,13 @@ def test_get_with_ea(arr):
result = ser.get("Z")
assert result is None
- assert ser.get(4) == ser.iloc[4]
- assert ser.get(-1) == ser.iloc[-1]
- assert ser.get(len(ser)) is None
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert ser.get(4) == ser.iloc[4]
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert ser.get(-1) == ser.iloc[-1]
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert ser.get(len(ser)) is None
# GH#21257
ser = Series(arr)
@@ -198,14 +209,17 @@ def test_get_with_ea(arr):
def test_getitem_get(string_series, object_series):
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+
for obj in [string_series, object_series]:
idx = obj.index[5]
assert obj[idx] == obj.get(idx)
- assert obj[idx] == obj[5]
+ assert obj[idx] == obj.iloc[5]
- assert string_series.get(-1) == string_series.get(string_series.index[-1])
- assert string_series[5] == string_series.get(string_series.index[5])
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert string_series.get(-1) == string_series.get(string_series.index[-1])
+ assert string_series.iloc[5] == string_series.get(string_series.index[5])
def test_get_none():
diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py
index 0f044ae576af8..8bfa59c5d9f08 100644
--- a/pandas/tests/series/indexing/test_getitem.py
+++ b/pandas/tests/series/indexing/test_getitem.py
@@ -72,14 +72,18 @@ def test_getitem_negative_out_of_bounds(self):
ser = Series(tm.rands_array(5, 10), index=tm.rands_array(10, 10))
msg = "index -11 is out of bounds for axis 0 with size 10"
+ warn_msg = "Series.__getitem__ treating keys as positions is deprecated"
with pytest.raises(IndexError, match=msg):
- ser[-11]
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ ser[-11]
def test_getitem_out_of_bounds_indexerror(self, datetime_series):
# don't segfault, GH#495
msg = r"index \d+ is out of bounds for axis 0 with size \d+"
+ warn_msg = "Series.__getitem__ treating keys as positions is deprecated"
with pytest.raises(IndexError, match=msg):
- datetime_series[len(datetime_series)]
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ datetime_series[len(datetime_series)]
def test_getitem_out_of_bounds_empty_rangeindex_keyerror(self):
# GH#917
@@ -109,7 +113,10 @@ def test_getitem_keyerror_with_integer_index(self, any_int_numpy_dtype):
def test_getitem_int64(self, datetime_series):
idx = np.int64(5)
- assert datetime_series[idx] == datetime_series[5]
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = datetime_series[idx]
+ assert res == datetime_series.iloc[5]
def test_getitem_full_range(self):
# github.com/pandas-dev/pandas/commit/4f433773141d2eb384325714a2776bcc5b2e20f7
@@ -140,7 +147,7 @@ def test_string_index_alias_tz_aware(self, tz):
ser = Series(np.random.randn(len(rng)), index=rng)
result = ser["1/3/2000"]
- tm.assert_almost_equal(result, ser[2])
+ tm.assert_almost_equal(result, ser.iloc[2])
def test_getitem_time_object(self):
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
@@ -205,7 +212,9 @@ def test_getitem_str_with_timedeltaindex(self):
def test_getitem_bool_index_positional(self):
# GH#48653
ser = Series({True: 1, False: 0})
- result = ser[0]
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = ser[0]
assert result == 1
@@ -371,7 +380,9 @@ def test_getitem_intlist_intervalindex_non_int(self, box):
expected = ser.iloc[:1]
key = box([0])
- result = ser[key]
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = ser[key]
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("box", [list, np.array, Index])
@@ -612,7 +623,9 @@ def test_getitem_preserve_name(datetime_series):
result = datetime_series[datetime_series > 0]
assert result.name == datetime_series.name
- result = datetime_series[[0, 2, 4]]
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = datetime_series[[0, 2, 4]]
assert result.name == datetime_series.name
result = datetime_series[5:10]
@@ -640,16 +653,20 @@ def test_getitem_missing(datetime_series):
def test_getitem_fancy(string_series, object_series):
- slice1 = string_series[[1, 2, 3]]
- slice2 = object_series[[1, 2, 3]]
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ slice1 = string_series[[1, 2, 3]]
+ slice2 = object_series[[1, 2, 3]]
assert string_series.index[2] == slice1.index[1]
assert object_series.index[2] == slice2.index[1]
- assert string_series[2] == slice1[1]
- assert object_series[2] == slice2[1]
+ assert string_series.iloc[2] == slice1.iloc[1]
+ assert object_series.iloc[2] == slice2.iloc[1]
def test_getitem_box_float64(datetime_series):
- value = datetime_series[5]
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ value = datetime_series[5]
assert isinstance(value, np.float64)
@@ -683,7 +700,10 @@ def test_slice_can_reorder_not_uniquely_indexed():
def test_duplicated_index_getitem_positional_indexer(index_vals):
# GH 11747
s = Series(range(5), index=list(index_vals))
- result = s[3]
+
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = s[3]
assert result == 3
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index b347691c3c101..83cae8d148feb 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -27,11 +27,14 @@
def test_basic_indexing():
s = Series(np.random.randn(5), index=["a", "b", "a", "a", "b"])
+ warn_msg = "Series.__[sg]etitem__ treating keys as positions is deprecated"
msg = "index 5 is out of bounds for axis 0 with size 5"
with pytest.raises(IndexError, match=msg):
- s[5]
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ s[5]
with pytest.raises(IndexError, match=msg):
- s[5] = 0
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ s[5] = 0
with pytest.raises(KeyError, match=r"^'c'$"):
s["c"]
@@ -39,10 +42,12 @@ def test_basic_indexing():
s = s.sort_index()
with pytest.raises(IndexError, match=msg):
- s[5]
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ s[5]
msg = r"index 5 is out of bounds for axis (0|1) with size 5|^5$"
with pytest.raises(IndexError, match=msg):
- s[5] = 0
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ s[5] = 0
def test_getitem_numeric_should_not_fallback_to_positional(any_numeric_dtype):
@@ -144,7 +149,9 @@ def test_series_box_timestamp():
assert isinstance(ser.iloc[4], Timestamp)
ser = Series(rng, index=rng)
- assert isinstance(ser[0], Timestamp)
+ msg = "Series.__getitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ assert isinstance(ser[0], Timestamp)
assert isinstance(ser.at[rng[1]], Timestamp)
assert isinstance(ser.iat[2], Timestamp)
assert isinstance(ser.loc[rng[3]], Timestamp)
@@ -187,12 +194,12 @@ def test_setitem_ambiguous_keyerror(indexer_sl):
def test_setitem(datetime_series):
datetime_series[datetime_series.index[5]] = np.NaN
- datetime_series[[1, 2, 17]] = np.NaN
- datetime_series[6] = np.NaN
- assert np.isnan(datetime_series[6])
- assert np.isnan(datetime_series[2])
+ datetime_series.iloc[[1, 2, 17]] = np.NaN
+ datetime_series.iloc[6] = np.NaN
+ assert np.isnan(datetime_series.iloc[6])
+ assert np.isnan(datetime_series.iloc[2])
datetime_series[np.isnan(datetime_series)] = 5
- assert not np.isnan(datetime_series[2])
+ assert not np.isnan(datetime_series.iloc[2])
def test_setslice(datetime_series):
@@ -291,9 +298,9 @@ def test_underlying_data_conversion(using_copy_on_write):
def test_preserve_refs(datetime_series):
- seq = datetime_series[[5, 10, 15]]
- seq[1] = np.NaN
- assert not np.isnan(datetime_series[10])
+ seq = datetime_series.iloc[[5, 10, 15]]
+ seq.iloc[1] = np.NaN
+ assert not np.isnan(datetime_series.iloc[10])
def test_multilevel_preserve_name(lexsorted_two_level_string_multiindex, indexer_sl):
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index 9df607cb6c64c..ede59b3ac9cb9 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -176,8 +176,10 @@ def test_setitem_negative_out_of_bounds(self):
ser = Series(tm.rands_array(5, 10), index=tm.rands_array(10, 10))
msg = "index -11 is out of bounds for axis 0 with size 10"
+ warn_msg = "Series.__setitem__ treating keys as positions is deprecated"
with pytest.raises(IndexError, match=msg):
- ser[-11] = "foo"
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ ser[-11] = "foo"
@pytest.mark.parametrize("indexer", [tm.loc, tm.at])
@pytest.mark.parametrize("ser_index", [0, 1])
@@ -1527,7 +1529,9 @@ def test_setitem_positional_with_casting():
# we fallback we *also* get a ValueError if we try to set inplace.
ser = Series([1, 2, 3], index=["a", "b", "c"])
- ser[0] = "X"
+ warn_msg = "Series.__setitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ ser[0] = "X"
expected = Series(["X", 2, 3], index=["a", "b", "c"], dtype=object)
tm.assert_series_equal(ser, expected)
@@ -1536,7 +1540,10 @@ def test_setitem_positional_float_into_int_coerces():
# Case where we hit a KeyError and then trying to set in-place incorrectly
# casts a float to an int
ser = Series([1, 2, 3], index=["a", "b", "c"])
- ser[0] = 1.5
+
+ warn_msg = "Series.__setitem__ treating keys as positions is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=warn_msg):
+ ser[0] = 1.5
expected = Series([1.5, 2, 3], index=["a", "b", "c"])
tm.assert_series_equal(ser, expected)
diff --git a/pandas/tests/series/methods/test_asof.py b/pandas/tests/series/methods/test_asof.py
index 638216302b92f..5ee5671d1dea3 100644
--- a/pandas/tests/series/methods/test_asof.py
+++ b/pandas/tests/series/methods/test_asof.py
@@ -71,16 +71,16 @@ def test_scalar(self):
val1 = ts.asof(ts.index[7])
val2 = ts.asof(ts.index[19])
- assert val1 == ts[4]
- assert val2 == ts[14]
+ assert val1 == ts.iloc[4]
+ assert val2 == ts.iloc[14]
# accepts strings
val1 = ts.asof(str(ts.index[7]))
- assert val1 == ts[4]
+ assert val1 == ts.iloc[4]
# in there
result = ts.asof(ts.index[3])
- assert result == ts[3]
+ assert result == ts.iloc[3]
# no as of value
d = ts.index[0] - offsets.BDay()
@@ -144,15 +144,15 @@ def test_periodindex(self):
val1 = ts.asof(ts.index[7])
val2 = ts.asof(ts.index[19])
- assert val1 == ts[4]
- assert val2 == ts[14]
+ assert val1 == ts.iloc[4]
+ assert val2 == ts.iloc[14]
# accepts strings
val1 = ts.asof(str(ts.index[7]))
- assert val1 == ts[4]
+ assert val1 == ts.iloc[4]
# in there
- assert ts.asof(ts.index[3]) == ts[3]
+ assert ts.asof(ts.index[3]) == ts.iloc[3]
# no as of value
d = ts.index[0].to_timestamp() - offsets.BDay()
diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py
index 36967c5cad925..df9e218e9fae4 100644
--- a/pandas/tests/series/methods/test_fillna.py
+++ b/pandas/tests/series/methods/test_fillna.py
@@ -72,7 +72,7 @@ def test_fillna(self):
tm.assert_series_equal(ts, ts.fillna(method="ffill"))
- ts[2] = np.NaN
+ ts.iloc[2] = np.NaN
exp = Series([0.0, 1.0, 1.0, 3.0, 4.0], index=ts.index)
tm.assert_series_equal(ts.fillna(method="ffill"), exp)
@@ -859,7 +859,7 @@ def test_fillna_bug(self):
def test_ffill(self):
ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5))
- ts[2] = np.NaN
+ ts.iloc[2] = np.NaN
tm.assert_series_equal(ts.ffill(), ts.fillna(method="ffill"))
def test_ffill_mixed_dtypes_without_missing_data(self):
@@ -870,7 +870,7 @@ def test_ffill_mixed_dtypes_without_missing_data(self):
def test_bfill(self):
ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5))
- ts[2] = np.NaN
+ ts.iloc[2] = np.NaN
tm.assert_series_equal(ts.bfill(), ts.fillna(method="bfill"))
def test_pad_nan(self):
@@ -885,7 +885,7 @@ def test_pad_nan(self):
[np.nan, 1.0, 1.0, 3.0, 3.0], ["z", "a", "b", "c", "d"], dtype=float
)
tm.assert_series_equal(x[1:], expected[1:])
- assert np.isnan(x[0]), np.isnan(expected[0])
+ assert np.isnan(x.iloc[0]), np.isnan(expected.iloc[0])
def test_series_fillna_limit(self):
index = np.arange(10)
diff --git a/pandas/tests/series/methods/test_map.py b/pandas/tests/series/methods/test_map.py
index c4570fdb499a3..925384cac605e 100644
--- a/pandas/tests/series/methods/test_map.py
+++ b/pandas/tests/series/methods/test_map.py
@@ -242,7 +242,7 @@ def test_map_type_inference():
def test_map_decimal(string_series):
result = string_series.map(lambda x: Decimal(str(x)))
assert result.dtype == np.object_
- assert isinstance(result[0], Decimal)
+ assert isinstance(result.iloc[0], Decimal)
def test_map_na_exclusion():
diff --git a/pandas/tests/series/methods/test_reset_index.py b/pandas/tests/series/methods/test_reset_index.py
index 9362b0b52a698..ec38c5b8b744b 100644
--- a/pandas/tests/series/methods/test_reset_index.py
+++ b/pandas/tests/series/methods/test_reset_index.py
@@ -20,7 +20,7 @@ def test_reset_index_dti_round_trip(self):
dti = date_range(start="1/1/2001", end="6/1/2001", freq="D")._with_freq(None)
d1 = DataFrame({"v": np.random.rand(len(dti))}, index=dti)
d2 = d1.reset_index()
- assert d2.dtypes[0] == np.dtype("M8[ns]")
+ assert d2.dtypes.iloc[0] == np.dtype("M8[ns]")
d3 = d2.set_index("index")
tm.assert_frame_equal(d1, d3, check_names=False)
@@ -30,7 +30,7 @@ def test_reset_index_dti_round_trip(self):
df = df.set_index("Date")
assert df.index[0] == stamp
- assert df.reset_index()["Date"][0] == stamp
+ assert df.reset_index()["Date"].iloc[0] == stamp
def test_reset_index(self):
df = tm.makeDataFrame()[:5]
diff --git a/pandas/tests/series/methods/test_values.py b/pandas/tests/series/methods/test_values.py
index 479c7033a3fb5..cb1595e68264f 100644
--- a/pandas/tests/series/methods/test_values.py
+++ b/pandas/tests/series/methods/test_values.py
@@ -25,5 +25,5 @@ def test_values_object_extension_dtypes(self, data):
def test_values(self, datetime_series):
tm.assert_almost_equal(
- datetime_series.values, datetime_series, check_dtype=False
+ datetime_series.values, list(datetime_series), check_dtype=False
)
diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py
index 3aa81c5e99ffe..a0edfae606e3f 100644
--- a/pandas/tests/series/test_arithmetic.py
+++ b/pandas/tests/series/test_arithmetic.py
@@ -225,8 +225,8 @@ def test_add_na_handling(self):
result = ser + ser.shift(1)
result2 = ser.shift(1) + ser
- assert isna(result[0])
- assert isna(result2[0])
+ assert isna(result.iloc[0])
+ assert isna(result2.iloc[0])
def test_add_corner_cases(self, datetime_series):
empty = Series([], index=Index([]), dtype=np.float64)
diff --git a/pandas/tests/series/test_iteration.py b/pandas/tests/series/test_iteration.py
index 21ad1747e1086..edc82455234bb 100644
--- a/pandas/tests/series/test_iteration.py
+++ b/pandas/tests/series/test_iteration.py
@@ -5,12 +5,12 @@ def test_keys(self, datetime_series):
def test_iter_datetimes(self, datetime_series):
for i, val in enumerate(datetime_series):
# pylint: disable-next=unnecessary-list-index-lookup
- assert val == datetime_series[i]
+ assert val == datetime_series.iloc[i]
def test_iter_strings(self, string_series):
for i, val in enumerate(string_series):
# pylint: disable-next=unnecessary-list-index-lookup
- assert val == string_series[i]
+ assert val == string_series.iloc[i]
def test_iteritems_datetimes(self, datetime_series):
for idx, val in datetime_series.items():
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index 6f6acb7a996b2..61f9289dd63f2 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -954,21 +954,21 @@ def test_flags_kwarg(any_string_dtype):
with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow):
result = data.str.match(pat, flags=re.IGNORECASE)
- assert result[0]
+ assert result.iloc[0]
with tm.maybe_produces_warning(PerformanceWarning, using_pyarrow):
result = data.str.fullmatch(pat, flags=re.IGNORECASE)
- assert result[0]
+ assert result.iloc[0]
result = data.str.findall(pat, flags=re.IGNORECASE)
- assert result[0][0] == ("dave", "google", "com")
+ assert result.iloc[0][0] == ("dave", "google", "com")
result = data.str.count(pat, flags=re.IGNORECASE)
- assert result[0] == 1
+ assert result.iloc[0] == 1
msg = "has match groups"
with tm.assert_produces_warning(
UserWarning, match=msg, raise_on_extra_warnings=not using_pyarrow
):
result = data.str.contains(pat, flags=re.IGNORECASE)
- assert result[0]
+ assert result.iloc[0]
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 92b4370e9d736..4466ee96235f5 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -2575,11 +2575,11 @@ def test_string_na_nat_conversion_with_name(self, cache):
expected = Series(np.empty(5, dtype="M8[ns]"), index=idx)
for i in range(5):
- x = series[i]
+ x = series.iloc[i]
if isna(x):
- expected[i] = NaT
+ expected.iloc[i] = NaT
else:
- expected[i] = to_datetime(x, cache=cache)
+ expected.iloc[i] = to_datetime(x, cache=cache)
tm.assert_series_equal(result, expected, check_names=False)
assert result.name == "foo"
diff --git a/pandas/tests/window/test_apply.py b/pandas/tests/window/test_apply.py
index ee7f57ddab0ad..c37fd5258874f 100644
--- a/pandas/tests/window/test_apply.py
+++ b/pandas/tests/window/test_apply.py
@@ -250,7 +250,7 @@ def test_time_rule_series(raw, series):
prev_date = last_date - 24 * offsets.BDay()
trunc_series = series[::2].truncate(prev_date, last_date)
- tm.assert_almost_equal(series_result[-1], np.mean(trunc_series))
+ tm.assert_almost_equal(series_result.iloc[-1], np.mean(trunc_series))
def test_time_rule_frame(raw, frame):
diff --git a/pandas/tests/window/test_pairwise.py b/pandas/tests/window/test_pairwise.py
index 77a64999053e2..f9bc572b41312 100644
--- a/pandas/tests/window/test_pairwise.py
+++ b/pandas/tests/window/test_pairwise.py
@@ -54,7 +54,7 @@ def test_rolling_cov(series):
B = A + np.random.randn(len(A))
result = A.rolling(window=50, min_periods=25).cov(B)
- tm.assert_almost_equal(result[-1], np.cov(A[-50:], B[-50:])[0, 1])
+ tm.assert_almost_equal(result.iloc[-1], np.cov(A[-50:], B[-50:])[0, 1])
def test_rolling_corr(series):
@@ -62,7 +62,7 @@ def test_rolling_corr(series):
B = A + np.random.randn(len(A))
result = A.rolling(window=50, min_periods=25).corr(B)
- tm.assert_almost_equal(result[-1], np.corrcoef(A[-50:], B[-50:])[0, 1])
+ tm.assert_almost_equal(result.iloc[-1], np.corrcoef(A[-50:], B[-50:])[0, 1])
# test for correct bias correction
a = tm.makeTimeSeries()
@@ -71,7 +71,7 @@ def test_rolling_corr(series):
b[:10] = np.nan
result = a.rolling(window=len(a), min_periods=1).corr(b)
- tm.assert_almost_equal(result[-1], a.corr(b))
+ tm.assert_almost_equal(result.iloc[-1], a.corr(b))
@pytest.mark.parametrize("func", ["cov", "corr"])
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index 3a58a6860a8b5..084b4b606ad5e 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -1060,7 +1060,7 @@ def test_rolling_numerical_too_large_numbers():
# GH: 11645
dates = date_range("2015-01-01", periods=10, freq="D")
ds = Series(data=range(10), index=dates, dtype=np.float64)
- ds[2] = -9e33
+ ds.iloc[2] = -9e33
result = ds.rolling(5).mean()
expected = Series(
[
diff --git a/pandas/tests/window/test_rolling_functions.py b/pandas/tests/window/test_rolling_functions.py
index c42f13d4b2235..03c0839d00787 100644
--- a/pandas/tests/window/test_rolling_functions.py
+++ b/pandas/tests/window/test_rolling_functions.py
@@ -99,7 +99,7 @@ def test_time_rule_series(series, compare_func, roll_func, kwargs, minp):
prev_date = last_date - 24 * offsets.BDay()
trunc_series = series[::2].truncate(prev_date, last_date)
- tm.assert_almost_equal(series_result[-1], compare_func(trunc_series))
+ tm.assert_almost_equal(series_result.iloc[-1], compare_func(trunc_series))
@pytest.mark.parametrize(
diff --git a/pandas/tests/window/test_rolling_quantile.py b/pandas/tests/window/test_rolling_quantile.py
index 2eba0b36ed187..e6d12d924f611 100644
--- a/pandas/tests/window/test_rolling_quantile.py
+++ b/pandas/tests/window/test_rolling_quantile.py
@@ -65,7 +65,7 @@ def test_time_rule_series(series, q):
prev_date = last_date - 24 * offsets.BDay()
trunc_series = series[::2].truncate(prev_date, last_date)
- tm.assert_almost_equal(series_result[-1], compare_func(trunc_series))
+ tm.assert_almost_equal(series_result.iloc[-1], compare_func(trunc_series))
@pytest.mark.parametrize("q", [0.0, 0.1, 0.5, 0.9, 1.0])
diff --git a/pandas/tests/window/test_rolling_skew_kurt.py b/pandas/tests/window/test_rolling_skew_kurt.py
index 43db772251219..56acee542aea4 100644
--- a/pandas/tests/window/test_rolling_skew_kurt.py
+++ b/pandas/tests/window/test_rolling_skew_kurt.py
@@ -56,7 +56,7 @@ def test_time_rule_series(series, sp_func, roll_func):
prev_date = last_date - 24 * offsets.BDay()
trunc_series = series[::2].truncate(prev_date, last_date)
- tm.assert_almost_equal(series_result[-1], compare_func(trunc_series))
+ tm.assert_almost_equal(series_result.iloc[-1], compare_func(trunc_series))
@td.skip_if_no_scipy
| - [ ] 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.
xref #50617, possibly closes | https://api.github.com/repos/pandas-dev/pandas/pulls/53201 | 2023-05-12T16:52:21Z | 2023-05-19T21:13:50Z | 2023-05-19T21:13:50Z | 2023-05-19T21:28:08Z |
PERF: Performance regression in Groupby.apply with group_keys=True | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 0d6647dc38b3c..c8159be4d7b6b 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 performance regression in :meth:`GroupBy.apply` (:issue:`53195`)
- 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`)
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index 018075c1687fe..23fd93aca4258 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -532,7 +532,7 @@ def _clean_keys_and_objs(
keys = type(keys).from_tuples(clean_keys, names=keys.names)
else:
name = getattr(keys, "name", None)
- keys = Index(clean_keys, name=name)
+ keys = Index(clean_keys, name=name, dtype=getattr(keys, "dtype", None))
if len(objs) == 0:
raise ValueError("All objects passed were None")
@@ -806,15 +806,19 @@ def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde
for hlevel, level in zip(zipped, levels):
to_concat = []
- for key, index in zip(hlevel, indexes):
- # Find matching codes, include matching nan values as equal.
- mask = (isna(level) & isna(key)) | (level == key)
- if not mask.any():
- raise ValueError(f"Key {key} not in level {level}")
- i = np.nonzero(mask)[0][0]
-
- to_concat.append(np.repeat(i, len(index)))
- codes_list.append(np.concatenate(to_concat))
+ if isinstance(hlevel, Index) and hlevel.equals(level):
+ lens = [len(idx) for idx in indexes]
+ codes_list.append(np.repeat(np.arange(len(hlevel)), lens))
+ else:
+ for key, index in zip(hlevel, indexes):
+ # Find matching codes, include matching nan values as equal.
+ mask = (isna(level) & isna(key)) | (level == key)
+ if not mask.any():
+ raise ValueError(f"Key {key} not in level {level}")
+ i = np.nonzero(mask)[0][0]
+
+ to_concat.append(np.repeat(i, len(index)))
+ codes_list.append(np.concatenate(to_concat))
concat_index = _concat_indexes(indexes)
| - [ ] 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.
I came accross this bottleneck through the changed default of ``group_keys``. Technically this is not a regression, but it's visible to all users that don't set ``group_keys`` explicitly. This change provides around a 20-30% speedup in groupby apply when you have many groups | https://api.github.com/repos/pandas-dev/pandas/pulls/53195 | 2023-05-12T07:14:34Z | 2023-05-12T16:58:18Z | 2023-05-12T16:58:18Z | 2023-05-16T16:18:15Z |
use is_integer in df.insert | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 52fc8512c9db3..e659bf7adbf1a 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -351,6 +351,7 @@ Conversion
- Bug in :meth:`ArrowDtype.numpy_dtype` returning nanosecond units for non-nanosecond ``pyarrow.timestamp`` and ``pyarrow.duration`` types (:issue:`51800`)
- Bug in :meth:`DataFrame.__repr__` incorrectly raising a ``TypeError`` when the dtype of a column is ``np.record`` (:issue:`48526`)
- Bug in :meth:`DataFrame.info` raising ``ValueError`` when ``use_numba`` is set (:issue:`51922`)
+- Bug in :meth:`DataFrame.insert` raising ``TypeError`` if ``loc`` is ``np.int64`` (:issue:`53193`)
-
Strings
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 485cc9db5ffe7..459b162e2a6c9 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4800,9 +4800,10 @@ def insert(
if not allow_duplicates and column in self.columns:
# Should this be a different kind of error??
raise ValueError(f"cannot insert {column}, already exists")
- if not isinstance(loc, int):
+ if not is_integer(loc):
raise TypeError("loc must be int")
-
+ # convert non stdlib ints to satisfy typing checks
+ loc = int(loc)
if isinstance(value, DataFrame) and len(value.columns) > 1:
raise ValueError(
f"Expected a one-dimensional object, got a DataFrame with "
diff --git a/pandas/tests/frame/indexing/test_insert.py b/pandas/tests/frame/indexing/test_insert.py
index 666a6ec3710a6..13e43abe0dd7f 100644
--- a/pandas/tests/frame/indexing/test_insert.py
+++ b/pandas/tests/frame/indexing/test_insert.py
@@ -110,3 +110,9 @@ def test_insert_frame(self):
)
with pytest.raises(ValueError, match=msg):
df.insert(1, "newcol", df)
+
+ def test_insert_int64_loc(self):
+ # GH#53193
+ df = DataFrame({"a": [1, 2]})
+ df.insert(np.int64(0), "b", 0)
+ tm.assert_frame_equal(df, DataFrame({"b": [0, 0], "a": [1, 2]}))
| - [ ] closes #53193
- [ ] [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/53194 | 2023-05-12T05:51:34Z | 2023-05-14T05:30:58Z | 2023-05-14T05:30:58Z | 2023-05-14T05:31:31Z |
BUG/CoW: Series.rename not making a lazy copy when passed a scalar | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 0d6647dc38b3c..8ef733f825d00 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -31,6 +31,7 @@ Bug fixes
- Bug in :meth:`DataFrame.__getitem__` not preserving dtypes for :class:`MultiIndex` partial keys (:issue:`51895`)
- 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:`Series.rename` not making a lazy copy when Copy-on-Write is enabled when a scalar is passed to it (:issue:`52450`)
- Bug in :meth:`pd.array` raising for ``NumPy`` array and ``pa.large_string`` or ``pa.large_binary`` (:issue:`52590`)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 84fa874831d85..e70b217e08dff 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1907,7 +1907,9 @@ def to_frame(self, name: Hashable = lib.no_default) -> DataFrame:
df = self._constructor_expanddim(mgr)
return df.__finalize__(self, method="to_frame")
- def _set_name(self, name, inplace: bool = False) -> Series:
+ def _set_name(
+ self, name, inplace: bool = False, deep: bool | None = None
+ ) -> Series:
"""
Set the Series name.
@@ -1916,9 +1918,11 @@ def _set_name(self, name, inplace: bool = False) -> Series:
name : str
inplace : bool
Whether to modify `self` directly or return a copy.
+ deep : bool|None, default None
+ Whether to do a deep copy, a shallow copy, or Copy on Write(None)
"""
inplace = validate_bool_kwarg(inplace, "inplace")
- ser = self if inplace else self.copy()
+ ser = self if inplace else self.copy(deep and not using_copy_on_write())
ser.name = name
return ser
@@ -4580,7 +4584,7 @@ def rename(
index: Renamer | Hashable | None = None,
*,
axis: Axis | None = None,
- copy: bool = True,
+ copy: bool | None = None,
inplace: bool = False,
level: Level | None = None,
errors: IgnoreRaise = "ignore",
@@ -4667,7 +4671,7 @@ def rename(
errors=errors,
)
else:
- return self._set_name(index, inplace=inplace)
+ return self._set_name(index, inplace=inplace, deep=copy)
@Appender(
"""
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py
index 68b41682ab411..67fc91e0567ef 100644
--- a/pandas/tests/copy_view/test_methods.py
+++ b/pandas/tests/copy_view/test_methods.py
@@ -141,6 +141,7 @@ def test_methods_copy_keyword(
"method",
[
lambda ser, copy: ser.rename(index={0: 100}, copy=copy),
+ lambda ser, copy: ser.rename(None, copy=copy),
lambda ser, copy: ser.reindex(index=ser.index, copy=copy),
lambda ser, copy: ser.reindex_like(ser, copy=copy),
lambda ser, copy: ser.align(ser, copy=copy)[0],
@@ -158,6 +159,7 @@ def test_methods_copy_keyword(
lambda ser, copy: ser.set_flags(allows_duplicate_labels=False, copy=copy),
],
ids=[
+ "rename (dict)",
"rename",
"reindex",
"reindex_like",
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index af3632bffe948..3edfd47cb05a1 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -316,7 +316,7 @@ def test_frame_setitem_existing_datetime64_col_other_units(self, unit):
df["dates"] = vals
assert (df["dates"].values == ex_vals).all()
- def test_setitem_dt64tz(self, timezone_frame):
+ def test_setitem_dt64tz(self, timezone_frame, using_copy_on_write):
df = timezone_frame
idx = df["B"].rename("foo")
@@ -331,12 +331,16 @@ def test_setitem_dt64tz(self, timezone_frame):
# assert that A & C are not sharing the same base (e.g. they
# are copies)
+ # Note: This does not hold with Copy on Write (because of lazy copying)
v1 = df._mgr.arrays[1]
v2 = df._mgr.arrays[2]
tm.assert_extension_array_equal(v1, v2)
v1base = v1._ndarray.base
v2base = v2._ndarray.base
- assert v1base is None or (id(v1base) != id(v2base))
+ if not using_copy_on_write:
+ assert v1base is None or (id(v1base) != id(v2base))
+ else:
+ assert id(v1base) == id(v2base)
# with nan
df2 = df.copy()
| - [ ] closes #52450 (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.
I put this in for 2.0.2 since we claim that the lazy-copy was implemented for ``rename`` in 2.0
| https://api.github.com/repos/pandas-dev/pandas/pulls/53189 | 2023-05-11T22:23:39Z | 2023-05-14T09:03:31Z | 2023-05-14T09:03:31Z | 2023-05-14T09:56:44Z |
DOC: Fix version switcher | diff --git a/doc/source/versions.json b/web/pandas/versions.json
similarity index 100%
rename from doc/source/versions.json
rename to web/pandas/versions.json
| - [X] closes #53180 | https://api.github.com/repos/pandas-dev/pandas/pulls/53188 | 2023-05-11T18:09:10Z | 2023-05-11T23:45:29Z | 2023-05-11T23:45:29Z | 2023-05-11T23:47:50Z |
DOC: Fix rst formatting in dev environment docs | diff --git a/doc/source/development/contributing_environment.rst b/doc/source/development/contributing_environment.rst
index 38e354d8c57d6..8bc15d6968afc 100644
--- a/doc/source/development/contributing_environment.rst
+++ b/doc/source/development/contributing_environment.rst
@@ -225,7 +225,7 @@ To compile pandas with meson, run::
# Build and install pandas
python -m pip install -ve . --no-build-isolation
-** Build options **
+**Build options**
It is possible to pass options from the pip frontend to the meson backend if you would like to configure your
install. Occasionally, you'll want to use this to adjust the build directory, and/or toggle debug/optimization levels.
| - [ ] 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.
This isn't formatted correctly in the [currently deployed version of the docs](https://pandas.pydata.org/docs/dev/development/contributing_environment.html#step-3-build-and-install-pandas). | https://api.github.com/repos/pandas-dev/pandas/pulls/53187 | 2023-05-11T18:04:54Z | 2023-05-11T20:17:25Z | 2023-05-11T20:17:25Z | 2023-05-11T20:17:42Z |
CI: Clean caches of closed PRs | diff --git a/.github/workflows/cache-cleanup.yml b/.github/workflows/cache-cleanup.yml
new file mode 100644
index 0000000000000..099974141c1d1
--- /dev/null
+++ b/.github/workflows/cache-cleanup.yml
@@ -0,0 +1,30 @@
+name: Clean closed branch caches
+on:
+ pull_request:
+ types:
+ - closed
+
+jobs:
+ cleanup:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Clean Cache
+ run: |
+ gh extension install actions/gh-actions-cache
+
+ REPO=${{ github.repository }}
+ BRANCH="refs/pull/${{ github.event.pull_request.number }}/merge"
+
+ echo "Fetching list of cache key"
+ cacheKeysForPR=$(gh actions-cache list -R $REPO -B $BRANCH | cut -f 1 )
+
+ ## Setting this to not fail the workflow while deleting cache keys.
+ set +e
+ echo "Deleting caches..."
+ for cacheKey in $cacheKeysForPR
+ do
+ gh actions-cache delete $cacheKey -R $REPO -B $BRANCH --confirm
+ done
+ echo "Done"
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
| Looks like we regularly go over the 10GB CI cache limit. One step that should help is removing CI caches from closed PRs
https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#force-deleting-cache-entries | https://api.github.com/repos/pandas-dev/pandas/pulls/53184 | 2023-05-11T16:49:00Z | 2023-05-15T20:27:19Z | 2023-05-15T20:27:19Z | 2023-05-15T20:27:23Z |
DOC: add missing parameters to offsets classes: BYearEnd, BusinessHour, WeekOfMonth | diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index ffbaddfcd2afa..87b511d92ac30 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -1714,6 +1714,8 @@ cdef class BusinessHour(BusinessMixin):
Start time of your custom business hour in 24h format.
end : str, time, or list of str/time, default: "17:00"
End time of your custom business hour in 24h format.
+ offset : timedelta, default timedelta(0)
+ Time offset to apply.
Examples
--------
@@ -2243,6 +2245,15 @@ cdef class BYearEnd(YearOffset):
"""
DateOffset increments between the last business day of the year.
+ Parameters
+ ----------
+ n : int, default 1
+ The number of years represented.
+ normalize : bool, default False
+ Normalize start/end dates to midnight before generating date range.
+ month : int, default 1
+ A specific integer for the month of the year.
+
Examples
--------
>>> from pandas.tseries.offsets import BYearEnd
@@ -3073,7 +3084,10 @@ cdef class WeekOfMonth(WeekOfMonthMixin):
Parameters
----------
- n : int
+ n : int, default 1
+ The number of months represented.
+ normalize : bool, default False
+ Normalize start/end dates to midnight before generating date range.
week : int {0, 1, 2, 3, ...}, default 0
A specific integer for the week of the month.
e.g. 0 is 1st week of month, 1 is the 2nd week, etc.
| - [x] towards #52431
Updated documentation for offsets classes: `BYearEnd,` `BusinessHour`, `WeekOfMonth`, added missing parameters. | https://api.github.com/repos/pandas-dev/pandas/pulls/53183 | 2023-05-11T15:54:07Z | 2023-05-16T11:10:27Z | 2023-05-16T11:10:27Z | 2023-05-16T11:33:54Z |
DOC Fixing EX01 - added examples | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 022b85b9eb55c..99bd90750b676 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -80,12 +80,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
MSG='Partially validate docstrings (EX01)' ; echo $MSG
$BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX01 --ignore_functions \
- pandas.Series.item \
- pandas.Series.pipe \
- pandas.Series.mode \
- pandas.Series.is_unique \
- pandas.Series.is_monotonic_increasing \
- pandas.Series.is_monotonic_decreasing \
pandas.Series.backfill \
pandas.Series.bfill \
pandas.Series.ffill \
@@ -319,7 +313,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
pandas.Index.fillna \
pandas.Index.dropna \
pandas.Index.astype \
- pandas.Index.item \
pandas.Index.map \
pandas.Index.ravel \
pandas.Index.to_list \
@@ -462,8 +455,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
pandas.core.groupby.SeriesGroupBy.cumsum \
pandas.core.groupby.SeriesGroupBy.diff \
pandas.core.groupby.SeriesGroupBy.ffill \
- pandas.core.groupby.SeriesGroupBy.is_monotonic_increasing \
- pandas.core.groupby.SeriesGroupBy.is_monotonic_decreasing \
pandas.core.groupby.SeriesGroupBy.max \
pandas.core.groupby.SeriesGroupBy.median \
pandas.core.groupby.SeriesGroupBy.min \
diff --git a/pandas/core/base.py b/pandas/core/base.py
index b281dace12fcb..e9a127259eb41 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -357,12 +357,24 @@ def item(self):
Returns
-------
scalar
- The first element of Series.
+ The first element of Series or Index.
Raises
------
ValueError
- If the data is not length-1.
+ If the data is not length = 1.
+
+ Examples
+ --------
+ >>> s = pd.Series([1])
+ >>> s.item()
+ 1
+
+ For an index:
+
+ >>> s = pd.Series([1], index=['a'])
+ >>> s.index.item()
+ 'a'
"""
if len(self) == 1:
return next(iter(self))
@@ -965,6 +977,16 @@ def is_unique(self) -> bool:
Returns
-------
bool
+
+ Examples
+ --------
+ >>> s = pd.Series([1, 2, 3])
+ >>> s.is_unique
+ True
+
+ >>> s = pd.Series([1, 2, 3, 1])
+ >>> s.is_unique
+ False
"""
return self.nunique(dropna=False) == len(self)
@@ -976,6 +998,16 @@ def is_monotonic_increasing(self) -> bool:
Returns
-------
bool
+
+ Examples
+ --------
+ >>> s = pd.Series([1, 2, 2])
+ >>> s.is_monotonic_increasing
+ True
+
+ >>> s = pd.Series([3, 2, 1])
+ >>> s.is_monotonic_increasing
+ False
"""
from pandas import Index
@@ -989,6 +1021,16 @@ def is_monotonic_decreasing(self) -> bool:
Returns
-------
bool
+
+ Examples
+ --------
+ >>> s = pd.Series([3, 2, 2, 1])
+ >>> s.is_monotonic_decreasing
+ True
+
+ >>> s = pd.Series([1, 2, 3])
+ >>> s.is_monotonic_decreasing
+ False
"""
from pandas import Index
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index d26448dffc11a..36ad6e4a11123 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1170,13 +1170,41 @@ def cov(
return result
@property
- @doc(Series.is_monotonic_increasing.__doc__)
def is_monotonic_increasing(self) -> Series:
+ """
+ Return whether each group's values are monotonically increasing.
+
+ Returns
+ -------
+ Series
+
+ Examples
+ --------
+ >>> s = pd.Series([2, 1, 3, 4], index=['Falcon', 'Falcon', 'Parrot', 'Parrot'])
+ >>> s.groupby(level=0).is_monotonic_increasing
+ Falcon False
+ Parrot True
+ dtype: bool
+ """
return self.apply(lambda ser: ser.is_monotonic_increasing)
@property
- @doc(Series.is_monotonic_decreasing.__doc__)
def is_monotonic_decreasing(self) -> Series:
+ """
+ Return whether each group's values are monotonically decreasing.
+
+ Returns
+ -------
+ Series
+
+ Examples
+ --------
+ >>> s = pd.Series([2, 1, 3, 4], index=['Falcon', 'Falcon', 'Parrot', 'Parrot'])
+ >>> s.groupby(level=0).is_monotonic_decreasing
+ Falcon True
+ Parrot False
+ dtype: bool
+ """
return self.apply(lambda ser: ser.is_monotonic_decreasing)
@doc(Series.hist.__doc__)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index e70b217e08dff..540a770b1c897 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2085,6 +2085,32 @@ def mode(self, dropna: bool = True) -> Series:
-------
Series
Modes of the Series in sorted order.
+
+ Examples
+ --------
+ >>> s = pd.Series([2, 4, 2, 2, 4, None])
+ >>> s.mode()
+ 0 2.0
+ dtype: float64
+
+ More than one mode:
+
+ >>> s = pd.Series([2, 4, 8, 2, 4, None])
+ >>> s.mode()
+ 0 2.0
+ 1 4.0
+ dtype: float64
+
+ With and without considering null value:
+
+ >>> s = pd.Series([2, 4, None, None, 4, None])
+ >>> s.mode(dropna=False)
+ 0 NaN
+ dtype: float64
+ >>> s = pd.Series([2, 4, None, None, 4, None])
+ >>> s.mode()
+ 0 4.0
+ dtype: float64
"""
# TODO: Add option for bins like value_counts()
values = self._values
| Towards #37875
I couldn't locally build the html files for `Series.SeriesGroupBy.is_monotonic_increasing` and `Series.SeriesGroupBy.is_monotonic_decreasing`. Followed https://github.com/noatamir/pyladies-berlin-sprints/issues/13 to split the docstrings from Series - but I'm not sure if adding #GH13 to the docstring is correct
Couldn't use a variable like {klass} for `item()` to avoid hardcoding `Series` or `Index`. | https://api.github.com/repos/pandas-dev/pandas/pulls/53181 | 2023-05-11T15:29:07Z | 2023-05-15T14:46:46Z | 2023-05-15T14:46:46Z | 2023-05-15T14:54:17Z |
Add asv benchmarks for Block.setitem() | diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py
index 53827cfcf64fb..84d95a23bd446 100644
--- a/asv_bench/benchmarks/indexing.py
+++ b/asv_bench/benchmarks/indexing.py
@@ -3,6 +3,7 @@
lower-level methods directly on Index and subclasses, see index_object.py,
indexing_engine.py, and index_cached.py
"""
+from datetime import datetime
import warnings
import numpy as np
@@ -531,4 +532,25 @@ def time_chained_indexing(self, mode):
df2["C"] = 1.0
+class Block:
+ params = [
+ (True, "True"),
+ (np.array(True), "np.array(True)"),
+ ]
+
+ def setup(self, true_value, mode):
+ self.df = DataFrame(
+ False,
+ columns=np.arange(500).astype(str),
+ index=date_range("2010-01-01", "2011-01-01"),
+ )
+
+ self.true_value = true_value
+
+ def time_test(self, true_value, mode):
+ start = datetime(2010, 5, 1)
+ end = datetime(2010, 9, 1)
+ self.df.loc[start:end, :] = true_value
+
+
from .pandas_vb_common import setup # noqa: F401 isort:skip
| - [x] closes #25756 (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.
I believe that this solves the issue , however let me know if i need to change anything as i am not familliar with asv benchmarks | https://api.github.com/repos/pandas-dev/pandas/pulls/53177 | 2023-05-11T13:09:18Z | 2023-05-15T20:28:10Z | 2023-05-15T20:28:10Z | 2023-05-15T20:28:19Z |
Add `np.intc` to `_factorizers` in `pd.merge` | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index e47c8c9b1714a..a40eb47508609 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -14,11 +14,11 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed performance regression in :meth:`GroupBy.apply` (:issue:`53195`)
+- Fixed regression in :func:`merge` on Windows when dtype is ``np.intc`` (:issue:`52451`)
- 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`)
--
.. ---------------------------------------------------------------------------
.. _whatsnew_202.bug_fixes:
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 7c046bddab4e8..8b9a498b27bbe 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -123,6 +123,10 @@
np.object_: libhashtable.ObjectFactorizer,
}
+# See https://github.com/pandas-dev/pandas/issues/52451
+if np.intc is not np.int32:
+ _factorizers[np.intc] = libhashtable.Int64Factorizer
+
_known = (np.ndarray, ExtensionArray, Index, ABCSeries)
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 088ebf6c88e6a..b3d8752a8e3a9 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -1461,7 +1461,9 @@ def test_different(self, right_vals):
result = merge(left, right, on="A")
assert is_object_dtype(result.A.dtype)
- @pytest.mark.parametrize("d1", [np.int64, np.int32, np.int16, np.int8, np.uint8])
+ @pytest.mark.parametrize(
+ "d1", [np.int64, np.int32, np.intc, np.int16, np.int8, np.uint8]
+ )
@pytest.mark.parametrize("d2", [np.int64, np.float64, np.float32, np.float16])
def test_join_multi_dtypes(self, d1, d2):
dtype1 = np.dtype(d1)
| - [x] closes #52451
- [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.
continuation of https://github.com/pandas-dev/pandas/pull/52478 | https://api.github.com/repos/pandas-dev/pandas/pulls/53175 | 2023-05-11T10:32:15Z | 2023-05-17T16:45:33Z | 2023-05-17T16:45:32Z | 2023-05-17T16:49:48Z |
Add test for groupby with TimeGrouper | diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 2e432a768af9e..7bda7c575d994 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -3058,3 +3058,27 @@ def test_groupby_selection_other_methods(df):
tm.assert_frame_equal(
g.filter(lambda x: len(x) == 3), g_exp.filter(lambda x: len(x) == 3)
)
+
+
+def test_groupby_with_Time_Grouper():
+ idx2 = [
+ to_datetime("2016-08-31 22:08:12.000"),
+ to_datetime("2016-08-31 22:09:12.200"),
+ to_datetime("2016-08-31 22:20:12.400"),
+ ]
+
+ test_data = DataFrame(
+ {"quant": [1.0, 1.0, 3.0], "quant2": [1.0, 1.0, 3.0], "time2": idx2}
+ )
+
+ expected_output = DataFrame(
+ {
+ "time2": date_range("2016-08-31 22:08:00", periods=13, freq="1T"),
+ "quant": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+ "quant2": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+ }
+ )
+
+ df = test_data.groupby(Grouper(key="time2", freq="1T")).count().reset_index()
+
+ tm.assert_frame_equal(df, expected_output)
| - [x] closes #17202
- [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).
- [ ] 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/53173 | 2023-05-10T23:21:14Z | 2023-05-11T15:23:30Z | 2023-05-11T15:23:30Z | 2023-05-11T15:23:37Z |
BUG/REF: ArrowExtensionArray non-nanosecond units | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index b264e6da82b50..299adc5af8aea 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -438,6 +438,7 @@ Sparse
ExtensionArray
^^^^^^^^^^^^^^
+- Bug in :class:`~arrays.ArrowExtensionArray` converting pandas non-nanosecond temporal objects from non-zero values to zero values (:issue:`53171`)
- Bug in :meth:`Series.quantile` for pyarrow temporal types raising ArrowInvalid (:issue:`52678`)
- Bug in :meth:`Series.rank` returning wrong order for small values with ``Float64`` dtype (:issue:`52471`)
- Bug where the ``__from_arrow__`` method of masked ExtensionDtypes(e.g. :class:`Float64Dtype`, :class:`BooleanDtype`) would not accept pyarrow arrays of type ``pyarrow.null()`` (:issue:`52223`)
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 402ad9240244f..3b92804f65112 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -18,6 +18,10 @@
import numpy as np
from pandas._libs import lib
+from pandas._libs.tslibs import (
+ Timedelta,
+ Timestamp,
+)
from pandas.compat import (
pa_version_under7p0,
pa_version_under8p0,
@@ -244,39 +248,9 @@ def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = Fal
"""
Construct a new ExtensionArray from a sequence of scalars.
"""
- pa_dtype = to_pyarrow_type(dtype)
- if (
- isinstance(scalars, np.ndarray)
- and isinstance(dtype, ArrowDtype)
- and (
- pa.types.is_large_binary(pa_dtype) or pa.types.is_large_string(pa_dtype)
- )
- ):
- # See https://github.com/apache/arrow/issues/35289
- scalars = scalars.tolist()
-
- if isinstance(scalars, cls):
- scalars = scalars._pa_array
- elif not isinstance(scalars, (pa.Array, pa.ChunkedArray)):
- if copy and is_array_like(scalars):
- # pa array should not get updated when numpy array is updated
- scalars = scalars.copy()
- try:
- scalars = pa.array(scalars, type=pa_dtype, from_pandas=True)
- except pa.ArrowInvalid:
- # GH50430: let pyarrow infer type, then cast
- scalars = pa.array(scalars, from_pandas=True)
- if pa_dtype and scalars.type != pa_dtype:
- if pa.types.is_dictionary(pa_dtype):
- scalars = scalars.dictionary_encode()
- else:
- scalars = scalars.cast(pa_dtype)
- arr = cls(scalars)
- if pa.types.is_duration(scalars.type) and scalars.null_count > 0:
- # GH52843: upstream bug for duration types when originally
- # constructed with data containing numpy NaT.
- # https://github.com/apache/arrow/issues/35088
- arr = arr.fillna(arr.dtype.na_value)
+ pa_type = to_pyarrow_type(dtype)
+ pa_array = cls._box_pa_array(scalars, pa_type=pa_type, copy=copy)
+ arr = cls(pa_array)
return arr
@classmethod
@@ -352,6 +326,150 @@ def _from_sequence_of_strings(
)
return cls._from_sequence(scalars, dtype=pa_type, copy=copy)
+ @classmethod
+ def _box_pa(
+ cls, value, pa_type: pa.DataType | None = None
+ ) -> pa.Array | pa.ChunkedArray | pa.Scalar:
+ """
+ Box value into a pyarrow Array, ChunkedArray or Scalar.
+
+ Parameters
+ ----------
+ value : any
+ pa_type : pa.DataType | None
+
+ Returns
+ -------
+ pa.Array or pa.ChunkedArray or pa.Scalar
+ """
+ if is_list_like(value):
+ return cls._box_pa_array(value, pa_type)
+ return cls._box_pa_scalar(value, pa_type)
+
+ @classmethod
+ def _box_pa_scalar(cls, value, pa_type: pa.DataType | None = None) -> pa.Scalar:
+ """
+ Box value into a pyarrow Scalar.
+
+ Parameters
+ ----------
+ value : any
+ pa_type : pa.DataType | None
+
+ Returns
+ -------
+ pa.Scalar
+ """
+ if isinstance(value, pa.Scalar):
+ pa_scalar = value
+ elif isna(value):
+ pa_scalar = pa.scalar(None, type=pa_type)
+ else:
+ # GH 53171: pyarrow does not yet handle pandas non-nano correctly
+ # see https://github.com/apache/arrow/issues/33321
+ if isinstance(value, Timedelta):
+ if pa_type is None:
+ pa_type = pa.duration(value.unit)
+ elif value.unit != pa_type.unit:
+ value = value.as_unit(pa_type.unit)
+ value = value._value
+ elif isinstance(value, Timestamp):
+ if pa_type is None:
+ pa_type = pa.timestamp(value.unit, tz=value.tz)
+ elif value.unit != pa_type.unit:
+ value = value.as_unit(pa_type.unit)
+ value = value._value
+
+ pa_scalar = pa.scalar(value, type=pa_type, from_pandas=True)
+
+ if pa_type is not None and pa_scalar.type != pa_type:
+ pa_scalar = pa_scalar.cast(pa_type)
+
+ return pa_scalar
+
+ @classmethod
+ def _box_pa_array(
+ cls, value, pa_type: pa.DataType | None = None, copy: bool = False
+ ) -> pa.Array | pa.ChunkedArray:
+ """
+ Box value into a pyarrow Array or ChunkedArray.
+
+ Parameters
+ ----------
+ value : Sequence
+ pa_type : pa.DataType | None
+
+ Returns
+ -------
+ pa.Array or pa.ChunkedArray
+ """
+ if isinstance(value, cls):
+ pa_array = value._pa_array
+ elif isinstance(value, (pa.Array, pa.ChunkedArray)):
+ pa_array = value
+ elif isinstance(value, BaseMaskedArray):
+ # GH 52625
+ if copy:
+ value = value.copy()
+ pa_array = value.__arrow_array__()
+ else:
+ if (
+ isinstance(value, np.ndarray)
+ and pa_type is not None
+ and (
+ pa.types.is_large_binary(pa_type)
+ or pa.types.is_large_string(pa_type)
+ )
+ ):
+ # See https://github.com/apache/arrow/issues/35289
+ value = value.tolist()
+ elif copy and is_array_like(value):
+ # pa array should not get updated when numpy array is updated
+ value = value.copy()
+
+ if (
+ pa_type is not None
+ and pa.types.is_duration(pa_type)
+ and (not isinstance(value, np.ndarray) or value.dtype.kind not in "mi")
+ ):
+ # GH 53171: pyarrow does not yet handle pandas non-nano correctly
+ # see https://github.com/apache/arrow/issues/33321
+ from pandas.core.tools.timedeltas import to_timedelta
+
+ value = to_timedelta(value, unit=pa_type.unit).as_unit(pa_type.unit)
+ value = value.to_numpy()
+
+ try:
+ pa_array = pa.array(value, type=pa_type, from_pandas=True)
+ except pa.ArrowInvalid:
+ # GH50430: let pyarrow infer type, then cast
+ pa_array = pa.array(value, from_pandas=True)
+
+ if pa_type is None and pa.types.is_duration(pa_array.type):
+ # GH 53171: pyarrow does not yet handle pandas non-nano correctly
+ # see https://github.com/apache/arrow/issues/33321
+ from pandas.core.tools.timedeltas import to_timedelta
+
+ value = to_timedelta(value)
+ value = value.to_numpy()
+ pa_array = pa.array(value, type=pa_type, from_pandas=True)
+
+ if pa.types.is_duration(pa_array.type) and pa_array.null_count > 0:
+ # GH52843: upstream bug for duration types when originally
+ # constructed with data containing numpy NaT.
+ # https://github.com/apache/arrow/issues/35088
+ arr = cls(pa_array)
+ arr = arr.fillna(arr.dtype.na_value)
+ pa_array = arr._pa_array
+
+ if pa_type is not None and pa_array.type != pa_type:
+ if pa.types.is_dictionary(pa_type):
+ pa_array = pa_array.dictionary_encode()
+ else:
+ pa_array = pa_array.cast(pa_type)
+
+ return pa_array
+
def __getitem__(self, item: PositionalIndexer):
"""Select a subset of self.
@@ -470,65 +588,50 @@ def __setstate__(self, state) -> None:
def _cmp_method(self, other, op):
pc_func = ARROW_CMP_FUNCS[op.__name__]
- if isinstance(other, ArrowExtensionArray):
- result = pc_func(self._pa_array, other._pa_array)
- elif isinstance(other, (np.ndarray, list)):
- result = pc_func(self._pa_array, other)
- elif isinstance(other, BaseMaskedArray):
- # GH 52625
- result = pc_func(self._pa_array, other.__arrow_array__())
- elif is_scalar(other):
- try:
- result = pc_func(self._pa_array, pa.scalar(other))
- except (pa.lib.ArrowNotImplementedError, pa.lib.ArrowInvalid):
+ try:
+ result = pc_func(self._pa_array, self._box_pa(other))
+ except (pa.lib.ArrowNotImplementedError, pa.lib.ArrowInvalid):
+ if is_scalar(other):
mask = isna(self) | isna(other)
valid = ~mask
result = np.zeros(len(self), dtype="bool")
result[valid] = op(np.array(self)[valid], other)
result = pa.array(result, type=pa.bool_())
result = pc.if_else(valid, result, None)
- else:
- raise NotImplementedError(
- f"{op.__name__} not implemented for {type(other)}"
- )
+ else:
+ raise NotImplementedError(
+ f"{op.__name__} not implemented for {type(other)}"
+ )
return ArrowExtensionArray(result)
def _evaluate_op_method(self, other, op, arrow_funcs):
pa_type = self._pa_array.type
+ other = self._box_pa(other)
+
if (pa.types.is_string(pa_type) or pa.types.is_binary(pa_type)) and op in [
operator.add,
roperator.radd,
]:
sep = pa.scalar("", type=pa_type)
- if isinstance(other, type(self)):
- other = other._pa_array
if op is operator.add:
result = pc.binary_join_element_wise(self._pa_array, other, sep)
else:
result = pc.binary_join_element_wise(other, self._pa_array, sep)
return type(self)(result)
+ if (
+ isinstance(other, pa.Scalar)
+ and pc.is_null(other).as_py()
+ and op.__name__ in ARROW_LOGICAL_FUNCS
+ ):
+ # pyarrow kleene ops require null to be typed
+ other = other.cast(pa_type)
+
pc_func = arrow_funcs[op.__name__]
if pc_func is NotImplemented:
raise NotImplementedError(f"{op.__name__} not implemented.")
- if isinstance(other, ArrowExtensionArray):
- result = pc_func(self._pa_array, other._pa_array)
- elif isinstance(other, (np.ndarray, list)):
- result = pc_func(self._pa_array, pa.array(other, from_pandas=True))
- elif isinstance(other, BaseMaskedArray):
- # GH 52625
- result = pc_func(self._pa_array, other.__arrow_array__())
- elif is_scalar(other):
- if isna(other) and op.__name__ in ARROW_LOGICAL_FUNCS:
- # pyarrow kleene ops require null to be typed
- pa_scalar = pa.scalar(None, type=self._pa_array.type)
- else:
- pa_scalar = pa.scalar(other)
- result = pc_func(self._pa_array, pa_scalar)
- else:
- raise NotImplementedError(
- f"{op.__name__} not implemented for {type(other)}"
- )
+
+ result = pc_func(self._pa_array, other)
return type(self)(result)
def _logical_method(self, other, op):
@@ -1610,16 +1713,8 @@ def _mode(self, dropna: bool = True) -> Self:
def _maybe_convert_setitem_value(self, value):
"""Maybe convert value to be pyarrow compatible."""
- if value is None:
- return value
- if isinstance(value, (pa.Scalar, pa.Array, pa.ChunkedArray)):
- return value
- if is_list_like(value):
- pa_box = pa.array
- else:
- pa_box = pa.scalar
try:
- value = pa_box(value, type=self._pa_array.type, from_pandas=True)
+ value = self._box_pa(value, self._pa_array.type)
except pa.ArrowTypeError as err:
msg = f"Invalid value '{str(value)}' for dtype {self.dtype}"
raise TypeError(msg) from err
diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py
index 1a729c204da58..9e5955da76d1c 100644
--- a/pandas/tests/extension/test_arrow.py
+++ b/pandas/tests/extension/test_arrow.py
@@ -1720,8 +1720,9 @@ def test_setitem_null_slice(data):
result = orig.copy()
result[:] = data[0]
- expected = ArrowExtensionArray(
- pa.array([data[0]] * len(data), type=data._pa_array.type)
+ expected = ArrowExtensionArray._from_sequence(
+ [data[0]] * len(data),
+ dtype=data._pa_array.type,
)
tm.assert_extension_array_equal(result, expected)
@@ -2934,3 +2935,76 @@ def test_infer_dtype_pyarrow_dtype(data, request):
request.node.add_marker(mark)
assert res == lib.infer_dtype(list(data), skipna=True)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_from_sequence_temporal(pa_type):
+ # GH 53171
+ val = 3
+ unit = pa_type.unit
+ if pa.types.is_duration(pa_type):
+ seq = [pd.Timedelta(val, unit=unit).as_unit(unit)]
+ else:
+ seq = [pd.Timestamp(val, unit=unit, tz=pa_type.tz).as_unit(unit)]
+
+ result = ArrowExtensionArray._from_sequence(seq, dtype=pa_type)
+ expected = ArrowExtensionArray(pa.array([val], type=pa_type))
+ tm.assert_extension_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_setitem_temporal(pa_type):
+ # GH 53171
+ unit = pa_type.unit
+ if pa.types.is_duration(pa_type):
+ val = pd.Timedelta(1, unit=unit).as_unit(unit)
+ else:
+ val = pd.Timestamp(1, unit=unit, tz=pa_type.tz).as_unit(unit)
+
+ arr = ArrowExtensionArray(pa.array([1, 2, 3], type=pa_type))
+
+ result = arr.copy()
+ result[:] = val
+ expected = ArrowExtensionArray(pa.array([1, 1, 1], type=pa_type))
+ tm.assert_extension_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_arithmetic_temporal(pa_type, request):
+ # GH 53171
+ if pa_version_under8p0 and pa.types.is_duration(pa_type):
+ mark = pytest.mark.xfail(
+ raises=pa.ArrowNotImplementedError,
+ reason="Function 'subtract_checked' has no kernel matching input types",
+ )
+ request.node.add_marker(mark)
+
+ arr = ArrowExtensionArray(pa.array([1, 2, 3], type=pa_type))
+ unit = pa_type.unit
+ result = arr - pd.Timedelta(1, unit=unit).as_unit(unit)
+ expected = ArrowExtensionArray(pa.array([0, 1, 2], type=pa_type))
+ tm.assert_extension_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES
+)
+def test_comparison_temporal(pa_type):
+ # GH 53171
+ unit = pa_type.unit
+ if pa.types.is_duration(pa_type):
+ val = pd.Timedelta(1, unit=unit).as_unit(unit)
+ else:
+ val = pd.Timestamp(1, unit=unit, tz=pa_type.tz).as_unit(unit)
+
+ arr = ArrowExtensionArray(pa.array([1, 2, 3], type=pa_type))
+
+ result = arr > val
+ expected = ArrowExtensionArray(pa.array([False, True, True], type=pa.bool_()))
+ tm.assert_extension_array_equal(result, expected)
| - [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/v2.1.0.rst` file if fixing a bug or adding a new feature.
Fixes a few bugs related to non-nanosecond units for pyarrow duration and timestamp types.
The underlying issue is upstream (https://github.com/apache/arrow/issues/33321) where pyarrow does not handle pandas `Timedelta` and `Timestamp` non-nano units correctly.
Example (1 seconds -> 0 seconds):
```
In [1]: import pandas as pd
In [2]: import pyarrow as pa
In [3]: td = pd.Timedelta(1, unit="s").as_unit("s")
In [4]: pa.scalar(td, type=pa.duration("s"))
Out[4]: <pyarrow.DurationScalar: datetime.timedelta(0)>
In [5]: pa.array([td], type=pa.duration("s"))
Out[5]:
<pyarrow.lib.DurationArray object at 0x10751d120>
[
0
]
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/53171 | 2023-05-10T22:02:22Z | 2023-05-16T00:04:47Z | 2023-05-16T00:04:47Z | 2023-05-30T22:16:27Z |
Switch to setup-micromamba | diff --git a/.github/actions/setup-conda/action.yml b/.github/actions/setup-conda/action.yml
index 700197e400c5f..84e81b9a9297f 100644
--- a/.github/actions/setup-conda/action.yml
+++ b/.github/actions/setup-conda/action.yml
@@ -3,23 +3,14 @@ inputs:
environment-file:
description: Conda environment file to use.
default: environment.yml
- environment-name:
- description: Name to use for the Conda environment
- default: test
- extra-specs:
- description: Extra packages to install
- required: false
runs:
using: composite
steps:
- name: Install ${{ inputs.environment-file }}
- uses: mamba-org/provision-with-micromamba@v15
+ uses: mamba-org/setup-micromamba@v1
with:
environment-file: ${{ inputs.environment-file }}
- environment-name: ${{ inputs.environment-name }}
- extra-specs: ${{ inputs.extra-specs }}
- channels: conda-forge
- channel-priority: 'strict'
+ environment-name: test
condarc-file: ci/condarc.yml
- cache-env: true
+ cache-environment: true
cache-downloads: true
diff --git a/.github/workflows/package-checks.yml b/.github/workflows/package-checks.yml
index db25719a016fd..0f3d4fce66282 100644
--- a/.github/workflows/package-checks.yml
+++ b/.github/workflows/package-checks.yml
@@ -67,17 +67,15 @@ jobs:
fetch-depth: 0
- name: Set up Python
- uses: mamba-org/provision-with-micromamba@v15
+ uses: mamba-org/setup-micromamba@v1
with:
- environment-file: false
environment-name: recipe-test
- extra-specs: |
+ extra-specs: >-
python=${{ matrix.python-version }}
boa
conda-verify
- channels: conda-forge
cache-downloads: true
- cache-env: true
+ cache-environment: true
- name: Build conda package
run: conda mambabuild ci --no-anaconda-upload --verify --strict-verify --output --output-folder .
| We are deprecating `provision-with-micromamba` and replacing it with https://github.com/mamba-org/setup-micromamba.
- [ ] 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/53168 | 2023-05-10T15:55:04Z | 2023-05-12T17:24:27Z | 2023-05-12T17:24:27Z | 2023-05-12T17:48:06Z |
BUG: from_dataframe with empty objects | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 5b62883c2741e..a5e39dc999129 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -449,6 +449,7 @@ Metadata
Other
^^^^^
- Bug in :class:`FloatingArray.__contains__` with ``NaN`` item incorrectly returning ``False`` when ``NaN`` values are present (:issue:`52840`)
+- Bug in :func:`api.interchange.from_dataframe` when converting an empty DataFrame object (:issue:`53155`)
- 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/core/interchange/from_dataframe.py b/pandas/core/interchange/from_dataframe.py
index 78e530f915117..4b67659aa40fd 100644
--- a/pandas/core/interchange/from_dataframe.py
+++ b/pandas/core/interchange/from_dataframe.py
@@ -79,7 +79,9 @@ def _from_dataframe(df: DataFrameXchg, allow_copy: bool = True):
raise RuntimeError(
"To join chunks a copy is required which is forbidden by allow_copy=False"
)
- if len(pandas_dfs) == 1:
+ if not pandas_dfs:
+ pandas_df = protocol_df_chunk_to_pandas(df)
+ elif len(pandas_dfs) == 1:
pandas_df = pandas_dfs[0]
else:
pandas_df = pd.concat(pandas_dfs, axis=0, ignore_index=True, copy=False)
diff --git a/pandas/tests/interchange/test_impl.py b/pandas/tests/interchange/test_impl.py
index 606f1374a61ce..49873768ca952 100644
--- a/pandas/tests/interchange/test_impl.py
+++ b/pandas/tests/interchange/test_impl.py
@@ -272,3 +272,15 @@ def test_categorical_to_numpy_dlpack():
result = np.from_dlpack(col.get_buffers()["data"][0])
expected = np.array([0, 1, 0], dtype="int8")
tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("data", [{}, {"a": []}])
+def test_empty_pyarrow(data):
+ # GH 53155
+ pytest.importorskip("pyarrow", "11.0.0")
+ from pyarrow.interchange import from_dataframe as pa_from_dataframe
+
+ expected = pd.DataFrame(data)
+ arrow_df = pa_from_dataframe(expected)
+ result = from_dataframe(arrow_df)
+ tm.assert_frame_equal(result, expected)
| - [ ] closes #53155 (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/53161 | 2023-05-09T23:08:04Z | 2023-05-15T20:36:52Z | 2023-05-15T20:36:52Z | 2023-05-15T20:36:56Z |
BUG: SparseDtype requires numpy dtype | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 62d56f684a11d..64c8f06349449 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -423,6 +423,7 @@ Reshaping
Sparse
^^^^^^
+- Bug in :class:`SparseDtype` constructor failing to raise ``TypeError`` when given an incompatible ``dtype`` for its subtype, which must be a ``numpy`` dtype (:issue:`53160`)
- Bug in :meth:`arrays.SparseArray.map` allowed the fill value to be included in the sparse values (:issue:`52095`)
-
diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py
index dadd161ceeb38..5747ff807600d 100644
--- a/pandas/core/arrays/sparse/dtype.py
+++ b/pandas/core/arrays/sparse/dtype.py
@@ -91,6 +91,9 @@ def __init__(self, dtype: Dtype = np.float64, fill_value: Any = None) -> None:
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)
diff --git a/pandas/tests/arrays/sparse/test_astype.py b/pandas/tests/arrays/sparse/test_astype.py
index 86d69610059b3..d729a31668ade 100644
--- a/pandas/tests/arrays/sparse/test_astype.py
+++ b/pandas/tests/arrays/sparse/test_astype.py
@@ -3,11 +3,7 @@
from pandas._libs.sparse import IntIndex
-from pandas import (
- DataFrame,
- Series,
- Timestamp,
-)
+from pandas import Timestamp
import pandas._testing as tm
from pandas.core.arrays.sparse import (
SparseArray,
@@ -135,13 +131,3 @@ def test_astype_dt64_to_int64(self):
arr3 = SparseArray(values, dtype=dtype)
result3 = arr3.astype("int64")
tm.assert_numpy_array_equal(result3, expected)
-
-
-def test_dtype_sparse_with_fill_value_not_present_in_data():
- # GH 49987
- df = DataFrame([["a", 0], ["b", 1], ["b", 2]], columns=["A", "B"])
- result = df["A"].astype(SparseDtype("category", fill_value="c"))
- expected = Series(
- ["a", "b", "b"], name="A", dtype=SparseDtype("object", fill_value="c")
- )
- tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/arrays/sparse/test_dtype.py b/pandas/tests/arrays/sparse/test_dtype.py
index 58fedbd3e4231..88f8577ded5b0 100644
--- a/pandas/tests/arrays/sparse/test_dtype.py
+++ b/pandas/tests/arrays/sparse/test_dtype.py
@@ -207,3 +207,10 @@ def test_repr():
result = str(SparseDtype(object, fill_value="0"))
expected = "Sparse[object, '0']"
assert result == expected
+
+
+def test_sparse_dtype_subtype_must_be_numpy_dtype():
+ # GH#53160
+ msg = "SparseDtype subtype must be a numpy dtype"
+ with pytest.raises(TypeError, match=msg):
+ SparseDtype("category", fill_value="c")
| - [ ] 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.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53160 | 2023-05-09T23:02:07Z | 2023-05-11T00:57:22Z | 2023-05-11T00:57:22Z | 2023-05-11T01:55:54Z |
DOC: #53035 clarify the behavior of sep=None. | diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py
index 8b2a02f0ac63a..ad9e5b646371e 100644
--- a/pandas/io/parsers/readers.py
+++ b/pandas/io/parsers/readers.py
@@ -103,11 +103,12 @@
sep : str, default {_default_sep}
Delimiter to use. If sep is None, the C engine cannot automatically detect
the separator, but the Python parsing engine can, meaning the latter will
- be used and automatically detect the separator by Python's builtin sniffer
- tool, ``csv.Sniffer``. In addition, separators longer than 1 character and
- different from ``'\s+'`` will be interpreted as regular expressions and
- will also force the use of the Python parsing engine. Note that regex
- delimiters are prone to ignoring quoted data. Regex example: ``'\r\t'``.
+ be used and automatically detect the separator from only the first valid
+ row of the file by Python's builtin sniffer tool, ``csv.Sniffer``.
+ In addition, separators longer than 1 character and different from
+ ``'\s+'`` will be interpreted as regular expressions and will also force
+ the use of the Python parsing engine. Note that regex delimiters are prone
+ to ignoring quoted data. Regex example: ``'\r\t'``.
delimiter : str, default ``None``
Alias for sep.
header : int, list of int, None, default 'infer'
| Clarified that only the first valid line is used to detect the separator if sep=None in read_csv.
- [ ] closes #53035 (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/53153 | 2023-05-09T13:00:54Z | 2023-05-09T16:52:10Z | 2023-05-09T16:52:10Z | 2023-05-09T21:57:54Z |
PERF: Series.str.get for pyarrow-backed strings | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 281db2759b9f0..07cedda9f9009 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -292,6 +292,7 @@ Performance improvements
- Performance improvement in :meth:`DataFrame.loc` when selecting rows and columns (:issue:`53014`)
- Performance improvement in :meth:`Series.add` for pyarrow string and binary dtypes (:issue:`53150`)
- Performance improvement in :meth:`Series.corr` and :meth:`Series.cov` for extension dtypes (:issue:`52502`)
+- Performance improvement in :meth:`Series.str.get` for pyarrow-backed strings (:issue:`53152`)
- Performance improvement in :meth:`Series.to_numpy` when dtype is a numpy float dtype and ``na_value`` is ``np.nan`` (:issue:`52430`)
- Performance improvement in :meth:`~arrays.ArrowExtensionArray.to_numpy` (:issue:`52525`)
- Performance improvement when doing various reshaping operations on :class:`arrays.IntegerArrays` & :class:`arrays.FloatingArray` by avoiding doing unnecessary validation (:issue:`53013`)
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 53baf1e171254..d842e49589c4d 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -1902,8 +1902,8 @@ def _str_get(self, i: int):
selected = pc.utf8_slice_codeunits(
self._pa_array, start=start, stop=stop, step=step
)
- result = pa.array([None] * self._pa_array.length(), type=self._pa_array.type)
- result = pc.if_else(not_out_of_bounds, selected, result)
+ null_value = pa.scalar(None, type=self._pa_array.type)
+ result = pc.if_else(not_out_of_bounds, selected, null_value)
return type(self)(result)
def _str_join(self, sep: str):
| - [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/v2.1.0.rst` file if fixing a bug or adding a new feature.
```
import pandas as pd
import pandas._testing as tm
import pyarrow as pa
N = 1_000_000
ser = pd.Series(tm.makeStringIndex(N), dtype=pd.ArrowDtype(pa.string()))
%timeit ser.str.get(1)
# 70.1 ms Β± 3.13 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each) -> main
# 37.7 ms Β± 2.09 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each) -> PR
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/53152 | 2023-05-09T10:43:27Z | 2023-05-10T00:58:38Z | 2023-05-10T00:58:38Z | 2023-05-30T22:16:32Z |
PERF: Series.add for pyarrow string/binary dtypes | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 258c14cec7925..295f0367e4c16 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -289,6 +289,7 @@ Performance improvements
- 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.add` for pyarrow string and binary dtypes (:issue:`53150`)
- 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`)
- Performance improvement in :meth:`~arrays.ArrowExtensionArray.to_numpy` (:issue:`52525`)
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index 4d62f680811ae..53baf1e171254 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -495,22 +495,13 @@ def _evaluate_op_method(self, other, op, arrow_funcs):
operator.add,
roperator.radd,
]:
- length = self._pa_array.length()
-
- seps: list[str] | list[bytes]
- if pa.types.is_string(pa_type):
- seps = [""] * length
- else:
- seps = [b""] * length
-
- if is_scalar(other):
- other = [other] * length
- elif isinstance(other, type(self)):
+ sep = pa.scalar("", type=pa_type)
+ if isinstance(other, type(self)):
other = other._pa_array
if op is operator.add:
- result = pc.binary_join_element_wise(self._pa_array, other, seps)
+ result = pc.binary_join_element_wise(self._pa_array, other, sep)
else:
- result = pc.binary_join_element_wise(other, self._pa_array, seps)
+ result = pc.binary_join_element_wise(other, self._pa_array, sep)
return type(self)(result)
pc_func = arrow_funcs[op.__name__]
| - [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/v2.1.0.rst` file if fixing a bug or adding a new feature.
```
import pandas as pd
import pandas._testing as tm
import pyarrow as pa
N = 1_000_000
s1 = pd.Series(tm.makeStringIndex(N), dtype=pd.ArrowDtype(pa.string()))
s2 = pd.Series(tm.makeStringIndex(N), dtype=pd.ArrowDtype(pa.string()))
%timeit s1 + s2
# 136 ms Β± 3.25 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each) -> main
# 61 ms Β± 2.86 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each) -> PR
%timeit s1 + "abc"
# 200 ms Β± 12.2 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each) -> main
# 64.5 ms Β± 2.95 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each) -> PR
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/53150 | 2023-05-09T00:44:40Z | 2023-05-09T16:53:37Z | 2023-05-09T16:53:37Z | 2023-05-30T22:16:33Z |
Backport PR #53027 on branch 2.0.x (CI: Add job to validate conda-forge meta.yaml) | diff --git a/.github/workflows/package-checks.yml b/.github/workflows/package-checks.yml
index fa1b5e5d4fba3..6f1fa771a7854 100644
--- a/.github/workflows/package-checks.yml
+++ b/.github/workflows/package-checks.yml
@@ -14,6 +14,10 @@ on:
permissions:
contents: read
+defaults:
+ run:
+ shell: bash -el {0}
+
jobs:
pip:
if: ${{ github.event.label.name == 'Build' || contains(github.event.pull_request.labels.*.name, 'Build') || github.event_name == 'push'}}
@@ -44,9 +48,39 @@ jobs:
run: |
python -m pip install --upgrade pip setuptools wheel python-dateutil pytz numpy cython
python -m pip install versioneer[toml]
- shell: bash -el {0}
- name: Pip install with extra
- run: |
- python -m pip install -e .[${{ matrix.extra }}] --no-build-isolation
- shell: bash -el {0}
+ run: python -m pip install -e .[${{ matrix.extra }}] --no-build-isolation
+ conda_forge_recipe:
+ if: ${{ github.event.label.name == 'Build' || contains(github.event.pull_request.labels.*.name, 'Build') || github.event_name == 'push'}}
+ runs-on: ubuntu-22.04
+ strategy:
+ matrix:
+ python-version: ['3.9', '3.10', '3.11']
+ fail-fast: false
+ name: Test Conda Forge Recipe - Python ${{ matrix.python-version }}
+ concurrency:
+ # https://github.community/t/concurrecy-not-work-for-push/183068/7
+ group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-conda-forge-recipe-${{ matrix.python-version }}
+ cancel-in-progress: true
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
+
+ - name: Set up Python
+ uses: mamba-org/provision-with-micromamba@v15
+ with:
+ environment-file: false
+ environment-name: recipe-test
+ extra-specs: |
+ python=${{ matrix.python-version }}
+ boa
+ conda-verify
+ channels: conda-forge
+ cache-downloads: true
+ cache-env: true
+
+ - name: Build conda package
+ run: conda mambabuild ci --no-anaconda-upload --verify --strict-verify --output --output-folder .
diff --git a/ci/meta.yaml b/ci/meta.yaml
new file mode 100644
index 0000000000000..f02c7eec001fc
--- /dev/null
+++ b/ci/meta.yaml
@@ -0,0 +1,93 @@
+{% set version = "2.0.1" %}
+
+package:
+ name: pandas
+ version: {{ version }}
+
+source:
+ git_url: ../..
+
+build:
+ number: 1
+ script:
+ - export PYTHONUNBUFFERED=1 # [ppc64le]
+ - {{ PYTHON }} -m pip install -vv --no-deps --ignore-installed . # [not unix]
+ - {{ PYTHON }} -m pip install -vv --no-deps --ignore-installed . --global-option="build_ext" --global-option="-j4" --no-use-pep517 # [unix]
+ skip: true # [py<39]
+
+requirements:
+ build:
+ - python # [build_platform != target_platform]
+ - cross-python_{{ target_platform }} # [build_platform != target_platform]
+ - cython # [build_platform != target_platform]
+ - numpy # [build_platform != target_platform]
+ - {{ compiler('c') }}
+ - {{ compiler('cxx') }}
+ host:
+ - python
+ - pip
+ - setuptools >=61.0.0
+ - cython >=0.29.33,<3
+ - numpy >=1.21.6 # [py<311]
+ - numpy >=1.23.2 # [py>=311]
+ - versioneer
+ - tomli # [py<311]
+ run:
+ - python
+ - {{ pin_compatible('numpy') }}
+ - python-dateutil >=2.8.2
+ - pytz >=2020.1
+ - python-tzdata >=2022.1
+
+test:
+ imports:
+ - pandas
+ commands:
+ - pip check
+ # Skip test suite on PyPy as it segfaults there
+ # xref: https://github.com/conda-forge/pandas-feedstock/issues/148
+ #
+ # Also skip `test_rolling_var_numerical_issues` on `ppc64le` as it is a known test failure.
+ # xref: https://github.com/conda-forge/pandas-feedstock/issues/149
+ {% set markers = ["not clipboard", "not single_cpu", "not db", "not network", "not slow"] %}
+ {% set markers = markers + ["not arm_slow"] %} # [aarch64 or ppc64le]
+ {% set extra_args = ["-n=2 -m " + " and ".join(markers)] %}
+ {% set tests_to_skip = "_not_a_real_test" %}
+ {% set tests_to_skip = tests_to_skip + " or test_rolling_var_numerical_issues" %} # [ppc64le]
+ {% set tests_to_skip = tests_to_skip + " or test_std_timedelta64_skipna_false" %} # [ppc64le]
+ {% set tests_to_skip = tests_to_skip + " or test_value_counts_normalized[M8[ns]]" %} # [ppc64le]
+ {% set tests_to_skip = tests_to_skip + " or test_to_datetime_format_YYYYMMDD_with_nat" %} # [ppc64le]
+ {% set tests_to_skip = tests_to_skip + " or (TestReductions and test_median_2d)" %} # [ppc64le]
+ {% set extra_args = extra_args + ["-k", "not (" + tests_to_skip + ")"] %}
+ - python -c "import pandas; pandas.test(extra_args={{ extra_args }})" # [python_impl == "cpython"]
+ requires:
+ - pip
+ - pytest >=7.0.0
+ - pytest-asyncio >=0.17.0
+ - pytest-xdist >=2.2.0
+ - pytest-cov
+ - hypothesis >=6.46.1
+ - tomli # [py<311]
+
+about:
+ home: http://pandas.pydata.org
+ license: BSD-3-Clause
+ license_file: LICENSE
+ summary: Powerful data structures for data analysis, time series, and statistics
+ doc_url: https://pandas.pydata.org/docs/
+ dev_url: https://github.com/pandas-dev/pandas
+
+extra:
+ recipe-maintainers:
+ - jreback
+ - jorisvandenbossche
+ - msarahan
+ - ocefpaf
+ - TomAugspurger
+ - WillAyd
+ - simonjayhawkins
+ - mroeschke
+ - datapythonista
+ - phofl
+ - lithomas1
+ - marcogorelli
| Backport PR #53027: CI: Add job to validate conda-forge meta.yaml | https://api.github.com/repos/pandas-dev/pandas/pulls/53146 | 2023-05-08T22:45:35Z | 2023-05-09T00:10:23Z | 2023-05-09T00:10:23Z | 2023-05-09T00:10:24Z |
MNT: Add support of Cython 3 master | diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index ae1d20ca4e225..a45299c8ba896 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -303,19 +303,19 @@ PandasParser_IMPORT
# cdef extern'ed declarations seem to leave behind an undefined symbol
cdef double xstrtod_wrapper(const char *p, char **q, char decimal,
char sci, char tsep, int skip_trailing,
- int *error, int *maybe_int) nogil:
+ int *error, int *maybe_int) noexcept nogil:
return xstrtod(p, q, decimal, sci, tsep, skip_trailing, error, maybe_int)
cdef double precise_xstrtod_wrapper(const char *p, char **q, char decimal,
char sci, char tsep, int skip_trailing,
- int *error, int *maybe_int) nogil:
+ int *error, int *maybe_int) noexcept nogil:
return precise_xstrtod(p, q, decimal, sci, tsep, skip_trailing, error, maybe_int)
cdef double round_trip_wrapper(const char *p, char **q, char decimal,
char sci, char tsep, int skip_trailing,
- int *error, int *maybe_int) nogil:
+ int *error, int *maybe_int) noexcept nogil:
return round_trip(p, q, decimal, sci, tsep, skip_trailing, error, maybe_int)
| - [ ] 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.
This PR adds support for Cython 3 master after PR https://github.com/cython/cython/pull/5386. This PR requires Cython >= 0.29.31 or Cython >= 3.0b3. See https://github.com/pandas-dev/pandas/issues/53125#issuecomment-1539086575 for details.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53145 | 2023-05-08T22:07:05Z | 2023-05-09T16:59:00Z | 2023-05-09T16:59:00Z | 2023-05-09T17:25:16Z |
MNT: Explicitly set cdef functions as noexcept | diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx
index 406b1a0f1f807..c62e60b7cdaa0 100644
--- a/pandas/_libs/groupby.pyx
+++ b/pandas/_libs/groupby.pyx
@@ -1360,7 +1360,7 @@ cdef inline void _check_below_mincount(
int64_t[:, ::1] nobs,
int64_t min_count,
mincount_t[:, ::1] resx,
-) nogil:
+) noexcept nogil:
"""
Check if the number of observations for a group is below min_count,
and if so set the result for that group to the appropriate NA-like value.
diff --git a/pandas/_libs/hashing.pyx b/pandas/_libs/hashing.pyx
index 9f01b38b758bd..8cc20a6503176 100644
--- a/pandas/_libs/hashing.pyx
+++ b/pandas/_libs/hashing.pyx
@@ -126,7 +126,7 @@ cdef uint64_t u8to64_le(uint8_t* p) nogil:
cdef void _sipround(uint64_t* v0, uint64_t* v1,
- uint64_t* v2, uint64_t* v3) nogil:
+ uint64_t* v2, uint64_t* v3) noexcept nogil:
v0[0] += v1[0]
v1[0] = _rotl(v1[0], 13)
v1[0] ^= v0[0]
diff --git a/pandas/_libs/hashtable.pxd b/pandas/_libs/hashtable.pxd
index 6f66884ac8206..eaec9e8462450 100644
--- a/pandas/_libs/hashtable.pxd
+++ b/pandas/_libs/hashtable.pxd
@@ -185,5 +185,5 @@ cdef class Int64Vector(Vector):
cdef resize(self)
cpdef ndarray to_array(self)
- cdef void append(self, int64_t x)
+ cdef void append(self, int64_t x) noexcept
cdef extend(self, int64_t[:] x)
diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in
index d4d3117a32ac9..de332d95cf594 100644
--- a/pandas/_libs/hashtable_class_helper.pxi.in
+++ b/pandas/_libs/hashtable_class_helper.pxi.in
@@ -141,7 +141,7 @@ ctypedef struct {{name}}VectorData:
@cython.wraparound(False)
@cython.boundscheck(False)
cdef void append_data_{{dtype}}({{name}}VectorData *data,
- {{c_type}} x) nogil:
+ {{c_type}} x) noexcept nogil:
data.data[data.n] = x
data.n += 1
@@ -241,7 +241,7 @@ cdef class {{name}}Vector(Vector):
self.external_view_exists = True
return self.ao
- cdef void append(self, {{c_type}} x):
+ cdef void append(self, {{c_type}} x) noexcept:
if needs_resize(self.data):
if self.external_view_exists:
@@ -311,7 +311,7 @@ cdef class StringVector(Vector):
self.data.m = self.data.n
return ao
- cdef void append(self, char *x):
+ cdef void append(self, char *x) noexcept:
if needs_resize(self.data):
self.resize()
diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx
index 2b3b147470cef..c49eaa3d619bd 100644
--- a/pandas/_libs/join.pyx
+++ b/pandas/_libs/join.pyx
@@ -213,7 +213,7 @@ def full_outer_join(const intp_t[:] left, const intp_t[:] right,
@cython.wraparound(False)
@cython.boundscheck(False)
-cdef void _get_result_indexer(intp_t[::1] sorter, intp_t[::1] indexer) nogil:
+cdef void _get_result_indexer(intp_t[::1] sorter, intp_t[::1] indexer) noexcept nogil:
"""NOTE: overwrites indexer with the result to avoid allocating another array"""
cdef:
Py_ssize_t i, n, idx
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index 1b20ffbe52493..57b7754b08289 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -595,7 +595,7 @@ cdef check_overflows(_TSObject obj, NPY_DATETIMEUNIT reso=NPY_FR_ns):
# ----------------------------------------------------------------------
# Localization
-cdef void _localize_tso(_TSObject obj, tzinfo tz, NPY_DATETIMEUNIT reso):
+cdef void _localize_tso(_TSObject obj, tzinfo tz, NPY_DATETIMEUNIT reso) noexcept:
"""
Given the UTC nanosecond timestamp in obj.value, find the wall-clock
representation of that timestamp in the given timezone.
diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd
index 7e19eb084b59e..6d2d625638231 100644
--- a/pandas/_libs/tslibs/np_datetime.pxd
+++ b/pandas/_libs/tslibs/np_datetime.pxd
@@ -80,7 +80,7 @@ cdef extern from "src/datetime/pd_datetime.h":
INFER_FORMAT
# You must call this before using the PandasDateTime CAPI functions
-cdef inline void import_pandas_datetime():
+cdef inline void import_pandas_datetime() noexcept:
PandasDateTime_IMPORT
cdef bint cmp_scalar(int64_t lhs, int64_t rhs, int op) except -1
@@ -90,11 +90,11 @@ cdef check_dts_bounds(npy_datetimestruct *dts, NPY_DATETIMEUNIT unit=?)
cdef int64_t pydatetime_to_dt64(
datetime val, npy_datetimestruct *dts, NPY_DATETIMEUNIT reso=?
)
-cdef void pydatetime_to_dtstruct(datetime dt, npy_datetimestruct *dts)
+cdef void pydatetime_to_dtstruct(datetime dt, npy_datetimestruct *dts) noexcept
cdef int64_t pydate_to_dt64(
date val, npy_datetimestruct *dts, NPY_DATETIMEUNIT reso=?
)
-cdef void pydate_to_dtstruct(date val, npy_datetimestruct *dts)
+cdef void pydate_to_dtstruct(date val, npy_datetimestruct *dts) noexcept
cdef npy_datetime get_datetime64_value(object obj) nogil
cdef npy_timedelta get_timedelta64_value(object obj) nogil
diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx
index 9980f28541201..e24a70c3d2b69 100644
--- a/pandas/_libs/tslibs/np_datetime.pyx
+++ b/pandas/_libs/tslibs/np_datetime.pyx
@@ -229,7 +229,7 @@ def py_td64_to_tdstruct(int64_t td64, NPY_DATETIMEUNIT unit):
return tds # <- returned as a dict to python
-cdef void pydatetime_to_dtstruct(datetime dt, npy_datetimestruct *dts):
+cdef void pydatetime_to_dtstruct(datetime dt, npy_datetimestruct *dts) noexcept:
if PyDateTime_CheckExact(dt):
dts.year = PyDateTime_GET_YEAR(dt)
else:
@@ -256,7 +256,7 @@ cdef int64_t pydatetime_to_dt64(datetime val,
return npy_datetimestruct_to_datetime(reso, dts)
-cdef void pydate_to_dtstruct(date val, npy_datetimestruct *dts):
+cdef void pydate_to_dtstruct(date val, npy_datetimestruct *dts) noexcept:
dts.year = PyDateTime_GET_YEAR(val)
dts.month = PyDateTime_GET_MONTH(val)
dts.day = PyDateTime_GET_DAY(val)
diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx
index 880ac70b39265..0cf03ecf34c41 100644
--- a/pandas/_libs/tslibs/parsing.pyx
+++ b/pandas/_libs/tslibs/parsing.pyx
@@ -1052,7 +1052,7 @@ cdef str _fill_token(token: str, padding: int):
return token_filled
-cdef void _maybe_warn_about_dayfirst(format: str, bint dayfirst):
+cdef void _maybe_warn_about_dayfirst(format: str, bint dayfirst) noexcept:
"""Warn if guessed datetime format doesn't respect dayfirst argument."""
cdef:
int day_index = format.find("%d")
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index d6bd25851be74..7f54765ddbab5 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -691,7 +691,7 @@ cdef int get_freq_group_index(int freq) nogil:
return freq // 1000
-cdef void adjust_dts_for_month(npy_datetimestruct* dts, int from_end) nogil:
+cdef void adjust_dts_for_month(npy_datetimestruct* dts, int from_end) noexcept nogil:
if from_end != 12:
dts.month += from_end
if dts.month > 12:
@@ -700,7 +700,7 @@ cdef void adjust_dts_for_month(npy_datetimestruct* dts, int from_end) nogil:
dts.year -= 1
-cdef void adjust_dts_for_qtr(npy_datetimestruct* dts, int to_end) nogil:
+cdef void adjust_dts_for_qtr(npy_datetimestruct* dts, int to_end) noexcept nogil:
if to_end != 12:
dts.month -= to_end
if dts.month <= 0:
@@ -803,7 +803,8 @@ cdef int64_t get_period_ordinal(npy_datetimestruct *dts, int freq) nogil:
return npy_datetimestruct_to_datetime(unit, dts)
-cdef void get_date_info(int64_t ordinal, int freq, npy_datetimestruct *dts) nogil:
+cdef void get_date_info(int64_t ordinal,
+ int freq, npy_datetimestruct *dts) noexcept nogil:
cdef:
int64_t unix_date, nanos
npy_datetimestruct dts2
@@ -985,7 +986,7 @@ def periodarr_to_dt64arr(const int64_t[:] periodarr, int freq):
cdef void get_asfreq_info(int from_freq, int to_freq,
- bint is_end, asfreq_info *af_info) nogil:
+ bint is_end, asfreq_info *af_info) noexcept nogil:
"""
Construct the `asfreq_info` object used to convert an ordinal from
`from_freq` to `to_freq`.
@@ -1084,7 +1085,7 @@ cdef void _period_asfreq(
int freq2,
bint end,
Py_ssize_t increment=1,
-):
+) noexcept:
"""See period_asfreq.__doc__"""
cdef:
Py_ssize_t i
diff --git a/pandas/_libs/tslibs/util.pxd b/pandas/_libs/tslibs/util.pxd
index 243c65a6e516e..e25e7e8b94e1d 100644
--- a/pandas/_libs/tslibs/util.pxd
+++ b/pandas/_libs/tslibs/util.pxd
@@ -44,14 +44,14 @@ cdef extern from "numpy/npy_common.h":
int64_t NPY_MIN_INT64
-cdef inline int64_t get_nat():
+cdef inline int64_t get_nat() noexcept:
return NPY_MIN_INT64
# --------------------------------------------------------------------
# Type Checking
-cdef inline bint is_integer_object(object obj) nogil:
+cdef inline bint is_integer_object(object obj) noexcept nogil:
"""
Cython equivalent of
@@ -73,7 +73,7 @@ cdef inline bint is_integer_object(object obj) nogil:
and not is_timedelta64_object(obj))
-cdef inline bint is_float_object(object obj) nogil:
+cdef inline bint is_float_object(object obj) noexcept nogil:
"""
Cython equivalent of `isinstance(val, (float, np.float_))`
@@ -89,7 +89,7 @@ cdef inline bint is_float_object(object obj) nogil:
(PyObject_TypeCheck(obj, &PyFloatingArrType_Type)))
-cdef inline bint is_complex_object(object obj) nogil:
+cdef inline bint is_complex_object(object obj) noexcept nogil:
"""
Cython equivalent of `isinstance(val, (complex, np.complex_))`
@@ -105,7 +105,7 @@ cdef inline bint is_complex_object(object obj) nogil:
PyObject_TypeCheck(obj, &PyComplexFloatingArrType_Type))
-cdef inline bint is_bool_object(object obj) nogil:
+cdef inline bint is_bool_object(object obj) noexcept nogil:
"""
Cython equivalent of `isinstance(val, (bool, np.bool_))`
@@ -121,11 +121,11 @@ cdef inline bint is_bool_object(object obj) nogil:
PyObject_TypeCheck(obj, &PyBoolArrType_Type))
-cdef inline bint is_real_number_object(object obj) nogil:
+cdef inline bint is_real_number_object(object obj) noexcept nogil:
return is_bool_object(obj) or is_integer_object(obj) or is_float_object(obj)
-cdef inline bint is_timedelta64_object(object obj) nogil:
+cdef inline bint is_timedelta64_object(object obj) noexcept nogil:
"""
Cython equivalent of `isinstance(val, np.timedelta64)`
@@ -140,7 +140,7 @@ cdef inline bint is_timedelta64_object(object obj) nogil:
return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type)
-cdef inline bint is_datetime64_object(object obj) nogil:
+cdef inline bint is_datetime64_object(object obj) noexcept nogil:
"""
Cython equivalent of `isinstance(val, np.datetime64)`
@@ -155,7 +155,7 @@ cdef inline bint is_datetime64_object(object obj) nogil:
return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type)
-cdef inline bint is_array(object val):
+cdef inline bint is_array(object val) noexcept:
"""
Cython equivalent of `isinstance(val, np.ndarray)`
@@ -217,11 +217,11 @@ cdef inline const char* get_c_string(str py_string) except NULL:
return get_c_string_buf_and_size(py_string, NULL)
-cdef inline bytes string_encode_locale(str py_string):
+cdef inline bytes string_encode_locale(str py_string) noexcept:
"""As opposed to PyUnicode_Encode, use current system locale to encode."""
return PyUnicode_EncodeLocale(py_string, NULL)
-cdef inline object char_to_string_locale(const char* data):
+cdef inline object char_to_string_locale(const char* data) noexcept:
"""As opposed to PyUnicode_FromString, use current system locale to decode."""
return PyUnicode_DecodeLocale(data, NULL)
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index 511df25c3a87f..ef05b00a994a7 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -89,7 +89,7 @@ cdef float64_t calc_sum(int64_t minp, int64_t nobs, float64_t sum_x,
cdef void add_sum(float64_t val, int64_t *nobs, float64_t *sum_x,
float64_t *compensation, int64_t *num_consecutive_same_value,
- float64_t *prev_value) nogil:
+ float64_t *prev_value) noexcept nogil:
""" add a value from the sum calc using Kahan summation """
cdef:
| - [ ] 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.
This PR marks functions returning `void` as `noexcept` to avoid checking an exception after every function call. `inline` functions are marked too to avoid unnecessary overhead. The improvement is only in Cython 3. In Cython 0.29.X `noexcept` keyword is ignored. See https://github.com/pandas-dev/pandas/issues/53125#issuecomment-1539086575 for details. | https://api.github.com/repos/pandas-dev/pandas/pulls/53144 | 2023-05-08T21:40:48Z | 2023-05-09T16:59:36Z | 2023-05-09T16:59:36Z | 2023-05-13T18:04:48Z |
BUG: Setting frame into df with dup cols loses dtypes | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 258c14cec7925..2d505cd7a2ed1 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -361,7 +361,7 @@ Interval
Indexing
^^^^^^^^
--
+- Bug in :meth:`DataFrame.__setitem__` losing dtype when setting a :class:`DataFrame` into duplicated columns (:issue:`53143`)
-
Missing
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 56c58bc9347e0..485cc9db5ffe7 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4101,10 +4101,15 @@ def _set_item_frame_value(self, key, value: DataFrame) -> None:
self[cols] = value[value.columns[0]]
return
- # now align rows
- arraylike, _ = _reindex_for_setitem(value, self.index)
- self._set_item_mgr(key, arraylike)
- return
+ locs: np.ndarray | list
+ if isinstance(loc, slice):
+ locs = np.arange(loc.start, loc.stop, loc.step)
+ elif is_scalar(loc):
+ locs = [loc]
+ else:
+ locs = loc.nonzero()[0]
+
+ return self.isetitem(locs, value)
if len(value.columns) != 1:
raise ValueError(
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index a51955548232b..af3632bffe948 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -1283,3 +1283,19 @@ def test_setitem_iloc_with_numpy_array(self, dtype):
expected = DataFrame({"a": [2, 1, 1]}, dtype=dtype)
tm.assert_frame_equal(df, expected)
+
+ def test_setitem_frame_dup_cols_dtype(self):
+ # GH#53143
+ df = DataFrame([[1, 2, 3, 4], [4, 5, 6, 7]], columns=["a", "b", "a", "c"])
+ rhs = DataFrame([[0, 1.5], [2, 2.5]], columns=["a", "a"])
+ df["a"] = rhs
+ expected = DataFrame(
+ [[0, 2, 1.5, 4], [2, 5, 2.5, 7]], columns=["a", "b", "a", "c"]
+ )
+ tm.assert_frame_equal(df, expected)
+
+ df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"])
+ rhs = DataFrame([[0, 1.5], [2, 2.5]], columns=["a", "a"])
+ df["a"] = rhs
+ expected = DataFrame([[0, 1.5, 3], [2, 2.5, 6]], columns=["a", "a", "b"])
+ tm.assert_frame_equal(df, expected)
| - [ ] 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/53143 | 2023-05-08T20:11:30Z | 2023-05-09T23:09:40Z | 2023-05-09T23:09:40Z | 2023-05-10T05:40:32Z |
CLN: Cleanup after CoW setitem PRs | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index a949ec808c5cd..762f41b4049c2 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -14,10 +14,12 @@ including other versions of pandas.
Enhancements
~~~~~~~~~~~~
-.. _whatsnew_210.enhancements.enhancement1:
+.. _whatsnew_210.enhancements.cow:
-enhancement1
-^^^^^^^^^^^^
+Copy-on-Write improvements
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+- Setting a :class:`Series` into a :class:`DataFrame` now creates a lazy instead of a deep copy (:issue:`53142`)
.. _whatsnew_210.enhancements.enhancement2:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 3e6c89139d06d..bf91a52163569 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3915,7 +3915,6 @@ def isetitem(self, loc, value) -> None:
In cases where ``frame.columns`` is unique, this is equivalent to
``frame[frame.columns[i]] = value``.
"""
- using_cow = using_copy_on_write()
if isinstance(value, DataFrame):
if is_integer(loc):
loc = [loc]
@@ -3927,13 +3926,11 @@ def isetitem(self, loc, value) -> None:
)
for i, idx in enumerate(loc):
- arraylike, refs = self._sanitize_column(
- value.iloc[:, i], using_cow=using_cow
- )
+ arraylike, refs = self._sanitize_column(value.iloc[:, i])
self._iset_item_mgr(idx, arraylike, inplace=False, refs=refs)
return
- arraylike, refs = self._sanitize_column(value, using_cow=using_cow)
+ arraylike, refs = self._sanitize_column(value)
self._iset_item_mgr(loc, arraylike, inplace=False, refs=refs)
def __setitem__(self, key, value):
@@ -4170,7 +4167,7 @@ def _set_item(self, key, value) -> None:
Series/TimeSeries will be conformed to the DataFrames index to
ensure homogeneity.
"""
- value, refs = self._sanitize_column(value, using_cow=using_copy_on_write())
+ value, refs = self._sanitize_column(value)
if (
key in self.columns
@@ -4813,7 +4810,7 @@ def insert(
elif isinstance(value, DataFrame):
value = value.iloc[:, 0]
- value, refs = self._sanitize_column(value, using_cow=using_copy_on_write())
+ value, refs = self._sanitize_column(value)
self._mgr.insert(loc, column, value, refs=refs)
def assign(self, **kwargs) -> DataFrame:
@@ -4884,9 +4881,7 @@ def assign(self, **kwargs) -> DataFrame:
data[k] = com.apply_if_callable(v, data)
return data
- def _sanitize_column(
- self, value, using_cow: bool = False
- ) -> tuple[ArrayLike, BlockValuesRefs | None]:
+ def _sanitize_column(self, value) -> tuple[ArrayLike, BlockValuesRefs | None]:
"""
Ensures new columns (which go into the BlockManager as new blocks) are
always copied (or a reference is being tracked to them under CoW)
@@ -4907,7 +4902,7 @@ def _sanitize_column(
if is_dict_like(value):
if not isinstance(value, Series):
value = Series(value)
- return _reindex_for_setitem(value, self.index, using_cow=using_cow)
+ return _reindex_for_setitem(value, self.index)
if is_list_like(value):
com.require_length_match(value, self.index)
@@ -11923,12 +11918,12 @@ def _from_nested_dict(data) -> collections.defaultdict:
def _reindex_for_setitem(
- value: DataFrame | Series, index: Index, using_cow: bool = False
+ value: DataFrame | Series, index: Index
) -> tuple[ArrayLike, BlockValuesRefs | None]:
# reindex if necessary
if value.index.equals(index) or not len(index):
- if using_cow and isinstance(value, Series):
+ if using_copy_on_write() and isinstance(value, Series):
return value._values, value._references
return value._values.copy(), None
| - [ ] 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.
Follow-up on https://github.com/pandas-dev/pandas/pull/51698 and linked PRs | https://api.github.com/repos/pandas-dev/pandas/pulls/53142 | 2023-05-08T19:54:44Z | 2023-06-09T13:48:17Z | 2023-06-09T13:48:17Z | 2023-06-12T06:00:41Z |
DOC: Move whatsnew after backport | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index c234de3e3b3ae..0d6647dc38b3c 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -28,6 +28,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 :func:`to_timedelta` was raising ``ValueError`` with ``pandas.NA`` (:issue:`52909`)
+- Bug in :meth:`DataFrame.__getitem__` not preserving dtypes for :class:`MultiIndex` partial keys (:issue:`51895`)
- 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/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 258c14cec7925..62d56f684a11d 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -371,7 +371,6 @@ Missing
MultiIndex
^^^^^^^^^^
-- Bug in :meth:`DataFrame.__getitem__` not preserving dtypes for :class:`MultiIndex` partial keys (:issue:`51895`)
- Bug in :meth:`MultiIndex.set_levels` not preserving dtypes for :class:`Categorical` (:issue:`52125`)
I/O
| - [ ] 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/53141 | 2023-05-08T19:48:02Z | 2023-05-09T14:02:51Z | 2023-05-09T14:02:51Z | 2023-05-09T14:03:09Z |
CI: Address non-failing warnings in CI jobs | diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml
index 6831eaba9e3fa..bec07c077ad59 100644
--- a/.github/workflows/unit-tests.yml
+++ b/.github/workflows/unit-tests.yml
@@ -232,7 +232,7 @@ jobs:
python -m pip install -U pip wheel setuptools meson[ninja]==1.0.1 meson-python==0.13.1
python -m pip install --no-cache-dir versioneer[toml] cython numpy python-dateutil pytz pytest>=7.0.0 pytest-xdist>=2.2.0 pytest-asyncio>=0.17 hypothesis>=6.46.1
python -m pip install --no-cache-dir --no-build-isolation -e .
- python -m pip list
+ python -m pip list --no-cache-dir
export PANDAS_CI=1
python -m pytest -m 'not slow and not network and not clipboard and not single_cpu' pandas --junitxml=test-data.xml
concurrency:
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index f69c9f9606c60..e3ebdb859319a 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -83,6 +83,7 @@ repos:
hooks:
- id: pylint
stages: [manual]
+ args: [--load-plugins=pylint.extensions.redefined_loop_name]
- id: pylint
alias: redefined-outer-name
name: Redefining name from outer scope
diff --git a/ci/condarc.yml b/ci/condarc.yml
index 9d750b7102c39..f5fb60b208a9c 100644
--- a/ci/condarc.yml
+++ b/ci/condarc.yml
@@ -11,7 +11,7 @@ always_yes: true
# The number seconds conda will wait for your client to establish a
# connection to a remote url resource.
#
-remote_connect_timeout_secs: 30.0
+remote_connect_timeout_secs: 30
# remote_max_retries (int)
# The maximum number of retries each HTTP connection should attempt.
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py
index 4a6443e22d690..a0d9c6ae99dcf 100644
--- a/pandas/tests/io/parser/test_network.py
+++ b/pandas/tests/io/parser/test_network.py
@@ -277,9 +277,7 @@ def test_read_csv_handles_boto_s3_object(self, s3_resource, tips_file):
@pytest.mark.single_cpu
@pytest.mark.skipif(
is_ci_environment(),
- reason="This test can hang in our CI min_versions build "
- "and leads to '##[error]The runner has "
- "received a shutdown signal...' in GHA. GH: 45651",
+ reason="GH: 45651: This test can hang in our CI min_versions build",
)
def test_read_csv_chunked_download(self, s3_resource, caplog, s3so):
# 8 MB, S3FS uses 5MB chunks
diff --git a/pandas/tests/io/test_user_agent.py b/pandas/tests/io/test_user_agent.py
index 3b552805198b5..06051a81679fa 100644
--- a/pandas/tests/io/test_user_agent.py
+++ b/pandas/tests/io/test_user_agent.py
@@ -19,9 +19,7 @@
pytestmark = pytest.mark.skipif(
is_ci_environment(),
- reason="This test can hang in our CI min_versions build "
- "and leads to '##[error]The runner has "
- "received a shutdown signal...' in GHA. GH 45651",
+ reason="GH 45651: This test can hang in our CI min_versions build",
)
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/53139 | 2023-05-08T17:35:51Z | 2023-05-12T17:16:31Z | 2023-05-12T17:16:31Z | 2023-05-12T17:16:34Z |
Add test case for applying a function to a groupby object that append⦠| diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py
index 5eaa2eb20f6bf..b52b708de50a6 100644
--- a/pandas/tests/groupby/test_apply.py
+++ b/pandas/tests/groupby/test_apply.py
@@ -19,6 +19,23 @@
from pandas.tests.groupby import get_groupby_method_args
+def test_apply_func_that_appends_group_to_list_without_copy():
+ # GH: 17718
+
+ df = DataFrame(1, index=list(range(10)) * 10, columns=[0]).reset_index()
+ groups = []
+
+ def store(group):
+ groups.append(group)
+
+ df.groupby("index").apply(store)
+ expected_value = DataFrame(
+ {"index": [0] * 10, 0: [1] * 10}, index=pd.RangeIndex(0, 100, 10)
+ )
+
+ tm.assert_frame_equal(groups[0], expected_value)
+
+
def test_apply_issues():
# GH 5788
| β¦s each group to a list without using copy() function. The test checks if the groups are correctly appended to the list. This resolves GH issue 17718.
- [ ] closes #17718 (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/53138 | 2023-05-08T17:07:53Z | 2023-05-09T16:45:19Z | 2023-05-09T16:45:19Z | 2023-05-09T16:55:13Z |
Backport PR #53118 on branch 2.0.x (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 7864791f8bc59..fae0f06beb3a8 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 c2393fc7ada06..a627a60ef0691 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -158,7 +158,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 d2fb4a8426cf8..b749a863a3937 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -1496,6 +1496,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):
| Backport PR #53118: REGR: read_sql dropping duplicated columns | https://api.github.com/repos/pandas-dev/pandas/pulls/53136 | 2023-05-08T13:15:47Z | 2023-05-08T16:32:21Z | 2023-05-08T16:32:21Z | 2023-05-08T16:32:22Z |
TYP: remove mypy ignore[assignment] from pandas/core/internals/construction.py | diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py
index 29e0bb11be4dc..f080683d76df7 100644
--- a/pandas/core/internals/construction.py
+++ b/pandas/core/internals/construction.py
@@ -675,8 +675,7 @@ def reorder_arrays(
if columns is not None:
if not columns.equals(arr_columns):
# if they are equal, there is nothing to do
- new_arrays: list[ArrayLike | None]
- new_arrays = [None] * len(columns)
+ new_arrays: list[ArrayLike] = []
indexer = arr_columns.get_indexer(columns)
for i, k in enumerate(indexer):
if k == -1:
@@ -685,12 +684,9 @@ def reorder_arrays(
arr.fill(np.nan)
else:
arr = arrays[k]
- new_arrays[i] = arr
+ new_arrays.append(arr)
- # Incompatible types in assignment (expression has type
- # "List[Union[ExtensionArray, ndarray[Any, Any], None]]", variable
- # has type "List[Union[ExtensionArray, ndarray[Any, Any]]]")
- arrays = new_arrays # type: ignore[assignment]
+ arrays = new_arrays
arr_columns = columns
return arrays, arr_columns
| Related to #37715
mypy ignore[assignment] was removed from pandas/core/internals/construction.py | https://api.github.com/repos/pandas-dev/pandas/pulls/53135 | 2023-05-08T09:24:42Z | 2023-05-12T11:06:11Z | 2023-05-12T11:06:11Z | 2023-05-12T11:06:11Z |
DOC: Updated applymap docstring | diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index b2505bc63926c..c599bcbfd4170 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -2051,7 +2051,7 @@ def applymap(
.. deprecated:: 2.1.0
- Styler.applymap_index has been deprecated. Use Styler.map_index instead.
+ Styler.applymap has been deprecated. Use Styler.map instead.
Parameters
----------
| - [X] closes #53097 (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.
Removed _index part from the docstring for applymap.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53132 | 2023-05-07T22:49:05Z | 2023-05-08T16:36:18Z | 2023-05-08T16:36:18Z | 2023-05-08T16:36:24Z |
CI: Don't run cron for forks | diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index 23609f692df7c..8715c5306a3b0 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -18,6 +18,7 @@ jobs:
actions: read
contents: read
security-events: write
+ if: github.repository_owner == 'pandas-dev'
strategy:
fail-fast: false
diff --git a/.github/workflows/stale-pr.yml b/.github/workflows/stale-pr.yml
index c47745e097d17..1f62b982278c9 100644
--- a/.github/workflows/stale-pr.yml
+++ b/.github/workflows/stale-pr.yml
@@ -11,6 +11,7 @@ jobs:
stale:
permissions:
pull-requests: write
+ if: github.repository_owner == 'pandas-dev'
runs-on: ubuntu-22.04
steps:
- uses: actions/stale@v4
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml
index 31ed5096991a6..0dfa7a2174320 100644
--- a/.github/workflows/wheels.yml
+++ b/.github/workflows/wheels.yml
@@ -37,7 +37,7 @@ jobs:
build_wheels:
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')) ||
| - [n/a] closes #xxxx (Replace xxxx with the GitHub issue number)
- [n/a] [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).
- [n/a] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [n/a?] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
The codeql and stale-pr workflows run on a cron:
```yml
on:
schedule:
# every day at midnight
- cron: "0 0 * * *"
```
As does the wheels workflow:
```yml
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 * *"
```
These are useful for the upstream https://github.com/pandas-dev/pandas repo but unnecessary for contributors' forks:
<img width="997" alt="image" src="https://user-images.githubusercontent.com/1324225/236686019-f97c10e6-9fcd-4de4-920e-42a837f6f497.png">
They also trigger emails when they fail on the fork:
<img width="712" alt="image" src="https://user-images.githubusercontent.com/1324225/236686197-c2b4e3cd-eb68-4f02-bb31-8c7b3cb2629f.png">
Similar to autoupdate-pre-commit-config, let's only run the schedule for upstream:
https://github.com/pandas-dev/pandas/blob/956b8008e90845093f57c581c97b15297c72090a/.github/workflows/autoupdate-pre-commit-config.yml#L16
| https://api.github.com/repos/pandas-dev/pandas/pulls/53129 | 2023-05-07T15:16:54Z | 2023-05-08T16:37:50Z | 2023-05-08T16:37:50Z | 2023-05-08T16:38:30Z |
ENH: add validate parameter to Categorical.from_codes | diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst
index 36b2aa3c28da5..a6302ca09f90a 100644
--- a/doc/source/whatsnew/v2.1.0.rst
+++ b/doc/source/whatsnew/v2.1.0.rst
@@ -95,6 +95,7 @@ Other enhancements
- Improved error message when creating a DataFrame with empty data (0 rows), no index and an incorrect number of columns. (:issue:`52084`)
- Let :meth:`DataFrame.to_feather` accept a non-default :class:`Index` and non-string column names (:issue:`51787`)
- Performance improvement in :func:`read_csv` (:issue:`52632`) with ``engine="c"``
+- :meth:`Categorical.from_codes` has gotten a ``validate`` parameter (:issue:`50975`)
- Performance improvement in :func:`concat` with homogeneous ``np.float64`` or ``np.float32`` dtypes (:issue:`52685`)
- Performance improvement in :meth:`DataFrame.filter` when ``items`` is given (:issue:`52941`)
-
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 41e05ffc70b2e..6eb21fae29612 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -649,7 +649,12 @@ def _from_inferred_categories(
@classmethod
def from_codes(
- cls, codes, categories=None, ordered=None, dtype: Dtype | None = None
+ cls,
+ codes,
+ categories=None,
+ ordered=None,
+ dtype: Dtype | None = None,
+ validate: bool = True,
) -> Self:
"""
Make a Categorical type from codes and categories or dtype.
@@ -677,6 +682,12 @@ def from_codes(
dtype : CategoricalDtype or "category", optional
If :class:`CategoricalDtype`, cannot be used together with
`categories` or `ordered`.
+ validate : bool, default True
+ If True, validate that the codes are valid for the dtype.
+ If False, don't validate that the codes are valid. Be careful about skipping
+ validation, as invalid codes can lead to severe problems, such as segfaults.
+
+ .. versionadded:: 2.1.0
Returns
-------
@@ -699,18 +710,9 @@ def from_codes(
)
raise ValueError(msg)
- if isinstance(codes, ExtensionArray) and is_integer_dtype(codes.dtype):
- # Avoid the implicit conversion of Int to object
- if isna(codes).any():
- raise ValueError("codes cannot contain NA values")
- codes = codes.to_numpy(dtype=np.int64)
- else:
- codes = np.asarray(codes)
- if len(codes) and codes.dtype.kind not in "iu":
- raise ValueError("codes need to be array-like integers")
-
- if len(codes) and (codes.max() >= len(dtype.categories) or codes.min() < -1):
- raise ValueError("codes need to be between -1 and len(categories)-1")
+ if validate:
+ # beware: non-valid codes may segfault
+ codes = cls._validate_codes_for_dtype(codes, dtype=dtype)
return cls._simple_new(codes, dtype=dtype)
@@ -1325,7 +1327,7 @@ def map(
if new_categories.is_unique and not new_categories.hasnans and na_val is np.nan:
new_dtype = CategoricalDtype(new_categories, ordered=self.ordered)
- return self.from_codes(self._codes.copy(), dtype=new_dtype)
+ return self.from_codes(self._codes.copy(), dtype=new_dtype, validate=False)
if has_nans:
new_categories = new_categories.insert(len(new_categories), na_val)
@@ -1378,6 +1380,22 @@ def _validate_scalar(self, fill_value):
) from None
return fill_value
+ @classmethod
+ def _validate_codes_for_dtype(cls, codes, *, dtype: CategoricalDtype) -> np.ndarray:
+ if isinstance(codes, ExtensionArray) and is_integer_dtype(codes.dtype):
+ # Avoid the implicit conversion of Int to object
+ if isna(codes).any():
+ raise ValueError("codes cannot contain NA values")
+ codes = codes.to_numpy(dtype=np.int64)
+ else:
+ codes = np.asarray(codes)
+ if len(codes) and codes.dtype.kind not in "iu":
+ raise ValueError("codes need to be array-like integers")
+
+ if len(codes) and (codes.max() >= len(dtype.categories) or codes.min() < -1):
+ raise ValueError("codes need to be between -1 and len(categories)-1")
+ return codes
+
# -------------------------------------------------------------
@ravel_compat
@@ -2724,7 +2742,7 @@ def factorize_from_iterable(values) -> tuple[np.ndarray, Index]:
# The Categorical we want to build has the same categories
# as values but its codes are by def [0, ..., len(n_categories) - 1]
cat_codes = np.arange(len(values.categories), dtype=values.codes.dtype)
- cat = Categorical.from_codes(cat_codes, dtype=values.dtype)
+ cat = Categorical.from_codes(cat_codes, dtype=values.dtype, validate=False)
categories = CategoricalIndex(cat)
codes = values.codes
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py
index e9833a41e2795..316b896da126f 100644
--- a/pandas/core/groupby/grouper.py
+++ b/pandas/core/groupby/grouper.py
@@ -721,7 +721,7 @@ def group_index(self) -> Index:
if self._sort and (codes == len(uniques)).any():
# Add NA value on the end when sorting
uniques = Categorical.from_codes(
- np.append(uniques.codes, [-1]), uniques.categories
+ np.append(uniques.codes, [-1]), uniques.categories, validate=False
)
elif len(codes) > 0:
# Need to determine proper placement of NA value when not sorting
@@ -730,8 +730,9 @@ def group_index(self) -> Index:
if cat.codes[na_idx] < 0:
# count number of unique codes that comes before the nan value
na_unique_idx = algorithms.nunique_ints(cat.codes[:na_idx])
+ new_codes = np.insert(uniques.codes, na_unique_idx, -1)
uniques = Categorical.from_codes(
- np.insert(uniques.codes, na_unique_idx, -1), uniques.categories
+ new_codes, uniques.categories, validate=False
)
return Index._with_infer(uniques, name=self.name)
@@ -754,7 +755,7 @@ def _codes_and_uniques(self) -> tuple[npt.NDArray[np.signedinteger], ArrayLike]:
ucodes = np.arange(len(categories))
uniques = Categorical.from_codes(
- codes=ucodes, categories=categories, ordered=cat.ordered
+ codes=ucodes, categories=categories, ordered=cat.ordered, validate=False
)
codes = cat.codes
@@ -800,7 +801,8 @@ def _codes_and_uniques(self) -> tuple[npt.NDArray[np.signedinteger], ArrayLike]:
@cache_readonly
def groups(self) -> dict[Hashable, np.ndarray]:
- return self._index.groupby(Categorical.from_codes(self.codes, self.group_index))
+ cats = Categorical.from_codes(self.codes, self.group_index, validate=False)
+ return self._index.groupby(cats)
def get_grouper(
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index deff5129ad64d..7a151cb811cbd 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -2393,7 +2393,7 @@ def cats(level_codes):
)
return [
- Categorical.from_codes(level_codes, cats(level_codes), ordered=True)
+ Categorical.from_codes(level_codes, cats(level_codes), True, validate=False)
for level_codes in self.codes
]
@@ -2583,7 +2583,7 @@ def _get_indexer_level_0(self, target) -> npt.NDArray[np.intp]:
"""
lev = self.levels[0]
codes = self._codes[0]
- cat = Categorical.from_codes(codes=codes, categories=lev)
+ cat = Categorical.from_codes(codes=codes, categories=lev, validate=False)
ci = Index(cat)
return ci.get_indexer_for(target)
diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py
index 357353ed38d46..83d004c8b8e3e 100644
--- a/pandas/core/reshape/tile.py
+++ b/pandas/core/reshape/tile.py
@@ -411,7 +411,8 @@ def _bins_to_cuts(
if isinstance(bins, IntervalIndex):
# we have a fast-path here
ids = bins.get_indexer(x)
- result = Categorical.from_codes(ids, categories=bins, ordered=True)
+ cat_dtype = CategoricalDtype(bins, ordered=True)
+ result = Categorical.from_codes(ids, dtype=cat_dtype, validate=False)
return result, bins
unique_bins = algos.unique(bins)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 33ff24f5fc981..c9dab71805b62 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2520,7 +2520,7 @@ def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str):
codes[codes != -1] -= mask.astype(int).cumsum()._values
converted = Categorical.from_codes(
- codes, categories=categories, ordered=ordered
+ codes, categories=categories, ordered=ordered, validate=False
)
else:
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py
index e6e829cdaf1c2..5eb7f37a4ae34 100644
--- a/pandas/tests/arrays/categorical/test_constructors.py
+++ b/pandas/tests/arrays/categorical/test_constructors.py
@@ -509,12 +509,13 @@ def test_construction_with_null(self, klass, nulls_fixture):
tm.assert_categorical_equal(result, expected)
- def test_from_codes_nullable_int_categories(self, any_numeric_ea_dtype):
+ @pytest.mark.parametrize("validate", [True, False])
+ def test_from_codes_nullable_int_categories(self, any_numeric_ea_dtype, validate):
# GH#39649
cats = pd.array(range(5), dtype=any_numeric_ea_dtype)
codes = np.random.randint(5, size=3)
dtype = CategoricalDtype(cats)
- arr = Categorical.from_codes(codes, dtype=dtype)
+ arr = Categorical.from_codes(codes, dtype=dtype, validate=validate)
assert arr.categories.dtype == cats.dtype
tm.assert_index_equal(arr.categories, Index(cats))
@@ -525,6 +526,17 @@ def test_from_codes_empty(self):
tm.assert_categorical_equal(result, expected)
+ @pytest.mark.parametrize("validate", [True, False])
+ def test_from_codes_validate(self, validate):
+ # GH53122
+ dtype = CategoricalDtype(["a", "b"])
+ if validate:
+ with pytest.raises(ValueError, match="codes need to be between "):
+ Categorical.from_codes([4, 5], dtype=dtype, validate=validate)
+ else:
+ # passes, though has incorrect codes, but that's the user responsibility
+ Categorical.from_codes([4, 5], dtype=dtype, validate=validate)
+
def test_from_codes_too_few_categories(self):
dtype = CategoricalDtype(categories=[1, 2])
msg = "codes need to be between "
| - [x] closes #50975
- [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/53122 | 2023-05-07T00:09:52Z | 2023-05-09T17:43:53Z | 2023-05-09T17:43:53Z | 2023-08-15T17:56:03Z |
Backport PR #51895 on branch 2.0.x (BUG: Fix getitem dtype preservation with multiindexes) | diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst
index 7864791f8bc59..f8ac59b49e6e3 100644
--- a/doc/source/whatsnew/v2.0.2.rst
+++ b/doc/source/whatsnew/v2.0.2.rst
@@ -29,6 +29,7 @@ Bug fixes
- 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`)
+- Bug in :meth:`DataFrame.__getitem__` not preserving dtypes for :class:`MultiIndex` partial keys (:issue:`51895`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 8be8ed188cce2..7e1d8711aee86 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3816,18 +3816,8 @@ def _getitem_multilevel(self, key):
if isinstance(loc, (slice, np.ndarray)):
new_columns = self.columns[loc]
result_columns = maybe_droplevels(new_columns, key)
- if self._is_mixed_type:
- result = self.reindex(columns=new_columns)
- result.columns = result_columns
- else:
- new_values = self._values[:, loc]
- result = self._constructor(
- new_values, index=self.index, columns=result_columns, copy=False
- )
- if using_copy_on_write() and isinstance(loc, slice):
- result._mgr.add_references(self._mgr) # type: ignore[arg-type]
-
- result = result.__finalize__(self)
+ result = self.iloc[:, loc]
+ result.columns = result_columns
# If there is only one column being returned, and its name is
# either an empty string, or a tuple with an empty string as its
diff --git a/pandas/tests/indexing/multiindex/test_multiindex.py b/pandas/tests/indexing/multiindex/test_multiindex.py
index 8e507212976ec..22a6f62f53392 100644
--- a/pandas/tests/indexing/multiindex/test_multiindex.py
+++ b/pandas/tests/indexing/multiindex/test_multiindex.py
@@ -6,12 +6,14 @@
import pandas as pd
from pandas import (
+ CategoricalDtype,
DataFrame,
Index,
MultiIndex,
Series,
)
import pandas._testing as tm
+from pandas.core.arrays.boolean import BooleanDtype
class TestMultiIndexBasic:
@@ -206,3 +208,21 @@ def test_multiindex_with_na_missing_key(self):
)
with pytest.raises(KeyError, match="missing_key"):
df[[("missing_key",)]]
+
+ def test_multiindex_dtype_preservation(self):
+ # GH51261
+ columns = MultiIndex.from_tuples([("A", "B")], names=["lvl1", "lvl2"])
+ df = DataFrame(["value"], columns=columns).astype("category")
+ df_no_multiindex = df["A"]
+ assert isinstance(df_no_multiindex["B"].dtype, CategoricalDtype)
+
+ # geopandas 1763 analogue
+ df = DataFrame(
+ [[1, 0], [0, 1]],
+ columns=[
+ ["foo", "foo"],
+ ["location", "location"],
+ ["x", "y"],
+ ],
+ ).assign(bools=Series([True, False], dtype="boolean"))
+ assert isinstance(df["bools"].dtype, BooleanDtype)
| xref #53119
cc @jorisvandenbossche @jbrockmendel
This fixes a pretty bad performance bottleneck for CoW. Would like to backport.
| https://api.github.com/repos/pandas-dev/pandas/pulls/53121 | 2023-05-06T21:28:20Z | 2023-05-08T16:40:06Z | 2023-05-08T16:40:06Z | 2023-05-08T17:34:32Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.