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 |
|---|---|---|---|---|---|---|---|
ENH: implement non-nano Timedelta scalar | diff --git a/pandas/_libs/tslibs/timedeltas.pxd b/pandas/_libs/tslibs/timedeltas.pxd
index f114fd9297920..3019be5a59c46 100644
--- a/pandas/_libs/tslibs/timedeltas.pxd
+++ b/pandas/_libs/tslibs/timedeltas.pxd
@@ -1,6 +1,8 @@
from cpython.datetime cimport timedelta
from numpy cimport int64_t
+from .np_datetime cimport NPY_DATETIMEUNIT
+
# Exposed for tslib, not intended for outside use.
cpdef int64_t delta_to_nanoseconds(delta) except? -1
@@ -13,7 +15,9 @@ cdef class _Timedelta(timedelta):
int64_t value # nanoseconds
bint _is_populated # are my components populated
int64_t _d, _h, _m, _s, _ms, _us, _ns
+ NPY_DATETIMEUNIT _reso
cpdef timedelta to_pytimedelta(_Timedelta self)
cdef bint _has_ns(self)
cdef _ensure_components(_Timedelta self)
+ cdef inline bint _compare_mismatched_resos(self, _Timedelta other, op)
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index 7979feb076c6e..6606158aea807 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -45,13 +45,19 @@ from pandas._libs.tslibs.nattype cimport (
)
from pandas._libs.tslibs.np_datetime cimport (
NPY_DATETIMEUNIT,
+ NPY_FR_ns,
+ cmp_dtstructs,
cmp_scalar,
get_datetime64_unit,
get_timedelta64_value,
+ npy_datetimestruct,
+ pandas_datetime_to_datetimestruct,
+ pandas_timedelta_to_timedeltastruct,
pandas_timedeltastruct,
- td64_to_tdstruct,
)
+
from pandas._libs.tslibs.np_datetime import OutOfBoundsTimedelta
+
from pandas._libs.tslibs.offsets cimport is_tick_object
from pandas._libs.tslibs.util cimport (
is_array,
@@ -176,7 +182,9 @@ cpdef int64_t delta_to_nanoseconds(delta) except? -1:
if is_tick_object(delta):
return delta.nanos
if isinstance(delta, _Timedelta):
- return delta.value
+ if delta._reso == NPY_FR_ns:
+ return delta.value
+ raise NotImplementedError(delta._reso)
if is_timedelta64_object(delta):
return get_timedelta64_value(ensure_td64ns(delta))
@@ -251,6 +259,8 @@ cdef convert_to_timedelta64(object ts, str unit):
return np.timedelta64(NPY_NAT, "ns")
elif isinstance(ts, _Timedelta):
# already in the proper format
+ if ts._reso != NPY_FR_ns:
+ raise NotImplementedError
ts = np.timedelta64(ts.value, "ns")
elif is_timedelta64_object(ts):
ts = ensure_td64ns(ts)
@@ -643,7 +653,8 @@ cdef bint _validate_ops_compat(other):
def _op_unary_method(func, name):
def f(self):
- return Timedelta(func(self.value), unit='ns')
+ new_value = func(self.value)
+ return _timedelta_from_value_and_reso(new_value, self._reso)
f.__name__ = name
return f
@@ -688,7 +699,17 @@ def _binary_op_method_timedeltalike(op, name):
if other is NaT:
# e.g. if original other was timedelta64('NaT')
return NaT
- return Timedelta(op(self.value, other.value), unit='ns')
+
+ if self._reso != other._reso:
+ raise NotImplementedError
+
+ res = op(self.value, other.value)
+ if res == NPY_NAT:
+ # e.g. test_implementation_limits
+ # TODO: more generally could do an overflowcheck in op?
+ return NaT
+
+ return _timedelta_from_value_and_reso(res, reso=self._reso)
f.__name__ = name
return f
@@ -818,6 +839,38 @@ cdef _to_py_int_float(v):
raise TypeError(f"Invalid type {type(v)}. Must be int or float.")
+def _timedelta_unpickle(value, reso):
+ return _timedelta_from_value_and_reso(value, reso)
+
+
+cdef _timedelta_from_value_and_reso(int64_t value, NPY_DATETIMEUNIT reso):
+ # Could make this a classmethod if/when cython supports cdef classmethods
+ cdef:
+ _Timedelta td_base
+
+ if reso == NPY_FR_ns:
+ td_base = _Timedelta.__new__(Timedelta, microseconds=int(value) // 1000)
+ elif reso == NPY_DATETIMEUNIT.NPY_FR_us:
+ td_base = _Timedelta.__new__(Timedelta, microseconds=int(value))
+ elif reso == NPY_DATETIMEUNIT.NPY_FR_ms:
+ td_base = _Timedelta.__new__(Timedelta, milliseconds=int(value))
+ elif reso == NPY_DATETIMEUNIT.NPY_FR_s:
+ td_base = _Timedelta.__new__(Timedelta, seconds=int(value))
+ elif reso == NPY_DATETIMEUNIT.NPY_FR_m:
+ td_base = _Timedelta.__new__(Timedelta, minutes=int(value))
+ elif reso == NPY_DATETIMEUNIT.NPY_FR_h:
+ td_base = _Timedelta.__new__(Timedelta, hours=int(value))
+ elif reso == NPY_DATETIMEUNIT.NPY_FR_D:
+ td_base = _Timedelta.__new__(Timedelta, days=int(value))
+ else:
+ raise NotImplementedError(reso)
+
+ td_base.value = value
+ td_base._is_populated = 0
+ td_base._reso = reso
+ return td_base
+
+
# Similar to Timestamp/datetime, this is a construction requirement for
# timedeltas that we need to do object instantiation in python. This will
# serve as a C extension type that shadows the Python class, where we do any
@@ -827,6 +880,7 @@ cdef class _Timedelta(timedelta):
# int64_t value # nanoseconds
# bint _is_populated # are my components populated
# int64_t _d, _h, _m, _s, _ms, _us, _ns
+ # NPY_DATETIMEUNIT _reso
# higher than np.ndarray and np.matrix
__array_priority__ = 100
@@ -853,6 +907,11 @@ cdef class _Timedelta(timedelta):
def __hash__(_Timedelta self):
if self._has_ns():
+ # Note: this does *not* satisfy the invariance
+ # td1 == td2 \\Rightarrow hash(td1) == hash(td2)
+ # if td1 and td2 have different _resos. timedelta64 also has this
+ # non-invariant behavior.
+ # see GH#44504
return hash(self.value)
else:
return timedelta.__hash__(self)
@@ -890,10 +949,30 @@ cdef class _Timedelta(timedelta):
else:
return NotImplemented
- return cmp_scalar(self.value, ots.value, op)
+ if self._reso == ots._reso:
+ return cmp_scalar(self.value, ots.value, op)
+ return self._compare_mismatched_resos(ots, op)
+
+ # TODO: re-use/share with Timestamp
+ cdef inline bint _compare_mismatched_resos(self, _Timedelta other, op):
+ # Can't just dispatch to numpy as they silently overflow and get it wrong
+ cdef:
+ npy_datetimestruct dts_self
+ npy_datetimestruct dts_other
+
+ # dispatch to the datetimestruct utils instead of writing new ones!
+ pandas_datetime_to_datetimestruct(self.value, self._reso, &dts_self)
+ pandas_datetime_to_datetimestruct(other.value, other._reso, &dts_other)
+ return cmp_dtstructs(&dts_self, &dts_other, op)
cdef bint _has_ns(self):
- return self.value % 1000 != 0
+ if self._reso == NPY_FR_ns:
+ return self.value % 1000 != 0
+ elif self._reso < NPY_FR_ns:
+ # i.e. seconds, millisecond, microsecond
+ return False
+ else:
+ raise NotImplementedError(self._reso)
cdef _ensure_components(_Timedelta self):
"""
@@ -905,7 +984,7 @@ cdef class _Timedelta(timedelta):
cdef:
pandas_timedeltastruct tds
- td64_to_tdstruct(self.value, &tds)
+ pandas_timedelta_to_timedeltastruct(self.value, self._reso, &tds)
self._d = tds.days
self._h = tds.hrs
self._m = tds.min
@@ -937,13 +1016,24 @@ cdef class _Timedelta(timedelta):
-----
Any nanosecond resolution will be lost.
"""
- return timedelta(microseconds=int(self.value) / 1000)
+ if self._reso == NPY_FR_ns:
+ return timedelta(microseconds=int(self.value) / 1000)
+
+ # TODO(@WillAyd): is this the right way to use components?
+ self._ensure_components()
+ return timedelta(
+ days=self._d, seconds=self._seconds, microseconds=self._microseconds
+ )
def to_timedelta64(self) -> np.timedelta64:
"""
Return a numpy.timedelta64 object with 'ns' precision.
"""
- return np.timedelta64(self.value, 'ns')
+ cdef:
+ str abbrev = npy_unit_to_abbrev(self._reso)
+ # TODO: way to create a np.timedelta64 obj with the reso directly
+ # instead of having to get the abbrev?
+ return np.timedelta64(self.value, abbrev)
def to_numpy(self, dtype=None, copy=False) -> np.timedelta64:
"""
@@ -1054,7 +1144,7 @@ cdef class _Timedelta(timedelta):
>>> td.asm8
numpy.timedelta64(42,'ns')
"""
- return np.int64(self.value).view('m8[ns]')
+ return self.to_timedelta64()
@property
def resolution_string(self) -> str:
@@ -1258,6 +1348,14 @@ cdef class _Timedelta(timedelta):
f'H{components.minutes}M{seconds}S')
return tpl
+ # ----------------------------------------------------------------
+ # Constructors
+
+ @classmethod
+ def _from_value_and_reso(cls, int64_t value, NPY_DATETIMEUNIT reso):
+ # exposing as classmethod for testing
+ return _timedelta_from_value_and_reso(value, reso)
+
# Python front end to C extension type _Timedelta
# This serves as the box for timedelta64
@@ -1413,19 +1511,21 @@ class Timedelta(_Timedelta):
if value == NPY_NAT:
return NaT
- # make timedelta happy
- td_base = _Timedelta.__new__(cls, microseconds=int(value) // 1000)
- td_base.value = value
- td_base._is_populated = 0
- return td_base
+ return _timedelta_from_value_and_reso(value, NPY_FR_ns)
def __setstate__(self, state):
- (value) = state
+ if len(state) == 1:
+ # older pickle, only supported nanosecond
+ value = state[0]
+ reso = NPY_FR_ns
+ else:
+ value, reso = state
self.value = value
+ self._reso = reso
def __reduce__(self):
- object_state = self.value,
- return (Timedelta, object_state)
+ object_state = self.value, self._reso
+ return (_timedelta_unpickle, object_state)
@cython.cdivision(True)
def _round(self, freq, mode):
@@ -1496,7 +1596,14 @@ class Timedelta(_Timedelta):
def __mul__(self, other):
if is_integer_object(other) or is_float_object(other):
- return Timedelta(other * self.value, unit='ns')
+ if util.is_nan(other):
+ # np.nan * timedelta -> np.timedelta64("NaT"), in this case NaT
+ return NaT
+
+ return _timedelta_from_value_and_reso(
+ <int64_t>(other * self.value),
+ reso=self._reso,
+ )
elif is_array(other):
# ndarray-like
diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py
index 1ec93c69def99..17a8ec5f86fc8 100644
--- a/pandas/tests/scalar/timedelta/test_timedelta.py
+++ b/pandas/tests/scalar/timedelta/test_timedelta.py
@@ -24,6 +24,79 @@
import pandas._testing as tm
+class TestNonNano:
+ @pytest.fixture(params=[7, 8, 9])
+ def unit(self, request):
+ # 7, 8, 9 correspond to second, millisecond, and microsecond, respectively
+ return request.param
+
+ @pytest.fixture
+ def val(self, unit):
+ # microsecond that would be just out of bounds for nano
+ us = 9223372800000000
+ if unit == 9:
+ value = us
+ elif unit == 8:
+ value = us // 1000
+ else:
+ value = us // 1_000_000
+ return value
+
+ @pytest.fixture
+ def td(self, unit, val):
+ return Timedelta._from_value_and_reso(val, unit)
+
+ def test_from_value_and_reso(self, unit, val):
+ # Just checking that the fixture is giving us what we asked for
+ td = Timedelta._from_value_and_reso(val, unit)
+ assert td.value == val
+ assert td._reso == unit
+ assert td.days == 106752
+
+ def test_unary_non_nano(self, td, unit):
+ assert abs(td)._reso == unit
+ assert (-td)._reso == unit
+ assert (+td)._reso == unit
+
+ def test_sub_preserves_reso(self, td, unit):
+ res = td - td
+ expected = Timedelta._from_value_and_reso(0, unit)
+ assert res == expected
+ assert res._reso == unit
+
+ def test_mul_preserves_reso(self, td, unit):
+ # The td fixture should always be far from the implementation
+ # bound, so doubling does not risk overflow.
+ res = td * 2
+ assert res.value == td.value * 2
+ assert res._reso == unit
+
+ def test_cmp_cross_reso(self, td):
+ other = Timedelta(days=106751, unit="ns")
+ assert other < td
+ assert td > other
+ assert not other == td
+ assert td != other
+
+ def test_to_pytimedelta(self, td):
+ res = td.to_pytimedelta()
+ expected = timedelta(days=106752)
+ assert type(res) is timedelta
+ assert res == expected
+
+ def test_to_timedelta64(self, td, unit):
+ for res in [td.to_timedelta64(), td.to_numpy(), td.asm8]:
+
+ assert isinstance(res, np.timedelta64)
+ assert res.view("i8") == td.value
+ if unit == 7:
+ assert res.dtype == "m8[s]"
+ elif unit == 8:
+ assert res.dtype == "m8[ms]"
+ elif unit == 9:
+ assert res.dtype == "m8[us]"
+
+
class TestTimedeltaUnaryOps:
def test_invert(self):
td = Timedelta(10, unit="d")
diff --git a/setup.py b/setup.py
index 62704dc4423c8..384c1a267afe3 100755
--- a/setup.py
+++ b/setup.py
@@ -538,6 +538,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"):
"_libs.tslibs.timedeltas": {
"pyxfile": "_libs/tslibs/timedeltas",
"depends": tseries_depends,
+ "sources": ["pandas/_libs/tslibs/src/datetime/np_datetime.c"],
},
"_libs.tslibs.timestamps": {
"pyxfile": "_libs/tslibs/timestamps",
| - [ ] 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 an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Not user-exposed. This is just enough to allow us to have non-nano TimedeltaArray.
asvs for tslibs.timedelta unchanged
| https://api.github.com/repos/pandas-dev/pandas/pulls/46688 | 2022-04-07T17:13:41Z | 2022-04-18T20:51:44Z | 2022-04-18T20:51:44Z | 2022-04-22T20:13:25Z |
Backport PR #46674 on branch 1.4.x (DOC: generate docs for the `Series.dt.isocalendar()` method.) | diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst
index a60dab549e66d..fcdc9ea9b95da 100644
--- a/doc/source/reference/series.rst
+++ b/doc/source/reference/series.rst
@@ -342,6 +342,7 @@ Datetime methods
:toctree: api/
:template: autosummary/accessor_method.rst
+ Series.dt.isocalendar
Series.dt.to_period
Series.dt.to_pydatetime
Series.dt.tz_localize
diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py
index 8c2813f2b57ec..78beda95d4658 100644
--- a/pandas/core/indexes/accessors.py
+++ b/pandas/core/indexes/accessors.py
@@ -277,12 +277,13 @@ def isocalendar(self):
@property
def weekofyear(self):
"""
- The week ordinal of the year.
+ The week ordinal of the year according to the ISO 8601 standard.
.. deprecated:: 1.1.0
- Series.dt.weekofyear and Series.dt.week have been deprecated.
- Please use Series.dt.isocalendar().week instead.
+ Series.dt.weekofyear and Series.dt.week have been deprecated. Please
+ call :func:`Series.dt.isocalendar` and access the ``week`` column
+ instead.
"""
warnings.warn(
"Series.dt.weekofyear and Series.dt.week have been deprecated. "
| Backport PR #46674: DOC: generate docs for the `Series.dt.isocalendar()` method. | https://api.github.com/repos/pandas-dev/pandas/pulls/46686 | 2022-04-07T16:37:12Z | 2022-04-09T01:59:20Z | 2022-04-09T01:59:20Z | 2022-04-09T01:59:20Z |
Fix a few test failures on big-endian systems | diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py
index fc48317114e23..0a62ee956be61 100644
--- a/pandas/_testing/__init__.py
+++ b/pandas/_testing/__init__.py
@@ -8,6 +8,7 @@
import os
import re
import string
+from sys import byteorder
from typing import (
TYPE_CHECKING,
Callable,
@@ -168,6 +169,8 @@
np.uint32,
]
+ENDIAN = {"little": "<", "big": ">"}[byteorder]
+
NULL_OBJECTS = [None, np.nan, pd.NaT, float("nan"), pd.NA, Decimal("NaN")]
NP_NAT_OBJECTS = [
cls("NaT", unit)
diff --git a/pandas/tests/arrays/boolean/test_astype.py b/pandas/tests/arrays/boolean/test_astype.py
index 57cec70262526..932e903c0e448 100644
--- a/pandas/tests/arrays/boolean/test_astype.py
+++ b/pandas/tests/arrays/boolean/test_astype.py
@@ -20,7 +20,7 @@ def test_astype():
tm.assert_numpy_array_equal(result, expected)
result = arr.astype("str")
- expected = np.array(["True", "False", "<NA>"], dtype="<U5")
+ expected = np.array(["True", "False", "<NA>"], dtype=f"{tm.ENDIAN}U5")
tm.assert_numpy_array_equal(result, expected)
# no missing values
diff --git a/pandas/tests/arrays/boolean/test_construction.py b/pandas/tests/arrays/boolean/test_construction.py
index 64b1786cbd101..d26eea19c06e9 100644
--- a/pandas/tests/arrays/boolean/test_construction.py
+++ b/pandas/tests/arrays/boolean/test_construction.py
@@ -273,7 +273,7 @@ def test_to_numpy(box):
arr = con([True, False, None], dtype="boolean")
result = arr.to_numpy(dtype="str")
- expected = np.array([True, False, pd.NA], dtype="<U5")
+ expected = np.array([True, False, pd.NA], dtype=f"{tm.ENDIAN}U5")
tm.assert_numpy_array_equal(result, expected)
# no missing values -> can convert to bool, otherwise raises
diff --git a/pandas/tests/arrays/floating/test_to_numpy.py b/pandas/tests/arrays/floating/test_to_numpy.py
index 26e5687b1b4a0..2ed52439adf53 100644
--- a/pandas/tests/arrays/floating/test_to_numpy.py
+++ b/pandas/tests/arrays/floating/test_to_numpy.py
@@ -115,7 +115,7 @@ def test_to_numpy_string(box, dtype):
arr = con([0.0, 1.0, None], dtype="Float64")
result = arr.to_numpy(dtype="str")
- expected = np.array([0.0, 1.0, pd.NA], dtype="<U32")
+ expected = np.array([0.0, 1.0, pd.NA], dtype=f"{tm.ENDIAN}U32")
tm.assert_numpy_array_equal(result, expected)
diff --git a/pandas/tests/arrays/integer/test_dtypes.py b/pandas/tests/arrays/integer/test_dtypes.py
index 8348ff79b24ee..1566476c32989 100644
--- a/pandas/tests/arrays/integer/test_dtypes.py
+++ b/pandas/tests/arrays/integer/test_dtypes.py
@@ -283,7 +283,7 @@ def test_to_numpy_na_raises(dtype):
def test_astype_str():
a = pd.array([1, 2, None], dtype="Int64")
- expected = np.array(["1", "2", "<NA>"], dtype="<U21")
+ expected = np.array(["1", "2", "<NA>"], dtype=f"{tm.ENDIAN}U21")
tm.assert_numpy_array_equal(a.astype(str), expected)
tm.assert_numpy_array_equal(a.astype("str"), expected)
diff --git a/pandas/tests/frame/methods/test_to_records.py b/pandas/tests/frame/methods/test_to_records.py
index 1a84fb73fd524..6332ffd181eba 100644
--- a/pandas/tests/frame/methods/test_to_records.py
+++ b/pandas/tests/frame/methods/test_to_records.py
@@ -151,7 +151,12 @@ def test_to_records_with_categorical(self):
{},
np.rec.array(
[(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],
- dtype=[("index", "<i8"), ("A", "<i8"), ("B", "<f8"), ("C", "O")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}i8"),
+ ("A", f"{tm.ENDIAN}i8"),
+ ("B", f"{tm.ENDIAN}f8"),
+ ("C", "O"),
+ ],
),
),
# Should have no effect in this case.
@@ -159,23 +164,38 @@ def test_to_records_with_categorical(self):
{"index": True},
np.rec.array(
[(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],
- dtype=[("index", "<i8"), ("A", "<i8"), ("B", "<f8"), ("C", "O")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}i8"),
+ ("A", f"{tm.ENDIAN}i8"),
+ ("B", f"{tm.ENDIAN}f8"),
+ ("C", "O"),
+ ],
),
),
# Column dtype applied across the board. Index unaffected.
(
- {"column_dtypes": "<U4"},
+ {"column_dtypes": f"{tm.ENDIAN}U4"},
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
- dtype=[("index", "<i8"), ("A", "<U4"), ("B", "<U4"), ("C", "<U4")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}i8"),
+ ("A", f"{tm.ENDIAN}U4"),
+ ("B", f"{tm.ENDIAN}U4"),
+ ("C", f"{tm.ENDIAN}U4"),
+ ],
),
),
# Index dtype applied across the board. Columns unaffected.
(
- {"index_dtypes": "<U1"},
+ {"index_dtypes": f"{tm.ENDIAN}U1"},
np.rec.array(
[("0", 1, 0.2, "a"), ("1", 2, 1.5, "bc")],
- dtype=[("index", "<U1"), ("A", "<i8"), ("B", "<f8"), ("C", "O")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}U1"),
+ ("A", f"{tm.ENDIAN}i8"),
+ ("B", f"{tm.ENDIAN}f8"),
+ ("C", "O"),
+ ],
),
),
# Pass in a type instance.
@@ -183,7 +203,12 @@ def test_to_records_with_categorical(self):
{"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")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}i8"),
+ ("A", f"{tm.ENDIAN}U"),
+ ("B", f"{tm.ENDIAN}U"),
+ ("C", f"{tm.ENDIAN}U"),
+ ],
),
),
# Pass in a dtype instance.
@@ -191,15 +216,31 @@ def test_to_records_with_categorical(self):
{"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")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}i8"),
+ ("A", f"{tm.ENDIAN}U"),
+ ("B", f"{tm.ENDIAN}U"),
+ ("C", f"{tm.ENDIAN}U"),
+ ],
),
),
# Pass in a dictionary (name-only).
(
- {"column_dtypes": {"A": np.int8, "B": np.float32, "C": "<U2"}},
+ {
+ "column_dtypes": {
+ "A": np.int8,
+ "B": np.float32,
+ "C": f"{tm.ENDIAN}U2",
+ }
+ },
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
- dtype=[("index", "<i8"), ("A", "i1"), ("B", "<f4"), ("C", "<U2")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}i8"),
+ ("A", "i1"),
+ ("B", f"{tm.ENDIAN}f4"),
+ ("C", f"{tm.ENDIAN}U2"),
+ ],
),
),
# Pass in a dictionary (indices-only).
@@ -207,15 +248,24 @@ def test_to_records_with_categorical(self):
{"index_dtypes": {0: "int16"}},
np.rec.array(
[(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],
- dtype=[("index", "i2"), ("A", "<i8"), ("B", "<f8"), ("C", "O")],
+ dtype=[
+ ("index", "i2"),
+ ("A", f"{tm.ENDIAN}i8"),
+ ("B", f"{tm.ENDIAN}f8"),
+ ("C", "O"),
+ ],
),
),
# Ignore index mappings if index is not True.
(
- {"index": False, "index_dtypes": "<U2"},
+ {"index": False, "index_dtypes": f"{tm.ENDIAN}U2"},
np.rec.array(
[(1, 0.2, "a"), (2, 1.5, "bc")],
- dtype=[("A", "<i8"), ("B", "<f8"), ("C", "O")],
+ dtype=[
+ ("A", f"{tm.ENDIAN}i8"),
+ ("B", f"{tm.ENDIAN}f8"),
+ ("C", "O"),
+ ],
),
),
# Non-existent names / indices in mapping should not error.
@@ -223,7 +273,12 @@ def test_to_records_with_categorical(self):
{"index_dtypes": {0: "int16", "not-there": "float32"}},
np.rec.array(
[(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],
- dtype=[("index", "i2"), ("A", "<i8"), ("B", "<f8"), ("C", "O")],
+ dtype=[
+ ("index", "i2"),
+ ("A", f"{tm.ENDIAN}i8"),
+ ("B", f"{tm.ENDIAN}f8"),
+ ("C", "O"),
+ ],
),
),
# Names / indices not in mapping default to array dtype.
@@ -231,7 +286,12 @@ def test_to_records_with_categorical(self):
{"column_dtypes": {"A": np.int8, "B": np.float32}},
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
- dtype=[("index", "<i8"), ("A", "i1"), ("B", "<f4"), ("C", "O")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}i8"),
+ ("A", "i1"),
+ ("B", f"{tm.ENDIAN}f4"),
+ ("C", "O"),
+ ],
),
),
# Names / indices not in dtype mapping default to array dtype.
@@ -239,18 +299,28 @@ def test_to_records_with_categorical(self):
{"column_dtypes": {"A": np.dtype("int8"), "B": np.dtype("float32")}},
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
- dtype=[("index", "<i8"), ("A", "i1"), ("B", "<f4"), ("C", "O")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}i8"),
+ ("A", "i1"),
+ ("B", f"{tm.ENDIAN}f4"),
+ ("C", "O"),
+ ],
),
),
# Mixture of everything.
(
{
"column_dtypes": {"A": np.int8, "B": np.float32},
- "index_dtypes": "<U2",
+ "index_dtypes": f"{tm.ENDIAN}U2",
},
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
- dtype=[("index", "<U2"), ("A", "i1"), ("B", "<f4"), ("C", "O")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}U2"),
+ ("A", "i1"),
+ ("B", f"{tm.ENDIAN}f4"),
+ ("C", "O"),
+ ],
),
),
# Invalid dype values.
@@ -299,7 +369,11 @@ def test_to_records_dtype(self, kwargs, expected):
{"column_dtypes": "float64", "index_dtypes": {0: "int32", 1: "int8"}},
np.rec.array(
[(1, 2, 3.0), (4, 5, 6.0), (7, 8, 9.0)],
- dtype=[("a", "<i4"), ("b", "i1"), ("c", "<f8")],
+ dtype=[
+ ("a", f"{tm.ENDIAN}i4"),
+ ("b", "i1"),
+ ("c", f"{tm.ENDIAN}f8"),
+ ],
),
),
# MultiIndex in the columns.
@@ -310,14 +384,17 @@ def test_to_records_dtype(self, kwargs, expected):
[("a", "d"), ("b", "e"), ("c", "f")]
),
),
- {"column_dtypes": {0: "<U1", 2: "float32"}, "index_dtypes": "float32"},
+ {
+ "column_dtypes": {0: f"{tm.ENDIAN}U1", 2: "float32"},
+ "index_dtypes": "float32",
+ },
np.rec.array(
[(0.0, "1", 2, 3.0), (1.0, "4", 5, 6.0), (2.0, "7", 8, 9.0)],
dtype=[
- ("index", "<f4"),
- ("('a', 'd')", "<U1"),
- ("('b', 'e')", "<i8"),
- ("('c', 'f')", "<f4"),
+ ("index", f"{tm.ENDIAN}f4"),
+ ("('a', 'd')", f"{tm.ENDIAN}U1"),
+ ("('b', 'e')", f"{tm.ENDIAN}i8"),
+ ("('c', 'f')", f"{tm.ENDIAN}f4"),
],
),
),
@@ -332,7 +409,10 @@ def test_to_records_dtype(self, kwargs, expected):
[("d", -4), ("d", -5), ("f", -6)], names=list("cd")
),
),
- {"column_dtypes": "float64", "index_dtypes": {0: "<U2", 1: "int8"}},
+ {
+ "column_dtypes": "float64",
+ "index_dtypes": {0: f"{tm.ENDIAN}U2", 1: "int8"},
+ },
np.rec.array(
[
("d", -4, 1.0, 2.0, 3.0),
@@ -340,11 +420,11 @@ def test_to_records_dtype(self, kwargs, expected):
("f", -6, 7, 8, 9.0),
],
dtype=[
- ("c", "<U2"),
+ ("c", f"{tm.ENDIAN}U2"),
("d", "i1"),
- ("('a', 'd')", "<f8"),
- ("('b', 'e')", "<f8"),
- ("('c', 'f')", "<f8"),
+ ("('a', 'd')", f"{tm.ENDIAN}f8"),
+ ("('b', 'e')", f"{tm.ENDIAN}f8"),
+ ("('c', 'f')", f"{tm.ENDIAN}f8"),
],
),
),
@@ -374,13 +454,18 @@ def keys(self):
dtype_mappings = {
"column_dtypes": DictLike(**{"A": np.int8, "B": np.float32}),
- "index_dtypes": "<U2",
+ "index_dtypes": f"{tm.ENDIAN}U2",
}
result = df.to_records(**dtype_mappings)
expected = np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
- dtype=[("index", "<U2"), ("A", "i1"), ("B", "<f4"), ("C", "O")],
+ dtype=[
+ ("index", f"{tm.ENDIAN}U2"),
+ ("A", "i1"),
+ ("B", f"{tm.ENDIAN}f4"),
+ ("C", "O"),
+ ],
)
tm.assert_almost_equal(result, expected)
diff --git a/pandas/tests/io/parser/test_c_parser_only.py b/pandas/tests/io/parser/test_c_parser_only.py
index 71af12b10b417..9a81790ca3bb0 100644
--- a/pandas/tests/io/parser/test_c_parser_only.py
+++ b/pandas/tests/io/parser/test_c_parser_only.py
@@ -144,9 +144,12 @@ def test_dtype_and_names_error(c_parser_only):
"the dtype timedelta64 is not supported for parsing",
{"dtype": {"A": "timedelta64", "B": "float64"}},
),
- ("the dtype <U8 is not supported for parsing", {"dtype": {"A": "U8"}}),
+ (
+ f"the dtype {tm.ENDIAN}U8 is not supported for parsing",
+ {"dtype": {"A": "U8"}},
+ ),
],
- ids=["dt64-0", "dt64-1", "td64", "<U8"],
+ ids=["dt64-0", "dt64-1", "td64", f"{tm.ENDIAN}U8"],
)
def test_unsupported_dtype(c_parser_only, match, kwargs):
parser = c_parser_only
diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py
index cf512463d0473..6c11ec42858c0 100644
--- a/pandas/tests/tools/test_to_timedelta.py
+++ b/pandas/tests/tools/test_to_timedelta.py
@@ -198,7 +198,8 @@ def test_to_timedelta_on_missing_values(self):
actual = to_timedelta(Series(["00:00:01", np.nan]))
expected = Series(
- [np.timedelta64(1000000000, "ns"), timedelta_NaT], dtype="<m8[ns]"
+ [np.timedelta64(1000000000, "ns"), timedelta_NaT],
+ dtype=f"{tm.ENDIAN}m8[ns]",
)
tm.assert_series_equal(actual, expected)
| These are all due to tests expecting little-endian dtypes, where in fact the endianness of the dtype is that of the host.
- [ ] closes #xxxx (Replace xxxx with the Github issue number) **No issue filed**
- [ ] [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 **Not applicable; fixes some tests on big-endian platforms**
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] 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/46681 | 2022-04-07T12:11:12Z | 2022-04-07T16:35:16Z | 2022-04-07T16:35:16Z | 2022-04-07T16:35:16Z |
DOC: generate docs for the `Series.dt.isocalendar()` method. | diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst
index a60dab549e66d..fcdc9ea9b95da 100644
--- a/doc/source/reference/series.rst
+++ b/doc/source/reference/series.rst
@@ -342,6 +342,7 @@ Datetime methods
:toctree: api/
:template: autosummary/accessor_method.rst
+ Series.dt.isocalendar
Series.dt.to_period
Series.dt.to_pydatetime
Series.dt.tz_localize
diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py
index a0bc0ae8e3511..26748a4342bb6 100644
--- a/pandas/core/indexes/accessors.py
+++ b/pandas/core/indexes/accessors.py
@@ -277,12 +277,13 @@ def isocalendar(self):
@property
def weekofyear(self):
"""
- The week ordinal of the year.
+ The week ordinal of the year according to the ISO 8601 standard.
.. deprecated:: 1.1.0
- Series.dt.weekofyear and Series.dt.week have been deprecated.
- Please use Series.dt.isocalendar().week instead.
+ Series.dt.weekofyear and Series.dt.week have been deprecated. Please
+ call :func:`Series.dt.isocalendar` and access the ``week`` column
+ instead.
"""
warnings.warn(
"Series.dt.weekofyear and Series.dt.week have been deprecated. "
| - [ ] 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 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/46674 | 2022-04-06T20:29:57Z | 2022-04-07T16:36:30Z | 2022-04-07T16:36:30Z | 2022-04-07T17:42:46Z |
Test added IntervalIndex_get_indexer_non_unique | diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 8880cab2ce29b..1d3033322511a 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -889,6 +889,51 @@ def test_is_all_dates(self):
year_2017_index = IntervalIndex([year_2017])
assert not year_2017_index._is_all_dates
+ @pytest.mark.parametrize(
+ "arrays",
+ [
+ IntervalIndex.from_breaks(
+ [
+ Timestamp("2018-01-02"),
+ Timestamp("2018-01-05"),
+ Timestamp("2018-01-08"),
+ Timestamp("2018-01-11"),
+ ],
+ closed="both",
+ ),
+ pd.array(
+ IntervalIndex.from_breaks(
+ [
+ Timestamp("2018-01-02"),
+ Timestamp("2018-01-05"),
+ Timestamp("2018-01-08"),
+ Timestamp("2018-01-11"),
+ ],
+ closed="both",
+ )
+ ),
+ list(
+ IntervalIndex.from_breaks(
+ [
+ Timestamp("2018-01-02"),
+ Timestamp("2018-01-05"),
+ Timestamp("2018-01-08"),
+ Timestamp("2018-01-11"),
+ ],
+ closed="both",
+ )
+ ),
+ ],
+ )
+ def test_IntervalIndex_get_indexer_non_unique(self, arrays):
+ # GH30178
+ int_inx = interval_range(Timestamp("2018-01-02"), freq="3D", periods=3)
+
+ actual = int_inx.get_indexer_non_unique(arrays)
+ expected = (np.array([0, 1, 2], dtype=np.int64), np.array([], dtype=np.int64))
+
+ tm.assert_equal(actual, expected)
+
def test_dir():
# GH#27571 dir(interval_index) should not raise
| - [x] closes #30178
- [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 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/46668 | 2022-04-06T13:38:03Z | 2022-05-25T22:42:44Z | null | 2022-05-25T22:42:44Z |
Backport PR #46663 on branch 1.4.x (CI/DOC: pin pydata-sphinx-theme to 0.8.0) | diff --git a/environment.yml b/environment.yml
index c23bb99c736dc..a90f28a2c9e16 100644
--- a/environment.yml
+++ b/environment.yml
@@ -34,7 +34,7 @@ dependencies:
- gitdb
- numpydoc < 1.2 # 2021-02-09 1.2dev breaking CI
- pandas-dev-flaker=0.4.0
- - pydata-sphinx-theme
+ - pydata-sphinx-theme=0.8.0
- pytest-cython
- sphinx
- sphinx-panels
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 6caa9a7512faf..bb6c5d9427d38 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -20,7 +20,7 @@ gitpython
gitdb
numpydoc < 1.2
pandas-dev-flaker==0.4.0
-pydata-sphinx-theme
+pydata-sphinx-theme==0.8.0
pytest-cython
sphinx
sphinx-panels
| Backport PR #46663 | https://api.github.com/repos/pandas-dev/pandas/pulls/46667 | 2022-04-06T13:36:56Z | 2022-04-07T00:13:57Z | 2022-04-07T00:13:57Z | 2022-04-07T09:37:10Z |
Allow using datetime64[ns, UTC] in IntervalDtype | diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index 58e91f46dff43..70b1f8a4b18e3 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -1054,7 +1054,8 @@ class IntervalDtype(PandasExtensionDtype):
"closed",
)
_match = re.compile(
- r"(I|i)nterval\[(?P<subtype>[^,]+)(, (?P<closed>(right|left|both|neither)))?\]"
+ r"(I|i)nterval\[(?P<subtype>[^,]+(\[.+\])?)"
+ r"(, (?P<closed>(right|left|both|neither)))?\]"
)
_cache_dtypes: dict[str_type, PandasExtensionDtype] = {}
| The current regexp doesn't allow the use of comma in the interval `subtype`, which means this statement fails
```
pd.IntervalIndex.from_arrays([1, 2], [2, 3], dtype='interval[datetime64[ns, UTC], right]')
```
with `TypeError: data type 'interval[datetime64[ns, UTC], right]' not understood`
The proposed change allows the use of comma inside square brackets in the `subtype`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/46666 | 2022-04-06T13:27:42Z | 2022-05-11T15:14:39Z | null | 2022-05-11T15:14:40Z |
TST/CI: simplify geopandas downstream test to not use fiona | diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-38-downstream_compat.yaml
index 01415122e6076..629d7b501692d 100644
--- a/ci/deps/actions-38-downstream_compat.yaml
+++ b/ci/deps/actions-38-downstream_compat.yaml
@@ -60,7 +60,7 @@ dependencies:
- cftime
- dask
- ipython
- - geopandas
+ - geopandas-base
- seaborn
- scikit-learn
- statsmodels
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index 83b476fefea46..b4887cc321785 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -8,7 +8,6 @@
import numpy as np
import pytest
-from pandas.compat import is_platform_windows
import pandas.util._test_decorators as td
import pandas as pd
@@ -224,20 +223,13 @@ def test_pandas_datareader():
pandas_datareader.DataReader("F", "quandl", "2017-01-01", "2017-02-01")
-# importing from pandas, Cython import warning
-@pytest.mark.filterwarnings("ignore:can't resolve:ImportWarning")
-@pytest.mark.xfail(
- is_platform_windows(),
- raises=ImportError,
- reason="ImportError: the 'read_file' function requires the 'fiona' package, "
- "but it is not installed or does not import correctly",
- strict=False,
-)
def test_geopandas():
geopandas = import_module("geopandas")
- fp = geopandas.datasets.get_path("naturalearth_lowres")
- assert geopandas.read_file(fp) is not None
+ gdf = geopandas.GeoDataFrame(
+ {"col": [1, 2, 3], "geometry": geopandas.points_from_xy([1, 2, 3], [1, 2, 3])}
+ )
+ assert gdf[["col", "geometry"]].geometry.x.equals(Series([1.0, 2.0, 3.0]))
# Cython import warning
| xref https://github.com/pandas-dev/pandas/pull/46536#issuecomment-1090244769 | https://api.github.com/repos/pandas-dev/pandas/pulls/46665 | 2022-04-06T13:09:55Z | 2022-04-06T21:58:37Z | 2022-04-06T21:58:37Z | 2022-04-07T06:12:43Z |
BUG: Fix infinite recursion loop when pivot of IntervalTree is ±inf | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 61848cb127029..4ad3f9e2ea391 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -786,6 +786,8 @@ Indexing
- Bug in :meth:`Series.asof` and :meth:`DataFrame.asof` incorrectly casting bool-dtype results to ``float64`` dtype (:issue:`16063`)
- Bug in :meth:`NDFrame.xs`, :meth:`DataFrame.iterrows`, :meth:`DataFrame.loc` and :meth:`DataFrame.iloc` not always propagating metadata (:issue:`28283`)
- Bug in :meth:`DataFrame.sum` min_count changes dtype if input contains NaNs (:issue:`46947`)
+- Bug in :class:`IntervalTree` that lead to an infinite recursion. (:issue:`46658`)
+-
Missing
^^^^^^^
diff --git a/pandas/_libs/intervaltree.pxi.in b/pandas/_libs/intervaltree.pxi.in
index 51db5f1e76c99..9842332bae7ef 100644
--- a/pandas/_libs/intervaltree.pxi.in
+++ b/pandas/_libs/intervaltree.pxi.in
@@ -342,6 +342,13 @@ cdef class {{dtype_title}}Closed{{closed_title}}IntervalNode(IntervalNode):
# calculate a pivot so we can create child nodes
self.is_leaf_node = False
self.pivot = np.median(left / 2 + right / 2)
+ if np.isinf(self.pivot):
+ self.pivot = cython.cast({{dtype}}_t, 0)
+ if self.pivot > np.max(right):
+ self.pivot = np.max(left)
+ if self.pivot < np.min(left):
+ self.pivot = np.min(right)
+
left_set, right_set, center_set = self.classify_intervals(
left, right)
diff --git a/pandas/tests/indexes/interval/test_interval_tree.py b/pandas/tests/indexes/interval/test_interval_tree.py
index 345025d63f4b2..06c499b9e33f4 100644
--- a/pandas/tests/indexes/interval/test_interval_tree.py
+++ b/pandas/tests/indexes/interval/test_interval_tree.py
@@ -207,3 +207,21 @@ def test_interval_tree_error_and_warning(self):
):
left, right = np.arange(10), [np.iinfo(np.int64).max] * 10
IntervalTree(left, right, closed="both")
+
+ @pytest.mark.xfail(not IS64, reason="GH 23440")
+ @pytest.mark.parametrize(
+ "left, right, expected",
+ [
+ ([-np.inf, 1.0], [1.0, 2.0], 0.0),
+ ([-np.inf, -2.0], [-2.0, -1.0], -2.0),
+ ([-2.0, -1.0], [-1.0, np.inf], 0.0),
+ ([1.0, 2.0], [2.0, np.inf], 2.0),
+ ],
+ )
+ def test_inf_bound_infinite_recursion(self, left, right, expected):
+ # GH 46658
+
+ tree = IntervalTree(left * 101, right * 101)
+
+ result = tree.root.pivot
+ assert result == expected
diff --git a/pandas/tests/indexing/interval/test_interval_new.py b/pandas/tests/indexing/interval/test_interval_new.py
index 2e3c765b2b372..602f45d637afb 100644
--- a/pandas/tests/indexing/interval/test_interval_new.py
+++ b/pandas/tests/indexing/interval/test_interval_new.py
@@ -3,7 +3,10 @@
import numpy as np
import pytest
+from pandas.compat import IS64
+
from pandas import (
+ Index,
Interval,
IntervalIndex,
Series,
@@ -217,3 +220,24 @@ def test_loc_getitem_missing_key_error_message(
obj = frame_or_series(ser)
with pytest.raises(KeyError, match=r"\[6\]"):
obj.loc[[4, 5, 6]]
+
+
+@pytest.mark.xfail(not IS64, reason="GH 23440")
+@pytest.mark.parametrize(
+ "intervals",
+ [
+ ([Interval(-np.inf, 0.0), Interval(0.0, 1.0)]),
+ ([Interval(-np.inf, -2.0), Interval(-2.0, -1.0)]),
+ ([Interval(-1.0, 0.0), Interval(0.0, np.inf)]),
+ ([Interval(1.0, 2.0), Interval(2.0, np.inf)]),
+ ],
+)
+def test_repeating_interval_index_with_infs(intervals):
+ # GH 46658
+
+ interval_index = Index(intervals * 51)
+
+ expected = np.arange(1, 102, 2, dtype=np.intp)
+ result = interval_index.get_indexer_for([intervals[1]])
+
+ tm.assert_equal(result, expected)
| When the pivot of an IntervalTree becomes ±inf the construction of the
IntervalTree comes to an infinite loop recursion. This patch tries to fix that
by catching those cases and set the pivot to a reasonable value.
- [x] closes #46658
- [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 an entry in the latest `doc/source/whatsnew/v1.5.0.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/46664 | 2022-04-06T11:58:49Z | 2022-06-06T17:03:40Z | 2022-06-06T17:03:39Z | 2022-06-06T17:03:47Z |
CI/DOC: pin pydata-sphinx-theme to 0.8.0 | diff --git a/environment.yml b/environment.yml
index c6ac88a622ad8..dc3cba3be2132 100644
--- a/environment.yml
+++ b/environment.yml
@@ -34,7 +34,7 @@ dependencies:
- gitdb
- numpydoc
- pandas-dev-flaker=0.5.0
- - pydata-sphinx-theme
+ - pydata-sphinx-theme=0.8.0
- pytest-cython
- sphinx
- sphinx-panels
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 4942ba509ded9..a3f71ac2a3aa5 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -20,7 +20,7 @@ gitpython
gitdb
numpydoc
pandas-dev-flaker==0.5.0
-pydata-sphinx-theme
+pydata-sphinx-theme==0.8.0
pytest-cython
sphinx
sphinx-panels
| Temporary fix for https://github.com/pandas-dev/pandas/issues/46615 | https://api.github.com/repos/pandas-dev/pandas/pulls/46663 | 2022-04-06T11:52:12Z | 2022-04-06T13:14:18Z | 2022-04-06T13:14:18Z | 2022-04-06T13:37:32Z |
TST: added test for joining dataframes with MultiIndex containing dates | diff --git a/pandas/tests/frame/methods/test_join.py b/pandas/tests/frame/methods/test_join.py
index c6bfd94b84908..8ad0fdf344edf 100644
--- a/pandas/tests/frame/methods/test_join.py
+++ b/pandas/tests/frame/methods/test_join.py
@@ -323,6 +323,26 @@ def test_join_multiindex_leftright(self):
tm.assert_frame_equal(df1.join(df2, how="right"), exp)
tm.assert_frame_equal(df2.join(df1, how="left"), exp[["value2", "value1"]])
+ def test_join_multiindex_dates(self):
+ # GH 33692
+ date = pd.Timestamp(2000, 1, 1).date()
+
+ df1_index = MultiIndex.from_tuples([(0, date)], names=["index_0", "date"])
+ df1 = DataFrame({"col1": [0]}, index=df1_index)
+ df2_index = MultiIndex.from_tuples([(0, date)], names=["index_0", "date"])
+ df2 = DataFrame({"col2": [0]}, index=df2_index)
+ df3_index = MultiIndex.from_tuples([(0, date)], names=["index_0", "date"])
+ df3 = DataFrame({"col3": [0]}, index=df3_index)
+
+ result = df1.join([df2, df3])
+
+ expected_index = MultiIndex.from_tuples([(0, date)], names=["index_0", "date"])
+ expected = DataFrame(
+ {"col1": [0], "col2": [0], "col3": [0]}, index=expected_index
+ )
+
+ tm.assert_equal(result, expected)
+
def test_merge_join_different_levels(self):
# GH#9455
| - [X] closes #33692
- [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 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/46660 | 2022-04-06T10:40:43Z | 2022-04-07T19:25:27Z | 2022-04-07T19:25:26Z | 2022-04-07T19:40:39Z |
BUG: df.nsmallest get wrong results when NaN in the sorting column | diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst
index 8572c136c28a9..0c326e15d90ed 100644
--- a/doc/source/whatsnew/v1.4.3.rst
+++ b/doc/source/whatsnew/v1.4.3.rst
@@ -14,6 +14,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Fixed regression in :meth:`DataFrame.nsmallest` led to wrong results when ``np.nan`` in the sorting column (:issue:`46589`)
- Fixed regression in :func:`read_fwf` raising ``ValueError`` when ``widths`` was specified with ``usecols`` (:issue:`46580`)
-
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 6c1dfc4c0da72..0c0b93f41c657 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1181,7 +1181,6 @@ def compute(self, method: str) -> Series:
arr = arr[::-1]
nbase = n
- findex = len(self.obj)
narr = len(arr)
n = min(n, narr)
@@ -1194,6 +1193,11 @@ def compute(self, method: str) -> Series:
if self.keep != "all":
inds = inds[:n]
findex = nbase
+ else:
+ if len(inds) < nbase and len(nan_index) + len(inds) >= nbase:
+ findex = len(nan_index) + len(inds)
+ else:
+ findex = len(inds)
if self.keep == "last":
# reverse indices
diff --git a/pandas/tests/frame/methods/test_nlargest.py b/pandas/tests/frame/methods/test_nlargest.py
index 1b2db80d782ce..a317dae562ae0 100644
--- a/pandas/tests/frame/methods/test_nlargest.py
+++ b/pandas/tests/frame/methods/test_nlargest.py
@@ -216,3 +216,24 @@ def test_nlargest_nan(self):
result = df.nlargest(5, 0)
expected = df.sort_values(0, ascending=False).head(5)
tm.assert_frame_equal(result, expected)
+
+ def test_nsmallest_nan_after_n_element(self):
+ # GH#46589
+ df = pd.DataFrame(
+ {
+ "a": [1, 2, 3, 4, 5, None, 7],
+ "b": [7, 6, 5, 4, 3, 2, 1],
+ "c": [1, 1, 2, 2, 3, 3, 3],
+ },
+ index=range(7),
+ )
+ result = df.nsmallest(5, columns=["a", "b"])
+ expected = pd.DataFrame(
+ {
+ "a": [1, 2, 3, 4, 5],
+ "b": [7, 6, 5, 4, 3],
+ "c": [1, 1, 2, 2, 3],
+ },
+ index=range(5),
+ ).astype({"a": "float"})
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_nlargest.py b/pandas/tests/series/methods/test_nlargest.py
index ee96ab08ad66c..4f07257038bc9 100644
--- a/pandas/tests/series/methods/test_nlargest.py
+++ b/pandas/tests/series/methods/test_nlargest.py
@@ -231,3 +231,15 @@ def test_nlargest_nullable(self, any_numeric_ea_dtype):
.astype(dtype)
)
tm.assert_series_equal(result, expected)
+
+ def test_nsmallest_nan_when_keep_is_all(self):
+ # GH#46589
+ s = Series([1, 2, 3, 3, 3, None])
+ result = s.nsmallest(3, keep="all")
+ expected = Series([1.0, 2.0, 3.0, 3.0, 3.0])
+ tm.assert_series_equal(result, expected)
+
+ s = Series([1, 2, None, None, None])
+ result = s.nsmallest(3, keep="all")
+ expected = Series([1, 2, None, None, None])
+ tm.assert_series_equal(result, expected)
| - [x] closes #46589
- [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).
- [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/46656 | 2022-04-06T06:24:11Z | 2022-04-10T16:59:38Z | 2022-04-10T16:59:37Z | 2022-04-12T10:34:42Z |
TST: add validation checks on levels keyword from pd.concat | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 73dc832e2007b..de4d70473f91e 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -92,6 +92,9 @@ Other enhancements
- :class:`Series` and :class:`DataFrame` with ``IntegerDtype`` now supports bitwise operations (:issue:`34463`)
- Add ``milliseconds`` field support for :class:`~pandas.DateOffset` (:issue:`43371`)
- :meth:`DataFrame.reset_index` now accepts a ``names`` argument which renames the index names (:issue:`6878`)
+- :meth:`pd.concat` now raises when ``levels`` is given but ``keys`` is None (:issue:`46653`)
+- :meth:`pd.concat` now raises when ``levels`` contains duplicate values (:issue:`46653`)
+-
.. ---------------------------------------------------------------------------
.. _whatsnew_150.notable_bug_fixes:
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index f2227a3e2ac83..054fbb85cead7 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -668,6 +668,8 @@ def _get_concat_axis(self) -> Index:
return idx
if self.keys is None:
+ if self.levels is not None:
+ raise ValueError("levels supported only when keys is not None")
concat_axis = _concat_indexes(indexes)
else:
concat_axis = _make_concat_multiindex(
@@ -712,6 +714,10 @@ def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde
else:
levels = [ensure_index(x) for x in levels]
+ for level in levels:
+ if not level.is_unique:
+ raise ValueError(f"Level values not unique: {level.tolist()}")
+
if not all_indexes_same(indexes) or not all(level.is_unique for level in levels):
codes_list = []
diff --git a/pandas/tests/reshape/concat/test_index.py b/pandas/tests/reshape/concat/test_index.py
index 50fee28669c58..b20e4bcc2256b 100644
--- a/pandas/tests/reshape/concat/test_index.py
+++ b/pandas/tests/reshape/concat/test_index.py
@@ -371,3 +371,19 @@ def test_concat_with_key_not_unique(self):
out_b = df_b.loc[("x", 0), :]
tm.assert_frame_equal(out_a, out_b)
+
+ def test_concat_with_duplicated_levels(self):
+ # keyword levels should be unique
+ df1 = DataFrame({"A": [1]}, index=["x"])
+ df2 = DataFrame({"A": [1]}, index=["y"])
+ msg = r"Level values not unique: \['x', 'y', 'y'\]"
+ with pytest.raises(ValueError, match=msg):
+ concat([df1, df2], keys=["x", "y"], levels=[["x", "y", "y"]])
+
+ @pytest.mark.parametrize("levels", [[["x", "y"]], [["x", "y", "y"]]])
+ def test_concat_with_levels_with_none_keys(self, levels):
+ df1 = DataFrame({"A": [1]}, index=["x"])
+ df2 = DataFrame({"A": [1]}, index=["y"])
+ msg = "levels supported only when keys is not None"
+ with pytest.raises(ValueError, match=msg):
+ concat([df1, df2], levels=levels)
| - [x] closes #46653
- [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).
- [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/46654 | 2022-04-06T04:23:21Z | 2022-04-07T00:15:26Z | 2022-04-07T00:15:26Z | 2022-04-07T00:20:57Z |
DOC: fix SA04 errors flagged by validate_docstrings.py and add SA04 t… | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index ec8545ad1ee4a..c6d9698882f4d 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -78,8 +78,8 @@ fi
### DOCSTRINGS ###
if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
- MSG='Validate docstrings (EX04, GL01, GL02, GL03, GL04, GL05, GL06, GL07, GL09, GL10, PR03, PR04, PR05, PR06, PR08, PR09, PR10, RT01, RT04, RT05, SA02, SA03, SS01, SS02, SS03, SS04, SS05)' ; echo $MSG
- $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX04,GL01,GL02,GL03,GL04,GL05,GL06,GL07,GL09,GL10,PR03,PR04,PR05,PR06,PR08,PR09,PR10,RT01,RT04,RT05,SA02,SA03,SS01,SS02,SS03,SS04,SS05
+ MSG='Validate docstrings (EX04, GL01, GL02, GL03, GL04, GL05, GL06, GL07, GL09, GL10, PR03, PR04, PR05, PR06, PR08, PR09, PR10, RT01, RT04, RT05, SA02, SA03, SA04, SS01, SS02, SS03, SS04, SS05)' ; echo $MSG
+ $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX04,GL01,GL02,GL03,GL04,GL05,GL06,GL07,GL09,GL10,PR03,PR04,PR05,PR06,PR08,PR09,PR10,RT01,RT04,RT05,SA02,SA03,SA04,SS01,SS02,SS03,SS04,SS05
RET=$(($RET + $?)) ; echo $MSG "DONE"
fi
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 2ded3c4926f6b..80527474f2be6 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4371,8 +4371,8 @@ def reindex(
See Also
--------
- Series.reindex
- DataFrame.reindex
+ Series.reindex : Conform Series to new index with optional filling logic.
+ DataFrame.reindex : Conform DataFrame to new index with optional filling logic.
Examples
--------
| - [x] closes #25337
- [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).
- [NA] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Many of the SA04 reported in #25337 are already fixed, but there were two outstanding SA04 errors reported by valdiate_docstrings.py on main. So, I fixed those and added 'SA04' to the code_checks.py as per #25337
| https://api.github.com/repos/pandas-dev/pandas/pulls/46652 | 2022-04-06T03:35:51Z | 2022-04-12T01:29:29Z | 2022-04-12T01:29:28Z | 2022-04-12T01:29:36Z |
DOC: clarified read_csv example | diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py
index c639f408c75f5..cf9195992a2c1 100644
--- a/pandas/io/parsers/readers.py
+++ b/pandas/io/parsers/readers.py
@@ -432,7 +432,7 @@
Examples
--------
->>> pd.{func_name}('data.csv') # doctest: +SKIP
+>>> df = pd.{func_name}('data.csv') # doctest: +SKIP
"""
)
| * Simple clarification to the read_csv/read_fwf docs so that the example actually loads data into a dataframe.
| https://api.github.com/repos/pandas-dev/pandas/pulls/46650 | 2022-04-06T02:42:05Z | 2022-04-22T14:43:45Z | null | 2022-04-22T14:49:57Z |
Backport PR #46647 on branch 1.4.x (CI/DOC: Unpin jinja2) | diff --git a/environment.yml b/environment.yml
index 753e210e6066a..c23bb99c736dc 100644
--- a/environment.yml
+++ b/environment.yml
@@ -44,7 +44,7 @@ dependencies:
- types-setuptools
# documentation (jupyter notebooks)
- - nbconvert>=5.4.1
+ - nbconvert>=6.4.5
- nbsphinx
- pandoc
@@ -86,7 +86,7 @@ dependencies:
- bottleneck>=1.3.1
- ipykernel
- ipython>=7.11.1
- - jinja2<=3.0.3 # pandas.Styler
+ - jinja2 # pandas.Styler
- matplotlib>=3.3.2 # pandas.plotting, Series.plot, DataFrame.plot
- numexpr>=2.7.1
- scipy>=1.4.1
diff --git a/requirements-dev.txt b/requirements-dev.txt
index c4f6bb30c59ec..6caa9a7512faf 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -28,7 +28,7 @@ types-python-dateutil
types-PyMySQL
types-pytz
types-setuptools
-nbconvert>=5.4.1
+nbconvert>=6.4.5
nbsphinx
pandoc
dask
@@ -58,7 +58,7 @@ blosc
bottleneck>=1.3.1
ipykernel
ipython>=7.11.1
-jinja2<=3.0.3
+jinja2
matplotlib>=3.3.2
numexpr>=2.7.1
scipy>=1.4.1
| Backport PR #46647: CI/DOC: Unpin jinja2 | https://api.github.com/repos/pandas-dev/pandas/pulls/46649 | 2022-04-05T23:36:58Z | 2022-04-06T00:48:53Z | 2022-04-06T00:48:53Z | 2022-04-06T00:48:53Z |
BUG/TST/DOC: added finalize to melt, GH28283 | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 73dc832e2007b..4ef7e74e4f722 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -620,6 +620,7 @@ Styler
Metadata
^^^^^^^^
+- Fixed metadata propagation in :meth:`DataFrame.melt` (:issue:`28283`)
- Fixed metadata propagation in :meth:`DataFrame.explode` (:issue:`28283`)
-
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 683674d8ef826..6c754683c7a98 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8717,7 +8717,7 @@ def melt(
value_name=value_name,
col_level=col_level,
ignore_index=ignore_index,
- )
+ ).__finalize__(self, method="melt")
# ----------------------------------------------------------------------
# Time series-related
diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py
index 9e5e616148a32..999fee5c8281c 100644
--- a/pandas/tests/generic/test_finalize.py
+++ b/pandas/tests/generic/test_finalize.py
@@ -156,13 +156,10 @@
(pd.DataFrame, frame_data, operator.methodcaller("stack")),
(pd.DataFrame, frame_data, operator.methodcaller("explode", "A")),
(pd.DataFrame, frame_mi_data, operator.methodcaller("unstack")),
- pytest.param(
- (
- pd.DataFrame,
- ({"A": ["a", "b", "c"], "B": [1, 3, 5], "C": [2, 4, 6]},),
- operator.methodcaller("melt", id_vars=["A"], value_vars=["B"]),
- ),
- marks=not_implemented_mark,
+ (
+ pd.DataFrame,
+ ({"A": ["a", "b", "c"], "B": [1, 3, 5], "C": [2, 4, 6]},),
+ operator.methodcaller("melt", id_vars=["A"], value_vars=["B"]),
),
pytest.param(
(pd.DataFrame, frame_data, operator.methodcaller("applymap", lambda x: x))
| Progress towards #28283
This PR gives the `melt` method the ability to propagate metadata using `__finalize__`.
- [ ] xref #28283
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests)
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added an entry in the latest `doc/source/whatsnew/v1.5.0.rst` file
Contributors:
- [Edward Huang](https://github.com/edwhuang23)
- [Solomon Song](https://github.com/songsol1) | https://api.github.com/repos/pandas-dev/pandas/pulls/46648 | 2022-04-05T20:55:52Z | 2022-04-08T00:21:24Z | 2022-04-08T00:21:24Z | 2022-04-08T00:21:40Z |
CI/DOC: Unpin jinja2 | diff --git a/environment.yml b/environment.yml
index e991f29b8a727..c6ac88a622ad8 100644
--- a/environment.yml
+++ b/environment.yml
@@ -44,7 +44,7 @@ dependencies:
- types-setuptools
# documentation (jupyter notebooks)
- - nbconvert>=5.4.1
+ - nbconvert>=6.4.5
- nbsphinx
- pandoc
@@ -86,7 +86,7 @@ dependencies:
- bottleneck>=1.3.1
- ipykernel
- ipython>=7.11.1
- - jinja2<=3.0.3 # pandas.Styler
+ - jinja2 # pandas.Styler
- matplotlib>=3.3.2 # pandas.plotting, Series.plot, DataFrame.plot
- numexpr>=2.7.1
- scipy>=1.4.1
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 22692da8f0ed4..4942ba509ded9 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -28,7 +28,7 @@ types-python-dateutil
types-PyMySQL
types-pytz
types-setuptools
-nbconvert>=5.4.1
+nbconvert>=6.4.5
nbsphinx
pandoc
dask
@@ -58,7 +58,7 @@ blosc
bottleneck>=1.3.1
ipykernel
ipython>=7.11.1
-jinja2<=3.0.3
+jinja2
matplotlib>=3.3.2
numexpr>=2.7.1
scipy>=1.4.1
| - [x] closes #46514 (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
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Should be closed by https://github.com/jupyter/nbconvert/pull/1737; we'll see if CI agrees. Also specifies `nbconvert>=6.4.5`; this is the most recent version of nbconvert but because this is only for dev I think it's okay. | https://api.github.com/repos/pandas-dev/pandas/pulls/46647 | 2022-04-05T20:32:44Z | 2022-04-05T23:36:23Z | 2022-04-05T23:36:22Z | 2022-04-07T02:43:26Z |
TST: Regression test added for Timedelta | diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index f077317e7ebbe..580d136505210 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -1107,3 +1107,15 @@ def test_compare_complex_dtypes():
with pytest.raises(TypeError, match=msg):
df.lt(df.astype(object))
+
+
+def test_categorical_of_booleans_is_boolean():
+ # https://github.com/pandas-dev/pandas/issues/46313
+ df = pd.DataFrame(
+ {"int_cat": [1, 2, 3], "bool_cat": [True, False, False]}, dtype="category"
+ )
+ value = df["bool_cat"].cat.categories.dtype
+ expected = np.dtype(np.bool_)
+ not_expected = np.dtype(np.object_)
+ assert value is expected
+ assert value is not not_expected
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 82c7117cc00c6..10eb367c08517 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -89,6 +89,21 @@ def test_constructor_from_2d_datetimearray(self, using_array_manager):
# GH#44724 big performance hit if we de-consolidate
assert len(df._mgr.blocks) == 1
+ def test_no_overflow_of_freq_and_time_in_dataframe(self):
+ # GH 35665
+ # https://github.com/pandas-dev/pandas/issues/35665
+ df = DataFrame(
+ {
+ "string_one": ["2132131SSS"],
+ "time": [Timedelta("0 days 00:00:00.990000")],
+ }
+ )
+ try:
+ for _, row in df.iterrows():
+ row
+ except OverflowError:
+ assert False, "Regression, see GH 35665"
+
def test_constructor_dict_with_tzaware_scalar(self):
# GH#42505
dt = Timestamp("2019-11-03 01:00:00-0700").tz_convert("America/Los_Angeles")
|
- [x] closes #35665
- [x] [Tests added and passed]
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
The commit on Mar 18 is approved. Not sure why it is showing up here... You can see it here:
https://github.com/pandas-dev/pandas/pull/46422
This PR adds a regression test for #35665 , which was caused by #38965. Please let me know if there's more I need to do! Thanks! | https://api.github.com/repos/pandas-dev/pandas/pulls/46645 | 2022-04-05T19:34:25Z | 2022-05-24T21:03:53Z | null | 2022-05-24T21:03:53Z |
BUG: DataFrame.dropna must not allow to set both how= and thresh= parameters | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 595845e107cf8..216a9846ac241 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -570,7 +570,7 @@ Missing
- Bug in :meth:`Series.fillna` and :meth:`DataFrame.fillna` with ``downcast`` keyword not being respected in some cases where there are no NA values present (:issue:`45423`)
- Bug in :meth:`Series.fillna` and :meth:`DataFrame.fillna` with :class:`IntervalDtype` and incompatible value raising instead of casting to a common (usually object) dtype (:issue:`45796`)
- Bug in :meth:`DataFrame.interpolate` with object-dtype column not returning a copy with ``inplace=False`` (:issue:`45791`)
--
+- Bug in :meth:`DataFrame.dropna` allows to set both ``how`` and ``thresh`` incompatible arguments (:issue:`46575`)
MultiIndex
^^^^^^^^^^
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index a79e23058ef98..7270d73e29741 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -42,7 +42,10 @@
properties,
)
from pandas._libs.hashtable import duplicated
-from pandas._libs.lib import no_default
+from pandas._libs.lib import (
+ NoDefault,
+ no_default,
+)
from pandas._typing import (
AggFuncType,
AnyArrayLike,
@@ -6110,8 +6113,8 @@ def notnull(self) -> DataFrame:
def dropna(
self,
axis: Axis = 0,
- how: str = "any",
- thresh=None,
+ how: str | NoDefault = no_default,
+ thresh: int | NoDefault = no_default,
subset: IndexLabel = None,
inplace: bool = False,
):
@@ -6143,7 +6146,7 @@ def dropna(
* 'all' : If all values are NA, drop that row or column.
thresh : int, optional
- Require that many non-NA values.
+ Require that many non-NA values. Cannot be combined with how.
subset : column label or sequence of labels, optional
Labels along other axis to consider, e.g. if you are dropping rows
these would be a list of columns to include.
@@ -6218,6 +6221,14 @@ def dropna(
name toy born
1 Batman Batmobile 1940-04-25
"""
+ if (how is not no_default) and (thresh is not no_default):
+ raise TypeError(
+ "You cannot set both the how and thresh arguments at the same time."
+ )
+
+ if how is no_default:
+ how = "any"
+
inplace = validate_bool_kwarg(inplace, "inplace")
if isinstance(axis, (tuple, list)):
# GH20987
@@ -6238,7 +6249,7 @@ def dropna(
raise KeyError(np.array(subset)[check].tolist())
agg_obj = self.take(indices, axis=agg_axis)
- if thresh is not None:
+ if thresh is not no_default:
count = agg_obj.count(axis=agg_axis)
mask = count >= thresh
elif how == "any":
@@ -6248,10 +6259,8 @@ def dropna(
# faster equivalent to 'agg_obj.count(agg_axis) > 0'
mask = notna(agg_obj).any(axis=agg_axis, bool_only=False)
else:
- if how is not None:
+ if how is not no_default:
raise ValueError(f"invalid how option: {how}")
- else:
- raise TypeError("must specify how or thresh")
if np.all(mask):
result = self.copy()
diff --git a/pandas/tests/frame/methods/test_dropna.py b/pandas/tests/frame/methods/test_dropna.py
index d0b9eebb31b93..43cecc6a1aed5 100644
--- a/pandas/tests/frame/methods/test_dropna.py
+++ b/pandas/tests/frame/methods/test_dropna.py
@@ -158,9 +158,6 @@ def test_dropna_corner(self, float_frame):
msg = "invalid how option: foo"
with pytest.raises(ValueError, match=msg):
float_frame.dropna(how="foo")
- msg = "must specify how or thresh"
- with pytest.raises(TypeError, match=msg):
- float_frame.dropna(how=None)
# non-existent column - 8303
with pytest.raises(KeyError, match=r"^\['X'\]$"):
float_frame.dropna(subset=["A", "X"])
@@ -274,3 +271,16 @@ def test_no_nans_in_frame(self, axis):
expected = df.copy()
result = df.dropna(axis=axis)
tm.assert_frame_equal(result, expected, check_index_type=True)
+
+ def test_how_thresh_param_incompatible(self):
+ # GH46575
+ df = DataFrame([1, 2, pd.NA])
+ msg = "You cannot set both the how and thresh arguments at the same time"
+ with pytest.raises(TypeError, match=msg):
+ df.dropna(how="all", thresh=2)
+
+ with pytest.raises(TypeError, match=msg):
+ df.dropna(how="any", thresh=2)
+
+ with pytest.raises(TypeError, match=msg):
+ df.dropna(how=None, thresh=None)
| - [x] closes #46575
- [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 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/46644 | 2022-04-05T15:45:25Z | 2022-04-27T22:23:19Z | 2022-04-27T22:23:19Z | 2022-04-28T08:44:14Z |
DOC: .bfill() (#46631) | diff --git a/doc/source/user_guide/cookbook.rst b/doc/source/user_guide/cookbook.rst
index f88f4a9708c45..d0b2119f9d315 100644
--- a/doc/source/user_guide/cookbook.rst
+++ b/doc/source/user_guide/cookbook.rst
@@ -423,7 +423,7 @@ Fill forward a reversed timeseries
)
df.loc[df.index[3], "A"] = np.nan
df
- df.reindex(df.index[::-1]).ffill()
+ df.bfill()
`cumsum reset at NaN values
<https://stackoverflow.com/questions/18196811/cumsum-reset-at-nan>`__
| - [x] closes #46631 (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 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/46642 | 2022-04-05T04:23:38Z | 2022-04-05T23:35:32Z | 2022-04-05T23:35:31Z | 2022-04-05T23:35:36Z |
added test for replace with value none | diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py
index 870a64cfa59c9..2637473334f8e 100644
--- a/pandas/tests/frame/methods/test_replace.py
+++ b/pandas/tests/frame/methods/test_replace.py
@@ -1486,6 +1486,13 @@ def test_replace_list_with_mixed_type(
tm.assert_equal(result, expected)
+ def test_replace_value_none(self):
+ #GH46606
+ df = DataFrame(dict(a=[1,2,3], b=[1,2,3]))
+ result = df.replace({1:5}, value=None)
+ expected = DataFrame(dict(a=[5,2,3], b=[1,2,3]))
+ tm.assert_frame_equal(result, expected)
+
class TestDataFrameReplaceRegex:
@pytest.mark.parametrize(
"data",
| - [ ] closes #46606
- [ ] Added test to pandas\tests\frame\methods\test_replace.py
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
| https://api.github.com/repos/pandas-dev/pandas/pulls/46641 | 2022-04-05T03:25:52Z | 2022-05-08T22:35:52Z | null | 2022-05-08T22:35:52Z |
homogeneous Period targets bug fix | diff --git a/sample.py b/sample.py
new file mode 100644
index 0000000000000..ac0ec6c193401
--- /dev/null
+++ b/sample.py
@@ -0,0 +1,37 @@
+import pandas as pd;
+print("version",pd.__version__)
+
+# date_interval = pd.interval_range(pd.Timestamp('2018-01-01'), freq='3D', periods=3)
+# print("data",date_interval)
+# table_format = pd.DataFrame({'date': date_interval})
+# print("Table Format")
+# print(table_format)
+
+# pi = pd.period_range('2018-01-01', freq='D', periods=3)
+# print("sequence of date", pi)
+
+# print("different between list and astype")
+# print("list of object--> ",list(pi), " only date--> ", list(pi.astype(str)))
+# array1 = date_interval.get_indexer(list(pi.astype(str)))
+# print(array1)
+
+date_interval = pd.interval_range(pd.Timestamp('2018-01-01'), freq='3D', periods=3)
+print("interval range", date_interval)
+pi = pd.period_range('2018-01-05', freq='D', periods=3)
+print("value to test", pi)
+array = date_interval.get_indexer(pi)
+print("array of object",pd.array(pi))
+array1 = date_interval.get_indexer(pd.array(pi))
+print("list of object",list(pi))
+array3 = date_interval.get_indexer(list(pi))
+print("value to test",list(pi) + [10])
+array4 = date_interval.get_indexer(list(pi) + [10])
+print("wrong output is", array4)
+
+print("correct format",list(pi.astype(str)))
+output = date_interval.get_indexer(list(pi.astype(str)))
+print("Proper output", output)
+
+
+
+
| - [ ] 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 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/46640 | 2022-04-04T20:38:46Z | 2022-04-07T19:33:38Z | null | 2022-04-07T19:33:38Z |
Update __init__.py | diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py
index 44f999cb1296a..4f27db7bf0af4 100644
--- a/pandas/errors/__init__.py
+++ b/pandas/errors/__init__.py
@@ -7,6 +7,8 @@
from pandas._libs.tslibs import ( # noqa:F401
OutOfBoundsDatetime,
OutOfBoundsTimedelta,
+ OutOfBoundsTimedeltahhh,
+
)
| - [ ] 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 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/46639 | 2022-04-04T20:08:43Z | 2022-04-04T20:30:26Z | null | 2022-04-04T20:30:35Z |
TYP: tighten return type in function any | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index ef5e6dd1d6757..bc190257a1cdd 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8988,6 +8988,42 @@ def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs):
agg = aggregate
+ # error: Signature of "any" incompatible with supertype "NDFrame" [override]
+ @overload # type: ignore[override]
+ def any(
+ self,
+ *,
+ axis: Axis = ...,
+ bool_only: bool | None = ...,
+ skipna: bool = ...,
+ level: None = ...,
+ **kwargs,
+ ) -> Series:
+ ...
+
+ @overload
+ def any(
+ self,
+ *,
+ axis: Axis = ...,
+ bool_only: bool | None = ...,
+ skipna: bool = ...,
+ level: Level,
+ **kwargs,
+ ) -> DataFrame | Series:
+ ...
+
+ @doc(NDFrame.any, **_shared_doc_kwargs)
+ def any(
+ self,
+ axis: Axis = 0,
+ bool_only: bool | None = None,
+ skipna: bool = True,
+ level: Level | None = None,
+ **kwargs,
+ ) -> DataFrame | Series:
+ ...
+
@doc(
_shared_docs["transform"],
klass=_shared_doc_kwargs["klass"],
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 1d3509cac0edd..b740bac78b263 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -4397,6 +4397,42 @@ def aggregate(self, func=None, axis=0, *args, **kwargs):
agg = aggregate
+ # error: Signature of "any" incompatible with supertype "NDFrame" [override]
+ @overload # type: ignore[override]
+ def any(
+ self,
+ *,
+ axis: Axis = ...,
+ bool_only: bool | None = ...,
+ skipna: bool = ...,
+ level: None = ...,
+ **kwargs,
+ ) -> bool:
+ ...
+
+ @overload
+ def any(
+ self,
+ *,
+ axis: Axis = ...,
+ bool_only: bool | None = ...,
+ skipna: bool = ...,
+ level: Level,
+ **kwargs,
+ ) -> Series | bool:
+ ...
+
+ @doc(NDFrame.any, **_shared_doc_kwargs)
+ def any(
+ self,
+ axis: Axis = 0,
+ bool_only: bool | None = None,
+ skipna: bool = True,
+ level: Level | None = None,
+ **kwargs,
+ ) -> Series | bool:
+ ...
+
@doc(
_shared_docs["transform"],
klass=_shared_doc_kwargs["klass"],
| - [x] closes #44802
- [ ] [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 an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Continuing remaining work after Pull request #44896.
`DataFrame.any` the return type should be DataFrame or Series, and for `Series.any` the return type should be Series or bool.
| https://api.github.com/repos/pandas-dev/pandas/pulls/46638 | 2022-04-04T19:46:16Z | 2022-05-07T12:40:15Z | 2022-05-07T12:40:15Z | 2022-05-07T17:43:38Z |
update index.html | diff --git a/web/pandas/index.html b/web/pandas/index.html
index 930f6caa59cb9..2018ed9651085 100644
--- a/web/pandas/index.html
+++ b/web/pandas/index.html
@@ -20,7 +20,7 @@ <h5>Getting started</h5>
<ul>
<!-- <li><a href="{{ base_url }}/try.html">Try pandas online</a></li> -->
<li><a href="{{ base_url }}/getting_started.html">Install pandas</a></li>
- <li><a href="{{ base_url }}/docs/getting_started/index.html">Getting started</a></li>
+ <li><a href="{{ base_url }}/docs/getting_started/index.html">Getting started with pandas</a></li>
</ul>
</div>
<div class="col-md-4">
| - [ ] 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 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/46637 | 2022-04-04T19:39:54Z | 2022-04-04T20:14:54Z | null | 2022-04-04T20:14:54Z |
REGR: Replace changes the dtype of other columns | diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst
index 0c326e15d90ed..7d9b5b83185ea 100644
--- a/doc/source/whatsnew/v1.4.3.rst
+++ b/doc/source/whatsnew/v1.4.3.rst
@@ -14,6 +14,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Fixed regression in :meth:`DataFrame.replace` when the replacement value was explicitly ``None`` when passed in a dictionary to ``to_replace`` also casting other columns to object dtype even when there were no values to replace (:issue:`46634`)
- Fixed regression in :meth:`DataFrame.nsmallest` led to wrong results when ``np.nan`` in the sorting column (:issue:`46589`)
- Fixed regression in :func:`read_fwf` raising ``ValueError`` when ``widths`` was specified with ``usecols`` (:issue:`46580`)
-
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index c8430a9266ea5..71e2a1e36cbbf 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -781,12 +781,14 @@ def _replace_coerce(
)
else:
if value is None:
- # gh-45601, gh-45836
- nb = self.astype(np.dtype(object), copy=False)
- if nb is self and not inplace:
- nb = nb.copy()
- putmask_inplace(nb.values, mask, value)
- return [nb]
+ # gh-45601, gh-45836, gh-46634
+ if mask.any():
+ nb = self.astype(np.dtype(object), copy=False)
+ if nb is self and not inplace:
+ nb = nb.copy()
+ putmask_inplace(nb.values, mask, value)
+ return [nb]
+ return [self] if inplace else [self.copy()]
return self.replace(
to_replace=to_replace, value=value, inplace=inplace, mask=mask
)
diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py
index 870a64cfa59c9..f7504e9173bf5 100644
--- a/pandas/tests/frame/methods/test_replace.py
+++ b/pandas/tests/frame/methods/test_replace.py
@@ -675,6 +675,25 @@ def test_replace_NAT_with_None(self):
expected = DataFrame([None, None])
tm.assert_frame_equal(result, expected)
+ def test_replace_with_None_keeps_categorical(self):
+ # gh-46634
+ cat_series = Series(["b", "b", "b", "d"], dtype="category")
+ df = DataFrame(
+ {
+ "id": Series([5, 4, 3, 2], dtype="float64"),
+ "col": cat_series,
+ }
+ )
+ result = df.replace({3: None})
+
+ expected = DataFrame(
+ {
+ "id": Series([5.0, 4.0, None, 2.0], dtype="object"),
+ "col": cat_series,
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+
def test_replace_value_is_none(self, datetime_frame):
orig_value = datetime_frame.iloc[0, 0]
orig2 = datetime_frame.iloc[1, 0]
| - [ ] closes #46634 (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 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/46636 | 2022-04-04T19:21:07Z | 2022-05-25T22:40:01Z | 2022-05-25T22:40:00Z | 2022-05-26T09:35:02Z |
CI: Remove grep from asv call (using strict parameter instead) | diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index aac6f4387a74a..a5fd72e343c16 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -141,11 +141,7 @@ jobs:
run: |
cd asv_bench
asv machine --yes
- # TODO add `--durations` when we start using asv >= 0.5 (#46598)
- asv run --quick --dry-run --python=same | sed "/failed$/ s/^/##[error]/" | tee benchmarks.log
- if grep "failed" benchmarks.log > /dev/null ; then
- exit 1
- fi
+ asv run --quick --dry-run --strict --durations=30 --python=same
build_docker_dev_environment:
name: Build Docker Dev Environment
| Looks like asv didn't fail the CI, because if requires a `--strict` parameter to do so. Adding it here. And will change this behavior in asv: https://github.com/airspeed-velocity/asv/issues/1199
Adding a failing benchmark to make sure this works as expected. Will remove if CI is red because of it. | https://api.github.com/repos/pandas-dev/pandas/pulls/46633 | 2022-04-04T13:34:05Z | 2022-04-05T10:22:32Z | 2022-04-05T10:22:32Z | 2022-04-10T11:18:37Z |
BUG: Join ValueError for DataFrame list | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 73dc832e2007b..ebbdb99bf81d2 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -601,6 +601,7 @@ Reshaping
- Bug in :meth:`DataFrame.align` when aligning a :class:`MultiIndex` to a :class:`Series` with another :class:`MultiIndex` (:issue:`46001`)
- Bug in concanenation with ``IntegerDtype``, or ``FloatingDtype`` arrays where the resulting dtype did not mirror the behavior of the non-nullable dtypes (:issue:`46379`)
- Bug in :func:`concat` with identical key leads to error when indexing :class:`MultiIndex` (:issue:`46519`)
+- Bug in :meth:`DataFrame.join` with a list when using suffixes to join DataFrames with duplicate column names (:issue:`46396`)
-
Sparse
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 683674d8ef826..1f083cbd3a71d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -9576,6 +9576,11 @@ def _join_compat(
"Joining multiple DataFrames only supported for joining on index"
)
+ if rsuffix or lsuffix:
+ raise ValueError(
+ "Suffixes not supported when joining multiple DataFrames"
+ )
+
frames = [self] + list(other)
can_concat = all(df.index.is_unique for df in frames)
diff --git a/pandas/tests/frame/methods/test_join.py b/pandas/tests/frame/methods/test_join.py
index c6bfd94b84908..36f3d04a7b6ac 100644
--- a/pandas/tests/frame/methods/test_join.py
+++ b/pandas/tests/frame/methods/test_join.py
@@ -82,6 +82,28 @@ def test_join(left, right, how, sort, expected):
tm.assert_frame_equal(result, expected)
+def test_suffix_on_list_join():
+ first = DataFrame({"key": [1, 2, 3, 4, 5]})
+ second = DataFrame({"key": [1, 8, 3, 2, 5], "v1": [1, 2, 3, 4, 5]})
+ third = DataFrame({"keys": [5, 2, 3, 4, 1], "v2": [1, 2, 3, 4, 5]})
+
+ # check proper errors are raised
+ msg = "Suffixes not supported when joining multiple DataFrames"
+ with pytest.raises(ValueError, match=msg):
+ first.join([second], lsuffix="y")
+ with pytest.raises(ValueError, match=msg):
+ first.join([second, third], rsuffix="x")
+ with pytest.raises(ValueError, match=msg):
+ first.join([second, third], lsuffix="y", rsuffix="x")
+ with pytest.raises(ValueError, match="Indexes have overlapping values"):
+ first.join([second, third])
+
+ # no errors should be raised
+ arr_joined = first.join([third])
+ norm_joined = first.join(third)
+ tm.assert_frame_equal(arr_joined, norm_joined)
+
+
def test_join_index(float_frame):
# left / right
| In the comments for `DataFrame.join()`, it says that suffixes are not supported for joining a list of DataFrame objects.
> Notes
> -----
> Parameters `on`, `lsuffix`, and `rsuffix` are not supported when
> passing a list of `DataFrame` objects.
- [x] closes #46396
- [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 an entry in the latest `doc/source/whatsnew/v1.5.0.rst` file if fixing a bug or adding a new feature.
| https://api.github.com/repos/pandas-dev/pandas/pulls/46630 | 2022-04-03T21:17:45Z | 2022-04-07T16:43:49Z | 2022-04-07T16:43:48Z | 2022-04-08T21:25:18Z |
BUG: added finalize to explode, GH28283 | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 56b1a6317472b..45782c1f8f89d 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -616,6 +616,11 @@ Styler
- Bug when attempting to apply styling functions to an empty DataFrame subset (:issue:`45313`)
-
+Metadata
+^^^^^^^^
+- Fixed metadata propagation in :meth:`DataFrame.explode` (:issue:`28283`)
+-
+
Other
^^^^^
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 6d4deb79b4898..683674d8ef826 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8629,7 +8629,7 @@ def explode(
result.index = self.index.take(result.index)
result = result.reindex(columns=self.columns, copy=False)
- return result
+ return result.__finalize__(self, method="explode")
def unstack(self, level: Level = -1, fill_value=None):
"""
diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py
index 9efc2bf53439a..9e5e616148a32 100644
--- a/pandas/tests/generic/test_finalize.py
+++ b/pandas/tests/generic/test_finalize.py
@@ -154,10 +154,7 @@
operator.methodcaller("pivot_table", columns="A", aggfunc=["mean", "sum"]),
),
(pd.DataFrame, frame_data, operator.methodcaller("stack")),
- pytest.param(
- (pd.DataFrame, frame_data, operator.methodcaller("explode", "A")),
- marks=not_implemented_mark,
- ),
+ (pd.DataFrame, frame_data, operator.methodcaller("explode", "A")),
(pd.DataFrame, frame_mi_data, operator.methodcaller("unstack")),
pytest.param(
(
| **Progress towards #28283**
This PR gives the `explode` method the ability to propagate metadata using `__finalize__`.
- [ ] xref #28283
- [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 an entry in the latest `doc/source/whatsnew/v1.5.0.rst` file
Contributors:
- [Solomon Song](https://github.com/songsol1)
- [Edward Huang](https://github.com/edwhuang23)
| https://api.github.com/repos/pandas-dev/pandas/pulls/46629 | 2022-04-03T21:04:52Z | 2022-04-06T01:29:11Z | 2022-04-06T01:29:11Z | 2022-04-06T01:29:15Z |
Fix NaN bug in ujson | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index ac9f8b02c7acb..141dd5d434a19 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -819,7 +819,7 @@ I/O
- Bug in :func:`read_excel` when reading a ``.ods`` file with newlines between xml elements (:issue:`45598`)
- Bug in :func:`read_parquet` when ``engine="fastparquet"`` where the file was not closed on error (:issue:`46555`)
- :meth:`to_html` now excludes the ``border`` attribute from ``<table>`` elements when ``border`` keyword is set to ``False``.
--
+- Bug in :func:`read_json` reading ``NaN`` values in corner cases (:issue:`46627`)
Period
^^^^^^
diff --git a/pandas/_libs/src/ujson/lib/ultrajson.h b/pandas/_libs/src/ujson/lib/ultrajson.h
index 71df0c5a186b7..2bad0adbb9ef5 100644
--- a/pandas/_libs/src/ujson/lib/ultrajson.h
+++ b/pandas/_libs/src/ujson/lib/ultrajson.h
@@ -149,6 +149,7 @@ enum JSTYPES {
JT_ARRAY, // Array structure
JT_OBJECT, // Key/Value structure
JT_INVALID, // Internal, do not return nor expect
+ JT_NAN, // Not A Number
JT_POS_INF, // Positive infinity
JT_NEG_INF, // Negative infinity
};
@@ -289,6 +290,7 @@ typedef struct __JSONObjectDecoder {
JSOBJ (*newTrue)(void *prv);
JSOBJ (*newFalse)(void *prv);
JSOBJ (*newNull)(void *prv);
+ JSOBJ (*newNaN)(void *prv);
JSOBJ (*newPosInf)(void *prv);
JSOBJ (*newNegInf)(void *prv);
JSOBJ (*newObject)(void *prv, void *decoder);
diff --git a/pandas/_libs/src/ujson/lib/ultrajsondec.c b/pandas/_libs/src/ujson/lib/ultrajsondec.c
index c7779b8b428ae..bb9c22263d1bd 100644
--- a/pandas/_libs/src/ujson/lib/ultrajsondec.c
+++ b/pandas/_libs/src/ujson/lib/ultrajsondec.c
@@ -293,9 +293,9 @@ JSOBJ FASTCALL_MSVC decode_numeric(struct DecoderState *ds) {
if (*(offset++) != 'a') goto SET_NAN_ERROR;
if (*(offset++) != 'N') goto SET_NAN_ERROR;
- ds->lastType = JT_NULL;
+ ds->lastType = JT_NAN;
ds->start = offset;
- return ds->dec->newNull(ds->prv);
+ return ds->dec->newNaN(ds->prv);
SET_NAN_ERROR:
return SetError(ds, -1, "Unexpected character found when decoding 'NaN'");
diff --git a/pandas/_libs/src/ujson/python/JSONtoObj.c b/pandas/_libs/src/ujson/python/JSONtoObj.c
index c58f25b8f99ea..5aab061f80209 100644
--- a/pandas/_libs/src/ujson/python/JSONtoObj.c
+++ b/pandas/_libs/src/ujson/python/JSONtoObj.c
@@ -459,6 +459,8 @@ JSOBJ Object_newFalse(void *prv) { Py_RETURN_FALSE; }
JSOBJ Object_newNull(void *prv) { Py_RETURN_NONE; }
+JSOBJ Object_newNaN(void *prv) { return PyFloat_FromDouble(Py_NAN); }
+
JSOBJ Object_newPosInf(void *prv) { return PyFloat_FromDouble(Py_HUGE_VAL); }
JSOBJ Object_newNegInf(void *prv) { return PyFloat_FromDouble(-Py_HUGE_VAL); }
@@ -510,6 +512,7 @@ PyObject *JSONToObj(PyObject *self, PyObject *args, PyObject *kwargs) {
JSONObjectDecoder dec = {
Object_newString, Object_objectAddKey, Object_arrayAddItem,
Object_newTrue, Object_newFalse, Object_newNull,
+ Object_newNaN,
Object_newPosInf, Object_newNegInf, Object_newObject,
Object_endObject, Object_newArray, Object_endArray,
Object_newInteger, Object_newLong, Object_newUnsignedLong,
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index 576d99f25e25c..4012b494b8847 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -1326,6 +1326,16 @@ def test_read_json_large_numbers2(self):
expected = DataFrame(1.404366e21, index=["articleId"], columns=[0])
tm.assert_frame_equal(result, expected)
+ def test_read_json_nans(self, nulls_fixture, request):
+ # GH 46627
+ json = StringIO('[NaN, {}, null, 1]')
+ result = read_json(json)
+ assert result.iloc[0, 0] is not None # used to return None here
+ assert np.isnan(result.iloc[0, 0])
+ assert result.iloc[1, 0] == {}
+ assert result.iloc[2, 0] is None
+ assert result.iloc[3, 0] == 1
+
def test_to_jsonl(self):
# GH9180
df = DataFrame([[1, 2], [1, 2]], columns=["a", "b"])
diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py
index e82a888f47388..e5537b527ac2d 100644
--- a/pandas/tests/io/json/test_ujson.py
+++ b/pandas/tests/io/json/test_ujson.py
@@ -417,6 +417,9 @@ def test_encode_time_conversion_dateutil(self):
def test_encode_as_null(self, decoded_input):
assert ujson.encode(decoded_input) == "null", "Expected null"
+ def test_decode_nan(self, decoded_input):
+ assert math.isnan(ujson.dumps("[NaN]")[0])
+
def test_datetime_units(self):
val = datetime.datetime(2013, 8, 17, 21, 17, 12, 215504)
stamp = Timestamp(val)
| - [X] closes #46627 (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).
- [X] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
This ports the fixes I made in ujson https://github.com/ultrajson/ultrajson/pull/514 wrt reading NaN values to pandas. | https://api.github.com/repos/pandas-dev/pandas/pulls/46628 | 2022-04-03T20:40:39Z | 2022-07-05T18:17:25Z | null | 2022-07-05T18:17:25Z |
Backport PR #46602 on branch 1.4.x (CI/TST: Make test_vector_resize more deterministic) | diff --git a/pandas/tests/libs/test_hashtable.py b/pandas/tests/libs/test_hashtable.py
index 937eccf7a0afe..0a3a10315b5fd 100644
--- a/pandas/tests/libs/test_hashtable.py
+++ b/pandas/tests/libs/test_hashtable.py
@@ -1,4 +1,5 @@
from contextlib import contextmanager
+import struct
import tracemalloc
import numpy as np
@@ -77,16 +78,16 @@ def test_get_set_contains_len(self, table_type, dtype):
with pytest.raises(KeyError, match=str(index + 2)):
table.get_item(index + 2)
- def test_map(self, table_type, dtype, writable):
- # PyObjectHashTable has no map-method
- if table_type != ht.PyObjectHashTable:
+ def test_map_keys_to_values(self, table_type, dtype, writable):
+ # only Int64HashTable has this method
+ if table_type == ht.Int64HashTable:
N = 77
table = table_type()
keys = np.arange(N).astype(dtype)
vals = np.arange(N).astype(np.int64) + N
keys.flags.writeable = writable
vals.flags.writeable = writable
- table.map(keys, vals)
+ table.map_keys_to_values(keys, vals)
for i in range(N):
assert table.get_item(keys[i]) == i + N
@@ -165,19 +166,139 @@ def test_get_state(self, table_type, dtype):
assert "n_buckets" in state
assert "upper_bound" in state
- def test_no_reallocation(self, table_type, dtype):
- for N in range(1, 110):
- keys = np.arange(N).astype(dtype)
- preallocated_table = table_type(N)
- n_buckets_start = preallocated_table.get_state()["n_buckets"]
- preallocated_table.map_locations(keys)
- n_buckets_end = preallocated_table.get_state()["n_buckets"]
- # original number of buckets was enough:
- assert n_buckets_start == n_buckets_end
- # check with clean table (not too much preallocated)
- clean_table = table_type()
- clean_table.map_locations(keys)
- assert n_buckets_start == clean_table.get_state()["n_buckets"]
+ @pytest.mark.parametrize("N", range(1, 110))
+ def test_no_reallocation(self, table_type, dtype, N):
+ keys = np.arange(N).astype(dtype)
+ preallocated_table = table_type(N)
+ n_buckets_start = preallocated_table.get_state()["n_buckets"]
+ preallocated_table.map_locations(keys)
+ n_buckets_end = preallocated_table.get_state()["n_buckets"]
+ # original number of buckets was enough:
+ assert n_buckets_start == n_buckets_end
+ # check with clean table (not too much preallocated)
+ clean_table = table_type()
+ clean_table.map_locations(keys)
+ assert n_buckets_start == clean_table.get_state()["n_buckets"]
+
+
+class TestHashTableUnsorted:
+ # TODO: moved from test_algos; may be redundancies with other tests
+ def test_string_hashtable_set_item_signature(self):
+ # GH#30419 fix typing in StringHashTable.set_item to prevent segfault
+ tbl = ht.StringHashTable()
+
+ tbl.set_item("key", 1)
+ assert tbl.get_item("key") == 1
+
+ with pytest.raises(TypeError, match="'key' has incorrect type"):
+ # key arg typed as string, not object
+ tbl.set_item(4, 6)
+ with pytest.raises(TypeError, match="'val' has incorrect type"):
+ tbl.get_item(4)
+
+ def test_lookup_nan(self, writable):
+ # GH#21688 ensure we can deal with readonly memory views
+ xs = np.array([2.718, 3.14, np.nan, -7, 5, 2, 3])
+ xs.setflags(write=writable)
+ m = ht.Float64HashTable()
+ m.map_locations(xs)
+ tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), dtype=np.intp))
+
+ def test_add_signed_zeros(self):
+ # GH#21866 inconsistent hash-function for float64
+ # default hash-function would lead to different hash-buckets
+ # for 0.0 and -0.0 if there are more than 2^30 hash-buckets
+ # but this would mean 16GB
+ N = 4 # 12 * 10**8 would trigger the error, if you have enough memory
+ m = ht.Float64HashTable(N)
+ m.set_item(0.0, 0)
+ m.set_item(-0.0, 0)
+ assert len(m) == 1 # 0.0 and -0.0 are equivalent
+
+ def test_add_different_nans(self):
+ # GH#21866 inconsistent hash-function for float64
+ # create different nans from bit-patterns:
+ NAN1 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000000))[0]
+ NAN2 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000001))[0]
+ assert NAN1 != NAN1
+ assert NAN2 != NAN2
+ # default hash function would lead to different hash-buckets
+ # for NAN1 and NAN2 even if there are only 4 buckets:
+ m = ht.Float64HashTable()
+ m.set_item(NAN1, 0)
+ m.set_item(NAN2, 0)
+ assert len(m) == 1 # NAN1 and NAN2 are equivalent
+
+ def test_lookup_overflow(self, writable):
+ xs = np.array([1, 2, 2**63], dtype=np.uint64)
+ # GH 21688 ensure we can deal with readonly memory views
+ xs.setflags(write=writable)
+ m = ht.UInt64HashTable()
+ m.map_locations(xs)
+ tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), dtype=np.intp))
+
+ @pytest.mark.parametrize("nvals", [0, 10]) # resizing to 0 is special case
+ @pytest.mark.parametrize(
+ "htable, uniques, dtype, safely_resizes",
+ [
+ (ht.PyObjectHashTable, ht.ObjectVector, "object", False),
+ (ht.StringHashTable, ht.ObjectVector, "object", True),
+ (ht.Float64HashTable, ht.Float64Vector, "float64", False),
+ (ht.Int64HashTable, ht.Int64Vector, "int64", False),
+ (ht.Int32HashTable, ht.Int32Vector, "int32", False),
+ (ht.UInt64HashTable, ht.UInt64Vector, "uint64", False),
+ ],
+ )
+ def test_vector_resize(
+ self, writable, htable, uniques, dtype, safely_resizes, nvals
+ ):
+ # Test for memory errors after internal vector
+ # reallocations (GH 7157)
+ # Changed from using np.random.rand to range
+ # which could cause flaky CI failures when safely_resizes=False
+ vals = np.array(range(1000), dtype=dtype)
+
+ # GH 21688 ensures we can deal with read-only memory views
+ vals.setflags(write=writable)
+
+ # initialise instances; cannot initialise in parametrization,
+ # as otherwise external views would be held on the array (which is
+ # one of the things this test is checking)
+ htable = htable()
+ uniques = uniques()
+
+ # get_labels may append to uniques
+ htable.get_labels(vals[:nvals], uniques, 0, -1)
+ # to_array() sets an external_view_exists flag on uniques.
+ tmp = uniques.to_array()
+ oldshape = tmp.shape
+
+ # subsequent get_labels() calls can no longer append to it
+ # (except for StringHashTables + ObjectVector)
+ if safely_resizes:
+ htable.get_labels(vals, uniques, 0, -1)
+ else:
+ with pytest.raises(ValueError, match="external reference.*"):
+ htable.get_labels(vals, uniques, 0, -1)
+
+ uniques.to_array() # should not raise here
+ assert tmp.shape == oldshape
+
+ @pytest.mark.parametrize(
+ "hashtable",
+ [
+ ht.PyObjectHashTable,
+ ht.StringHashTable,
+ ht.Float64HashTable,
+ ht.Int64HashTable,
+ ht.Int32HashTable,
+ ht.UInt64HashTable,
+ ],
+ )
+ def test_hashtable_large_sizehint(self, hashtable):
+ # GH#22729 smoketest for not raising when passing a large size_hint
+ size_hint = np.iinfo(np.uint32).max + 1
+ hashtable(size_hint=size_hint)
class TestPyObjectHashTableWithNans:
@@ -282,19 +403,19 @@ def test_tracemalloc_for_empty_StringHashTable():
assert get_allocated_khash_memory() == 0
-def test_no_reallocation_StringHashTable():
- for N in range(1, 110):
- keys = np.arange(N).astype(np.compat.unicode).astype(np.object_)
- preallocated_table = ht.StringHashTable(N)
- n_buckets_start = preallocated_table.get_state()["n_buckets"]
- preallocated_table.map_locations(keys)
- n_buckets_end = preallocated_table.get_state()["n_buckets"]
- # original number of buckets was enough:
- assert n_buckets_start == n_buckets_end
- # check with clean table (not too much preallocated)
- clean_table = ht.StringHashTable()
- clean_table.map_locations(keys)
- assert n_buckets_start == clean_table.get_state()["n_buckets"]
+@pytest.mark.parametrize("N", range(1, 110))
+def test_no_reallocation_StringHashTable(N):
+ keys = np.arange(N).astype(np.compat.unicode).astype(np.object_)
+ preallocated_table = ht.StringHashTable(N)
+ n_buckets_start = preallocated_table.get_state()["n_buckets"]
+ preallocated_table.map_locations(keys)
+ n_buckets_end = preallocated_table.get_state()["n_buckets"]
+ # original number of buckets was enough:
+ assert n_buckets_start == n_buckets_end
+ # check with clean table (not too much preallocated)
+ clean_table = ht.StringHashTable()
+ clean_table.map_locations(keys)
+ assert n_buckets_start == clean_table.get_state()["n_buckets"]
@pytest.mark.parametrize(
@@ -322,15 +443,6 @@ def test_get_set_contains_len(self, table_type, dtype):
assert index in table
assert table.get_item(index) == 41
- def test_map(self, table_type, dtype):
- N = 332
- table = table_type()
- keys = np.full(N, np.nan, dtype=dtype)
- vals = (np.arange(N) + N).astype(np.int64)
- table.map(keys, vals)
- assert len(table) == 1
- assert table.get_item(np.nan) == 2 * N - 1
-
def test_map_locations(self, table_type, dtype):
N = 10
table = table_type()
@@ -468,6 +580,21 @@ def test_unique_label_indices_intp(writable):
tm.assert_numpy_array_equal(result, expected)
+def test_unique_label_indices():
+
+ a = np.random.randint(1, 1 << 10, 1 << 15).astype(np.intp)
+
+ left = ht.unique_label_indices(a)
+ right = np.unique(a, return_index=True)[1]
+
+ tm.assert_numpy_array_equal(left, right, check_dtype=False)
+
+ a[np.random.choice(len(a), 10)] = -1
+ left = ht.unique_label_indices(a)
+ right = np.unique(a, return_index=True)[1][1:]
+ tm.assert_numpy_array_equal(left, right, check_dtype=False)
+
+
@pytest.mark.parametrize(
"dtype",
[
| Backport PR #46602
(cherry picked from commit bea02f300bdf54d86aded7d5c4461dc340ddb929)
- [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).
Additionally migrates all the refactoring work done in `test_hashtables.py`
| https://api.github.com/repos/pandas-dev/pandas/pulls/46625 | 2022-04-03T16:08:31Z | 2022-04-07T14:28:47Z | null | 2022-04-07T14:28:53Z |
Remove references to previously-vendored Sphinx extensions | diff --git a/LICENSES/OTHER b/LICENSES/OTHER
index f0550b4ee208a..7446d68eb43a6 100644
--- a/LICENSES/OTHER
+++ b/LICENSES/OTHER
@@ -1,8 +1,3 @@
-numpydoc license
-----------------
-
-The numpydoc license is in pandas/doc/sphinxext/LICENSE.txt
-
Bottleneck license
------------------
@@ -77,4 +72,4 @@ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/doc/sphinxext/README.rst b/doc/sphinxext/README.rst
index 8f0f4a8b2636d..ef52433e5e869 100644
--- a/doc/sphinxext/README.rst
+++ b/doc/sphinxext/README.rst
@@ -1,17 +1,5 @@
sphinxext
=========
-This directory contains copies of different sphinx extensions in use in the
-pandas documentation. These copies originate from other projects:
-
-- ``numpydoc`` - Numpy's Sphinx extensions: this can be found at its own
- repository: https://github.com/numpy/numpydoc
-- ``ipython_directive`` and ``ipython_console_highlighting`` in the folder
- ``ipython_sphinxext`` - Sphinx extensions from IPython: these are included
- in IPython: https://github.com/ipython/ipython/tree/master/IPython/sphinxext
-
-.. note::
-
- These copies are maintained at the respective projects, so fixes should,
- to the extent possible, be pushed upstream instead of only adapting our
- local copy to avoid divergence between the local and upstream version.
+This directory contains custom sphinx extensions in use in the pandas
+documentation.
| - [ ] closes #xxxx (Replace xxxx with the Github issue number) **No issue filed**
- [ ] [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 **Not applicable**
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. **Not applicable**
| https://api.github.com/repos/pandas-dev/pandas/pulls/46624 | 2022-04-03T12:16:28Z | 2022-04-06T01:24:39Z | 2022-04-06T01:24:39Z | 2022-04-06T01:24:43Z |
BUG: SeriesGroupBy apply wrong name | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 98d56bac402ac..97ff3a9af6e26 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -602,6 +602,7 @@ Groupby/resample/rolling
- Bug in :meth:`GroupBy.cummax` with ``int64`` dtype with leading value being the smallest possible int64 (:issue:`46382`)
- Bug in :meth:`GroupBy.max` with empty groups and ``uint64`` dtype incorrectly raising ``RuntimeError`` (:issue:`46408`)
- Bug in :meth:`.GroupBy.apply` would fail when ``func`` was a string and args or kwargs were supplied (:issue:`46479`)
+- Bug in :meth:`SeriesGroupBy.apply` would incorrectly name its result when there was a unique group (:issue:`46369`)
- Bug in :meth:`.Rolling.var` would segfault calculating weighted variance when window size was larger than data size (:issue:`46760`)
Reshaping
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 6c3d2c91ab012..90f665362ef56 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -612,7 +612,7 @@ def get_cython_func(arg: Callable) -> str | None:
def is_builtin_func(arg):
"""
- if we define an builtin function for this argument, return it,
+ if we define a builtin function for this argument, return it,
otherwise return the arg
"""
return _builtin_table.get(arg, arg)
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 8d9b94f242e33..06a1aed8e3b09 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -397,11 +397,13 @@ def _wrap_applied_output(
res_ser.name = self.obj.name
return res_ser
elif isinstance(values[0], (Series, DataFrame)):
- return self._concat_objects(
+ result = self._concat_objects(
values,
not_indexed_same=not_indexed_same,
override_group_keys=override_group_keys,
)
+ result.name = self.obj.name
+ return result
else:
# GH #6265 #24880
result = self.obj._constructor(
diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py
index 9cb64766a1079..4cfc3ea41543b 100644
--- a/pandas/tests/groupby/test_apply.py
+++ b/pandas/tests/groupby/test_apply.py
@@ -1320,3 +1320,13 @@ def test_apply_str_with_args(df, args, kwargs):
result = gb.apply("sum", *args, **kwargs)
expected = gb.sum(numeric_only=True)
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("name", ["some_name", None])
+def test_result_name_when_one_group(name):
+ # GH 46369
+ ser = Series([1, 2], name=name)
+ result = ser.groupby(["a", "a"], group_keys=False).apply(lambda x: x)
+ expected = Series([1, 2], name=name)
+
+ tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/groupby/test_value_counts.py b/pandas/tests/groupby/test_value_counts.py
index d38ba84cd1397..577a72d3f5090 100644
--- a/pandas/tests/groupby/test_value_counts.py
+++ b/pandas/tests/groupby/test_value_counts.py
@@ -183,12 +183,11 @@ def test_series_groupby_value_counts_on_categorical():
),
]
),
- name=0,
)
# Expected:
# 0 a 1
# b 0
- # Name: 0, dtype: int64
+ # dtype: int64
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index a77c95e30ab43..237d6a96f39ec 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -1511,10 +1511,5 @@ def test_null_group_str_transformer_series(request, dropna, transformation_func)
msg = f"{transformation_func} is deprecated"
with tm.assert_produces_warning(warn, match=msg):
result = gb.transform(transformation_func, *args)
- if dropna and transformation_func == "fillna":
- # GH#46369 - result name is the group; remove this block when fixed.
- tm.assert_equal(result, expected, check_names=False)
- # This should be None
- assert result.name == 1.0
- else:
- tm.assert_equal(result, expected)
+
+ tm.assert_equal(result, expected)
| - [x] closes #46369
- [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).
- [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/46623 | 2022-04-03T11:45:44Z | 2022-04-19T02:49:13Z | 2022-04-19T02:49:13Z | 2022-04-19T02:49:26Z |
wip | diff --git a/.github/workflows/assign.yml b/.github/workflows/assign.yml
deleted file mode 100644
index a1812843b1a8f..0000000000000
--- a/.github/workflows/assign.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-name: Assign
-on:
- issue_comment:
- types: created
-
-jobs:
- issue_assign:
- runs-on: ubuntu-latest
- steps:
- - if: github.event.comment.body == 'take'
- run: |
- echo "Assigning issue ${{ github.event.issue.number }} to ${{ github.event.comment.user.login }}"
- curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -d '{"assignees": ["${{ github.event.comment.user.login }}"]}' https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.issue.number }}/assignees
diff --git a/.github/workflows/asv-bot.yml b/.github/workflows/asv-bot.yml
deleted file mode 100644
index 78c224b84d5d9..0000000000000
--- a/.github/workflows/asv-bot.yml
+++ /dev/null
@@ -1,81 +0,0 @@
-name: "ASV Bot"
-
-on:
- issue_comment: # Pull requests are issues
- types:
- - created
-
-env:
- ENV_FILE: environment.yml
- COMMENT: ${{github.event.comment.body}}
-
-jobs:
- autotune:
- name: "Run benchmarks"
- # TODO: Support more benchmarking options later, against different branches, against self, etc
- if: startsWith(github.event.comment.body, '@github-actions benchmark')
- runs-on: ubuntu-latest
- defaults:
- run:
- shell: bash -el {0}
-
- concurrency:
- # Set concurrency to prevent abuse(full runs are ~5.5 hours !!!)
- # each user can only run one concurrent benchmark bot at a time
- # We don't cancel in progress jobs, but if you want to benchmark multiple PRs, you're gonna have
- # to wait
- group: ${{ github.actor }}-asv
- cancel-in-progress: false
-
- steps:
- - name: Checkout
- uses: actions/checkout@v3
- with:
- fetch-depth: 0
-
- - name: Cache conda
- uses: actions/cache@v3
- with:
- path: ~/conda_pkgs_dir
- key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
-
- # Although asv sets up its own env, deps are still needed
- # during discovery process
- - uses: conda-incubator/setup-miniconda@v2.1.1
- with:
- activate-environment: pandas-dev
- channel-priority: strict
- environment-file: ${{ env.ENV_FILE }}
- use-only-tar-bz2: true
-
- - name: Run benchmarks
- id: bench
- continue-on-error: true # This is a fake failure, asv will exit code 1 for regressions
- run: |
- # extracting the regex, see https://stackoverflow.com/a/36798723
- REGEX=$(echo "$COMMENT" | sed -n "s/^.*-b\s*\(\S*\).*$/\1/p")
- cd asv_bench
- asv check -E existing
- git remote add upstream https://github.com/pandas-dev/pandas.git
- git fetch upstream
- asv machine --yes
- asv continuous -f 1.1 -b $REGEX upstream/main HEAD
- echo 'BENCH_OUTPUT<<EOF' >> $GITHUB_ENV
- asv compare -f 1.1 upstream/main HEAD >> $GITHUB_ENV
- echo 'EOF' >> $GITHUB_ENV
- echo "REGEX=$REGEX" >> $GITHUB_ENV
-
- - uses: actions/github-script@v6
- env:
- BENCH_OUTPUT: ${{env.BENCH_OUTPUT}}
- REGEX: ${{env.REGEX}}
- with:
- script: |
- const ENV_VARS = process.env
- const run_url = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`
- github.rest.issues.createComment({
- issue_number: context.issue.number,
- owner: context.repo.owner,
- repo: context.repo.repo,
- body: '\nBenchmarks completed. View runner logs here.' + run_url + '\nRegex used: '+ 'regex ' + ENV_VARS["REGEX"] + '\n' + ENV_VARS["BENCH_OUTPUT"]
- })
diff --git a/.github/workflows/autoupdate-pre-commit-config.yml b/.github/workflows/autoupdate-pre-commit-config.yml
deleted file mode 100644
index d2eac234ca361..0000000000000
--- a/.github/workflows/autoupdate-pre-commit-config.yml
+++ /dev/null
@@ -1,33 +0,0 @@
-name: "Update pre-commit config"
-
-on:
- schedule:
- - cron: "0 7 1 * *" # At 07:00 on 1st of every month.
- workflow_dispatch:
-
-jobs:
- update-pre-commit:
- if: github.repository_owner == 'pandas-dev'
- name: Autoupdate pre-commit config
- runs-on: ubuntu-latest
- steps:
- - name: Set up Python
- uses: actions/setup-python@v3
- - name: Cache multiple paths
- uses: actions/cache@v3
- with:
- path: |
- ~/.cache/pre-commit
- ~/.cache/pip
- key: pre-commit-autoupdate-${{ runner.os }}-build
- - name: Update pre-commit config packages
- uses: technote-space/create-pr-action@v2
- with:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- EXECUTE_COMMANDS: |
- pip install pre-commit
- pre-commit autoupdate || (exit 0);
- pre-commit run -a || (exit 0);
- COMMIT_MESSAGE: "⬆️ UPGRADE: Autoupdate pre-commit config"
- PR_BRANCH_NAME: "pre-commit-config-update-${PR_ID}"
- PR_TITLE: "⬆️ UPGRADE: Autoupdate pre-commit config"
diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
deleted file mode 100644
index 16ac3cbf47705..0000000000000
--- a/.github/workflows/code-checks.yml
+++ /dev/null
@@ -1,182 +0,0 @@
-name: Code Checks
-
-on:
- push:
- branches:
- - main
- - 1.4.x
- pull_request:
- branches:
- - main
- - 1.4.x
-
-env:
- ENV_FILE: environment.yml
- PANDAS_CI: 1
-
-jobs:
- pre_commit:
- name: pre-commit
- runs-on: ubuntu-latest
- concurrency:
- # https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-pre-commit
- cancel-in-progress: true
- steps:
- - name: Checkout
- uses: actions/checkout@v3
-
- - name: Install Python
- uses: actions/setup-python@v3
- with:
- python-version: '3.9.7'
-
- - name: Run pre-commit
- uses: pre-commit/action@v2.0.3
-
- typing_and_docstring_validation:
- name: Docstring and typing validation
- runs-on: ubuntu-latest
- defaults:
- run:
- shell: bash -el {0}
-
- concurrency:
- # https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-code-checks
- cancel-in-progress: true
-
- steps:
- - name: Checkout
- uses: actions/checkout@v3
- with:
- fetch-depth: 0
-
- - name: Cache conda
- uses: actions/cache@v3
- with:
- path: ~/conda_pkgs_dir
- key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
-
- - uses: conda-incubator/setup-miniconda@v2.1.1
- with:
- mamba-version: "*"
- channels: conda-forge
- activate-environment: pandas-dev
- channel-priority: strict
- environment-file: ${{ env.ENV_FILE }}
- use-only-tar-bz2: true
-
- - name: Install node.js (for pyright)
- uses: actions/setup-node@v3
- with:
- node-version: "16"
-
- - name: Install pyright
- # note: keep version in sync with .pre-commit-config.yaml
- run: npm install -g pyright@1.1.230
-
- - name: Build Pandas
- id: build
- uses: ./.github/actions/build_pandas
-
- - name: Run checks on imported code
- run: ci/code_checks.sh code
- if: ${{ steps.build.outcome == 'success' }}
-
- - name: Run doctests
- run: ci/code_checks.sh doctests
- if: ${{ steps.build.outcome == 'success' }}
-
- - name: Run docstring validation
- run: ci/code_checks.sh docstrings
- if: ${{ steps.build.outcome == 'success' }}
-
- - name: Run typing validation
- run: ci/code_checks.sh typing
- if: ${{ steps.build.outcome == 'success' }}
-
- - name: Run docstring validation script tests
- run: pytest scripts
- if: ${{ steps.build.outcome == 'success' }}
-
- asv-benchmarks:
- name: ASV Benchmarks
- runs-on: ubuntu-latest
- defaults:
- run:
- shell: bash -el {0}
-
- concurrency:
- # https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-asv-benchmarks
- cancel-in-progress: true
-
- steps:
- - name: Checkout
- uses: actions/checkout@v3
- with:
- fetch-depth: 0
-
- - name: Cache conda
- uses: actions/cache@v3
- with:
- path: ~/conda_pkgs_dir
- key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
-
- - uses: conda-incubator/setup-miniconda@v2.1.1
- with:
- mamba-version: "*"
- channels: conda-forge
- activate-environment: pandas-dev
- channel-priority: strict
- environment-file: ${{ env.ENV_FILE }}
- use-only-tar-bz2: true
-
- - name: Build Pandas
- id: build
- uses: ./.github/actions/build_pandas
-
- - name: Run ASV benchmarks
- run: |
- cd asv_bench
- asv check -E existing
- git remote add upstream https://github.com/pandas-dev/pandas.git
- git fetch upstream
- asv machine --yes
- asv dev | sed "/failed$/ s/^/##[error]/" | tee benchmarks.log
- if grep "failed" benchmarks.log > /dev/null ; then
- exit 1
- fi
- if: ${{ steps.build.outcome == 'success' }}
-
- - name: Publish benchmarks artifact
- uses: actions/upload-artifact@v3
- with:
- name: Benchmarks log
- path: asv_bench/benchmarks.log
- if: failure()
-
- build_docker_dev_environment:
- name: Build Docker Dev Environment
- runs-on: ubuntu-latest
- defaults:
- run:
- shell: bash -el {0}
-
- concurrency:
- # https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-build_docker_dev_environment
- cancel-in-progress: true
-
- steps:
- - name: Clean up dangling images
- run: docker image prune -f
-
- - name: Checkout
- uses: actions/checkout@v3
- with:
- fetch-depth: 0
-
- - name: Build image
- run: docker build --pull --no-cache --tag pandas-dev-env .
diff --git a/.github/workflows/comment_bot.yml b/.github/workflows/comment_bot.yml
deleted file mode 100644
index 3824e015e8336..0000000000000
--- a/.github/workflows/comment_bot.yml
+++ /dev/null
@@ -1,40 +0,0 @@
-name: Comment-bot
-
-on:
- issue_comment:
- types:
- - created
- - edited
-
-jobs:
- autotune:
- name: "Fixup pre-commit formatting"
- if: startsWith(github.event.comment.body, '@github-actions pre-commit')
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v3
- - uses: r-lib/actions/pr-fetch@v2
- with:
- repo-token: ${{ secrets.GITHUB_TOKEN }}
- - name: Cache multiple paths
- uses: actions/cache@v3
- with:
- path: |
- ~/.cache/pre-commit
- ~/.cache/pip
- key: pre-commit-dispatched-${{ runner.os }}-build
- - uses: actions/setup-python@v3
- with:
- python-version: 3.8
- - name: Install-pre-commit
- run: python -m pip install --upgrade pre-commit
- - name: Run pre-commit
- run: pre-commit run --from-ref=origin/main --to-ref=HEAD --all-files || (exit 0)
- - name: Commit results
- run: |
- git config user.name "$(git log -1 --pretty=format:%an)"
- git config user.email "$(git log -1 --pretty=format:%ae)"
- git commit -a -m 'Fixes from pre-commit [automated commit]' || echo "No changes to commit"
- - uses: r-lib/actions/pr-push@v2
- with:
- repo-token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml
deleted file mode 100644
index bba9f62a0eca6..0000000000000
--- a/.github/workflows/docbuild-and-upload.yml
+++ /dev/null
@@ -1,72 +0,0 @@
-name: Doc Build and Upload
-
-on:
- push:
- branches:
- - main
- - 1.4.x
- pull_request:
- branches:
- - main
- - 1.4.x
-
-env:
- ENV_FILE: environment.yml
- PANDAS_CI: 1
-
-jobs:
- web_and_docs:
- name: Doc Build and Upload
- runs-on: ubuntu-latest
-
- concurrency:
- # https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-web-docs
- cancel-in-progress: true
-
- steps:
- - name: Checkout
- uses: actions/checkout@v3
- with:
- fetch-depth: 0
-
- - name: Set up pandas
- uses: ./.github/actions/setup
-
- - name: Build website
- run: |
- source activate pandas-dev
- python web/pandas_web.py web/pandas --target-path=web/build
- - name: Build documentation
- run: |
- source activate pandas-dev
- doc/make.py --warnings-are-errors
-
- - name: Install ssh key
- run: |
- mkdir -m 700 -p ~/.ssh
- echo "${{ secrets.server_ssh_key }}" > ~/.ssh/id_rsa
- chmod 600 ~/.ssh/id_rsa
- echo "${{ secrets.server_ip }} ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBE1Kkopomm7FHG5enATf7SgnpICZ4W2bw+Ho+afqin+w7sMcrsa0je7sbztFAV8YchDkiBKnWTG4cRT+KZgZCaY=" > ~/.ssh/known_hosts
- if: ${{github.event_name == 'push' && github.ref == 'refs/heads/main'}}
-
- - name: Copy cheatsheets into site directory
- run: cp doc/cheatsheet/Pandas_Cheat_Sheet* web/build/
-
- - name: Upload web
- run: rsync -az --delete --exclude='pandas-docs' --exclude='docs' web/build/ docs@${{ secrets.server_ip }}:/usr/share/nginx/pandas
- if: ${{github.event_name == 'push' && github.ref == 'refs/heads/main'}}
-
- - name: Upload dev docs
- run: rsync -az --delete doc/build/html/ docs@${{ secrets.server_ip }}:/usr/share/nginx/pandas/pandas-docs/dev
- if: ${{github.event_name == 'push' && github.ref == 'refs/heads/main'}}
-
- - name: Move docs into site directory
- run: mv doc/build/html web/build/docs
-
- - name: Save website as an artifact
- uses: actions/upload-artifact@v3
- with:
- name: website
- path: web/build
- retention-days: 14
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
deleted file mode 100644
index ec7da7d68ba9f..0000000000000
--- a/.github/workflows/posix.yml
+++ /dev/null
@@ -1,191 +0,0 @@
-name: Posix
-
-on:
- push:
- branches:
- - main
- - 1.4.x
- pull_request:
- branches:
- - main
- - 1.4.x
- paths-ignore:
- - "doc/**"
-
-env:
- PANDAS_CI: 1
-
-jobs:
- pytest:
- runs-on: ubuntu-latest
- defaults:
- run:
- shell: bash -el {0}
- timeout-minutes: 120
- strategy:
- matrix:
- env_file: [actions-38.yaml, actions-39.yaml, actions-310.yaml]
- pattern: ["not single_cpu", "single_cpu"]
- # Don't test pyarrow v2/3: Causes timeouts in read_csv engine
- # even if tests are skipped/xfailed
- pyarrow_version: ["5", "7"]
- include:
- - name: "Downstream Compat"
- env_file: actions-38-downstream_compat.yaml
- pattern: "not slow and not network and not single_cpu"
- pytest_target: "pandas/tests/test_downstream.py"
- - name: "Minimum Versions"
- env_file: actions-38-minimum_versions.yaml
- pattern: "not slow and not network and not single_cpu"
- - name: "Locale: it_IT.utf8"
- env_file: actions-38.yaml
- pattern: "not slow and not network and not single_cpu"
- extra_apt: "language-pack-it"
- lang: "it_IT.utf8"
- lc_all: "it_IT.utf8"
- - name: "Locale: zh_CN.utf8"
- env_file: actions-38.yaml
- pattern: "not slow and not network and not single_cpu"
- extra_apt: "language-pack-zh-hans"
- lang: "zh_CN.utf8"
- lc_all: "zh_CN.utf8"
- - name: "Data Manager"
- env_file: actions-38.yaml
- pattern: "not slow and not network and not single_cpu"
- pandas_data_manager: "array"
- - name: "Pypy"
- env_file: actions-pypy-38.yaml
- pattern: "not slow and not network and not single_cpu"
- test_args: "--max-worker-restart 0"
- - name: "Numpy Dev"
- env_file: actions-310-numpydev.yaml
- pattern: "not slow and not network and not single_cpu"
- pandas_testing_mode: "deprecate"
- test_args: "-W error"
- fail-fast: false
- name: ${{ matrix.name || format('{0} pyarrow={1} {2}', matrix.env_file, matrix.pyarrow_version, matrix.pattern) }}
- env:
- ENV_FILE: ci/deps/${{ matrix.env_file }}
- PATTERN: ${{ matrix.pattern }}
- EXTRA_APT: ${{ matrix.extra_apt || '' }}
- LANG: ${{ matrix.lang || '' }}
- LC_ALL: ${{ matrix.lc_all || '' }}
- PANDAS_TESTING_MODE: ${{ matrix.pandas_testing_mode || '' }}
- PANDAS_DATA_MANAGER: ${{ matrix.pandas_data_manager || 'block' }}
- TEST_ARGS: ${{ matrix.test_args || '' }}
- PYTEST_WORKERS: ${{ contains(matrix.pattern, 'not single_cpu') && 'auto' || '1' }}
- PYTEST_TARGET: ${{ matrix.pytest_target || 'pandas' }}
- IS_PYPY: ${{ contains(matrix.env_file, 'pypy') }}
- # TODO: re-enable coverage on pypy, its slow
- COVERAGE: ${{ !contains(matrix.env_file, 'pypy') }}
- concurrency:
- # https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.env_file }}-${{ matrix.pattern }}-${{ matrix.pyarrow_version || '' }}-${{ matrix.extra_apt || '' }}-${{ matrix.pandas_data_manager || '' }}
- cancel-in-progress: true
-
- services:
- mysql:
- image: mysql
- env:
- MYSQL_ALLOW_EMPTY_PASSWORD: yes
- MYSQL_DATABASE: pandas
- options: >-
- --health-cmd "mysqladmin ping"
- --health-interval 10s
- --health-timeout 5s
- --health-retries 5
- ports:
- - 3306:3306
-
- postgres:
- image: postgres
- env:
- POSTGRES_USER: postgres
- POSTGRES_PASSWORD: postgres
- POSTGRES_DB: pandas
- options: >-
- --health-cmd pg_isready
- --health-interval 10s
- --health-timeout 5s
- --health-retries 5
- ports:
- - 5432:5432
-
- moto:
- image: motoserver/moto
- env:
- AWS_ACCESS_KEY_ID: foobar_key
- AWS_SECRET_ACCESS_KEY: foobar_secret
- ports:
- - 5000:5000
-
- steps:
- - name: Checkout
- uses: actions/checkout@v3
- with:
- fetch-depth: 0
-
- - name: Cache conda
- uses: actions/cache@v3
- env:
- CACHE_NUMBER: 0
- with:
- path: ~/conda_pkgs_dir
- key: ${{ runner.os }}-conda-${{ env.CACHE_NUMBER }}-${{
- hashFiles('${{ env.ENV_FILE }}') }}
-
- - name: Extra installs
- # xsel for clipboard tests
- run: sudo apt-get update && sudo apt-get install -y libc6-dev-i386 xsel ${{ env.EXTRA_APT }}
-
- - uses: conda-incubator/setup-miniconda@v2.1.1
- with:
- mamba-version: "*"
- channels: conda-forge
- activate-environment: pandas-dev
- channel-priority: flexible
- environment-file: ${{ env.ENV_FILE }}
- use-only-tar-bz2: true
- if: ${{ env.IS_PYPY == 'false' }} # No pypy3.8 support
-
- - name: Upgrade Arrow version
- run: conda install -n pandas-dev -c conda-forge --no-update-deps pyarrow=${{ matrix.pyarrow_version }}
- if: ${{ matrix.pyarrow_version }}
-
- - name: Setup PyPy
- uses: actions/setup-python@v3
- with:
- python-version: "pypy-3.8"
- if: ${{ env.IS_PYPY == 'true' }}
-
- - name: Setup PyPy dependencies
- run: |
- # TODO: re-enable cov, its slowing the tests down though
- pip install Cython numpy python-dateutil pytz pytest>=6.0 pytest-xdist>=1.31.0 pytest-asyncio>=0.17 hypothesis>=5.5.3
- if: ${{ env.IS_PYPY == 'true' }}
-
- - name: Build Pandas
- uses: ./.github/actions/build_pandas
-
- - name: Test
- run: ci/run_tests.sh
- # TODO: Don't continue on error for PyPy
- continue-on-error: ${{ env.IS_PYPY == 'true' }}
- if: always()
-
- - name: Build Version
- run: pushd /tmp && python -c "import pandas; pandas.show_versions();" && popd
-
- - name: Publish test results
- uses: actions/upload-artifact@v3
- with:
- name: Test results
- path: test-data.xml
- if: failure()
-
- - name: Upload coverage to Codecov
- uses: codecov/codecov-action@v2
- with:
- flags: unittests
- name: codecov-pandas
- fail_ci_if_error: false
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
deleted file mode 100644
index 8ca4cce155e96..0000000000000
--- a/.github/workflows/python-dev.yml
+++ /dev/null
@@ -1,97 +0,0 @@
-# This file is purposely frozen(does not run). DO NOT DELETE IT
-# Unfreeze(by commentingthe if: false() condition) once the
-# next Python Dev version has released beta 1 and both Cython and numpy support it
-# After that Python has released, migrate the workflows to the
-# posix GHA workflows/Azure pipelines and "freeze" this file by
-# uncommenting the if: false() condition
-# Feel free to modify this comment as necessary.
-
-name: Python Dev
-
-on:
- push:
- branches:
- - main
- - 1.4.x
- pull_request:
- branches:
- - main
- - 1.4.x
- paths-ignore:
- - "doc/**"
-
-env:
- PYTEST_WORKERS: "auto"
- PANDAS_CI: 1
- PATTERN: "not slow and not network and not clipboard and not single_cpu"
- COVERAGE: true
- PYTEST_TARGET: pandas
-
-jobs:
- build:
- if: false # Comment this line out to "unfreeze"
- runs-on: ${{ matrix.os }}
- strategy:
- fail-fast: false
- matrix:
- os: [ubuntu-latest, macOS-latest, windows-latest]
-
- name: actions-311-dev
- timeout-minutes: 80
-
- concurrency:
- #https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.os }}-${{ matrix.pytest_target }}-dev
- cancel-in-progress: true
-
- steps:
- - uses: actions/checkout@v3
- with:
- fetch-depth: 0
-
- - name: Set up Python Dev Version
- uses: actions/setup-python@v3
- with:
- python-version: '3.11-dev'
-
- # TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- - name: Install dependencies
- shell: bash -el {0}
- run: |
- python -m pip install --upgrade pip "setuptools<60.0.0" wheel
- pip install -i https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
- pip install git+https://github.com/nedbat/coveragepy.git
- pip install cython python-dateutil pytz hypothesis pytest>=6.2.5 pytest-xdist pytest-cov
- pip list
-
- - name: Build Pandas
- run: |
- python setup.py build_ext -q -j2
- python -m pip install -e . --no-build-isolation --no-use-pep517
-
- - name: Build Version
- run: |
- python -c "import pandas; pandas.show_versions();"
-
- - name: Test with pytest
- shell: bash -el {0}
- run: |
- ci/run_tests.sh
-
- - name: Publish test results
- uses: actions/upload-artifact@v3
- with:
- name: Test results
- path: test-data.xml
- if: failure()
-
- - name: Report Coverage
- run: |
- coverage report -m
-
- - name: Upload coverage to Codecov
- uses: codecov/codecov-action@v2
- with:
- flags: unittests
- name: codecov-pandas
- fail_ci_if_error: true
diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml
deleted file mode 100644
index cd19eb7641c8c..0000000000000
--- a/.github/workflows/sdist.yml
+++ /dev/null
@@ -1,91 +0,0 @@
-name: sdist
-
-on:
- push:
- branches:
- - main
- - 1.4.x
- pull_request:
- branches:
- - main
- - 1.4.x
- types: [labeled, opened, synchronize, reopened]
- paths-ignore:
- - "doc/**"
-
-jobs:
- build:
- if: ${{ github.event.label.name == 'Build' || contains(github.event.pull_request.labels.*.name, 'Build') || github.event_name == 'push'}}
- runs-on: ubuntu-latest
- timeout-minutes: 60
- defaults:
- run:
- shell: bash -el {0}
-
- strategy:
- fail-fast: false
- matrix:
- python-version: ["3.8", "3.9", "3.10"]
- concurrency:
- # https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{matrix.python-version}}-sdist
- cancel-in-progress: true
-
- steps:
- - uses: actions/checkout@v3
- with:
- fetch-depth: 0
-
- - name: Set up Python
- uses: actions/setup-python@v3
- with:
- python-version: ${{ matrix.python-version }}
-
- # TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- - name: Install dependencies
- run: |
- python -m pip install --upgrade pip "setuptools<60.0.0" wheel
-
- # GH 39416
- pip install numpy
-
- - name: Build pandas sdist
- run: |
- pip list
- python setup.py sdist --formats=gztar
-
- - name: Upload sdist artifact
- uses: actions/upload-artifact@v3
- with:
- name: ${{matrix.python-version}}-sdist.gz
- path: dist/*.gz
-
- - uses: conda-incubator/setup-miniconda@v2.1.1
- with:
- activate-environment: pandas-sdist
- channels: conda-forge
- python-version: '${{ matrix.python-version }}'
-
- # TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- - name: Install pandas from sdist
- run: |
- python -m pip install --upgrade "setuptools<60.0.0"
- pip list
- python -m pip install dist/*.gz
-
- - name: Force oldest supported NumPy
- run: |
- case "${{matrix.python-version}}" in
- 3.8)
- pip install numpy==1.18.5 ;;
- 3.9)
- pip install numpy==1.19.3 ;;
- 3.10)
- pip install numpy==1.21.2 ;;
- esac
-
- - name: Import pandas
- run: |
- cd ..
- conda list
- python -c "import pandas; pandas.show_versions();"
diff --git a/.github/workflows/stale-pr.yml b/.github/workflows/stale-pr.yml
deleted file mode 100644
index b97b60717a2b8..0000000000000
--- a/.github/workflows/stale-pr.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-name: "Stale PRs"
-on:
- schedule:
- # * is a special character in YAML so you have to quote this string
- - cron: "0 0 * * *"
-
-jobs:
- stale:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/stale@v4
- with:
- repo-token: ${{ secrets.GITHUB_TOKEN }}
- stale-pr-message: "This pull request is stale because it has been open for thirty days with no activity. Please [update](https://pandas.pydata.org/pandas-docs/stable/development/contributing.html#updating-your-pull-request) and respond to this comment if you're still interested in working on this."
- stale-pr-label: "Stale"
- exempt-pr-labels: "Needs Review,Blocked,Needs Discussion"
- days-before-issue-stale: -1
- days-before-pr-stale: 30
- days-before-close: -1
- remove-stale-when-updated: false
- debug-only: false
| - [ ] 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 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/46617 | 2022-04-02T16:17:47Z | 2022-04-02T16:17:55Z | null | 2022-04-02T16:18:34Z |
Backport PR #46609 on branch 1.4.x (DOC: Start v1.4.3 release notes) | diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst
index 0f546d04ea0e7..47a46c86c3a44 100644
--- a/doc/source/whatsnew/index.rst
+++ b/doc/source/whatsnew/index.rst
@@ -16,6 +16,7 @@ Version 1.4
.. toctree::
:maxdepth: 2
+ v1.4.3
v1.4.2
v1.4.1
v1.4.0
diff --git a/doc/source/whatsnew/v1.4.2.rst b/doc/source/whatsnew/v1.4.2.rst
index 8a2bb4c6b3201..64c36632bfefe 100644
--- a/doc/source/whatsnew/v1.4.2.rst
+++ b/doc/source/whatsnew/v1.4.2.rst
@@ -42,4 +42,4 @@ Bug fixes
Contributors
~~~~~~~~~~~~
-.. contributors:: v1.4.1..v1.4.2|HEAD
+.. contributors:: v1.4.1..v1.4.2
diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst
new file mode 100644
index 0000000000000..d53acc698c3bb
--- /dev/null
+++ b/doc/source/whatsnew/v1.4.3.rst
@@ -0,0 +1,45 @@
+.. _whatsnew_143:
+
+What's new in 1.4.3 (April ??, 2022)
+------------------------------------
+
+These are the changes in pandas 1.4.3. See :ref:`release` for a full changelog
+including other versions of pandas.
+
+{{ header }}
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_143.regressions:
+
+Fixed regressions
+~~~~~~~~~~~~~~~~~
+-
+-
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_143.bug_fixes:
+
+Bug fixes
+~~~~~~~~~
+-
+-
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_143.other:
+
+Other
+~~~~~
+-
+-
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_143.contributors:
+
+Contributors
+~~~~~~~~~~~~
+
+.. contributors:: v1.4.2..v1.4.3|HEAD
| Backport PR #46609: DOC: Start v1.4.3 release notes | https://api.github.com/repos/pandas-dev/pandas/pulls/46612 | 2022-04-02T10:42:54Z | 2022-04-02T11:58:32Z | 2022-04-02T11:58:32Z | 2022-04-02T11:58:32Z |
Add setup-conda action | diff --git a/.circleci/config.yml b/.circleci/config.yml
index 612552f4eac59..0d9e3ade08846 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -13,7 +13,7 @@ jobs:
PANDAS_CI: "1"
steps:
- checkout
- - run: ci/setup_env.sh
+ - run: .circleci/setup_env.sh
- run: PATH=$HOME/miniconda3/envs/pandas-dev/bin:$HOME/miniconda3/condabin:$PATH ci/run_tests.sh
workflows:
diff --git a/ci/setup_env.sh b/.circleci/setup_env.sh
similarity index 100%
rename from ci/setup_env.sh
rename to .circleci/setup_env.sh
diff --git a/.github/actions/setup-conda/action.yml b/.github/actions/setup-conda/action.yml
new file mode 100644
index 0000000000000..1c947ff244fb9
--- /dev/null
+++ b/.github/actions/setup-conda/action.yml
@@ -0,0 +1,27 @@
+name: Set up Conda environment
+inputs:
+ environment-file:
+ description: Conda environment file to use.
+ default: environment.yml
+ pyarrow-version:
+ description: If set, overrides the PyArrow version in the Conda environment to the given string.
+ required: false
+runs:
+ using: composite
+ steps:
+ - name: Set Arrow version in ${{ inputs.environment-file }} to ${{ inputs.pyarrow-version }}
+ run: |
+ grep -q ' - pyarrow' ${{ inputs.environment-file }}
+ sed -i"" -e "s/ - pyarrow/ - pyarrow=${{ inputs.pyarrow-version }}/" ${{ inputs.environment-file }}
+ cat ${{ inputs.environment-file }}
+ shell: bash
+ if: ${{ inputs.pyarrow-version }}
+
+ - name: Install ${{ inputs.environment-file }}
+ uses: conda-incubator/setup-miniconda@v2
+ with:
+ environment-file: ${{ inputs.environment-file }}
+ channel-priority: ${{ runner.os == 'macOS' && 'flexible' || 'strict' }}
+ channels: conda-forge
+ mamba-version: "0.23"
+ use-mamba: true
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml
deleted file mode 100644
index c357f149f2c7f..0000000000000
--- a/.github/actions/setup/action.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-name: Set up pandas
-description: Runs all the setup steps required to have a built pandas ready to use
-runs:
- using: composite
- steps:
- - name: Setting conda path
- run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
- shell: bash -el {0}
-
- - name: Setup environment and build pandas
- run: ci/setup_env.sh
- shell: bash -el {0}
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml
index 8c2c86dc693a9..5ffd4135802bd 100644
--- a/.github/workflows/docbuild-and-upload.yml
+++ b/.github/workflows/docbuild-and-upload.yml
@@ -24,24 +24,27 @@ jobs:
group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-web-docs
cancel-in-progress: true
+ defaults:
+ run:
+ shell: bash -el {0}
+
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- - name: Set up pandas
- uses: ./.github/actions/setup
+ - name: Set up Conda
+ uses: ./.github/actions/setup-conda
+
+ - name: Build Pandas
+ uses: ./.github/actions/build_pandas
- name: Build website
- run: |
- source activate pandas-dev
- python web/pandas_web.py web/pandas --target-path=web/build
+ run: python web/pandas_web.py web/pandas --target-path=web/build
- name: Build documentation
- run: |
- source activate pandas-dev
- doc/make.py --warnings-are-errors
+ run: doc/make.py --warnings-are-errors
- name: Install ssh key
run: |
@@ -49,18 +52,18 @@ jobs:
echo "${{ secrets.server_ssh_key }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
echo "${{ secrets.server_ip }} ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBE1Kkopomm7FHG5enATf7SgnpICZ4W2bw+Ho+afqin+w7sMcrsa0je7sbztFAV8YchDkiBKnWTG4cRT+KZgZCaY=" > ~/.ssh/known_hosts
- if: ${{github.event_name == 'push' && github.ref == 'refs/heads/main'}}
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'
- name: Copy cheatsheets into site directory
run: cp doc/cheatsheet/Pandas_Cheat_Sheet* web/build/
- name: Upload web
run: rsync -az --delete --exclude='pandas-docs' --exclude='docs' web/build/ docs@${{ secrets.server_ip }}:/usr/share/nginx/pandas
- if: ${{github.event_name == 'push' && github.ref == 'refs/heads/main'}}
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'
- name: Upload dev docs
run: rsync -az --delete doc/build/html/ docs@${{ secrets.server_ip }}:/usr/share/nginx/pandas/pandas-docs/dev
- if: ${{github.event_name == 'push' && github.ref == 'refs/heads/main'}}
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'
- name: Move docs into site directory
run: mv doc/build/html web/build/docs
diff --git a/.github/workflows/macos-windows.yml b/.github/workflows/macos-windows.yml
index 560a421ec74ec..26e6c8699ca64 100644
--- a/.github/workflows/macos-windows.yml
+++ b/.github/workflows/macos-windows.yml
@@ -43,22 +43,11 @@ jobs:
with:
fetch-depth: 0
- - name: Install Dependencies
- uses: conda-incubator/setup-miniconda@v2.1.1
+ - name: Set up Conda
+ uses: ./.github/actions/setup-conda
with:
- mamba-version: "*"
- channels: conda-forge
- activate-environment: pandas-dev
- channel-priority: ${{ matrix.os == 'macos-latest' && 'flexible' || 'strict' }}
environment-file: ci/deps/${{ matrix.env_file }}
- use-only-tar-bz2: true
-
- # ImportError: 2): Library not loaded: @rpath/libssl.1.1.dylib
- # Referenced from: /Users/runner/miniconda3/envs/pandas-dev/lib/libthrift.0.13.0.dylib
- # Reason: image not found
- - name: Upgrade pyarrow on MacOS
- run: conda install -n pandas-dev -c conda-forge --no-update-deps pyarrow=6
- if: ${{ matrix.os == 'macos-latest' }}
+ pyarrow-version: ${{ matrix.os == 'macos-latest' && '6' || '' }}
- name: Build Pandas
uses: ./.github/actions/build_pandas
@@ -66,9 +55,6 @@ jobs:
- name: Test
run: ci/run_tests.sh
- - name: Build Version
- run: conda list
-
- name: Publish test results
uses: actions/upload-artifact@v3
with:
diff --git a/setup.py b/setup.py
index 0418fe67c2f76..ced8b8dbc96c6 100755
--- a/setup.py
+++ b/setup.py
@@ -333,7 +333,7 @@ def run(self):
extra_compile_args.append("/Z7")
extra_link_args.append("/DEBUG")
else:
- # PANDAS_CI=1 is set by ci/setup_env.sh
+ # PANDAS_CI=1 is set in CI
if os.environ.get("PANDAS_CI", "0") == "1":
extra_compile_args.append("-Werror")
if debugging_symbols_requested:
| Smaller version of https://github.com/pandas-dev/pandas/pull/46493 according to suggestion in https://github.com/pandas-dev/pandas/pull/46493#issuecomment-1079541210. Should be orthogonal to https://github.com/pandas-dev/pandas/pull/46538.
- [x] closes #39175 (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 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/46611 | 2022-04-02T10:39:41Z | 2022-06-03T20:59:04Z | 2022-06-03T20:59:04Z | 2022-06-03T20:59:20Z |
DOC: Start v1.4.3 release notes | diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst
index 7ea81611ede27..ccec4f90183bc 100644
--- a/doc/source/whatsnew/index.rst
+++ b/doc/source/whatsnew/index.rst
@@ -24,6 +24,7 @@ Version 1.4
.. toctree::
:maxdepth: 2
+ v1.4.3
v1.4.2
v1.4.1
v1.4.0
diff --git a/doc/source/whatsnew/v1.4.2.rst b/doc/source/whatsnew/v1.4.2.rst
index 8a2bb4c6b3201..64c36632bfefe 100644
--- a/doc/source/whatsnew/v1.4.2.rst
+++ b/doc/source/whatsnew/v1.4.2.rst
@@ -42,4 +42,4 @@ Bug fixes
Contributors
~~~~~~~~~~~~
-.. contributors:: v1.4.1..v1.4.2|HEAD
+.. contributors:: v1.4.1..v1.4.2
diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst
new file mode 100644
index 0000000000000..d53acc698c3bb
--- /dev/null
+++ b/doc/source/whatsnew/v1.4.3.rst
@@ -0,0 +1,45 @@
+.. _whatsnew_143:
+
+What's new in 1.4.3 (April ??, 2022)
+------------------------------------
+
+These are the changes in pandas 1.4.3. See :ref:`release` for a full changelog
+including other versions of pandas.
+
+{{ header }}
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_143.regressions:
+
+Fixed regressions
+~~~~~~~~~~~~~~~~~
+-
+-
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_143.bug_fixes:
+
+Bug fixes
+~~~~~~~~~
+-
+-
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_143.other:
+
+Other
+~~~~~
+-
+-
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_143.contributors:
+
+Contributors
+~~~~~~~~~~~~
+
+.. contributors:: v1.4.2..v1.4.3|HEAD
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/46609 | 2022-04-02T09:08:28Z | 2022-04-02T10:42:24Z | 2022-04-02T10:42:24Z | 2022-04-02T10:42:28Z |
TYP: fix hashable keys for pd.concat | diff --git a/pandas/_typing.py b/pandas/_typing.py
index 35c057df43322..1debc4265508f 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -73,6 +73,7 @@
else:
npt: Any = None
+HashableT = TypeVar("HashableT", bound=Hashable)
# array-like
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index 72f3b402d49e3..17e78d3bb900a 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -18,7 +18,10 @@
import numpy as np
-from pandas._typing import Axis
+from pandas._typing import (
+ Axis,
+ HashableT,
+)
from pandas.util._decorators import (
cache_readonly,
deprecate_nonkeyword_arguments,
@@ -62,7 +65,7 @@
@overload
def concat(
- objs: Iterable[DataFrame] | Mapping[Hashable, DataFrame],
+ objs: Iterable[DataFrame] | Mapping[HashableT, DataFrame],
axis: Literal[0, "index"] = ...,
join: str = ...,
ignore_index: bool = ...,
@@ -78,7 +81,7 @@ def concat(
@overload
def concat(
- objs: Iterable[Series] | Mapping[Hashable, Series],
+ objs: Iterable[Series] | Mapping[HashableT, Series],
axis: Literal[0, "index"] = ...,
join: str = ...,
ignore_index: bool = ...,
@@ -94,7 +97,7 @@ def concat(
@overload
def concat(
- objs: Iterable[NDFrame] | Mapping[Hashable, NDFrame],
+ objs: Iterable[NDFrame] | Mapping[HashableT, NDFrame],
axis: Literal[0, "index"] = ...,
join: str = ...,
ignore_index: bool = ...,
@@ -110,7 +113,7 @@ def concat(
@overload
def concat(
- objs: Iterable[NDFrame] | Mapping[Hashable, NDFrame],
+ objs: Iterable[NDFrame] | Mapping[HashableT, NDFrame],
axis: Literal[1, "columns"],
join: str = ...,
ignore_index: bool = ...,
@@ -126,7 +129,7 @@ def concat(
@overload
def concat(
- objs: Iterable[NDFrame] | Mapping[Hashable, NDFrame],
+ objs: Iterable[NDFrame] | Mapping[HashableT, NDFrame],
axis: Axis = ...,
join: str = ...,
ignore_index: bool = ...,
@@ -142,7 +145,7 @@ def concat(
@deprecate_nonkeyword_arguments(version=None, allowed_args=["objs"])
def concat(
- objs: Iterable[NDFrame] | Mapping[Hashable, NDFrame],
+ objs: Iterable[NDFrame] | Mapping[HashableT, NDFrame],
axis: Axis = 0,
join: str = "outer",
ignore_index: bool = False,
@@ -367,7 +370,7 @@ class _Concatenator:
def __init__(
self,
- objs: Iterable[NDFrame] | Mapping[Hashable, NDFrame],
+ objs: Iterable[NDFrame] | Mapping[HashableT, NDFrame],
axis=0,
join: str = "outer",
keys=None,
| Could use `Any` but I think in this case the covariant `TypeVar` approach isn't ugly (I think so - happy to change to `Any`). | https://api.github.com/repos/pandas-dev/pandas/pulls/46608 | 2022-04-02T02:17:39Z | 2022-04-04T13:42:55Z | 2022-04-04T13:42:55Z | 2022-05-26T01:59:15Z |
Backport PR #46605 on branch 1.4.x (DOC: 1.4.2 release date) | diff --git a/doc/source/whatsnew/v1.4.2.rst b/doc/source/whatsnew/v1.4.2.rst
index 66068f9faa923..8a2bb4c6b3201 100644
--- a/doc/source/whatsnew/v1.4.2.rst
+++ b/doc/source/whatsnew/v1.4.2.rst
@@ -1,7 +1,7 @@
.. _whatsnew_142:
-What's new in 1.4.2 (March ??, 2022)
-------------------------------------
+What's new in 1.4.2 (April 2, 2022)
+-----------------------------------
These are the changes in pandas 1.4.2. See :ref:`release` for a full changelog
including other versions of pandas.
@@ -22,6 +22,7 @@ Fixed regressions
- Fixed regression in :meth:`DataFrame.replace` when the replacement value was explicitly ``None`` when passed in a dictionary to ``to_replace`` (:issue:`45601`, :issue:`45836`)
- Fixed regression when setting values with :meth:`DataFrame.loc` losing :class:`MultiIndex` names if :class:`DataFrame` was empty before (:issue:`46317`)
- Fixed regression when rendering boolean datatype columns with :meth:`.Styler` (:issue:`46384`)
+- Fixed regression in :meth:`Groupby.rolling` with a frequency window that would raise a ``ValueError`` even if the datetimes within each group were monotonic (:issue:`46061`)
.. ---------------------------------------------------------------------------
@@ -33,16 +34,6 @@ Bug fixes
- Fixed "longtable" formatting in :meth:`.Styler.to_latex` when ``column_format`` is given in extended format (:issue:`46037`)
- Fixed incorrect rendering in :meth:`.Styler.format` with ``hyperlinks="html"`` when the url contains a colon or other special characters (:issue:`46389`)
- Improved error message in :class:`~pandas.core.window.Rolling` when ``window`` is a frequency and ``NaT`` is in the rolling axis (:issue:`46087`)
-- Fixed :meth:`Groupby.rolling` with a frequency window that would raise a ``ValueError`` even if the datetimes within each group were monotonic (:issue:`46061`)
-
-.. ---------------------------------------------------------------------------
-
-.. _whatsnew_142.other:
-
-Other
-~~~~~
--
--
.. ---------------------------------------------------------------------------
| Backport PR #46605: DOC: 1.4.2 release date | https://api.github.com/repos/pandas-dev/pandas/pulls/46607 | 2022-04-01T20:38:54Z | 2022-04-01T21:44:02Z | 2022-04-01T21:44:02Z | 2022-04-01T21:44:02Z |
DOC: 1.4.2 release date | diff --git a/doc/source/whatsnew/v1.4.2.rst b/doc/source/whatsnew/v1.4.2.rst
index 66068f9faa923..8a2bb4c6b3201 100644
--- a/doc/source/whatsnew/v1.4.2.rst
+++ b/doc/source/whatsnew/v1.4.2.rst
@@ -1,7 +1,7 @@
.. _whatsnew_142:
-What's new in 1.4.2 (March ??, 2022)
-------------------------------------
+What's new in 1.4.2 (April 2, 2022)
+-----------------------------------
These are the changes in pandas 1.4.2. See :ref:`release` for a full changelog
including other versions of pandas.
@@ -22,6 +22,7 @@ Fixed regressions
- Fixed regression in :meth:`DataFrame.replace` when the replacement value was explicitly ``None`` when passed in a dictionary to ``to_replace`` (:issue:`45601`, :issue:`45836`)
- Fixed regression when setting values with :meth:`DataFrame.loc` losing :class:`MultiIndex` names if :class:`DataFrame` was empty before (:issue:`46317`)
- Fixed regression when rendering boolean datatype columns with :meth:`.Styler` (:issue:`46384`)
+- Fixed regression in :meth:`Groupby.rolling` with a frequency window that would raise a ``ValueError`` even if the datetimes within each group were monotonic (:issue:`46061`)
.. ---------------------------------------------------------------------------
@@ -33,16 +34,6 @@ Bug fixes
- Fixed "longtable" formatting in :meth:`.Styler.to_latex` when ``column_format`` is given in extended format (:issue:`46037`)
- Fixed incorrect rendering in :meth:`.Styler.format` with ``hyperlinks="html"`` when the url contains a colon or other special characters (:issue:`46389`)
- Improved error message in :class:`~pandas.core.window.Rolling` when ``window`` is a frequency and ``NaT`` is in the rolling axis (:issue:`46087`)
-- Fixed :meth:`Groupby.rolling` with a frequency window that would raise a ``ValueError`` even if the datetimes within each group were monotonic (:issue:`46061`)
-
-.. ---------------------------------------------------------------------------
-
-.. _whatsnew_142.other:
-
-Other
-~~~~~
--
--
.. ---------------------------------------------------------------------------
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/46605 | 2022-04-01T19:25:22Z | 2022-04-01T20:38:09Z | 2022-04-01T20:38:08Z | 2022-04-01T20:38:12Z |
DOC: moved release note for #46087 | diff --git a/doc/source/whatsnew/v1.4.2.rst b/doc/source/whatsnew/v1.4.2.rst
index e98e419283508..66068f9faa923 100644
--- a/doc/source/whatsnew/v1.4.2.rst
+++ b/doc/source/whatsnew/v1.4.2.rst
@@ -32,6 +32,7 @@ Bug fixes
- Fix some cases for subclasses that define their ``_constructor`` properties as general callables (:issue:`46018`)
- Fixed "longtable" formatting in :meth:`.Styler.to_latex` when ``column_format`` is given in extended format (:issue:`46037`)
- Fixed incorrect rendering in :meth:`.Styler.format` with ``hyperlinks="html"`` when the url contains a colon or other special characters (:issue:`46389`)
+- Improved error message in :class:`~pandas.core.window.Rolling` when ``window`` is a frequency and ``NaT`` is in the rolling axis (:issue:`46087`)
- Fixed :meth:`Groupby.rolling` with a frequency window that would raise a ``ValueError`` even if the datetimes within each group were monotonic (:issue:`46061`)
.. ---------------------------------------------------------------------------
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 0b8f11fc4749b..56b1a6317472b 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -89,7 +89,6 @@ Other enhancements
- :meth:`DataFrame.rolling` and :meth:`Series.rolling` now support a ``step`` parameter with fixed-length windows (:issue:`15354`)
- Implemented a ``bool``-dtype :class:`Index`, passing a bool-dtype array-like to ``pd.Index`` will now retain ``bool`` dtype instead of casting to ``object`` (:issue:`45061`)
- Implemented a complex-dtype :class:`Index`, passing a complex-dtype array-like to ``pd.Index`` will now retain complex dtype instead of casting to ``object`` (:issue:`45845`)
-- Improved error message in :class:`~pandas.core.window.Rolling` when ``window`` is a frequency and ``NaT`` is in the rolling axis (:issue:`46087`)
- :class:`Series` and :class:`DataFrame` with ``IntegerDtype`` now supports bitwise operations (:issue:`34463`)
- Add ``milliseconds`` field support for :class:`~pandas.DateOffset` (:issue:`43371`)
- :meth:`DataFrame.reset_index` now accepts a ``names`` argument which renames the index names (:issue:`6878`)
| xref #46592
I'm going to merge this before all tests complete, since this PR is for main only and want to follow-up quickly with a PR for the release date of 1.4.2 (and move another release note xref https://github.com/pandas-dev/pandas/pull/46592#issuecomment-1086173499) which will conflict with this one | https://api.github.com/repos/pandas-dev/pandas/pulls/46604 | 2022-04-01T18:37:36Z | 2022-04-01T19:15:01Z | 2022-04-01T19:15:01Z | 2022-04-01T19:15:05Z |
TYP: na_value | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 112c401500472..393eb2997f6f0 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -500,7 +500,7 @@ def factorize_array(
values: np.ndarray,
na_sentinel: int = -1,
size_hint: int | None = None,
- na_value=None,
+ na_value: object = None,
mask: npt.NDArray[np.bool_] | None = None,
) -> tuple[npt.NDArray[np.intp], np.ndarray]:
"""
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index b06a46dfd1447..a188692a2d8f7 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -460,7 +460,7 @@ def to_numpy(
self,
dtype: npt.DTypeLike | None = None,
copy: bool = False,
- na_value=lib.no_default,
+ na_value: object = lib.no_default,
) -> np.ndarray:
"""
Convert to a NumPy ndarray.
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 5ae71b305ac60..90f56a3eea0fb 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -337,7 +337,7 @@ def to_numpy(
self,
dtype: npt.DTypeLike | None = None,
copy: bool = False,
- na_value: Scalar | lib.NoDefault | libmissing.NAType = lib.no_default,
+ na_value: object = lib.no_default,
) -> np.ndarray:
"""
Convert to a NumPy Array.
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py
index be7dc5e0ebdc6..36c67d2fe1225 100644
--- a/pandas/core/arrays/numpy_.py
+++ b/pandas/core/arrays/numpy_.py
@@ -368,7 +368,7 @@ def to_numpy(
self,
dtype: npt.DTypeLike | None = None,
copy: bool = False,
- na_value=lib.no_default,
+ na_value: object = lib.no_default,
) -> np.ndarray:
result = np.asarray(self._ndarray, dtype=dtype)
diff --git a/pandas/core/base.py b/pandas/core/base.py
index ce11f31281f5d..12ab942e70574 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -433,7 +433,7 @@ def to_numpy(
self,
dtype: npt.DTypeLike | None = None,
copy: bool = False,
- na_value=lib.no_default,
+ na_value: object = lib.no_default,
**kwargs,
) -> np.ndarray:
"""
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 0a102d4e2bdc9..ded525cd099fc 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1511,7 +1511,7 @@ def as_array(
self,
dtype: np.dtype | None = None,
copy: bool = False,
- na_value=lib.no_default,
+ na_value: object = lib.no_default,
) -> np.ndarray:
"""
Convert the blockmanager data into an numpy array.
@@ -1570,7 +1570,7 @@ def as_array(
def _interleave(
self,
dtype: np.dtype | None = None,
- na_value=lib.no_default,
+ na_value: object = lib.no_default,
) -> np.ndarray:
"""
Return ndarray from blocks with specified item order
diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py
index a3edc95fce96b..6eaa90d7b868a 100644
--- a/pandas/tests/extension/decimal/array.py
+++ b/pandas/tests/extension/decimal/array.py
@@ -105,7 +105,11 @@ def _from_factorized(cls, values, original):
_HANDLED_TYPES = (decimal.Decimal, numbers.Number, np.ndarray)
def to_numpy(
- self, dtype=None, copy: bool = False, na_value=no_default, decimals=None
+ self,
+ dtype=None,
+ copy: bool = False,
+ na_value: object = no_default,
+ decimals=None,
) -> np.ndarray:
result = np.asarray(self, dtype=dtype)
if decimals is not None:
| `na_value` can in most cases be anything (`object`) | https://api.github.com/repos/pandas-dev/pandas/pulls/46603 | 2022-04-01T18:24:17Z | 2022-04-30T00:51:15Z | 2022-04-30T00:51:15Z | 2022-05-26T01:59:19Z |
CI/TST: Make test_vector_resize more deterministic | diff --git a/pandas/tests/libs/test_hashtable.py b/pandas/tests/libs/test_hashtable.py
index bed427da5dd12..0a3a10315b5fd 100644
--- a/pandas/tests/libs/test_hashtable.py
+++ b/pandas/tests/libs/test_hashtable.py
@@ -246,16 +246,7 @@ def test_lookup_overflow(self, writable):
(ht.Float64HashTable, ht.Float64Vector, "float64", False),
(ht.Int64HashTable, ht.Int64Vector, "int64", False),
(ht.Int32HashTable, ht.Int32Vector, "int32", False),
- pytest.param(
- ht.UInt64HashTable,
- ht.UInt64Vector,
- "uint64",
- False,
- marks=pytest.mark.xfail(
- reason="Sometimes doesn't raise.",
- strict=False,
- ),
- ),
+ (ht.UInt64HashTable, ht.UInt64Vector, "uint64", False),
],
)
def test_vector_resize(
@@ -263,7 +254,9 @@ def test_vector_resize(
):
# Test for memory errors after internal vector
# reallocations (GH 7157)
- vals = np.array(np.random.randn(1000), dtype=dtype)
+ # Changed from using np.random.rand to range
+ # which could cause flaky CI failures when safely_resizes=False
+ vals = np.array(range(1000), dtype=dtype)
# GH 21688 ensures we can deal with read-only memory views
vals.setflags(write=writable)
| - [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).
I had to `xfail(strict=True)` this test once before which leads me to believe that the initial random data may be causing this test to be flaky.
https://dev.azure.com/pandas-dev/pandas/_build/results?buildId=76111&view=logs&jobId=b1891a80-bdb0-5193-5f59-ce68a0874df0&j=b1891a80-bdb0-5193-5f59-ce68a0874df0&t=0a58a9e9-0673-539c-5bde-d78a5a3b655e
```
=================================== FAILURES ===================================
_ TestHashTableUnsorted.test_vector_resize[False-Int32HashTable-Int32Vector-int32-False-10] _
[gw1] darwin -- Python 3.9.12 /usr/local/miniconda/envs/pandas-dev/bin/python
self = <pandas.tests.libs.test_hashtable.TestHashTableUnsorted object at 0x161a3d7c0>
writable = False
htable = <pandas._libs.hashtable.Int32HashTable object at 0x1764fee30>
uniques = <pandas._libs.hashtable.Int32Vector object at 0x176528e00>
dtype = 'int32', safely_resizes = False, nvals = 10
@pytest.mark.parametrize("nvals", [0, 10]) # resizing to 0 is special case
@pytest.mark.parametrize(
"htable, uniques, dtype, safely_resizes",
[
(ht.PyObjectHashTable, ht.ObjectVector, "object", False),
(ht.StringHashTable, ht.ObjectVector, "object", True),
(ht.Float64HashTable, ht.Float64Vector, "float64", False),
(ht.Int64HashTable, ht.Int64Vector, "int64", False),
(ht.Int32HashTable, ht.Int32Vector, "int32", False),
pytest.param(
ht.UInt64HashTable,
ht.UInt64Vector,
"uint64",
False,
marks=pytest.mark.xfail(
reason="Sometimes doesn't raise.",
else:
with pytest.raises(ValueError, match="external reference.*"):
> htable.get_labels(vals, uniques, 0, -1)
E Failed: DID NOT RAISE <class 'ValueError'>
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/46602 | 2022-04-01T17:26:11Z | 2022-04-03T02:38:00Z | 2022-04-03T02:38:00Z | 2022-04-07T15:15:25Z |
BUG: algorithms.factorize moves null values when sort=False | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 0ceac8aeb9db8..dcac0e5af912f 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -299,6 +299,7 @@ Other enhancements
- Added ``copy`` keyword to :meth:`Series.set_axis` and :meth:`DataFrame.set_axis` to allow user to set axis on a new object without necessarily copying the underlying data (:issue:`47932`)
- :meth:`Series.add_suffix`, :meth:`DataFrame.add_suffix`, :meth:`Series.add_prefix` and :meth:`DataFrame.add_prefix` support a ``copy`` argument. If ``False``, the underlying data is not copied in the returned object (:issue:`47934`)
- :meth:`DataFrame.set_index` now supports a ``copy`` keyword. If ``False``, the underlying data is not copied when a new :class:`DataFrame` is returned (:issue:`48043`)
+- The method :meth:`.ExtensionArray.factorize` accepts ``use_na_sentinel=False`` for determining how null values are to be treated (:issue:`46601`)
.. ---------------------------------------------------------------------------
.. _whatsnew_150.notable_bug_fixes:
@@ -927,6 +928,7 @@ Numeric
- Bug in division, ``pow`` and ``mod`` operations on array-likes with ``dtype="boolean"`` not being like their ``np.bool_`` counterparts (:issue:`46063`)
- Bug in multiplying a :class:`Series` with ``IntegerDtype`` or ``FloatingDtype`` by an array-like with ``timedelta64[ns]`` dtype incorrectly raising (:issue:`45622`)
- Bug in :meth:`mean` where the optional dependency ``bottleneck`` causes precision loss linear in the length of the array. ``bottleneck`` has been disabled for :meth:`mean` improving the loss to log-linear but may result in a performance decrease. (:issue:`42878`)
+- Bug in :func:`factorize` would convert the value ``None`` to ``np.nan`` (:issue:`46601`)
Conversion
^^^^^^^^^^
@@ -1098,6 +1100,7 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrame.groupby` and :meth:`Series.groupby` would not respect ``dropna=False`` when the input DataFrame/Series had a NaN values in a :class:`MultiIndex` (:issue:`46783`)
- Bug in :meth:`DataFrameGroupBy.resample` raises ``KeyError`` when getting the result from a key list which misses the resample key (:issue:`47362`)
- Bug in :meth:`DataFrame.groupby` would lose index columns when the DataFrame is empty for transforms, like fillna (:issue:`47787`)
+- Bug in :meth:`DataFrame.groupby` and :meth:`Series.groupby` with ``dropna=False`` and ``sort=False`` would put any null groups at the end instead the order that they are encountered (:issue:`46584`)
-
Reshaping
diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in
index 8a2b9c2f77627..f25e4ad009153 100644
--- a/pandas/_libs/hashtable_class_helper.pxi.in
+++ b/pandas/_libs/hashtable_class_helper.pxi.in
@@ -658,7 +658,7 @@ cdef class {{name}}HashTable(HashTable):
return_inverse=return_inverse)
def factorize(self, const {{dtype}}_t[:] values, Py_ssize_t na_sentinel=-1,
- object na_value=None, object mask=None):
+ object na_value=None, object mask=None, ignore_na=True):
"""
Calculate unique values and labels (no sorting!)
@@ -690,7 +690,7 @@ cdef class {{name}}HashTable(HashTable):
"""
uniques_vector = {{name}}Vector()
return self._unique(values, uniques_vector, na_sentinel=na_sentinel,
- na_value=na_value, ignore_na=True, mask=mask,
+ na_value=na_value, ignore_na=ignore_na, mask=mask,
return_inverse=True)
def get_labels(self, const {{dtype}}_t[:] values, {{name}}Vector uniques,
@@ -1037,7 +1037,7 @@ cdef class StringHashTable(HashTable):
return_inverse=return_inverse)
def factorize(self, ndarray[object] values, Py_ssize_t na_sentinel=-1,
- object na_value=None, object mask=None):
+ object na_value=None, object mask=None, ignore_na=True):
"""
Calculate unique values and labels (no sorting!)
@@ -1067,7 +1067,7 @@ cdef class StringHashTable(HashTable):
"""
uniques_vector = ObjectVector()
return self._unique(values, uniques_vector, na_sentinel=na_sentinel,
- na_value=na_value, ignore_na=True,
+ na_value=na_value, ignore_na=ignore_na,
return_inverse=True)
def get_labels(self, ndarray[object] values, ObjectVector uniques,
@@ -1290,7 +1290,7 @@ cdef class PyObjectHashTable(HashTable):
return_inverse=return_inverse)
def factorize(self, ndarray[object] values, Py_ssize_t na_sentinel=-1,
- object na_value=None, object mask=None):
+ object na_value=None, object mask=None, ignore_na=True):
"""
Calculate unique values and labels (no sorting!)
@@ -1320,7 +1320,7 @@ cdef class PyObjectHashTable(HashTable):
"""
uniques_vector = ObjectVector()
return self._unique(values, uniques_vector, na_sentinel=na_sentinel,
- na_value=na_value, ignore_na=True,
+ na_value=na_value, ignore_na=ignore_na,
return_inverse=True)
def get_labels(self, ndarray[object] values, ObjectVector uniques,
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index a4736c2a141a5..9b031fc9517c7 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -509,7 +509,7 @@ def f(c, v):
def factorize_array(
values: np.ndarray,
- na_sentinel: int = -1,
+ na_sentinel: int | None = -1,
size_hint: int | None = None,
na_value: object = None,
mask: npt.NDArray[np.bool_] | None = None,
@@ -540,6 +540,10 @@ def factorize_array(
codes : ndarray[np.intp]
uniques : ndarray
"""
+ ignore_na = na_sentinel is not None
+ if not ignore_na:
+ na_sentinel = -1
+
original = values
if values.dtype.kind in ["m", "M"]:
# _get_hashtable_algo will cast dt64/td64 to i8 via _ensure_data, so we
@@ -552,7 +556,11 @@ def factorize_array(
table = hash_klass(size_hint or len(values))
uniques, codes = table.factorize(
- values, na_sentinel=na_sentinel, na_value=na_value, mask=mask
+ values,
+ na_sentinel=na_sentinel,
+ na_value=na_value,
+ mask=mask,
+ ignore_na=ignore_na,
)
# re-cast e.g. i8->dt64/td64, uint8->bool
@@ -726,6 +734,10 @@ def factorize(
# responsible only for factorization. All data coercion, sorting and boxing
# should happen here.
+ # GH#46910 deprecated na_sentinel in favor of use_na_sentinel:
+ # na_sentinel=None corresponds to use_na_sentinel=False
+ # na_sentinel=-1 correspond to use_na_sentinel=True
+ # Other na_sentinel values will not be supported when the deprecation is enforced.
na_sentinel = resolve_na_sentinel(na_sentinel, use_na_sentinel)
if isinstance(values, ABCRangeIndex):
return values.factorize(sort=sort)
@@ -737,10 +749,7 @@ def factorize(
# GH35667, if na_sentinel=None, we will not dropna NaNs from the uniques
# of values, assign na_sentinel=-1 to replace code value for NaN.
- dropna = True
- if na_sentinel is None:
- na_sentinel = -1
- dropna = False
+ dropna = na_sentinel is not None
if (
isinstance(values, (ABCDatetimeArray, ABCTimedeltaArray))
@@ -753,38 +762,58 @@ def factorize(
elif not isinstance(values.dtype, np.dtype):
if (
- na_sentinel == -1
- and "use_na_sentinel" in inspect.signature(values.factorize).parameters
- ):
+ na_sentinel == -1 or na_sentinel is None
+ ) and "use_na_sentinel" in inspect.signature(values.factorize).parameters:
# Avoid using catch_warnings when possible
# GH#46910 - TimelikeOps has deprecated signature
codes, uniques = values.factorize( # type: ignore[call-arg]
- use_na_sentinel=True
+ use_na_sentinel=na_sentinel is not None
)
else:
+ na_sentinel_arg = -1 if na_sentinel is None else na_sentinel
with warnings.catch_warnings():
# We've already warned above
warnings.filterwarnings("ignore", ".*use_na_sentinel.*", FutureWarning)
- codes, uniques = values.factorize(na_sentinel=na_sentinel)
+ codes, uniques = values.factorize(na_sentinel=na_sentinel_arg)
else:
values = np.asarray(values) # convert DTA/TDA/MultiIndex
+ # TODO: pass na_sentinel=na_sentinel to factorize_array. When sort is True and
+ # na_sentinel is None we append NA on the end because safe_sort does not
+ # handle null values in uniques.
+ if na_sentinel is None and sort:
+ na_sentinel_arg = -1
+ elif na_sentinel is None:
+ na_sentinel_arg = None
+ else:
+ na_sentinel_arg = na_sentinel
codes, uniques = factorize_array(
- values, na_sentinel=na_sentinel, size_hint=size_hint
+ values,
+ na_sentinel=na_sentinel_arg,
+ size_hint=size_hint,
)
if sort and len(uniques) > 0:
+ if na_sentinel is None:
+ # TODO: Can remove when na_sentinel=na_sentinel as in TODO above
+ na_sentinel = -1
uniques, codes = safe_sort(
uniques, codes, na_sentinel=na_sentinel, assume_unique=True, verify=False
)
- code_is_na = codes == na_sentinel
- if not dropna and code_is_na.any():
- # na_value is set based on the dtype of uniques, and compat set to False is
- # because we do not want na_value to be 0 for integers
- na_value = na_value_for_dtype(uniques.dtype, compat=False)
- uniques = np.append(uniques, [na_value])
- codes = np.where(code_is_na, len(uniques) - 1, codes)
+ if not dropna and sort:
+ # TODO: Can remove entire block when na_sentinel=na_sentinel as in TODO above
+ if na_sentinel is None:
+ na_sentinel_arg = -1
+ else:
+ na_sentinel_arg = na_sentinel
+ code_is_na = codes == na_sentinel_arg
+ if code_is_na.any():
+ # na_value is set based on the dtype of uniques, and compat set to False is
+ # because we do not want na_value to be 0 for integers
+ na_value = na_value_for_dtype(uniques.dtype, compat=False)
+ uniques = np.append(uniques, [na_value])
+ codes = np.where(code_is_na, len(uniques) - 1, codes)
uniques = _reconstruct_data(uniques, original.dtype, original)
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
index a3b2003b0caf3..8d80cb18d21db 100644
--- a/pandas/core/arrays/arrow/array.py
+++ b/pandas/core/arrays/arrow/array.py
@@ -551,20 +551,32 @@ def factorize(
use_na_sentinel: bool | lib.NoDefault = lib.no_default,
) -> tuple[np.ndarray, ExtensionArray]:
resolved_na_sentinel = resolve_na_sentinel(na_sentinel, use_na_sentinel)
- if resolved_na_sentinel is None:
- raise NotImplementedError("Encoding NaN values is not yet implemented")
+ if pa_version_under4p0:
+ encoded = self._data.dictionary_encode()
else:
- na_sentinel = resolved_na_sentinel
- encoded = self._data.dictionary_encode()
+ null_encoding = "mask" if resolved_na_sentinel is not None else "encode"
+ encoded = self._data.dictionary_encode(null_encoding=null_encoding)
indices = pa.chunked_array(
[c.indices for c in encoded.chunks], type=encoded.type.index_type
).to_pandas()
if indices.dtype.kind == "f":
- indices[np.isnan(indices)] = na_sentinel
+ indices[np.isnan(indices)] = (
+ resolved_na_sentinel if resolved_na_sentinel is not None else -1
+ )
indices = indices.astype(np.int64, copy=False)
if encoded.num_chunks:
uniques = type(self)(encoded.chunk(0).dictionary)
+ if resolved_na_sentinel is None and pa_version_under4p0:
+ # TODO: share logic with BaseMaskedArray.factorize
+ # Insert na with the proper code
+ na_mask = indices.values == -1
+ na_index = na_mask.argmax()
+ if na_mask[na_index]:
+ uniques = uniques.insert(na_index, self.dtype.na_value)
+ na_code = 0 if na_index == 0 else indices[:na_index].argmax() + 1
+ indices[indices >= na_code] += 1
+ indices[indices == -1] = na_code
else:
uniques = type(self)(pa.array([], type=encoded.type.value_type))
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 043917376b8c1..1e3b137184660 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -1081,14 +1081,10 @@ def factorize(
# 2. ExtensionArray.factorize.
# Complete control over factorization.
resolved_na_sentinel = resolve_na_sentinel(na_sentinel, use_na_sentinel)
- if resolved_na_sentinel is None:
- raise NotImplementedError("Encoding NaN values is not yet implemented")
- else:
- na_sentinel = resolved_na_sentinel
arr, na_value = self._values_for_factorize()
codes, uniques = factorize_array(
- arr, na_sentinel=na_sentinel, na_value=na_value
+ arr, na_sentinel=resolved_na_sentinel, na_value=na_value
)
uniques_ea = self._from_factorized(uniques, self)
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 128c7e44f5075..fb350b311532f 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -875,19 +875,39 @@ def factorize(
use_na_sentinel: bool | lib.NoDefault = lib.no_default,
) -> tuple[np.ndarray, ExtensionArray]:
resolved_na_sentinel = algos.resolve_na_sentinel(na_sentinel, use_na_sentinel)
- if resolved_na_sentinel is None:
- raise NotImplementedError("Encoding NaN values is not yet implemented")
- else:
- na_sentinel = resolved_na_sentinel
arr = self._data
mask = self._mask
- codes, uniques = factorize_array(arr, na_sentinel=na_sentinel, mask=mask)
+ # Pass non-None na_sentinel; recode and add NA to uniques if necessary below
+ na_sentinel_arg = -1 if resolved_na_sentinel is None else resolved_na_sentinel
+ codes, uniques = factorize_array(arr, na_sentinel=na_sentinel_arg, mask=mask)
# check that factorize_array correctly preserves dtype.
assert uniques.dtype == self.dtype.numpy_dtype, (uniques.dtype, self.dtype)
- uniques_ea = type(self)(uniques, np.zeros(len(uniques), dtype=bool))
+ has_na = mask.any()
+ if resolved_na_sentinel is not None or not has_na:
+ size = len(uniques)
+ else:
+ # Make room for an NA value
+ size = len(uniques) + 1
+ uniques_mask = np.zeros(size, dtype=bool)
+ if resolved_na_sentinel is None and has_na:
+ na_index = mask.argmax()
+ # Insert na with the proper code
+ if na_index == 0:
+ na_code = np.intp(0)
+ else:
+ # mypy error: Slice index must be an integer or None
+ # https://github.com/python/mypy/issues/2410
+ na_code = codes[:na_index].argmax() + 1 # type: ignore[misc]
+ codes[codes >= na_code] += 1
+ codes[codes == -1] = na_code
+ # dummy value for uniques; not used since uniques_mask will be True
+ uniques = np.insert(uniques, na_code, 0)
+ uniques_mask[na_code] = True
+ uniques_ea = type(self)(uniques, uniques_mask)
+
return codes, uniques_ea
@doc(ExtensionArray._values_for_argsort)
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index e9302efdce2e7..e2cb49957cc2a 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -875,6 +875,10 @@ def factorize(
codes, uniques = algos.factorize(
np.asarray(self), na_sentinel=na_sentinel, use_na_sentinel=use_na_sentinel
)
+ if na_sentinel is lib.no_default:
+ na_sentinel = -1
+ if use_na_sentinel is lib.no_default or use_na_sentinel:
+ codes[codes == -1] = na_sentinel
uniques_sp = SparseArray(uniques, dtype=self.dtype)
return codes, uniques_sp
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index e2bc08c03ed3c..0e2df9f7cf728 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -380,8 +380,8 @@ def __arrow_array__(self, type=None):
def _values_for_factorize(self):
arr = self._ndarray.copy()
mask = self.isna()
- arr[mask] = -1
- return arr, -1
+ arr[mask] = None
+ return arr, None
def __setitem__(self, key, value):
value = extract_array(value, extract_numpy=True)
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py
index 04ebc00b8e964..72f54abdced27 100644
--- a/pandas/core/groupby/grouper.py
+++ b/pandas/core/groupby/grouper.py
@@ -658,9 +658,10 @@ def group_index(self) -> Index:
@cache_readonly
def _codes_and_uniques(self) -> tuple[npt.NDArray[np.signedinteger], ArrayLike]:
- if self._passed_categorical:
+ if self._dropna and self._passed_categorical:
# we make a CategoricalIndex out of the cat grouper
- # preserving the categories / ordered attributes
+ # preserving the categories / ordered attributes;
+ # doesn't (yet - GH#46909) handle dropna=False
cat = self.grouping_vector
categories = cat.categories
diff --git a/pandas/tests/groupby/test_groupby_dropna.py b/pandas/tests/groupby/test_groupby_dropna.py
index 515c96780e731..ee08307c95311 100644
--- a/pandas/tests/groupby/test_groupby_dropna.py
+++ b/pandas/tests/groupby/test_groupby_dropna.py
@@ -1,6 +1,8 @@
import numpy as np
import pytest
+from pandas.compat.pyarrow import pa_version_under1p01
+
import pandas as pd
import pandas._testing as tm
@@ -387,3 +389,61 @@ def test_groupby_drop_nan_with_multi_index():
result = df.groupby(["a", "b"], dropna=False).first()
expected = df
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "values, dtype",
+ [
+ ([2, np.nan, 1, 2], None),
+ ([2, np.nan, 1, 2], "UInt8"),
+ ([2, np.nan, 1, 2], "Int8"),
+ ([2, np.nan, 1, 2], "UInt16"),
+ ([2, np.nan, 1, 2], "Int16"),
+ ([2, np.nan, 1, 2], "UInt32"),
+ ([2, np.nan, 1, 2], "Int32"),
+ ([2, np.nan, 1, 2], "UInt64"),
+ ([2, np.nan, 1, 2], "Int64"),
+ ([2, np.nan, 1, 2], "Float32"),
+ ([2, np.nan, 1, 2], "Int64"),
+ ([2, np.nan, 1, 2], "Float64"),
+ (["y", None, "x", "y"], "category"),
+ (["y", pd.NA, "x", "y"], "string"),
+ pytest.param(
+ ["y", pd.NA, "x", "y"],
+ "string[pyarrow]",
+ marks=pytest.mark.skipif(
+ pa_version_under1p01, reason="pyarrow is not installed"
+ ),
+ ),
+ (
+ ["2016-01-01", np.datetime64("NaT"), "2017-01-01", "2016-01-01"],
+ "datetime64[ns]",
+ ),
+ (
+ [
+ pd.Period("2012-02-01", freq="D"),
+ pd.NA,
+ pd.Period("2012-01-01", freq="D"),
+ pd.Period("2012-02-01", freq="D"),
+ ],
+ None,
+ ),
+ (pd.arrays.SparseArray([2, np.nan, 1, 2]), None),
+ ],
+)
+@pytest.mark.parametrize("test_series", [True, False])
+def test_no_sort_keep_na(values, dtype, test_series):
+ # GH#46584
+ key = pd.Series(values, dtype=dtype)
+ df = pd.DataFrame({"key": key, "a": [1, 2, 3, 4]})
+ gb = df.groupby("key", dropna=False, sort=False)
+ if test_series:
+ gb = gb["a"]
+ result = gb.sum()
+ expected = pd.DataFrame({"a": [5, 2, 3]}, index=key[:-1].rename("key"))
+ if test_series:
+ expected = expected["a"]
+ if expected.index.is_categorical():
+ # TODO: Slicing reorders categories?
+ expected.index = expected.index.reorder_categories(["y", "x"])
+ tm.assert_equal(result, expected)
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index d2928c52c33e2..113bd4a0c4c65 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -1326,12 +1326,8 @@ def test_transform_cumcount():
@pytest.mark.parametrize("keys", [["A1"], ["A1", "A2"]])
-def test_null_group_lambda_self(request, sort, dropna, keys):
+def test_null_group_lambda_self(sort, dropna, keys):
# GH 17093
- if not sort and not dropna:
- msg = "GH#46584: null values get sorted when sort=False"
- request.node.add_marker(pytest.mark.xfail(reason=msg, strict=False))
-
size = 50
nulls1 = np.random.choice([False, True], size)
nulls2 = np.random.choice([False, True], size)
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index def63c552e059..aff48d327a11c 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -455,13 +455,13 @@ def test_factorize_na_sentinel(self, sort, na_sentinel, data, uniques):
[
(
["a", None, "b", "a"],
- np.array([0, 2, 1, 0], dtype=np.dtype("intp")),
- np.array(["a", "b", np.nan], dtype=object),
+ np.array([0, 1, 2, 0], dtype=np.dtype("intp")),
+ np.array(["a", None, "b"], dtype=object),
),
(
["a", np.nan, "b", "a"],
- np.array([0, 2, 1, 0], dtype=np.dtype("intp")),
- np.array(["a", "b", np.nan], dtype=object),
+ np.array([0, 1, 2, 0], dtype=np.dtype("intp")),
+ np.array(["a", np.nan, "b"], dtype=object),
),
],
)
@@ -478,13 +478,13 @@ def test_object_factorize_use_na_sentinel_false(
[
(
[1, None, 1, 2],
- np.array([0, 2, 0, 1], dtype=np.dtype("intp")),
- np.array([1, 2, np.nan], dtype="O"),
+ np.array([0, 1, 0, 2], dtype=np.dtype("intp")),
+ np.array([1, None, 2], dtype="O"),
),
(
[1, np.nan, 1, 2],
- np.array([0, 2, 0, 1], dtype=np.dtype("intp")),
- np.array([1, 2, np.nan], dtype=np.float64),
+ np.array([0, 1, 0, 2], dtype=np.dtype("intp")),
+ np.array([1, np.nan, 2], dtype=np.float64),
),
],
)
| - [x] closes #46584 (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 an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
In the example below, the result_index has nan moved even though sort=False. This is the order that will be in any groupby reduction result and the reason why transform currently returns wrong results.
```
df = pd.DataFrame({'a': [1, 3, np.nan, 1, 2], 'b': [3, 4, 5, 6, 7]})
print(df.groupby('a', sort=False, dropna=False).grouper.result_index)
# main
Float64Index([1.0, 3.0, 2.0, nan], dtype='float64', name='a')
# this PR
Float64Index([1.0, 3.0, nan, 2.0], dtype='float64', name='a')
```
cc @jbrockmendel @jreback | https://api.github.com/repos/pandas-dev/pandas/pulls/46601 | 2022-04-01T16:46:57Z | 2022-08-18T16:09:11Z | 2022-08-18T16:09:11Z | 2022-09-10T16:49:41Z |
CI: Simplify call to asv | diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index 16ac3cbf47705..aac6f4387a74a 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -140,22 +140,12 @@ jobs:
- name: Run ASV benchmarks
run: |
cd asv_bench
- asv check -E existing
- git remote add upstream https://github.com/pandas-dev/pandas.git
- git fetch upstream
asv machine --yes
- asv dev | sed "/failed$/ s/^/##[error]/" | tee benchmarks.log
+ # TODO add `--durations` when we start using asv >= 0.5 (#46598)
+ asv run --quick --dry-run --python=same | sed "/failed$/ s/^/##[error]/" | tee benchmarks.log
if grep "failed" benchmarks.log > /dev/null ; then
exit 1
fi
- if: ${{ steps.build.outcome == 'success' }}
-
- - name: Publish benchmarks artifact
- uses: actions/upload-artifact@v3
- with:
- name: Benchmarks log
- path: asv_bench/benchmarks.log
- if: failure()
build_docker_dev_environment:
name: Build Docker Dev Environment
diff --git a/environment.yml b/environment.yml
index 0dc9806856585..e991f29b8a727 100644
--- a/environment.yml
+++ b/environment.yml
@@ -9,7 +9,7 @@ dependencies:
- pytz
# benchmarks
- - asv < 0.5.0 # 2022-02-08: v0.5.0 > leads to ASV checks running > 3 hours on CI
+ - asv
# building
# The compiler packages are meta-packages and install the correct compiler (activation) packages on the respective platforms.
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 94709171739d2..22692da8f0ed4 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -4,7 +4,7 @@
numpy>=1.18.5
python-dateutil>=2.8.1
pytz
-asv < 0.5.0
+asv
cython>=0.29.24
black==22.3.0
cpplint
| The way we are calling `asv` in the CI is too complex for no reason. Removing the next unnecessary things:
- `asv check` not worth calling, since just imports the benchmarks which will be later imported anyway when calling `asv run`
- Adding the `remote` to git doesn't have any effect I think, since we don't specify the commit, and we should be running benchmarks for what's been checked out
- `asv machine` is not useful, since we won't save the results, or compare them with other runs
- `asv dev` just avoids creating environments, but we can speed up things a bit by just running each benchmark once, and not save the results, which are not used anyway
- The conditional to just run the benchmarks if the previous step build is successful, is the default. It makes sense in other parts of this file, since there are several steps depending on a build, but not in this case
- I don't think publishing the asv log makes a lot of sense. I think I added that myself in the past, but now feels just a waste of time and resources (unless someone used that artifact, then please let me know)
I'm going to see how to remove the hacky grep and just leave the asv call, but I think this needs a new asv release. | https://api.github.com/repos/pandas-dev/pandas/pulls/46599 | 2022-04-01T14:47:48Z | 2022-04-03T02:37:25Z | 2022-04-03T02:37:25Z | 2022-04-10T11:18:58Z |
Backport PR #46567 on branch 1.4.x (BUG: groupby().rolling(freq) with monotonic dates within groups #46065 ) | diff --git a/doc/source/whatsnew/v1.4.2.rst b/doc/source/whatsnew/v1.4.2.rst
index 76b2a5d6ffd47..66068f9faa923 100644
--- a/doc/source/whatsnew/v1.4.2.rst
+++ b/doc/source/whatsnew/v1.4.2.rst
@@ -32,6 +32,8 @@ Bug fixes
- Fix some cases for subclasses that define their ``_constructor`` properties as general callables (:issue:`46018`)
- Fixed "longtable" formatting in :meth:`.Styler.to_latex` when ``column_format`` is given in extended format (:issue:`46037`)
- Fixed incorrect rendering in :meth:`.Styler.format` with ``hyperlinks="html"`` when the url contains a colon or other special characters (:issue:`46389`)
+- Improved error message in :class:`~pandas.core.window.Rolling` when ``window`` is a frequency and ``NaT`` is in the rolling axis (:issue:`46087`)
+- Fixed :meth:`Groupby.rolling` with a frequency window that would raise a ``ValueError`` even if the datetimes within each group were monotonic (:issue:`46061`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 72ebbcbc65e5e..6d74c6db1f7ed 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -837,12 +837,6 @@ def _gotitem(self, key, ndim, subset=None):
subset = self.obj.set_index(self._on)
return super()._gotitem(key, ndim, subset=subset)
- def _validate_monotonic(self):
- """
- Validate that "on" is monotonic; already validated at a higher level.
- """
- pass
-
class Window(BaseWindow):
"""
@@ -1687,7 +1681,7 @@ def _validate(self):
or isinstance(self._on, (DatetimeIndex, TimedeltaIndex, PeriodIndex))
) and isinstance(self.window, (str, BaseOffset, timedelta)):
- self._validate_monotonic()
+ self._validate_datetimelike_monotonic()
# this will raise ValueError on non-fixed freqs
try:
@@ -1712,18 +1706,24 @@ def _validate(self):
elif not is_integer(self.window) or self.window < 0:
raise ValueError("window must be an integer 0 or greater")
- def _validate_monotonic(self):
+ def _validate_datetimelike_monotonic(self):
"""
- Validate monotonic (increasing or decreasing).
+ Validate self._on is monotonic (increasing or decreasing) and has
+ no NaT values for frequency windows.
"""
+ if self._on.hasnans:
+ self._raise_monotonic_error("values must not have NaT")
if not (self._on.is_monotonic_increasing or self._on.is_monotonic_decreasing):
- self._raise_monotonic_error()
+ self._raise_monotonic_error("values must be monotonic")
- def _raise_monotonic_error(self):
- formatted = self.on
- if self.on is None:
- formatted = "index"
- raise ValueError(f"{formatted} must be monotonic")
+ def _raise_monotonic_error(self, msg: str):
+ on = self.on
+ if on is None:
+ if self.axis == 0:
+ on = "index"
+ else:
+ on = "column"
+ raise ValueError(f"{on} {msg}")
@doc(
_shared_docs["aggregate"],
@@ -2631,12 +2631,20 @@ def _get_window_indexer(self) -> GroupbyIndexer:
)
return window_indexer
- def _validate_monotonic(self):
+ def _validate_datetimelike_monotonic(self):
"""
- Validate that on is monotonic;
+ Validate that each group in self._on is monotonic
"""
- if (
- not (self._on.is_monotonic_increasing or self._on.is_monotonic_decreasing)
- or self._on.hasnans
- ):
- self._raise_monotonic_error()
+ # GH 46061
+ if self._on.hasnans:
+ self._raise_monotonic_error("values must not have NaT")
+ for group_indices in self._grouper.indices.values():
+ group_on = self._on.take(group_indices)
+ if not (
+ group_on.is_monotonic_increasing or group_on.is_monotonic_decreasing
+ ):
+ on = "index" if self.on is None else self.on
+ raise ValueError(
+ f"Each group within {on} must be monotonic. "
+ f"Sort the values in {on} first."
+ )
diff --git a/pandas/tests/window/test_groupby.py b/pandas/tests/window/test_groupby.py
index 6ec19e4899d53..f1d84f7ae1cbf 100644
--- a/pandas/tests/window/test_groupby.py
+++ b/pandas/tests/window/test_groupby.py
@@ -651,7 +651,7 @@ def test_groupby_rolling_nans_in_index(self, rollings, key):
)
if key == "index":
df = df.set_index("a")
- with pytest.raises(ValueError, match=f"{key} must be monotonic"):
+ with pytest.raises(ValueError, match=f"{key} values must not have NaT"):
df.groupby("c").rolling("60min", **rollings)
@pytest.mark.parametrize("group_keys", [True, False])
@@ -895,6 +895,83 @@ def test_nan_and_zero_endpoints(self):
)
tm.assert_series_equal(result, expected)
+ def test_groupby_rolling_non_monotonic(self):
+ # GH 43909
+
+ shuffled = [3, 0, 1, 2]
+ sec = 1_000
+ df = DataFrame(
+ [{"t": Timestamp(2 * x * sec), "x": x + 1, "c": 42} for x in shuffled]
+ )
+ with pytest.raises(ValueError, match=r".* must be monotonic"):
+ df.groupby("c").rolling(on="t", window="3s")
+
+ def test_groupby_monotonic(self):
+
+ # GH 15130
+ # we don't need to validate monotonicity when grouping
+
+ # GH 43909 we should raise an error here to match
+ # behaviour of non-groupby rolling.
+
+ data = [
+ ["David", "1/1/2015", 100],
+ ["David", "1/5/2015", 500],
+ ["David", "5/30/2015", 50],
+ ["David", "7/25/2015", 50],
+ ["Ryan", "1/4/2014", 100],
+ ["Ryan", "1/19/2015", 500],
+ ["Ryan", "3/31/2016", 50],
+ ["Joe", "7/1/2015", 100],
+ ["Joe", "9/9/2015", 500],
+ ["Joe", "10/15/2015", 50],
+ ]
+
+ df = DataFrame(data=data, columns=["name", "date", "amount"])
+ df["date"] = to_datetime(df["date"])
+ df = df.sort_values("date")
+
+ expected = (
+ df.set_index("date")
+ .groupby("name")
+ .apply(lambda x: x.rolling("180D")["amount"].sum())
+ )
+ result = df.groupby("name").rolling("180D", on="date")["amount"].sum()
+ tm.assert_series_equal(result, expected)
+
+ def test_datelike_on_monotonic_within_each_group(self):
+ # GH 13966 (similar to #15130, closed by #15175)
+
+ # superseded by 43909
+ # GH 46061: OK if the on is monotonic relative to each each group
+
+ dates = date_range(start="2016-01-01 09:30:00", periods=20, freq="s")
+ df = DataFrame(
+ {
+ "A": [1] * 20 + [2] * 12 + [3] * 8,
+ "B": np.concatenate((dates, dates)),
+ "C": np.arange(40),
+ }
+ )
+
+ expected = (
+ df.set_index("B").groupby("A").apply(lambda x: x.rolling("4s")["C"].mean())
+ )
+ result = df.groupby("A").rolling("4s", on="B").C.mean()
+ tm.assert_series_equal(result, expected)
+
+ def test_datelike_on_not_monotonic_within_each_group(self):
+ # GH 46061
+ df = DataFrame(
+ {
+ "A": [1] * 3 + [2] * 3,
+ "B": [Timestamp(year, 1, 1) for year in [2020, 2021, 2019]] * 2,
+ "C": range(6),
+ }
+ )
+ with pytest.raises(ValueError, match="Each group within B must be monotonic."):
+ df.groupby("A").rolling("365D", on="B")
+
class TestExpanding:
def setup_method(self):
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index 814bd6b998182..b60f2e60e1035 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -1419,18 +1419,6 @@ def test_groupby_rolling_nan_included():
tm.assert_frame_equal(result, expected)
-def test_groupby_rolling_non_monotonic():
- # GH 43909
-
- shuffled = [3, 0, 1, 2]
- sec = 1_000
- df = DataFrame(
- [{"t": Timestamp(2 * x * sec), "x": x + 1, "c": 42} for x in shuffled]
- )
- with pytest.raises(ValueError, match=r".* must be monotonic"):
- df.groupby("c").rolling(on="t", window="3s")
-
-
@pytest.mark.parametrize("method", ["skew", "kurt"])
def test_rolling_skew_kurt_numerical_stability(method):
# GH#6929
diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py
index f2cf7bd47e15b..274c986ac28f5 100644
--- a/pandas/tests/window/test_timeseries_window.py
+++ b/pandas/tests/window/test_timeseries_window.py
@@ -5,10 +5,10 @@
DataFrame,
Index,
MultiIndex,
+ NaT,
Series,
Timestamp,
date_range,
- to_datetime,
)
import pandas._testing as tm
@@ -134,7 +134,7 @@ def test_non_monotonic_on(self):
assert not df.index.is_monotonic
- msg = "index must be monotonic"
+ msg = "index values must be monotonic"
with pytest.raises(ValueError, match=msg):
df.rolling("2s").sum()
@@ -643,65 +643,6 @@ def agg_by_day(x):
tm.assert_frame_equal(result, expected)
- def test_groupby_monotonic(self):
-
- # GH 15130
- # we don't need to validate monotonicity when grouping
-
- # GH 43909 we should raise an error here to match
- # behaviour of non-groupby rolling.
-
- data = [
- ["David", "1/1/2015", 100],
- ["David", "1/5/2015", 500],
- ["David", "5/30/2015", 50],
- ["David", "7/25/2015", 50],
- ["Ryan", "1/4/2014", 100],
- ["Ryan", "1/19/2015", 500],
- ["Ryan", "3/31/2016", 50],
- ["Joe", "7/1/2015", 100],
- ["Joe", "9/9/2015", 500],
- ["Joe", "10/15/2015", 50],
- ]
-
- df = DataFrame(data=data, columns=["name", "date", "amount"])
- df["date"] = to_datetime(df["date"])
- df = df.sort_values("date")
-
- expected = (
- df.set_index("date")
- .groupby("name")
- .apply(lambda x: x.rolling("180D")["amount"].sum())
- )
- result = df.groupby("name").rolling("180D", on="date")["amount"].sum()
- tm.assert_series_equal(result, expected)
-
- def test_non_monotonic_raises(self):
- # GH 13966 (similar to #15130, closed by #15175)
-
- # superseded by 43909
-
- dates = date_range(start="2016-01-01 09:30:00", periods=20, freq="s")
- df = DataFrame(
- {
- "A": [1] * 20 + [2] * 12 + [3] * 8,
- "B": np.concatenate((dates, dates)),
- "C": np.arange(40),
- }
- )
-
- expected = (
- df.set_index("B").groupby("A").apply(lambda x: x.rolling("4s")["C"].mean())
- )
- with pytest.raises(ValueError, match=r".* must be monotonic"):
- df.groupby("A").rolling(
- "4s", on="B"
- ).C.mean() # should raise for non-monotonic t series
-
- df2 = df.sort_values("B")
- result = df2.groupby("A").rolling("4s", on="B").C.mean()
- tm.assert_series_equal(result, expected)
-
def test_rolling_cov_offset(self):
# GH16058
@@ -757,3 +698,12 @@ def test_rolling_on_multi_index_level(self):
{"column": [0.0, 1.0, 3.0, 6.0, 10.0, 15.0]}, index=df.index
)
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("msg, axis", [["column", 1], ["index", 0]])
+def test_nat_axis_error(msg, axis):
+ idx = [Timestamp("2020"), NaT]
+ kwargs = {"columns" if axis == 1 else "index": idx}
+ df = DataFrame(np.eye(2), **kwargs)
+ with pytest.raises(ValueError, match=f"{msg} values must not have NaT"):
+ df.rolling("D", axis=axis).mean()
| Backport PRs #46567, #46087
@mroeschke marked as draft as this PR also backports #46087 (which conflicts that caused the autobackport to fail)
The only conflict doing this was the release note in 1.5 (which would need a separate PR to move on main) (side note: why was the release note for #46567 in bug fix section and not regression?)
#46087 is labelled as an enhancement but could also be considered a bugfix? Although saying that, I think we generally don't consider changes to error message to be API changes (only changes to exception type)?
wdyt about backporting #46087? No pressure, but if you prefer not to, I will leave it to you to do the manual backport ! (you are more familiar with this code so less likely to make a mistake) | https://api.github.com/repos/pandas-dev/pandas/pulls/46592 | 2022-04-01T09:34:19Z | 2022-04-01T17:42:19Z | 2022-04-01T17:42:19Z | 2022-04-01T17:42:23Z |
REF: Create pandas/core/arrays/arrow | diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index eb0ebd8d08340..4563759c63a36 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -28,11 +28,6 @@
npt,
type_t,
)
-from pandas.compat import (
- pa_version_under1p01,
- pa_version_under2p0,
- pa_version_under5p0,
-)
from pandas.errors import AbstractMethodError
from pandas.util._decorators import doc
from pandas.util._validators import (
@@ -42,11 +37,7 @@
)
from pandas.core.dtypes.common import (
- is_array_like,
- is_bool_dtype,
is_dtype_equal,
- is_integer,
- is_scalar,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import (
@@ -54,10 +45,7 @@
ExtensionDtype,
PeriodDtype,
)
-from pandas.core.dtypes.missing import (
- array_equivalent,
- isna,
-)
+from pandas.core.dtypes.missing import array_equivalent
from pandas.core import missing
from pandas.core.algorithms import (
@@ -69,28 +57,19 @@
from pandas.core.array_algos.transforms import shift
from pandas.core.arrays.base import ExtensionArray
from pandas.core.construction import extract_array
-from pandas.core.indexers import (
- check_array_indexer,
- validate_indices,
-)
+from pandas.core.indexers import check_array_indexer
from pandas.core.sorting import nargminmax
NDArrayBackedExtensionArrayT = TypeVar(
"NDArrayBackedExtensionArrayT", bound="NDArrayBackedExtensionArray"
)
-if not pa_version_under1p01:
- import pyarrow as pa
- import pyarrow.compute as pc
-
if TYPE_CHECKING:
from pandas._typing import (
NumpySorter,
NumpyValueArrayLike,
)
- from pandas import Series
-
def ravel_compat(meth: F) -> F:
"""
@@ -538,402 +517,3 @@ def _empty(
arr = cls._from_sequence([], dtype=dtype)
backing = np.empty(shape, dtype=arr._ndarray.dtype)
return arr._from_backing_data(backing)
-
-
-ArrowExtensionArrayT = TypeVar("ArrowExtensionArrayT", bound="ArrowExtensionArray")
-
-
-class ArrowExtensionArray(ExtensionArray):
- """
- Base class for ExtensionArray backed by Arrow array.
- """
-
- _data: pa.ChunkedArray
-
- def __init__(self, values: pa.ChunkedArray) -> None:
- self._data = values
-
- def __arrow_array__(self, type=None):
- """Convert myself to a pyarrow Array or ChunkedArray."""
- return self._data
-
- def equals(self, other) -> bool:
- if not isinstance(other, ArrowExtensionArray):
- return False
- # I'm told that pyarrow makes __eq__ behave like pandas' equals;
- # TODO: is this documented somewhere?
- return self._data == other._data
-
- @property
- def nbytes(self) -> int:
- """
- The number of bytes needed to store this object in memory.
- """
- return self._data.nbytes
-
- def __len__(self) -> int:
- """
- Length of this array.
-
- Returns
- -------
- length : int
- """
- return len(self._data)
-
- def isna(self) -> npt.NDArray[np.bool_]:
- """
- Boolean NumPy array indicating if each value is missing.
-
- This should return a 1-D array the same length as 'self'.
- """
- if pa_version_under2p0:
- return self._data.is_null().to_pandas().values
- else:
- return self._data.is_null().to_numpy()
-
- def copy(self: ArrowExtensionArrayT) -> ArrowExtensionArrayT:
- """
- Return a shallow copy of the array.
-
- Underlying ChunkedArray is immutable, so a deep copy is unnecessary.
-
- Returns
- -------
- type(self)
- """
- return type(self)(self._data)
-
- @doc(ExtensionArray.factorize)
- def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]:
- encoded = self._data.dictionary_encode()
- indices = pa.chunked_array(
- [c.indices for c in encoded.chunks], type=encoded.type.index_type
- ).to_pandas()
- if indices.dtype.kind == "f":
- indices[np.isnan(indices)] = na_sentinel
- indices = indices.astype(np.int64, copy=False)
-
- if encoded.num_chunks:
- uniques = type(self)(encoded.chunk(0).dictionary)
- else:
- uniques = type(self)(pa.array([], type=encoded.type.value_type))
-
- return indices.values, uniques
-
- def take(
- self,
- indices: TakeIndexer,
- allow_fill: bool = False,
- fill_value: Any = None,
- ):
- """
- Take elements from an array.
-
- Parameters
- ----------
- indices : sequence of int or one-dimensional np.ndarray of int
- Indices to be taken.
- allow_fill : bool, default False
- How to handle negative values in `indices`.
-
- * False: negative values in `indices` indicate positional indices
- from the right (the default). This is similar to
- :func:`numpy.take`.
-
- * True: negative values in `indices` indicate
- missing values. These values are set to `fill_value`. Any other
- other negative values raise a ``ValueError``.
-
- fill_value : any, optional
- Fill value to use for NA-indices when `allow_fill` is True.
- This may be ``None``, in which case the default NA value for
- the type, ``self.dtype.na_value``, is used.
-
- For many ExtensionArrays, there will be two representations of
- `fill_value`: a user-facing "boxed" scalar, and a low-level
- physical NA value. `fill_value` should be the user-facing version,
- and the implementation should handle translating that to the
- physical version for processing the take if necessary.
-
- Returns
- -------
- ExtensionArray
-
- Raises
- ------
- IndexError
- When the indices are out of bounds for the array.
- ValueError
- When `indices` contains negative values other than ``-1``
- and `allow_fill` is True.
-
- See Also
- --------
- numpy.take
- api.extensions.take
-
- Notes
- -----
- ExtensionArray.take is called by ``Series.__getitem__``, ``.loc``,
- ``iloc``, when `indices` is a sequence of values. Additionally,
- it's called by :meth:`Series.reindex`, or any other method
- that causes realignment, with a `fill_value`.
- """
- # TODO: Remove once we got rid of the (indices < 0) check
- if not is_array_like(indices):
- indices_array = np.asanyarray(indices)
- else:
- # error: Incompatible types in assignment (expression has type
- # "Sequence[int]", variable has type "ndarray")
- indices_array = indices # type: ignore[assignment]
-
- if len(self._data) == 0 and (indices_array >= 0).any():
- raise IndexError("cannot do a non-empty take")
- if indices_array.size > 0 and indices_array.max() >= len(self._data):
- raise IndexError("out of bounds value in 'indices'.")
-
- if allow_fill:
- fill_mask = indices_array < 0
- if fill_mask.any():
- validate_indices(indices_array, len(self._data))
- # TODO(ARROW-9433): Treat negative indices as NULL
- indices_array = pa.array(indices_array, mask=fill_mask)
- result = self._data.take(indices_array)
- if isna(fill_value):
- return type(self)(result)
- # TODO: ArrowNotImplementedError: Function fill_null has no
- # kernel matching input types (array[string], scalar[string])
- result = type(self)(result)
- result[fill_mask] = fill_value
- return result
- # return type(self)(pc.fill_null(result, pa.scalar(fill_value)))
- else:
- # Nothing to fill
- return type(self)(self._data.take(indices))
- else: # allow_fill=False
- # TODO(ARROW-9432): Treat negative indices as indices from the right.
- if (indices_array < 0).any():
- # Don't modify in-place
- indices_array = np.copy(indices_array)
- indices_array[indices_array < 0] += len(self._data)
- return type(self)(self._data.take(indices_array))
-
- def value_counts(self, dropna: bool = True) -> Series:
- """
- Return a Series containing counts of each unique value.
-
- Parameters
- ----------
- dropna : bool, default True
- Don't include counts of missing values.
-
- Returns
- -------
- counts : Series
-
- See Also
- --------
- Series.value_counts
- """
- from pandas import (
- Index,
- Series,
- )
-
- vc = self._data.value_counts()
-
- values = vc.field(0)
- counts = vc.field(1)
- if dropna and self._data.null_count > 0:
- mask = values.is_valid()
- values = values.filter(mask)
- counts = counts.filter(mask)
-
- # No missing values so we can adhere to the interface and return a numpy array.
- counts = np.array(counts)
-
- index = Index(type(self)(values))
-
- return Series(counts, index=index).astype("Int64")
-
- @classmethod
- def _concat_same_type(
- cls: type[ArrowExtensionArrayT], to_concat
- ) -> ArrowExtensionArrayT:
- """
- Concatenate multiple ArrowExtensionArrays.
-
- Parameters
- ----------
- to_concat : sequence of ArrowExtensionArrays
-
- Returns
- -------
- ArrowExtensionArray
- """
- import pyarrow as pa
-
- chunks = [array for ea in to_concat for array in ea._data.iterchunks()]
- arr = pa.chunked_array(chunks)
- return cls(arr)
-
- def __setitem__(self, key: int | slice | np.ndarray, value: Any) -> None:
- """Set one or more values inplace.
-
- Parameters
- ----------
- key : int, ndarray, or slice
- When called from, e.g. ``Series.__setitem__``, ``key`` will be
- one of
-
- * scalar int
- * ndarray of integers.
- * boolean ndarray
- * slice object
-
- value : ExtensionDtype.type, Sequence[ExtensionDtype.type], or object
- value or values to be set of ``key``.
-
- Returns
- -------
- None
- """
- key = check_array_indexer(self, key)
- indices = self._indexing_key_to_indices(key)
- value = self._maybe_convert_setitem_value(value)
-
- argsort = np.argsort(indices)
- indices = indices[argsort]
-
- if is_scalar(value):
- value = np.broadcast_to(value, len(self))
- elif len(indices) != len(value):
- raise ValueError("Length of indexer and values mismatch")
- else:
- value = np.asarray(value)[argsort]
-
- self._data = self._set_via_chunk_iteration(indices=indices, value=value)
-
- def _indexing_key_to_indices(
- self, key: int | slice | np.ndarray
- ) -> npt.NDArray[np.intp]:
- """
- Convert indexing key for self into positional indices.
-
- Parameters
- ----------
- key : int | slice | np.ndarray
-
- Returns
- -------
- npt.NDArray[np.intp]
- """
- n = len(self)
- if isinstance(key, slice):
- indices = np.arange(n)[key]
- elif is_integer(key):
- indices = np.arange(n)[[key]] # type: ignore[index]
- elif is_bool_dtype(key):
- key = np.asarray(key)
- if len(key) != n:
- raise ValueError("Length of indexer and values mismatch")
- indices = key.nonzero()[0]
- else:
- key = np.asarray(key)
- indices = np.arange(n)[key]
- return indices
-
- def _maybe_convert_setitem_value(self, value):
- """Maybe convert value to be pyarrow compatible."""
- raise NotImplementedError()
-
- def _set_via_chunk_iteration(
- self, indices: npt.NDArray[np.intp], value: npt.NDArray[Any]
- ) -> pa.ChunkedArray:
- """
- Loop through the array chunks and set the new values while
- leaving the chunking layout unchanged.
-
- Parameters
- ----------
- indices : npt.NDArray[np.intp]
- Position indices for the underlying ChunkedArray.
-
- value : ExtensionDtype.type, Sequence[ExtensionDtype.type], or object
- value or values to be set of ``key``.
-
- Notes
- -----
- Assumes that indices is sorted. Caller is responsible for sorting.
- """
- new_data = []
- stop = 0
- for chunk in self._data.iterchunks():
- start, stop = stop, stop + len(chunk)
- if len(indices) == 0 or stop <= indices[0]:
- new_data.append(chunk)
- else:
- n = int(np.searchsorted(indices, stop, side="left"))
- c_ind = indices[:n] - start
- indices = indices[n:]
- n = len(c_ind)
- c_value, value = value[:n], value[n:]
- new_data.append(self._replace_with_indices(chunk, c_ind, c_value))
- return pa.chunked_array(new_data)
-
- @classmethod
- def _replace_with_indices(
- cls,
- chunk: pa.Array,
- indices: npt.NDArray[np.intp],
- value: npt.NDArray[Any],
- ) -> pa.Array:
- """
- Replace items selected with a set of positional indices.
-
- Analogous to pyarrow.compute.replace_with_mask, except that replacement
- positions are identified via indices rather than a mask.
-
- Parameters
- ----------
- chunk : pa.Array
- indices : npt.NDArray[np.intp]
- value : npt.NDArray[Any]
- Replacement value(s).
-
- Returns
- -------
- pa.Array
- """
- n = len(indices)
-
- if n == 0:
- return chunk
-
- start, stop = indices[[0, -1]]
-
- if (stop - start) == (n - 1):
- # fast path for a contiguous set of indices
- arrays = [
- chunk[:start],
- pa.array(value, type=chunk.type),
- chunk[stop + 1 :],
- ]
- arrays = [arr for arr in arrays if len(arr)]
- if len(arrays) == 1:
- return arrays[0]
- return pa.concat_arrays(arrays)
-
- mask = np.zeros(len(chunk), dtype=np.bool_)
- mask[indices] = True
-
- if pa_version_under5p0:
- arr = chunk.to_numpy(zero_copy_only=False)
- arr[mask] = value
- return pa.array(arr, type=chunk.type)
-
- if isna(value).all():
- return pc.if_else(mask, None, chunk)
-
- return pc.replace_with_mask(chunk, mask, value)
diff --git a/pandas/core/arrays/arrow/__init__.py b/pandas/core/arrays/arrow/__init__.py
new file mode 100644
index 0000000000000..6bdf29e38ac62
--- /dev/null
+++ b/pandas/core/arrays/arrow/__init__.py
@@ -0,0 +1,3 @@
+# flake8: noqa: F401
+
+from pandas.core.arrays.arrow.array import ArrowExtensionArray
diff --git a/pandas/core/arrays/_arrow_utils.py b/pandas/core/arrays/arrow/_arrow_utils.py
similarity index 100%
rename from pandas/core/arrays/_arrow_utils.py
rename to pandas/core/arrays/arrow/_arrow_utils.py
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py
new file mode 100644
index 0000000000000..0a48638f5cf05
--- /dev/null
+++ b/pandas/core/arrays/arrow/array.py
@@ -0,0 +1,439 @@
+from __future__ import annotations
+
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ TypeVar,
+)
+
+import numpy as np
+
+from pandas._typing import (
+ TakeIndexer,
+ npt,
+)
+from pandas.compat import (
+ pa_version_under1p01,
+ pa_version_under2p0,
+ pa_version_under5p0,
+)
+from pandas.util._decorators import doc
+
+from pandas.core.dtypes.common import (
+ is_array_like,
+ is_bool_dtype,
+ is_integer,
+ is_scalar,
+)
+from pandas.core.dtypes.missing import isna
+
+from pandas.core.arrays.base import ExtensionArray
+from pandas.core.indexers import (
+ check_array_indexer,
+ validate_indices,
+)
+
+if not pa_version_under1p01:
+ import pyarrow as pa
+ import pyarrow.compute as pc
+
+if TYPE_CHECKING:
+ from pandas import Series
+
+ArrowExtensionArrayT = TypeVar("ArrowExtensionArrayT", bound="ArrowExtensionArray")
+
+
+class ArrowExtensionArray(ExtensionArray):
+ """
+ Base class for ExtensionArray backed by Arrow array.
+ """
+
+ _data: pa.ChunkedArray
+
+ def __init__(self, values: pa.ChunkedArray) -> None:
+ self._data = values
+
+ def __arrow_array__(self, type=None):
+ """Convert myself to a pyarrow Array or ChunkedArray."""
+ return self._data
+
+ def equals(self, other) -> bool:
+ if not isinstance(other, ArrowExtensionArray):
+ return False
+ # I'm told that pyarrow makes __eq__ behave like pandas' equals;
+ # TODO: is this documented somewhere?
+ return self._data == other._data
+
+ @property
+ def nbytes(self) -> int:
+ """
+ The number of bytes needed to store this object in memory.
+ """
+ return self._data.nbytes
+
+ def __len__(self) -> int:
+ """
+ Length of this array.
+
+ Returns
+ -------
+ length : int
+ """
+ return len(self._data)
+
+ def isna(self) -> npt.NDArray[np.bool_]:
+ """
+ Boolean NumPy array indicating if each value is missing.
+
+ This should return a 1-D array the same length as 'self'.
+ """
+ if pa_version_under2p0:
+ return self._data.is_null().to_pandas().values
+ else:
+ return self._data.is_null().to_numpy()
+
+ def copy(self: ArrowExtensionArrayT) -> ArrowExtensionArrayT:
+ """
+ Return a shallow copy of the array.
+
+ Underlying ChunkedArray is immutable, so a deep copy is unnecessary.
+
+ Returns
+ -------
+ type(self)
+ """
+ return type(self)(self._data)
+
+ @doc(ExtensionArray.factorize)
+ def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]:
+ encoded = self._data.dictionary_encode()
+ indices = pa.chunked_array(
+ [c.indices for c in encoded.chunks], type=encoded.type.index_type
+ ).to_pandas()
+ if indices.dtype.kind == "f":
+ indices[np.isnan(indices)] = na_sentinel
+ indices = indices.astype(np.int64, copy=False)
+
+ if encoded.num_chunks:
+ uniques = type(self)(encoded.chunk(0).dictionary)
+ else:
+ uniques = type(self)(pa.array([], type=encoded.type.value_type))
+
+ return indices.values, uniques
+
+ def take(
+ self,
+ indices: TakeIndexer,
+ allow_fill: bool = False,
+ fill_value: Any = None,
+ ):
+ """
+ Take elements from an array.
+
+ Parameters
+ ----------
+ indices : sequence of int or one-dimensional np.ndarray of int
+ Indices to be taken.
+ allow_fill : bool, default False
+ How to handle negative values in `indices`.
+
+ * False: negative values in `indices` indicate positional indices
+ from the right (the default). This is similar to
+ :func:`numpy.take`.
+
+ * True: negative values in `indices` indicate
+ missing values. These values are set to `fill_value`. Any other
+ other negative values raise a ``ValueError``.
+
+ fill_value : any, optional
+ Fill value to use for NA-indices when `allow_fill` is True.
+ This may be ``None``, in which case the default NA value for
+ the type, ``self.dtype.na_value``, is used.
+
+ For many ExtensionArrays, there will be two representations of
+ `fill_value`: a user-facing "boxed" scalar, and a low-level
+ physical NA value. `fill_value` should be the user-facing version,
+ and the implementation should handle translating that to the
+ physical version for processing the take if necessary.
+
+ Returns
+ -------
+ ExtensionArray
+
+ Raises
+ ------
+ IndexError
+ When the indices are out of bounds for the array.
+ ValueError
+ When `indices` contains negative values other than ``-1``
+ and `allow_fill` is True.
+
+ See Also
+ --------
+ numpy.take
+ api.extensions.take
+
+ Notes
+ -----
+ ExtensionArray.take is called by ``Series.__getitem__``, ``.loc``,
+ ``iloc``, when `indices` is a sequence of values. Additionally,
+ it's called by :meth:`Series.reindex`, or any other method
+ that causes realignment, with a `fill_value`.
+ """
+ # TODO: Remove once we got rid of the (indices < 0) check
+ if not is_array_like(indices):
+ indices_array = np.asanyarray(indices)
+ else:
+ # error: Incompatible types in assignment (expression has type
+ # "Sequence[int]", variable has type "ndarray")
+ indices_array = indices # type: ignore[assignment]
+
+ if len(self._data) == 0 and (indices_array >= 0).any():
+ raise IndexError("cannot do a non-empty take")
+ if indices_array.size > 0 and indices_array.max() >= len(self._data):
+ raise IndexError("out of bounds value in 'indices'.")
+
+ if allow_fill:
+ fill_mask = indices_array < 0
+ if fill_mask.any():
+ validate_indices(indices_array, len(self._data))
+ # TODO(ARROW-9433): Treat negative indices as NULL
+ indices_array = pa.array(indices_array, mask=fill_mask)
+ result = self._data.take(indices_array)
+ if isna(fill_value):
+ return type(self)(result)
+ # TODO: ArrowNotImplementedError: Function fill_null has no
+ # kernel matching input types (array[string], scalar[string])
+ result = type(self)(result)
+ result[fill_mask] = fill_value
+ return result
+ # return type(self)(pc.fill_null(result, pa.scalar(fill_value)))
+ else:
+ # Nothing to fill
+ return type(self)(self._data.take(indices))
+ else: # allow_fill=False
+ # TODO(ARROW-9432): Treat negative indices as indices from the right.
+ if (indices_array < 0).any():
+ # Don't modify in-place
+ indices_array = np.copy(indices_array)
+ indices_array[indices_array < 0] += len(self._data)
+ return type(self)(self._data.take(indices_array))
+
+ def value_counts(self, dropna: bool = True) -> Series:
+ """
+ Return a Series containing counts of each unique value.
+
+ Parameters
+ ----------
+ dropna : bool, default True
+ Don't include counts of missing values.
+
+ Returns
+ -------
+ counts : Series
+
+ See Also
+ --------
+ Series.value_counts
+ """
+ from pandas import (
+ Index,
+ Series,
+ )
+
+ vc = self._data.value_counts()
+
+ values = vc.field(0)
+ counts = vc.field(1)
+ if dropna and self._data.null_count > 0:
+ mask = values.is_valid()
+ values = values.filter(mask)
+ counts = counts.filter(mask)
+
+ # No missing values so we can adhere to the interface and return a numpy array.
+ counts = np.array(counts)
+
+ index = Index(type(self)(values))
+
+ return Series(counts, index=index).astype("Int64")
+
+ @classmethod
+ def _concat_same_type(
+ cls: type[ArrowExtensionArrayT], to_concat
+ ) -> ArrowExtensionArrayT:
+ """
+ Concatenate multiple ArrowExtensionArrays.
+
+ Parameters
+ ----------
+ to_concat : sequence of ArrowExtensionArrays
+
+ Returns
+ -------
+ ArrowExtensionArray
+ """
+ import pyarrow as pa
+
+ chunks = [array for ea in to_concat for array in ea._data.iterchunks()]
+ arr = pa.chunked_array(chunks)
+ return cls(arr)
+
+ def __setitem__(self, key: int | slice | np.ndarray, value: Any) -> None:
+ """Set one or more values inplace.
+
+ Parameters
+ ----------
+ key : int, ndarray, or slice
+ When called from, e.g. ``Series.__setitem__``, ``key`` will be
+ one of
+
+ * scalar int
+ * ndarray of integers.
+ * boolean ndarray
+ * slice object
+
+ value : ExtensionDtype.type, Sequence[ExtensionDtype.type], or object
+ value or values to be set of ``key``.
+
+ Returns
+ -------
+ None
+ """
+ key = check_array_indexer(self, key)
+ indices = self._indexing_key_to_indices(key)
+ value = self._maybe_convert_setitem_value(value)
+
+ argsort = np.argsort(indices)
+ indices = indices[argsort]
+
+ if is_scalar(value):
+ value = np.broadcast_to(value, len(self))
+ elif len(indices) != len(value):
+ raise ValueError("Length of indexer and values mismatch")
+ else:
+ value = np.asarray(value)[argsort]
+
+ self._data = self._set_via_chunk_iteration(indices=indices, value=value)
+
+ def _indexing_key_to_indices(
+ self, key: int | slice | np.ndarray
+ ) -> npt.NDArray[np.intp]:
+ """
+ Convert indexing key for self into positional indices.
+
+ Parameters
+ ----------
+ key : int | slice | np.ndarray
+
+ Returns
+ -------
+ npt.NDArray[np.intp]
+ """
+ n = len(self)
+ if isinstance(key, slice):
+ indices = np.arange(n)[key]
+ elif is_integer(key):
+ indices = np.arange(n)[[key]] # type: ignore[index]
+ elif is_bool_dtype(key):
+ key = np.asarray(key)
+ if len(key) != n:
+ raise ValueError("Length of indexer and values mismatch")
+ indices = key.nonzero()[0]
+ else:
+ key = np.asarray(key)
+ indices = np.arange(n)[key]
+ return indices
+
+ def _maybe_convert_setitem_value(self, value):
+ """Maybe convert value to be pyarrow compatible."""
+ raise NotImplementedError()
+
+ def _set_via_chunk_iteration(
+ self, indices: npt.NDArray[np.intp], value: npt.NDArray[Any]
+ ) -> pa.ChunkedArray:
+ """
+ Loop through the array chunks and set the new values while
+ leaving the chunking layout unchanged.
+
+ Parameters
+ ----------
+ indices : npt.NDArray[np.intp]
+ Position indices for the underlying ChunkedArray.
+
+ value : ExtensionDtype.type, Sequence[ExtensionDtype.type], or object
+ value or values to be set of ``key``.
+
+ Notes
+ -----
+ Assumes that indices is sorted. Caller is responsible for sorting.
+ """
+ new_data = []
+ stop = 0
+ for chunk in self._data.iterchunks():
+ start, stop = stop, stop + len(chunk)
+ if len(indices) == 0 or stop <= indices[0]:
+ new_data.append(chunk)
+ else:
+ n = int(np.searchsorted(indices, stop, side="left"))
+ c_ind = indices[:n] - start
+ indices = indices[n:]
+ n = len(c_ind)
+ c_value, value = value[:n], value[n:]
+ new_data.append(self._replace_with_indices(chunk, c_ind, c_value))
+ return pa.chunked_array(new_data)
+
+ @classmethod
+ def _replace_with_indices(
+ cls,
+ chunk: pa.Array,
+ indices: npt.NDArray[np.intp],
+ value: npt.NDArray[Any],
+ ) -> pa.Array:
+ """
+ Replace items selected with a set of positional indices.
+
+ Analogous to pyarrow.compute.replace_with_mask, except that replacement
+ positions are identified via indices rather than a mask.
+
+ Parameters
+ ----------
+ chunk : pa.Array
+ indices : npt.NDArray[np.intp]
+ value : npt.NDArray[Any]
+ Replacement value(s).
+
+ Returns
+ -------
+ pa.Array
+ """
+ n = len(indices)
+
+ if n == 0:
+ return chunk
+
+ start, stop = indices[[0, -1]]
+
+ if (stop - start) == (n - 1):
+ # fast path for a contiguous set of indices
+ arrays = [
+ chunk[:start],
+ pa.array(value, type=chunk.type),
+ chunk[stop + 1 :],
+ ]
+ arrays = [arr for arr in arrays if len(arr)]
+ if len(arrays) == 1:
+ return arrays[0]
+ return pa.concat_arrays(arrays)
+
+ mask = np.zeros(len(chunk), dtype=np.bool_)
+ mask[indices] = True
+
+ if pa_version_under5p0:
+ arr = chunk.to_numpy(zero_copy_only=False)
+ arr[mask] = value
+ return pa.array(arr, type=chunk.type)
+
+ if isna(value).all():
+ return pc.if_else(mask, None, chunk)
+
+ return pc.replace_with_mask(chunk, mask, value)
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index e14eec419377c..679feaca71024 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -1445,7 +1445,7 @@ def __arrow_array__(self, type=None):
"""
import pyarrow
- from pandas.core.arrays._arrow_utils import ArrowIntervalType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType
try:
subtype = pyarrow.from_numpy_dtype(self.dtype.subtype)
diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py
index 98d43db9904c8..cdffd57df9a84 100644
--- a/pandas/core/arrays/numeric.py
+++ b/pandas/core/arrays/numeric.py
@@ -70,7 +70,9 @@ def __from_arrow__(
"""
import pyarrow
- from pandas.core.arrays._arrow_utils import pyarrow_array_to_numpy_and_mask
+ from pandas.core.arrays.arrow._arrow_utils import (
+ pyarrow_array_to_numpy_and_mask,
+ )
array_class = self.construct_array_type()
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 7d0b30a1abb60..065e597537be9 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -366,7 +366,7 @@ def __arrow_array__(self, type=None):
"""
import pyarrow
- from pandas.core.arrays._arrow_utils import ArrowPeriodType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType
if type is not None:
if pyarrow.types.is_integer(type):
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 154c143ac89df..b8136402b00e6 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -42,7 +42,7 @@
from pandas.core.dtypes.missing import isna
from pandas.core.arraylike import OpsMixin
-from pandas.core.arrays._mixins import ArrowExtensionArray
+from pandas.core.arrays.arrow import ArrowExtensionArray
from pandas.core.arrays.boolean import BooleanDtype
from pandas.core.arrays.integer import Int64Dtype
from pandas.core.arrays.numeric import NumericDtype
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index 66eed0a75fa19..58e91f46dff43 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -997,7 +997,9 @@ def __from_arrow__(
import pyarrow
from pandas.core.arrays import PeriodArray
- from pandas.core.arrays._arrow_utils import pyarrow_array_to_numpy_and_mask
+ from pandas.core.arrays.arrow._arrow_utils import (
+ pyarrow_array_to_numpy_and_mask,
+ )
if isinstance(array, pyarrow.Array):
chunks = [array]
diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py
index 27b0b3d08ad53..cbf3bcc9278d5 100644
--- a/pandas/io/parquet.py
+++ b/pandas/io/parquet.py
@@ -151,7 +151,7 @@ def __init__(self) -> None:
import pyarrow.parquet
# import utils to register the pyarrow extension types
- import pandas.core.arrays._arrow_utils # noqa:F401
+ import pandas.core.arrays.arrow._arrow_utils # noqa:F401
self.api = pyarrow
diff --git a/pandas/tests/arrays/interval/test_interval.py b/pandas/tests/arrays/interval/test_interval.py
index 2b5712e76e8cc..eaf86f5d521ae 100644
--- a/pandas/tests/arrays/interval/test_interval.py
+++ b/pandas/tests/arrays/interval/test_interval.py
@@ -248,7 +248,7 @@ def test_min_max(self, left_right_dtypes, index_or_series_or_array):
def test_arrow_extension_type():
import pyarrow as pa
- from pandas.core.arrays._arrow_utils import ArrowIntervalType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType
p1 = ArrowIntervalType(pa.int64(), "left")
p2 = ArrowIntervalType(pa.int64(), "left")
@@ -265,7 +265,7 @@ def test_arrow_extension_type():
def test_arrow_array():
import pyarrow as pa
- from pandas.core.arrays._arrow_utils import ArrowIntervalType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType
intervals = pd.interval_range(1, 5, freq=1).array
@@ -295,7 +295,7 @@ def test_arrow_array():
def test_arrow_array_missing():
import pyarrow as pa
- from pandas.core.arrays._arrow_utils import ArrowIntervalType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType
arr = IntervalArray.from_breaks([0.0, 1.0, 2.0, 3.0])
arr[1] = None
@@ -330,7 +330,7 @@ def test_arrow_array_missing():
def test_arrow_table_roundtrip(breaks):
import pyarrow as pa
- from pandas.core.arrays._arrow_utils import ArrowIntervalType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType
arr = IntervalArray.from_breaks(breaks)
arr[1] = None
diff --git a/pandas/tests/arrays/masked/test_arrow_compat.py b/pandas/tests/arrays/masked/test_arrow_compat.py
index 051762511a6ca..4ccc54636eaee 100644
--- a/pandas/tests/arrays/masked/test_arrow_compat.py
+++ b/pandas/tests/arrays/masked/test_arrow_compat.py
@@ -6,7 +6,7 @@
pa = pytest.importorskip("pyarrow", minversion="1.0.1")
-from pandas.core.arrays._arrow_utils import pyarrow_array_to_numpy_and_mask
+from pandas.core.arrays.arrow._arrow_utils import pyarrow_array_to_numpy_and_mask
arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]
arrays += [pd.array([0.1, 0.2, 0.3, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES]
diff --git a/pandas/tests/arrays/period/test_arrow_compat.py b/pandas/tests/arrays/period/test_arrow_compat.py
index 560299a4a47f5..7d2d2daed3497 100644
--- a/pandas/tests/arrays/period/test_arrow_compat.py
+++ b/pandas/tests/arrays/period/test_arrow_compat.py
@@ -13,7 +13,7 @@
def test_arrow_extension_type():
- from pandas.core.arrays._arrow_utils import ArrowPeriodType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType
p1 = ArrowPeriodType("D")
p2 = ArrowPeriodType("D")
@@ -34,7 +34,7 @@ def test_arrow_extension_type():
],
)
def test_arrow_array(data, freq):
- from pandas.core.arrays._arrow_utils import ArrowPeriodType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType
periods = period_array(data, freq=freq)
result = pa.array(periods)
@@ -57,7 +57,7 @@ def test_arrow_array(data, freq):
def test_arrow_array_missing():
- from pandas.core.arrays._arrow_utils import ArrowPeriodType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType
arr = PeriodArray([1, 2, 3], freq="D")
arr[1] = pd.NaT
@@ -70,7 +70,7 @@ def test_arrow_array_missing():
def test_arrow_table_roundtrip():
- from pandas.core.arrays._arrow_utils import ArrowPeriodType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType
arr = PeriodArray([1, 2, 3], freq="D")
arr[1] = pd.NaT
@@ -91,7 +91,7 @@ def test_arrow_table_roundtrip():
def test_arrow_load_from_zero_chunks():
# GH-41040
- from pandas.core.arrays._arrow_utils import ArrowPeriodType
+ from pandas.core.arrays.arrow._arrow_utils import ArrowPeriodType
arr = PeriodArray([], freq="D")
df = pd.DataFrame({"a": arr})
diff --git a/pandas/tests/extension/arrow/arrays.py b/pandas/tests/extension/arrow/arrays.py
index 33eef35153bce..d19a6245809be 100644
--- a/pandas/tests/extension/arrow/arrays.py
+++ b/pandas/tests/extension/arrow/arrays.py
@@ -24,7 +24,7 @@
)
from pandas.api.types import is_scalar
from pandas.core.arraylike import OpsMixin
-from pandas.core.arrays._mixins import ArrowExtensionArray as _ArrowExtensionArray
+from pandas.core.arrays.arrow import ArrowExtensionArray as _ArrowExtensionArray
from pandas.core.construction import extract_array
| - [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).
* `pandas/core/arrays/_arrow_utils.py` -> `pandas/core/arrays/arrow/_arrow_utils.py`
* `ArrowExtensionArray`: `pandas/core/arrays/_mixins.py` -> `pandas/core/arrays/arrow/array.py` | https://api.github.com/repos/pandas-dev/pandas/pulls/46591 | 2022-04-01T04:36:50Z | 2022-04-03T02:34:43Z | 2022-04-03T02:34:43Z | 2022-07-28T17:57:34Z |
DOC: Fix errors detected by sphinx-lint | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 04e148453387b..c6c7acf5b3823 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -70,6 +70,10 @@ repos:
- id: rst-inline-touching-normal
types: [text] # overwrite types: [rst]
types_or: [python, rst]
+- repo: https://github.com/sphinx-contrib/sphinx-lint
+ rev: v0.2
+ hooks:
+ - id: sphinx-lint
- repo: https://github.com/asottile/yesqa
rev: v1.3.0
hooks:
diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst
index 61e3bcd44bea8..2fa6bf62ba80f 100644
--- a/doc/source/development/contributing_codebase.rst
+++ b/doc/source/development/contributing_codebase.rst
@@ -223,7 +223,7 @@ In some cases you may be tempted to use ``cast`` from the typing module when you
...
else: # Reasonably only str objects would reach this but...
obj = cast(str, obj) # Mypy complains without this!
- return obj.upper()
+ return obj.upper()
The limitation here is that while a human can reasonably understand that ``is_number`` would catch the ``int`` and ``float`` types mypy cannot make that same inference just yet (see `mypy #5206 <https://github.com/python/mypy/issues/5206>`_. While the above works, the use of ``cast`` is **strongly discouraged**. Where applicable a refactor of the code to appease static analysis is preferable
diff --git a/doc/source/development/contributing_environment.rst b/doc/source/development/contributing_environment.rst
index fb27d07cfb18f..c881770aa7584 100644
--- a/doc/source/development/contributing_environment.rst
+++ b/doc/source/development/contributing_environment.rst
@@ -85,10 +85,10 @@ You will need `Build Tools for Visual Studio 2019
<https://visualstudio.microsoft.com/downloads/>`_.
.. warning::
- You DO NOT need to install Visual Studio 2019.
- You only need "Build Tools for Visual Studio 2019" found by
- scrolling down to "All downloads" -> "Tools for Visual Studio 2019".
- In the installer, select the "C++ build tools" workload.
+ You DO NOT need to install Visual Studio 2019.
+ You only need "Build Tools for Visual Studio 2019" found by
+ scrolling down to "All downloads" -> "Tools for Visual Studio 2019".
+ In the installer, select the "C++ build tools" workload.
You can install the necessary components on the commandline using
`vs_buildtools.exe <https://download.visualstudio.microsoft.com/download/pr/9a26f37e-6001-429b-a5db-c5455b93953c/460d80ab276046de2455a4115cc4e2f1e6529c9e6cb99501844ecafd16c619c4/vs_BuildTools.exe>`_:
diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index 15fa58f8d804a..256c3ee36e80c 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -540,7 +540,7 @@ Pandas-Genomics provides extension types, extension arrays, and extension access
`Pint-Pandas`_
~~~~~~~~~~~~~~
-``Pint-Pandas <https://github.com/hgrecco/pint-pandas>`` provides an extension type for
+`Pint-Pandas <https://github.com/hgrecco/pint-pandas>`_ provides an extension type for
storing numeric arrays with units. These arrays can be stored inside pandas'
Series and DataFrame. Operations between Series and DataFrame columns which
use pint's extension array are then units aware.
@@ -548,7 +548,7 @@ use pint's extension array are then units aware.
`Text Extensions for Pandas`_
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-``Text Extensions for Pandas <https://ibm.biz/text-extensions-for-pandas>``
+`Text Extensions for Pandas <https://ibm.biz/text-extensions-for-pandas>`_
provides extension types to cover common data structures for representing natural language
data, plus library integrations that convert the outputs of popular natural language
processing libraries into Pandas DataFrames.
diff --git a/doc/source/user_guide/dsintro.rst b/doc/source/user_guide/dsintro.rst
index ba8ef0d86d130..571f8980070af 100644
--- a/doc/source/user_guide/dsintro.rst
+++ b/doc/source/user_guide/dsintro.rst
@@ -678,7 +678,7 @@ Boolean operators operate element-wise as well:
Transposing
~~~~~~~~~~~
-To transpose, access the ``T`` attribute or :meth:`DataFrame.transpose``,
+To transpose, access the ``T`` attribute or :meth:`DataFrame.transpose`,
similar to an ndarray:
.. ipython:: python
diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst
index bc772b5dab66c..f381d72069775 100644
--- a/doc/source/user_guide/groupby.rst
+++ b/doc/source/user_guide/groupby.rst
@@ -539,19 +539,19 @@ Some common aggregating functions are tabulated below:
:widths: 20, 80
:delim: ;
- :meth:`~pd.core.groupby.DataFrameGroupBy.mean`;Compute mean of groups
- :meth:`~pd.core.groupby.DataFrameGroupBy.sum`;Compute sum of group values
- :meth:`~pd.core.groupby.DataFrameGroupBy.size`;Compute group sizes
- :meth:`~pd.core.groupby.DataFrameGroupBy.count`;Compute count of group
- :meth:`~pd.core.groupby.DataFrameGroupBy.std`;Standard deviation of groups
- :meth:`~pd.core.groupby.DataFrameGroupBy.var`;Compute variance of groups
- :meth:`~pd.core.groupby.DataFrameGroupBy.sem`;Standard error of the mean of groups
- :meth:`~pd.core.groupby.DataFrameGroupBy.describe`;Generates descriptive statistics
- :meth:`~pd.core.groupby.DataFrameGroupBy.first`;Compute first of group values
- :meth:`~pd.core.groupby.DataFrameGroupBy.last`;Compute last of group values
- :meth:`~pd.core.groupby.DataFrameGroupBy.nth`;Take nth value, or a subset if n is a list
- :meth:`~pd.core.groupby.DataFrameGroupBy.min`;Compute min of group values
- :meth:`~pd.core.groupby.DataFrameGroupBy.max`;Compute max of group values
+ :meth:`~pd.core.groupby.DataFrameGroupBy.mean`;Compute mean of groups
+ :meth:`~pd.core.groupby.DataFrameGroupBy.sum`;Compute sum of group values
+ :meth:`~pd.core.groupby.DataFrameGroupBy.size`;Compute group sizes
+ :meth:`~pd.core.groupby.DataFrameGroupBy.count`;Compute count of group
+ :meth:`~pd.core.groupby.DataFrameGroupBy.std`;Standard deviation of groups
+ :meth:`~pd.core.groupby.DataFrameGroupBy.var`;Compute variance of groups
+ :meth:`~pd.core.groupby.DataFrameGroupBy.sem`;Standard error of the mean of groups
+ :meth:`~pd.core.groupby.DataFrameGroupBy.describe`;Generates descriptive statistics
+ :meth:`~pd.core.groupby.DataFrameGroupBy.first`;Compute first of group values
+ :meth:`~pd.core.groupby.DataFrameGroupBy.last`;Compute last of group values
+ :meth:`~pd.core.groupby.DataFrameGroupBy.nth`;Take nth value, or a subset if n is a list
+ :meth:`~pd.core.groupby.DataFrameGroupBy.min`;Compute min of group values
+ :meth:`~pd.core.groupby.DataFrameGroupBy.max`;Compute max of group values
The aggregating functions above will exclude NA values. Any function which
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index 3a8583d395cc4..4ed71913d7b4d 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -5695,9 +5695,9 @@ for an explanation of how the database connection is handled.
.. warning::
- When you open a connection to a database you are also responsible for closing it.
- Side effects of leaving a connection open may include locking the database or
- other breaking behaviour.
+ When you open a connection to a database you are also responsible for closing it.
+ Side effects of leaving a connection open may include locking the database or
+ other breaking behaviour.
Writing DataFrames
''''''''''''''''''
diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst
index b524205ed7679..582620d8b6479 100644
--- a/doc/source/user_guide/timeseries.rst
+++ b/doc/source/user_guide/timeseries.rst
@@ -2405,9 +2405,9 @@ you can use the ``tz_convert`` method.
.. warning::
- Be wary of conversions between libraries. For some time zones, ``pytz`` and ``dateutil`` have different
- definitions of the zone. This is more of a problem for unusual time zones than for
- 'standard' zones like ``US/Eastern``.
+ Be wary of conversions between libraries. For some time zones, ``pytz`` and ``dateutil`` have different
+ definitions of the zone. This is more of a problem for unusual time zones than for
+ 'standard' zones like ``US/Eastern``.
.. warning::
diff --git a/doc/source/user_guide/window.rst b/doc/source/user_guide/window.rst
index f8c1f89be5d41..2407fd3113830 100644
--- a/doc/source/user_guide/window.rst
+++ b/doc/source/user_guide/window.rst
@@ -624,13 +624,13 @@ average of ``3, NaN, 5`` would be calculated as
.. math::
- \frac{(1-\alpha)^2 \cdot 3 + 1 \cdot 5}{(1-\alpha)^2 + 1}.
+ \frac{(1-\alpha)^2 \cdot 3 + 1 \cdot 5}{(1-\alpha)^2 + 1}.
Whereas if ``ignore_na=True``, the weighted average would be calculated as
.. math::
- \frac{(1-\alpha) \cdot 3 + 1 \cdot 5}{(1-\alpha) + 1}.
+ \frac{(1-\alpha) \cdot 3 + 1 \cdot 5}{(1-\alpha) + 1}.
The :meth:`~Ewm.var`, :meth:`~Ewm.std`, and :meth:`~Ewm.cov` functions have a ``bias`` argument,
specifying whether the result should contain biased or unbiased statistics.
diff --git a/doc/source/whatsnew/v0.15.0.rst b/doc/source/whatsnew/v0.15.0.rst
index fc2b070df4392..04506f1655c7d 100644
--- a/doc/source/whatsnew/v0.15.0.rst
+++ b/doc/source/whatsnew/v0.15.0.rst
@@ -462,15 +462,15 @@ Rolling/expanding moments improvements
.. code-block:: ipython
- In [51]: ewma(s, com=3., min_periods=2)
- Out[51]:
- 0 NaN
- 1 NaN
- 2 1.000000
- 3 1.000000
- 4 1.571429
- 5 2.189189
- dtype: float64
+ In [51]: pd.ewma(s, com=3., min_periods=2)
+ Out[51]:
+ 0 NaN
+ 1 NaN
+ 2 1.000000
+ 3 1.000000
+ 4 1.571429
+ 5 2.189189
+ dtype: float64
New behavior (note values start at index ``4``, the location of the 2nd (since ``min_periods=2``) non-empty value):
@@ -557,21 +557,21 @@ Rolling/expanding moments improvements
.. code-block:: ipython
- In [89]: ewmvar(s, com=2., bias=False)
- Out[89]:
- 0 -2.775558e-16
- 1 3.000000e-01
- 2 9.556787e-01
- 3 3.585799e+00
- dtype: float64
-
- In [90]: ewmvar(s, com=2., bias=False) / ewmvar(s, com=2., bias=True)
- Out[90]:
- 0 1.25
- 1 1.25
- 2 1.25
- 3 1.25
- dtype: float64
+ In [89]: pd.ewmvar(s, com=2., bias=False)
+ Out[89]:
+ 0 -2.775558e-16
+ 1 3.000000e-01
+ 2 9.556787e-01
+ 3 3.585799e+00
+ dtype: float64
+
+ In [90]: pd.ewmvar(s, com=2., bias=False) / pd.ewmvar(s, com=2., bias=True)
+ Out[90]:
+ 0 1.25
+ 1 1.25
+ 2 1.25
+ 3 1.25
+ dtype: float64
Note that entry ``0`` is approximately 0, and the debiasing factors are a constant 1.25.
By comparison, the following 0.15.0 results have a ``NaN`` for entry ``0``,
diff --git a/doc/source/whatsnew/v0.18.1.rst b/doc/source/whatsnew/v0.18.1.rst
index 3db00f686d62c..f873d320822ae 100644
--- a/doc/source/whatsnew/v0.18.1.rst
+++ b/doc/source/whatsnew/v0.18.1.rst
@@ -149,8 +149,8 @@ can return a valid boolean indexer or anything which is valid for these indexer'
# callable returns list of labels
df.loc[lambda x: [1, 2], lambda x: ["A", "B"]]
-Indexing with``[]``
-"""""""""""""""""""
+Indexing with ``[]``
+""""""""""""""""""""
Finally, you can use a callable in ``[]`` indexing of Series, DataFrame and Panel.
The callable must return a valid input for ``[]`` indexing depending on its
diff --git a/doc/source/whatsnew/v0.19.0.rst b/doc/source/whatsnew/v0.19.0.rst
index 340e1ce9ee1ef..a2bb935c708bc 100644
--- a/doc/source/whatsnew/v0.19.0.rst
+++ b/doc/source/whatsnew/v0.19.0.rst
@@ -1553,7 +1553,7 @@ Bug fixes
- Bug in invalid datetime parsing in ``to_datetime`` and ``DatetimeIndex`` may raise ``TypeError`` rather than ``ValueError`` (:issue:`11169`, :issue:`11287`)
- Bug in ``Index`` created with tz-aware ``Timestamp`` and mismatched ``tz`` option incorrectly coerces timezone (:issue:`13692`)
- Bug in ``DatetimeIndex`` with nanosecond frequency does not include timestamp specified with ``end`` (:issue:`13672`)
-- Bug in ```Series`` when setting a slice with a ``np.timedelta64`` (:issue:`14155`)
+- Bug in ``Series`` when setting a slice with a ``np.timedelta64`` (:issue:`14155`)
- Bug in ``Index`` raises ``OutOfBoundsDatetime`` if ``datetime`` exceeds ``datetime64[ns]`` bounds, rather than coercing to ``object`` dtype (:issue:`13663`)
- Bug in ``Index`` may ignore specified ``datetime64`` or ``timedelta64`` passed as ``dtype`` (:issue:`13981`)
- Bug in ``RangeIndex`` can be created without no arguments rather than raises ``TypeError`` (:issue:`13793`)
diff --git a/doc/source/whatsnew/v0.21.1.rst b/doc/source/whatsnew/v0.21.1.rst
index 090a988d6406a..e217e1a75efc5 100644
--- a/doc/source/whatsnew/v0.21.1.rst
+++ b/doc/source/whatsnew/v0.21.1.rst
@@ -125,7 +125,7 @@ Indexing
IO
^^
-- Bug in class:`~pandas.io.stata.StataReader` not converting date/time columns with display formatting addressed (:issue:`17990`). Previously columns with display formatting were normally left as ordinal numbers and not converted to datetime objects.
+- Bug in :class:`~pandas.io.stata.StataReader` not converting date/time columns with display formatting addressed (:issue:`17990`). Previously columns with display formatting were normally left as ordinal numbers and not converted to datetime objects.
- Bug in :func:`read_csv` when reading a compressed UTF-16 encoded file (:issue:`18071`)
- Bug in :func:`read_csv` for handling null values in index columns when specifying ``na_filter=False`` (:issue:`5239`)
- Bug in :func:`read_csv` when reading numeric category fields with high cardinality (:issue:`18186`)
diff --git a/doc/source/whatsnew/v0.23.0.rst b/doc/source/whatsnew/v0.23.0.rst
index be84c562b3c32..9f24bc8e8ec50 100644
--- a/doc/source/whatsnew/v0.23.0.rst
+++ b/doc/source/whatsnew/v0.23.0.rst
@@ -1126,7 +1126,7 @@ Removal of prior version deprecations/changes
- The ``Panel`` class has dropped the ``to_long`` and ``toLong`` methods (:issue:`19077`)
- The options ``display.line_with`` and ``display.height`` are removed in favor of ``display.width`` and ``display.max_rows`` respectively (:issue:`4391`, :issue:`19107`)
- The ``labels`` attribute of the ``Categorical`` class has been removed in favor of :attr:`Categorical.codes` (:issue:`7768`)
-- The ``flavor`` parameter have been removed from func:`to_sql` method (:issue:`13611`)
+- The ``flavor`` parameter have been removed from :func:`to_sql` method (:issue:`13611`)
- The modules ``pandas.tools.hashing`` and ``pandas.util.hashing`` have been removed (:issue:`16223`)
- The top-level functions ``pd.rolling_*``, ``pd.expanding_*`` and ``pd.ewm*`` have been removed (Deprecated since v0.18).
Instead, use the DataFrame/Series methods :attr:`~DataFrame.rolling`, :attr:`~DataFrame.expanding` and :attr:`~DataFrame.ewm` (:issue:`18723`)
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index e89e2f878fc24..e4dd6fa091d80 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -1121,7 +1121,7 @@ Indexing
- Bug in which :meth:`DataFrame.to_csv` caused a segfault for a reindexed data frame, when the indices were single-level :class:`MultiIndex` (:issue:`26303`).
- Fixed bug where assigning a :class:`arrays.PandasArray` to a :class:`pandas.core.frame.DataFrame` would raise error (:issue:`26390`)
- Allow keyword arguments for callable local reference used in the :meth:`DataFrame.query` string (:issue:`26426`)
-- Fixed a ``KeyError`` when indexing a :class:`MultiIndex`` level with a list containing exactly one label, which is missing (:issue:`27148`)
+- Fixed a ``KeyError`` when indexing a :class:`MultiIndex` level with a list containing exactly one label, which is missing (:issue:`27148`)
- Bug which produced ``AttributeError`` on partial matching :class:`Timestamp` in a :class:`MultiIndex` (:issue:`26944`)
- Bug in :class:`Categorical` and :class:`CategoricalIndex` with :class:`Interval` values when using the ``in`` operator (``__contains``) with objects that are not comparable to the values in the ``Interval`` (:issue:`23705`)
- Bug in :meth:`DataFrame.loc` and :meth:`DataFrame.iloc` on a :class:`DataFrame` with a single timezone-aware datetime64[ns] column incorrectly returning a scalar instead of a :class:`Series` (:issue:`27110`)
diff --git a/doc/source/whatsnew/v0.7.0.rst b/doc/source/whatsnew/v0.7.0.rst
index 1b947030ab8ab..1ee6a9899a655 100644
--- a/doc/source/whatsnew/v0.7.0.rst
+++ b/doc/source/whatsnew/v0.7.0.rst
@@ -190,11 +190,11 @@ been added:
:header: "Method","Description"
:widths: 40,60
- ``Series.iget_value(i)``, Retrieve value stored at location ``i``
- ``Series.iget(i)``, Alias for ``iget_value``
- ``DataFrame.irow(i)``, Retrieve the ``i``-th row
- ``DataFrame.icol(j)``, Retrieve the ``j``-th column
- "``DataFrame.iget_value(i, j)``", Retrieve the value at row ``i`` and column ``j``
+ ``Series.iget_value(i)``, Retrieve value stored at location ``i``
+ ``Series.iget(i)``, Alias for ``iget_value``
+ ``DataFrame.irow(i)``, Retrieve the ``i``-th row
+ ``DataFrame.icol(j)``, Retrieve the ``j``-th column
+ "``DataFrame.iget_value(i, j)``", Retrieve the value at row ``i`` and column ``j``
API tweaks regarding label-based slicing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/whatsnew/v0.9.1.rst b/doc/source/whatsnew/v0.9.1.rst
index 6b05e5bcded7e..a5c3860a895a2 100644
--- a/doc/source/whatsnew/v0.9.1.rst
+++ b/doc/source/whatsnew/v0.9.1.rst
@@ -54,44 +54,44 @@ New features
- DataFrame has new ``where`` and ``mask`` methods to select values according to a
given boolean mask (:issue:`2109`, :issue:`2151`)
- DataFrame currently supports slicing via a boolean vector the same length as the DataFrame (inside the ``[]``).
- The returned DataFrame has the same number of columns as the original, but is sliced on its index.
+ DataFrame currently supports slicing via a boolean vector the same length as the DataFrame (inside the ``[]``).
+ The returned DataFrame has the same number of columns as the original, but is sliced on its index.
.. ipython:: python
- df = DataFrame(np.random.randn(5, 3), columns = ['A','B','C'])
+ df = pd.DataFrame(np.random.randn(5, 3), columns=['A', 'B', 'C'])
- df
+ df
- df[df['A'] > 0]
+ df[df['A'] > 0]
- If a DataFrame is sliced with a DataFrame based boolean condition (with the same size as the original DataFrame),
- then a DataFrame the same size (index and columns) as the original is returned, with
- elements that do not meet the boolean condition as ``NaN``. This is accomplished via
- the new method ``DataFrame.where``. In addition, ``where`` takes an optional ``other`` argument for replacement.
+ If a DataFrame is sliced with a DataFrame based boolean condition (with the same size as the original DataFrame),
+ then a DataFrame the same size (index and columns) as the original is returned, with
+ elements that do not meet the boolean condition as ``NaN``. This is accomplished via
+ the new method ``DataFrame.where``. In addition, ``where`` takes an optional ``other`` argument for replacement.
- .. ipython:: python
+ .. ipython:: python
- df[df>0]
+ df[df > 0]
- df.where(df>0)
+ df.where(df > 0)
- df.where(df>0,-df)
+ df.where(df > 0, -df)
- Furthermore, ``where`` now aligns the input boolean condition (ndarray or DataFrame), such that partial selection
- with setting is possible. This is analogous to partial setting via ``.ix`` (but on the contents rather than the axis labels)
+ Furthermore, ``where`` now aligns the input boolean condition (ndarray or DataFrame), such that partial selection
+ with setting is possible. This is analogous to partial setting via ``.ix`` (but on the contents rather than the axis labels)
- .. ipython:: python
+ .. ipython:: python
- df2 = df.copy()
- df2[ df2[1:4] > 0 ] = 3
- df2
+ df2 = df.copy()
+ df2[df2[1:4] > 0] = 3
+ df2
- ``DataFrame.mask`` is the inverse boolean operation of ``where``.
+ ``DataFrame.mask`` is the inverse boolean operation of ``where``.
- .. ipython:: python
+ .. ipython:: python
- df.mask(df<=0)
+ df.mask(df <= 0)
- Enable referencing of Excel columns by their column names (:issue:`1936`)
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 03dfe475475a1..2ab0af46cda88 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -525,7 +525,7 @@ Use :meth:`arrays.IntegerArray.to_numpy` with an explicit ``na_value`` instead.
a.to_numpy(dtype="float", na_value=np.nan)
-**Reductions can return ``pd.NA``**
+**Reductions can return** ``pd.NA``
When performing a reduction such as a sum with ``skipna=False``, the result
will now be ``pd.NA`` instead of ``np.nan`` in presence of missing values
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index ebd76d97e78b3..e1f54c439ae9b 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -665,9 +665,9 @@ the previous index (:issue:`32240`).
In [4]: result
Out[4]:
min_val
- 0 x
- 1 y
- 2 z
+ 0 x
+ 1 y
+ 2 z
*New behavior*:
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 87982a149054c..52aa9312d4c14 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -826,7 +826,7 @@ Datetimelike
- Bug in :meth:`Timestamp.to_pydatetime` failing to retain the ``fold`` attribute (:issue:`45087`)
- Bug in :meth:`Series.mode` with ``DatetimeTZDtype`` incorrectly returning timezone-naive and ``PeriodDtype`` incorrectly raising (:issue:`41927`)
- Fixed regression in :meth:`~Series.reindex` raising an error when using an incompatible fill value with a datetime-like dtype (or not raising a deprecation warning for using a ``datetime.date`` as fill value) (:issue:`42921`)
-- Bug in :class:`DateOffset`` addition with :class:`Timestamp` where ``offset.nanoseconds`` would not be included in the result (:issue:`43968`, :issue:`36589`)
+- Bug in :class:`DateOffset` addition with :class:`Timestamp` where ``offset.nanoseconds`` would not be included in the result (:issue:`43968`, :issue:`36589`)
- Bug in :meth:`Timestamp.fromtimestamp` not supporting the ``tz`` argument (:issue:`45083`)
- Bug in :class:`DataFrame` construction from dict of :class:`Series` with mismatched index dtypes sometimes raising depending on the ordering of the passed dict (:issue:`44091`)
- Bug in :class:`Timestamp` hashing during some DST transitions caused a segmentation fault (:issue:`33931` and :issue:`40817`)
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 76511cb3eb48c..6986c04ae8d37 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1658,13 +1658,13 @@ def value_counts(
... })
>>> df
- gender education country
- 0 male low US
- 1 male medium FR
- 2 female high US
- 3 male low FR
- 4 female high FR
- 5 male low FR
+ gender education country
+ 0 male low US
+ 1 male medium FR
+ 2 female high US
+ 3 male low FR
+ 4 female high FR
+ 5 male low FR
>>> df.groupby('gender').value_counts()
gender education country
diff --git a/pandas/tests/io/parser/common/test_common_basic.py b/pandas/tests/io/parser/common/test_common_basic.py
index 5472bd99fa746..0ac0fe23bbbb7 100644
--- a/pandas/tests/io/parser/common/test_common_basic.py
+++ b/pandas/tests/io/parser/common/test_common_basic.py
@@ -699,7 +699,7 @@ def test_read_csv_and_table_sys_setprofile(all_parsers, read_func):
def test_first_row_bom(all_parsers):
# see gh-26545
parser = all_parsers
- data = '''\ufeff"Head1" "Head2" "Head3"'''
+ data = '''\ufeff"Head1"\t"Head2"\t"Head3"'''
result = parser.read_csv(StringIO(data), delimiter="\t")
expected = DataFrame(columns=["Head1", "Head2", "Head3"])
@@ -710,7 +710,7 @@ def test_first_row_bom(all_parsers):
def test_first_row_bom_unquoted(all_parsers):
# see gh-36343
parser = all_parsers
- data = """\ufeffHead1 Head2 Head3"""
+ data = """\ufeffHead1\tHead2\tHead3"""
result = parser.read_csv(StringIO(data), delimiter="\t")
expected = DataFrame(columns=["Head1", "Head2", "Head3"])
diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py
index 0cd4f9c02f69f..73e563fd2b743 100644
--- a/pandas/tests/io/test_clipboard.py
+++ b/pandas/tests/io/test_clipboard.py
@@ -209,9 +209,9 @@ def test_read_clipboard_infer_excel(self, request, mock_clipboard):
text = dedent(
"""
- John James Charlie Mingus
- 1 2
- 4 Harry Carney
+ John James\tCharlie Mingus
+ 1\t2
+ 4\tHarry Carney
""".strip()
)
mock_clipboard[request.node.name] = text
| Found a few issues on the doc with [sphinx-lint](https://github.com/sphinx-contrib/sphinx-lint).
Fixed them. | https://api.github.com/repos/pandas-dev/pandas/pulls/46586 | 2022-03-31T13:37:58Z | 2022-04-07T17:04:23Z | 2022-04-07T17:04:23Z | 2022-04-08T09:00:39Z |
REGR: groupby.transform producing segfault | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 3089a6b8c16ae..91c35d7555705 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1106,7 +1106,7 @@ def _set_result_index_ordered(
# set the result index on the passed values object and
# return the new object, xref 8046
- if self.grouper.is_monotonic:
+ if self.grouper.is_monotonic and not self.grouper.has_dropped_na:
# shortcut if we have an already ordered grouper
result.set_axis(self.obj._get_axis(self.axis), axis=self.axis, inplace=True)
return result
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 5f15e11c4740c..b43319765c5b4 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -818,7 +818,10 @@ def result_ilocs(self) -> npt.NDArray[np.intp]:
# Original indices are where group_index would go via sorting.
# But when dropna is true, we need to remove null values while accounting for
# any gaps that then occur because of them.
- group_index = get_group_index(self.codes, self.shape, sort=False, xnull=True)
+ group_index = get_group_index(
+ self.codes, self.shape, sort=self._sort, xnull=True
+ )
+ group_index, _ = compress_group_index(group_index, sort=self._sort)
if self.has_dropped_na:
mask = np.where(group_index >= 0)
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index c210c79c29426..f178e05d40dd0 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -1303,23 +1303,34 @@ def test_transform_cumcount():
tm.assert_series_equal(result, expected)
-def test_null_group_lambda_self(sort, dropna):
+@pytest.mark.parametrize("keys", [["A1"], ["A1", "A2"]])
+def test_null_group_lambda_self(request, sort, dropna, keys):
# GH 17093
- np.random.seed(0)
- keys = np.random.randint(0, 5, size=50).astype(float)
- nulls = np.random.choice([0, 1], keys.shape).astype(bool)
- keys[nulls] = np.nan
- values = np.random.randint(0, 5, size=keys.shape)
- df = DataFrame({"A": keys, "B": values})
+ if not sort and not dropna:
+ msg = "GH#46584: null values get sorted when sort=False"
+ request.node.add_marker(pytest.mark.xfail(reason=msg, strict=False))
+
+ size = 50
+ nulls1 = np.random.choice([False, True], size)
+ nulls2 = np.random.choice([False, True], size)
+ # Whether a group contains a null value or not
+ nulls_grouper = nulls1 if len(keys) == 1 else nulls1 | nulls2
+
+ a1 = np.random.randint(0, 5, size=size).astype(float)
+ a1[nulls1] = np.nan
+ a2 = np.random.randint(0, 5, size=size).astype(float)
+ a2[nulls2] = np.nan
+ values = np.random.randint(0, 5, size=a1.shape)
+ df = DataFrame({"A1": a1, "A2": a2, "B": values})
expected_values = values
- if dropna and nulls.any():
+ if dropna and nulls_grouper.any():
expected_values = expected_values.astype(float)
- expected_values[nulls] = np.nan
+ expected_values[nulls_grouper] = np.nan
expected = DataFrame(expected_values, columns=["B"])
- gb = df.groupby("A", dropna=dropna, sort=sort)
- result = gb.transform(lambda x: x)
+ gb = df.groupby(keys, dropna=dropna, sort=sort)
+ result = gb[["B"]].transform(lambda x: x)
tm.assert_frame_equal(result, expected)
| - [x] closes #46566 (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).
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
No whatsnew because this is only on main currently. | https://api.github.com/repos/pandas-dev/pandas/pulls/46585 | 2022-03-31T13:04:58Z | 2022-03-31T17:59:23Z | 2022-03-31T17:59:23Z | 2022-03-31T18:00:02Z |
REF: expose pandas_timedelta_to_timedeltastruct | diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py
index 4c74959fee60d..15836854bad4d 100644
--- a/pandas/_libs/tslibs/__init__.py
+++ b/pandas/_libs/tslibs/__init__.py
@@ -27,10 +27,7 @@
]
from pandas._libs.tslibs import dtypes
-from pandas._libs.tslibs.conversion import (
- OutOfBoundsTimedelta,
- localize_pydatetime,
-)
+from pandas._libs.tslibs.conversion import localize_pydatetime
from pandas._libs.tslibs.dtypes import Resolution
from pandas._libs.tslibs.nattype import (
NaT,
@@ -38,7 +35,10 @@
iNaT,
nat_strings,
)
-from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
+from pandas._libs.tslibs.np_datetime import (
+ OutOfBoundsDatetime,
+ OutOfBoundsTimedelta,
+)
from pandas._libs.tslibs.offsets import (
BaseOffset,
Tick,
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index e4b0c527a4cac..457b27b293f11 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -44,7 +44,10 @@ from pandas._libs.tslibs.np_datetime cimport (
pydatetime_to_dt64,
)
-from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
+from pandas._libs.tslibs.np_datetime import (
+ OutOfBoundsDatetime,
+ OutOfBoundsTimedelta,
+)
from pandas._libs.tslibs.timezones cimport (
get_dst_info,
@@ -85,15 +88,6 @@ DT64NS_DTYPE = np.dtype('M8[ns]')
TD64NS_DTYPE = np.dtype('m8[ns]')
-class OutOfBoundsTimedelta(ValueError):
- """
- Raised when encountering a timedelta value that cannot be represented
- as a timedelta64[ns].
- """
- # Timedelta analogue to OutOfBoundsDatetime
- pass
-
-
# ----------------------------------------------------------------------
# Unit Conversion Helpers
diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd
index 211b47cc3dc20..fb8ae4aae0e7b 100644
--- a/pandas/_libs/tslibs/np_datetime.pxd
+++ b/pandas/_libs/tslibs/np_datetime.pxd
@@ -66,6 +66,10 @@ cdef extern from "src/datetime/np_datetime.h":
npy_datetime npy_datetimestruct_to_datetime(NPY_DATETIMEUNIT fr,
npy_datetimestruct *d) nogil
+ void pandas_timedelta_to_timedeltastruct(npy_timedelta val,
+ NPY_DATETIMEUNIT fr,
+ pandas_timedeltastruct *result
+ ) nogil
cdef bint cmp_scalar(int64_t lhs, int64_t rhs, int op) except -1
@@ -94,3 +98,5 @@ cpdef cnp.ndarray astype_overflowsafe(
cnp.dtype dtype, # ndarray[datetime64[anyunit]]
bint copy=*,
)
+
+cdef bint cmp_dtstructs(npy_datetimestruct* left, npy_datetimestruct* right, int op)
diff --git a/pandas/_libs/tslibs/np_datetime.pyi b/pandas/_libs/tslibs/np_datetime.pyi
index 922fe8c4a4dce..59f4427125266 100644
--- a/pandas/_libs/tslibs/np_datetime.pyi
+++ b/pandas/_libs/tslibs/np_datetime.pyi
@@ -1,6 +1,7 @@
import numpy as np
class OutOfBoundsDatetime(ValueError): ...
+class OutOfBoundsTimedelta(ValueError): ...
# only exposed for testing
def py_get_unit_from_dtype(dtype: np.dtype): ...
diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx
index 2a0b4ceeb98f8..44646b0d4e87f 100644
--- a/pandas/_libs/tslibs/np_datetime.pyx
+++ b/pandas/_libs/tslibs/np_datetime.pyx
@@ -34,11 +34,6 @@ cdef extern from "src/datetime/np_datetime.h":
int cmp_npy_datetimestruct(npy_datetimestruct *a,
npy_datetimestruct *b)
- void pandas_timedelta_to_timedeltastruct(npy_timedelta val,
- NPY_DATETIMEUNIT fr,
- pandas_timedeltastruct *result
- ) nogil
-
# AS, FS, PS versions exist but are not imported because they are not used.
npy_datetimestruct _NS_MIN_DTS, _NS_MAX_DTS
npy_datetimestruct _US_MIN_DTS, _US_MAX_DTS
@@ -100,6 +95,28 @@ def py_get_unit_from_dtype(dtype):
# Comparison
+cdef bint cmp_dtstructs(
+ npy_datetimestruct* left, npy_datetimestruct* right, int op
+):
+ cdef:
+ int cmp_res
+
+ cmp_res = cmp_npy_datetimestruct(left, right)
+ if op == Py_EQ:
+ return cmp_res == 0
+ if op == Py_NE:
+ return cmp_res != 0
+ if op == Py_GT:
+ return cmp_res == 1
+ if op == Py_LT:
+ return cmp_res == -1
+ if op == Py_GE:
+ return cmp_res == 1 or cmp_res == 0
+ else:
+ # i.e. op == Py_LE
+ return cmp_res == -1 or cmp_res == 0
+
+
cdef inline bint cmp_scalar(int64_t lhs, int64_t rhs, int op) except -1:
"""
cmp_scalar is a more performant version of PyObject_RichCompare
@@ -127,6 +144,15 @@ class OutOfBoundsDatetime(ValueError):
pass
+class OutOfBoundsTimedelta(ValueError):
+ """
+ Raised when encountering a timedelta value that cannot be represented
+ as a timedelta64[ns].
+ """
+ # Timedelta analogue to OutOfBoundsDatetime
+ pass
+
+
cdef check_dts_bounds(npy_datetimestruct *dts, NPY_DATETIMEUNIT unit=NPY_FR_ns):
"""Raises OutOfBoundsDatetime if the given date is outside the range that
can be represented by nanosecond-resolution 64-bit integers."""
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index 627006a7f32c0..b443ae283755c 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -51,6 +51,7 @@ from pandas._libs.tslibs.np_datetime cimport (
pandas_timedeltastruct,
td64_to_tdstruct,
)
+from pandas._libs.tslibs.np_datetime import OutOfBoundsTimedelta
from pandas._libs.tslibs.offsets cimport is_tick_object
from pandas._libs.tslibs.util cimport (
is_array,
@@ -188,7 +189,6 @@ cpdef int64_t delta_to_nanoseconds(delta) except? -1:
+ delta.microseconds
) * 1000
except OverflowError as err:
- from pandas._libs.tslibs.conversion import OutOfBoundsTimedelta
raise OutOfBoundsTimedelta(*err.args) from err
raise TypeError(type(delta))
@@ -226,7 +226,6 @@ cdef object ensure_td64ns(object ts):
# NB: cython#1381 this cannot be *=
td64_value = td64_value * mult
except OverflowError as err:
- from pandas._libs.tslibs.conversion import OutOfBoundsTimedelta
raise OutOfBoundsTimedelta(ts) from err
return np.timedelta64(td64_value, "ns")
| Broken off from a branch implementing non-nano Timedelta scalar.
`cmp_dtstructs` will end up being used by both `Timedelta.__richcmp__` and `Timestamp.__richcmo__` | https://api.github.com/repos/pandas-dev/pandas/pulls/46578 | 2022-03-31T03:15:54Z | 2022-03-31T17:34:42Z | 2022-03-31T17:34:42Z | 2022-03-31T18:36:04Z |
Backport PR #46548 on branch 1.4.x (REGR: tests + whats new: boolean dtype in styler render) | diff --git a/doc/source/whatsnew/v1.4.2.rst b/doc/source/whatsnew/v1.4.2.rst
index 13f3e9a0d0a8c..76b2a5d6ffd47 100644
--- a/doc/source/whatsnew/v1.4.2.rst
+++ b/doc/source/whatsnew/v1.4.2.rst
@@ -21,7 +21,7 @@ Fixed regressions
- Fixed regression in :meth:`DataFrame.replace` when a replacement value was also a target for replacement (:issue:`46306`)
- Fixed regression in :meth:`DataFrame.replace` when the replacement value was explicitly ``None`` when passed in a dictionary to ``to_replace`` (:issue:`45601`, :issue:`45836`)
- Fixed regression when setting values with :meth:`DataFrame.loc` losing :class:`MultiIndex` names if :class:`DataFrame` was empty before (:issue:`46317`)
--
+- Fixed regression when rendering boolean datatype columns with :meth:`.Styler` (:issue:`46384`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/tests/io/formats/style/test_format.py b/pandas/tests/io/formats/style/test_format.py
index 5207be992d606..a52c679e16ad5 100644
--- a/pandas/tests/io/formats/style/test_format.py
+++ b/pandas/tests/io/formats/style/test_format.py
@@ -434,3 +434,11 @@ def test_1level_multiindex():
assert ctx["body"][0][0]["is_visible"] is True
assert ctx["body"][1][0]["display_value"] == "2"
assert ctx["body"][1][0]["is_visible"] is True
+
+
+def test_boolean_format():
+ # gh 46384: booleans do not collapse to integer representation on display
+ df = DataFrame([[True, False]])
+ ctx = df.style._translate(True, True)
+ assert ctx["body"][0][1]["display_value"] is True
+ assert ctx["body"][0][2]["display_value"] is False
| Backport PR #46548: REGR: tests + whats new: boolean dtype in styler render | https://api.github.com/repos/pandas-dev/pandas/pulls/46577 | 2022-03-30T21:36:57Z | 2022-03-31T00:24:32Z | 2022-03-31T00:24:32Z | 2022-03-31T00:24:32Z |
STYLE update black formatter in v1.4.x | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 3ffcf29f47688..2d3178f9d62fe 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -9,7 +9,7 @@ repos:
- id: absolufy-imports
files: ^pandas/
- repo: https://github.com/python/black
- rev: 21.12b0
+ rev: 22.3.0
hooks:
- id: black
- repo: https://github.com/codespell-project/codespell
diff --git a/asv_bench/benchmarks/algorithms.py b/asv_bench/benchmarks/algorithms.py
index 2e43827232ae5..0008a589ca71f 100644
--- a/asv_bench/benchmarks/algorithms.py
+++ b/asv_bench/benchmarks/algorithms.py
@@ -34,7 +34,7 @@ class Factorize:
param_names = ["unique", "sort", "dtype"]
def setup(self, unique, sort, dtype):
- N = 10 ** 5
+ N = 10**5
string_index = tm.makeStringIndex(N)
string_arrow = None
if dtype == "string[pyarrow]":
@@ -74,7 +74,7 @@ class Duplicated:
param_names = ["unique", "keep", "dtype"]
def setup(self, unique, keep, dtype):
- N = 10 ** 5
+ N = 10**5
data = {
"int": pd.Index(np.arange(N), dtype="int64"),
"uint": pd.Index(np.arange(N), dtype="uint64"),
@@ -97,7 +97,7 @@ def time_duplicated(self, unique, keep, dtype):
class Hashing:
def setup_cache(self):
- N = 10 ** 5
+ N = 10**5
df = pd.DataFrame(
{
@@ -145,7 +145,7 @@ class Quantile:
param_names = ["quantile", "interpolation", "dtype"]
def setup(self, quantile, interpolation, dtype):
- N = 10 ** 5
+ N = 10**5
data = {
"int": np.arange(N),
"uint": np.arange(N).astype(np.uint64),
@@ -158,7 +158,7 @@ def time_quantile(self, quantile, interpolation, dtype):
class SortIntegerArray:
- params = [10 ** 3, 10 ** 5]
+ params = [10**3, 10**5]
def setup(self, N):
data = np.arange(N, dtype=float)
diff --git a/asv_bench/benchmarks/algos/isin.py b/asv_bench/benchmarks/algos/isin.py
index 37fa0b490bd9e..16d90b9d23741 100644
--- a/asv_bench/benchmarks/algos/isin.py
+++ b/asv_bench/benchmarks/algos/isin.py
@@ -49,7 +49,7 @@ def setup(self, dtype):
elif dtype in ["category[object]", "category[int]"]:
# Note: sizes are different in this case than others
- n = 5 * 10 ** 5
+ n = 5 * 10**5
sample_size = 100
arr = list(np.random.randint(0, n // 10, size=n))
@@ -174,7 +174,7 @@ class IsinWithArange:
def setup(self, dtype, M, offset_factor):
offset = int(M * offset_factor)
- tmp = Series(np.random.randint(offset, M + offset, 10 ** 6))
+ tmp = Series(np.random.randint(offset, M + offset, 10**6))
self.series = tmp.astype(dtype)
self.values = np.arange(M).astype(dtype)
@@ -191,8 +191,8 @@ class IsInFloat64:
param_names = ["dtype", "title"]
def setup(self, dtype, title):
- N_many = 10 ** 5
- N_few = 10 ** 6
+ N_many = 10**5
+ N_few = 10**6
self.series = Series([1, 2], dtype=dtype)
if title == "many_different_values":
@@ -240,10 +240,10 @@ class IsInForObjects:
param_names = ["series_type", "vals_type"]
def setup(self, series_type, vals_type):
- N_many = 10 ** 5
+ N_many = 10**5
if series_type == "nans":
- ser_vals = np.full(10 ** 4, np.nan)
+ ser_vals = np.full(10**4, np.nan)
elif series_type == "short":
ser_vals = np.arange(2)
elif series_type == "long":
@@ -254,7 +254,7 @@ def setup(self, series_type, vals_type):
self.series = Series(ser_vals).astype(object)
if vals_type == "nans":
- values = np.full(10 ** 4, np.nan)
+ values = np.full(10**4, np.nan)
elif vals_type == "short":
values = np.arange(2)
elif vals_type == "long":
@@ -277,7 +277,7 @@ class IsInLongSeriesLookUpDominates:
param_names = ["dtype", "MaxNumber", "series_type"]
def setup(self, dtype, MaxNumber, series_type):
- N = 10 ** 7
+ N = 10**7
if series_type == "random_hits":
array = np.random.randint(0, MaxNumber, N)
@@ -304,7 +304,7 @@ class IsInLongSeriesValuesDominate:
param_names = ["dtype", "series_type"]
def setup(self, dtype, series_type):
- N = 10 ** 7
+ N = 10**7
if series_type == "random":
vals = np.random.randint(0, 10 * N, N)
@@ -312,7 +312,7 @@ def setup(self, dtype, series_type):
vals = np.arange(N)
self.values = vals.astype(dtype.lower())
- M = 10 ** 6 + 1
+ M = 10**6 + 1
self.series = Series(np.arange(M)).astype(dtype)
def time_isin(self, dtypes, series_type):
diff --git a/asv_bench/benchmarks/arithmetic.py b/asv_bench/benchmarks/arithmetic.py
index edd1132116f76..9db2e2c2a9732 100644
--- a/asv_bench/benchmarks/arithmetic.py
+++ b/asv_bench/benchmarks/arithmetic.py
@@ -59,7 +59,7 @@ def time_frame_op_with_scalar(self, dtype, scalar, op):
class OpWithFillValue:
def setup(self):
# GH#31300
- arr = np.arange(10 ** 6)
+ arr = np.arange(10**6)
df = DataFrame({"A": arr})
ser = df["A"]
@@ -93,7 +93,7 @@ class MixedFrameWithSeriesAxis:
param_names = ["opname"]
def setup(self, opname):
- arr = np.arange(10 ** 6).reshape(1000, -1)
+ arr = np.arange(10**6).reshape(1000, -1)
df = DataFrame(arr)
df["C"] = 1.0
self.df = df
@@ -201,7 +201,7 @@ def teardown(self, use_numexpr, threads):
class Ops2:
def setup(self):
- N = 10 ** 3
+ N = 10**3
self.df = DataFrame(np.random.randn(N, N))
self.df2 = DataFrame(np.random.randn(N, N))
@@ -258,7 +258,7 @@ class Timeseries:
param_names = ["tz"]
def setup(self, tz):
- N = 10 ** 6
+ N = 10**6
halfway = (N // 2) - 1
self.s = Series(date_range("20010101", periods=N, freq="T", tz=tz))
self.ts = self.s[halfway]
@@ -280,7 +280,7 @@ def time_timestamp_ops_diff_with_shift(self, tz):
class IrregularOps:
def setup(self):
- N = 10 ** 5
+ N = 10**5
idx = date_range(start="1/1/2000", periods=N, freq="s")
s = Series(np.random.randn(N), index=idx)
self.left = s.sample(frac=1)
@@ -304,7 +304,7 @@ class CategoricalComparisons:
param_names = ["op"]
def setup(self, op):
- N = 10 ** 5
+ N = 10**5
self.cat = pd.Categorical(list("aabbcd") * N, ordered=True)
def time_categorical_op(self, op):
@@ -317,7 +317,7 @@ class IndexArithmetic:
param_names = ["dtype"]
def setup(self, dtype):
- N = 10 ** 6
+ N = 10**6
indexes = {"int": "makeIntIndex", "float": "makeFloatIndex"}
self.index = getattr(tm, indexes[dtype])(N)
@@ -343,7 +343,7 @@ class NumericInferOps:
param_names = ["dtype"]
def setup(self, dtype):
- N = 5 * 10 ** 5
+ N = 5 * 10**5
self.df = DataFrame(
{"A": np.arange(N).astype(dtype), "B": np.arange(N).astype(dtype)}
)
@@ -367,7 +367,7 @@ def time_modulo(self, dtype):
class DateInferOps:
# from GH 7332
def setup_cache(self):
- N = 5 * 10 ** 5
+ N = 5 * 10**5
df = DataFrame({"datetime64": np.arange(N).astype("datetime64[ms]")})
df["timedelta"] = df["datetime64"] - df["datetime64"]
return df
@@ -388,7 +388,7 @@ class AddOverflowScalar:
param_names = ["scalar"]
def setup(self, scalar):
- N = 10 ** 6
+ N = 10**6
self.arr = np.arange(N)
def time_add_overflow_scalar(self, scalar):
@@ -397,7 +397,7 @@ def time_add_overflow_scalar(self, scalar):
class AddOverflowArray:
def setup(self):
- N = 10 ** 6
+ N = 10**6
self.arr = np.arange(N)
self.arr_rev = np.arange(-N, 0)
self.arr_mixed = np.array([1, -1]).repeat(N / 2)
diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py
index 268f25c3d12e3..2b60871cbf82b 100644
--- a/asv_bench/benchmarks/categoricals.py
+++ b/asv_bench/benchmarks/categoricals.py
@@ -19,7 +19,7 @@
class Constructor:
def setup(self):
- N = 10 ** 5
+ N = 10**5
self.categories = list("abcde")
self.cat_idx = pd.Index(self.categories)
self.values = np.tile(self.categories, N)
@@ -71,16 +71,16 @@ def time_existing_series(self):
class AsType:
def setup(self):
- N = 10 ** 5
+ N = 10**5
random_pick = np.random.default_rng().choice
categories = {
"str": list(string.ascii_letters),
- "int": np.random.randint(2 ** 16, size=154),
+ "int": np.random.randint(2**16, size=154),
"float": sys.maxsize * np.random.random((38,)),
"timestamp": [
- pd.Timestamp(x, unit="s") for x in np.random.randint(2 ** 18, size=578)
+ pd.Timestamp(x, unit="s") for x in np.random.randint(2**18, size=578)
],
}
@@ -112,7 +112,7 @@ def astype_datetime(self):
class Concat:
def setup(self):
- N = 10 ** 5
+ N = 10**5
self.s = pd.Series(list("aabbcd") * N).astype("category")
self.a = pd.Categorical(list("aabbcd") * N)
@@ -148,7 +148,7 @@ class ValueCounts:
param_names = ["dropna"]
def setup(self, dropna):
- n = 5 * 10 ** 5
+ n = 5 * 10**5
arr = [f"s{i:04d}" for i in np.random.randint(0, n // 10, size=n)]
self.ts = pd.Series(arr).astype("category")
@@ -166,7 +166,7 @@ def time_rendering(self):
class SetCategories:
def setup(self):
- n = 5 * 10 ** 5
+ n = 5 * 10**5
arr = [f"s{i:04d}" for i in np.random.randint(0, n // 10, size=n)]
self.ts = pd.Series(arr).astype("category")
@@ -176,7 +176,7 @@ def time_set_categories(self):
class RemoveCategories:
def setup(self):
- n = 5 * 10 ** 5
+ n = 5 * 10**5
arr = [f"s{i:04d}" for i in np.random.randint(0, n // 10, size=n)]
self.ts = pd.Series(arr).astype("category")
@@ -186,7 +186,7 @@ def time_remove_categories(self):
class Rank:
def setup(self):
- N = 10 ** 5
+ N = 10**5
ncats = 100
self.s_str = pd.Series(tm.makeCategoricalIndex(N, ncats)).astype(str)
@@ -241,7 +241,7 @@ def time_categorical_series_is_monotonic_decreasing(self):
class Contains:
def setup(self):
- N = 10 ** 5
+ N = 10**5
self.ci = tm.makeCategoricalIndex(N)
self.c = self.ci.values
self.key = self.ci.categories[0]
@@ -259,7 +259,7 @@ class CategoricalSlicing:
param_names = ["index"]
def setup(self, index):
- N = 10 ** 6
+ N = 10**6
categories = ["a", "b", "c"]
values = [0] * N + [1] * N + [2] * N
if index == "monotonic_incr":
@@ -295,7 +295,7 @@ def time_getitem_bool_array(self, index):
class Indexing:
def setup(self):
- N = 10 ** 5
+ N = 10**5
self.index = pd.CategoricalIndex(range(N), range(N))
self.series = pd.Series(range(N), index=self.index).sort_index()
self.category = self.index[500]
@@ -327,7 +327,7 @@ def time_sort_values(self):
class SearchSorted:
def setup(self):
- N = 10 ** 5
+ N = 10**5
self.ci = tm.makeCategoricalIndex(N).sort_values()
self.c = self.ci.values
self.key = self.ci.categories[1]
diff --git a/asv_bench/benchmarks/ctors.py b/asv_bench/benchmarks/ctors.py
index 5993b068feadf..ef8b16f376d6a 100644
--- a/asv_bench/benchmarks/ctors.py
+++ b/asv_bench/benchmarks/ctors.py
@@ -76,7 +76,7 @@ def setup(self, data_fmt, with_index, dtype):
raise NotImplementedError(
"Series constructors do not support using generators with indexes"
)
- N = 10 ** 4
+ N = 10**4
if dtype == "float":
arr = np.random.randn(N)
else:
@@ -90,7 +90,7 @@ def time_series_constructor(self, data_fmt, with_index, dtype):
class SeriesDtypesConstructors:
def setup(self):
- N = 10 ** 4
+ N = 10**4
self.arr = np.random.randn(N)
self.arr_str = np.array(["foo", "bar", "baz"], dtype=object)
self.s = Series(
@@ -114,7 +114,7 @@ def time_dtindex_from_index_with_series(self):
class MultiIndexConstructor:
def setup(self):
- N = 10 ** 4
+ N = 10**4
self.iterables = [tm.makeStringIndex(N), range(20)]
def time_multiindex_from_iterables(self):
diff --git a/asv_bench/benchmarks/eval.py b/asv_bench/benchmarks/eval.py
index cbab9fdc9c0ba..b5442531e748a 100644
--- a/asv_bench/benchmarks/eval.py
+++ b/asv_bench/benchmarks/eval.py
@@ -43,7 +43,7 @@ def teardown(self, engine, threads):
class Query:
def setup(self):
- N = 10 ** 6
+ N = 10**6
halfway = (N // 2) - 1
index = pd.date_range("20010101", periods=N, freq="T")
s = pd.Series(index)
diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py
index eace665ba0bac..810c29ec70a6f 100644
--- a/asv_bench/benchmarks/frame_ctor.py
+++ b/asv_bench/benchmarks/frame_ctor.py
@@ -77,7 +77,7 @@ class FromDictwithTimestamp:
param_names = ["offset"]
def setup(self, offset):
- N = 10 ** 3
+ N = 10**3
idx = date_range(Timestamp("1/1/1900"), freq=offset, periods=N)
df = DataFrame(np.random.randn(N, 10), index=idx)
self.d = df.to_dict()
diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py
index 16925b7959e6a..29ac92b15f632 100644
--- a/asv_bench/benchmarks/frame_methods.py
+++ b/asv_bench/benchmarks/frame_methods.py
@@ -50,7 +50,7 @@ def time_frame_fancy_lookup_all(self):
class Reindex:
def setup(self):
- N = 10 ** 3
+ N = 10**3
self.df = DataFrame(np.random.randn(N * 10, N))
self.idx = np.arange(4 * N, 7 * N)
self.idx_cols = np.random.randint(0, N, N)
@@ -84,7 +84,7 @@ def time_reindex_upcast(self):
class Rename:
def setup(self):
- N = 10 ** 3
+ N = 10**3
self.df = DataFrame(np.random.randn(N * 10, N))
self.idx = np.arange(4 * N, 7 * N)
self.dict_idx = {k: k for k in self.idx}
@@ -329,7 +329,7 @@ def time_frame_mask_floats(self):
class Isnull:
def setup(self):
- N = 10 ** 3
+ N = 10**3
self.df_no_null = DataFrame(np.random.randn(N, N))
sample = np.array([np.nan, 1.0])
@@ -497,7 +497,7 @@ def time_frame_dtypes(self):
class Equals:
def setup(self):
- N = 10 ** 3
+ N = 10**3
self.float_df = DataFrame(np.random.randn(N, N))
self.float_df_nan = self.float_df.copy()
self.float_df_nan.iloc[-1, -1] = np.nan
@@ -618,7 +618,7 @@ class XS:
param_names = ["axis"]
def setup(self, axis):
- self.N = 10 ** 4
+ self.N = 10**4
self.df = DataFrame(np.random.randn(self.N, self.N))
def time_frame_xs(self, axis):
@@ -718,9 +718,9 @@ class Describe:
def setup(self):
self.df = DataFrame(
{
- "a": np.random.randint(0, 100, 10 ** 6),
- "b": np.random.randint(0, 100, 10 ** 6),
- "c": np.random.randint(0, 100, 10 ** 6),
+ "a": np.random.randint(0, 100, 10**6),
+ "b": np.random.randint(0, 100, 10**6),
+ "c": np.random.randint(0, 100, 10**6),
}
)
diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py
index ac7cd87c846d5..af2efe56c2530 100644
--- a/asv_bench/benchmarks/gil.py
+++ b/asv_bench/benchmarks/gil.py
@@ -55,8 +55,8 @@ class ParallelGroupbyMethods:
def setup(self, threads, method):
if not have_real_test_parallel:
raise NotImplementedError
- N = 10 ** 6
- ngroups = 10 ** 3
+ N = 10**6
+ ngroups = 10**3
df = DataFrame(
{"key": np.random.randint(0, ngroups, size=N), "data": np.random.randn(N)}
)
@@ -88,8 +88,8 @@ class ParallelGroups:
def setup(self, threads):
if not have_real_test_parallel:
raise NotImplementedError
- size = 2 ** 22
- ngroups = 10 ** 3
+ size = 2**22
+ ngroups = 10**3
data = Series(np.random.randint(0, ngroups, size=size))
@test_parallel(num_threads=threads)
@@ -110,7 +110,7 @@ class ParallelTake1D:
def setup(self, dtype):
if not have_real_test_parallel:
raise NotImplementedError
- N = 10 ** 6
+ N = 10**6
df = DataFrame({"col": np.arange(N, dtype=dtype)})
indexer = np.arange(100, len(df) - 100)
@@ -133,8 +133,8 @@ class ParallelKth:
def setup(self):
if not have_real_test_parallel:
raise NotImplementedError
- N = 10 ** 7
- k = 5 * 10 ** 5
+ N = 10**7
+ k = 5 * 10**5
kwargs_list = [{"arr": np.random.randn(N)}, {"arr": np.random.randn(N)}]
@test_parallel(num_threads=2, kwargs_list=kwargs_list)
@@ -151,7 +151,7 @@ class ParallelDatetimeFields:
def setup(self):
if not have_real_test_parallel:
raise NotImplementedError
- N = 10 ** 6
+ N = 10**6
self.dti = date_range("1900-01-01", periods=N, freq="T")
self.period = self.dti.to_period("D")
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py
index ff58e382a9ba2..05dd53fc38a60 100644
--- a/asv_bench/benchmarks/groupby.py
+++ b/asv_bench/benchmarks/groupby.py
@@ -73,7 +73,7 @@ class Apply:
params = [4, 5]
def setup(self, factor):
- N = 10 ** factor
+ N = 10**factor
# two cases:
# - small groups: small data (N**4) + many labels (2000) -> average group
# size of 5 (-> larger overhead of slicing method)
@@ -116,7 +116,7 @@ class Groups:
params = ["int64_small", "int64_large", "object_small", "object_large"]
def setup_cache(self):
- size = 10 ** 6
+ size = 10**6
data = {
"int64_small": Series(np.random.randint(0, 100, size=size)),
"int64_large": Series(np.random.randint(0, 10000, size=size)),
@@ -160,7 +160,7 @@ class Nth:
params = ["float32", "float64", "datetime", "object"]
def setup(self, dtype):
- N = 10 ** 5
+ N = 10**5
# with datetimes (GH7555)
if dtype == "datetime":
values = date_range("1/1/2011", periods=N, freq="s")
@@ -268,7 +268,7 @@ def time_multi_int_nunique(self, df):
class AggFunctions:
def setup_cache(self):
- N = 10 ** 5
+ N = 10**5
fac1 = np.array(["A", "B", "C"], dtype="O")
fac2 = np.array(["one", "two"], dtype="O")
df = DataFrame(
@@ -301,7 +301,7 @@ def time_different_python_functions_singlecol(self, df):
class GroupStrings:
def setup(self):
- n = 2 * 10 ** 5
+ n = 2 * 10**5
alpha = list(map("".join, product(ascii_letters, repeat=4)))
data = np.random.choice(alpha, (n // 5, 4), replace=False)
data = np.repeat(data, 5, axis=0)
@@ -315,7 +315,7 @@ def time_multi_columns(self):
class MultiColumn:
def setup_cache(self):
- N = 10 ** 5
+ N = 10**5
key1 = np.tile(np.arange(100, dtype=object), 1000)
key2 = key1.copy()
np.random.shuffle(key1)
@@ -345,7 +345,7 @@ def time_col_select_numpy_sum(self, df):
class Size:
def setup(self):
- n = 10 ** 5
+ n = 10**5
offsets = np.random.randint(n, size=n).astype("timedelta64[ns]")
dates = np.datetime64("now") + offsets
self.df = DataFrame(
@@ -582,7 +582,7 @@ class RankWithTies:
]
def setup(self, dtype, tie_method):
- N = 10 ** 4
+ N = 10**4
if dtype == "datetime64":
data = np.array([Timestamp("2011/01/01")] * N, dtype=dtype)
else:
@@ -640,7 +640,7 @@ def time_str_func(self, dtype, method):
class Categories:
def setup(self):
- N = 10 ** 5
+ N = 10**5
arr = np.random.random(N)
data = {"a": Categorical(np.random.randint(10000, size=N)), "b": arr}
self.df = DataFrame(data)
@@ -682,14 +682,14 @@ class Datelike:
param_names = ["grouper"]
def setup(self, grouper):
- N = 10 ** 4
+ N = 10**4
rng_map = {
"period_range": period_range,
"date_range": date_range,
"date_range_tz": partial(date_range, tz="US/Central"),
}
self.grouper = rng_map[grouper]("1900-01-01", freq="D", periods=N)
- self.df = DataFrame(np.random.randn(10 ** 4, 2))
+ self.df = DataFrame(np.random.randn(10**4, 2))
def time_sum(self, grouper):
self.df.groupby(self.grouper).sum()
@@ -798,7 +798,7 @@ class TransformEngine:
params = [[True, False]]
def setup(self, parallel):
- N = 10 ** 3
+ N = 10**3
data = DataFrame(
{0: [str(i) for i in range(100)] * N, 1: list(range(100)) * N},
columns=[0, 1],
@@ -841,7 +841,7 @@ class AggEngine:
params = [[True, False]]
def setup(self, parallel):
- N = 10 ** 3
+ N = 10**3
data = DataFrame(
{0: [str(i) for i in range(100)] * N, 1: list(range(100)) * N},
columns=[0, 1],
@@ -904,7 +904,7 @@ def function(values):
class Sample:
def setup(self):
- N = 10 ** 3
+ N = 10**3
self.df = DataFrame({"a": np.zeros(N)})
self.groups = np.arange(0, N)
self.weights = np.ones(N)
diff --git a/asv_bench/benchmarks/hash_functions.py b/asv_bench/benchmarks/hash_functions.py
index 6703cc791493a..d9a291dc27125 100644
--- a/asv_bench/benchmarks/hash_functions.py
+++ b/asv_bench/benchmarks/hash_functions.py
@@ -16,9 +16,9 @@ class Float64GroupIndex:
# GH28303
def setup(self):
self.df = pd.date_range(
- start="1/1/2018", end="1/2/2018", periods=10 ** 6
+ start="1/1/2018", end="1/2/2018", periods=10**6
).to_frame()
- self.group_index = np.round(self.df.index.astype(int) / 10 ** 9)
+ self.group_index = np.round(self.df.index.astype(int) / 10**9)
def time_groupby(self):
self.df.groupby(self.group_index).last()
@@ -29,8 +29,8 @@ class UniqueAndFactorizeArange:
param_names = ["exponent"]
def setup(self, exponent):
- a = np.arange(10 ** 4, dtype="float64")
- self.a2 = (a + 10 ** exponent).repeat(100)
+ a = np.arange(10**4, dtype="float64")
+ self.a2 = (a + 10**exponent).repeat(100)
def time_factorize(self, exponent):
pd.factorize(self.a2)
@@ -43,7 +43,7 @@ class NumericSeriesIndexing:
params = [
(pd.Int64Index, pd.UInt64Index, pd.Float64Index),
- (10 ** 4, 10 ** 5, 5 * 10 ** 5, 10 ** 6, 5 * 10 ** 6),
+ (10**4, 10**5, 5 * 10**5, 10**6, 5 * 10**6),
]
param_names = ["index_dtype", "N"]
@@ -61,7 +61,7 @@ class NumericSeriesIndexingShuffled:
params = [
(pd.Int64Index, pd.UInt64Index, pd.Float64Index),
- (10 ** 4, 10 ** 5, 5 * 10 ** 5, 10 ** 6, 5 * 10 ** 6),
+ (10**4, 10**5, 5 * 10**5, 10**6, 5 * 10**6),
]
param_names = ["index_dtype", "N"]
diff --git a/asv_bench/benchmarks/index_cached_properties.py b/asv_bench/benchmarks/index_cached_properties.py
index 16fbc741775e4..ad6170e256091 100644
--- a/asv_bench/benchmarks/index_cached_properties.py
+++ b/asv_bench/benchmarks/index_cached_properties.py
@@ -22,7 +22,7 @@ class IndexCache:
param_names = ["index_type"]
def setup(self, index_type):
- N = 10 ** 5
+ N = 10**5
if index_type == "MultiIndex":
self.idx = pd.MultiIndex.from_product(
[pd.date_range("1/1/2000", freq="T", periods=N // 2), ["a", "b"]]
diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py
index 2b2302a796730..dab33f02c2cd9 100644
--- a/asv_bench/benchmarks/index_object.py
+++ b/asv_bench/benchmarks/index_object.py
@@ -25,7 +25,7 @@ class SetOperations:
param_names = ["dtype", "method"]
def setup(self, dtype, method):
- N = 10 ** 5
+ N = 10**5
dates_left = date_range("1/1/2000", periods=N, freq="T")
fmt = "%Y-%m-%d %H:%M:%S"
date_str_left = Index(dates_left.strftime(fmt))
@@ -46,7 +46,7 @@ def time_operation(self, dtype, method):
class SetDisjoint:
def setup(self):
- N = 10 ** 5
+ N = 10**5
B = N + 20000
self.datetime_left = DatetimeIndex(range(N))
self.datetime_right = DatetimeIndex(range(N, B))
@@ -57,8 +57,8 @@ def time_datetime_difference_disjoint(self):
class Range:
def setup(self):
- self.idx_inc = RangeIndex(start=0, stop=10 ** 6, step=3)
- self.idx_dec = RangeIndex(start=10 ** 6, stop=-1, step=-3)
+ self.idx_inc = RangeIndex(start=0, stop=10**6, step=3)
+ self.idx_dec = RangeIndex(start=10**6, stop=-1, step=-3)
def time_max(self):
self.idx_inc.max()
@@ -139,7 +139,7 @@ class Indexing:
param_names = ["dtype"]
def setup(self, dtype):
- N = 10 ** 6
+ N = 10**6
self.idx = getattr(tm, f"make{dtype}Index")(N)
self.array_mask = (np.arange(N) % 3) == 0
self.series_mask = Series(self.array_mask)
@@ -192,7 +192,7 @@ def time_get_loc(self):
class IntervalIndexMethod:
# GH 24813
- params = [10 ** 3, 10 ** 5]
+ params = [10**3, 10**5]
def setup(self, N):
left = np.append(np.arange(N), np.array(0))
diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py
index 58f2a73d82842..1135e1ada1b78 100644
--- a/asv_bench/benchmarks/indexing.py
+++ b/asv_bench/benchmarks/indexing.py
@@ -37,7 +37,7 @@ class NumericSeriesIndexing:
param_names = ["index_dtype", "index_structure"]
def setup(self, index, index_structure):
- N = 10 ** 6
+ N = 10**6
indices = {
"unique_monotonic_inc": index(range(N)),
"nonunique_monotonic_inc": index(
@@ -97,7 +97,7 @@ class NonNumericSeriesIndexing:
param_names = ["index_dtype", "index_structure"]
def setup(self, index, index_structure):
- N = 10 ** 6
+ N = 10**6
if index == "string":
index = tm.makeStringIndex(N)
elif index == "datetime":
@@ -263,7 +263,7 @@ class CategoricalIndexIndexing:
param_names = ["index"]
def setup(self, index):
- N = 10 ** 5
+ N = 10**5
values = list("a" * N + "b" * N + "c" * N)
indices = {
"monotonic_incr": CategoricalIndex(values),
@@ -332,7 +332,7 @@ class IndexSingleRow:
param_names = ["unique_cols"]
def setup(self, unique_cols):
- arr = np.arange(10 ** 7).reshape(-1, 10)
+ arr = np.arange(10**7).reshape(-1, 10)
df = DataFrame(arr)
dtypes = ["u1", "u2", "u4", "u8", "i1", "i2", "i4", "i8", "f8", "f4"]
for i, d in enumerate(dtypes):
@@ -364,7 +364,7 @@ def time_frame_assign_timeseries_index(self):
class InsertColumns:
def setup(self):
- self.N = 10 ** 3
+ self.N = 10**3
self.df = DataFrame(index=range(self.N))
self.df2 = DataFrame(np.random.randn(self.N, 2))
diff --git a/asv_bench/benchmarks/indexing_engines.py b/asv_bench/benchmarks/indexing_engines.py
index 60e07a9d1469c..0c6cb89f49da1 100644
--- a/asv_bench/benchmarks/indexing_engines.py
+++ b/asv_bench/benchmarks/indexing_engines.py
@@ -36,7 +36,7 @@ class NumericEngineIndexing:
_get_numeric_engines(),
["monotonic_incr", "monotonic_decr", "non_monotonic"],
[True, False],
- [10 ** 5, 2 * 10 ** 6], # 2e6 is above SIZE_CUTOFF
+ [10**5, 2 * 10**6], # 2e6 is above SIZE_CUTOFF
]
param_names = ["engine_and_dtype", "index_type", "unique", "N"]
@@ -86,7 +86,7 @@ class ObjectEngineIndexing:
param_names = ["index_type"]
def setup(self, index_type):
- N = 10 ** 5
+ N = 10**5
values = list("a" * N + "b" * N + "c" * N)
arr = {
"monotonic_incr": np.array(values, dtype=object),
diff --git a/asv_bench/benchmarks/inference.py b/asv_bench/benchmarks/inference.py
index a5a7bc5b5c8bd..0bbb599f2b045 100644
--- a/asv_bench/benchmarks/inference.py
+++ b/asv_bench/benchmarks/inference.py
@@ -85,8 +85,8 @@ class MaybeConvertNumeric:
# go in benchmarks/libs.py
def setup_cache(self):
- N = 10 ** 6
- arr = np.repeat([2 ** 63], N) + np.arange(N).astype("uint64")
+ N = 10**6
+ arr = np.repeat([2**63], N) + np.arange(N).astype("uint64")
data = arr.astype(object)
data[1::2] = arr[1::2].astype(str)
data[-1] = -1
@@ -101,7 +101,7 @@ class MaybeConvertObjects:
# does have some run-time imports from outside of _libs
def setup(self):
- N = 10 ** 5
+ N = 10**5
data = list(range(N))
data[0] = NaT
diff --git a/asv_bench/benchmarks/io/csv.py b/asv_bench/benchmarks/io/csv.py
index 0b443b29116a2..10aef954a3475 100644
--- a/asv_bench/benchmarks/io/csv.py
+++ b/asv_bench/benchmarks/io/csv.py
@@ -266,8 +266,8 @@ def time_skipprows(self, skiprows, engine):
class ReadUint64Integers(StringIORewind):
def setup(self):
- self.na_values = [2 ** 63 + 500]
- arr = np.arange(10000).astype("uint64") + 2 ** 63
+ self.na_values = [2**63 + 500]
+ arr = np.arange(10000).astype("uint64") + 2**63
self.data1 = StringIO("\n".join(arr.astype(str).tolist()))
arr = arr.astype(object)
arr[500] = -1
diff --git a/asv_bench/benchmarks/io/json.py b/asv_bench/benchmarks/io/json.py
index d1468a238c491..bb09fe0ff634d 100644
--- a/asv_bench/benchmarks/io/json.py
+++ b/asv_bench/benchmarks/io/json.py
@@ -109,7 +109,7 @@ class ToJSON(BaseIO):
param_names = ["orient", "frame"]
def setup(self, orient, frame):
- N = 10 ** 5
+ N = 10**5
ncols = 5
index = date_range("20000101", periods=N, freq="H")
timedeltas = timedelta_range(start=1, periods=N, freq="s")
@@ -193,7 +193,7 @@ class ToJSONISO(BaseIO):
param_names = ["orient"]
def setup(self, orient):
- N = 10 ** 5
+ N = 10**5
index = date_range("20000101", periods=N, freq="H")
timedeltas = timedelta_range(start=1, periods=N, freq="s")
datetimes = date_range(start=1, periods=N, freq="s")
@@ -216,7 +216,7 @@ class ToJSONLines(BaseIO):
fname = "__test__.json"
def setup(self):
- N = 10 ** 5
+ N = 10**5
ncols = 5
index = date_range("20000101", periods=N, freq="H")
timedeltas = timedelta_range(start=1, periods=N, freq="s")
diff --git a/asv_bench/benchmarks/join_merge.py b/asv_bench/benchmarks/join_merge.py
index ad40adc75c567..dc9b1f501749e 100644
--- a/asv_bench/benchmarks/join_merge.py
+++ b/asv_bench/benchmarks/join_merge.py
@@ -226,7 +226,7 @@ class I8Merge:
param_names = ["how"]
def setup(self, how):
- low, high, n = -1000, 1000, 10 ** 6
+ low, high, n = -1000, 1000, 10**6
self.left = DataFrame(
np.random.randint(low, high, (n, 7)), columns=list("ABCDEFG")
)
@@ -394,8 +394,8 @@ def time_multiby(self, direction, tolerance):
class Align:
def setup(self):
- size = 5 * 10 ** 5
- rng = np.arange(0, 10 ** 13, 10 ** 7)
+ size = 5 * 10**5
+ rng = np.arange(0, 10**13, 10**7)
stamps = np.datetime64("now").view("i8") + rng
idx1 = np.sort(np.random.choice(stamps, size, replace=False))
idx2 = np.sort(np.random.choice(stamps, size, replace=False))
diff --git a/asv_bench/benchmarks/multiindex_object.py b/asv_bench/benchmarks/multiindex_object.py
index 25df5b0214959..e349ae76ba573 100644
--- a/asv_bench/benchmarks/multiindex_object.py
+++ b/asv_bench/benchmarks/multiindex_object.py
@@ -203,7 +203,7 @@ class SetOperations:
param_names = ["index_structure", "dtype", "method"]
def setup(self, index_structure, dtype, method):
- N = 10 ** 5
+ N = 10**5
level1 = range(1000)
level2 = date_range(start="1/1/2000", periods=N // 1000)
diff --git a/asv_bench/benchmarks/replace.py b/asv_bench/benchmarks/replace.py
index 2a115fb0b4fe3..c4c50f5ca8eb5 100644
--- a/asv_bench/benchmarks/replace.py
+++ b/asv_bench/benchmarks/replace.py
@@ -9,7 +9,7 @@ class FillNa:
param_names = ["inplace"]
def setup(self, inplace):
- N = 10 ** 6
+ N = 10**6
rng = pd.date_range("1/1/2000", periods=N, freq="min")
data = np.random.randn(N)
data[::2] = np.nan
@@ -28,10 +28,10 @@ class ReplaceDict:
param_names = ["inplace"]
def setup(self, inplace):
- N = 10 ** 5
- start_value = 10 ** 5
+ N = 10**5
+ start_value = 10**5
self.to_rep = dict(enumerate(np.arange(N) + start_value))
- self.s = pd.Series(np.random.randint(N, size=10 ** 3))
+ self.s = pd.Series(np.random.randint(N, size=10**3))
def time_replace_series(self, inplace):
self.s.replace(self.to_rep, inplace=inplace)
@@ -44,7 +44,7 @@ class ReplaceList:
param_names = ["inplace"]
def setup(self, inplace):
- self.df = pd.DataFrame({"A": 0, "B": 0}, index=range(4 * 10 ** 7))
+ self.df = pd.DataFrame({"A": 0, "B": 0}, index=range(4 * 10**7))
def time_replace_list(self, inplace):
self.df.replace([np.inf, -np.inf], np.nan, inplace=inplace)
@@ -60,7 +60,7 @@ class Convert:
param_names = ["constructor", "replace_data"]
def setup(self, constructor, replace_data):
- N = 10 ** 3
+ N = 10**3
data = {
"Series": pd.Series(np.random.randint(N, size=N)),
"DataFrame": pd.DataFrame(
diff --git a/asv_bench/benchmarks/reshape.py b/asv_bench/benchmarks/reshape.py
index c83cd9a925f6d..7046c8862b0d7 100644
--- a/asv_bench/benchmarks/reshape.py
+++ b/asv_bench/benchmarks/reshape.py
@@ -259,7 +259,7 @@ class Cut:
param_names = ["bins"]
def setup(self, bins):
- N = 10 ** 5
+ N = 10**5
self.int_series = pd.Series(np.arange(N).repeat(5))
self.float_series = pd.Series(np.random.randn(N).repeat(5))
self.timedelta_series = pd.Series(
diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py
index 1c53d4adc8c25..d65a1a39e8bc7 100644
--- a/asv_bench/benchmarks/rolling.py
+++ b/asv_bench/benchmarks/rolling.py
@@ -16,7 +16,7 @@ class Methods:
param_names = ["constructor", "window_kwargs", "dtype", "method"]
def setup(self, constructor, window_kwargs, dtype, method):
- N = 10 ** 5
+ N = 10**5
window, kwargs = window_kwargs
arr = (100 * np.random.random(N)).astype(dtype)
obj = getattr(pd, constructor)(arr)
@@ -40,7 +40,7 @@ class Apply:
param_names = ["constructor", "window", "dtype", "function", "raw"]
def setup(self, constructor, window, dtype, function, raw):
- N = 10 ** 3
+ N = 10**3
arr = (100 * np.random.random(N)).astype(dtype)
self.roll = getattr(pd, constructor)(arr).rolling(window)
@@ -67,7 +67,7 @@ class NumbaEngineMethods:
]
def setup(self, constructor, dtype, window_kwargs, method, parallel, cols):
- N = 10 ** 3
+ N = 10**3
window, kwargs = window_kwargs
shape = (N, cols) if cols is not None and constructor != "Series" else N
arr = (100 * np.random.random(shape)).astype(dtype)
@@ -107,7 +107,7 @@ class NumbaEngineApply:
]
def setup(self, constructor, dtype, window_kwargs, function, parallel, cols):
- N = 10 ** 3
+ N = 10**3
window, kwargs = window_kwargs
shape = (N, cols) if cols is not None and constructor != "Series" else N
arr = (100 * np.random.random(shape)).astype(dtype)
@@ -140,7 +140,7 @@ class EWMMethods:
(
{
"halflife": "1 Day",
- "times": pd.date_range("1900", periods=10 ** 5, freq="23s"),
+ "times": pd.date_range("1900", periods=10**5, freq="23s"),
},
"mean",
),
@@ -150,7 +150,7 @@ class EWMMethods:
param_names = ["constructor", "kwargs_method", "dtype"]
def setup(self, constructor, kwargs_method, dtype):
- N = 10 ** 5
+ N = 10**5
kwargs, method = kwargs_method
arr = (100 * np.random.random(N)).astype(dtype)
self.method = method
@@ -170,7 +170,7 @@ class VariableWindowMethods(Methods):
param_names = ["constructor", "window", "dtype", "method"]
def setup(self, constructor, window, dtype, method):
- N = 10 ** 5
+ N = 10**5
arr = (100 * np.random.random(N)).astype(dtype)
index = pd.date_range("2017-01-01", periods=N, freq="5s")
self.window = getattr(pd, constructor)(arr, index=index).rolling(window)
@@ -186,7 +186,7 @@ class Pairwise:
param_names = ["window_kwargs", "method", "pairwise"]
def setup(self, kwargs_window, method, pairwise):
- N = 10 ** 4
+ N = 10**4
n_groups = 20
kwargs, window = kwargs_window
groups = [i for _ in range(N // n_groups) for i in range(n_groups)]
@@ -215,7 +215,7 @@ class Quantile:
param_names = ["constructor", "window", "dtype", "percentile"]
def setup(self, constructor, window, dtype, percentile, interpolation):
- N = 10 ** 5
+ N = 10**5
arr = np.random.random(N).astype(dtype)
self.roll = getattr(pd, constructor)(arr).rolling(window)
@@ -242,7 +242,7 @@ class Rank:
]
def setup(self, constructor, window, dtype, percentile, ascending, method):
- N = 10 ** 5
+ N = 10**5
arr = np.random.random(N).astype(dtype)
self.roll = getattr(pd, constructor)(arr).rolling(window)
@@ -255,7 +255,7 @@ class PeakMemFixedWindowMinMax:
params = ["min", "max"]
def setup(self, operation):
- N = 10 ** 6
+ N = 10**6
arr = np.random.random(N)
self.roll = pd.Series(arr).rolling(2)
@@ -274,7 +274,7 @@ class ForwardWindowMethods:
param_names = ["constructor", "window_size", "dtype", "method"]
def setup(self, constructor, window_size, dtype, method):
- N = 10 ** 5
+ N = 10**5
arr = np.random.random(N).astype(dtype)
indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=window_size)
self.roll = getattr(pd, constructor)(arr).rolling(window=indexer)
diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py
index d8578ed604ae3..b9907b5281aa7 100644
--- a/asv_bench/benchmarks/series_methods.py
+++ b/asv_bench/benchmarks/series_methods.py
@@ -32,7 +32,7 @@ class ToFrame:
param_names = ["dtype", "name"]
def setup(self, dtype, name):
- arr = np.arange(10 ** 5)
+ arr = np.arange(10**5)
ser = Series(arr, dtype=dtype)
self.ser = ser
@@ -61,7 +61,7 @@ class Dropna:
param_names = ["dtype"]
def setup(self, dtype):
- N = 10 ** 6
+ N = 10**6
data = {
"int": np.random.randint(1, 10, N),
"datetime": date_range("2000-01-01", freq="S", periods=N),
@@ -94,7 +94,7 @@ class SearchSorted:
param_names = ["dtype"]
def setup(self, dtype):
- N = 10 ** 5
+ N = 10**5
data = np.array([1] * N + [2] * N + [3] * N).astype(dtype)
self.s = Series(data)
@@ -130,7 +130,7 @@ def time_map(self, mapper, *args, **kwargs):
class Clip:
- params = [50, 1000, 10 ** 5]
+ params = [50, 1000, 10**5]
param_names = ["n"]
def setup(self, n):
@@ -142,7 +142,7 @@ def time_clip(self, n):
class ValueCounts:
- params = [[10 ** 3, 10 ** 4, 10 ** 5], ["int", "uint", "float", "object"]]
+ params = [[10**3, 10**4, 10**5], ["int", "uint", "float", "object"]]
param_names = ["N", "dtype"]
def setup(self, N, dtype):
@@ -154,7 +154,7 @@ def time_value_counts(self, N, dtype):
class ValueCountsObjectDropNAFalse:
- params = [10 ** 3, 10 ** 4, 10 ** 5]
+ params = [10**3, 10**4, 10**5]
param_names = ["N"]
def setup(self, N):
@@ -166,7 +166,7 @@ def time_value_counts(self, N):
class Mode:
- params = [[10 ** 3, 10 ** 4, 10 ** 5], ["int", "uint", "float", "object"]]
+ params = [[10**3, 10**4, 10**5], ["int", "uint", "float", "object"]]
param_names = ["N", "dtype"]
def setup(self, N, dtype):
@@ -178,7 +178,7 @@ def time_mode(self, N, dtype):
class ModeObjectDropNAFalse:
- params = [10 ** 3, 10 ** 4, 10 ** 5]
+ params = [10**3, 10**4, 10**5]
param_names = ["N"]
def setup(self, N):
@@ -199,7 +199,7 @@ def time_dir_strings(self):
class SeriesGetattr:
# https://github.com/pandas-dev/pandas/issues/19764
def setup(self):
- self.s = Series(1, index=date_range("2012-01-01", freq="s", periods=10 ** 6))
+ self.s = Series(1, index=date_range("2012-01-01", freq="s", periods=10**6))
def time_series_datetimeindex_repr(self):
getattr(self.s, "a", None)
@@ -207,7 +207,7 @@ def time_series_datetimeindex_repr(self):
class All:
- params = [[10 ** 3, 10 ** 6], ["fast", "slow"], ["bool", "boolean"]]
+ params = [[10**3, 10**6], ["fast", "slow"], ["bool", "boolean"]]
param_names = ["N", "case", "dtype"]
def setup(self, N, case, dtype):
@@ -220,7 +220,7 @@ def time_all(self, N, case, dtype):
class Any:
- params = [[10 ** 3, 10 ** 6], ["fast", "slow"], ["bool", "boolean"]]
+ params = [[10**3, 10**6], ["fast", "slow"], ["bool", "boolean"]]
param_names = ["N", "case", "dtype"]
def setup(self, N, case, dtype):
@@ -248,7 +248,7 @@ class NanOps:
"kurt",
"prod",
],
- [10 ** 3, 10 ** 6],
+ [10**3, 10**6],
["int8", "int32", "int64", "float64", "Int64", "boolean"],
]
param_names = ["func", "N", "dtype"]
diff --git a/asv_bench/benchmarks/sparse.py b/asv_bench/benchmarks/sparse.py
index ec704896f5726..ff6bb582e1af5 100644
--- a/asv_bench/benchmarks/sparse.py
+++ b/asv_bench/benchmarks/sparse.py
@@ -40,7 +40,7 @@ class SparseArrayConstructor:
param_names = ["dense_proportion", "fill_value", "dtype"]
def setup(self, dense_proportion, fill_value, dtype):
- N = 10 ** 6
+ N = 10**6
self.array = make_array(N, dense_proportion, fill_value, dtype)
def time_sparse_array(self, dense_proportion, fill_value, dtype):
@@ -111,7 +111,7 @@ class Arithmetic:
param_names = ["dense_proportion", "fill_value"]
def setup(self, dense_proportion, fill_value):
- N = 10 ** 6
+ N = 10**6
arr1 = make_array(N, dense_proportion, fill_value, np.int64)
self.array1 = SparseArray(arr1, fill_value=fill_value)
arr2 = make_array(N, dense_proportion, fill_value, np.int64)
@@ -136,7 +136,7 @@ class ArithmeticBlock:
param_names = ["fill_value"]
def setup(self, fill_value):
- N = 10 ** 6
+ N = 10**6
self.arr1 = self.make_block_array(
length=N, num_blocks=1000, block_size=10, fill_value=fill_value
)
diff --git a/asv_bench/benchmarks/stat_ops.py b/asv_bench/benchmarks/stat_ops.py
index 5639d6702a92c..92a78b7c2f63d 100644
--- a/asv_bench/benchmarks/stat_ops.py
+++ b/asv_bench/benchmarks/stat_ops.py
@@ -83,7 +83,7 @@ class Rank:
param_names = ["constructor", "pct"]
def setup(self, constructor, pct):
- values = np.random.randn(10 ** 5)
+ values = np.random.randn(10**5)
self.data = getattr(pd, constructor)(values)
def time_rank(self, constructor, pct):
diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py
index 32fbf4e6c7de3..3ac59c5883742 100644
--- a/asv_bench/benchmarks/strings.py
+++ b/asv_bench/benchmarks/strings.py
@@ -17,7 +17,7 @@ class Dtypes:
def setup(self, dtype):
try:
- self.s = Series(tm.makeStringIndex(10 ** 5), dtype=dtype)
+ self.s = Series(tm.makeStringIndex(10**5), dtype=dtype)
except ImportError:
raise NotImplementedError
@@ -28,7 +28,7 @@ class Construction:
param_names = ["dtype"]
def setup(self, dtype):
- self.series_arr = tm.rands_array(nchars=10, size=10 ** 5)
+ self.series_arr = tm.rands_array(nchars=10, size=10**5)
self.frame_arr = self.series_arr.reshape((50_000, 2)).copy()
# GH37371. Testing construction of string series/frames from ExtensionArrays
@@ -180,7 +180,7 @@ class Repeat:
param_names = ["repeats"]
def setup(self, repeats):
- N = 10 ** 5
+ N = 10**5
self.s = Series(tm.makeStringIndex(N))
repeat = {"int": 1, "array": np.random.randint(1, 3, N)}
self.values = repeat[repeats]
@@ -195,7 +195,7 @@ class Cat:
param_names = ["other_cols", "sep", "na_rep", "na_frac"]
def setup(self, other_cols, sep, na_rep, na_frac):
- N = 10 ** 5
+ N = 10**5
mask_gen = lambda: np.random.choice([True, False], N, p=[1 - na_frac, na_frac])
self.s = Series(tm.makeStringIndex(N)).where(mask_gen())
if other_cols == 0:
diff --git a/asv_bench/benchmarks/timeseries.py b/asv_bench/benchmarks/timeseries.py
index 5b123c7127c28..9373edadb8e90 100644
--- a/asv_bench/benchmarks/timeseries.py
+++ b/asv_bench/benchmarks/timeseries.py
@@ -131,7 +131,7 @@ class Iteration:
param_names = ["time_index"]
def setup(self, time_index):
- N = 10 ** 6
+ N = 10**6
if time_index is timedelta_range:
self.idx = time_index(start=0, freq="T", periods=N)
else:
@@ -247,7 +247,7 @@ class SortIndex:
param_names = ["monotonic"]
def setup(self, monotonic):
- N = 10 ** 5
+ N = 10**5
idx = date_range(start="1/1/2000", periods=N, freq="s")
self.s = Series(np.random.randn(N), index=idx)
if not monotonic:
diff --git a/asv_bench/benchmarks/tslibs/normalize.py b/asv_bench/benchmarks/tslibs/normalize.py
index f5f7adbf63995..69732018aea9a 100644
--- a/asv_bench/benchmarks/tslibs/normalize.py
+++ b/asv_bench/benchmarks/tslibs/normalize.py
@@ -31,7 +31,7 @@ def setup(self, size, tz):
dti = pd.date_range("2016-01-01", periods=10, tz=tz).repeat(size // 10)
self.i8data = dti.asi8
- if size == 10 ** 6 and tz is tzlocal_obj:
+ if size == 10**6 and tz is tzlocal_obj:
# tzlocal is cumbersomely slow, so skip to keep runtime in check
raise NotImplementedError
diff --git a/asv_bench/benchmarks/tslibs/period.py b/asv_bench/benchmarks/tslibs/period.py
index 15a922da7ee76..6cb1011e3c037 100644
--- a/asv_bench/benchmarks/tslibs/period.py
+++ b/asv_bench/benchmarks/tslibs/period.py
@@ -130,7 +130,7 @@ class TimeDT64ArrToPeriodArr:
param_names = ["size", "freq", "tz"]
def setup(self, size, freq, tz):
- if size == 10 ** 6 and tz is tzlocal_obj:
+ if size == 10**6 and tz is tzlocal_obj:
# tzlocal is cumbersomely slow, so skip to keep runtime in check
raise NotImplementedError
diff --git a/asv_bench/benchmarks/tslibs/resolution.py b/asv_bench/benchmarks/tslibs/resolution.py
index 4b52efc188bf4..44f288c7de216 100644
--- a/asv_bench/benchmarks/tslibs/resolution.py
+++ b/asv_bench/benchmarks/tslibs/resolution.py
@@ -40,7 +40,7 @@ class TimeResolution:
param_names = ["unit", "size", "tz"]
def setup(self, unit, size, tz):
- if size == 10 ** 6 and tz is tzlocal_obj:
+ if size == 10**6 and tz is tzlocal_obj:
# tzlocal is cumbersomely slow, so skip to keep runtime in check
raise NotImplementedError
diff --git a/asv_bench/benchmarks/tslibs/tslib.py b/asv_bench/benchmarks/tslibs/tslib.py
index 180f95e7fbda5..f93ef1cef841f 100644
--- a/asv_bench/benchmarks/tslibs/tslib.py
+++ b/asv_bench/benchmarks/tslibs/tslib.py
@@ -41,7 +41,7 @@
gettz("Asia/Tokyo"),
tzlocal_obj,
]
-_sizes = [0, 1, 100, 10 ** 4, 10 ** 6]
+_sizes = [0, 1, 100, 10**4, 10**6]
class TimeIntsToPydatetime:
@@ -57,7 +57,7 @@ def setup(self, box, size, tz):
if box == "date" and tz is not None:
# tz is ignored, so avoid running redundant benchmarks
raise NotImplementedError # skip benchmark
- if size == 10 ** 6 and tz is _tzs[-1]:
+ if size == 10**6 and tz is _tzs[-1]:
# This is cumbersomely-slow, so skip to trim runtime
raise NotImplementedError # skip benchmark
diff --git a/asv_bench/benchmarks/tslibs/tz_convert.py b/asv_bench/benchmarks/tslibs/tz_convert.py
index 793f43e9bbe35..803c2aaa635b0 100644
--- a/asv_bench/benchmarks/tslibs/tz_convert.py
+++ b/asv_bench/benchmarks/tslibs/tz_convert.py
@@ -25,7 +25,7 @@ class TimeTZConvert:
param_names = ["size", "tz"]
def setup(self, size, tz):
- if size == 10 ** 6 and tz is tzlocal_obj:
+ if size == 10**6 and tz is tzlocal_obj:
# tzlocal is cumbersomely slow, so skip to keep runtime in check
raise NotImplementedError
diff --git a/environment.yml b/environment.yml
index 0a87e2b56f4cb..753e210e6066a 100644
--- a/environment.yml
+++ b/environment.yml
@@ -18,7 +18,7 @@ dependencies:
- cython>=0.29.24
# code checks
- - black=21.5b2
+ - black=22.3.0
- cpplint
- flake8=4.0.1
- flake8-bugbear=21.3.2 # used by flake8, find likely bugs
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index 77e4065008804..4fa9c1aabe716 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -212,7 +212,7 @@ def _get_tol_from_less_precise(check_less_precise: bool | int) -> float:
return 0.5e-5
else:
# Equivalent to setting checking_less_precise=<decimals>
- return 0.5 * 10 ** -check_less_precise
+ return 0.5 * 10**-check_less_precise
def _check_isinstance(left, right, cls):
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py
index 703e67b88fec8..d0d7d6a1b8da6 100644
--- a/pandas/compat/__init__.py
+++ b/pandas/compat/__init__.py
@@ -27,7 +27,7 @@
PY39 = sys.version_info >= (3, 9)
PY310 = sys.version_info >= (3, 10)
PYPY = platform.python_implementation() == "PyPy"
-IS64 = sys.maxsize > 2 ** 32
+IS64 = sys.maxsize > 2**32
def set_function_name(f: F, name: str, cls) -> F:
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 00d5f113e16e0..6843e4f7eeb58 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -1923,8 +1923,8 @@ def to_julian_date(self) -> np.ndarray:
self.hour
+ self.minute / 60
+ self.second / 3600
- + self.microsecond / 3600 / 10 ** 6
- + self.nanosecond / 3600 / 10 ** 9
+ + self.microsecond / 3600 / 10**6
+ + self.nanosecond / 3600 / 10**9
)
/ 24
)
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index bf2d770ee1e7f..dd106b6dbb63c 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -876,7 +876,7 @@ def register_converter_cb(key):
cf.register_option(
"render.max_elements",
- 2 ** 18,
+ 2**18,
styler_max_elements,
validator=is_nonnegative_int,
)
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 40664f178993e..9dcc1c8222791 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -1202,7 +1202,7 @@ def nanskew(
adjusted = values - mean
if skipna and mask is not None:
np.putmask(adjusted, mask, 0)
- adjusted2 = adjusted ** 2
+ adjusted2 = adjusted**2
adjusted3 = adjusted2 * adjusted
m2 = adjusted2.sum(axis, dtype=np.float64)
m3 = adjusted3.sum(axis, dtype=np.float64)
@@ -1215,7 +1215,7 @@ def nanskew(
m3 = _zero_out_fperr(m3)
with np.errstate(invalid="ignore", divide="ignore"):
- result = (count * (count - 1) ** 0.5 / (count - 2)) * (m3 / m2 ** 1.5)
+ result = (count * (count - 1) ** 0.5 / (count - 2)) * (m3 / m2**1.5)
dtype = values.dtype
if is_float_dtype(dtype):
@@ -1290,15 +1290,15 @@ def nankurt(
adjusted = values - mean
if skipna and mask is not None:
np.putmask(adjusted, mask, 0)
- adjusted2 = adjusted ** 2
- adjusted4 = adjusted2 ** 2
+ adjusted2 = adjusted**2
+ adjusted4 = adjusted2**2
m2 = adjusted2.sum(axis, dtype=np.float64)
m4 = adjusted4.sum(axis, dtype=np.float64)
with np.errstate(invalid="ignore", divide="ignore"):
adj = 3 * (count - 1) ** 2 / ((count - 2) * (count - 3))
numerator = count * (count + 1) * (count - 1) * m4
- denominator = (count - 2) * (count - 3) * m2 ** 2
+ denominator = (count - 2) * (count - 3) * m2**2
# floating point error
#
diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py
index 4d5b11546a42f..262cd9774f694 100644
--- a/pandas/core/reshape/melt.py
+++ b/pandas/core/reshape/melt.py
@@ -494,7 +494,7 @@ def wide_to_long(
"""
def get_var_names(df, stub: str, sep: str, suffix: str) -> list[str]:
- regex = fr"^{re.escape(stub)}{re.escape(sep)}{suffix}$"
+ regex = rf"^{re.escape(stub)}{re.escape(sep)}{suffix}$"
pattern = re.compile(regex)
return [col for col in df.columns if pattern.match(col)]
diff --git a/pandas/core/roperator.py b/pandas/core/roperator.py
index e6691ddf8984e..15b16b6fa976a 100644
--- a/pandas/core/roperator.py
+++ b/pandas/core/roperator.py
@@ -45,7 +45,7 @@ def rdivmod(left, right):
def rpow(left, right):
- return right ** left
+ return right**left
def rand_(left, right):
diff --git a/pandas/io/common.py b/pandas/io/common.py
index eaf6f6475ec84..0331d320725ac 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -568,7 +568,7 @@ def check_parent_directory(path: Path | str) -> None:
"""
parent = Path(path).parent
if not parent.is_dir():
- raise OSError(fr"Cannot save file into a non-existent directory: '{parent}'")
+ raise OSError(rf"Cannot save file into a non-existent directory: '{parent}'")
@overload
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index 5992d5d6908ce..53627cc8bd753 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -471,8 +471,8 @@ class ExcelFormatter:
This is only called for body cells.
"""
- max_rows = 2 ** 20
- max_cols = 2 ** 14
+ max_rows = 2**20
+ max_cols = 2**14
def __init__(
self,
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 616331bf80a44..3795fbaab9122 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -1744,7 +1744,7 @@ def is_dates_only(values: np.ndarray | DatetimeArray | Index | DatetimeIndex) ->
values_int = values.asi8
consider_values = values_int != iNaT
- one_day_nanos = 86400 * 10 ** 9
+ one_day_nanos = 86400 * 10**9
even_days = (
np.logical_and(consider_values, values_int % int(one_day_nanos) != 0).sum() == 0
)
@@ -1851,7 +1851,7 @@ def get_format_timedelta64(
consider_values = values_int != iNaT
- one_day_nanos = 86400 * 10 ** 9
+ one_day_nanos = 86400 * 10**9
# error: Unsupported operand types for % ("ExtensionArray" and "int")
not_midnight = values_int % one_day_nanos != 0 # type: ignore[operator]
# error: Argument 1 to "__call__" of "ufunc" has incompatible type
@@ -1962,7 +1962,7 @@ def _trim_zeros_float(
necessary.
"""
trimmed = str_floats
- number_regex = re.compile(fr"^\s*[\+-]?[0-9]+\{decimal}[0-9]*$")
+ number_regex = re.compile(rf"^\s*[\+-]?[0-9]+\{decimal}[0-9]*$")
def is_number_with_decimal(x):
return re.match(number_regex, x) is not None
@@ -2079,7 +2079,7 @@ def __call__(self, num: int | float) -> str:
else:
prefix = f"E+{int_pow10:02d}"
- mant = sign * dnum / (10 ** pow10)
+ mant = sign * dnum / (10**pow10)
if self.accuracy is None: # pragma: no cover
format_str = "{mant: g}{prefix}"
diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index 52fa3be4ff418..04639123c5cfc 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -158,12 +158,12 @@ def __init__(self, f: ReadCsvBuffer[str] | list, **kwds):
decimal = re.escape(self.decimal)
if self.thousands is None:
- regex = fr"^[\-\+]?[0-9]*({decimal}[0-9]*)?([0-9]?(E|e)\-?[0-9]+)?$"
+ regex = rf"^[\-\+]?[0-9]*({decimal}[0-9]*)?([0-9]?(E|e)\-?[0-9]+)?$"
else:
thousands = re.escape(self.thousands)
regex = (
- fr"^[\-\+]?([0-9]+{thousands}|[0-9])*({decimal}[0-9]*)?"
- fr"([0-9]?(E|e)\-?[0-9]+)?$"
+ rf"^[\-\+]?([0-9]+{thousands}|[0-9])*({decimal}[0-9]*)?"
+ rf"([0-9]?(E|e)\-?[0-9]+)?$"
)
self.num = re.compile(regex)
@@ -1209,7 +1209,7 @@ def detect_colspecs(
self, infer_nrows: int = 100, skiprows: set[int] | None = None
) -> list[tuple[int, int]]:
# Regex escape the delimiters
- delimiters = "".join([fr"\{x}" for x in self.delimiter])
+ delimiters = "".join([rf"\{x}" for x in self.delimiter])
pattern = re.compile(f"([^{delimiters}]+)")
rows = self.get_rows(infer_nrows, skiprows)
if not rows:
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 4a50a3dabe5e7..b4b4291af59c1 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -605,7 +605,7 @@ def _cast_to_stata_types(data: DataFrame) -> DataFrame:
else:
dtype = c_data[2]
if c_data[2] == np.int64: # Warn if necessary
- if data[col].max() >= 2 ** 53:
+ if data[col].max() >= 2**53:
ws = precision_loss_doc.format("uint64", "float64")
data[col] = data[col].astype(dtype)
@@ -622,7 +622,7 @@ def _cast_to_stata_types(data: DataFrame) -> DataFrame:
data[col] = data[col].astype(np.int32)
else:
data[col] = data[col].astype(np.float64)
- if data[col].max() >= 2 ** 53 or data[col].min() <= -(2 ** 53):
+ if data[col].max() >= 2**53 or data[col].min() <= -(2**53):
ws = precision_loss_doc.format("int64", "float64")
elif dtype in (np.float32, np.float64):
value = data[col].max()
diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py
index 90d3f8d9836bf..8216374732aff 100644
--- a/pandas/plotting/_matplotlib/converter.py
+++ b/pandas/plotting/_matplotlib/converter.py
@@ -63,7 +63,7 @@
SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR
SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY
-MUSEC_PER_DAY = 10 ** 6 * SEC_PER_DAY
+MUSEC_PER_DAY = 10**6 * SEC_PER_DAY
_mpl_units = {} # Cache for units overwritten by us
@@ -141,7 +141,7 @@ def deregister():
def _to_ordinalf(tm: pydt.time) -> float:
- tot_sec = tm.hour * 3600 + tm.minute * 60 + tm.second + tm.microsecond / 10 ** 6
+ tot_sec = tm.hour * 3600 + tm.minute * 60 + tm.second + tm.microsecond / 10**6
return tot_sec
@@ -207,7 +207,7 @@ def __call__(self, x, pos=0) -> str:
"""
fmt = "%H:%M:%S.%f"
s = int(x)
- msus = round((x - s) * 10 ** 6)
+ msus = round((x - s) * 10**6)
ms = msus // 1000
us = msus % 1000
m, s = divmod(s, 60)
@@ -1084,7 +1084,7 @@ def format_timedelta_ticks(x, pos, n_decimals: int) -> str:
"""
Convert seconds to 'D days HH:MM:SS.F'
"""
- s, ns = divmod(x, 10 ** 9)
+ s, ns = divmod(x, 10**9)
m, s = divmod(s, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
@@ -1098,7 +1098,7 @@ def format_timedelta_ticks(x, pos, n_decimals: int) -> str:
def __call__(self, x, pos=0) -> str:
(vmin, vmax) = tuple(self.axis.get_view_interval())
- n_decimals = int(np.ceil(np.log10(100 * 10 ** 9 / abs(vmax - vmin))))
+ n_decimals = int(np.ceil(np.log10(100 * 10**9 / abs(vmax - vmin))))
if n_decimals > 9:
n_decimals = 9
return self.format_timedelta_ticks(x, pos, n_decimals)
diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py
index 5314a61191d78..7bd90a4e4d908 100644
--- a/pandas/plotting/_matplotlib/tools.py
+++ b/pandas/plotting/_matplotlib/tools.py
@@ -117,7 +117,7 @@ def _get_layout(nplots: int, layout=None, layout_type: str = "box") -> tuple[int
return layouts[nplots]
except KeyError:
k = 1
- while k ** 2 < nplots:
+ while k**2 < nplots:
k += 1
if (k - 1) * k >= nplots:
diff --git a/pandas/tests/apply/test_series_apply.py b/pandas/tests/apply/test_series_apply.py
index b7084e2bc6dc7..3b6bdeea3b3c8 100644
--- a/pandas/tests/apply/test_series_apply.py
+++ b/pandas/tests/apply/test_series_apply.py
@@ -378,11 +378,11 @@ def test_agg_apply_evaluate_lambdas_the_same(string_series):
def test_with_nested_series(datetime_series):
# GH 2316
# .agg with a reducer and a transform, what to do
- result = datetime_series.apply(lambda x: Series([x, x ** 2], index=["x", "x^2"]))
- expected = DataFrame({"x": datetime_series, "x^2": datetime_series ** 2})
+ result = datetime_series.apply(lambda x: Series([x, x**2], index=["x", "x^2"]))
+ expected = DataFrame({"x": datetime_series, "x^2": datetime_series**2})
tm.assert_frame_equal(result, expected)
- result = datetime_series.agg(lambda x: Series([x, x ** 2], index=["x", "x^2"]))
+ result = datetime_series.agg(lambda x: Series([x, x**2], index=["x", "x^2"]))
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index bc7a929ecaa4a..22d20d7fe2356 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -120,12 +120,12 @@ def test_numeric_cmp_string_numexpr_path(self, box_with_array):
box = box_with_array
xbox = box if box is not Index else np.ndarray
- obj = Series(np.random.randn(10 ** 5))
+ obj = Series(np.random.randn(10**5))
obj = tm.box_expected(obj, box, transpose=False)
result = obj == "a"
- expected = Series(np.zeros(10 ** 5, dtype=bool))
+ expected = Series(np.zeros(10**5, dtype=bool))
expected = tm.box_expected(expected, xbox, transpose=False)
tm.assert_equal(result, expected)
@@ -231,7 +231,7 @@ def test_numeric_arr_mul_tdscalar_numexpr_path(
# GH#44772 for the float64 case
box = box_with_array
- arr_i8 = np.arange(2 * 10 ** 4).astype(np.int64, copy=False)
+ arr_i8 = np.arange(2 * 10**4).astype(np.int64, copy=False)
arr = arr_i8.astype(dtype, copy=False)
obj = tm.box_expected(arr, box, transpose=False)
@@ -676,7 +676,7 @@ def test_mul_index(self, numeric_idx):
idx = numeric_idx
result = idx * idx
- tm.assert_index_equal(result, idx ** 2)
+ tm.assert_index_equal(result, idx**2)
def test_mul_datelike_raises(self, numeric_idx):
idx = numeric_idx
@@ -775,7 +775,7 @@ def test_operators_frame(self):
df = pd.DataFrame({"A": ts})
tm.assert_series_equal(ts + ts, ts + df["A"], check_names=False)
- tm.assert_series_equal(ts ** ts, ts ** df["A"], check_names=False)
+ tm.assert_series_equal(ts**ts, ts ** df["A"], check_names=False)
tm.assert_series_equal(ts < ts, ts < df["A"], check_names=False)
tm.assert_series_equal(ts / ts, ts / df["A"], check_names=False)
@@ -1269,7 +1269,7 @@ def test_numeric_compat2(self):
# __pow__
idx = RangeIndex(0, 1000, 2)
- result = idx ** 2
+ result = idx**2
expected = Int64Index(idx._values) ** 2
tm.assert_index_equal(Index(result.values), expected, exact=True)
@@ -1393,7 +1393,7 @@ def test_sub_multiindex_swapped_levels():
@pytest.mark.parametrize("string_size", [0, 1, 2, 5])
def test_empty_str_comparison(power, string_size):
# GH 37348
- a = np.array(range(10 ** power))
+ a = np.array(range(10**power))
right = pd.DataFrame(a, dtype=np.int64)
left = " " * string_size
diff --git a/pandas/tests/arithmetic/test_object.py b/pandas/tests/arithmetic/test_object.py
index c96d7c01ec97f..e107ff6b65c0f 100644
--- a/pandas/tests/arithmetic/test_object.py
+++ b/pandas/tests/arithmetic/test_object.py
@@ -80,12 +80,12 @@ def test_pow_ops_object(self):
# pow is weird with masking & 1, so testing here
a = Series([1, np.nan, 1, np.nan], dtype=object)
b = Series([1, np.nan, np.nan, 1], dtype=object)
- result = a ** b
- expected = Series(a.values ** b.values, dtype=object)
+ result = a**b
+ expected = Series(a.values**b.values, dtype=object)
tm.assert_series_equal(result, expected)
- result = b ** a
- expected = Series(b.values ** a.values, dtype=object)
+ result = b**a
+ expected = Series(b.values**a.values, dtype=object)
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index 543531889531a..3bc38c3e38213 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -1474,7 +1474,7 @@ def test_tdi_mul_int_array_zerodim(self, box_with_array):
def test_tdi_mul_int_array(self, box_with_array):
rng5 = np.arange(5, dtype="int64")
idx = TimedeltaIndex(rng5)
- expected = TimedeltaIndex(rng5 ** 2)
+ expected = TimedeltaIndex(rng5**2)
idx = tm.box_expected(idx, box_with_array)
expected = tm.box_expected(expected, box_with_array)
@@ -2089,10 +2089,10 @@ def test_td64arr_pow_invalid(self, scalar_td, box_with_array):
# defined
pattern = "operate|unsupported|cannot|not supported"
with pytest.raises(TypeError, match=pattern):
- scalar_td ** td1
+ scalar_td**td1
with pytest.raises(TypeError, match=pattern):
- td1 ** scalar_td
+ td1**scalar_td
def test_add_timestamp_to_timedelta():
diff --git a/pandas/tests/arrays/datetimes/test_constructors.py b/pandas/tests/arrays/datetimes/test_constructors.py
index e6c65499f6fcc..ed285f2389959 100644
--- a/pandas/tests/arrays/datetimes/test_constructors.py
+++ b/pandas/tests/arrays/datetimes/test_constructors.py
@@ -29,7 +29,7 @@ def test_only_1dim_accepted(self):
def test_freq_validation(self):
# GH#24623 check that invalid instances cannot be created with the
# public constructor
- arr = np.arange(5, dtype=np.int64) * 3600 * 10 ** 9
+ arr = np.arange(5, dtype=np.int64) * 3600 * 10**9
msg = (
"Inferred frequency H from passed values does not "
@@ -64,7 +64,7 @@ def test_mixing_naive_tzaware_raises(self, meth):
meth(obj)
def test_from_pandas_array(self):
- arr = pd.array(np.arange(5, dtype=np.int64)) * 3600 * 10 ** 9
+ arr = pd.array(np.arange(5, dtype=np.int64)) * 3600 * 10**9
result = DatetimeArray._from_sequence(arr)._with_freq("infer")
diff --git a/pandas/tests/arrays/floating/test_arithmetic.py b/pandas/tests/arrays/floating/test_arithmetic.py
index e5f67a2dce3ad..7776e00c201ac 100644
--- a/pandas/tests/arrays/floating/test_arithmetic.py
+++ b/pandas/tests/arrays/floating/test_arithmetic.py
@@ -51,19 +51,19 @@ def test_divide_by_zero(dtype, zero, negative):
def test_pow_scalar(dtype):
a = pd.array([-1, 0, 1, None, 2], dtype=dtype)
- result = a ** 0
+ result = a**0
expected = pd.array([1, 1, 1, 1, 1], dtype=dtype)
tm.assert_extension_array_equal(result, expected)
- result = a ** 1
+ result = a**1
expected = pd.array([-1, 0, 1, None, 2], dtype=dtype)
tm.assert_extension_array_equal(result, expected)
- result = a ** pd.NA
+ result = a**pd.NA
expected = pd.array([None, None, 1, None, None], dtype=dtype)
tm.assert_extension_array_equal(result, expected)
- result = a ** np.nan
+ result = a**np.nan
# TODO np.nan should be converted to pd.NA / missing before operation?
expected = FloatingArray(
np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype=dtype.numpy_dtype),
@@ -74,19 +74,19 @@ def test_pow_scalar(dtype):
# reversed
a = a[1:] # Can't raise integers to negative powers.
- result = 0 ** a
+ result = 0**a
expected = pd.array([1, 0, None, 0], dtype=dtype)
tm.assert_extension_array_equal(result, expected)
- result = 1 ** a
+ result = 1**a
expected = pd.array([1, 1, 1, 1], dtype=dtype)
tm.assert_extension_array_equal(result, expected)
- result = pd.NA ** a
+ result = pd.NA**a
expected = pd.array([1, None, None, None], dtype=dtype)
tm.assert_extension_array_equal(result, expected)
- result = np.nan ** a
+ result = np.nan**a
expected = FloatingArray(
np.array([1, np.nan, np.nan, np.nan], dtype=dtype.numpy_dtype), mask=a._mask
)
@@ -96,7 +96,7 @@ def test_pow_scalar(dtype):
def test_pow_array(dtype):
a = pd.array([0, 0, 0, 1, 1, 1, None, None, None], dtype=dtype)
b = pd.array([0, 1, None, 0, 1, None, 0, 1, None], dtype=dtype)
- result = a ** b
+ result = a**b
expected = pd.array([1, 0, None, 1, 1, 1, 1, None, None], dtype=dtype)
tm.assert_extension_array_equal(result, expected)
diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py
index 273bd9e4d34d5..bbaa95c8fa5a7 100644
--- a/pandas/tests/arrays/integer/test_arithmetic.py
+++ b/pandas/tests/arrays/integer/test_arithmetic.py
@@ -88,19 +88,19 @@ def test_mod(dtype):
def test_pow_scalar():
a = pd.array([-1, 0, 1, None, 2], dtype="Int64")
- result = a ** 0
+ result = a**0
expected = pd.array([1, 1, 1, 1, 1], dtype="Int64")
tm.assert_extension_array_equal(result, expected)
- result = a ** 1
+ result = a**1
expected = pd.array([-1, 0, 1, None, 2], dtype="Int64")
tm.assert_extension_array_equal(result, expected)
- result = a ** pd.NA
+ result = a**pd.NA
expected = pd.array([None, None, 1, None, None], dtype="Int64")
tm.assert_extension_array_equal(result, expected)
- result = a ** np.nan
+ result = a**np.nan
expected = FloatingArray(
np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype="float64"),
np.array([False, False, False, True, False]),
@@ -110,19 +110,19 @@ def test_pow_scalar():
# reversed
a = a[1:] # Can't raise integers to negative powers.
- result = 0 ** a
+ result = 0**a
expected = pd.array([1, 0, None, 0], dtype="Int64")
tm.assert_extension_array_equal(result, expected)
- result = 1 ** a
+ result = 1**a
expected = pd.array([1, 1, 1, 1], dtype="Int64")
tm.assert_extension_array_equal(result, expected)
- result = pd.NA ** a
+ result = pd.NA**a
expected = pd.array([1, None, None, None], dtype="Int64")
tm.assert_extension_array_equal(result, expected)
- result = np.nan ** a
+ result = np.nan**a
expected = FloatingArray(
np.array([1, np.nan, np.nan, np.nan], dtype="float64"),
np.array([False, False, True, False]),
@@ -133,7 +133,7 @@ def test_pow_scalar():
def test_pow_array():
a = pd.array([0, 0, 0, 1, 1, 1, None, None, None])
b = pd.array([0, 1, None, 0, 1, None, 0, 1, None])
- result = a ** b
+ result = a**b
expected = pd.array([1, 0, None, 1, 1, 1, 1, None, None])
tm.assert_extension_array_equal(result, expected)
diff --git a/pandas/tests/arrays/integer/test_dtypes.py b/pandas/tests/arrays/integer/test_dtypes.py
index 3911b7f9bad34..2bb6e36bf57b2 100644
--- a/pandas/tests/arrays/integer/test_dtypes.py
+++ b/pandas/tests/arrays/integer/test_dtypes.py
@@ -217,7 +217,7 @@ def test_astype_floating():
def test_astype_dt64():
# GH#32435
- arr = pd.array([1, 2, 3, pd.NA]) * 10 ** 9
+ arr = pd.array([1, 2, 3, pd.NA]) * 10**9
result = arr.astype("datetime64[ns]")
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py
index 7484fdccf4937..56dc3363a7f52 100644
--- a/pandas/tests/arrays/test_datetimelike.py
+++ b/pandas/tests/arrays/test_datetimelike.py
@@ -81,7 +81,7 @@ class SharedTests:
@pytest.fixture
def arr1d(self):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
return arr
@@ -148,7 +148,7 @@ def test_compare_categorical_dtype(self, arr1d, as_index, reverse, ordered):
tm.assert_numpy_array_equal(result, ones)
def test_take(self):
- data = np.arange(100, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(100, dtype="i8") * 24 * 3600 * 10**9
np.random.shuffle(data)
freq = None if self.array_cls is not PeriodArray else "D"
@@ -170,7 +170,7 @@ def test_take(self):
@pytest.mark.parametrize("fill_value", [2, 2.0, Timestamp(2021, 1, 1, 12).time])
def test_take_fill_raises(self, fill_value):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
@@ -179,7 +179,7 @@ def test_take_fill_raises(self, fill_value):
arr.take([0, 1], allow_fill=True, fill_value=fill_value)
def test_take_fill(self):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
@@ -215,7 +215,7 @@ def test_concat_same_type(self, arr1d):
tm.assert_index_equal(self.index_cls(result), expected)
def test_unbox_scalar(self):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
result = arr._unbox_scalar(arr[0])
expected = arr._data.dtype.type
@@ -229,7 +229,7 @@ def test_unbox_scalar(self):
arr._unbox_scalar("foo")
def test_check_compatible_with(self):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
arr._check_compatible_with(arr[0])
@@ -237,13 +237,13 @@ def test_check_compatible_with(self):
arr._check_compatible_with(NaT)
def test_scalar_from_string(self):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
result = arr._scalar_from_string(str(arr[0]))
assert result == arr[0]
def test_reduce_invalid(self):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
msg = "does not support reduction 'not a method'"
@@ -252,7 +252,7 @@ def test_reduce_invalid(self):
@pytest.mark.parametrize("method", ["pad", "backfill"])
def test_fillna_method_doesnt_change_orig(self, method):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
arr[4] = NaT
@@ -265,7 +265,7 @@ def test_fillna_method_doesnt_change_orig(self, method):
assert arr[4] is NaT
def test_searchsorted(self):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
# scalar
@@ -415,11 +415,11 @@ def test_repr_2d(self, arr1d):
assert result == expected
def test_setitem(self):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
arr[0] = arr[1]
- expected = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ expected = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
expected[0] = expected[1]
tm.assert_numpy_array_equal(arr.asi8, expected)
@@ -504,7 +504,7 @@ def test_setitem_categorical(self, arr1d, as_index):
tm.assert_equal(arr1d, expected)
def test_setitem_raises(self):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
val = arr[0]
@@ -540,7 +540,7 @@ def test_setitem_numeric_raises(self, arr1d, box):
def test_inplace_arithmetic(self):
# GH#24115 check that iadd and isub are actually in-place
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
expected = arr + pd.Timedelta(days=1)
@@ -553,7 +553,7 @@ def test_inplace_arithmetic(self):
def test_shift_fill_int_deprecated(self):
# GH#31971
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = self.array_cls(data, freq="D")
msg = "Passing <class 'int'> to shift"
diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py
index 73b4e7c19dc2e..ad75c137ec703 100644
--- a/pandas/tests/arrays/test_datetimes.py
+++ b/pandas/tests/arrays/test_datetimes.py
@@ -280,7 +280,7 @@ def test_array_interface(self):
@pytest.mark.parametrize("index", [True, False])
def test_searchsorted_different_tz(self, index):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = DatetimeArray(data, freq="D").tz_localize("Asia/Tokyo")
if index:
arr = pd.Index(arr)
@@ -295,7 +295,7 @@ def test_searchsorted_different_tz(self, index):
@pytest.mark.parametrize("index", [True, False])
def test_searchsorted_tzawareness_compat(self, index):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = DatetimeArray(data, freq="D")
if index:
arr = pd.Index(arr)
@@ -322,14 +322,14 @@ def test_searchsorted_tzawareness_compat(self, index):
np.timedelta64("NaT"),
pd.Timedelta(days=2),
"invalid",
- np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9,
- np.arange(10).view("timedelta64[ns]") * 24 * 3600 * 10 ** 9,
+ np.arange(10, dtype="i8") * 24 * 3600 * 10**9,
+ np.arange(10).view("timedelta64[ns]") * 24 * 3600 * 10**9,
pd.Timestamp("2021-01-01").to_period("D"),
],
)
@pytest.mark.parametrize("index", [True, False])
def test_searchsorted_invalid_types(self, other, index):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = DatetimeArray(data, freq="D")
if index:
arr = pd.Index(arr)
diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py
index 1db0f6ad56ce3..675c6ac8c9233 100644
--- a/pandas/tests/arrays/test_timedeltas.py
+++ b/pandas/tests/arrays/test_timedeltas.py
@@ -52,14 +52,14 @@ def test_setitem_objects(self, obj):
np.datetime64("NaT"),
pd.Timestamp("2021-01-01"),
"invalid",
- np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9,
- (np.arange(10) * 24 * 3600 * 10 ** 9).view("datetime64[ns]"),
+ np.arange(10, dtype="i8") * 24 * 3600 * 10**9,
+ (np.arange(10) * 24 * 3600 * 10**9).view("datetime64[ns]"),
pd.Timestamp("2021-01-01").to_period("D"),
],
)
@pytest.mark.parametrize("index", [True, False])
def test_searchsorted_invalid_types(self, other, index):
- data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
+ data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9
arr = TimedeltaArray(data, freq="D")
if index:
arr = pd.Index(arr)
@@ -76,10 +76,10 @@ def test_searchsorted_invalid_types(self, other, index):
class TestUnaryOps:
def test_abs(self):
- vals = np.array([-3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]")
+ vals = np.array([-3600 * 10**9, "NaT", 7200 * 10**9], dtype="m8[ns]")
arr = TimedeltaArray(vals)
- evals = np.array([3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]")
+ evals = np.array([3600 * 10**9, "NaT", 7200 * 10**9], dtype="m8[ns]")
expected = TimedeltaArray(evals)
result = abs(arr)
@@ -89,7 +89,7 @@ def test_abs(self):
tm.assert_timedelta_array_equal(result2, expected)
def test_pos(self):
- vals = np.array([-3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]")
+ vals = np.array([-3600 * 10**9, "NaT", 7200 * 10**9], dtype="m8[ns]")
arr = TimedeltaArray(vals)
result = +arr
@@ -101,10 +101,10 @@ def test_pos(self):
assert not tm.shares_memory(result2, arr)
def test_neg(self):
- vals = np.array([-3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]")
+ vals = np.array([-3600 * 10**9, "NaT", 7200 * 10**9], dtype="m8[ns]")
arr = TimedeltaArray(vals)
- evals = np.array([3600 * 10 ** 9, "NaT", -7200 * 10 ** 9], dtype="m8[ns]")
+ evals = np.array([3600 * 10**9, "NaT", -7200 * 10**9], dtype="m8[ns]")
expected = TimedeltaArray(evals)
result = -arr
diff --git a/pandas/tests/arrays/timedeltas/test_constructors.py b/pandas/tests/arrays/timedeltas/test_constructors.py
index d297e745f107b..d24fabfeecb26 100644
--- a/pandas/tests/arrays/timedeltas/test_constructors.py
+++ b/pandas/tests/arrays/timedeltas/test_constructors.py
@@ -19,7 +19,7 @@ def test_only_1dim_accepted(self):
def test_freq_validation(self):
# ensure that the public constructor cannot create an invalid instance
- arr = np.array([0, 0, 1], dtype=np.int64) * 3600 * 10 ** 9
+ arr = np.array([0, 0, 1], dtype=np.int64) * 3600 * 10**9
msg = (
"Inferred frequency None from passed values does not "
diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py
index 84e4992cce0e3..216c9b1546b9d 100644
--- a/pandas/tests/base/test_conversion.py
+++ b/pandas/tests/base/test_conversion.py
@@ -199,7 +199,7 @@ def test_iter_box(self):
"datetime64[ns]",
),
(
- pd.TimedeltaIndex([10 ** 10]),
+ pd.TimedeltaIndex([10**10]),
TimedeltaArray,
"m8[ns]",
),
diff --git a/pandas/tests/dtypes/cast/test_can_hold_element.py b/pandas/tests/dtypes/cast/test_can_hold_element.py
index 906123b1aee74..06d256c57a631 100644
--- a/pandas/tests/dtypes/cast/test_can_hold_element.py
+++ b/pandas/tests/dtypes/cast/test_can_hold_element.py
@@ -33,11 +33,11 @@ def test_can_hold_element_range(any_int_numpy_dtype):
assert can_hold_element(arr, rng)
# empty
- rng = range(-(10 ** 10), -(10 ** 10))
+ rng = range(-(10**10), -(10**10))
assert len(rng) == 0
# assert can_hold_element(arr, rng)
- rng = range(10 ** 10, 10 ** 10)
+ rng = range(10**10, 10**10)
assert len(rng) == 0
assert can_hold_element(arr, rng)
@@ -51,7 +51,7 @@ def test_can_hold_element_int_values_float_ndarray():
assert not can_hold_element(arr, element + 0.5)
# integer but not losslessly castable to int64
- element = np.array([3, 2 ** 65], dtype=np.float64)
+ element = np.array([3, 2**65], dtype=np.float64)
assert not can_hold_element(arr, element)
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 7953d650636be..b4113d877836b 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -594,25 +594,25 @@ def test_convert_non_hashable(self):
tm.assert_numpy_array_equal(result, np.array([np.nan, 1.0, np.nan]))
def test_convert_numeric_uint64(self):
- arr = np.array([2 ** 63], dtype=object)
- exp = np.array([2 ** 63], dtype=np.uint64)
+ arr = np.array([2**63], dtype=object)
+ exp = np.array([2**63], dtype=np.uint64)
tm.assert_numpy_array_equal(lib.maybe_convert_numeric(arr, set())[0], exp)
- arr = np.array([str(2 ** 63)], dtype=object)
- exp = np.array([2 ** 63], dtype=np.uint64)
+ arr = np.array([str(2**63)], dtype=object)
+ exp = np.array([2**63], dtype=np.uint64)
tm.assert_numpy_array_equal(lib.maybe_convert_numeric(arr, set())[0], exp)
- arr = np.array([np.uint64(2 ** 63)], dtype=object)
- exp = np.array([2 ** 63], dtype=np.uint64)
+ arr = np.array([np.uint64(2**63)], dtype=object)
+ exp = np.array([2**63], dtype=np.uint64)
tm.assert_numpy_array_equal(lib.maybe_convert_numeric(arr, set())[0], exp)
@pytest.mark.parametrize(
"arr",
[
- np.array([2 ** 63, np.nan], dtype=object),
- np.array([str(2 ** 63), np.nan], dtype=object),
- np.array([np.nan, 2 ** 63], dtype=object),
- np.array([np.nan, str(2 ** 63)], dtype=object),
+ np.array([2**63, np.nan], dtype=object),
+ np.array([str(2**63), np.nan], dtype=object),
+ np.array([np.nan, 2**63], dtype=object),
+ np.array([np.nan, str(2**63)], dtype=object),
],
)
def test_convert_numeric_uint64_nan(self, coerce, arr):
@@ -624,11 +624,11 @@ def test_convert_numeric_uint64_nan(self, coerce, arr):
def test_convert_numeric_uint64_nan_values(
self, coerce, convert_to_masked_nullable
):
- arr = np.array([2 ** 63, 2 ** 63 + 1], dtype=object)
- na_values = {2 ** 63}
+ arr = np.array([2**63, 2**63 + 1], dtype=object)
+ na_values = {2**63}
expected = (
- np.array([np.nan, 2 ** 63 + 1], dtype=float) if coerce else arr.copy()
+ np.array([np.nan, 2**63 + 1], dtype=float) if coerce else arr.copy()
)
result = lib.maybe_convert_numeric(
arr,
@@ -638,7 +638,7 @@ def test_convert_numeric_uint64_nan_values(
)
if convert_to_masked_nullable and coerce:
expected = IntegerArray(
- np.array([0, 2 ** 63 + 1], dtype="u8"),
+ np.array([0, 2**63 + 1], dtype="u8"),
np.array([True, False], dtype="bool"),
)
result = IntegerArray(*result)
@@ -649,12 +649,12 @@ def test_convert_numeric_uint64_nan_values(
@pytest.mark.parametrize(
"case",
[
- np.array([2 ** 63, -1], dtype=object),
- np.array([str(2 ** 63), -1], dtype=object),
- np.array([str(2 ** 63), str(-1)], dtype=object),
- np.array([-1, 2 ** 63], dtype=object),
- np.array([-1, str(2 ** 63)], dtype=object),
- np.array([str(-1), str(2 ** 63)], dtype=object),
+ np.array([2**63, -1], dtype=object),
+ np.array([str(2**63), -1], dtype=object),
+ np.array([str(2**63), str(-1)], dtype=object),
+ np.array([-1, 2**63], dtype=object),
+ np.array([-1, str(2**63)], dtype=object),
+ np.array([str(-1), str(2**63)], dtype=object),
],
)
@pytest.mark.parametrize("convert_to_masked_nullable", [True, False])
@@ -686,7 +686,7 @@ def test_convert_numeric_string_uint64(self, convert_to_masked_nullable):
result = result[0]
assert np.isnan(result)
- @pytest.mark.parametrize("value", [-(2 ** 63) - 1, 2 ** 64])
+ @pytest.mark.parametrize("value", [-(2**63) - 1, 2**64])
def test_convert_int_overflow(self, value):
# see gh-18584
arr = np.array([value], dtype=object)
@@ -695,23 +695,23 @@ def test_convert_int_overflow(self, value):
def test_maybe_convert_objects_uint64(self):
# see gh-4471
- arr = np.array([2 ** 63], dtype=object)
- exp = np.array([2 ** 63], dtype=np.uint64)
+ arr = np.array([2**63], dtype=object)
+ exp = np.array([2**63], dtype=np.uint64)
tm.assert_numpy_array_equal(lib.maybe_convert_objects(arr), exp)
# NumPy bug: can't compare uint64 to int64, as that
# results in both casting to float64, so we should
# make sure that this function is robust against it
- arr = np.array([np.uint64(2 ** 63)], dtype=object)
- exp = np.array([2 ** 63], dtype=np.uint64)
+ arr = np.array([np.uint64(2**63)], dtype=object)
+ exp = np.array([2**63], dtype=np.uint64)
tm.assert_numpy_array_equal(lib.maybe_convert_objects(arr), exp)
arr = np.array([2, -1], dtype=object)
exp = np.array([2, -1], dtype=np.int64)
tm.assert_numpy_array_equal(lib.maybe_convert_objects(arr), exp)
- arr = np.array([2 ** 63, -1], dtype=object)
- exp = np.array([2 ** 63, -1], dtype=object)
+ arr = np.array([2**63, -1], dtype=object)
+ exp = np.array([2**63, -1], dtype=object)
tm.assert_numpy_array_equal(lib.maybe_convert_objects(arr), exp)
def test_maybe_convert_objects_datetime(self):
diff --git a/pandas/tests/frame/conftest.py b/pandas/tests/frame/conftest.py
index b512664b57ade..8dbed84b85837 100644
--- a/pandas/tests/frame/conftest.py
+++ b/pandas/tests/frame/conftest.py
@@ -212,7 +212,7 @@ def uint64_frame():
Columns are ['A', 'B']
"""
return DataFrame(
- {"A": np.arange(3), "B": [2 ** 63, 2 ** 63 + 5, 2 ** 63 + 10]}, dtype=np.uint64
+ {"A": np.arange(3), "B": [2**63, 2**63 + 5, 2**63 + 10]}, dtype=np.uint64
)
diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py
index 9b6e04dffa6ce..22d8d13b77f72 100644
--- a/pandas/tests/frame/indexing/test_where.py
+++ b/pandas/tests/frame/indexing/test_where.py
@@ -721,7 +721,7 @@ def test_where_datetimelike_noop(self, dtype):
# GH#45135, analogue to GH#44181 for Period don't raise on no-op
# For td64/dt64/dt64tz we already don't raise, but also are
# checking that we don't unnecessarily upcast to object.
- ser = Series(np.arange(3) * 10 ** 9, dtype=np.int64).view(dtype)
+ ser = Series(np.arange(3) * 10**9, dtype=np.int64).view(dtype)
df = ser.to_frame()
mask = np.array([False, False, False])
@@ -761,9 +761,9 @@ def test_where_int_downcasting_deprecated(using_array_manager):
msg = "Downcasting integer-dtype"
warn = FutureWarning if not using_array_manager else None
with tm.assert_produces_warning(warn, match=msg):
- res = df.where(mask, 2 ** 17)
+ res = df.where(mask, 2**17)
- expected = DataFrame({0: arr[:, 0], 1: np.array([2 ** 17] * 3, dtype=np.int32)})
+ expected = DataFrame({0: arr[:, 0], 1: np.array([2**17] * 3, dtype=np.int32)})
tm.assert_frame_equal(res, expected)
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index d326ca3493977..bc297ebb56b48 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -455,10 +455,10 @@ def test_astype_to_incorrect_datetimelike(self, unit):
msg = "|".join(
[
# BlockManager path
- fr"Cannot cast DatetimeArray to dtype timedelta64\[{unit}\]",
+ rf"Cannot cast DatetimeArray to dtype timedelta64\[{unit}\]",
# ArrayManager path
"cannot astype a datetimelike from "
- fr"\[datetime64\[ns\]\] to \[timedelta64\[{unit}\]\]",
+ rf"\[datetime64\[ns\]\] to \[timedelta64\[{unit}\]\]",
]
)
with pytest.raises(TypeError, match=msg):
@@ -467,10 +467,10 @@ def test_astype_to_incorrect_datetimelike(self, unit):
msg = "|".join(
[
# BlockManager path
- fr"Cannot cast TimedeltaArray to dtype datetime64\[{unit}\]",
+ rf"Cannot cast TimedeltaArray to dtype datetime64\[{unit}\]",
# ArrayManager path
"cannot astype a timedelta from "
- fr"\[timedelta64\[ns\]\] to \[datetime64\[{unit}\]\]",
+ rf"\[timedelta64\[ns\]\] to \[datetime64\[{unit}\]\]",
]
)
df = DataFrame(np.array([[1, 2, 3]], dtype=other))
diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py
index 6a1466ae1ea46..2e545942b6f46 100644
--- a/pandas/tests/frame/methods/test_cov_corr.py
+++ b/pandas/tests/frame/methods/test_cov_corr.py
@@ -348,7 +348,7 @@ def test_corr_numerical_instabilities(self):
def test_corrwith_spearman(self):
# GH#21925
df = DataFrame(np.random.random(size=(100, 3)))
- result = df.corrwith(df ** 2, method="spearman")
+ result = df.corrwith(df**2, method="spearman")
expected = Series(np.ones(len(result)))
tm.assert_series_equal(result, expected)
@@ -356,6 +356,6 @@ def test_corrwith_spearman(self):
def test_corrwith_kendall(self):
# GH#21925
df = DataFrame(np.random.random(size=(100, 3)))
- result = df.corrwith(df ** 2, method="kendall")
+ result = df.corrwith(df**2, method="kendall")
expected = Series(np.ones(len(result)))
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_pipe.py b/pandas/tests/frame/methods/test_pipe.py
index 1d7cc16f49280..5bcc4360487f3 100644
--- a/pandas/tests/frame/methods/test_pipe.py
+++ b/pandas/tests/frame/methods/test_pipe.py
@@ -15,7 +15,7 @@ def test_pipe(self, frame_or_series):
obj = obj["A"]
expected = expected["A"]
- f = lambda x, y: x ** y
+ f = lambda x, y: x**y
result = obj.pipe(f, 2)
tm.assert_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_rank.py b/pandas/tests/frame/methods/test_rank.py
index 31a6d7637a244..68c87a59d8230 100644
--- a/pandas/tests/frame/methods/test_rank.py
+++ b/pandas/tests/frame/methods/test_rank.py
@@ -332,7 +332,7 @@ def test_rank_pct_true(self, method, exp):
def test_pct_max_many_rows(self):
# GH 18271
df = DataFrame(
- {"A": np.arange(2 ** 24 + 1), "B": np.arange(2 ** 24 + 1, 0, -1)}
+ {"A": np.arange(2**24 + 1), "B": np.arange(2**24 + 1, 0, -1)}
)
result = df.rank(pct=True).max()
assert (result == 1).all()
diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py
index 8130c4fa41c12..8ddda099cf898 100644
--- a/pandas/tests/frame/methods/test_reset_index.py
+++ b/pandas/tests/frame/methods/test_reset_index.py
@@ -41,7 +41,7 @@ def test_reset_index_empty_rangeindex(self):
def test_set_reset(self):
- idx = Index([2 ** 63, 2 ** 63 + 5, 2 ** 63 + 10], name="foo")
+ idx = Index([2**63, 2**63 + 5, 2**63 + 10], name="foo")
# set/reset
df = DataFrame({"A": [0, 1, 2]}, index=idx)
@@ -232,7 +232,7 @@ def test_reset_index_level(self):
def test_reset_index_right_dtype(self):
time = np.arange(0.0, 10, np.sqrt(2) / 2)
s1 = Series(
- (9.81 * time ** 2) / 2, index=Index(time, name="time"), name="speed"
+ (9.81 * time**2) / 2, index=Index(time, name="time"), name="speed"
)
df = DataFrame(s1)
diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py
index 4820fcce6486b..bde44ddf12a8e 100644
--- a/pandas/tests/frame/test_arithmetic.py
+++ b/pandas/tests/frame/test_arithmetic.py
@@ -870,13 +870,13 @@ def _test_op(df, op):
_test_op(df, lambda x, y: y - x)
_test_op(df, lambda x, y: y * x)
_test_op(df, lambda x, y: y / x)
- _test_op(df, lambda x, y: y ** x)
+ _test_op(df, lambda x, y: y**x)
_test_op(df, lambda x, y: x + y)
_test_op(df, lambda x, y: x - y)
_test_op(df, lambda x, y: x * y)
_test_op(df, lambda x, y: x / y)
- _test_op(df, lambda x, y: x ** y)
+ _test_op(df, lambda x, y: x**y)
@pytest.mark.parametrize(
"values", [[1, 2], (1, 2), np.array([1, 2]), range(1, 3), deque([1, 2])]
@@ -949,9 +949,9 @@ def test_frame_with_frame_reindex(self):
[
(1, "i8"),
(1.0, "f8"),
- (2 ** 63, "f8"),
+ (2**63, "f8"),
(1j, "complex128"),
- (2 ** 63, "complex128"),
+ (2**63, "complex128"),
(True, "bool"),
(np.timedelta64(20, "ns"), "<m8[ns]"),
(np.datetime64(20, "ns"), "<M8[ns]"),
@@ -1766,7 +1766,7 @@ def test_pow_with_realignment():
left = DataFrame({"A": [0, 1, 2]})
right = DataFrame(index=[0, 1, 2])
- result = left ** right
+ result = left**right
expected = DataFrame({"A": [np.nan, 1.0, np.nan]})
tm.assert_frame_equal(result, expected)
@@ -1778,7 +1778,7 @@ def test_pow_nan_with_zero():
expected = DataFrame({"A": [1.0, 1.0, 1.0]})
- result = left ** right
+ result = left**right
tm.assert_frame_equal(result, expected)
result = left["A"] ** right["A"]
diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py
index 01a8982c5fe16..8aa0e980b01c4 100644
--- a/pandas/tests/frame/test_block_internals.py
+++ b/pandas/tests/frame/test_block_internals.py
@@ -118,14 +118,14 @@ def test_boolean_set_uncons(self, float_frame):
def test_constructor_with_convert(self):
# this is actually mostly a test of lib.maybe_convert_objects
# #2845
- df = DataFrame({"A": [2 ** 63 - 1]})
+ df = DataFrame({"A": [2**63 - 1]})
result = df["A"]
- expected = Series(np.asarray([2 ** 63 - 1], np.int64), name="A")
+ expected = Series(np.asarray([2**63 - 1], np.int64), name="A")
tm.assert_series_equal(result, expected)
- df = DataFrame({"A": [2 ** 63]})
+ df = DataFrame({"A": [2**63]})
result = df["A"]
- expected = Series(np.asarray([2 ** 63], np.uint64), name="A")
+ expected = Series(np.asarray([2**63], np.uint64), name="A")
tm.assert_series_equal(result, expected)
df = DataFrame({"A": [datetime(2005, 1, 1), True]})
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 08027d5807d8e..23bdfd9ee180e 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -398,7 +398,7 @@ def test_constructor_bool(self):
def test_constructor_overflow_int64(self):
# see gh-14881
- values = np.array([2 ** 64 - i for i in range(1, 10)], dtype=np.uint64)
+ values = np.array([2**64 - i for i in range(1, 10)], dtype=np.uint64)
result = DataFrame({"a": values})
assert result["a"].dtype == np.uint64
@@ -420,12 +420,12 @@ def test_constructor_overflow_int64(self):
@pytest.mark.parametrize(
"values",
[
- np.array([2 ** 64], dtype=object),
- np.array([2 ** 65]),
- [2 ** 64 + 1],
- np.array([-(2 ** 63) - 4], dtype=object),
- np.array([-(2 ** 64) - 1]),
- [-(2 ** 65) - 2],
+ np.array([2**64], dtype=object),
+ np.array([2**65]),
+ [2**64 + 1],
+ np.array([-(2**63) - 4], dtype=object),
+ np.array([-(2**64) - 1]),
+ [-(2**65) - 2],
],
)
def test_constructor_int_overflow(self, values):
@@ -2082,7 +2082,7 @@ def test_constructor_for_list_with_dtypes(self):
tm.assert_series_equal(result, expected)
# overflow issue? (we always expected int64 upcasting here)
- df = DataFrame({"a": [2 ** 31, 2 ** 31 + 1]})
+ df = DataFrame({"a": [2**31, 2**31 + 1]})
assert df.dtypes.iloc[0] == np.dtype("int64")
# GH #2751 (construction with no index specified), make sure we cast to
diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index 005d2600b2bae..a8ed07d6deda0 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -1848,8 +1848,8 @@ def __init__(self, *args, **kwargs):
with monkeypatch.context() as m:
m.setattr(reshape_lib, "_Unstacker", MockUnstacker)
df = DataFrame(
- np.random.randn(2 ** 16, 2),
- index=[np.arange(2 ** 16), np.arange(2 ** 16)],
+ np.random.randn(2**16, 2),
+ index=[np.arange(2**16), np.arange(2**16)],
)
msg = "The following operation may generate"
with tm.assert_produces_warning(PerformanceWarning, match=msg):
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index 2ab553434873c..1ea44871eea4d 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -225,10 +225,10 @@ def test_agg_str_with_kwarg_axis_1_raises(df, reduction_func):
"func, expected, dtype, result_dtype_dict",
[
("sum", [5, 7, 9], "int64", {}),
- ("std", [4.5 ** 0.5] * 3, int, {"i": float, "j": float, "k": float}),
+ ("std", [4.5**0.5] * 3, int, {"i": float, "j": float, "k": float}),
("var", [4.5] * 3, int, {"i": float, "j": float, "k": float}),
("sum", [5, 7, 9], "Int64", {"j": "int64"}),
- ("std", [4.5 ** 0.5] * 3, "Int64", {"i": float, "j": float, "k": float}),
+ ("std", [4.5**0.5] * 3, "Int64", {"i": float, "j": float, "k": float}),
("var", [4.5] * 3, "Int64", {"i": "float64", "j": "float64", "k": "float64"}),
],
)
@@ -250,7 +250,7 @@ def test_multiindex_groupby_mixed_cols_axis1(func, expected, dtype, result_dtype
[
("sum", [[2, 4], [10, 12], [18, 20]], {10: "int64", 20: "int64"}),
# std should ideally return Int64 / Float64 #43330
- ("std", [[2 ** 0.5] * 2] * 3, "float64"),
+ ("std", [[2**0.5] * 2] * 3, "float64"),
("var", [[2] * 2] * 3, {10: "float64", 20: "float64"}),
],
)
@@ -1097,7 +1097,7 @@ def test_agg_with_one_lambda(self):
# check pd.NameAgg case
result1 = df.groupby(by="kind").agg(
height_sqr_min=pd.NamedAgg(
- column="height", aggfunc=lambda x: np.min(x ** 2)
+ column="height", aggfunc=lambda x: np.min(x**2)
),
height_max=pd.NamedAgg(column="height", aggfunc="max"),
weight_max=pd.NamedAgg(column="weight", aggfunc="max"),
@@ -1106,7 +1106,7 @@ def test_agg_with_one_lambda(self):
# check agg(key=(col, aggfunc)) case
result2 = df.groupby(by="kind").agg(
- height_sqr_min=("height", lambda x: np.min(x ** 2)),
+ height_sqr_min=("height", lambda x: np.min(x**2)),
height_max=("height", "max"),
weight_max=("weight", "max"),
)
@@ -1143,7 +1143,7 @@ def test_agg_multiple_lambda(self):
# check agg(key=(col, aggfunc)) case
result1 = df.groupby(by="kind").agg(
- height_sqr_min=("height", lambda x: np.min(x ** 2)),
+ height_sqr_min=("height", lambda x: np.min(x**2)),
height_max=("height", "max"),
weight_max=("weight", "max"),
height_max_2=("height", lambda x: np.max(x)),
@@ -1154,7 +1154,7 @@ def test_agg_multiple_lambda(self):
# check pd.NamedAgg case
result2 = df.groupby(by="kind").agg(
height_sqr_min=pd.NamedAgg(
- column="height", aggfunc=lambda x: np.min(x ** 2)
+ column="height", aggfunc=lambda x: np.min(x**2)
),
height_max=pd.NamedAgg(column="height", aggfunc="max"),
weight_max=pd.NamedAgg(column="weight", aggfunc="max"),
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index dbc38497d3bee..1555e9d02c8ca 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -866,7 +866,7 @@ def test_cummin_max_skipna_multiple_cols(method):
@td.skip_if_32bit
@pytest.mark.parametrize("method", ["cummin", "cummax"])
@pytest.mark.parametrize(
- "dtype,val", [("UInt64", np.iinfo("uint64").max), ("Int64", 2 ** 53 + 1)]
+ "dtype,val", [("UInt64", np.iinfo("uint64").max), ("Int64", 2**53 + 1)]
)
def test_nullable_int_not_cast_as_float(method, dtype, val):
data = [val, pd.NA]
diff --git a/pandas/tests/groupby/test_libgroupby.py b/pandas/tests/groupby/test_libgroupby.py
index 2a24448d24ce2..cde9b36fd0bf4 100644
--- a/pandas/tests/groupby/test_libgroupby.py
+++ b/pandas/tests/groupby/test_libgroupby.py
@@ -112,13 +112,13 @@ def test_group_var_large_inputs(self):
out = np.array([[np.nan]], dtype=self.dtype)
counts = np.array([0], dtype="int64")
- values = (prng.rand(10 ** 6) + 10 ** 12).astype(self.dtype)
- values.shape = (10 ** 6, 1)
- labels = np.zeros(10 ** 6, dtype="intp")
+ values = (prng.rand(10**6) + 10**12).astype(self.dtype)
+ values.shape = (10**6, 1)
+ labels = np.zeros(10**6, dtype="intp")
self.algo(out, counts, values, labels)
- assert counts[0] == 10 ** 6
+ assert counts[0] == 10**6
tm.assert_almost_equal(out[0, 0], 1.0 / 12, rtol=0.5e-3)
diff --git a/pandas/tests/groupby/test_pipe.py b/pandas/tests/groupby/test_pipe.py
index 42bd6a84e05f6..1229251f88c7d 100644
--- a/pandas/tests/groupby/test_pipe.py
+++ b/pandas/tests/groupby/test_pipe.py
@@ -27,7 +27,7 @@ def f(dfgb):
return dfgb.B.max() - dfgb.C.min().min()
def square(srs):
- return srs ** 2
+ return srs**2
# Note that the transformations are
# GroupBy -> Series
diff --git a/pandas/tests/indexes/base_class/test_indexing.py b/pandas/tests/indexes/base_class/test_indexing.py
index 9cd582925ff79..8135dd57bba3f 100644
--- a/pandas/tests/indexes/base_class/test_indexing.py
+++ b/pandas/tests/indexes/base_class/test_indexing.py
@@ -51,7 +51,7 @@ def test_get_loc_tuple_monotonic_above_size_cutoff(self):
lev = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
dti = pd.date_range("2016-01-01", periods=100)
- mi = pd.MultiIndex.from_product([lev, range(10 ** 3), dti])
+ mi = pd.MultiIndex.from_product([lev, range(10**3), dti])
oidx = mi.to_flat_index()
loc = len(oidx) // 2
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 61cfd5593abc0..0cf66c0814293 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -892,6 +892,6 @@ def test_arithmetic_explicit_conversions(self):
def test_invalid_dtype(self, invalid_dtype):
# GH 29539
dtype = invalid_dtype
- msg = fr"Incorrect `dtype` passed: expected \w+(?: \w+)?, received {dtype}"
+ msg = rf"Incorrect `dtype` passed: expected \w+(?: \w+)?, received {dtype}"
with pytest.raises(ValueError, match=msg):
self._index_cls([1, 2, 3], dtype=dtype)
diff --git a/pandas/tests/indexes/datetimelike_/test_equals.py b/pandas/tests/indexes/datetimelike_/test_equals.py
index cc90e8f6d9bec..39e8270b1c4f5 100644
--- a/pandas/tests/indexes/datetimelike_/test_equals.py
+++ b/pandas/tests/indexes/datetimelike_/test_equals.py
@@ -167,7 +167,7 @@ def test_equals2(self):
# Check that we dont raise OverflowError on comparisons outside the
# implementation range GH#28532
- oob = Index([timedelta(days=10 ** 6)] * 3, dtype=object)
+ oob = Index([timedelta(days=10**6)] * 3, dtype=object)
assert not idx.equals(oob)
assert not idx2.equals(oob)
diff --git a/pandas/tests/indexes/datetimelike_/test_indexing.py b/pandas/tests/indexes/datetimelike_/test_indexing.py
index eb37c2c4ad2a3..b64d5421a2067 100644
--- a/pandas/tests/indexes/datetimelike_/test_indexing.py
+++ b/pandas/tests/indexes/datetimelike_/test_indexing.py
@@ -20,7 +20,7 @@
@pytest.mark.parametrize("rdtype", dtlike_dtypes)
def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype):
- vals = np.tile(3600 * 10 ** 9 * np.arange(3), 2)
+ vals = np.tile(3600 * 10**9 * np.arange(3), 2)
def construct(dtype):
if dtype is dtlike_dtypes[-1]:
diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py
index 2f32f9e18311d..8ddcd6a453080 100644
--- a/pandas/tests/indexes/datetimes/test_partial_slicing.py
+++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py
@@ -281,7 +281,7 @@ def test_partial_slicing_dataframe(self):
result = df["a"][ts_string]
assert isinstance(result, np.int64)
assert result == expected
- msg = fr"^'{ts_string}'$"
+ msg = rf"^'{ts_string}'$"
with pytest.raises(KeyError, match=msg):
df[ts_string]
@@ -311,7 +311,7 @@ def test_partial_slicing_dataframe(self):
result = df["a"][ts_string]
assert isinstance(result, np.int64)
assert result == 2
- msg = fr"^'{ts_string}'$"
+ msg = rf"^'{ts_string}'$"
with pytest.raises(KeyError, match=msg):
df[ts_string]
@@ -320,7 +320,7 @@ def test_partial_slicing_dataframe(self):
for fmt, res in list(zip(formats, resolutions))[rnum + 1 :]:
ts = index[1] + Timedelta("1 " + res)
ts_string = ts.strftime(fmt)
- msg = fr"^'{ts_string}'$"
+ msg = rf"^'{ts_string}'$"
with pytest.raises(KeyError, match=msg):
df["a"][ts_string]
with pytest.raises(KeyError, match=msg):
diff --git a/pandas/tests/indexes/interval/test_interval_tree.py b/pandas/tests/indexes/interval/test_interval_tree.py
index ab6eac482211d..f2d9ec3608271 100644
--- a/pandas/tests/indexes/interval/test_interval_tree.py
+++ b/pandas/tests/indexes/interval/test_interval_tree.py
@@ -58,7 +58,7 @@ def test_get_indexer(self, tree):
@pytest.mark.parametrize(
"dtype, target_value, target_dtype",
- [("int64", 2 ** 63 + 1, "uint64"), ("uint64", -1, "int64")],
+ [("int64", 2**63 + 1, "uint64"), ("uint64", -1, "int64")],
)
def test_get_indexer_overflow(self, dtype, target_value, target_dtype):
left, right = np.array([0, 1], dtype=dtype), np.array([1, 2], dtype=dtype)
@@ -89,7 +89,7 @@ def test_get_indexer_non_unique(self, tree):
@pytest.mark.parametrize(
"dtype, target_value, target_dtype",
- [("int64", 2 ** 63 + 1, "uint64"), ("uint64", -1, "int64")],
+ [("int64", 2**63 + 1, "uint64"), ("uint64", -1, "int64")],
)
def test_get_indexer_non_unique_overflow(self, dtype, target_value, target_dtype):
left, right = np.array([0, 2], dtype=dtype), np.array([1, 3], dtype=dtype)
diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py
index 9cb65128e7068..f81d9f9a9ce2a 100644
--- a/pandas/tests/indexes/multi/test_indexing.py
+++ b/pandas/tests/indexes/multi/test_indexing.py
@@ -790,8 +790,8 @@ def test_contains_td64_level(self):
@pytest.mark.slow
def test_large_mi_contains(self):
# GH#10645
- result = MultiIndex.from_arrays([range(10 ** 6), range(10 ** 6)])
- assert not (10 ** 6, 0) in result
+ result = MultiIndex.from_arrays([range(10**6), range(10**6)])
+ assert not (10**6, 0) in result
def test_timestamp_multiindex_indexer():
diff --git a/pandas/tests/indexes/multi/test_integrity.py b/pandas/tests/indexes/multi/test_integrity.py
index e1c2134b5b1f8..b9596ca62d030 100644
--- a/pandas/tests/indexes/multi/test_integrity.py
+++ b/pandas/tests/indexes/multi/test_integrity.py
@@ -52,7 +52,7 @@ def test_values_boxed():
def test_values_multiindex_datetimeindex():
# Test to ensure we hit the boxing / nobox part of MI.values
- ints = np.arange(10 ** 18, 10 ** 18 + 5)
+ ints = np.arange(10**18, 10**18 + 5)
naive = pd.DatetimeIndex(ints)
aware = pd.DatetimeIndex(ints, tz="US/Central")
diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py
index a70845a4def7f..7081cbdfe6428 100644
--- a/pandas/tests/indexes/numeric/test_indexing.py
+++ b/pandas/tests/indexes/numeric/test_indexing.py
@@ -20,7 +20,7 @@
@pytest.fixture
def index_large():
# large values used in UInt64Index tests where no compat needed with Int64/Float64
- large = [2 ** 63, 2 ** 63 + 10, 2 ** 63 + 15, 2 ** 63 + 20, 2 ** 63 + 25]
+ large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
return UInt64Index(large)
@@ -161,7 +161,7 @@ def test_get_loc_float_index_nan_with_method(self, vals, method):
@pytest.mark.parametrize("dtype", ["f8", "i8", "u8"])
def test_get_loc_numericindex_none_raises(self, dtype):
# case that goes through searchsorted and key is non-comparable to values
- arr = np.arange(10 ** 7, dtype=dtype)
+ arr = np.arange(10**7, dtype=dtype)
idx = Index(arr)
with pytest.raises(KeyError, match="None"):
idx.get_loc(None)
@@ -376,17 +376,17 @@ def test_get_indexer_int64(self):
tm.assert_numpy_array_equal(indexer, expected)
def test_get_indexer_uint64(self, index_large):
- target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2 ** 63)
+ target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2**63)
indexer = index_large.get_indexer(target)
expected = np.array([0, -1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
- target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2 ** 63)
+ target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2**63)
indexer = index_large.get_indexer(target, method="pad")
expected = np.array([0, 0, 1, 2, 3, 4, 4, 4, 4, 4], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
- target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2 ** 63)
+ target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2**63)
indexer = index_large.get_indexer(target, method="backfill")
expected = np.array([0, 1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
diff --git a/pandas/tests/indexes/numeric/test_join.py b/pandas/tests/indexes/numeric/test_join.py
index 2a47289b65aad..9bbe7a64ada87 100644
--- a/pandas/tests/indexes/numeric/test_join.py
+++ b/pandas/tests/indexes/numeric/test_join.py
@@ -198,13 +198,13 @@ class TestJoinUInt64Index:
@pytest.fixture
def index_large(self):
# large values used in TestUInt64Index where no compat needed with Int64/Float64
- large = [2 ** 63, 2 ** 63 + 10, 2 ** 63 + 15, 2 ** 63 + 20, 2 ** 63 + 25]
+ large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
return UInt64Index(large)
def test_join_inner(self, index_large):
- other = UInt64Index(2 ** 63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
+ other = UInt64Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
other_mono = UInt64Index(
- 2 ** 63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")
+ 2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")
)
# not monotonic
@@ -216,7 +216,7 @@ def test_join_inner(self, index_large):
lidx = lidx.take(ind)
ridx = ridx.take(ind)
- eres = UInt64Index(2 ** 63 + np.array([10, 25], dtype="uint64"))
+ eres = UInt64Index(2**63 + np.array([10, 25], dtype="uint64"))
elidx = np.array([1, 4], dtype=np.intp)
eridx = np.array([5, 2], dtype=np.intp)
@@ -242,9 +242,9 @@ def test_join_inner(self, index_large):
tm.assert_numpy_array_equal(ridx, eridx)
def test_join_left(self, index_large):
- other = UInt64Index(2 ** 63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
+ other = UInt64Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
other_mono = UInt64Index(
- 2 ** 63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")
+ 2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")
)
# not monotonic
@@ -267,12 +267,12 @@ def test_join_left(self, index_large):
tm.assert_numpy_array_equal(ridx, eridx)
# non-unique
- idx = UInt64Index(2 ** 63 + np.array([1, 1, 2, 5], dtype="uint64"))
- idx2 = UInt64Index(2 ** 63 + np.array([1, 2, 5, 7, 9], dtype="uint64"))
+ idx = UInt64Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64"))
+ idx2 = UInt64Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64"))
res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True)
# 1 is in idx2, so it should be x2
- eres = UInt64Index(2 ** 63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64"))
+ eres = UInt64Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64"))
eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
@@ -281,9 +281,9 @@ def test_join_left(self, index_large):
tm.assert_numpy_array_equal(ridx, eridx)
def test_join_right(self, index_large):
- other = UInt64Index(2 ** 63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
+ other = UInt64Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
other_mono = UInt64Index(
- 2 ** 63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")
+ 2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")
)
# not monotonic
@@ -309,12 +309,12 @@ def test_join_right(self, index_large):
assert ridx is None
# non-unique
- idx = UInt64Index(2 ** 63 + np.array([1, 1, 2, 5], dtype="uint64"))
- idx2 = UInt64Index(2 ** 63 + np.array([1, 2, 5, 7, 9], dtype="uint64"))
+ idx = UInt64Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64"))
+ idx2 = UInt64Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64"))
res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True)
# 1 is in idx2, so it should be x2
- eres = UInt64Index(2 ** 63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64"))
+ eres = UInt64Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64"))
elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
@@ -324,20 +324,20 @@ def test_join_right(self, index_large):
def test_join_non_int_index(self, index_large):
other = Index(
- 2 ** 63 + np.array([1, 5, 7, 10, 20], dtype="uint64"), dtype=object
+ 2**63 + np.array([1, 5, 7, 10, 20], dtype="uint64"), dtype=object
)
outer = index_large.join(other, how="outer")
outer2 = other.join(index_large, how="outer")
expected = Index(
- 2 ** 63 + np.array([0, 1, 5, 7, 10, 15, 20, 25], dtype="uint64")
+ 2**63 + np.array([0, 1, 5, 7, 10, 15, 20, 25], dtype="uint64")
)
tm.assert_index_equal(outer, outer2)
tm.assert_index_equal(outer, expected)
inner = index_large.join(other, how="inner")
inner2 = other.join(index_large, how="inner")
- expected = Index(2 ** 63 + np.array([10, 20], dtype="uint64"))
+ expected = Index(2**63 + np.array([10, 20], dtype="uint64"))
tm.assert_index_equal(inner, inner2)
tm.assert_index_equal(inner, expected)
@@ -354,9 +354,9 @@ def test_join_non_int_index(self, index_large):
tm.assert_index_equal(right2, index_large.astype(object))
def test_join_outer(self, index_large):
- other = UInt64Index(2 ** 63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
+ other = UInt64Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
other_mono = UInt64Index(
- 2 ** 63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")
+ 2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64")
)
# not monotonic
@@ -366,7 +366,7 @@ def test_join_outer(self, index_large):
tm.assert_index_equal(res, noidx_res)
eres = UInt64Index(
- 2 ** 63 + np.array([0, 1, 2, 7, 10, 12, 15, 20, 25], dtype="uint64")
+ 2**63 + np.array([0, 1, 2, 7, 10, 12, 15, 20, 25], dtype="uint64")
)
elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp)
eridx = np.array([-1, 3, 4, 0, 5, 1, -1, -1, 2], dtype=np.intp)
diff --git a/pandas/tests/indexes/numeric/test_numeric.py b/pandas/tests/indexes/numeric/test_numeric.py
index af308379cba5e..85384cbd41ea5 100644
--- a/pandas/tests/indexes/numeric/test_numeric.py
+++ b/pandas/tests/indexes/numeric/test_numeric.py
@@ -563,8 +563,8 @@ def simple_index(self, dtype):
@pytest.fixture(
params=[
- [2 ** 63, 2 ** 63 + 10, 2 ** 63 + 15, 2 ** 63 + 20, 2 ** 63 + 25],
- [2 ** 63 + 25, 2 ** 63 + 20, 2 ** 63 + 15, 2 ** 63 + 10, 2 ** 63],
+ [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25],
+ [2**63 + 25, 2**63 + 20, 2**63 + 15, 2**63 + 10, 2**63],
],
ids=["index_inc", "index_dec"],
)
@@ -594,21 +594,21 @@ def test_constructor(self, dtype):
res = Index([1, 2, 3], dtype=dtype)
tm.assert_index_equal(res, idx, exact=exact)
- idx = index_cls([1, 2 ** 63])
- res = Index([1, 2 ** 63], dtype=dtype)
+ idx = index_cls([1, 2**63])
+ res = Index([1, 2**63], dtype=dtype)
tm.assert_index_equal(res, idx, exact=exact)
- idx = index_cls([1, 2 ** 63])
- res = Index([1, 2 ** 63])
+ idx = index_cls([1, 2**63])
+ res = Index([1, 2**63])
tm.assert_index_equal(res, idx, exact=exact)
- idx = Index([-1, 2 ** 63], dtype=object)
- res = Index(np.array([-1, 2 ** 63], dtype=object))
+ idx = Index([-1, 2**63], dtype=object)
+ res = Index(np.array([-1, 2**63], dtype=object))
tm.assert_index_equal(res, idx, exact=exact)
# https://github.com/pandas-dev/pandas/issues/29526
- idx = index_cls([1, 2 ** 63 + 1], dtype=dtype)
- res = Index([1, 2 ** 63 + 1], dtype=dtype)
+ idx = index_cls([1, 2**63 + 1], dtype=dtype)
+ res = Index([1, 2**63 + 1], dtype=dtype)
tm.assert_index_equal(res, idx, exact=exact)
def test_constructor_does_not_cast_to_float(self):
diff --git a/pandas/tests/indexes/numeric/test_setops.py b/pandas/tests/indexes/numeric/test_setops.py
index 72336d3e33b79..9f2174c2de51e 100644
--- a/pandas/tests/indexes/numeric/test_setops.py
+++ b/pandas/tests/indexes/numeric/test_setops.py
@@ -19,7 +19,7 @@
@pytest.fixture
def index_large():
# large values used in TestUInt64Index where no compat needed with Int64/Float64
- large = [2 ** 63, 2 ** 63 + 10, 2 ** 63 + 15, 2 ** 63 + 20, 2 ** 63 + 25]
+ large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
return UInt64Index(large)
@@ -89,7 +89,7 @@ def test_float64_index_difference(self):
tm.assert_index_equal(result, string_index)
def test_intersection_uint64_outside_int64_range(self, index_large):
- other = Index([2 ** 63, 2 ** 63 + 5, 2 ** 63 + 10, 2 ** 63 + 15, 2 ** 63 + 20])
+ other = Index([2**63, 2**63 + 5, 2**63 + 10, 2**63 + 15, 2**63 + 20])
result = index_large.intersection(other)
expected = Index(np.sort(np.intersect1d(index_large.values, other.values)))
tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 1145de14ad3c4..222f1fc3e7648 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -743,7 +743,7 @@ def test_drop_tuple(self, values, to_drop):
tm.assert_index_equal(result, expected)
removed = index.drop(to_drop[1])
- msg = fr"\"\[{re.escape(to_drop[1].__repr__())}\] not found in axis\""
+ msg = rf"\"\[{re.escape(to_drop[1].__repr__())}\] not found in axis\""
for drop_me in to_drop[1], [to_drop[1]]:
with pytest.raises(KeyError, match=msg):
removed.drop(drop_me)
@@ -871,7 +871,7 @@ def test_isin_level_kwarg_bad_label_raises(self, label, index):
msg = f"'Level {label} not found'"
else:
index = index.rename("foo")
- msg = fr"Requested level \({label}\) does not match index name \(foo\)"
+ msg = rf"Requested level \({label}\) does not match index name \(foo\)"
with pytest.raises(KeyError, match=msg):
index.isin([], level=label)
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index 5fb9673cf52d7..6159c53ea5bf4 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -195,8 +195,8 @@ def test_unique_level(self, index_flat):
index.unique(level=3)
msg = (
- fr"Requested level \(wrong\) does not match index name "
- fr"\({re.escape(index.name.__repr__())}\)"
+ rf"Requested level \(wrong\) does not match index name "
+ rf"\({re.escape(index.name.__repr__())}\)"
)
with pytest.raises(KeyError, match=msg):
index.unique(level="wrong")
diff --git a/pandas/tests/indexes/timedeltas/test_constructors.py b/pandas/tests/indexes/timedeltas/test_constructors.py
index dcddba8b22937..25a0a66ada519 100644
--- a/pandas/tests/indexes/timedeltas/test_constructors.py
+++ b/pandas/tests/indexes/timedeltas/test_constructors.py
@@ -51,7 +51,7 @@ def test_infer_from_tdi(self):
# GH#23539
# fast-path for inferring a frequency if the passed data already
# has one
- tdi = timedelta_range("1 second", periods=10 ** 7, freq="1s")
+ tdi = timedelta_range("1 second", periods=10**7, freq="1s")
result = TimedeltaIndex(tdi, freq="infer")
assert result.freq == tdi.freq
diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py
index 8ceef8186e4ea..6904a847b04ed 100644
--- a/pandas/tests/indexes/timedeltas/test_timedelta.py
+++ b/pandas/tests/indexes/timedeltas/test_timedelta.py
@@ -105,7 +105,7 @@ def test_freq_conversion_always_floating(self):
tdi = timedelta_range("1 Day", periods=30)
res = tdi.astype("m8[s]")
- expected = Index((tdi.view("i8") / 10 ** 9).astype(np.float64))
+ expected = Index((tdi.view("i8") / 10**9).astype(np.float64))
tm.assert_index_equal(res, expected)
# check this matches Series and TimedeltaArray
diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py
index 75337cb3f453f..2f616b79a680f 100644
--- a/pandas/tests/indexing/test_coercion.py
+++ b/pandas/tests/indexing/test_coercion.py
@@ -114,7 +114,7 @@ def test_setitem_series_int64(self, val, exp_dtype):
self._assert_setitem_series_conversion(obj, val, exp, exp_dtype)
@pytest.mark.parametrize(
- "val,exp_dtype", [(np.int32(1), np.int8), (np.int16(2 ** 9), np.int16)]
+ "val,exp_dtype", [(np.int32(1), np.int8), (np.int16(2**9), np.int16)]
)
def test_setitem_series_int8(self, val, exp_dtype):
obj = pd.Series([1, 2, 3, 4], dtype=np.int8)
diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py
index 902bd943584d9..81e1b82dd432e 100644
--- a/pandas/tests/indexing/test_floats.py
+++ b/pandas/tests/indexing/test_floats.py
@@ -240,13 +240,13 @@ def test_slice_non_numeric(self, index_func, idx, frame_or_series, indexer_sli):
if indexer_sli is tm.iloc:
msg = (
"cannot do positional indexing "
- fr"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
+ rf"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
"type float"
)
else:
msg = (
"cannot do slice indexing "
- fr"on {type(index).__name__} with these indexers "
+ rf"on {type(index).__name__} with these indexers "
r"\[(3|4)(\.0)?\] "
r"of type (float|int)"
)
@@ -306,7 +306,7 @@ def test_slice_integer(self):
# positional indexing
msg = (
"cannot do slice indexing "
- fr"on {type(index).__name__} with these indexers \[-6\.0\] of "
+ rf"on {type(index).__name__} with these indexers \[-6\.0\] of "
"type float"
)
with pytest.raises(TypeError, match=msg):
@@ -330,7 +330,7 @@ def test_slice_integer(self):
# positional indexing
msg = (
"cannot do slice indexing "
- fr"on {type(index).__name__} with these indexers \[(2|3)\.5\] of "
+ rf"on {type(index).__name__} with these indexers \[(2|3)\.5\] of "
"type float"
)
with pytest.raises(TypeError, match=msg):
@@ -350,7 +350,7 @@ def test_integer_positional_indexing(self, idx):
klass = RangeIndex
msg = (
"cannot do (slice|positional) indexing "
- fr"on {klass.__name__} with these indexers \[(2|4)\.0\] of "
+ rf"on {klass.__name__} with these indexers \[(2|4)\.0\] of "
"type float"
)
with pytest.raises(TypeError, match=msg):
@@ -376,7 +376,7 @@ def test_slice_integer_frame_getitem(self, index_func):
# positional indexing
msg = (
"cannot do slice indexing "
- fr"on {type(index).__name__} with these indexers \[(0|1)\.0\] of "
+ rf"on {type(index).__name__} with these indexers \[(0|1)\.0\] of "
"type float"
)
with pytest.raises(TypeError, match=msg):
@@ -391,7 +391,7 @@ def test_slice_integer_frame_getitem(self, index_func):
# positional indexing
msg = (
"cannot do slice indexing "
- fr"on {type(index).__name__} with these indexers \[-10\.0\] of "
+ rf"on {type(index).__name__} with these indexers \[-10\.0\] of "
"type float"
)
with pytest.raises(TypeError, match=msg):
@@ -410,7 +410,7 @@ def test_slice_integer_frame_getitem(self, index_func):
# positional indexing
msg = (
"cannot do slice indexing "
- fr"on {type(index).__name__} with these indexers \[0\.5\] of "
+ rf"on {type(index).__name__} with these indexers \[0\.5\] of "
"type float"
)
with pytest.raises(TypeError, match=msg):
@@ -434,7 +434,7 @@ def test_float_slice_getitem_with_integer_index_raises(self, idx, index_func):
# positional indexing
msg = (
"cannot do slice indexing "
- fr"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
+ rf"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
"type float"
)
with pytest.raises(TypeError, match=msg):
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index ee9d276925d41..d5909ce8eb48f 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -747,7 +747,7 @@ def test_iloc_mask(self):
# the possibilities
locs = np.arange(4)
- nums = 2 ** locs
+ nums = 2**locs
reps = [bin(num) for num in nums]
df = DataFrame({"locs": locs, "nums": nums}, reps)
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index 63c5091865160..892de75855c19 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -1307,11 +1307,11 @@ def test_loc_getitem_timedelta_0seconds(self):
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
- "val,expected", [(2 ** 63 - 1, Series([1])), (2 ** 63, Series([2]))]
+ "val,expected", [(2**63 - 1, Series([1])), (2**63, Series([2]))]
)
def test_loc_getitem_uint64_scalar(self, val, expected):
# see GH#19399
- df = DataFrame([1, 2], index=[2 ** 63 - 1, 2 ** 63])
+ df = DataFrame([1, 2], index=[2**63 - 1, 2**63])
result = df.loc[val]
expected.name = val
@@ -1825,9 +1825,9 @@ class TestLocSetitemWithExpansion:
@pytest.mark.slow
def test_loc_setitem_with_expansion_large_dataframe(self):
# GH#10692
- result = DataFrame({"x": range(10 ** 6)}, dtype="int64")
+ result = DataFrame({"x": range(10**6)}, dtype="int64")
result.loc[len(result)] = len(result) + 1
- expected = DataFrame({"x": range(10 ** 6 + 1)}, dtype="int64")
+ expected = DataFrame({"x": range(10**6 + 1)}, dtype="int64")
tm.assert_frame_equal(result, expected)
def test_loc_setitem_empty_series(self):
@@ -2735,10 +2735,10 @@ def test_loc_getitem_nullable_index_with_duplicates():
class TestLocSeries:
- @pytest.mark.parametrize("val,expected", [(2 ** 63 - 1, 3), (2 ** 63, 4)])
+ @pytest.mark.parametrize("val,expected", [(2**63 - 1, 3), (2**63, 4)])
def test_loc_uint64(self, val, expected):
# see GH#19399
- ser = Series({2 ** 63 - 1: 3, 2 ** 63: 4})
+ ser = Series({2**63 - 1: 3, 2**63: 4})
assert ser.loc[val] == expected
def test_loc_getitem(self, string_series, datetime_series):
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index 0315783569c23..c69876c6a3956 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -338,8 +338,8 @@ class TestExcelWriter:
def test_excel_sheet_size(self, path):
# GH 26080
- breaking_row_count = 2 ** 20 + 1
- breaking_col_count = 2 ** 14 + 1
+ breaking_row_count = 2**20 + 1
+ breaking_col_count = 2**14 + 1
# purposely using two arrays to prevent memory issues while testing
row_arr = np.zeros(shape=(breaking_row_count, 1))
col_arr = np.zeros(shape=(1, breaking_col_count))
diff --git a/pandas/tests/io/formats/test_eng_formatting.py b/pandas/tests/io/formats/test_eng_formatting.py
index b8e3122cac5c4..2f18623559557 100644
--- a/pandas/tests/io/formats/test_eng_formatting.py
+++ b/pandas/tests/io/formats/test_eng_formatting.py
@@ -56,57 +56,57 @@ def test_exponents_with_eng_prefix(self):
formatter = fmt.EngFormatter(accuracy=3, use_eng_prefix=True)
f = np.sqrt(2)
in_out = [
- (f * 10 ** -24, " 1.414y"),
- (f * 10 ** -23, " 14.142y"),
- (f * 10 ** -22, " 141.421y"),
- (f * 10 ** -21, " 1.414z"),
- (f * 10 ** -20, " 14.142z"),
- (f * 10 ** -19, " 141.421z"),
- (f * 10 ** -18, " 1.414a"),
- (f * 10 ** -17, " 14.142a"),
- (f * 10 ** -16, " 141.421a"),
- (f * 10 ** -15, " 1.414f"),
- (f * 10 ** -14, " 14.142f"),
- (f * 10 ** -13, " 141.421f"),
- (f * 10 ** -12, " 1.414p"),
- (f * 10 ** -11, " 14.142p"),
- (f * 10 ** -10, " 141.421p"),
- (f * 10 ** -9, " 1.414n"),
- (f * 10 ** -8, " 14.142n"),
- (f * 10 ** -7, " 141.421n"),
- (f * 10 ** -6, " 1.414u"),
- (f * 10 ** -5, " 14.142u"),
- (f * 10 ** -4, " 141.421u"),
- (f * 10 ** -3, " 1.414m"),
- (f * 10 ** -2, " 14.142m"),
- (f * 10 ** -1, " 141.421m"),
- (f * 10 ** 0, " 1.414"),
- (f * 10 ** 1, " 14.142"),
- (f * 10 ** 2, " 141.421"),
- (f * 10 ** 3, " 1.414k"),
- (f * 10 ** 4, " 14.142k"),
- (f * 10 ** 5, " 141.421k"),
- (f * 10 ** 6, " 1.414M"),
- (f * 10 ** 7, " 14.142M"),
- (f * 10 ** 8, " 141.421M"),
- (f * 10 ** 9, " 1.414G"),
- (f * 10 ** 10, " 14.142G"),
- (f * 10 ** 11, " 141.421G"),
- (f * 10 ** 12, " 1.414T"),
- (f * 10 ** 13, " 14.142T"),
- (f * 10 ** 14, " 141.421T"),
- (f * 10 ** 15, " 1.414P"),
- (f * 10 ** 16, " 14.142P"),
- (f * 10 ** 17, " 141.421P"),
- (f * 10 ** 18, " 1.414E"),
- (f * 10 ** 19, " 14.142E"),
- (f * 10 ** 20, " 141.421E"),
- (f * 10 ** 21, " 1.414Z"),
- (f * 10 ** 22, " 14.142Z"),
- (f * 10 ** 23, " 141.421Z"),
- (f * 10 ** 24, " 1.414Y"),
- (f * 10 ** 25, " 14.142Y"),
- (f * 10 ** 26, " 141.421Y"),
+ (f * 10**-24, " 1.414y"),
+ (f * 10**-23, " 14.142y"),
+ (f * 10**-22, " 141.421y"),
+ (f * 10**-21, " 1.414z"),
+ (f * 10**-20, " 14.142z"),
+ (f * 10**-19, " 141.421z"),
+ (f * 10**-18, " 1.414a"),
+ (f * 10**-17, " 14.142a"),
+ (f * 10**-16, " 141.421a"),
+ (f * 10**-15, " 1.414f"),
+ (f * 10**-14, " 14.142f"),
+ (f * 10**-13, " 141.421f"),
+ (f * 10**-12, " 1.414p"),
+ (f * 10**-11, " 14.142p"),
+ (f * 10**-10, " 141.421p"),
+ (f * 10**-9, " 1.414n"),
+ (f * 10**-8, " 14.142n"),
+ (f * 10**-7, " 141.421n"),
+ (f * 10**-6, " 1.414u"),
+ (f * 10**-5, " 14.142u"),
+ (f * 10**-4, " 141.421u"),
+ (f * 10**-3, " 1.414m"),
+ (f * 10**-2, " 14.142m"),
+ (f * 10**-1, " 141.421m"),
+ (f * 10**0, " 1.414"),
+ (f * 10**1, " 14.142"),
+ (f * 10**2, " 141.421"),
+ (f * 10**3, " 1.414k"),
+ (f * 10**4, " 14.142k"),
+ (f * 10**5, " 141.421k"),
+ (f * 10**6, " 1.414M"),
+ (f * 10**7, " 14.142M"),
+ (f * 10**8, " 141.421M"),
+ (f * 10**9, " 1.414G"),
+ (f * 10**10, " 14.142G"),
+ (f * 10**11, " 141.421G"),
+ (f * 10**12, " 1.414T"),
+ (f * 10**13, " 14.142T"),
+ (f * 10**14, " 141.421T"),
+ (f * 10**15, " 1.414P"),
+ (f * 10**16, " 14.142P"),
+ (f * 10**17, " 141.421P"),
+ (f * 10**18, " 1.414E"),
+ (f * 10**19, " 14.142E"),
+ (f * 10**20, " 141.421E"),
+ (f * 10**21, " 1.414Z"),
+ (f * 10**22, " 14.142Z"),
+ (f * 10**23, " 141.421Z"),
+ (f * 10**24, " 1.414Y"),
+ (f * 10**25, " 14.142Y"),
+ (f * 10**26, " 141.421Y"),
]
self.compare_all(formatter, in_out)
@@ -114,57 +114,57 @@ def test_exponents_without_eng_prefix(self):
formatter = fmt.EngFormatter(accuracy=4, use_eng_prefix=False)
f = np.pi
in_out = [
- (f * 10 ** -24, " 3.1416E-24"),
- (f * 10 ** -23, " 31.4159E-24"),
- (f * 10 ** -22, " 314.1593E-24"),
- (f * 10 ** -21, " 3.1416E-21"),
- (f * 10 ** -20, " 31.4159E-21"),
- (f * 10 ** -19, " 314.1593E-21"),
- (f * 10 ** -18, " 3.1416E-18"),
- (f * 10 ** -17, " 31.4159E-18"),
- (f * 10 ** -16, " 314.1593E-18"),
- (f * 10 ** -15, " 3.1416E-15"),
- (f * 10 ** -14, " 31.4159E-15"),
- (f * 10 ** -13, " 314.1593E-15"),
- (f * 10 ** -12, " 3.1416E-12"),
- (f * 10 ** -11, " 31.4159E-12"),
- (f * 10 ** -10, " 314.1593E-12"),
- (f * 10 ** -9, " 3.1416E-09"),
- (f * 10 ** -8, " 31.4159E-09"),
- (f * 10 ** -7, " 314.1593E-09"),
- (f * 10 ** -6, " 3.1416E-06"),
- (f * 10 ** -5, " 31.4159E-06"),
- (f * 10 ** -4, " 314.1593E-06"),
- (f * 10 ** -3, " 3.1416E-03"),
- (f * 10 ** -2, " 31.4159E-03"),
- (f * 10 ** -1, " 314.1593E-03"),
- (f * 10 ** 0, " 3.1416E+00"),
- (f * 10 ** 1, " 31.4159E+00"),
- (f * 10 ** 2, " 314.1593E+00"),
- (f * 10 ** 3, " 3.1416E+03"),
- (f * 10 ** 4, " 31.4159E+03"),
- (f * 10 ** 5, " 314.1593E+03"),
- (f * 10 ** 6, " 3.1416E+06"),
- (f * 10 ** 7, " 31.4159E+06"),
- (f * 10 ** 8, " 314.1593E+06"),
- (f * 10 ** 9, " 3.1416E+09"),
- (f * 10 ** 10, " 31.4159E+09"),
- (f * 10 ** 11, " 314.1593E+09"),
- (f * 10 ** 12, " 3.1416E+12"),
- (f * 10 ** 13, " 31.4159E+12"),
- (f * 10 ** 14, " 314.1593E+12"),
- (f * 10 ** 15, " 3.1416E+15"),
- (f * 10 ** 16, " 31.4159E+15"),
- (f * 10 ** 17, " 314.1593E+15"),
- (f * 10 ** 18, " 3.1416E+18"),
- (f * 10 ** 19, " 31.4159E+18"),
- (f * 10 ** 20, " 314.1593E+18"),
- (f * 10 ** 21, " 3.1416E+21"),
- (f * 10 ** 22, " 31.4159E+21"),
- (f * 10 ** 23, " 314.1593E+21"),
- (f * 10 ** 24, " 3.1416E+24"),
- (f * 10 ** 25, " 31.4159E+24"),
- (f * 10 ** 26, " 314.1593E+24"),
+ (f * 10**-24, " 3.1416E-24"),
+ (f * 10**-23, " 31.4159E-24"),
+ (f * 10**-22, " 314.1593E-24"),
+ (f * 10**-21, " 3.1416E-21"),
+ (f * 10**-20, " 31.4159E-21"),
+ (f * 10**-19, " 314.1593E-21"),
+ (f * 10**-18, " 3.1416E-18"),
+ (f * 10**-17, " 31.4159E-18"),
+ (f * 10**-16, " 314.1593E-18"),
+ (f * 10**-15, " 3.1416E-15"),
+ (f * 10**-14, " 31.4159E-15"),
+ (f * 10**-13, " 314.1593E-15"),
+ (f * 10**-12, " 3.1416E-12"),
+ (f * 10**-11, " 31.4159E-12"),
+ (f * 10**-10, " 314.1593E-12"),
+ (f * 10**-9, " 3.1416E-09"),
+ (f * 10**-8, " 31.4159E-09"),
+ (f * 10**-7, " 314.1593E-09"),
+ (f * 10**-6, " 3.1416E-06"),
+ (f * 10**-5, " 31.4159E-06"),
+ (f * 10**-4, " 314.1593E-06"),
+ (f * 10**-3, " 3.1416E-03"),
+ (f * 10**-2, " 31.4159E-03"),
+ (f * 10**-1, " 314.1593E-03"),
+ (f * 10**0, " 3.1416E+00"),
+ (f * 10**1, " 31.4159E+00"),
+ (f * 10**2, " 314.1593E+00"),
+ (f * 10**3, " 3.1416E+03"),
+ (f * 10**4, " 31.4159E+03"),
+ (f * 10**5, " 314.1593E+03"),
+ (f * 10**6, " 3.1416E+06"),
+ (f * 10**7, " 31.4159E+06"),
+ (f * 10**8, " 314.1593E+06"),
+ (f * 10**9, " 3.1416E+09"),
+ (f * 10**10, " 31.4159E+09"),
+ (f * 10**11, " 314.1593E+09"),
+ (f * 10**12, " 3.1416E+12"),
+ (f * 10**13, " 31.4159E+12"),
+ (f * 10**14, " 314.1593E+12"),
+ (f * 10**15, " 3.1416E+15"),
+ (f * 10**16, " 31.4159E+15"),
+ (f * 10**17, " 314.1593E+15"),
+ (f * 10**18, " 3.1416E+18"),
+ (f * 10**19, " 31.4159E+18"),
+ (f * 10**20, " 314.1593E+18"),
+ (f * 10**21, " 3.1416E+21"),
+ (f * 10**22, " 31.4159E+21"),
+ (f * 10**23, " 314.1593E+21"),
+ (f * 10**24, " 3.1416E+24"),
+ (f * 10**25, " 31.4159E+24"),
+ (f * 10**26, " 314.1593E+24"),
]
self.compare_all(formatter, in_out)
diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py
index 01bc94bf594d9..f8015851c9a83 100644
--- a/pandas/tests/io/formats/test_to_latex.py
+++ b/pandas/tests/io/formats/test_to_latex.py
@@ -282,7 +282,7 @@ def test_to_latex_longtable_without_index(self):
)
def test_to_latex_longtable_continued_on_next_page(self, df, expected_number):
result = df.to_latex(index=False, longtable=True)
- assert fr"\multicolumn{{{expected_number}}}" in result
+ assert rf"\multicolumn{{{expected_number}}}" in result
class TestToLatexHeader:
@@ -1006,7 +1006,7 @@ def test_to_latex_na_rep_and_float_format(self, na_rep):
)
result = df.to_latex(na_rep=na_rep, float_format="{:.2f}".format)
expected = _dedent(
- fr"""
+ rf"""
\begin{{tabular}}{{llr}}
\toprule
{{}} & Group & Data \\
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index f571daef3b40f..966fddda46bd8 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -1275,7 +1275,7 @@ def test_to_json_large_numbers(self, bigNum):
expected = '{"0":{"articleId":' + str(bigNum) + "}}"
assert json == expected
- @pytest.mark.parametrize("bigNum", [-(2 ** 63) - 1, 2 ** 64])
+ @pytest.mark.parametrize("bigNum", [-(2**63) - 1, 2**64])
def test_read_json_large_numbers(self, bigNum):
# GH20599, 26068
json = StringIO('{"articleId":' + str(bigNum) + "}")
diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py
index b4ae54d48dc68..41a417f6b3ef4 100644
--- a/pandas/tests/io/json/test_ujson.py
+++ b/pandas/tests/io/json/test_ujson.py
@@ -428,13 +428,13 @@ def test_datetime_units(self):
stamp = Timestamp(val)
roundtrip = ujson.decode(ujson.encode(val, date_unit="s"))
- assert roundtrip == stamp.value // 10 ** 9
+ assert roundtrip == stamp.value // 10**9
roundtrip = ujson.decode(ujson.encode(val, date_unit="ms"))
- assert roundtrip == stamp.value // 10 ** 6
+ assert roundtrip == stamp.value // 10**6
roundtrip = ujson.decode(ujson.encode(val, date_unit="us"))
- assert roundtrip == stamp.value // 10 ** 3
+ assert roundtrip == stamp.value // 10**3
roundtrip = ujson.decode(ujson.encode(val, date_unit="ns"))
assert roundtrip == stamp.value
@@ -606,7 +606,7 @@ def test_encode_long_conversion(self, long_input):
assert output == json.dumps(long_input)
assert long_input == ujson.decode(output)
- @pytest.mark.parametrize("bigNum", [2 ** 64, -(2 ** 63) - 1])
+ @pytest.mark.parametrize("bigNum", [2**64, -(2**63) - 1])
def test_dumps_ints_larger_than_maxsize(self, bigNum):
encoding = ujson.encode(bigNum)
assert str(bigNum) == encoding
@@ -628,7 +628,7 @@ def test_loads_non_str_bytes_raises(self):
with pytest.raises(TypeError, match=msg):
ujson.loads(None)
- @pytest.mark.parametrize("val", [3590016419, 2 ** 31, 2 ** 32, (2 ** 32) - 1])
+ @pytest.mark.parametrize("val", [3590016419, 2**31, 2**32, (2**32) - 1])
def test_decode_number_with_32bit_sign_bit(self, val):
# Test that numbers that fit within 32 bits but would have the
# sign bit set (2**31 <= x < 2**32) are decoded properly.
diff --git a/pandas/tests/io/parser/common/test_ints.py b/pandas/tests/io/parser/common/test_ints.py
index aef2020fe0847..e3159ef3e6a42 100644
--- a/pandas/tests/io/parser/common/test_ints.py
+++ b/pandas/tests/io/parser/common/test_ints.py
@@ -193,7 +193,7 @@ def test_outside_int64_uint64_range(all_parsers, val):
@skip_pyarrow
-@pytest.mark.parametrize("exp_data", [[str(-1), str(2 ** 63)], [str(2 ** 63), str(-1)]])
+@pytest.mark.parametrize("exp_data", [[str(-1), str(2**63)], [str(2**63), str(-1)]])
def test_numeric_range_too_wide(all_parsers, exp_data):
# No numerical dtype can hold both negative and uint64
# values, so they should be cast as string.
diff --git a/pandas/tests/io/parser/test_na_values.py b/pandas/tests/io/parser/test_na_values.py
index f9356dfc7d0e3..9fb096bfeb346 100644
--- a/pandas/tests/io/parser/test_na_values.py
+++ b/pandas/tests/io/parser/test_na_values.py
@@ -469,12 +469,12 @@ def test_na_values_dict_col_index(all_parsers):
"data,kwargs,expected",
[
(
- str(2 ** 63) + "\n" + str(2 ** 63 + 1),
- {"na_values": [2 ** 63]},
- DataFrame([str(2 ** 63), str(2 ** 63 + 1)]),
+ str(2**63) + "\n" + str(2**63 + 1),
+ {"na_values": [2**63]},
+ DataFrame([str(2**63), str(2**63 + 1)]),
),
- (str(2 ** 63) + ",1" + "\n,2", {}, DataFrame([[str(2 ** 63), 1], ["", 2]])),
- (str(2 ** 63) + "\n1", {"na_values": [2 ** 63]}, DataFrame([np.nan, 1])),
+ (str(2**63) + ",1" + "\n,2", {}, DataFrame([[str(2**63), 1], ["", 2]])),
+ (str(2**63) + "\n1", {"na_values": [2**63]}, DataFrame([np.nan, 1])),
],
)
def test_na_values_uint64(all_parsers, data, kwargs, expected):
diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py
index f38ea4d5cf306..ec72ca49747b3 100644
--- a/pandas/tests/io/pytables/test_append.py
+++ b/pandas/tests/io/pytables/test_append.py
@@ -77,10 +77,10 @@ def test_append(setup_path):
np.random.randint(0, high=65535, size=5), dtype=np.uint16
),
"u32": Series(
- np.random.randint(0, high=2 ** 30, size=5), dtype=np.uint32
+ np.random.randint(0, high=2**30, size=5), dtype=np.uint32
),
"u64": Series(
- [2 ** 58, 2 ** 59, 2 ** 60, 2 ** 61, 2 ** 62],
+ [2**58, 2**59, 2**60, 2**61, 2**62],
dtype=np.uint64,
),
},
diff --git a/pandas/tests/io/pytables/test_compat.py b/pandas/tests/io/pytables/test_compat.py
index c7200385aa998..5fe55fda8a452 100644
--- a/pandas/tests/io/pytables/test_compat.py
+++ b/pandas/tests/io/pytables/test_compat.py
@@ -23,7 +23,7 @@ def pytables_hdf5_file():
testsamples = [
{"c0": t0, "c1": "aaaaa", "c2": 1},
{"c0": t0 + 1, "c1": "bbbbb", "c2": 2},
- {"c0": t0 + 2, "c1": "ccccc", "c2": 10 ** 5},
+ {"c0": t0 + 2, "c1": "ccccc", "c2": 10**5},
{"c0": t0 + 3, "c1": "ddddd", "c2": 4_294_967_295},
]
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
index b458f3351c860..36048601b3248 100644
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -195,23 +195,23 @@ def test_read_non_existent(self, reader, module, error_class, fn_ext):
pytest.importorskip(module)
path = os.path.join(HERE, "data", "does_not_exist." + fn_ext)
- msg1 = fr"File (b')?.+does_not_exist\.{fn_ext}'? does not exist"
- msg2 = fr"\[Errno 2\] No such file or directory: '.+does_not_exist\.{fn_ext}'"
+ msg1 = rf"File (b')?.+does_not_exist\.{fn_ext}'? does not exist"
+ msg2 = rf"\[Errno 2\] No such file or directory: '.+does_not_exist\.{fn_ext}'"
msg3 = "Expected object or value"
msg4 = "path_or_buf needs to be a string file path or file-like"
msg5 = (
- fr"\[Errno 2\] File .+does_not_exist\.{fn_ext} does not exist: "
- fr"'.+does_not_exist\.{fn_ext}'"
+ rf"\[Errno 2\] File .+does_not_exist\.{fn_ext} does not exist: "
+ rf"'.+does_not_exist\.{fn_ext}'"
)
- msg6 = fr"\[Errno 2\] 没有那个文件或目录: '.+does_not_exist\.{fn_ext}'"
+ msg6 = rf"\[Errno 2\] 没有那个文件或目录: '.+does_not_exist\.{fn_ext}'"
msg7 = (
- fr"\[Errno 2\] File o directory non esistente: '.+does_not_exist\.{fn_ext}'"
+ rf"\[Errno 2\] File o directory non esistente: '.+does_not_exist\.{fn_ext}'"
)
- msg8 = fr"Failed to open local file.+does_not_exist\.{fn_ext}"
+ msg8 = rf"Failed to open local file.+does_not_exist\.{fn_ext}"
with pytest.raises(
error_class,
- match=fr"({msg1}|{msg2}|{msg3}|{msg4}|{msg5}|{msg6}|{msg7}|{msg8})",
+ match=rf"({msg1}|{msg2}|{msg3}|{msg4}|{msg5}|{msg6}|{msg7}|{msg8})",
):
reader(path)
@@ -265,23 +265,23 @@ def test_read_expands_user_home_dir(
path = os.path.join("~", "does_not_exist." + fn_ext)
monkeypatch.setattr(icom, "_expand_user", lambda x: os.path.join("foo", x))
- msg1 = fr"File (b')?.+does_not_exist\.{fn_ext}'? does not exist"
- msg2 = fr"\[Errno 2\] No such file or directory: '.+does_not_exist\.{fn_ext}'"
+ msg1 = rf"File (b')?.+does_not_exist\.{fn_ext}'? does not exist"
+ msg2 = rf"\[Errno 2\] No such file or directory: '.+does_not_exist\.{fn_ext}'"
msg3 = "Unexpected character found when decoding 'false'"
msg4 = "path_or_buf needs to be a string file path or file-like"
msg5 = (
- fr"\[Errno 2\] File .+does_not_exist\.{fn_ext} does not exist: "
- fr"'.+does_not_exist\.{fn_ext}'"
+ rf"\[Errno 2\] File .+does_not_exist\.{fn_ext} does not exist: "
+ rf"'.+does_not_exist\.{fn_ext}'"
)
- msg6 = fr"\[Errno 2\] 没有那个文件或目录: '.+does_not_exist\.{fn_ext}'"
+ msg6 = rf"\[Errno 2\] 没有那个文件或目录: '.+does_not_exist\.{fn_ext}'"
msg7 = (
- fr"\[Errno 2\] File o directory non esistente: '.+does_not_exist\.{fn_ext}'"
+ rf"\[Errno 2\] File o directory non esistente: '.+does_not_exist\.{fn_ext}'"
)
- msg8 = fr"Failed to open local file.+does_not_exist\.{fn_ext}"
+ msg8 = rf"Failed to open local file.+does_not_exist\.{fn_ext}"
with pytest.raises(
error_class,
- match=fr"({msg1}|{msg2}|{msg3}|{msg4}|{msg5}|{msg6}|{msg7}|{msg8})",
+ match=rf"({msg1}|{msg2}|{msg3}|{msg4}|{msg5}|{msg6}|{msg7}|{msg8})",
):
reader(path)
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 8263c437030eb..4d483099157ae 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -369,7 +369,7 @@ def test_frame1():
def test_frame3():
columns = ["index", "A", "B"]
data = [
- ("2000-01-03 00:00:00", 2 ** 31 - 1, -1.987670),
+ ("2000-01-03 00:00:00", 2**31 - 1, -1.987670),
("2000-01-04 00:00:00", -29, -0.0412318367011),
("2000-01-05 00:00:00", 20000, 0.731167677815),
("2000-01-06 00:00:00", -290867, 1.56762092543),
@@ -1721,7 +1721,7 @@ def test_default_type_conversion(self):
def test_bigint(self):
# int64 should be converted to BigInteger, GH7433
- df = DataFrame(data={"i64": [2 ** 62]})
+ df = DataFrame(data={"i64": [2**62]})
assert df.to_sql("test_bigint", self.conn, index=False) == 1
result = sql.read_sql_table("test_bigint", self.conn)
@@ -1963,7 +1963,7 @@ def test_datetime_time(self):
def test_mixed_dtype_insert(self):
# see GH6509
- s1 = Series(2 ** 25 + 1, dtype=np.int32)
+ s1 = Series(2**25 + 1, dtype=np.int32)
s2 = Series(0.0, dtype=np.float32)
df = DataFrame({"s1": s1, "s2": s2})
diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py
index f0fd391c2a9c4..235b285551ecc 100644
--- a/pandas/tests/io/test_stata.py
+++ b/pandas/tests/io/test_stata.py
@@ -477,9 +477,9 @@ def test_read_write_dta12(self, version):
tm.assert_frame_equal(written_and_read_again.set_index("index"), formatted)
def test_read_write_dta13(self):
- s1 = Series(2 ** 9, dtype=np.int16)
- s2 = Series(2 ** 17, dtype=np.int32)
- s3 = Series(2 ** 33, dtype=np.int64)
+ s1 = Series(2**9, dtype=np.int16)
+ s2 = Series(2**17, dtype=np.int32)
+ s3 = Series(2**33, dtype=np.int64)
original = DataFrame({"int16": s1, "int32": s2, "int64": s3})
original.index.name = "index"
@@ -610,8 +610,8 @@ def test_string_no_dates(self):
def test_large_value_conversion(self):
s0 = Series([1, 99], dtype=np.int8)
s1 = Series([1, 127], dtype=np.int8)
- s2 = Series([1, 2 ** 15 - 1], dtype=np.int16)
- s3 = Series([1, 2 ** 63 - 1], dtype=np.int64)
+ s2 = Series([1, 2**15 - 1], dtype=np.int16)
+ s3 = Series([1, 2**63 - 1], dtype=np.int64)
original = DataFrame({"s0": s0, "s1": s1, "s2": s2, "s3": s3})
original.index.name = "index"
with tm.ensure_clean() as path:
@@ -699,10 +699,10 @@ def test_bool_uint(self, byteorder, version):
s0 = Series([0, 1, True], dtype=np.bool_)
s1 = Series([0, 1, 100], dtype=np.uint8)
s2 = Series([0, 1, 255], dtype=np.uint8)
- s3 = Series([0, 1, 2 ** 15 - 100], dtype=np.uint16)
- s4 = Series([0, 1, 2 ** 16 - 1], dtype=np.uint16)
- s5 = Series([0, 1, 2 ** 31 - 100], dtype=np.uint32)
- s6 = Series([0, 1, 2 ** 32 - 1], dtype=np.uint32)
+ s3 = Series([0, 1, 2**15 - 100], dtype=np.uint16)
+ s4 = Series([0, 1, 2**16 - 1], dtype=np.uint16)
+ s5 = Series([0, 1, 2**31 - 100], dtype=np.uint32)
+ s6 = Series([0, 1, 2**32 - 1], dtype=np.uint32)
original = DataFrame(
{"s0": s0, "s1": s1, "s2": s2, "s3": s3, "s4": s4, "s5": s5, "s6": s6}
@@ -1999,7 +1999,7 @@ def test_iterator_value_labels():
def test_precision_loss():
df = DataFrame(
- [[sum(2 ** i for i in range(60)), sum(2 ** i for i in range(52))]],
+ [[sum(2**i for i in range(60)), sum(2**i for i in range(52))]],
columns=["big", "little"],
)
with tm.ensure_clean() as path:
diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py
index d595f4b453b28..8243b6b73f8d8 100644
--- a/pandas/tests/plotting/test_converter.py
+++ b/pandas/tests/plotting/test_converter.py
@@ -213,7 +213,7 @@ def test_conversion(self):
assert rs[1] == xp
def test_conversion_float(self):
- rtol = 0.5 * 10 ** -9
+ rtol = 0.5 * 10**-9
rs = self.dtc.convert(Timestamp("2012-1-1 01:02:03", tz="UTC"), None, None)
xp = converter.dates.date2num(Timestamp("2012-1-1 01:02:03", tz="UTC"))
@@ -261,7 +261,7 @@ def test_time_formatter(self, time, format_expected):
assert result == format_expected
def test_dateindex_conversion(self):
- rtol = 10 ** -9
+ rtol = 10**-9
for freq in ("B", "L", "S"):
dateindex = tm.makeDateIndex(k=10, freq=freq)
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index 70e739d1440d6..445f3aa7defec 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -210,8 +210,8 @@ class TestIndexReductions:
[
(0, 400, 3),
(500, 0, -6),
- (-(10 ** 6), 10 ** 6, 4),
- (10 ** 6, -(10 ** 6), -4),
+ (-(10**6), 10**6, 4),
+ (10**6, -(10**6), -4),
(0, 10, 20),
],
)
@@ -1451,16 +1451,16 @@ def test_mode_category(self, dropna, expected1, expected2, expected3):
@pytest.mark.parametrize(
"dropna, expected1, expected2",
- [(True, [2 ** 63], [1, 2 ** 63]), (False, [2 ** 63], [1, 2 ** 63])],
+ [(True, [2**63], [1, 2**63]), (False, [2**63], [1, 2**63])],
)
def test_mode_intoverflow(self, dropna, expected1, expected2):
# Test for uint64 overflow.
- s = Series([1, 2 ** 63, 2 ** 63], dtype=np.uint64)
+ s = Series([1, 2**63, 2**63], dtype=np.uint64)
result = s.mode(dropna)
expected1 = Series(expected1, dtype=np.uint64)
tm.assert_series_equal(result, expected1)
- s = Series([1, 2 ** 63], dtype=np.uint64)
+ s = Series([1, 2**63], dtype=np.uint64)
result = s.mode(dropna)
expected2 = Series(expected2, dtype=np.uint64)
tm.assert_series_equal(result, expected2)
diff --git a/pandas/tests/reductions/test_stat_reductions.py b/pandas/tests/reductions/test_stat_reductions.py
index 2f1ae5df0d5d4..0a6c0ccc891bb 100644
--- a/pandas/tests/reductions/test_stat_reductions.py
+++ b/pandas/tests/reductions/test_stat_reductions.py
@@ -128,7 +128,7 @@ def _check_stat_op(
# GH#2888
items = [0]
- items.extend(range(2 ** 40, 2 ** 40 + 1000))
+ items.extend(range(2**40, 2**40 + 1000))
s = Series(items, dtype="int64")
tm.assert_almost_equal(float(f(s)), float(alternate(s.values)))
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index a023adfb509a0..3caa54e11f8ed 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -2004,7 +2004,7 @@ def __init__(self, *args, **kwargs):
with monkeypatch.context() as m:
m.setattr(reshape_lib, "_Unstacker", MockUnstacker)
df = DataFrame(
- {"ind1": np.arange(2 ** 16), "ind2": np.arange(2 ** 16), "count": 0}
+ {"ind1": np.arange(2**16), "ind2": np.arange(2**16), "count": 0}
)
msg = "The following operation may generate"
diff --git a/pandas/tests/scalar/test_na_scalar.py b/pandas/tests/scalar/test_na_scalar.py
index 77265e8745315..88b06ec578905 100644
--- a/pandas/tests/scalar/test_na_scalar.py
+++ b/pandas/tests/scalar/test_na_scalar.py
@@ -100,7 +100,7 @@ def test_comparison_ops():
def test_pow_special(value, asarray):
if asarray:
value = np.array([value])
- result = NA ** value
+ result = NA**value
if asarray:
result = result[0]
@@ -117,7 +117,7 @@ def test_pow_special(value, asarray):
def test_rpow_special(value, asarray):
if asarray:
value = np.array([value])
- result = value ** NA
+ result = value**NA
if asarray:
result = result[0]
@@ -133,7 +133,7 @@ def test_rpow_special(value, asarray):
def test_rpow_minus_one(value, asarray):
if asarray:
value = np.array([value])
- result = value ** NA
+ result = value**NA
if asarray:
result = result[0]
diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py
index 36ad24f2e1ef2..ff1f6ad42feb3 100644
--- a/pandas/tests/scalar/timedelta/test_arithmetic.py
+++ b/pandas/tests/scalar/timedelta/test_arithmetic.py
@@ -427,9 +427,9 @@ def test_td_div_td64_non_nano(self):
# truediv
td = Timedelta("1 days 2 hours 3 ns")
result = td / np.timedelta64(1, "D")
- assert result == td.value / (86400 * 10 ** 9)
+ assert result == td.value / (86400 * 10**9)
result = td / np.timedelta64(1, "s")
- assert result == td.value / 10 ** 9
+ assert result == td.value / 10**9
result = td / np.timedelta64(1, "ns")
assert result == td.value
@@ -694,7 +694,7 @@ def test_td_rfloordiv_timedeltalike_array(self):
def test_td_rfloordiv_intarray(self):
# deprecated GH#19761, enforced GH#29797
- ints = np.array([1349654400, 1349740800, 1349827200, 1349913600]) * 10 ** 9
+ ints = np.array([1349654400, 1349740800, 1349827200, 1349913600]) * 10**9
msg = "Invalid dtype"
with pytest.raises(TypeError, match=msg):
diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py
index 2ff1de51c33ad..b46962fb82896 100644
--- a/pandas/tests/scalar/timestamp/test_arithmetic.py
+++ b/pandas/tests/scalar/timestamp/test_arithmetic.py
@@ -61,7 +61,7 @@ def test_overflow_offset_raises(self):
# used to crash, so check for proper overflow exception
stamp = Timestamp("2000/1/1")
- offset_overflow = to_offset("D") * 100 ** 5
+ offset_overflow = to_offset("D") * 100**5
with pytest.raises(OverflowError, match=lmsg):
stamp + offset_overflow
diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py
index b3deb1a57e5c3..25f3f9c98023b 100644
--- a/pandas/tests/scalar/timestamp/test_constructors.py
+++ b/pandas/tests/scalar/timestamp/test_constructors.py
@@ -292,20 +292,17 @@ def test_constructor_keyword(self):
Timestamp("20151112")
)
- assert (
- repr(
- Timestamp(
- year=2015,
- month=11,
- day=12,
- hour=1,
- minute=2,
- second=3,
- microsecond=999999,
- )
+ assert repr(
+ Timestamp(
+ year=2015,
+ month=11,
+ day=12,
+ hour=1,
+ minute=2,
+ second=3,
+ microsecond=999999,
)
- == repr(Timestamp("2015-11-12 01:02:03.999999"))
- )
+ ) == repr(Timestamp("2015-11-12 01:02:03.999999"))
@pytest.mark.filterwarnings("ignore:Timestamp.freq is:FutureWarning")
@pytest.mark.filterwarnings("ignore:The 'freq' argument:FutureWarning")
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index fb07b28c5a54f..c3f82ff3d8285 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -1058,7 +1058,7 @@ def inplace(self):
[
np.array([2.0, 3.0]),
np.array([2.5, 3.5]),
- np.array([2 ** 65, 2 ** 65 + 1], dtype=np.float64), # all ints, but can't cast
+ np.array([2**65, 2**65 + 1], dtype=np.float64), # all ints, but can't cast
],
)
class TestSetitemFloatNDarrayIntoIntegerSeries(SetitemCastingEquivalents):
@@ -1117,7 +1117,7 @@ def test_mask_key(self, obj, key, expected, val, indexer_sli, request):
super().test_mask_key(obj, key, expected, val, indexer_sli)
-@pytest.mark.parametrize("val", [2 ** 33 + 1.0, 2 ** 33 + 1.1, 2 ** 62])
+@pytest.mark.parametrize("val", [2**33 + 1.0, 2**33 + 1.1, 2**62])
class TestSmallIntegerSetitemUpcast(SetitemCastingEquivalents):
# https://github.com/pandas-dev/pandas/issues/39584#issuecomment-941212124
@pytest.fixture
@@ -1134,9 +1134,9 @@ def inplace(self):
@pytest.fixture
def expected(self, val):
- if val == 2 ** 62:
+ if val == 2**62:
return Series([val, 2, 3], dtype="i8")
- elif val == 2 ** 33 + 1.1:
+ elif val == 2**33 + 1.1:
return Series([val, 2, 3], dtype="f8")
else:
return Series([val, 2, 3], dtype="i8")
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
index 8197722687e78..01140f29aa5d9 100644
--- a/pandas/tests/series/methods/test_astype.py
+++ b/pandas/tests/series/methods/test_astype.py
@@ -135,8 +135,8 @@ def test_astype_generic_timestamp_no_frequency(self, dtype, request):
request.node.add_marker(mark)
msg = (
- fr"The '{dtype.__name__}' dtype has no unit\. "
- fr"Please pass in '{dtype.__name__}\[ns\]' instead."
+ rf"The '{dtype.__name__}' dtype has no unit\. "
+ rf"Please pass in '{dtype.__name__}\[ns\]' instead."
)
with pytest.raises(ValueError, match=msg):
ser.astype(dtype)
diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py
index 9617565cab0b4..d3667c9343f53 100644
--- a/pandas/tests/series/methods/test_fillna.py
+++ b/pandas/tests/series/methods/test_fillna.py
@@ -277,7 +277,7 @@ def test_timedelta_fillna(self, frame_or_series):
expected = frame_or_series(expected)
tm.assert_equal(result, expected)
- result = obj.fillna(np.timedelta64(10 ** 9))
+ result = obj.fillna(np.timedelta64(10**9))
expected = Series(
[
timedelta(seconds=1),
diff --git a/pandas/tests/series/methods/test_isin.py b/pandas/tests/series/methods/test_isin.py
index f769c08a512ef..2288dfb5c2409 100644
--- a/pandas/tests/series/methods/test_isin.py
+++ b/pandas/tests/series/methods/test_isin.py
@@ -22,7 +22,7 @@ def test_isin(self):
# This specific issue has to have a series over 1e6 in len, but the
# comparison array (in_list) must be large enough so that numpy doesn't
# do a manual masking trick that will avoid this issue altogether
- s = Series(list("abcdefghijk" * 10 ** 5))
+ s = Series(list("abcdefghijk" * 10**5))
# If numpy doesn't do the manual comparison/mask, these
# unorderable mixed types are what cause the exception in numpy
in_list = [-1, "a", "b", "G", "Y", "Z", "E", "K", "E", "S", "I", "R", "R"] * 6
diff --git a/pandas/tests/series/methods/test_rank.py b/pandas/tests/series/methods/test_rank.py
index b49ffda4a7a91..4ab99673dfe46 100644
--- a/pandas/tests/series/methods/test_rank.py
+++ b/pandas/tests/series/methods/test_rank.py
@@ -479,6 +479,6 @@ def test_rank_first_pct(dtype, ser, exp):
@pytest.mark.high_memory
def test_pct_max_many_rows():
# GH 18271
- s = Series(np.arange(2 ** 24 + 1))
+ s = Series(np.arange(2**24 + 1))
result = s.rank(pct=True).max()
assert result == 1
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index cab5fd456d69f..293ae86a3965f 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -1585,28 +1585,28 @@ def test_constructor_range_dtype(self, dtype):
def test_constructor_range_overflows(self):
# GH#30173 range objects that overflow int64
- rng = range(2 ** 63, 2 ** 63 + 4)
+ rng = range(2**63, 2**63 + 4)
ser = Series(rng)
expected = Series(list(rng))
tm.assert_series_equal(ser, expected)
assert list(ser) == list(rng)
assert ser.dtype == np.uint64
- rng2 = range(2 ** 63 + 4, 2 ** 63, -1)
+ rng2 = range(2**63 + 4, 2**63, -1)
ser2 = Series(rng2)
expected2 = Series(list(rng2))
tm.assert_series_equal(ser2, expected2)
assert list(ser2) == list(rng2)
assert ser2.dtype == np.uint64
- rng3 = range(-(2 ** 63), -(2 ** 63) - 4, -1)
+ rng3 = range(-(2**63), -(2**63) - 4, -1)
ser3 = Series(rng3)
expected3 = Series(list(rng3))
tm.assert_series_equal(ser3, expected3)
assert list(ser3) == list(rng3)
assert ser3.dtype == object
- rng4 = range(2 ** 73, 2 ** 73 + 4)
+ rng4 = range(2**73, 2**73 + 4)
ser4 = Series(rng4)
expected4 = Series(list(rng4))
tm.assert_series_equal(ser4, expected4)
diff --git a/pandas/tests/series/test_reductions.py b/pandas/tests/series/test_reductions.py
index 8fb51af70f3a0..d2a3de7577353 100644
--- a/pandas/tests/series/test_reductions.py
+++ b/pandas/tests/series/test_reductions.py
@@ -94,7 +94,7 @@ def test_validate_any_all_out_keepdims_raises(kwargs, func):
msg = (
f"the '{param}' parameter is not "
"supported in the pandas "
- fr"implementation of {name}\(\)"
+ rf"implementation of {name}\(\)"
)
with pytest.raises(ValueError, match=msg):
func(ser, **kwargs)
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 0007a966840e8..5cae600bbd8b8 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -266,20 +266,20 @@ def test_float64_factorize(self, writable):
tm.assert_numpy_array_equal(uniques, expected_uniques)
def test_uint64_factorize(self, writable):
- data = np.array([2 ** 64 - 1, 1, 2 ** 64 - 1], dtype=np.uint64)
+ data = np.array([2**64 - 1, 1, 2**64 - 1], dtype=np.uint64)
data.setflags(write=writable)
expected_codes = np.array([0, 1, 0], dtype=np.intp)
- expected_uniques = np.array([2 ** 64 - 1, 1], dtype=np.uint64)
+ expected_uniques = np.array([2**64 - 1, 1], dtype=np.uint64)
codes, uniques = algos.factorize(data)
tm.assert_numpy_array_equal(codes, expected_codes)
tm.assert_numpy_array_equal(uniques, expected_uniques)
def test_int64_factorize(self, writable):
- data = np.array([2 ** 63 - 1, -(2 ** 63), 2 ** 63 - 1], dtype=np.int64)
+ data = np.array([2**63 - 1, -(2**63), 2**63 - 1], dtype=np.int64)
data.setflags(write=writable)
expected_codes = np.array([0, 1, 0], dtype=np.intp)
- expected_uniques = np.array([2 ** 63 - 1, -(2 ** 63)], dtype=np.int64)
+ expected_uniques = np.array([2**63 - 1, -(2**63)], dtype=np.int64)
codes, uniques = algos.factorize(data)
tm.assert_numpy_array_equal(codes, expected_codes)
@@ -354,7 +354,7 @@ def test_factorize_rangeindex_decreasing(self, sort):
def test_deprecate_order(self):
# gh 19727 - check warning is raised for deprecated keyword, order.
# Test not valid once order keyword is removed.
- data = np.array([2 ** 63, 1, 2 ** 63], dtype=np.uint64)
+ data = np.array([2**63, 1, 2**63], dtype=np.uint64)
with pytest.raises(TypeError, match="got an unexpected keyword"):
algos.factorize(data, order=True)
with tm.assert_produces_warning(False):
@@ -364,7 +364,7 @@ def test_deprecate_order(self):
"data",
[
np.array([0, 1, 0], dtype="u8"),
- np.array([-(2 ** 63), 1, -(2 ** 63)], dtype="i8"),
+ np.array([-(2**63), 1, -(2**63)], dtype="i8"),
np.array(["__nan__", "foo", "__nan__"], dtype="object"),
],
)
@@ -381,8 +381,8 @@ def test_parametrized_factorize_na_value_default(self, data):
[
(np.array([0, 1, 0, 2], dtype="u8"), 0),
(np.array([1, 0, 1, 2], dtype="u8"), 1),
- (np.array([-(2 ** 63), 1, -(2 ** 63), 0], dtype="i8"), -(2 ** 63)),
- (np.array([1, -(2 ** 63), 1, 0], dtype="i8"), 1),
+ (np.array([-(2**63), 1, -(2**63), 0], dtype="i8"), -(2**63)),
+ (np.array([1, -(2**63), 1, 0], dtype="i8"), 1),
(np.array(["a", "", "a", "b"], dtype=object), "a"),
(np.array([(), ("a", 1), (), ("a", 2)], dtype=object), ()),
(np.array([("a", 1), (), ("a", 1), ("a", 2)], dtype=object), ("a", 1)),
@@ -601,8 +601,8 @@ def test_timedelta64_dtype_array_returned(self):
assert result.dtype == expected.dtype
def test_uint64_overflow(self):
- s = Series([1, 2, 2 ** 63, 2 ** 63], dtype=np.uint64)
- exp = np.array([1, 2, 2 ** 63], dtype=np.uint64)
+ s = Series([1, 2, 2**63, 2**63], dtype=np.uint64)
+ exp = np.array([1, 2, 2**63], dtype=np.uint64)
tm.assert_numpy_array_equal(algos.unique(s), exp)
def test_nan_in_object_array(self):
@@ -1280,14 +1280,14 @@ def test_value_counts_normalized(self, dtype):
tm.assert_series_equal(result, expected)
def test_value_counts_uint64(self):
- arr = np.array([2 ** 63], dtype=np.uint64)
- expected = Series([1], index=[2 ** 63])
+ arr = np.array([2**63], dtype=np.uint64)
+ expected = Series([1], index=[2**63])
result = algos.value_counts(arr)
tm.assert_series_equal(result, expected)
- arr = np.array([-1, 2 ** 63], dtype=object)
- expected = Series([1, 1], index=[-1, 2 ** 63])
+ arr = np.array([-1, 2**63], dtype=object)
+ expected = Series([1, 1], index=[-1, 2**63])
result = algos.value_counts(arr)
tm.assert_series_equal(result, expected)
@@ -1354,7 +1354,7 @@ def test_duplicated_with_nas(self):
),
np.array(["a", "b", "a", "e", "c", "b", "d", "a", "e", "f"], dtype=object),
np.array(
- [1, 2 ** 63, 1, 3 ** 5, 10, 2 ** 63, 39, 1, 3 ** 5, 7], dtype=np.uint64
+ [1, 2**63, 1, 3**5, 10, 2**63, 39, 1, 3**5, 7], dtype=np.uint64
),
],
)
@@ -1572,7 +1572,7 @@ def test_add_different_nans(self):
assert len(m) == 1 # NAN1 and NAN2 are equivalent
def test_lookup_overflow(self, writable):
- xs = np.array([1, 2, 2 ** 63], dtype=np.uint64)
+ xs = np.array([1, 2, 2**63], dtype=np.uint64)
# GH 21688 ensure we can deal with readonly memory views
xs.setflags(write=writable)
m = ht.UInt64HashTable()
@@ -1580,8 +1580,8 @@ def test_lookup_overflow(self, writable):
tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), dtype=np.intp))
def test_get_unique(self):
- s = Series([1, 2, 2 ** 63, 2 ** 63], dtype=np.uint64)
- exp = np.array([1, 2, 2 ** 63], dtype=np.uint64)
+ s = Series([1, 2, 2**63, 2**63], dtype=np.uint64)
+ exp = np.array([1, 2, 2**63], dtype=np.uint64)
tm.assert_numpy_array_equal(s.unique(), exp)
@pytest.mark.parametrize("nvals", [0, 10]) # resizing to 0 is special case
@@ -1777,7 +1777,7 @@ def test_basic(self, writable, dtype):
def test_uint64_overflow(self, dtype):
exp = np.array([1, 2], dtype=np.float64)
- s = Series([1, 2 ** 63], dtype=dtype)
+ s = Series([1, 2**63], dtype=dtype)
tm.assert_numpy_array_equal(algos.rank(s), exp)
def test_too_many_ndims(self):
@@ -1791,11 +1791,11 @@ def test_too_many_ndims(self):
@pytest.mark.high_memory
def test_pct_max_many_rows(self):
# GH 18271
- values = np.arange(2 ** 24 + 1)
+ values = np.arange(2**24 + 1)
result = algos.rank(values, pct=True).max()
assert result == 1
- values = np.arange(2 ** 25 + 2).reshape(2 ** 24 + 1, 2)
+ values = np.arange(2**25 + 2).reshape(2**24 + 1, 2)
result = algos.rank(values, pct=True).max()
assert result == 1
@@ -2361,13 +2361,13 @@ def test_mixed_dtype(self):
tm.assert_series_equal(ser.mode(), exp)
def test_uint64_overflow(self):
- exp = Series([2 ** 63], dtype=np.uint64)
- ser = Series([1, 2 ** 63, 2 ** 63], dtype=np.uint64)
+ exp = Series([2**63], dtype=np.uint64)
+ ser = Series([1, 2**63, 2**63], dtype=np.uint64)
tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
tm.assert_series_equal(ser.mode(), exp)
- exp = Series([1, 2 ** 63], dtype=np.uint64)
- ser = Series([1, 2 ** 63], dtype=np.uint64)
+ exp = Series([1, 2**63], dtype=np.uint64)
+ ser = Series([1, 2**63], dtype=np.uint64)
tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
tm.assert_series_equal(ser.mode(), exp)
diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py
index 0850ba66bbdbd..cbd11cd6d8685 100644
--- a/pandas/tests/test_common.py
+++ b/pandas/tests/test_common.py
@@ -64,7 +64,7 @@ def test_random_state():
# check array-like
# GH32503
- state_arr_like = npr.randint(0, 2 ** 31, size=624, dtype="uint32")
+ state_arr_like = npr.randint(0, 2**31, size=624, dtype="uint32")
assert (
com.random_state(state_arr_like).uniform()
== npr.RandomState(state_arr_like).uniform()
diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py
index ee451d0288581..44977b9834b80 100644
--- a/pandas/tests/test_nanops.py
+++ b/pandas/tests/test_nanops.py
@@ -305,7 +305,7 @@ def test_nanmean_overflow(self):
# In the previous implementation mean can overflow for int dtypes, it
# is now consistent with numpy
- for a in [2 ** 55, -(2 ** 55), 20150515061816532]:
+ for a in [2**55, -(2**55), 20150515061816532]:
s = Series(a, index=range(500), dtype=np.int64)
result = s.mean()
np_result = s.values.mean()
@@ -789,7 +789,7 @@ class TestNanvarFixedValues:
def setup_method(self, method):
# Samples from a normal distribution.
self.variance = variance = 3.0
- self.samples = self.prng.normal(scale=variance ** 0.5, size=100000)
+ self.samples = self.prng.normal(scale=variance**0.5, size=100000)
def test_nanvar_all_finite(self):
samples = self.samples
@@ -811,7 +811,7 @@ def test_nanstd_nans(self):
samples[::2] = self.samples
actual_std = nanops.nanstd(samples, skipna=True)
- tm.assert_almost_equal(actual_std, self.variance ** 0.5, rtol=1e-2)
+ tm.assert_almost_equal(actual_std, self.variance**0.5, rtol=1e-2)
actual_std = nanops.nanvar(samples, skipna=False)
tm.assert_almost_equal(actual_std, np.nan, rtol=1e-2)
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 0a9d422c45036..fa95693369416 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -982,7 +982,7 @@ def test_datetime_invalid_index(self, values, format, infer):
@pytest.mark.parametrize("constructor", [list, tuple, np.array, Index, deque])
def test_to_datetime_cache(self, utc, format, constructor):
date = "20130101 00:00:00"
- test_dates = [date] * 10 ** 5
+ test_dates = [date] * 10**5
data = constructor(test_dates)
result = to_datetime(data, utc=utc, format=format, cache=True)
@@ -1000,7 +1000,7 @@ def test_to_datetime_from_deque(self):
@pytest.mark.parametrize("format", ["%Y%m%d %H:%M:%S", None])
def test_to_datetime_cache_series(self, utc, format):
date = "20130101 00:00:00"
- test_dates = [date] * 10 ** 5
+ test_dates = [date] * 10**5
data = Series(test_dates)
result = to_datetime(data, utc=utc, format=format, cache=True)
expected = to_datetime(data, utc=utc, format=format, cache=False)
@@ -2624,7 +2624,7 @@ def test_no_slicing_errors_in_should_cache(self, listlike):
def test_nullable_integer_to_datetime():
# Test for #30050
- ser = Series([1, 2, None, 2 ** 61, None])
+ ser = Series([1, 2, None, 2**61, None])
ser = ser.astype("Int64")
ser_copy = ser.copy()
diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py
index ec6fccd42dbc9..cf512463d0473 100644
--- a/pandas/tests/tools/test_to_timedelta.py
+++ b/pandas/tests/tools/test_to_timedelta.py
@@ -217,7 +217,7 @@ def test_to_timedelta_float(self):
# https://github.com/pandas-dev/pandas/issues/25077
arr = np.arange(0, 1, 1e-6)[-10:]
result = to_timedelta(arr, unit="s")
- expected_asi8 = np.arange(999990000, 10 ** 9, 1000, dtype="int64")
+ expected_asi8 = np.arange(999990000, 10**9, 1000, dtype="int64")
tm.assert_numpy_array_equal(result.asi8, expected_asi8)
def test_to_timedelta_coerce_strings_unit(self):
diff --git a/pandas/tests/tslibs/test_fields.py b/pandas/tests/tslibs/test_fields.py
index 9d0b3ff4fca80..9e6464f7727bd 100644
--- a/pandas/tests/tslibs/test_fields.py
+++ b/pandas/tests/tslibs/test_fields.py
@@ -8,7 +8,7 @@
@pytest.fixture
def dtindex():
- dtindex = np.arange(5, dtype=np.int64) * 10 ** 9 * 3600 * 24 * 32
+ dtindex = np.arange(5, dtype=np.int64) * 10**9 * 3600 * 24 * 32
dtindex.flags.writeable = False
return dtindex
diff --git a/pandas/tests/util/test_assert_extension_array_equal.py b/pandas/tests/util/test_assert_extension_array_equal.py
index 545f0dcbf695f..dec10e5b76894 100644
--- a/pandas/tests/util/test_assert_extension_array_equal.py
+++ b/pandas/tests/util/test_assert_extension_array_equal.py
@@ -35,7 +35,7 @@ def test_assert_extension_array_equal_not_exact(kwargs):
@pytest.mark.parametrize("decimals", range(10))
def test_assert_extension_array_equal_less_precise(decimals):
- rtol = 0.5 * 10 ** -decimals
+ rtol = 0.5 * 10**-decimals
arr1 = SparseArray([0.5, 0.123456])
arr2 = SparseArray([0.5, 0.123457])
diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py
index 150e7e8f3d738..93a2e4b83e760 100644
--- a/pandas/tests/util/test_assert_series_equal.py
+++ b/pandas/tests/util/test_assert_series_equal.py
@@ -110,7 +110,7 @@ def test_series_not_equal_metadata_mismatch(kwargs):
@pytest.mark.parametrize("dtype", ["float32", "float64", "Float32"])
@pytest.mark.parametrize("decimals", [0, 1, 2, 3, 5, 10])
def test_less_precise(data1, data2, dtype, decimals):
- rtol = 10 ** -decimals
+ rtol = 10**-decimals
s1 = Series([data1], dtype=dtype)
s2 = Series([data2], dtype=dtype)
diff --git a/pandas/tests/util/test_validate_args.py b/pandas/tests/util/test_validate_args.py
index db532480efe07..77e6b01ba1180 100644
--- a/pandas/tests/util/test_validate_args.py
+++ b/pandas/tests/util/test_validate_args.py
@@ -20,8 +20,8 @@ def test_bad_arg_length_max_value_single():
max_length = len(compat_args) + min_fname_arg_count
actual_length = len(args) + min_fname_arg_count
msg = (
- fr"{_fname}\(\) takes at most {max_length} "
- fr"argument \({actual_length} given\)"
+ rf"{_fname}\(\) takes at most {max_length} "
+ rf"argument \({actual_length} given\)"
)
with pytest.raises(TypeError, match=msg):
@@ -36,8 +36,8 @@ def test_bad_arg_length_max_value_multiple():
max_length = len(compat_args) + min_fname_arg_count
actual_length = len(args) + min_fname_arg_count
msg = (
- fr"{_fname}\(\) takes at most {max_length} "
- fr"arguments \({actual_length} given\)"
+ rf"{_fname}\(\) takes at most {max_length} "
+ rf"arguments \({actual_length} given\)"
)
with pytest.raises(TypeError, match=msg):
@@ -49,7 +49,7 @@ def test_not_all_defaults(i):
bad_arg = "foo"
msg = (
f"the '{bad_arg}' parameter is not supported "
- fr"in the pandas implementation of {_fname}\(\)"
+ rf"in the pandas implementation of {_fname}\(\)"
)
compat_args = {"foo": 2, "bar": -1, "baz": 3}
diff --git a/pandas/tests/util/test_validate_args_and_kwargs.py b/pandas/tests/util/test_validate_args_and_kwargs.py
index 941ba86c61319..54d94d2194909 100644
--- a/pandas/tests/util/test_validate_args_and_kwargs.py
+++ b/pandas/tests/util/test_validate_args_and_kwargs.py
@@ -15,8 +15,8 @@ def test_invalid_total_length_max_length_one():
actual_length = len(kwargs) + len(args) + min_fname_arg_count
msg = (
- fr"{_fname}\(\) takes at most {max_length} "
- fr"argument \({actual_length} given\)"
+ rf"{_fname}\(\) takes at most {max_length} "
+ rf"argument \({actual_length} given\)"
)
with pytest.raises(TypeError, match=msg):
@@ -33,8 +33,8 @@ def test_invalid_total_length_max_length_multiple():
actual_length = len(kwargs) + len(args) + min_fname_arg_count
msg = (
- fr"{_fname}\(\) takes at most {max_length} "
- fr"arguments \({actual_length} given\)"
+ rf"{_fname}\(\) takes at most {max_length} "
+ rf"arguments \({actual_length} given\)"
)
with pytest.raises(TypeError, match=msg):
@@ -49,8 +49,8 @@ def test_missing_args_or_kwargs(args, kwargs):
compat_args = {"foo": -5, bad_arg: 1}
msg = (
- fr"the '{bad_arg}' parameter is not supported "
- fr"in the pandas implementation of {_fname}\(\)"
+ rf"the '{bad_arg}' parameter is not supported "
+ rf"in the pandas implementation of {_fname}\(\)"
)
with pytest.raises(ValueError, match=msg):
@@ -64,7 +64,7 @@ def test_duplicate_argument():
kwargs = {"foo": None, "bar": None}
args = (None,) # duplicate value for "foo"
- msg = fr"{_fname}\(\) got multiple values for keyword argument 'foo'"
+ msg = rf"{_fname}\(\) got multiple values for keyword argument 'foo'"
with pytest.raises(TypeError, match=msg):
validate_args_and_kwargs(_fname, args, kwargs, min_fname_arg_count, compat_args)
diff --git a/pandas/tests/util/test_validate_kwargs.py b/pandas/tests/util/test_validate_kwargs.py
index 0e271ef42ca93..de49cdd5e247d 100644
--- a/pandas/tests/util/test_validate_kwargs.py
+++ b/pandas/tests/util/test_validate_kwargs.py
@@ -15,7 +15,7 @@ def test_bad_kwarg():
compat_args = {good_arg: "foo", bad_arg + "o": "bar"}
kwargs = {good_arg: "foo", bad_arg: "bar"}
- msg = fr"{_fname}\(\) got an unexpected keyword argument '{bad_arg}'"
+ msg = rf"{_fname}\(\) got an unexpected keyword argument '{bad_arg}'"
with pytest.raises(TypeError, match=msg):
validate_kwargs(_fname, kwargs, compat_args)
@@ -25,8 +25,8 @@ def test_bad_kwarg():
def test_not_all_none(i):
bad_arg = "foo"
msg = (
- fr"the '{bad_arg}' parameter is not supported "
- fr"in the pandas implementation of {_fname}\(\)"
+ rf"the '{bad_arg}' parameter is not supported "
+ rf"in the pandas implementation of {_fname}\(\)"
)
compat_args = {"foo": 1, "bar": "s", "baz": None}
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 6fd3ac53c50cb..c4f6bb30c59ec 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -6,7 +6,7 @@ python-dateutil>=2.8.1
pytz
asv < 0.5.0
cython>=0.29.24
-black==21.5b2
+black==22.3.0
cpplint
flake8==4.0.1
flake8-bugbear==21.3.2
| replacement for #46563 | https://api.github.com/repos/pandas-dev/pandas/pulls/46576 | 2022-03-30T18:53:30Z | 2022-03-30T20:42:10Z | 2022-03-30T20:42:10Z | 2022-03-30T20:42:11Z |
Backport of CI/Build related PRs on 1.4.x (2) | diff --git a/.github/actions/build_pandas/action.yml b/.github/actions/build_pandas/action.yml
index 2e4bfea165316..e916d5bfde5fb 100644
--- a/.github/actions/build_pandas/action.yml
+++ b/.github/actions/build_pandas/action.yml
@@ -8,10 +8,10 @@ runs:
run: |
conda info
conda list
- shell: bash -l {0}
+ shell: bash -el {0}
- name: Build Pandas
run: |
python setup.py build_ext -j 2
python -m pip install -e . --no-build-isolation --no-use-pep517 --no-index
- shell: bash -l {0}
+ shell: bash -el {0}
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml
index 9ef00e7a85a6f..c357f149f2c7f 100644
--- a/.github/actions/setup/action.yml
+++ b/.github/actions/setup/action.yml
@@ -5,8 +5,8 @@ runs:
steps:
- name: Setting conda path
run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
- shell: bash -l {0}
+ shell: bash -el {0}
- name: Setup environment and build pandas
run: ci/setup_env.sh
- shell: bash -l {0}
+ shell: bash -el {0}
diff --git a/.github/workflows/asv-bot.yml b/.github/workflows/asv-bot.yml
index f3946aeb84a63..78c224b84d5d9 100644
--- a/.github/workflows/asv-bot.yml
+++ b/.github/workflows/asv-bot.yml
@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# Set concurrency to prevent abuse(full runs are ~5.5 hours !!!)
@@ -29,19 +29,19 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Cache conda
- uses: actions/cache@v2
+ uses: actions/cache@v3
with:
path: ~/conda_pkgs_dir
key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
# Although asv sets up its own env, deps are still needed
# during discovery process
- - uses: conda-incubator/setup-miniconda@v2
+ - uses: conda-incubator/setup-miniconda@v2.1.1
with:
activate-environment: pandas-dev
channel-priority: strict
@@ -65,7 +65,7 @@ jobs:
echo 'EOF' >> $GITHUB_ENV
echo "REGEX=$REGEX" >> $GITHUB_ENV
- - uses: actions/github-script@v5
+ - uses: actions/github-script@v6
env:
BENCH_OUTPUT: ${{env.BENCH_OUTPUT}}
REGEX: ${{env.REGEX}}
diff --git a/.github/workflows/autoupdate-pre-commit-config.yml b/.github/workflows/autoupdate-pre-commit-config.yml
index 3696cba8cf2e6..d2eac234ca361 100644
--- a/.github/workflows/autoupdate-pre-commit-config.yml
+++ b/.github/workflows/autoupdate-pre-commit-config.yml
@@ -12,9 +12,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
- name: Cache multiple paths
- uses: actions/cache@v2
+ uses: actions/cache@v3
with:
path: |
~/.cache/pre-commit
diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index 7141b02cac376..59fb81b167bd4 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -24,10 +24,10 @@ jobs:
cancel-in-progress: true
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
- name: Install Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: '3.9.7'
@@ -39,7 +39,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
@@ -48,17 +48,17 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Cache conda
- uses: actions/cache@v2
+ uses: actions/cache@v3
with:
path: ~/conda_pkgs_dir
key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
- - uses: conda-incubator/setup-miniconda@v2
+ - uses: conda-incubator/setup-miniconda@v2.1.1
with:
mamba-version: "*"
channels: conda-forge
@@ -68,7 +68,7 @@ jobs:
use-only-tar-bz2: true
- name: Install node.js (for pyright)
- uses: actions/setup-node@v2
+ uses: actions/setup-node@v3
with:
node-version: "16"
@@ -105,7 +105,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
@@ -114,17 +114,17 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Cache conda
- uses: actions/cache@v2
+ uses: actions/cache@v3
with:
path: ~/conda_pkgs_dir
key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
- - uses: conda-incubator/setup-miniconda@v2
+ - uses: conda-incubator/setup-miniconda@v2.1.1
with:
mamba-version: "*"
channels: conda-forge
@@ -151,8 +151,32 @@ jobs:
if: ${{ steps.build.outcome == 'success' }}
- name: Publish benchmarks artifact
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v3
with:
name: Benchmarks log
path: asv_bench/benchmarks.log
if: failure()
+
+ build_docker_dev_environment:
+ name: Build Docker Dev Environment
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ shell: bash -el {0}
+
+ concurrency:
+ # https://github.community/t/concurrecy-not-work-for-push/183068/7
+ group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-build_docker_dev_environment
+ cancel-in-progress: true
+
+ steps:
+ - name: Clean up dangling images
+ run: docker image prune -f
+
+ - name: Checkout
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
+
+ - name: Build image
+ run: docker build --pull --no-cache --tag pandas-dev-env .
diff --git a/.github/workflows/comment_bot.yml b/.github/workflows/comment_bot.yml
index 8f610fd5781ef..3824e015e8336 100644
--- a/.github/workflows/comment_bot.yml
+++ b/.github/workflows/comment_bot.yml
@@ -12,18 +12,18 @@ jobs:
if: startsWith(github.event.comment.body, '@github-actions pre-commit')
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- uses: r-lib/actions/pr-fetch@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
- name: Cache multiple paths
- uses: actions/cache@v2
+ uses: actions/cache@v3
with:
path: |
~/.cache/pre-commit
~/.cache/pip
key: pre-commit-dispatched-${{ runner.os }}-build
- - uses: actions/setup-python@v2
+ - uses: actions/setup-python@v3
with:
python-version: 3.8
- name: Install-pre-commit
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml
index 4cce75779d750..bba9f62a0eca6 100644
--- a/.github/workflows/docbuild-and-upload.yml
+++ b/.github/workflows/docbuild-and-upload.yml
@@ -26,7 +26,7 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
@@ -65,7 +65,7 @@ jobs:
run: mv doc/build/html web/build/docs
- name: Save website as an artifact
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v3
with:
name: website
path: web/build
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index 0d5ef807a3392..ea9df610c1dff 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -20,7 +20,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
timeout-minutes: 120
strategy:
matrix:
@@ -121,12 +121,12 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Cache conda
- uses: actions/cache@v2
+ uses: actions/cache@v3
env:
CACHE_NUMBER: 0
with:
@@ -138,7 +138,7 @@ jobs:
# xsel for clipboard tests
run: sudo apt-get update && sudo apt-get install -y libc6-dev-i386 xsel ${{ env.EXTRA_APT }}
- - uses: conda-incubator/setup-miniconda@v2
+ - uses: conda-incubator/setup-miniconda@v2.1.1
with:
mamba-version: "*"
channels: conda-forge
@@ -153,13 +153,12 @@ jobs:
if: ${{ matrix.pyarrow_version }}
- name: Setup PyPy
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: "pypy-3.8"
if: ${{ env.IS_PYPY == 'true' }}
- name: Setup PyPy dependencies
- shell: bash
run: |
# TODO: re-enable cov, its slowing the tests down though
pip install Cython numpy python-dateutil pytz pytest>=6.0 pytest-xdist>=1.31.0 pytest-asyncio>=0.17 hypothesis>=5.5.3
@@ -178,7 +177,7 @@ jobs:
run: pushd /tmp && python -c "import pandas; pandas.show_versions();" && popd
- name: Publish test results
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v3
with:
name: Test results
path: test-data.xml
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index c287827206336..8ca4cce155e96 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -45,18 +45,18 @@ jobs:
cancel-in-progress: true
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python Dev Version
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: '3.11-dev'
# TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- name: Install dependencies
- shell: bash
+ shell: bash -el {0}
run: |
python -m pip install --upgrade pip "setuptools<60.0.0" wheel
pip install -i https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
@@ -74,12 +74,12 @@ jobs:
python -c "import pandas; pandas.show_versions();"
- name: Test with pytest
- shell: bash
+ shell: bash -el {0}
run: |
ci/run_tests.sh
- name: Publish test results
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v3
with:
name: Test results
path: test-data.xml
diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml
index dd030f1aacc44..8406743889f71 100644
--- a/.github/workflows/sdist.yml
+++ b/.github/workflows/sdist.yml
@@ -18,7 +18,7 @@ jobs:
timeout-minutes: 60
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
strategy:
fail-fast: false
@@ -30,12 +30,12 @@ jobs:
cancel-in-progress: true
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
@@ -52,7 +52,13 @@ jobs:
pip list
python setup.py sdist --formats=gztar
- - uses: conda-incubator/setup-miniconda@v2
+ - name: Upload sdist artifact
+ uses: actions/upload-artifact@v3
+ with:
+ name: ${{matrix.python-version}}-sdist.gz
+ path: dist/*.gz
+
+ - uses: conda-incubator/setup-miniconda@v2.1.1
with:
activate-environment: pandas-sdist
channels: conda-forge
diff --git a/Dockerfile b/Dockerfile
index 8887e80566772..2923cd60cc53b 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,4 +1,4 @@
-FROM quay.io/condaforge/miniforge3
+FROM quay.io/condaforge/miniforge3:4.11.0-0
# if you forked pandas, you can pass in your own GitHub username to use your fork
# i.e. gh_username=myname
@@ -45,4 +45,4 @@ RUN . /opt/conda/etc/profile.d/conda.sh \
&& cd "$pandas_home" \
&& export \
&& python setup.py build_ext -j 4 \
- && python -m pip install -e .
+ && python -m pip install --no-build-isolation -e .
| backports #45889, #46541, #46277 and #46540 | https://api.github.com/repos/pandas-dev/pandas/pulls/46572 | 2022-03-30T12:08:59Z | 2022-03-30T20:07:28Z | 2022-03-30T20:07:28Z | 2022-03-30T20:07:32Z |
POC For docker compose | diff --git a/ci/docker/pandas-db-test.dockerfile b/ci/docker/pandas-db-test.dockerfile
new file mode 100644
index 0000000000000..9270054ef6867
--- /dev/null
+++ b/ci/docker/pandas-db-test.dockerfile
@@ -0,0 +1,19 @@
+FROM python
+
+RUN apt-get update
+
+RUN python -m pip install --upgrade pip
+RUN python -m pip install \
+ cython \
+ hypothesis \
+ numpy \
+ pymysql \
+ psycopg2 \
+ pytest \
+ pytest-asyncio \
+ python-dateutil \
+ pytz \
+ sqlalchemy
+
+WORKDIR /pandas
+
diff --git a/ci/scripts/run-db-tests.sh b/ci/scripts/run-db-tests.sh
new file mode 100755
index 0000000000000..b6e5356b97316
--- /dev/null
+++ b/ci/scripts/run-db-tests.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+
+set -e
+
+python setup.py build_ext --inplace -j4
+python -m pytest pandas/tests/io/test_sql.py
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000000000..257bda50101df
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,21 @@
+services:
+ testing:
+ build:
+ context: .
+ dockerfile: ci/docker/pandas-db-test.dockerfile
+ volumes:
+ - .:/pandas
+ command: /pandas/ci/scripts/run-db-tests.sh
+
+ postgres-db:
+ image: postgres
+ environment:
+ POSTGRES_USER: postgres
+ POSTGRES_PASSWORD: postgres
+ POSTGRES_DB: pandas
+
+ mysql-db:
+ image: mysql
+ environment:
+ MYSQL_ALLOW_EMPTY_PASSWORD: yes
+ MYSQL_DATABASE: pandas
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index e4318f1d79102..e57293d445a7b 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -381,7 +381,7 @@ def mysql_pymysql_engine(iris_path, types_data):
sqlalchemy = pytest.importorskip("sqlalchemy")
pymysql = pytest.importorskip("pymysql")
engine = sqlalchemy.create_engine(
- "mysql+pymysql://root@localhost:3306/pandas",
+ "mysql+pymysql://root@mysql-db:3306/pandas",
connect_args={"client_flag": pymysql.constants.CLIENT.MULTI_STATEMENTS},
)
insp = sqlalchemy.inspect(engine)
@@ -409,7 +409,7 @@ def postgresql_psycopg2_engine(iris_path, types_data):
sqlalchemy = pytest.importorskip("sqlalchemy")
pytest.importorskip("psycopg2")
engine = sqlalchemy.create_engine(
- "postgresql+psycopg2://postgres:postgres@localhost:5432/pandas"
+ "postgresql+psycopg2://postgres:postgres@postgres-db:5432/pandas"
)
insp = sqlalchemy.inspect(engine)
if not insp.has_table("iris"):
@@ -1528,7 +1528,7 @@ def test_sql_open_close(self, test_frame3):
@pytest.mark.skipif(SQLALCHEMY_INSTALLED, reason="SQLAlchemy is installed")
def test_con_string_import_error(self):
- conn = "mysql://root@localhost/pandas"
+ conn = "mysql://root@mysql-db/pandas"
msg = "Using URI string without sqlalchemy installed"
with pytest.raises(ImportError, match=msg):
sql.read_sql("SELECT * FROM iris", conn)
@@ -2382,7 +2382,7 @@ class _TestMySQLAlchemy:
@classmethod
def connect(cls):
return sqlalchemy.create_engine(
- f"mysql+{cls.driver}://root@localhost:{cls.port}/pandas",
+ f"mysql+{cls.driver}://root@mysql-db:{cls.port}/pandas",
connect_args=cls.connect_args,
)
@@ -2408,7 +2408,7 @@ class _TestPostgreSQLAlchemy:
@classmethod
def connect(cls):
return sqlalchemy.create_engine(
- f"postgresql+{cls.driver}://postgres:postgres@localhost:{cls.port}/pandas"
+ f"postgresql+{cls.driver}://postgres:postgres@postgres-db:{cls.port}/pandas"
)
@classmethod
| - [X] closes #46532
POC using docker compose, which is also used by the arrow project.
The idea here is that we can simply run `docker compose build db-testing` to build an image with postgres (can later add mysql) and our minimal development requirements then `docker compose run --rm db-testing` to run relevant tests. This can be done both by a developer as well as on GH actions.
This still needs a bit more work as it currently muddles user permissions on the host when building pandas
cc @jonashaag who looks to have been doing some awesome work on CI lately | https://api.github.com/repos/pandas-dev/pandas/pulls/46570 | 2022-03-30T05:31:11Z | 2022-04-04T23:40:22Z | null | 2023-04-12T20:16:02Z |
CLN/TYP: assorted | diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx
index 4e3cdc0fdd14a..44234013c7a3c 100644
--- a/pandas/_libs/algos.pyx
+++ b/pandas/_libs/algos.pyx
@@ -750,7 +750,7 @@ def is_monotonic(ndarray[numeric_object_t, ndim=1] arr, bint timelike):
n = len(arr)
if n == 1:
- if arr[0] != arr[0] or (timelike and <int64_t>arr[0] == NPY_NAT):
+ if arr[0] != arr[0] or (numeric_object_t is int64_t and timelike and arr[0] == NPY_NAT):
# single value is NaN
return False, False, True
else:
diff --git a/pandas/_libs/indexing.pyx b/pandas/_libs/indexing.pyx
index 181de174c53fb..c274b28b7559a 100644
--- a/pandas/_libs/indexing.pyx
+++ b/pandas/_libs/indexing.pyx
@@ -2,21 +2,24 @@ cdef class NDFrameIndexerBase:
"""
A base class for _NDFrameIndexer for fast instantiation and attribute access.
"""
+ cdef:
+ Py_ssize_t _ndim
+
cdef public:
str name
- object obj, _ndim
+ object obj
def __init__(self, name: str, obj):
self.obj = obj
self.name = name
- self._ndim = None
+ self._ndim = -1
@property
def ndim(self) -> int:
# Delay `ndim` instantiation until required as reading it
# from `obj` isn't entirely cheap.
ndim = self._ndim
- if ndim is None:
+ if ndim == -1:
ndim = self._ndim = self.obj.ndim
if ndim > 2:
raise ValueError( # pragma: no cover
diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx
index ac423ef6c0ca2..d2dc60d27706d 100644
--- a/pandas/_libs/internals.pyx
+++ b/pandas/_libs/internals.pyx
@@ -544,7 +544,7 @@ cpdef update_blklocs_and_blknos(
"""
cdef:
Py_ssize_t i
- cnp.npy_intp length = len(blklocs) + 1
+ cnp.npy_intp length = blklocs.shape[0] + 1
ndarray[intp_t, ndim=1] new_blklocs, new_blknos
# equiv: new_blklocs = np.empty(length, dtype=np.intp)
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 9dfc438319148..5c0b69d51367a 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -218,7 +218,7 @@ def array_with_unit_to_datetime(
"""
cdef:
Py_ssize_t i, j, n=len(values)
- int64_t m
+ int64_t mult
int prec = 0
ndarray[float64_t] fvalues
bint is_ignore = errors=='ignore'
@@ -242,7 +242,7 @@ def array_with_unit_to_datetime(
)
return result, tz
- m, _ = precision_from_unit(unit)
+ mult, _ = precision_from_unit(unit)
if is_raise:
# try a quick conversion to i8/f8
@@ -254,7 +254,7 @@ def array_with_unit_to_datetime(
# fill missing values by comparing to NPY_NAT
mask = iresult == NPY_NAT
iresult[mask] = 0
- fvalues = iresult.astype("f8") * m
+ fvalues = iresult.astype("f8") * mult
need_to_iterate = False
if not need_to_iterate:
@@ -265,10 +265,10 @@ def array_with_unit_to_datetime(
raise OutOfBoundsDatetime(f"cannot convert input with unit '{unit}'")
if values.dtype.kind in ["i", "u"]:
- result = (iresult * m).astype("M8[ns]")
+ result = (iresult * mult).astype("M8[ns]")
elif values.dtype.kind == "f":
- fresult = (values * m).astype("f8")
+ fresult = (values * mult).astype("f8")
fresult[mask] = 0
if prec:
fresult = round(fresult, prec)
diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd
index 206e0171e0a55..ba03de6f0b81f 100644
--- a/pandas/_libs/tslibs/conversion.pxd
+++ b/pandas/_libs/tslibs/conversion.pxd
@@ -19,9 +19,9 @@ cdef class _TSObject:
bint fold
-cdef convert_to_tsobject(object ts, tzinfo tz, str unit,
- bint dayfirst, bint yearfirst,
- int32_t nanos=*)
+cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit,
+ bint dayfirst, bint yearfirst,
+ int32_t nanos=*)
cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz,
int32_t nanos=*)
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index 457b27b293f11..cf85a5111e1a9 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -345,8 +345,8 @@ cdef class _TSObject:
self.fold = 0
-cdef convert_to_tsobject(object ts, tzinfo tz, str unit,
- bint dayfirst, bint yearfirst, int32_t nanos=0):
+cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit,
+ bint dayfirst, bint yearfirst, int32_t nanos=0):
"""
Extract datetime and int64 from any of:
- np.int64 (with unit providing a possible modifier)
diff --git a/pandas/_libs/tslibs/dtypes.pxd b/pandas/_libs/tslibs/dtypes.pxd
index f61409fc16653..8cc7bcb2a1aad 100644
--- a/pandas/_libs/tslibs/dtypes.pxd
+++ b/pandas/_libs/tslibs/dtypes.pxd
@@ -5,7 +5,7 @@ from pandas._libs.tslibs.np_datetime cimport NPY_DATETIMEUNIT
cdef str npy_unit_to_abbrev(NPY_DATETIMEUNIT unit)
cdef NPY_DATETIMEUNIT freq_group_code_to_npy_unit(int freq) nogil
-cdef int64_t periods_per_day(NPY_DATETIMEUNIT reso=*)
+cdef int64_t periods_per_day(NPY_DATETIMEUNIT reso=*) except? -1
cdef dict attrname_to_abbrevs
diff --git a/pandas/_libs/tslibs/dtypes.pyx b/pandas/_libs/tslibs/dtypes.pyx
index 48a06b2c01ae4..8f87bfe0b8c7c 100644
--- a/pandas/_libs/tslibs/dtypes.pyx
+++ b/pandas/_libs/tslibs/dtypes.pyx
@@ -307,7 +307,7 @@ cdef NPY_DATETIMEUNIT freq_group_code_to_npy_unit(int freq) nogil:
return NPY_DATETIMEUNIT.NPY_FR_D
-cdef int64_t periods_per_day(NPY_DATETIMEUNIT reso=NPY_DATETIMEUNIT.NPY_FR_ns):
+cdef int64_t periods_per_day(NPY_DATETIMEUNIT reso=NPY_DATETIMEUNIT.NPY_FR_ns) except? -1:
"""
How many of the given time units fit into a single day?
"""
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index 5a7f931292e7b..ce7246f7ab19e 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -1910,7 +1910,7 @@ cdef class WeekOfMonthMixin(SingleConstructorOffset):
shifted = shift_month(other, months, "start")
to_day = self._get_offset_day(shifted)
- return shift_day(shifted, to_day - shifted.day)
+ return _shift_day(shifted, to_day - shifted.day)
def is_on_offset(self, dt: datetime) -> bool:
if self.normalize and not _is_normalized(dt):
@@ -3132,7 +3132,7 @@ cdef class FY5253Quarter(FY5253Mixin):
qtr_lens = self.get_weeks(norm)
# check that qtr_lens is consistent with self._offset addition
- end = shift_day(start, days=7 * sum(qtr_lens))
+ end = _shift_day(start, days=7 * sum(qtr_lens))
assert self._offset.is_on_offset(end), (start, end, qtr_lens)
tdelta = norm - start
@@ -3173,7 +3173,7 @@ cdef class FY5253Quarter(FY5253Mixin):
# Note: we always have 0 <= n < 4
weeks = sum(qtr_lens[:n])
if weeks:
- res = shift_day(res, days=weeks * 7)
+ res = _shift_day(res, days=weeks * 7)
return res
@@ -3210,7 +3210,7 @@ cdef class FY5253Quarter(FY5253Mixin):
current = next_year_end
for qtr_len in qtr_lens:
- current = shift_day(current, days=qtr_len * 7)
+ current = _shift_day(current, days=qtr_len * 7)
if dt == current:
return True
return False
@@ -3729,7 +3729,7 @@ cpdef to_offset(freq):
# ----------------------------------------------------------------------
# RelativeDelta Arithmetic
-def shift_day(other: datetime, days: int) -> datetime:
+cdef datetime _shift_day(datetime other, int days):
"""
Increment the datetime `other` by the given number of days, retaining
the time-portion of the datetime. For tz-naive datetimes this is
@@ -3915,6 +3915,8 @@ cdef inline void _shift_quarters(const int64_t[:] dtindex,
out[i] = dtstruct_to_dt64(&dts)
+@cython.wraparound(False)
+@cython.boundscheck(False)
cdef ndarray[int64_t] _shift_bdays(const int64_t[:] i8other, int periods):
"""
Implementation of BusinessDay.apply_offset.
diff --git a/pandas/_libs/tslibs/timedeltas.pxd b/pandas/_libs/tslibs/timedeltas.pxd
index f054a22ed7ad7..f114fd9297920 100644
--- a/pandas/_libs/tslibs/timedeltas.pxd
+++ b/pandas/_libs/tslibs/timedeltas.pxd
@@ -15,4 +15,5 @@ cdef class _Timedelta(timedelta):
int64_t _d, _h, _m, _s, _ms, _us, _ns
cpdef timedelta to_pytimedelta(_Timedelta self)
- cpdef bint _has_ns(self)
+ cdef bint _has_ns(self)
+ cdef _ensure_components(_Timedelta self)
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index b443ae283755c..7979feb076c6e 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -154,7 +154,7 @@ def ints_to_pytimedelta(const int64_t[:] arr, box=False):
cdef:
Py_ssize_t i, n = len(arr)
int64_t value
- object[:] result = np.empty(n, dtype=object)
+ object[::1] result = np.empty(n, dtype=object)
for i in range(n):
@@ -892,10 +892,10 @@ cdef class _Timedelta(timedelta):
return cmp_scalar(self.value, ots.value, op)
- cpdef bint _has_ns(self):
+ cdef bint _has_ns(self):
return self.value % 1000 != 0
- def _ensure_components(_Timedelta self):
+ cdef _ensure_components(_Timedelta self):
"""
compute the components
"""
@@ -1160,7 +1160,10 @@ cdef class _Timedelta(timedelta):
converted : string of a Timedelta
"""
- cdef object sign, seconds_pretty, subs, fmt, comp_dict
+ cdef:
+ str sign, fmt
+ dict comp_dict
+ object subs
self._ensure_components()
diff --git a/pandas/_libs/tslibs/timestamps.pxd b/pandas/_libs/tslibs/timestamps.pxd
index 9b05fbc5be915..ce4c5d07ecc53 100644
--- a/pandas/_libs/tslibs/timestamps.pxd
+++ b/pandas/_libs/tslibs/timestamps.pxd
@@ -6,17 +6,18 @@ from numpy cimport int64_t
from pandas._libs.tslibs.base cimport ABCTimestamp
from pandas._libs.tslibs.np_datetime cimport npy_datetimestruct
+from pandas._libs.tslibs.offsets cimport BaseOffset
-cdef object create_timestamp_from_ts(int64_t value,
- npy_datetimestruct dts,
- tzinfo tz, object freq, bint fold)
+cdef _Timestamp create_timestamp_from_ts(int64_t value,
+ npy_datetimestruct dts,
+ tzinfo tz, BaseOffset freq, bint fold)
cdef class _Timestamp(ABCTimestamp):
cdef readonly:
int64_t value, nanosecond
- object _freq
+ BaseOffset _freq
cdef bint _get_start_end_field(self, str field, freq)
cdef _get_date_name_field(self, str field, object locale)
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx
index 5ba28a9fae429..698e19f97c6aa 100644
--- a/pandas/_libs/tslibs/timestamps.pyx
+++ b/pandas/_libs/tslibs/timestamps.pyx
@@ -82,6 +82,7 @@ from pandas._libs.tslibs.np_datetime cimport (
from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
from pandas._libs.tslibs.offsets cimport (
+ BaseOffset,
is_offset_object,
to_offset,
)
@@ -113,9 +114,9 @@ _no_input = object()
# ----------------------------------------------------------------------
-cdef inline object create_timestamp_from_ts(int64_t value,
- npy_datetimestruct dts,
- tzinfo tz, object freq, bint fold):
+cdef inline _Timestamp create_timestamp_from_ts(int64_t value,
+ npy_datetimestruct dts,
+ tzinfo tz, BaseOffset freq, bint fold):
""" convenience routine to construct a Timestamp from its parts """
cdef _Timestamp ts_base
ts_base = _Timestamp.__new__(Timestamp, dts.year, dts.month,
diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx
index 224c5be1f3b7d..6e3f7a370e5dd 100644
--- a/pandas/_libs/tslibs/timezones.pyx
+++ b/pandas/_libs/tslibs/timezones.pyx
@@ -230,10 +230,10 @@ cdef object _get_utc_trans_times_from_dateutil_tz(tzinfo tz):
return new_trans
-cdef int64_t[:] unbox_utcoffsets(object transinfo):
+cdef int64_t[::1] unbox_utcoffsets(object transinfo):
cdef:
Py_ssize_t i, sz
- int64_t[:] arr
+ int64_t[::1] arr
sz = len(transinfo)
arr = np.empty(sz, dtype='i8')
diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx
index afcfe94a695bb..cee2de0cf0f4a 100644
--- a/pandas/_libs/tslibs/tzconversion.pyx
+++ b/pandas/_libs/tslibs/tzconversion.pyx
@@ -610,7 +610,7 @@ cdef int64_t _tz_localize_using_tzinfo_api(
int64_t val, tzinfo tz, bint to_utc=True, bint* fold=NULL
) except? -1:
"""
- Convert the i8 representation of a datetime from a general-cast timezone to
+ Convert the i8 representation of a datetime from a general-case timezone to
UTC, or vice-versa using the datetime/tzinfo API.
Private, not intended for use outside of tslibs.tzconversion.
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 9ffe33e0cf38e..e40acad0cb51a 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -2006,10 +2006,10 @@ def sequence_to_datetimes(data, require_iso8601: bool = False) -> DatetimeArray:
def _sequence_to_dt64ns(
data,
dtype=None,
- copy=False,
+ copy: bool = False,
tz=None,
- dayfirst=False,
- yearfirst=False,
+ dayfirst: bool = False,
+ yearfirst: bool = False,
ambiguous="raise",
*,
allow_mixed: bool = False,
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/46568 | 2022-03-30T02:41:10Z | 2022-04-03T03:12:53Z | 2022-04-03T03:12:53Z | 2022-04-03T15:10:23Z |
BUG: groupby().rolling(freq) with monotonic dates within groups #46065 | diff --git a/doc/source/whatsnew/v1.4.2.rst b/doc/source/whatsnew/v1.4.2.rst
index 13f3e9a0d0a8c..a8763819d0531 100644
--- a/doc/source/whatsnew/v1.4.2.rst
+++ b/doc/source/whatsnew/v1.4.2.rst
@@ -32,6 +32,7 @@ Bug fixes
- Fix some cases for subclasses that define their ``_constructor`` properties as general callables (:issue:`46018`)
- Fixed "longtable" formatting in :meth:`.Styler.to_latex` when ``column_format`` is given in extended format (:issue:`46037`)
- Fixed incorrect rendering in :meth:`.Styler.format` with ``hyperlinks="html"`` when the url contains a colon or other special characters (:issue:`46389`)
+- Fixed :meth:`Groupby.rolling` with a frequency window that would raise a ``ValueError`` even if the datetimes within each group were monotonic (:issue:`46061`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index d4569816f9f7a..ac3d8b3dabb2b 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -2680,3 +2680,21 @@ def _get_window_indexer(self) -> GroupbyIndexer:
indexer_kwargs=indexer_kwargs,
)
return window_indexer
+
+ def _validate_datetimelike_monotonic(self):
+ """
+ Validate that each group in self._on is monotonic
+ """
+ # GH 46061
+ if self._on.hasnans:
+ self._raise_monotonic_error("values must not have NaT")
+ for group_indices in self._grouper.indices.values():
+ group_on = self._on.take(group_indices)
+ if not (
+ group_on.is_monotonic_increasing or group_on.is_monotonic_decreasing
+ ):
+ on = "index" if self.on is None else self.on
+ raise ValueError(
+ f"Each group within {on} must be monotonic. "
+ f"Sort the values in {on} first."
+ )
diff --git a/pandas/tests/window/test_groupby.py b/pandas/tests/window/test_groupby.py
index b4d0f6562f2d5..5f4805eaa01d2 100644
--- a/pandas/tests/window/test_groupby.py
+++ b/pandas/tests/window/test_groupby.py
@@ -927,6 +927,83 @@ def test_nan_and_zero_endpoints(self):
)
tm.assert_series_equal(result, expected)
+ def test_groupby_rolling_non_monotonic(self):
+ # GH 43909
+
+ shuffled = [3, 0, 1, 2]
+ sec = 1_000
+ df = DataFrame(
+ [{"t": Timestamp(2 * x * sec), "x": x + 1, "c": 42} for x in shuffled]
+ )
+ with pytest.raises(ValueError, match=r".* must be monotonic"):
+ df.groupby("c").rolling(on="t", window="3s")
+
+ def test_groupby_monotonic(self):
+
+ # GH 15130
+ # we don't need to validate monotonicity when grouping
+
+ # GH 43909 we should raise an error here to match
+ # behaviour of non-groupby rolling.
+
+ data = [
+ ["David", "1/1/2015", 100],
+ ["David", "1/5/2015", 500],
+ ["David", "5/30/2015", 50],
+ ["David", "7/25/2015", 50],
+ ["Ryan", "1/4/2014", 100],
+ ["Ryan", "1/19/2015", 500],
+ ["Ryan", "3/31/2016", 50],
+ ["Joe", "7/1/2015", 100],
+ ["Joe", "9/9/2015", 500],
+ ["Joe", "10/15/2015", 50],
+ ]
+
+ df = DataFrame(data=data, columns=["name", "date", "amount"])
+ df["date"] = to_datetime(df["date"])
+ df = df.sort_values("date")
+
+ expected = (
+ df.set_index("date")
+ .groupby("name")
+ .apply(lambda x: x.rolling("180D")["amount"].sum())
+ )
+ result = df.groupby("name").rolling("180D", on="date")["amount"].sum()
+ tm.assert_series_equal(result, expected)
+
+ def test_datelike_on_monotonic_within_each_group(self):
+ # GH 13966 (similar to #15130, closed by #15175)
+
+ # superseded by 43909
+ # GH 46061: OK if the on is monotonic relative to each each group
+
+ dates = date_range(start="2016-01-01 09:30:00", periods=20, freq="s")
+ df = DataFrame(
+ {
+ "A": [1] * 20 + [2] * 12 + [3] * 8,
+ "B": np.concatenate((dates, dates)),
+ "C": np.arange(40),
+ }
+ )
+
+ expected = (
+ df.set_index("B").groupby("A").apply(lambda x: x.rolling("4s")["C"].mean())
+ )
+ result = df.groupby("A").rolling("4s", on="B").C.mean()
+ tm.assert_series_equal(result, expected)
+
+ def test_datelike_on_not_monotonic_within_each_group(self):
+ # GH 46061
+ df = DataFrame(
+ {
+ "A": [1] * 3 + [2] * 3,
+ "B": [Timestamp(year, 1, 1) for year in [2020, 2021, 2019]] * 2,
+ "C": range(6),
+ }
+ )
+ with pytest.raises(ValueError, match="Each group within B must be monotonic."):
+ df.groupby("A").rolling("365D", on="B")
+
class TestExpanding:
def setup_method(self):
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index 7e9bc121f06ff..89c90836ae957 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -1456,18 +1456,6 @@ def test_groupby_rolling_nan_included():
tm.assert_frame_equal(result, expected)
-def test_groupby_rolling_non_monotonic():
- # GH 43909
-
- shuffled = [3, 0, 1, 2]
- sec = 1_000
- df = DataFrame(
- [{"t": Timestamp(2 * x * sec), "x": x + 1, "c": 42} for x in shuffled]
- )
- with pytest.raises(ValueError, match=r".* must be monotonic"):
- df.groupby("c").rolling(on="t", window="3s")
-
-
@pytest.mark.parametrize("method", ["skew", "kurt"])
def test_rolling_skew_kurt_numerical_stability(method):
# GH#6929
diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py
index ee28b27b17365..907c654570273 100644
--- a/pandas/tests/window/test_timeseries_window.py
+++ b/pandas/tests/window/test_timeseries_window.py
@@ -9,7 +9,6 @@
Series,
Timestamp,
date_range,
- to_datetime,
)
import pandas._testing as tm
@@ -649,65 +648,6 @@ def agg_by_day(x):
tm.assert_frame_equal(result, expected)
- def test_groupby_monotonic(self):
-
- # GH 15130
- # we don't need to validate monotonicity when grouping
-
- # GH 43909 we should raise an error here to match
- # behaviour of non-groupby rolling.
-
- data = [
- ["David", "1/1/2015", 100],
- ["David", "1/5/2015", 500],
- ["David", "5/30/2015", 50],
- ["David", "7/25/2015", 50],
- ["Ryan", "1/4/2014", 100],
- ["Ryan", "1/19/2015", 500],
- ["Ryan", "3/31/2016", 50],
- ["Joe", "7/1/2015", 100],
- ["Joe", "9/9/2015", 500],
- ["Joe", "10/15/2015", 50],
- ]
-
- df = DataFrame(data=data, columns=["name", "date", "amount"])
- df["date"] = to_datetime(df["date"])
- df = df.sort_values("date")
-
- expected = (
- df.set_index("date")
- .groupby("name")
- .apply(lambda x: x.rolling("180D")["amount"].sum())
- )
- result = df.groupby("name").rolling("180D", on="date")["amount"].sum()
- tm.assert_series_equal(result, expected)
-
- def test_non_monotonic_raises(self):
- # GH 13966 (similar to #15130, closed by #15175)
-
- # superseded by 43909
-
- dates = date_range(start="2016-01-01 09:30:00", periods=20, freq="s")
- df = DataFrame(
- {
- "A": [1] * 20 + [2] * 12 + [3] * 8,
- "B": np.concatenate((dates, dates)),
- "C": np.arange(40),
- }
- )
-
- expected = (
- df.set_index("B").groupby("A").apply(lambda x: x.rolling("4s")["C"].mean())
- )
- with pytest.raises(ValueError, match=r".* must be monotonic"):
- df.groupby("A").rolling(
- "4s", on="B"
- ).C.mean() # should raise for non-monotonic t series
-
- df2 = df.sort_values("B")
- result = df2.groupby("A").rolling("4s", on="B").C.mean()
- tm.assert_series_equal(result, expected)
-
def test_rolling_cov_offset(self):
# GH16058
| - [x] closes #46061 (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 an entry in the latest `doc/source/whatsnew/v1.4.2.rst` file if fixing a bug or adding a new feature.
Restored version in https://github.com/pandas-dev/pandas/pull/46065 as there is some support for the bug fix despite the performance hit. | https://api.github.com/repos/pandas-dev/pandas/pulls/46567 | 2022-03-30T02:15:00Z | 2022-03-31T18:01:23Z | 2022-03-31T18:01:23Z | 2022-04-02T07:56:36Z |
TYP: setter for index/columns property-like (AxisProperty) | diff --git a/pandas/_libs/properties.pyi b/pandas/_libs/properties.pyi
index b2ba55aefb8a5..595e3bd706f1d 100644
--- a/pandas/_libs/properties.pyi
+++ b/pandas/_libs/properties.pyi
@@ -1,9 +1,28 @@
-# pyright: reportIncompleteStub = false
-from typing import Any
+from typing import (
+ Sequence,
+ overload,
+)
+
+from pandas._typing import (
+ AnyArrayLike,
+ DataFrame,
+ Index,
+ Series,
+)
# note: this is a lie to make type checkers happy (they special
# case property). cache_readonly uses attribute names similar to
# property (fget) but it does not provide fset and fdel.
cache_readonly = property
-def __getattr__(name: str) -> Any: ... # incomplete
+class AxisProperty:
+
+ axis: int
+ def __init__(self, axis: int = ..., doc: str = ...) -> None: ...
+ @overload
+ def __get__(self, obj: DataFrame | Series, type) -> Index: ...
+ @overload
+ def __get__(self, obj: None, type) -> AxisProperty: ...
+ def __set__(
+ self, obj: DataFrame | Series, value: AnyArrayLike | Sequence
+ ) -> None: ...
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index d37080fce6e1c..c0200c7d7c5b7 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -235,8 +235,12 @@ def transform(self) -> DataFrame | Series:
and not obj.empty
):
raise ValueError("Transform function failed")
+ # error: Argument 1 to "__get__" of "AxisProperty" has incompatible type
+ # "Union[Series, DataFrame, GroupBy[Any], SeriesGroupBy,
+ # DataFrameGroupBy, BaseWindow, Resampler]"; expected "Union[DataFrame,
+ # Series]"
if not isinstance(result, (ABCSeries, ABCDataFrame)) or not result.index.equals(
- obj.index
+ obj.index # type:ignore[arg-type]
):
raise ValueError("Function did not transform")
@@ -645,7 +649,11 @@ class NDFrameApply(Apply):
@property
def index(self) -> Index:
- return self.obj.index
+ # error: Argument 1 to "__get__" of "AxisProperty" has incompatible type
+ # "Union[Series, DataFrame, GroupBy[Any], SeriesGroupBy,
+ # DataFrameGroupBy, BaseWindow, Resampler]"; expected "Union[DataFrame,
+ # Series]"
+ return self.obj.index # type:ignore[arg-type]
@property
def agg_axis(self) -> Index:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 44d79fe2f1519..4376c784bc847 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -11199,12 +11199,10 @@ def isin(self, values) -> DataFrame:
_info_axis_number = 1
_info_axis_name = "columns"
- index: Index = properties.AxisProperty(
+ index = properties.AxisProperty(
axis=1, doc="The index (row labels) of the DataFrame."
)
- columns: Index = properties.AxisProperty(
- axis=0, doc="The column labels of the DataFrame."
- )
+ columns = properties.AxisProperty(axis=0, doc="The column labels of the DataFrame.")
@property
def _AXIS_NUMBERS(self) -> dict[str, int]:
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 89a590f291356..673228a758aca 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -37,6 +37,7 @@
to_offset,
)
from pandas._typing import (
+ AnyArrayLike,
ArrayLike,
Axis,
CompressionOptions,
@@ -757,7 +758,7 @@ def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool_t):
obj.set_axis(labels, axis=axis, inplace=True)
return obj
- def _set_axis(self, axis: int, labels: Index) -> None:
+ def _set_axis(self, axis: int, labels: AnyArrayLike | Sequence) -> None:
labels = ensure_index(labels)
self._mgr.set_axis(axis, labels)
self._clear_item_cache()
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 5d215ec81a6cd..a469372d85967 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -275,9 +275,9 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
func = maybe_mangle_lambdas(func)
ret = self._aggregate_multiple_funcs(func)
if relabeling:
- # error: Incompatible types in assignment (expression has type
- # "Optional[List[str]]", variable has type "Index")
- ret.columns = columns # type: ignore[assignment]
+ # columns is not narrowed by mypy from relabeling flag
+ assert columns is not None # for mypy
+ ret.columns = columns
return ret
else:
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 6ef024f13fbb1..d8ee7365120f7 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -33,6 +33,7 @@
from pandas._libs.lib import no_default
from pandas._typing import (
AggFuncType,
+ AnyArrayLike,
ArrayLike,
Axis,
Dtype,
@@ -553,7 +554,7 @@ def _constructor_expanddim(self) -> Callable[..., DataFrame]:
def _can_hold_na(self) -> bool:
return self._mgr._can_hold_na
- def _set_axis(self, axis: int, labels) -> None:
+ def _set_axis(self, axis: int, labels: AnyArrayLike | Sequence) -> None:
"""
Override generic, we want to set the _typ here.
@@ -5813,7 +5814,7 @@ def mask(
_info_axis_number = 0
_info_axis_name = "index"
- index: Index = properties.AxisProperty(
+ index = properties.AxisProperty(
axis=0, doc="The index (axis labels) of the Series."
)
diff --git a/pandas/io/parsers/arrow_parser_wrapper.py b/pandas/io/parsers/arrow_parser_wrapper.py
index 97a57054f3aa9..21e8bb5f9e89f 100644
--- a/pandas/io/parsers/arrow_parser_wrapper.py
+++ b/pandas/io/parsers/arrow_parser_wrapper.py
@@ -105,12 +105,7 @@ def _finalize_output(self, frame: DataFrame) -> DataFrame:
multi_index_named = False
frame.columns = self.names
# we only need the frame not the names
- # error: Incompatible types in assignment (expression has type
- # "Union[List[Union[Union[str, int, float, bool], Union[Period, Timestamp,
- # Timedelta, Any]]], Index]", variable has type "Index") [assignment]
- frame.columns, frame = self._do_date_conversions( # type: ignore[assignment]
- frame.columns, frame
- )
+ frame.columns, frame = self._do_date_conversions(frame.columns, frame)
if self.index_col is not None:
for i, item in enumerate(self.index_col):
if is_integer(item):
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/46565 | 2022-03-29T19:50:17Z | 2022-06-10T22:53:30Z | 2022-06-10T22:53:30Z | 2022-06-11T09:36:35Z |
Don't run GHA CI for Azure changes and vice-versa | diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index 16ac3cbf47705..c7712bebc3b8f 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -9,6 +9,9 @@ on:
branches:
- main
- 1.4.x
+ paths-ignore:
+ - 'azure-pipelines.yml'
+ - 'ci/azure/**'
env:
ENV_FILE: environment.yml
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml
index bba9f62a0eca6..c84a067a2f94d 100644
--- a/.github/workflows/docbuild-and-upload.yml
+++ b/.github/workflows/docbuild-and-upload.yml
@@ -9,6 +9,9 @@ on:
branches:
- main
- 1.4.x
+ paths-ignore:
+ - 'azure-pipelines.yml'
+ - 'ci/azure/**'
env:
ENV_FILE: environment.yml
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index ec7da7d68ba9f..76562e10096c1 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -11,6 +11,8 @@ on:
- 1.4.x
paths-ignore:
- "doc/**"
+ - 'azure-pipelines.yml'
+ - 'ci/azure/**'
env:
PANDAS_CI: 1
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index 8ca4cce155e96..748d95ab6f36f 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -19,6 +19,8 @@ on:
- 1.4.x
paths-ignore:
- "doc/**"
+ - 'azure-pipelines.yml'
+ - 'ci/azure/**'
env:
PYTEST_WORKERS: "auto"
diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml
index cd19eb7641c8c..1528a5a576476 100644
--- a/.github/workflows/sdist.yml
+++ b/.github/workflows/sdist.yml
@@ -12,6 +12,8 @@ on:
types: [labeled, opened, synchronize, reopened]
paths-ignore:
- "doc/**"
+ - 'azure-pipelines.yml'
+ - 'ci/azure/**'
jobs:
build:
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 9b83ed6116ed3..7f6210a62269d 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -7,6 +7,7 @@ trigger:
paths:
exclude:
- 'doc/**'
+ - '.github/**'
pr:
autoCancel: true
| - [ ] 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 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/46564 | 2022-03-29T17:30:41Z | 2022-04-05T07:07:40Z | null | 2022-04-05T07:07:41Z |
Backport PR #46558: CI: pre-commit autoupdate to fix CI | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 3ffcf29f47688..9b2b39e6b5a6c 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -9,7 +9,7 @@ repos:
- id: absolufy-imports
files: ^pandas/
- repo: https://github.com/python/black
- rev: 21.12b0
+ rev: 22.3.0
hooks:
- id: black
- repo: https://github.com/codespell-project/codespell
@@ -26,7 +26,7 @@ repos:
exclude: \.txt$
- id: trailing-whitespace
- repo: https://github.com/cpplint/cpplint
- rev: 1.5.5
+ rev: 1.6.0
hooks:
- id: cpplint
# We don't lint all C files because we don't want to lint any that are built
@@ -49,7 +49,7 @@ repos:
hooks:
- id: isort
- repo: https://github.com/asottile/pyupgrade
- rev: v2.31.0
+ rev: v2.31.1
hooks:
- id: pyupgrade
args: [--py38-plus]
diff --git a/environment.yml b/environment.yml
index da5d6fabcde20..2ed56ad8126e0 100644
--- a/environment.yml
+++ b/environment.yml
@@ -18,7 +18,7 @@ dependencies:
- cython>=0.29.24
# code checks
- - black=21.5b2
+ - black=22.3.0
- cpplint
- flake8=4.0.1
- flake8-bugbear=21.3.2 # used by flake8, find likely bugs
diff --git a/requirements-dev.txt b/requirements-dev.txt
index ac525f1d09fbe..beda85b09cf83 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -6,7 +6,7 @@ python-dateutil>=2.8.1
pytz
asv < 0.5.0
cython>=0.29.24
-black==21.5b2
+black==22.3.0
cpplint
flake8==4.0.1
flake8-bugbear==21.3.2
| Backport PR #46558 | https://api.github.com/repos/pandas-dev/pandas/pulls/46563 | 2022-03-29T13:52:06Z | 2022-03-30T18:54:02Z | null | 2022-03-30T18:54:03Z |
tocsv_interval _categories | diff --git a/pandas/core/array_algos/take.py b/pandas/core/array_algos/take.py
index 188725f003f1e..6acfd4e155b51 100644
--- a/pandas/core/array_algos/take.py
+++ b/pandas/core/array_algos/take.py
@@ -22,6 +22,7 @@
from pandas.core.dtypes.common import (
ensure_platform_int,
is_1d_only_ea_obj,
+ is_interval_dtype,
)
from pandas.core.dtypes.missing import na_value_for_dtype
@@ -110,6 +111,9 @@ def take_nd(
return arr.take(
indexer, fill_value=fill_value, allow_fill=allow_fill, axis=axis
)
+ if arr.dtype.kind in "O" and is_interval_dtype(arr):
+ # # GH46297 Interval
+ return arr.take(indexer, allow_fill=allow_fill)
return arr.take(indexer, fill_value=fill_value, allow_fill=allow_fill)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 26569b571724d..778dcf336f39f 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -2281,6 +2281,13 @@ def to_native_types(
results_converted.append(result.astype(object, copy=False))
return np.vstack(results_converted)
+ elif isinstance(values, (PeriodArray, IntervalArray)):
+ # GH46297
+ values = np.array(values, dtype="object")
+ mask = isna(values)
+ values[mask] = na_rep
+ return values
+
elif values.dtype.kind == "f" and not is_sparse(values):
# see GH#13418: no special formatting is desired at the
# output (important for appropriate 'quoting' behaviour),
diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py
index d3f8e27c47e98..a92fe2a2576f4 100644
--- a/pandas/tests/io/formats/test_to_csv.py
+++ b/pandas/tests/io/formats/test_to_csv.py
@@ -315,6 +315,17 @@ def test_to_csv_date_format_in_categorical(self):
ser = ser.astype("category")
assert ser.to_csv(index=False, date_format="%Y-%m-%d") == expected
+ def test_to_cvs_interval_format_in_categorical(self):
+ # GH#46297
+ df = DataFrame(index=[0], columns=["a"])
+ df.at[0, "a"] = pd.Interval(
+ pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")
+ )
+ df["a"] = df["a"].astype("category")
+ result = df.to_csv(index=False, date_format="%Y-%m-%d")
+ expected = tm.convert_rows_list_to_csv_str(["a", '"(2020-01-01, 2020-01-02]"'])
+ assert result == expected
+
def test_to_csv_float_ea_float_format(self):
# GH#45991
df = DataFrame({"a": [1.1, 2.02, pd.NA, 6.000006], "b": "c"})
| - [x] closes #46297
- [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 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/46562 | 2022-03-29T13:43:10Z | 2022-06-15T08:18:46Z | null | 2022-06-15T08:18:46Z |
Backport of CI related PRs on 1.4.x | diff --git a/.circleci/config.yml b/.circleci/config.yml
index dc357101e79fd..9d1a11026b35d 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -8,7 +8,7 @@ jobs:
environment:
ENV_FILE: ci/deps/circle-38-arm64.yaml
PYTEST_WORKERS: auto
- PATTERN: "not slow and not network and not clipboard and not arm_slow"
+ PATTERN: "not single_cpu and not slow and not network and not clipboard and not arm_slow and not db"
PYTEST_TARGET: "pandas"
steps:
- checkout
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index 303d58d96c2c7..0d5ef807a3392 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -162,8 +162,7 @@ jobs:
shell: bash
run: |
# TODO: re-enable cov, its slowing the tests down though
- # TODO: Unpin Cython, the new Cython 0.29.26 is causing compilation errors
- pip install Cython==0.29.25 numpy python-dateutil pytz pytest>=6.0 pytest-xdist>=1.31.0 hypothesis>=5.5.3
+ pip install Cython numpy python-dateutil pytz pytest>=6.0 pytest-xdist>=1.31.0 pytest-asyncio>=0.17 hypothesis>=5.5.3
if: ${{ env.IS_PYPY == 'true' }}
- name: Build Pandas
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index a37ea3eb89167..ec798bd607034 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -45,7 +45,7 @@ jobs:
/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<60.0.0' && \
- pip install cython numpy python-dateutil pytz pytest pytest-xdist hypothesis pytest-azurepipelines && \
+ pip install cython numpy python-dateutil pytz pytest pytest-xdist pytest-asyncio>=0.17 hypothesis && \
python setup.py build_ext -q -j2 && \
python -m pip install --no-build-isolation -e . && \
pytest -m 'not slow and not network and not clipboard' pandas --junitxml=test-data.xml"
diff --git a/ci/deps/actions-310-numpydev.yaml b/ci/deps/actions-310-numpydev.yaml
index 3e32665d5433f..401be14aaca02 100644
--- a/ci/deps/actions-310-numpydev.yaml
+++ b/ci/deps/actions-310-numpydev.yaml
@@ -9,6 +9,7 @@ dependencies:
- pytest-cov
- pytest-xdist>=1.31
- hypothesis>=5.5.3
+ - pytest-asyncio>=0.17
# pandas dependencies
- python-dateutil
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml
index bbc468f9d8f43..dac1219245e84 100644
--- a/ci/deps/actions-310.yaml
+++ b/ci/deps/actions-310.yaml
@@ -11,6 +11,8 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
+ - pytest-asyncio>=0.17
+ - boto3
# required dependencies
- python-dateutil
@@ -21,6 +23,7 @@ dependencies:
- beautifulsoup4
- blosc
- bottleneck
+ - brotlipy
- fastparquet
- fsspec
- html5lib
@@ -39,6 +42,7 @@ dependencies:
- pytables
- pyarrow
- pyreadstat
+ - python-snappy
- pyxlsb
- s3fs
- scipy
diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-38-downstream_compat.yaml
index f3fa95d03c98e..01415122e6076 100644
--- a/ci/deps/actions-38-downstream_compat.yaml
+++ b/ci/deps/actions-38-downstream_compat.yaml
@@ -12,6 +12,8 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
+ - pytest-asyncio>=0.17
+ - boto3
# required dependencies
- python-dateutil
@@ -21,6 +23,7 @@ dependencies:
# optional dependencies
- beautifulsoup4
- blosc
+ - brotlipy
- bottleneck
- fastparquet
- fsspec
@@ -35,10 +38,11 @@ dependencies:
- odfpy
- pandas-gbq
- psycopg2
- - pymysql
- - pytables
- pyarrow
+ - pymysql
- pyreadstat
+ - pytables
+ - python-snappy
- pyxlsb
- s3fs
- scipy
@@ -52,17 +56,14 @@ dependencies:
# downstream packages
- aiobotocore
- - boto3
- botocore
- cftime
- dask
- ipython
- geopandas
- - python-snappy
- seaborn
- scikit-learn
- statsmodels
- - brotlipy
- coverage
- pandas-datareader
- pyyaml
diff --git a/ci/deps/actions-38-minimum_versions.yaml b/ci/deps/actions-38-minimum_versions.yaml
index 2e782817f3f14..f3a967f67cbc3 100644
--- a/ci/deps/actions-38-minimum_versions.yaml
+++ b/ci/deps/actions-38-minimum_versions.yaml
@@ -13,6 +13,8 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
+ - pytest-asyncio>=0.17
+ - boto3
# required dependencies
- python-dateutil=2.8.1
@@ -23,6 +25,7 @@ dependencies:
- beautifulsoup4=4.8.2
- blosc=1.20.1
- bottleneck=1.3.1
+ - brotlipy=0.7.0
- fastparquet=0.4.0
- fsspec=0.7.4
- html5lib=1.1
@@ -37,10 +40,11 @@ dependencies:
- openpyxl=3.0.3
- pandas-gbq=0.14.0
- psycopg2=2.8.4
- - pymysql=0.10.1
- - pytables=3.6.1
- pyarrow=1.0.1
+ - pymysql=0.10.1
- pyreadstat=1.1.0
+ - pytables=3.6.1
+ - python-snappy=0.6.0
- pyxlsb=1.0.6
- s3fs=0.4.0
- scipy=1.4.1
diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml
index 60db02def8a3d..79cd831051c2f 100644
--- a/ci/deps/actions-38.yaml
+++ b/ci/deps/actions-38.yaml
@@ -11,6 +11,8 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
+ - pytest-asyncio>=0.17
+ - boto3
# required dependencies
- python-dateutil
@@ -21,6 +23,7 @@ dependencies:
- beautifulsoup4
- blosc
- bottleneck
+ - brotlipy
- fastparquet
- fsspec
- html5lib
@@ -34,10 +37,11 @@ dependencies:
- odfpy
- pandas-gbq
- psycopg2
- - pymysql
- - pytables
- pyarrow
+ - pymysql
- pyreadstat
+ - pytables
+ - python-snappy
- pyxlsb
- s3fs
- scipy
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml
index 2d6430afd0b36..1c681104f3196 100644
--- a/ci/deps/actions-39.yaml
+++ b/ci/deps/actions-39.yaml
@@ -11,6 +11,8 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
+ - pytest-asyncio>=0.17
+ - boto3
# required dependencies
- python-dateutil
@@ -21,6 +23,7 @@ dependencies:
- beautifulsoup4
- blosc
- bottleneck
+ - brotlipy
- fastparquet
- fsspec
- html5lib
@@ -35,9 +38,10 @@ dependencies:
- pandas-gbq
- psycopg2
- pymysql
- - pytables
- pyarrow
- pyreadstat
+ - pytables
+ - python-snappy
- pyxlsb
- s3fs
- scipy
diff --git a/ci/deps/circle-38-arm64.yaml b/ci/deps/circle-38-arm64.yaml
index 60608c3ee1a86..66fedccc5eca7 100644
--- a/ci/deps/circle-38-arm64.yaml
+++ b/ci/deps/circle-38-arm64.yaml
@@ -4,18 +4,52 @@ channels:
dependencies:
- python=3.8
- # tools
- - cython>=0.29.24
+ # test dependencies
+ - cython=0.29.24
- pytest>=6.0
+ - pytest-cov
- pytest-xdist>=1.31
- hypothesis>=5.5.3
+ - psutil
+ - pytest-asyncio>=0.17
+ - boto3
- # pandas dependencies
- - botocore>=1.11
- - flask
- - moto
- - numpy
+ # required dependencies
- python-dateutil
+ - numpy
- pytz
+
+ # optional dependencies
+ - beautifulsoup4
+ - blosc
+ - bottleneck
+ - brotlipy
+ - fastparquet
+ - fsspec
+ - html5lib
+ - gcsfs
+ - jinja2
+ - lxml
+ - matplotlib
+ - numba
+ - numexpr
+ - openpyxl
+ - odfpy
+ - pandas-gbq
+ - psycopg2
+ - pyarrow
+ - pymysql
+ # Not provided on ARM
+ #- pyreadstat
+ - pytables
+ - python-snappy
+ - pyxlsb
+ - s3fs
+ - scipy
+ - sqlalchemy
+ - tabulate
+ - xarray
+ - xlrd
+ - xlsxwriter
+ - xlwt
- zstandard
- - pip
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index 8106efcfcfd98..e312889f2eb6a 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -410,5 +410,7 @@ Compression
========================= ================== =============================================================
Dependency Minimum Version Notes
========================= ================== =============================================================
-Zstandard Zstandard compression
+brotli 0.7.0 Brotli compression
+python-snappy 0.6.0 Snappy compression
+Zstandard 0.15.2 Zstandard compression
========================= ================== =============================================================
diff --git a/environment.yml b/environment.yml
index da5d6fabcde20..0a87e2b56f4cb 100644
--- a/environment.yml
+++ b/environment.yml
@@ -69,7 +69,7 @@ dependencies:
- pytest>=6.0
- pytest-cov
- pytest-xdist>=1.31
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- pytest-instafail
# downstream tests
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index cb9b0c6de6d3b..e69bee5c647d8 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -13,6 +13,7 @@
"bs4": "4.8.2",
"blosc": "1.20.1",
"bottleneck": "1.3.1",
+ "brotli": "0.7.0",
"fastparquet": "0.4.0",
"fsspec": "0.7.4",
"html5lib": "1.1",
@@ -34,6 +35,7 @@
"pyxlsb": "1.0.6",
"s3fs": "0.4.0",
"scipy": "1.4.1",
+ "snappy": "0.6.0",
"sqlalchemy": "1.4.0",
"tables": "3.6.1",
"tabulate": "0.8.7",
@@ -50,12 +52,14 @@
INSTALL_MAPPING = {
"bs4": "beautifulsoup4",
"bottleneck": "Bottleneck",
+ "brotli": "brotlipy",
+ "jinja2": "Jinja2",
"lxml.etree": "lxml",
"odf": "odfpy",
"pandas_gbq": "pandas-gbq",
- "tables": "pytables",
+ "snappy": "python-snappy",
"sqlalchemy": "SQLAlchemy",
- "jinja2": "Jinja2",
+ "tables": "pytables",
}
@@ -66,6 +70,13 @@ def get_version(module: types.ModuleType) -> str:
version = getattr(module, "__VERSION__", None)
if version is None:
+ if module.__name__ == "brotli":
+ # brotli doesn't contain attributes to confirm it's version
+ return ""
+ if module.__name__ == "snappy":
+ # snappy doesn't contain attributes to confirm it's version
+ # See https://github.com/andrix/python-snappy/pull/119
+ return ""
raise ImportError(f"Can't determine version for {module.__name__}")
if module.__name__ == "psycopg2":
# psycopg2 appends " (dt dec pq3 ext lo64)" to it's version
@@ -141,7 +152,7 @@ def import_optional_dependency(
minimum_version = min_version if min_version is not None else VERSIONS.get(parent)
if minimum_version:
version = get_version(module_to_get)
- if Version(version) < Version(minimum_version):
+ if version and Version(version) < Version(minimum_version):
msg = (
f"Pandas requires version '{minimum_version}' or newer of '{parent}' "
f"(version '{version}' currently installed)."
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index 22fe7bb0de949..b5b4007798135 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -504,7 +504,7 @@ def test_memory_usage(dtype):
# GH 33963
if dtype.storage == "pyarrow":
- pytest.skip("not applicable")
+ pytest.skip(f"not applicable for {dtype.storage}")
series = pd.Series(["a", "b", "c"], dtype=dtype)
diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py
index a73684868e3ae..7f4766bac0329 100644
--- a/pandas/tests/extension/arrow/test_bool.py
+++ b/pandas/tests/extension/arrow/test_bool.py
@@ -1,6 +1,11 @@
import numpy as np
import pytest
+from pandas.compat import (
+ is_ci_environment,
+ is_platform_windows,
+)
+
import pandas as pd
import pandas._testing as tm
from pandas.api.types import is_bool_dtype
@@ -91,6 +96,10 @@ def test_reduce_series_boolean(self):
pass
+@pytest.mark.skipif(
+ is_ci_environment() and is_platform_windows(),
+ reason="Causes stack overflow on Windows CI",
+)
class TestReduceBoolean(base.BaseBooleanReduceTests):
pass
diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py
index 1d3d736ca7ee2..a1d232b737da7 100644
--- a/pandas/tests/extension/base/ops.py
+++ b/pandas/tests/extension/base/ops.py
@@ -114,17 +114,22 @@ def test_add_series_with_extension_array(self, data):
self.assert_series_equal(result, expected)
@pytest.mark.parametrize("box", [pd.Series, pd.DataFrame])
- def test_direct_arith_with_ndframe_returns_not_implemented(self, data, box):
+ def test_direct_arith_with_ndframe_returns_not_implemented(
+ self, request, data, box
+ ):
# EAs should return NotImplemented for ops with Series/DataFrame
# Pandas takes care of unboxing the series and calling the EA's op.
other = pd.Series(data)
if box is pd.DataFrame:
other = other.to_frame()
- if hasattr(data, "__add__"):
- result = data.__add__(other)
- assert result is NotImplemented
- else:
- raise pytest.skip(f"{type(data).__name__} does not implement add")
+ if not hasattr(data, "__add__"):
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"{type(data).__name__} does not implement add"
+ )
+ )
+ result = data.__add__(other)
+ assert result is NotImplemented
class BaseComparisonOpsTests(BaseOpsUtil):
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index d530a75b74c8f..84491adb30ef6 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -1,5 +1,6 @@
import collections
import operator
+import sys
import pytest
@@ -155,20 +156,32 @@ def test_contains(self, data):
class TestConstructors(BaseJSON, base.BaseConstructorsTests):
- @pytest.mark.skip(reason="not implemented constructor from dtype")
+ @pytest.mark.xfail(reason="not implemented constructor from dtype")
def test_from_dtype(self, data):
# construct from our dtype & string dtype
- pass
+ super(self).test_from_dtype(data)
@pytest.mark.xfail(reason="RecursionError, GH-33900")
def test_series_constructor_no_data_with_index(self, dtype, na_value):
# RecursionError: maximum recursion depth exceeded in comparison
- super().test_series_constructor_no_data_with_index(dtype, na_value)
+ rec_limit = sys.getrecursionlimit()
+ try:
+ # Limit to avoid stack overflow on Windows CI
+ sys.setrecursionlimit(100)
+ super().test_series_constructor_no_data_with_index(dtype, na_value)
+ finally:
+ sys.setrecursionlimit(rec_limit)
@pytest.mark.xfail(reason="RecursionError, GH-33900")
def test_series_constructor_scalar_na_with_index(self, dtype, na_value):
# RecursionError: maximum recursion depth exceeded in comparison
- super().test_series_constructor_scalar_na_with_index(dtype, na_value)
+ rec_limit = sys.getrecursionlimit()
+ try:
+ # Limit to avoid stack overflow on Windows CI
+ sys.setrecursionlimit(100)
+ super().test_series_constructor_scalar_na_with_index(dtype, na_value)
+ finally:
+ sys.setrecursionlimit(rec_limit)
@pytest.mark.xfail(reason="collection as scalar, GH-33901")
def test_series_constructor_scalar_with_index(self, data, dtype):
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index d21110e078709..1e17bf33c806c 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -50,7 +50,7 @@ def data():
"""Length-100 array for this type.
* data[0] and data[1] should both be non missing
- * data[0] and data[1] should not gbe equal
+ * data[0] and data[1] should not be equal
"""
return Categorical(make_data())
@@ -86,7 +86,7 @@ class TestDtype(base.BaseDtypeTests):
class TestInterface(base.BaseInterfaceTests):
- @pytest.mark.skip(reason="Memory usage doesn't match")
+ @pytest.mark.xfail(reason="Memory usage doesn't match")
def test_memory_usage(self, data):
# Is this deliberate?
super().test_memory_usage(data)
@@ -149,13 +149,7 @@ class TestIndex(base.BaseIndexTests):
class TestMissing(base.BaseMissingTests):
- @pytest.mark.skip(reason="Not implemented")
- def test_fillna_limit_pad(self, data_missing):
- super().test_fillna_limit_pad(data_missing)
-
- @pytest.mark.skip(reason="Not implemented")
- def test_fillna_limit_backfill(self, data_missing):
- super().test_fillna_limit_backfill(data_missing)
+ pass
class TestReduce(base.BaseNoReduceTests):
@@ -163,7 +157,7 @@ class TestReduce(base.BaseNoReduceTests):
class TestMethods(base.BaseMethodsTests):
- @pytest.mark.skip(reason="Unobserved categories included")
+ @pytest.mark.xfail(reason="Unobserved categories included")
def test_value_counts(self, all_data, dropna):
return super().test_value_counts(all_data, dropna)
@@ -184,10 +178,6 @@ def test_combine_add(self, data_repeated):
expected = pd.Series([a + val for a in list(orig_data1)])
self.assert_series_equal(result, expected)
- @pytest.mark.skip(reason="Not Applicable")
- def test_fillna_length_mismatch(self, data_missing):
- super().test_fillna_length_mismatch(data_missing)
-
class TestCasting(base.BaseCastingTests):
@pytest.mark.parametrize("cls", [Categorical, CategoricalIndex])
diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py
index a64b42fad9415..92796c604333d 100644
--- a/pandas/tests/extension/test_datetime.py
+++ b/pandas/tests/extension/test_datetime.py
@@ -175,9 +175,7 @@ class TestMissing(BaseDatetimeTests, base.BaseMissingTests):
class TestReshaping(BaseDatetimeTests, base.BaseReshapingTests):
- @pytest.mark.skip(reason="We have DatetimeTZBlock")
- def test_concat(self, data, in_frame):
- pass
+ pass
class TestSetitem(BaseDatetimeTests, base.BaseSetitemTests):
diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py
index e2f4d69c489ba..0f916cea9d518 100644
--- a/pandas/tests/extension/test_interval.py
+++ b/pandas/tests/extension/test_interval.py
@@ -121,9 +121,9 @@ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna):
class TestMethods(BaseInterval, base.BaseMethodsTests):
- @pytest.mark.skip(reason="addition is not defined for intervals")
+ @pytest.mark.xfail(reason="addition is not defined for intervals")
def test_combine_add(self, data_repeated):
- pass
+ super().test_combine_add(data_repeated)
@pytest.mark.xfail(
reason="Raises with incorrect message bc it disallows *all* listlikes "
@@ -134,29 +134,31 @@ def test_fillna_length_mismatch(self, data_missing):
class TestMissing(BaseInterval, base.BaseMissingTests):
- # Index.fillna only accepts scalar `value`, so we have to skip all
+ # Index.fillna only accepts scalar `value`, so we have to xfail all
# non-scalar fill tests.
- unsupported_fill = pytest.mark.skip("Unsupported fillna option.")
+ unsupported_fill = pytest.mark.xfail(
+ reason="Unsupported fillna option for Interval."
+ )
@unsupported_fill
def test_fillna_limit_pad(self):
- pass
+ super().test_fillna_limit_pad()
@unsupported_fill
def test_fillna_series_method(self):
- pass
+ super().test_fillna_series_method()
@unsupported_fill
def test_fillna_limit_backfill(self):
- pass
+ super().test_fillna_limit_backfill()
@unsupported_fill
def test_fillna_no_op_returns_copy(self):
- pass
+ super().test_fillna_no_op_returns_copy()
@unsupported_fill
def test_fillna_series(self):
- pass
+ super().test_fillna_series()
def test_fillna_non_scalar_raises(self, data_missing):
msg = "can only insert Interval objects and NA into an IntervalArray"
@@ -173,9 +175,9 @@ class TestSetitem(BaseInterval, base.BaseSetitemTests):
class TestPrinting(BaseInterval, base.BasePrintingTests):
- @pytest.mark.skip(reason="custom repr")
+ @pytest.mark.xfail(reason="Interval has custom repr")
def test_array_repr(self, data, size):
- pass
+ super().test_array_repr()
class TestParsing(BaseInterval, base.BaseParsingTests):
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index 2e1112ccf2205..ee181101a181a 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -208,10 +208,15 @@ def test_series_constructor_scalar_with_index(self, data, dtype):
class TestDtype(BaseNumPyTests, base.BaseDtypeTests):
- @pytest.mark.skip(reason="Incorrect expected.")
- # we unsurprisingly clash with a NumPy name.
- def test_check_dtype(self, data):
- pass
+ def test_check_dtype(self, data, request):
+ if data.dtype.numpy_dtype == "object":
+ request.node.add_marker(
+ pytest.mark.xfail(
+ reason=f"PandasArray expectedly clashes with a "
+ f"NumPy name: {data.dtype.numpy_dtype}"
+ )
+ )
+ super().test_check_dtype(data)
class TestGetitem(BaseNumPyTests, base.BaseGetitemTests):
@@ -345,11 +350,6 @@ def test_fillna_frame(self, data_missing):
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests):
- @pytest.mark.skip(reason="Incorrect expected.")
- def test_merge(self, data, na_value):
- # Fails creating expected (key column becomes a PandasDtype because)
- super().test_merge(data, na_value)
-
@pytest.mark.parametrize(
"in_frame",
[
diff --git a/pandas/tests/extension/test_string.py b/pandas/tests/extension/test_string.py
index 4256142556894..e96850e4e945b 100644
--- a/pandas/tests/extension/test_string.py
+++ b/pandas/tests/extension/test_string.py
@@ -28,7 +28,7 @@
def split_array(arr):
if arr.dtype.storage != "pyarrow":
- pytest.skip("chunked array n/a")
+ pytest.skip("only applicable for pyarrow chunked array n/a")
def _split_array(arr):
import pyarrow as pa
@@ -162,9 +162,9 @@ class TestMethods(base.BaseMethodsTests):
def test_value_counts(self, all_data, dropna):
return super().test_value_counts(all_data, dropna)
- @pytest.mark.skip(reason="returns nullable")
+ @pytest.mark.xfail(reason="returns nullable: GH 44692")
def test_value_counts_with_normalize(self, data):
- pass
+ super().test_value_counts_with_normalize(data)
class TestCasting(base.BaseCastingTests):
diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py
index ff247349ff4d5..449a1c69a4ef6 100644
--- a/pandas/tests/plotting/frame/test_frame.py
+++ b/pandas/tests/plotting/frame/test_frame.py
@@ -167,12 +167,11 @@ def test_nullable_int_plot(self):
df = DataFrame(
{
"A": [1, 2, 3, 4, 5],
- "B": [1.0, 2.0, 3.0, 4.0, 5.0],
- "C": [7, 5, np.nan, 3, 2],
+ "B": [1, 2, 3, 4, 5],
+ "C": np.array([7, 5, np.nan, 3, 2], dtype=object),
"D": pd.to_datetime(dates, format="%Y").view("i8"),
"E": pd.to_datetime(dates, format="%Y", utc=True).view("i8"),
- },
- dtype=np.int64,
+ }
)
_check_plot_works(df.plot, x="A", y="B")
diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py
index fe8620ef76c4b..d595f4b453b28 100644
--- a/pandas/tests/plotting/test_converter.py
+++ b/pandas/tests/plotting/test_converter.py
@@ -334,7 +334,7 @@ def test_conversion(self):
rs = self.pc.convert(
np.array(
- ["2012-01-01 00:00:00+0000", "2012-01-02 00:00:00+0000"],
+ ["2012-01-01 00:00:00", "2012-01-02 00:00:00"],
dtype="datetime64[ns]",
),
None,
diff --git a/pyproject.toml b/pyproject.toml
index 1d318ab5f70c3..318a7398e1035 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -57,6 +57,7 @@ markers = [
"arm_slow: mark a test as slow for arm64 architecture",
"arraymanager: mark a test to run with ArrayManager enabled",
]
+asyncio_mode = "strict"
[tool.mypy]
# Import discovery
diff --git a/requirements-dev.txt b/requirements-dev.txt
index ac525f1d09fbe..6fd3ac53c50cb 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -47,7 +47,7 @@ flask
pytest>=6.0
pytest-cov
pytest-xdist>=1.31
-pytest-asyncio
+pytest-asyncio>=0.17
pytest-instafail
seaborn
statsmodels
| backports #46543, #46401, #46347, #46260, #46426, #46016, #46370 and #46358
(will change milestones on those, once CI here is successful and merged.) | https://api.github.com/repos/pandas-dev/pandas/pulls/46559 | 2022-03-29T12:54:08Z | 2022-03-29T22:40:54Z | 2022-03-29T22:40:54Z | 2022-03-30T10:44:07Z |
CI: pre-commit autoupdate to fix CI | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 0a2f3f8f2506d..04e148453387b 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -16,7 +16,7 @@ repos:
pass_filenames: true
require_serial: false
- repo: https://github.com/python/black
- rev: 22.1.0
+ rev: 22.3.0
hooks:
- id: black
- repo: https://github.com/codespell-project/codespell
@@ -33,7 +33,7 @@ repos:
exclude: \.txt$
- id: trailing-whitespace
- repo: https://github.com/cpplint/cpplint
- rev: 1.5.5
+ rev: 1.6.0
hooks:
- id: cpplint
# We don't lint all C files because we don't want to lint any that are built
@@ -56,7 +56,7 @@ repos:
hooks:
- id: isort
- repo: https://github.com/asottile/pyupgrade
- rev: v2.31.0
+ rev: v2.31.1
hooks:
- id: pyupgrade
args: [--py38-plus]
diff --git a/environment.yml b/environment.yml
index 187f666938aeb..0dc9806856585 100644
--- a/environment.yml
+++ b/environment.yml
@@ -18,7 +18,7 @@ dependencies:
- cython>=0.29.24
# code checks
- - black=22.1.0
+ - black=22.3.0
- cpplint
- flake8=4.0.1
- flake8-bugbear=21.3.2 # used by flake8, find likely bugs
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 3ccedcbad1782..94709171739d2 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -6,7 +6,7 @@ python-dateutil>=2.8.1
pytz
asv < 0.5.0
cython>=0.29.24
-black==22.1.0
+black==22.3.0
cpplint
flake8==4.0.1
flake8-bugbear==21.3.2
| new click release broke previous version of `black`, see https://github.com/psf/black/issues/2964 | https://api.github.com/repos/pandas-dev/pandas/pulls/46558 | 2022-03-29T12:34:45Z | 2022-03-29T13:48:59Z | 2022-03-29T13:48:59Z | 2022-03-30T21:32:09Z |
Backport PR #46358 on branch 1.4.x (CI: Debug Windows stack overflow) | diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index a37ea3eb89167..d05caa7d881f0 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -45,7 +45,7 @@ jobs:
/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<60.0.0' && \
- pip install cython numpy python-dateutil pytz pytest pytest-xdist hypothesis pytest-azurepipelines && \
+ pip install cython numpy python-dateutil pytz pytest pytest-xdist hypothesis && \
python setup.py build_ext -q -j2 && \
python -m pip install --no-build-isolation -e . && \
pytest -m 'not slow and not network and not clipboard' pandas --junitxml=test-data.xml"
diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py
index a73684868e3ae..7f4766bac0329 100644
--- a/pandas/tests/extension/arrow/test_bool.py
+++ b/pandas/tests/extension/arrow/test_bool.py
@@ -1,6 +1,11 @@
import numpy as np
import pytest
+from pandas.compat import (
+ is_ci_environment,
+ is_platform_windows,
+)
+
import pandas as pd
import pandas._testing as tm
from pandas.api.types import is_bool_dtype
@@ -91,6 +96,10 @@ def test_reduce_series_boolean(self):
pass
+@pytest.mark.skipif(
+ is_ci_environment() and is_platform_windows(),
+ reason="Causes stack overflow on Windows CI",
+)
class TestReduceBoolean(base.BaseBooleanReduceTests):
pass
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index d530a75b74c8f..f13ef65267304 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -1,5 +1,6 @@
import collections
import operator
+import sys
import pytest
@@ -163,12 +164,24 @@ def test_from_dtype(self, data):
@pytest.mark.xfail(reason="RecursionError, GH-33900")
def test_series_constructor_no_data_with_index(self, dtype, na_value):
# RecursionError: maximum recursion depth exceeded in comparison
- super().test_series_constructor_no_data_with_index(dtype, na_value)
+ rec_limit = sys.getrecursionlimit()
+ try:
+ # Limit to avoid stack overflow on Windows CI
+ sys.setrecursionlimit(100)
+ super().test_series_constructor_no_data_with_index(dtype, na_value)
+ finally:
+ sys.setrecursionlimit(rec_limit)
@pytest.mark.xfail(reason="RecursionError, GH-33900")
def test_series_constructor_scalar_na_with_index(self, dtype, na_value):
# RecursionError: maximum recursion depth exceeded in comparison
- super().test_series_constructor_scalar_na_with_index(dtype, na_value)
+ rec_limit = sys.getrecursionlimit()
+ try:
+ # Limit to avoid stack overflow on Windows CI
+ sys.setrecursionlimit(100)
+ super().test_series_constructor_scalar_na_with_index(dtype, na_value)
+ finally:
+ sys.setrecursionlimit(rec_limit)
@pytest.mark.xfail(reason="collection as scalar, GH-33901")
def test_series_constructor_scalar_with_index(self, data, dtype):
| Backport PR #46358: CI: Debug Windows stack overflow | https://api.github.com/repos/pandas-dev/pandas/pulls/46557 | 2022-03-29T12:23:31Z | 2022-03-29T12:55:26Z | null | 2022-03-29T12:55:27Z |
Close FastParquet file even on error | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 6cbee83247692..48a52f21e3640 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -498,7 +498,8 @@ I/O
- Bug in :func:`read_parquet` when ``engine="pyarrow"`` which caused partial write to disk when column of unsupported datatype was passed (:issue:`44914`)
- Bug in :func:`DataFrame.to_excel` and :class:`ExcelWriter` would raise when writing an empty DataFrame to a ``.ods`` file (:issue:`45793`)
- Bug in Parquet roundtrip for Interval dtype with ``datetime64[ns]`` subtype (:issue:`45881`)
-- Bug in :func:`read_excel` when reading a ``.ods`` file with newlines between xml elements(:issue:`45598`)
+- Bug in :func:`read_excel` when reading a ``.ods`` file with newlines between xml elements (:issue:`45598`)
+- Bug in :func:`read_parquet` when ``engine="fastparquet"`` where the file was not closed on error (:issue:`46555`)
Period
^^^^^^
diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py
index c7e8d67189e5d..27b0b3d08ad53 100644
--- a/pandas/io/parquet.py
+++ b/pandas/io/parquet.py
@@ -349,13 +349,12 @@ def read(
)
path = handles.handle
- parquet_file = self.api.ParquetFile(path, **parquet_kwargs)
-
- result = parquet_file.to_pandas(columns=columns, **kwargs)
-
- if handles is not None:
- handles.close()
- return result
+ try:
+ parquet_file = self.api.ParquetFile(path, **parquet_kwargs)
+ return parquet_file.to_pandas(columns=columns, **kwargs)
+ finally:
+ if handles is not None:
+ handles.close()
@doc(storage_options=_shared_docs["storage_options"])
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index 3001922e95a54..7c04a51e803f6 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -1155,3 +1155,11 @@ def test_use_nullable_dtypes_not_supported(self, fp):
df.to_parquet(path)
with pytest.raises(ValueError, match="not supported for the fastparquet"):
read_parquet(path, engine="fastparquet", use_nullable_dtypes=True)
+
+ def test_close_file_handle_on_read_error(self):
+ with tm.ensure_clean("test.parquet") as path:
+ pathlib.Path(path).write_bytes(b"breakit")
+ with pytest.raises(Exception, match=""): # Not important which exception
+ read_parquet(path, engine="fastparquet")
+ # The next line raises an error on Windows if the file is still open
+ pathlib.Path(path).unlink(missing_ok=False)
| - [x] closes #46555
- [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 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/46556 | 2022-03-29T10:56:04Z | 2022-03-30T18:53:15Z | 2022-03-30T18:53:14Z | 2022-03-30T21:07:58Z |
Backport PR #46542 on branch 1.4.x (Reorder YAML) | diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index 5452f9d67ee81..303d58d96c2c7 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -30,38 +30,38 @@ jobs:
# even if tests are skipped/xfailed
pyarrow_version: ["5", "6", "7"]
include:
- - env_file: actions-38-downstream_compat.yaml
+ - name: "Downstream Compat"
+ env_file: actions-38-downstream_compat.yaml
pattern: "not slow and not network and not single_cpu"
pytest_target: "pandas/tests/test_downstream.py"
- name: "Downstream Compat"
- - env_file: actions-38-minimum_versions.yaml
+ - name: "Minimum Versions"
+ env_file: actions-38-minimum_versions.yaml
pattern: "not slow and not network and not single_cpu"
- name: "Minimum Versions"
- - env_file: actions-38.yaml
+ - name: "Locale: it_IT.utf8"
+ env_file: actions-38.yaml
pattern: "not slow and not network and not single_cpu"
extra_apt: "language-pack-it"
lang: "it_IT.utf8"
lc_all: "it_IT.utf8"
- name: "Locale: it_IT.utf8"
- - env_file: actions-38.yaml
+ - name: "Locale: zh_CN.utf8"
+ env_file: actions-38.yaml
pattern: "not slow and not network and not single_cpu"
extra_apt: "language-pack-zh-hans"
lang: "zh_CN.utf8"
lc_all: "zh_CN.utf8"
- name: "Locale: zh_CN.utf8"
- - env_file: actions-38.yaml
+ - name: "Data Manager"
+ env_file: actions-38.yaml
pattern: "not slow and not network and not single_cpu"
pandas_data_manager: "array"
- name: "Data Manager"
- - env_file: actions-pypy-38.yaml
+ - name: "Pypy"
+ env_file: actions-pypy-38.yaml
pattern: "not slow and not network and not single_cpu"
test_args: "--max-worker-restart 0"
- name: "Pypy"
- - env_file: actions-310-numpydev.yaml
+ - name: "Numpy Dev"
+ env_file: actions-310-numpydev.yaml
pattern: "not slow and not network and not single_cpu"
pandas_testing_mode: "deprecate"
test_args: "-W error"
- name: "Numpy Dev"
fail-fast: false
name: ${{ matrix.name || format('{0} pyarrow={1} {2}', matrix.env_file, matrix.pyarrow_version, matrix.pattern) }}
env:
| Backport PR #46542: Reorder YAML | https://api.github.com/repos/pandas-dev/pandas/pulls/46550 | 2022-03-28T22:59:41Z | 2022-03-29T11:39:32Z | 2022-03-29T11:39:32Z | 2022-03-29T11:39:33Z |
REGR: tests + whats new: boolean dtype in styler render | diff --git a/doc/source/whatsnew/v1.4.2.rst b/doc/source/whatsnew/v1.4.2.rst
index 13f3e9a0d0a8c..76b2a5d6ffd47 100644
--- a/doc/source/whatsnew/v1.4.2.rst
+++ b/doc/source/whatsnew/v1.4.2.rst
@@ -21,7 +21,7 @@ Fixed regressions
- Fixed regression in :meth:`DataFrame.replace` when a replacement value was also a target for replacement (:issue:`46306`)
- Fixed regression in :meth:`DataFrame.replace` when the replacement value was explicitly ``None`` when passed in a dictionary to ``to_replace`` (:issue:`45601`, :issue:`45836`)
- Fixed regression when setting values with :meth:`DataFrame.loc` losing :class:`MultiIndex` names if :class:`DataFrame` was empty before (:issue:`46317`)
--
+- Fixed regression when rendering boolean datatype columns with :meth:`.Styler` (:issue:`46384`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/tests/io/formats/style/test_format.py b/pandas/tests/io/formats/style/test_format.py
index 5207be992d606..a52c679e16ad5 100644
--- a/pandas/tests/io/formats/style/test_format.py
+++ b/pandas/tests/io/formats/style/test_format.py
@@ -434,3 +434,11 @@ def test_1level_multiindex():
assert ctx["body"][0][0]["is_visible"] is True
assert ctx["body"][1][0]["display_value"] == "2"
assert ctx["body"][1][0]["is_visible"] is True
+
+
+def test_boolean_format():
+ # gh 46384: booleans do not collapse to integer representation on display
+ df = DataFrame([[True, False]])
+ ctx = df.style._translate(True, True)
+ assert ctx["body"][0][1]["display_value"] is True
+ assert ctx["body"][0][2]["display_value"] is False
| ### COMES AFTER #46501
closes #46384 | https://api.github.com/repos/pandas-dev/pandas/pulls/46548 | 2022-03-28T21:41:21Z | 2022-03-30T21:36:26Z | 2022-03-30T21:36:25Z | 2022-03-30T21:36:26Z |
Speed up a test | diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py
index 3fd2a5e2bca32..d3ba14f93e9d9 100644
--- a/pandas/io/formats/csvs.py
+++ b/pandas/io/formats/csvs.py
@@ -44,6 +44,9 @@
from pandas.io.formats.format import DataFrameFormatter
+_DEFAULT_CHUNKSIZE_CELLS = 100_000
+
+
class CSVFormatter:
cols: np.ndarray
@@ -162,7 +165,7 @@ def _initialize_columns(self, cols: Sequence[Hashable] | None) -> np.ndarray:
def _initialize_chunksize(self, chunksize: int | None) -> int:
if chunksize is None:
- return (100000 // (len(self.cols) or 1)) or 1
+ return (_DEFAULT_CHUNKSIZE_CELLS // (len(self.cols) or 1)) or 1
return int(chunksize)
@property
diff --git a/pandas/tests/frame/methods/test_to_csv.py b/pandas/tests/frame/methods/test_to_csv.py
index b7874d51b6f33..a883e68331546 100644
--- a/pandas/tests/frame/methods/test_to_csv.py
+++ b/pandas/tests/frame/methods/test_to_csv.py
@@ -759,9 +759,11 @@ def test_to_csv_chunking(self, chunksize):
tm.assert_frame_equal(rs, aa)
@pytest.mark.slow
- def test_to_csv_wide_frame_formatting(self):
+ def test_to_csv_wide_frame_formatting(self, monkeypatch):
# Issue #8621
- df = DataFrame(np.random.randn(1, 100010), columns=None, index=None)
+ n_cells = 1_000
+ monkeypatch.setattr("pandas.io.formats.csvs._DEFAULT_CHUNKSIZE_CELLS", n_cells)
+ df = DataFrame(np.random.randn(1, n_cells + 10), columns=None, index=None)
with tm.ensure_clean() as filename:
df.to_csv(filename, header=False, index=False)
rs = read_csv(filename, header=None)
| Saves 30s of test time, it ain't much but it's honest work :-) Also moves a magic number to a constant.
- [ ] 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 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/46547 | 2022-03-28T20:35:52Z | 2022-03-28T22:55:57Z | null | 2023-05-11T01:21:42Z |
BUG: pd.concat with identical key leads to multi-indexing error | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 8c02785647861..121c2805be8ca 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -536,6 +536,7 @@ Reshaping
- Bug in :func:`get_dummies` that selected object and categorical dtypes but not string (:issue:`44965`)
- Bug in :meth:`DataFrame.align` when aligning a :class:`MultiIndex` to a :class:`Series` with another :class:`MultiIndex` (:issue:`46001`)
- Bug in concanenation with ``IntegerDtype``, or ``FloatingDtype`` arrays where the resulting dtype did not mirror the behavior of the non-nullable dtypes (:issue:`46379`)
+- Bug in :func:`concat` with identical key leads to error when indexing :class:`MultiIndex` (:issue:`46519`)
-
Sparse
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index 72f3b402d49e3..864aa97df0587 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -705,7 +705,7 @@ def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde
names = [None]
if levels is None:
- levels = [ensure_index(keys)]
+ levels = [ensure_index(keys).unique()]
else:
levels = [ensure_index(x) for x in levels]
diff --git a/pandas/tests/reshape/concat/test_index.py b/pandas/tests/reshape/concat/test_index.py
index aad56a1dccedc..50fee28669c58 100644
--- a/pandas/tests/reshape/concat/test_index.py
+++ b/pandas/tests/reshape/concat/test_index.py
@@ -1,6 +1,8 @@
import numpy as np
import pytest
+from pandas.errors import PerformanceWarning
+
import pandas as pd
from pandas import (
DataFrame,
@@ -323,3 +325,49 @@ def test_concat_multiindex_(self):
{"col": ["a", "b", "c"]}, index=MultiIndex.from_product(iterables)
)
tm.assert_frame_equal(result_df, expected_df)
+
+ def test_concat_with_key_not_unique(self):
+ # GitHub #46519
+ df1 = DataFrame({"name": [1]})
+ df2 = DataFrame({"name": [2]})
+ df3 = DataFrame({"name": [3]})
+ df_a = concat([df1, df2, df3], keys=["x", "y", "x"])
+ # the warning is caused by indexing unsorted multi-index
+ with tm.assert_produces_warning(
+ PerformanceWarning, match="indexing past lexsort depth"
+ ):
+ out_a = df_a.loc[("x", 0), :]
+
+ df_b = DataFrame(
+ {"name": [1, 2, 3]}, index=Index([("x", 0), ("y", 0), ("x", 0)])
+ )
+ with tm.assert_produces_warning(
+ PerformanceWarning, match="indexing past lexsort depth"
+ ):
+ out_b = df_b.loc[("x", 0)]
+
+ tm.assert_frame_equal(out_a, out_b)
+
+ df1 = DataFrame({"name": ["a", "a", "b"]})
+ df2 = DataFrame({"name": ["a", "b"]})
+ df3 = DataFrame({"name": ["c", "d"]})
+ df_a = concat([df1, df2, df3], keys=["x", "y", "x"])
+ with tm.assert_produces_warning(
+ PerformanceWarning, match="indexing past lexsort depth"
+ ):
+ out_a = df_a.loc[("x", 0), :]
+
+ df_b = DataFrame(
+ {
+ "a": ["x", "x", "x", "y", "y", "x", "x"],
+ "b": [0, 1, 2, 0, 1, 0, 1],
+ "name": list("aababcd"),
+ }
+ ).set_index(["a", "b"])
+ df_b.index.names = [None, None]
+ with tm.assert_produces_warning(
+ PerformanceWarning, match="indexing past lexsort depth"
+ ):
+ out_b = df_b.loc[("x", 0), :]
+
+ tm.assert_frame_equal(out_a, out_b)
| - [x] closes #46519
- [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).
- [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/46546 | 2022-03-28T19:47:50Z | 2022-04-05T20:20:21Z | 2022-04-05T20:20:21Z | 2022-04-05T20:25:53Z |
Pin pytest-asyncio>=0.17 | diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index bc8791afc69f7..2fc1d0d512cf1 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -162,7 +162,7 @@ jobs:
shell: bash
run: |
# TODO: re-enable cov, its slowing the tests down though
- pip install Cython numpy python-dateutil pytz pytest>=6.0 pytest-xdist>=1.31.0 pytest-asyncio hypothesis>=5.5.3
+ pip install Cython numpy python-dateutil pytz pytest>=6.0 pytest-xdist>=1.31.0 pytest-asyncio>=0.17 hypothesis>=5.5.3
if: ${{ env.IS_PYPY == 'true' }}
- name: Build Pandas
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 86cf0c79759f5..9b83ed6116ed3 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -45,7 +45,7 @@ jobs:
/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<60.0.0' && \
- pip install cython numpy python-dateutil pytz pytest pytest-xdist pytest-asyncio hypothesis && \
+ pip install cython numpy python-dateutil pytz pytest pytest-xdist pytest-asyncio>=0.17 hypothesis && \
python setup.py build_ext -q -j2 && \
python -m pip install --no-build-isolation -e . && \
pytest -m 'not slow and not network and not clipboard and not single_cpu' pandas --junitxml=test-data.xml"
diff --git a/ci/deps/actions-310-numpydev.yaml b/ci/deps/actions-310-numpydev.yaml
index a5eb8a69e19da..401be14aaca02 100644
--- a/ci/deps/actions-310-numpydev.yaml
+++ b/ci/deps/actions-310-numpydev.yaml
@@ -9,7 +9,7 @@ dependencies:
- pytest-cov
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- - pytest-asyncio
+ - pytest-asyncio>=0.17
# pandas dependencies
- python-dateutil
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml
index 37e7ea04a348a..dac1219245e84 100644
--- a/ci/deps/actions-310.yaml
+++ b/ci/deps/actions-310.yaml
@@ -11,7 +11,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-38-downstream_compat.yaml
index 40f48884f1822..01415122e6076 100644
--- a/ci/deps/actions-38-downstream_compat.yaml
+++ b/ci/deps/actions-38-downstream_compat.yaml
@@ -12,7 +12,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/ci/deps/actions-38-minimum_versions.yaml b/ci/deps/actions-38-minimum_versions.yaml
index abba5ddd60325..f3a967f67cbc3 100644
--- a/ci/deps/actions-38-minimum_versions.yaml
+++ b/ci/deps/actions-38-minimum_versions.yaml
@@ -13,7 +13,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml
index 9c46eca4ab989..79cd831051c2f 100644
--- a/ci/deps/actions-38.yaml
+++ b/ci/deps/actions-38.yaml
@@ -11,7 +11,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml
index 89b647372d7bc..1c681104f3196 100644
--- a/ci/deps/actions-39.yaml
+++ b/ci/deps/actions-39.yaml
@@ -11,7 +11,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/ci/deps/circle-38-arm64.yaml b/ci/deps/circle-38-arm64.yaml
index f38c401ca49f8..66fedccc5eca7 100644
--- a/ci/deps/circle-38-arm64.yaml
+++ b/ci/deps/circle-38-arm64.yaml
@@ -11,7 +11,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/environment.yml b/environment.yml
index ac8921b12f4a3..a424100eda21a 100644
--- a/environment.yml
+++ b/environment.yml
@@ -69,7 +69,7 @@ dependencies:
- pytest>=6.0
- pytest-cov
- pytest-xdist>=1.31
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- pytest-instafail
# downstream tests
diff --git a/requirements-dev.txt b/requirements-dev.txt
index a0558f1a00177..2746b91986a3c 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -47,7 +47,7 @@ flask
pytest>=6.0
pytest-cov
pytest-xdist>=1.31
-pytest-asyncio
+pytest-asyncio>=0.17
pytest-instafail
seaborn
statsmodels
| Required for "asyncio_mode" setting that was added to pyproject.toml.
Part of https://github.com/pandas-dev/pandas/pull/46493#issuecomment-1079541210
- [ ] 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 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/46543 | 2022-03-28T18:14:17Z | 2022-03-28T22:57:39Z | 2022-03-28T22:57:39Z | 2022-03-30T10:45:20Z |
Reorder YAML | diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index bc8791afc69f7..5bd1ac35e0746 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -30,38 +30,38 @@ jobs:
# even if tests are skipped/xfailed
pyarrow_version: ["5", "7"]
include:
- - env_file: actions-38-downstream_compat.yaml
+ - name: "Downstream Compat"
+ env_file: actions-38-downstream_compat.yaml
pattern: "not slow and not network and not single_cpu"
pytest_target: "pandas/tests/test_downstream.py"
- name: "Downstream Compat"
- - env_file: actions-38-minimum_versions.yaml
+ - name: "Minimum Versions"
+ env_file: actions-38-minimum_versions.yaml
pattern: "not slow and not network and not single_cpu"
- name: "Minimum Versions"
- - env_file: actions-38.yaml
+ - name: "Locale: it_IT.utf8"
+ env_file: actions-38.yaml
pattern: "not slow and not network and not single_cpu"
extra_apt: "language-pack-it"
lang: "it_IT.utf8"
lc_all: "it_IT.utf8"
- name: "Locale: it_IT.utf8"
- - env_file: actions-38.yaml
+ - name: "Locale: zh_CN.utf8"
+ env_file: actions-38.yaml
pattern: "not slow and not network and not single_cpu"
extra_apt: "language-pack-zh-hans"
lang: "zh_CN.utf8"
lc_all: "zh_CN.utf8"
- name: "Locale: zh_CN.utf8"
- - env_file: actions-38.yaml
+ - name: "Data Manager"
+ env_file: actions-38.yaml
pattern: "not slow and not network and not single_cpu"
pandas_data_manager: "array"
- name: "Data Manager"
- - env_file: actions-pypy-38.yaml
+ - name: "Pypy"
+ env_file: actions-pypy-38.yaml
pattern: "not slow and not network and not single_cpu"
test_args: "--max-worker-restart 0"
- name: "Pypy"
- - env_file: actions-310-numpydev.yaml
+ - name: "Numpy Dev"
+ env_file: actions-310-numpydev.yaml
pattern: "not slow and not network and not single_cpu"
pandas_testing_mode: "deprecate"
test_args: "-W error"
- name: "Numpy Dev"
fail-fast: false
name: ${{ matrix.name || format('{0} pyarrow={1} {2}', matrix.env_file, matrix.pyarrow_version, matrix.pattern) }}
env:
| Part of https://github.com/pandas-dev/pandas/pull/46493#issuecomment-1079541210
- [ ] 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 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/46542 | 2022-03-28T18:11:58Z | 2022-03-28T22:59:12Z | 2022-03-28T22:59:12Z | 2022-03-28T22:59:48Z |
GHA: Use bash -el | diff --git a/.github/actions/build_pandas/action.yml b/.github/actions/build_pandas/action.yml
index 2e4bfea165316..e916d5bfde5fb 100644
--- a/.github/actions/build_pandas/action.yml
+++ b/.github/actions/build_pandas/action.yml
@@ -8,10 +8,10 @@ runs:
run: |
conda info
conda list
- shell: bash -l {0}
+ shell: bash -el {0}
- name: Build Pandas
run: |
python setup.py build_ext -j 2
python -m pip install -e . --no-build-isolation --no-use-pep517 --no-index
- shell: bash -l {0}
+ shell: bash -el {0}
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml
index 9ef00e7a85a6f..c357f149f2c7f 100644
--- a/.github/actions/setup/action.yml
+++ b/.github/actions/setup/action.yml
@@ -5,8 +5,8 @@ runs:
steps:
- name: Setting conda path
run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
- shell: bash -l {0}
+ shell: bash -el {0}
- name: Setup environment and build pandas
run: ci/setup_env.sh
- shell: bash -l {0}
+ shell: bash -el {0}
diff --git a/.github/workflows/asv-bot.yml b/.github/workflows/asv-bot.yml
index f3946aeb84a63..7b974f24fc162 100644
--- a/.github/workflows/asv-bot.yml
+++ b/.github/workflows/asv-bot.yml
@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# Set concurrency to prevent abuse(full runs are ~5.5 hours !!!)
diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index f32fed3b3ee68..4592279442b82 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -39,7 +39,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
@@ -105,7 +105,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
@@ -162,7 +162,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index bc8791afc69f7..9f67c78ce7bb8 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -20,7 +20,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
timeout-minutes: 120
strategy:
matrix:
@@ -159,7 +159,6 @@ jobs:
if: ${{ env.IS_PYPY == 'true' }}
- name: Setup PyPy dependencies
- shell: bash
run: |
# TODO: re-enable cov, its slowing the tests down though
pip install Cython numpy python-dateutil pytz pytest>=6.0 pytest-xdist>=1.31.0 pytest-asyncio hypothesis>=5.5.3
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index c287827206336..a44f85222fb0e 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -56,7 +56,7 @@ jobs:
# TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- name: Install dependencies
- shell: bash
+ shell: bash -el {0}
run: |
python -m pip install --upgrade pip "setuptools<60.0.0" wheel
pip install -i https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
@@ -74,7 +74,7 @@ jobs:
python -c "import pandas; pandas.show_versions();"
- name: Test with pytest
- shell: bash
+ shell: bash -el {0}
run: |
ci/run_tests.sh
diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml
index 431710a49a7dd..b97b08c73fb71 100644
--- a/.github/workflows/sdist.yml
+++ b/.github/workflows/sdist.yml
@@ -20,7 +20,7 @@ jobs:
timeout-minutes: 60
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
strategy:
fail-fast: false
| Part of https://github.com/pandas-dev/pandas/pull/46493#issuecomment-1079541210
- [ ] 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 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/46541 | 2022-03-28T18:10:22Z | 2022-03-28T23:10:33Z | 2022-03-28T23:10:33Z | 2022-03-30T20:08:25Z |
Upgrade GitHub Actions versions | diff --git a/.github/workflows/asv-bot.yml b/.github/workflows/asv-bot.yml
index f3946aeb84a63..18e13a5ff51c9 100644
--- a/.github/workflows/asv-bot.yml
+++ b/.github/workflows/asv-bot.yml
@@ -29,19 +29,19 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Cache conda
- uses: actions/cache@v2
+ uses: actions/cache@v3
with:
path: ~/conda_pkgs_dir
key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
# Although asv sets up its own env, deps are still needed
# during discovery process
- - uses: conda-incubator/setup-miniconda@v2
+ - uses: conda-incubator/setup-miniconda@v2.1.1
with:
activate-environment: pandas-dev
channel-priority: strict
@@ -65,7 +65,7 @@ jobs:
echo 'EOF' >> $GITHUB_ENV
echo "REGEX=$REGEX" >> $GITHUB_ENV
- - uses: actions/github-script@v5
+ - uses: actions/github-script@v6
env:
BENCH_OUTPUT: ${{env.BENCH_OUTPUT}}
REGEX: ${{env.REGEX}}
diff --git a/.github/workflows/autoupdate-pre-commit-config.yml b/.github/workflows/autoupdate-pre-commit-config.yml
index 3696cba8cf2e6..d2eac234ca361 100644
--- a/.github/workflows/autoupdate-pre-commit-config.yml
+++ b/.github/workflows/autoupdate-pre-commit-config.yml
@@ -12,9 +12,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
- name: Cache multiple paths
- uses: actions/cache@v2
+ uses: actions/cache@v3
with:
path: |
~/.cache/pre-commit
diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index f32fed3b3ee68..9f582edc56523 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -24,10 +24,10 @@ jobs:
cancel-in-progress: true
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
- name: Install Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: '3.9.7'
@@ -48,17 +48,17 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Cache conda
- uses: actions/cache@v2
+ uses: actions/cache@v3
with:
path: ~/conda_pkgs_dir
key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
- - uses: conda-incubator/setup-miniconda@v2
+ - uses: conda-incubator/setup-miniconda@v2.1.1
with:
mamba-version: "*"
channels: conda-forge
@@ -68,7 +68,7 @@ jobs:
use-only-tar-bz2: true
- name: Install node.js (for pyright)
- uses: actions/setup-node@v2
+ uses: actions/setup-node@v3
with:
node-version: "16"
@@ -114,17 +114,17 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Cache conda
- uses: actions/cache@v2
+ uses: actions/cache@v3
with:
path: ~/conda_pkgs_dir
key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
- - uses: conda-incubator/setup-miniconda@v2
+ - uses: conda-incubator/setup-miniconda@v2.1.1
with:
mamba-version: "*"
channels: conda-forge
@@ -151,7 +151,7 @@ jobs:
if: ${{ steps.build.outcome == 'success' }}
- name: Publish benchmarks artifact
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v3
with:
name: Benchmarks log
path: asv_bench/benchmarks.log
@@ -174,7 +174,7 @@ jobs:
run: docker image prune -f
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
diff --git a/.github/workflows/comment_bot.yml b/.github/workflows/comment_bot.yml
index 8f610fd5781ef..3824e015e8336 100644
--- a/.github/workflows/comment_bot.yml
+++ b/.github/workflows/comment_bot.yml
@@ -12,18 +12,18 @@ jobs:
if: startsWith(github.event.comment.body, '@github-actions pre-commit')
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- uses: r-lib/actions/pr-fetch@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
- name: Cache multiple paths
- uses: actions/cache@v2
+ uses: actions/cache@v3
with:
path: |
~/.cache/pre-commit
~/.cache/pip
key: pre-commit-dispatched-${{ runner.os }}-build
- - uses: actions/setup-python@v2
+ - uses: actions/setup-python@v3
with:
python-version: 3.8
- name: Install-pre-commit
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml
index 4cce75779d750..bba9f62a0eca6 100644
--- a/.github/workflows/docbuild-and-upload.yml
+++ b/.github/workflows/docbuild-and-upload.yml
@@ -26,7 +26,7 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
@@ -65,7 +65,7 @@ jobs:
run: mv doc/build/html web/build/docs
- name: Save website as an artifact
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v3
with:
name: website
path: web/build
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index bc8791afc69f7..182c5c2629349 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -121,12 +121,12 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Cache conda
- uses: actions/cache@v2
+ uses: actions/cache@v3
env:
CACHE_NUMBER: 0
with:
@@ -138,7 +138,7 @@ jobs:
# xsel for clipboard tests
run: sudo apt-get update && sudo apt-get install -y libc6-dev-i386 xsel ${{ env.EXTRA_APT }}
- - uses: conda-incubator/setup-miniconda@v2
+ - uses: conda-incubator/setup-miniconda@v2.1.1
with:
mamba-version: "*"
channels: conda-forge
@@ -153,7 +153,7 @@ jobs:
if: ${{ matrix.pyarrow_version }}
- name: Setup PyPy
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: "pypy-3.8"
if: ${{ env.IS_PYPY == 'true' }}
@@ -178,7 +178,7 @@ jobs:
run: pushd /tmp && python -c "import pandas; pandas.show_versions();" && popd
- name: Publish test results
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v3
with:
name: Test results
path: test-data.xml
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index c287827206336..36cd26504956e 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -45,12 +45,12 @@ jobs:
cancel-in-progress: true
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python Dev Version
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: '3.11-dev'
@@ -79,7 +79,7 @@ jobs:
ci/run_tests.sh
- name: Publish test results
- uses: actions/upload-artifact@v2
+ uses: actions/upload-artifact@v3
with:
name: Test results
path: test-data.xml
diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml
index 431710a49a7dd..bcfe0e69029f6 100644
--- a/.github/workflows/sdist.yml
+++ b/.github/workflows/sdist.yml
@@ -32,12 +32,12 @@ jobs:
cancel-in-progress: true
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
@@ -60,7 +60,7 @@ jobs:
name: ${{matrix.python-version}}-sdist.gz
path: dist/*.gz
- - uses: conda-incubator/setup-miniconda@v2
+ - uses: conda-incubator/setup-miniconda@v2.1.1
with:
activate-environment: pandas-sdist
channels: conda-forge
| Part of https://github.com/pandas-dev/pandas/pull/46493#issuecomment-1079541210
- [ ] 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 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/46540 | 2022-03-28T18:08:47Z | 2022-03-28T23:13:32Z | 2022-03-28T23:13:31Z | 2022-03-30T20:09:43Z |
CI: Refactor sdist workflow and add setup-python action | diff --git a/.github/actions/setup-python/action.yml b/.github/actions/setup-python/action.yml
new file mode 100644
index 0000000000000..4962b88362a3b
--- /dev/null
+++ b/.github/actions/setup-python/action.yml
@@ -0,0 +1,31 @@
+name: Setup Python and install requirements
+inputs:
+ python-version:
+ required: true
+ architecture:
+ default: x64
+runs:
+ using: composite
+ steps:
+ - name: Set up Python
+ uses: actions/setup-python@v3
+ with:
+ python-version: ${{ inputs.python-version }}
+ architecture: ${{ inputs.architecture }}
+
+ - name: Fix $PATH on macOS
+ run: |
+ # On macOS, the Python version we installed above is too late in $PATH
+ # to be effective if using "bash -l" (which we need for code that works
+ # with Conda envs).
+ cat >> ~/.bash_profile <<EOF
+ export PATH="\$(echo "\$PATH" | grep -Eio '[^:]+hostedtoolcache/python[^:]+bin'):\$PATH" \
+ EOF
+ shell: bash -el {0}
+ if: ${{ runner.os == 'macOS' }}
+
+ - name: Install dependencies
+ run: |
+ pip install -r ci/deps/pip-requirements.txt
+ pip list
+ shell: bash -el {0}
diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml
index cd19eb7641c8c..8cb1e969c3c22 100644
--- a/.github/workflows/sdist.yml
+++ b/.github/workflows/sdist.yml
@@ -14,8 +14,8 @@ on:
- "doc/**"
jobs:
- build:
- if: ${{ github.event.label.name == 'Build' || contains(github.event.pull_request.labels.*.name, 'Build') || github.event_name == 'push'}}
+ sdist:
+ #if: ${{ github.event.label.name == 'Build' || contains(github.event.pull_request.labels.*.name, 'Build') || github.event_name == 'push'}}
runs-on: ubuntu-latest
timeout-minutes: 60
defaults:
@@ -26,6 +26,8 @@ jobs:
fail-fast: false
matrix:
python-version: ["3.8", "3.9", "3.10"]
+ name: sdist 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 }}-${{matrix.python-version}}-sdist
@@ -36,8 +38,8 @@ jobs:
with:
fetch-depth: 0
- - name: Set up Python
- uses: actions/setup-python@v3
+ - name: Set up Python ${{ matrix.python-version }} and install dependencies
+ uses: ./.github/actions/setup-python
with:
python-version: ${{ matrix.python-version }}
diff --git a/ci/deps/pip-requirements.txt b/ci/deps/pip-requirements.txt
new file mode 100644
index 0000000000000..29dd9dd804c90
--- /dev/null
+++ b/ci/deps/pip-requirements.txt
@@ -0,0 +1,22 @@
+# Requirements for pip-based CI environments (eg., sdist and python-dev)
+
+# Python deps
+pip
+# TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
+setuptools<60.0.0
+wheel
+
+# Pandas deps
+# GH 39416
+numpy
+cython
+python-dateutil
+pytz
+
+# Test deps
+git+https://github.com/nedbat/coveragepy.git
+hypothesis
+pytest>=6.2.5
+pytest-xdist
+pytest-cov
+pytest-asyncio>=0.17
| Smaller version of https://github.com/pandas-dev/pandas/pull/46493 according to suggestion in https://github.com/pandas-dev/pandas/pull/46493#issuecomment-1079541210
- [ ] 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 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/46538 | 2022-03-28T07:57:06Z | 2022-06-28T18:24:16Z | null | 2022-06-28T18:24:16Z |
REF: Create StorageExtensionDtype | diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index f3db5598e306c..21b5dc625956e 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -1,9 +1,6 @@
from __future__ import annotations
-from typing import (
- TYPE_CHECKING,
- Any,
-)
+from typing import TYPE_CHECKING
import numpy as np
@@ -24,6 +21,7 @@
from pandas.core.dtypes.base import (
ExtensionDtype,
+ StorageExtensionDtype,
register_extension_dtype,
)
from pandas.core.dtypes.common import (
@@ -55,7 +53,7 @@
@register_extension_dtype
-class StringDtype(ExtensionDtype):
+class StringDtype(StorageExtensionDtype):
"""
Extension dtype for string data.
@@ -67,7 +65,7 @@ class StringDtype(ExtensionDtype):
parts of the API may change without warning.
In particular, StringDtype.na_value may change to no longer be
- ``numpy.nan``.
+ ``pd.NA``.
Parameters
----------
@@ -141,7 +139,6 @@ def construct_from_string(cls, string):
-----
TypeError
If the string is not a valid option.
-
"""
if not isinstance(string, str):
raise TypeError(
@@ -156,15 +153,6 @@ def construct_from_string(cls, string):
else:
raise TypeError(f"Cannot construct a '{cls.__name__}' from '{string}'")
- def __eq__(self, other: Any) -> bool:
- if isinstance(other, str) and other == "string":
- return True
- return super().__eq__(other)
-
- def __hash__(self) -> int:
- # custom __eq__ so have to override __hash__
- return super().__hash__()
-
# https://github.com/pandas-dev/pandas/issues/36126
# error: Signature of "construct_array_type" incompatible with supertype
# "ExtensionDtype"
@@ -185,12 +173,6 @@ def construct_array_type( # type: ignore[override]
else:
return ArrowStringArray
- def __repr__(self):
- return f"string[{self.storage}]"
-
- def __str__(self):
- return self.name
-
def __from_arrow__(
self, array: pyarrow.Array | pyarrow.ChunkedArray
) -> BaseStringArray:
diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index eb5d1ccc5ed84..9762b779477e4 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -1,7 +1,6 @@
"""
Extend pandas with custom array types.
"""
-
from __future__ import annotations
from typing import (
@@ -14,6 +13,7 @@
import numpy as np
+from pandas._libs import missing as libmissing
from pandas._libs.hashtable import object_hash
from pandas._typing import (
DtypeObj,
@@ -391,6 +391,32 @@ def _can_hold_na(self) -> bool:
return True
+class StorageExtensionDtype(ExtensionDtype):
+ """ExtensionDtype that may be backed by more than one implementation."""
+
+ name: str
+ na_value = libmissing.NA
+ _metadata = ("storage",)
+
+ def __init__(self, storage=None) -> None:
+ self.storage = storage
+
+ def __repr__(self):
+ return f"{self.name}[{self.storage}]"
+
+ def __str__(self):
+ return self.name
+
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, self.type) and other == self.name:
+ return True
+ return super().__eq__(other)
+
+ def __hash__(self) -> int:
+ # custom __eq__ so have to override __hash__
+ return super().__hash__()
+
+
def register_extension_dtype(cls: type_t[ExtensionDtypeT]) -> type_t[ExtensionDtypeT]:
"""
Register an ExtensionType with pandas as class decorator.
| - [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).
Working towards eventually having `int[pyarrow]` for example, generalizing some of the storage concepts of `StringDtype` into `StorageExtensionDtype`
| https://api.github.com/repos/pandas-dev/pandas/pulls/46537 | 2022-03-27T23:42:24Z | 2022-03-28T19:38:35Z | 2022-03-28T19:38:35Z | 2022-05-25T18:19:38Z |
CI: xfail geopandas downstream test on Windows due to fiona install | diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index c1e7a8ae883ae..83b476fefea46 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -8,6 +8,7 @@
import numpy as np
import pytest
+from pandas.compat import is_platform_windows
import pandas.util._test_decorators as td
import pandas as pd
@@ -225,6 +226,13 @@ def test_pandas_datareader():
# importing from pandas, Cython import warning
@pytest.mark.filterwarnings("ignore:can't resolve:ImportWarning")
+@pytest.mark.xfail(
+ is_platform_windows(),
+ raises=ImportError,
+ reason="ImportError: the 'read_file' function requires the 'fiona' package, "
+ "but it is not installed or does not import correctly",
+ strict=False,
+)
def test_geopandas():
geopandas = import_module("geopandas")
| - [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).
Similar to https://github.com/pandas-dev/pandas/pull/46296 but now happening on Windows
```
def _check_fiona(func):
if fiona is None:
> raise ImportError(
f"the {func} requires the 'fiona' package, but it is not installed or does "
f"not import correctly.\nImporting fiona resulted in: {fiona_import_error}"
)
E ImportError: the 'read_file' function requires the 'fiona' package, but it is not installed or does not import correctly.
E Importing fiona resulted in: DLL load failed while importing ogrext: The specified procedure could not be found.
```
cc @jorisvandenbossche can this downstream test be changed to not go through fiona?
| https://api.github.com/repos/pandas-dev/pandas/pulls/46536 | 2022-03-27T22:57:08Z | 2022-03-28T12:37:11Z | 2022-03-28T12:37:11Z | 2022-04-06T13:04:20Z |
TYP: Many typing constructs are invariant | diff --git a/pandas/_typing.py b/pandas/_typing.py
index e3b3a4774f558..abf1315f3607a 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -74,6 +74,15 @@
npt: Any = None
+# Functions that take Dict/Mapping/List/Sequence/Callable as arguments can be
+# tricky to type:
+# - keys of Dict and Mapping cannot be sub-classes (Mapping allows them for values)
+# - elements of List cannot be sub-classes (Sequence does)
+# - input arguments of Callable cannot be sub-classes
+# If you want to allow any type and it's sub-classes in the above cases, you can
+# use TypeVar("AllowsSubclasses", bound=class); List[AllowsSubclasses]
+HashableT = TypeVar("HashableT", bound=Hashable)
+
# array-like
ArrayLike = Union["ExtensionArray", np.ndarray]
@@ -127,19 +136,19 @@
Dtype = Union["ExtensionDtype", NpDtype]
AstypeArg = Union["ExtensionDtype", "npt.DTypeLike"]
# DtypeArg specifies all allowable dtypes in a functions its dtype argument
-DtypeArg = Union[Dtype, Dict[Hashable, Dtype]]
+DtypeArg = Union[Dtype, Dict[HashableT, Dtype]]
DtypeObj = Union[np.dtype, "ExtensionDtype"]
# converters
-ConvertersArg = Dict[Hashable, Callable[[Dtype], Dtype]]
+ConvertersArg = Dict[HashableT, Callable[[Dtype], Dtype]]
# parse_dates
ParseDatesArg = Union[
- bool, List[Hashable], List[List[Hashable]], Dict[Hashable, List[Hashable]]
+ bool, List[HashableT], List[List[HashableT]], Dict[HashableT, List[Hashable]]
]
# For functions like rename that convert one label to another
-Renamer = Union[Mapping[Hashable, Any], Callable[[Hashable], Hashable]]
+Renamer = Union[Mapping[HashableT, Any], Callable[[HashableT], Hashable]]
# to maintain type information across generic functions and parametrization
T = TypeVar("T")
@@ -156,7 +165,7 @@
# types of `func` kwarg for DataFrame.aggregate and Series.aggregate
AggFuncTypeBase = Union[Callable, str]
-AggFuncTypeDict = Dict[Hashable, Union[AggFuncTypeBase, List[AggFuncTypeBase]]]
+AggFuncTypeDict = Dict[HashableT, Union[AggFuncTypeBase, List[AggFuncTypeBase]]]
AggFuncType = Union[
AggFuncTypeBase,
List[AggFuncTypeBase],
@@ -260,10 +269,10 @@ def closed(self) -> bool:
FormattersType = Union[
List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable]
]
-ColspaceType = Mapping[Hashable, Union[str, int]]
+ColspaceType = Mapping[HashableT, Union[str, int]]
FloatFormatType = Union[str, Callable, "EngFormatter"]
ColspaceArgType = Union[
- str, int, Sequence[Union[str, int]], Mapping[Hashable, Union[str, int]]
+ str, int, Sequence[Union[str, int]], Mapping[HashableT, Union[str, int]]
]
# Arguments for fillna()
| Indexes and columns can be of any hashable type: we often have functions accepting a list/dict/callables of hashable types.
Unfortunately, List/Dict/Mapping/Callable are all invariant in their (first) argument, which leads to unintuitive behavior:
```py
from typing import Hashable
def test(x: list[Hashable]) -> None:
...
x1: list[str] = ["a"] # str is Hashable
test(x1) # but this still errors
x2: list[Hashable] = ["a"]
test(x2) # works
```
One (honestly not well-promotet) use case of TypeVars is to allow sub-classes in these cases:
```py
from typing import Hashable, TypeVar
HashableT = TypeVar("HashableT", bound=Hashable)
def test(x: list[HashableT]) -> None:
...
x1: list[str] = ["a"] # str is Hashable
test(x1) # works :)
x2: list[Hashable] = ["a"]
test(x2) # still works
```
If we had type tests, we would have noticed this earlier - Thanks to @Dr-Irv for finding this!
xref https://github.com/pandas-dev/pandas/pull/46428#discussion_r835795663
It might be worth preventing Hashable being the first argument to the above typing containers by enforcing that in pandas-dev-flaker | https://api.github.com/repos/pandas-dev/pandas/pulls/46535 | 2022-03-27T21:40:06Z | 2022-03-29T23:02:20Z | null | 2022-04-01T01:36:12Z |
TST: Add test with large shape to check_below_min_count | diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py
index 3e07682d1cdd2..240b9dacce73a 100644
--- a/pandas/tests/test_nanops.py
+++ b/pandas/tests/test_nanops.py
@@ -1090,3 +1090,32 @@ def test_nanops_independent_of_mask_param(operation):
median_expected = operation(s)
median_result = operation(s, mask=mask)
assert median_expected == median_result
+
+
+@pytest.mark.parametrize("min_count", [-1, 0])
+def test_check_below_min_count__negative_or_zero_min_count(min_count):
+ # GH35227
+ result = nanops.check_below_min_count((21, 37), None, min_count)
+ expected_result = False
+ assert result == expected_result
+
+
+@pytest.mark.parametrize(
+ "mask", [None, np.array([False, False, True]), np.array([True] + 9 * [False])]
+)
+@pytest.mark.parametrize("min_count, expected_result", [(1, False), (101, True)])
+def test_check_below_min_count__positive_min_count(mask, min_count, expected_result):
+ # GH35227
+ shape = (10, 10)
+ result = nanops.check_below_min_count(shape, mask, min_count)
+ assert result == expected_result
+
+
+@td.skip_if_windows
+@td.skip_if_32bit
+@pytest.mark.parametrize("min_count, expected_result", [(1, False), (2812191852, True)])
+def test_check_below_min_count__large_shape(min_count, expected_result):
+ # GH35227 large shape used to show that the issue is fixed
+ shape = (2244367, 1253)
+ result = nanops.check_below_min_count(shape, mask=None, min_count=min_count)
+ assert result == expected_result
| The function in question didn't have any tests in the first place so I thought that I will add them and simply use the problematic tuple for `shape` argument.
- [x] closes #35227
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
| https://api.github.com/repos/pandas-dev/pandas/pulls/46534 | 2022-03-27T20:00:34Z | 2022-04-05T23:34:48Z | 2022-04-05T23:34:48Z | 2022-04-07T19:20:09Z |
change default value (for index) of func named to_csv | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 98e0ab43f2a09..517650f138cf3 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3401,7 +3401,7 @@ def to_csv(
float_format: str | None = None,
columns: Sequence[Hashable] | None = None,
header: bool_t | list[str] = True,
- index: bool_t = True,
+ index: bool_t = False,
index_label: IndexLabel | None = None,
mode: str = "w",
encoding: str | None = 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 an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
# Objective
We find the extra index output annoying, and to remedy that.
# Changes
```python
...
def to_csv(
self,
path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None,
sep: str = ",",
na_rep: str = "",
float_format: str | None = None,
columns: Sequence[Hashable] | None = None,
header: bool_t | list[str] = True,
# index: bool_t = True,
index: bool_t = False, # My Suggestion
index_label: IndexLabel | None = None,
mode: str = "w",
encoding: str | None = None,
compression: CompressionOptions = "infer",
quoting: int | None = None,
quotechar: str = '"',
lineterminator: str | None = None,
chunksize: int | None = None,
date_format: str | None = None,
doublequote: bool_t = True,
escapechar: str | None = None,
decimal: str = ".",
errors: str = "strict",
storage_options: StorageOptions = None,
) -> str | None:
...
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/46531 | 2022-03-27T18:40:54Z | 2022-03-27T21:46:27Z | null | 2022-03-28T09:01:46Z |
Revert "TYP: Many typing constructs are invariant" | diff --git a/pandas/_typing.py b/pandas/_typing.py
index 2b38b25d6347d..e3b3a4774f558 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -74,14 +74,6 @@
npt: Any = None
-# Functions that take Dict/Mapping/List/Sequence/Callable can be tricky to type:
-# - keys of Dict and Mapping do not accept sub-classes
-# - items of List and Sequence do not accept sub-classes
-# - input argument to Callable cannot be sub-classes
-# If you want to allow any type and it's sub-classes in the above cases, you can
-# use TypeVar("AllowsSubclasses", bound=class)
-HashableT = TypeVar("HashableT", bound=Hashable)
-
# array-like
ArrayLike = Union["ExtensionArray", np.ndarray]
@@ -113,7 +105,7 @@
NDFrameT = TypeVar("NDFrameT", bound="NDFrame")
Axis = Union[str, int]
-IndexLabel = Union[Hashable, Sequence[HashableT]]
+IndexLabel = Union[Hashable, Sequence[Hashable]]
Level = Union[Hashable, int]
Shape = Tuple[int, ...]
Suffixes = Tuple[Optional[str], Optional[str]]
@@ -135,19 +127,19 @@
Dtype = Union["ExtensionDtype", NpDtype]
AstypeArg = Union["ExtensionDtype", "npt.DTypeLike"]
# DtypeArg specifies all allowable dtypes in a functions its dtype argument
-DtypeArg = Union[Dtype, Dict[HashableT, Dtype]]
+DtypeArg = Union[Dtype, Dict[Hashable, Dtype]]
DtypeObj = Union[np.dtype, "ExtensionDtype"]
# converters
-ConvertersArg = Dict[HashableT, Callable[[Dtype], Dtype]]
+ConvertersArg = Dict[Hashable, Callable[[Dtype], Dtype]]
# parse_dates
ParseDatesArg = Union[
- bool, List[HashableT], List[List[HashableT]], Dict[HashableT, List[Hashable]]
+ bool, List[Hashable], List[List[Hashable]], Dict[Hashable, List[Hashable]]
]
# For functions like rename that convert one label to another
-Renamer = Union[Mapping[HashableT, Any], Callable[[HashableT], Hashable]]
+Renamer = Union[Mapping[Hashable, Any], Callable[[Hashable], Hashable]]
# to maintain type information across generic functions and parametrization
T = TypeVar("T")
@@ -164,7 +156,7 @@
# types of `func` kwarg for DataFrame.aggregate and Series.aggregate
AggFuncTypeBase = Union[Callable, str]
-AggFuncTypeDict = Dict[HashableT, Union[AggFuncTypeBase, List[AggFuncTypeBase]]]
+AggFuncTypeDict = Dict[Hashable, Union[AggFuncTypeBase, List[AggFuncTypeBase]]]
AggFuncType = Union[
AggFuncTypeBase,
List[AggFuncTypeBase],
@@ -268,10 +260,10 @@ def closed(self) -> bool:
FormattersType = Union[
List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable]
]
-ColspaceType = Mapping[HashableT, Union[str, int]]
+ColspaceType = Mapping[Hashable, Union[str, int]]
FloatFormatType = Union[str, Callable, "EngFormatter"]
ColspaceArgType = Union[
- str, int, Sequence[Union[str, int]], Mapping[HashableT, Union[str, int]]
+ str, int, Sequence[Union[str, int]], Mapping[Hashable, Union[str, int]]
]
# Arguments for fillna()
| I accidentally pushed to pandas instead of my fork :(
Is it possible in github to disallow direct pushes to the repository (only allow PRs)?
edit: It seems that this is possible https://stackoverflow.com/a/57685576 | https://api.github.com/repos/pandas-dev/pandas/pulls/46530 | 2022-03-27T18:26:03Z | 2022-03-27T20:12:38Z | 2022-03-27T20:12:38Z | 2022-04-02T01:15:07Z |
STYLE: fix PDF026 issues | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index aeb49c2b1a545..0a2f3f8f2506d 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -50,7 +50,7 @@ repos:
- flake8==4.0.1
- flake8-comprehensions==3.7.0
- flake8-bugbear==21.3.2
- - pandas-dev-flaker==0.4.0
+ - pandas-dev-flaker==0.5.0
- repo: https://github.com/PyCQA/isort
rev: 5.10.1
hooks:
diff --git a/environment.yml b/environment.yml
index a424100eda21a..187f666938aeb 100644
--- a/environment.yml
+++ b/environment.yml
@@ -33,7 +33,7 @@ dependencies:
- gitpython # obtain contributors from git for whatsnew
- gitdb
- numpydoc
- - pandas-dev-flaker=0.4.0
+ - pandas-dev-flaker=0.5.0
- pydata-sphinx-theme
- pytest-cython
- sphinx
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 0013ddf73cddc..caa08c67cbfab 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1555,14 +1555,10 @@ def __matmul__(self, other: Series) -> Series:
...
@overload
- def __matmul__(
- self, other: AnyArrayLike | DataFrame | Series
- ) -> DataFrame | Series:
+ def __matmul__(self, other: AnyArrayLike | DataFrame) -> DataFrame | Series:
...
- def __matmul__(
- self, other: AnyArrayLike | DataFrame | Series
- ) -> DataFrame | Series:
+ def __matmul__(self, other: AnyArrayLike | DataFrame) -> DataFrame | Series:
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 2746b91986a3c..3ccedcbad1782 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -19,7 +19,7 @@ pyupgrade
gitpython
gitdb
numpydoc
-pandas-dev-flaker==0.4.0
+pandas-dev-flaker==0.5.0
pydata-sphinx-theme
pytest-cython
sphinx
| - [x] closes #46528
- [x] closes #42359
- [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 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/46529 | 2022-03-27T16:13:46Z | 2022-03-29T09:27:29Z | 2022-03-29T09:27:28Z | 2022-03-29T16:21:27Z |
REF: re-use tz_convert_from_utc_single in _localize_tso | diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py
index 11de4e60f202d..4c74959fee60d 100644
--- a/pandas/_libs/tslibs/__init__.py
+++ b/pandas/_libs/tslibs/__init__.py
@@ -55,7 +55,9 @@
)
from pandas._libs.tslibs.timestamps import Timestamp
from pandas._libs.tslibs.timezones import tz_compare
-from pandas._libs.tslibs.tzconversion import tz_convert_from_utc_single
+from pandas._libs.tslibs.tzconversion import (
+ py_tz_convert_from_utc_single as tz_convert_from_utc_single,
+)
from pandas._libs.tslibs.vectorized import (
dt64arr_to_periodarr,
get_resolution,
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index f51f25c2065f2..e4b0c527a4cac 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -72,8 +72,9 @@ from pandas._libs.tslibs.nattype cimport (
)
from pandas._libs.tslibs.tzconversion cimport (
bisect_right_i8,
- infer_datetuil_fold,
+ infer_dateutil_fold,
localize_tzinfo_api,
+ tz_convert_from_utc_single,
tz_localize_to_utc_single,
)
@@ -531,7 +532,7 @@ cdef _TSObject _create_tsobject_tz_using_offset(npy_datetimestruct dts,
if typ == 'dateutil':
tdata = <int64_t*>cnp.PyArray_DATA(trans)
pos = bisect_right_i8(tdata, obj.value, trans.shape[0]) - 1
- obj.fold = infer_datetuil_fold(obj.value, trans, deltas, pos)
+ obj.fold = infer_dateutil_fold(obj.value, trans, deltas, pos)
# Keep the converter same as PyDateTime's
dt = datetime(obj.dts.year, obj.dts.month, obj.dts.day,
@@ -683,7 +684,7 @@ cdef inline void _localize_tso(_TSObject obj, tzinfo tz):
int64_t[::1] deltas
int64_t local_val
int64_t* tdata
- Py_ssize_t pos, ntrans
+ Py_ssize_t pos, ntrans, outpos = -1
str typ
assert obj.tzinfo is None
@@ -692,35 +693,12 @@ cdef inline void _localize_tso(_TSObject obj, tzinfo tz):
pass
elif obj.value == NPY_NAT:
pass
- elif is_tzlocal(tz):
- local_val = obj.value + localize_tzinfo_api(obj.value, tz, &obj.fold)
- dt64_to_dtstruct(local_val, &obj.dts)
else:
- # Adjust datetime64 timestamp, recompute datetimestruct
- trans, deltas, typ = get_dst_info(tz)
- ntrans = trans.shape[0]
-
- if typ == "pytz":
- # i.e. treat_tz_as_pytz(tz)
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
- pos = bisect_right_i8(tdata, obj.value, ntrans) - 1
- local_val = obj.value + deltas[pos]
-
- # find right representation of dst etc in pytz timezone
- tz = tz._tzinfos[tz._transition_info[pos]]
- elif typ == "dateutil":
- # i.e. treat_tz_as_dateutil(tz)
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
- pos = bisect_right_i8(tdata, obj.value, ntrans) - 1
- local_val = obj.value + deltas[pos]
+ local_val = tz_convert_from_utc_single(obj.value, tz, &obj.fold, &outpos)
- # dateutil supports fold, so we infer fold from value
- obj.fold = infer_datetuil_fold(obj.value, trans, deltas, pos)
- else:
- # All other cases have len(deltas) == 1. As of 2018-07-17
- # (and 2022-03-07), all test cases that get here have
- # is_fixed_offset(tz).
- local_val = obj.value + deltas[0]
+ if outpos != -1:
+ # infer we went through a pytz path
+ tz = tz._tzinfos[tz._transition_info[outpos]]
dt64_to_dtstruct(local_val, &obj.dts)
diff --git a/pandas/_libs/tslibs/tzconversion.pxd b/pandas/_libs/tslibs/tzconversion.pxd
index 74aab9f297379..ce7541fe1e74e 100644
--- a/pandas/_libs/tslibs/tzconversion.pxd
+++ b/pandas/_libs/tslibs/tzconversion.pxd
@@ -8,14 +8,16 @@ from numpy cimport (
cdef int64_t localize_tzinfo_api(
int64_t utc_val, tzinfo tz, bint* fold=*
) except? -1
-cpdef int64_t tz_convert_from_utc_single(int64_t val, tzinfo tz)
+cdef int64_t tz_convert_from_utc_single(
+ int64_t utc_val, tzinfo tz, bint* fold=?, Py_ssize_t* outpos=?
+) except? -1
cdef int64_t tz_localize_to_utc_single(
int64_t val, tzinfo tz, object ambiguous=*, object nonexistent=*
) except? -1
cdef Py_ssize_t bisect_right_i8(int64_t *data, int64_t val, Py_ssize_t n)
-cdef bint infer_datetuil_fold(
+cdef bint infer_dateutil_fold(
int64_t value,
const int64_t[::1] trans,
const int64_t[::1] deltas,
diff --git a/pandas/_libs/tslibs/tzconversion.pyi b/pandas/_libs/tslibs/tzconversion.pyi
index e1a0263cf59ef..5e513eefdca15 100644
--- a/pandas/_libs/tslibs/tzconversion.pyi
+++ b/pandas/_libs/tslibs/tzconversion.pyi
@@ -12,7 +12,9 @@ def tz_convert_from_utc(
vals: npt.NDArray[np.int64], # const int64_t[:]
tz: tzinfo,
) -> npt.NDArray[np.int64]: ...
-def tz_convert_from_utc_single(val: np.int64, tz: tzinfo) -> np.int64: ...
+
+# py_tz_convert_from_utc_single exposed for testing
+def py_tz_convert_from_utc_single(val: np.int64, tz: tzinfo) -> np.int64: ...
def tz_localize_to_utc(
vals: npt.NDArray[np.int64],
tz: tzinfo | None,
diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx
index a63a27b8194de..afcfe94a695bb 100644
--- a/pandas/_libs/tslibs/tzconversion.pyx
+++ b/pandas/_libs/tslibs/tzconversion.pyx
@@ -444,7 +444,18 @@ cdef int64_t localize_tzinfo_api(
return _tz_localize_using_tzinfo_api(utc_val, tz, to_utc=False, fold=fold)
-cpdef int64_t tz_convert_from_utc_single(int64_t utc_val, tzinfo tz):
+def py_tz_convert_from_utc_single(int64_t utc_val, tzinfo tz):
+ # The 'bint* fold=NULL' in tz_convert_from_utc_single means we cannot
+ # make it cdef, so this is version exposed for testing from python.
+ return tz_convert_from_utc_single(utc_val, tz)
+
+
+cdef int64_t tz_convert_from_utc_single(
+ int64_t utc_val,
+ tzinfo tz,
+ bint* fold=NULL,
+ Py_ssize_t* outpos=NULL,
+) except? -1:
"""
Convert the val (in i8) from UTC to tz
@@ -454,6 +465,8 @@ cpdef int64_t tz_convert_from_utc_single(int64_t utc_val, tzinfo tz):
----------
utc_val : int64
tz : tzinfo
+ fold : bint*, default NULL
+ outpos : Py_ssize_t*, default NULL
Returns
-------
@@ -473,15 +486,31 @@ cpdef int64_t tz_convert_from_utc_single(int64_t utc_val, tzinfo tz):
return utc_val
elif is_tzlocal(tz):
return utc_val + _tz_localize_using_tzinfo_api(utc_val, tz, to_utc=False)
- elif is_fixed_offset(tz):
- _, deltas, _ = get_dst_info(tz)
- delta = deltas[0]
- return utc_val + delta
else:
- trans, deltas, _ = get_dst_info(tz)
+ trans, deltas, typ = get_dst_info(tz)
tdata = <int64_t*>cnp.PyArray_DATA(trans)
- pos = bisect_right_i8(tdata, utc_val, trans.shape[0]) - 1
- return utc_val + deltas[pos]
+
+ if typ == "dateutil":
+ pos = bisect_right_i8(tdata, utc_val, trans.shape[0]) - 1
+
+ if fold is not NULL:
+ fold[0] = infer_dateutil_fold(utc_val, trans, deltas, pos)
+ return utc_val + deltas[pos]
+
+ elif typ == "pytz":
+ pos = bisect_right_i8(tdata, utc_val, trans.shape[0]) - 1
+
+ # We need to get 'pos' back to the caller so it can pick the
+ # correct "standardized" tzinfo objecg.
+ if outpos is not NULL:
+ outpos[0] = pos
+ return utc_val + deltas[pos]
+
+ else:
+ # All other cases have len(deltas) == 1. As of 2018-07-17
+ # (and 2022-03-07), all test cases that get here have
+ # is_fixed_offset(tz).
+ return utc_val + deltas[0]
def tz_convert_from_utc(const int64_t[:] vals, tzinfo tz):
@@ -635,7 +664,7 @@ cdef int64_t _tz_localize_using_tzinfo_api(
# NB: relies on dateutil internals, subject to change.
-cdef bint infer_datetuil_fold(
+cdef bint infer_dateutil_fold(
int64_t value,
const int64_t[::1] trans,
const int64_t[::1] deltas,
diff --git a/pandas/tests/tslibs/test_conversion.py b/pandas/tests/tslibs/test_conversion.py
index d0864ae8e1b7b..a790b2617783f 100644
--- a/pandas/tests/tslibs/test_conversion.py
+++ b/pandas/tests/tslibs/test_conversion.py
@@ -21,7 +21,7 @@
def _compare_utc_to_local(tz_didx):
def f(x):
- return tzconversion.tz_convert_from_utc_single(x, tz_didx.tz)
+ return tzconversion.py_tz_convert_from_utc_single(x, tz_didx.tz)
result = tzconversion.tz_convert_from_utc(tz_didx.asi8, tz_didx.tz)
expected = np.vectorize(f)(tz_didx.asi8)
| Largely sits on top of #46516
The observation is that what _localize_tso is doing is similar to what tz_convert_from_utc_single is doing if we could just get a couple more pieces of information back from the latter call. Getting `fold` back is easy to do by passing via pointer (which we do elsewhere). Getting `new_tz` back is uglier but its the best we got. (im assuming that returning a tuple`(int64_t, bint, Py_ssize_t)` would incur a perf penalty but ive bothered the cython folks enough already recently)
May be able to get some extra de-duplication in _create_tsobject_tz_using_offset and/or ints_to_pydatetime. But I'm skittish perf-wise.
#46516 should definitely be merged. This I won't be offended if reviewers ask for %timeits out the wazoo.
At some point, someone with just the right amount of adderall drip should figure out the optimal way to check for `typ=="dateutil" etc. | https://api.github.com/repos/pandas-dev/pandas/pulls/46525 | 2022-03-27T04:02:05Z | 2022-03-29T22:41:10Z | 2022-03-29T22:41:10Z | 2022-03-29T22:55:19Z |
Add a new material in Community tutorials page | diff --git a/doc/source/getting_started/tutorials.rst b/doc/source/getting_started/tutorials.rst
index a4c555ac227e6..8febc3adb9666 100644
--- a/doc/source/getting_started/tutorials.rst
+++ b/doc/source/getting_started/tutorials.rst
@@ -75,6 +75,16 @@ Excel charts with pandas, vincent and xlsxwriter
* `Using Pandas and XlsxWriter to create Excel charts <https://pandas-xlsxwriter-charts.readthedocs.io/>`_
+Joyful pandas
+-------------
+
+A tutorial written in Chinese by Yuanhao Geng. It covers the basic operations
+for NumPy and pandas, 4 main data manipulation methods (including indexing, groupby, reshaping
+and concatenation) and 4 main data types (including missing data, string data, categorical
+data and time series data). At the end of each chapter, corresponding exercises are posted.
+All the datasets and related materials can be found in the GitHub repository
+`datawhalechina/joyful-pandas <https://github.com/datawhalechina/joyful-pandas>`_.
+
Video tutorials
---------------
| Currently, [Joyful pandas](https://github.com/datawhalechina/joyful-pandas) is one of the popular tutorials for pandas on GitHub, which ranks after guipsamora/pandas_exercises and Julia Evans' pandas cookbook by stars. This tutorial is based on pandas with
a newer version and includes most of the essential parts in pandas. The webpage for the tutorial follows pandas's sphinx template. I believe this can be helpful for the community. Thanks. | https://api.github.com/repos/pandas-dev/pandas/pulls/46523 | 2022-03-26T17:09:32Z | 2022-03-27T00:20:06Z | 2022-03-27T00:20:06Z | 2022-03-27T02:02:47Z |
ENH: consistency of input args for boundaries - Interval | diff --git a/asv_bench/benchmarks/reshape.py b/asv_bench/benchmarks/reshape.py
index 7046c8862b0d7..b42729476c818 100644
--- a/asv_bench/benchmarks/reshape.py
+++ b/asv_bench/benchmarks/reshape.py
@@ -268,7 +268,9 @@ def setup(self, bins):
self.datetime_series = pd.Series(
np.random.randint(N, size=N), dtype="datetime64[ns]"
)
- self.interval_bins = pd.IntervalIndex.from_breaks(np.linspace(0, N, bins))
+ self.interval_bins = pd.IntervalIndex.from_breaks(
+ np.linspace(0, N, bins), "right"
+ )
def time_cut_int(self, bins):
pd.cut(self.int_series, bins)
diff --git a/doc/redirects.csv b/doc/redirects.csv
index 9b8a5a73dedff..173e670e30f0e 100644
--- a/doc/redirects.csv
+++ b/doc/redirects.csv
@@ -741,11 +741,11 @@ generated/pandas.Index.values,../reference/api/pandas.Index.values
generated/pandas.Index.view,../reference/api/pandas.Index.view
generated/pandas.Index.where,../reference/api/pandas.Index.where
generated/pandas.infer_freq,../reference/api/pandas.infer_freq
-generated/pandas.Interval.closed,../reference/api/pandas.Interval.closed
+generated/pandas.Interval.inclusive,../reference/api/pandas.Interval.inclusive
generated/pandas.Interval.closed_left,../reference/api/pandas.Interval.closed_left
generated/pandas.Interval.closed_right,../reference/api/pandas.Interval.closed_right
generated/pandas.Interval,../reference/api/pandas.Interval
-generated/pandas.IntervalIndex.closed,../reference/api/pandas.IntervalIndex.closed
+generated/pandas.IntervalIndex.inclusive,../reference/api/pandas.IntervalIndex.inclusive
generated/pandas.IntervalIndex.contains,../reference/api/pandas.IntervalIndex.contains
generated/pandas.IntervalIndex.from_arrays,../reference/api/pandas.IntervalIndex.from_arrays
generated/pandas.IntervalIndex.from_breaks,../reference/api/pandas.IntervalIndex.from_breaks
diff --git a/doc/source/reference/arrays.rst b/doc/source/reference/arrays.rst
index 1b8e0fdb856b5..fed0d2c5f7827 100644
--- a/doc/source/reference/arrays.rst
+++ b/doc/source/reference/arrays.rst
@@ -303,7 +303,7 @@ Properties
.. autosummary::
:toctree: api/
- Interval.closed
+ Interval.inclusive
Interval.closed_left
Interval.closed_right
Interval.is_empty
@@ -340,7 +340,7 @@ A collection of intervals may be stored in an :class:`arrays.IntervalArray`.
arrays.IntervalArray.left
arrays.IntervalArray.right
- arrays.IntervalArray.closed
+ arrays.IntervalArray.inclusive
arrays.IntervalArray.mid
arrays.IntervalArray.length
arrays.IntervalArray.is_empty
diff --git a/doc/source/reference/indexing.rst b/doc/source/reference/indexing.rst
index ddfef14036ef3..89a9a0a92ef08 100644
--- a/doc/source/reference/indexing.rst
+++ b/doc/source/reference/indexing.rst
@@ -242,7 +242,7 @@ IntervalIndex components
IntervalIndex.left
IntervalIndex.right
IntervalIndex.mid
- IntervalIndex.closed
+ IntervalIndex.inclusive
IntervalIndex.length
IntervalIndex.values
IntervalIndex.is_empty
diff --git a/doc/source/user_guide/advanced.rst b/doc/source/user_guide/advanced.rst
index 3081c6f7c6a08..aaff76261b3ad 100644
--- a/doc/source/user_guide/advanced.rst
+++ b/doc/source/user_guide/advanced.rst
@@ -1020,7 +1020,7 @@ Trying to select an ``Interval`` that is not exactly contained in the ``Interval
In [7]: df.loc[pd.Interval(0.5, 2.5)]
---------------------------------------------------------------------------
- KeyError: Interval(0.5, 2.5, closed='right')
+ KeyError: Interval(0.5, 2.5, inclusive='right')
Selecting all ``Intervals`` that overlap a given ``Interval`` can be performed using the
:meth:`~IntervalIndex.overlaps` method to create a boolean indexer.
diff --git a/doc/source/whatsnew/v0.20.0.rst b/doc/source/whatsnew/v0.20.0.rst
index faf4b1ac44d5b..a23c977e94b65 100644
--- a/doc/source/whatsnew/v0.20.0.rst
+++ b/doc/source/whatsnew/v0.20.0.rst
@@ -448,7 +448,7 @@ Selecting via a specific interval:
.. ipython:: python
- df.loc[pd.Interval(1.5, 3.0)]
+ df.loc[pd.Interval(1.5, 3.0, "right")]
Selecting via a scalar value that is contained *in* the intervals.
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index e4dd6fa091d80..4f04d5a0ee69d 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -584,18 +584,18 @@ this would previously return ``True`` for any ``Interval`` overlapping an ``Inte
.. code-block:: python
- In [4]: pd.Interval(1, 2, closed='neither') in ii
+ In [4]: pd.Interval(1, 2, inclusive='neither') in ii
Out[4]: True
- In [5]: pd.Interval(-10, 10, closed='both') in ii
+ In [5]: pd.Interval(-10, 10, inclusive='both') in ii
Out[5]: True
*New behavior*:
.. ipython:: python
- pd.Interval(1, 2, closed='neither') in ii
- pd.Interval(-10, 10, closed='both') in ii
+ pd.Interval(1, 2, inclusive='neither') in ii
+ pd.Interval(-10, 10, inclusive='both') in ii
The :meth:`~IntervalIndex.get_loc` method now only returns locations for exact matches to ``Interval`` queries, as opposed to the previous behavior of
returning locations for overlapping matches. A ``KeyError`` will be raised if an exact match is not found.
@@ -619,7 +619,7 @@ returning locations for overlapping matches. A ``KeyError`` will be raised if a
In [7]: ii.get_loc(pd.Interval(2, 6))
---------------------------------------------------------------------------
- KeyError: Interval(2, 6, closed='right')
+ KeyError: Interval(2, 6, inclusive='right')
Likewise, :meth:`~IntervalIndex.get_indexer` and :meth:`~IntervalIndex.get_indexer_non_unique` will also only return locations for exact matches
to ``Interval`` queries, with ``-1`` denoting that an exact match was not found.
@@ -680,11 +680,11 @@ Similarly, a ``KeyError`` will be raised for non-exact matches instead of return
In [6]: s[pd.Interval(2, 3)]
---------------------------------------------------------------------------
- KeyError: Interval(2, 3, closed='right')
+ KeyError: Interval(2, 3, inclusive='right')
In [7]: s.loc[pd.Interval(2, 3)]
---------------------------------------------------------------------------
- KeyError: Interval(2, 3, closed='right')
+ KeyError: Interval(2, 3, inclusive='right')
The :meth:`~IntervalIndex.overlaps` method can be used to create a boolean indexer that replicates the
previous behavior of returning overlapping matches.
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index eb08034bb92eb..ac9f8b02c7acb 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -669,7 +669,12 @@ Other Deprecations
- Deprecated the methods :meth:`DataFrame.mad`, :meth:`Series.mad`, and the corresponding groupby methods (:issue:`11787`)
- Deprecated positional arguments to :meth:`Index.join` except for ``other``, use keyword-only arguments instead of positional arguments (:issue:`46518`)
- Deprecated indexing on a timezone-naive :class:`DatetimeIndex` using a string representing a timezone-aware datetime (:issue:`46903`, :issue:`36148`)
--
+- Deprecated the ``closed`` argument in :class:`Interval` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`)
+- Deprecated the ``closed`` argument in :class:`IntervalIndex` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`)
+- Deprecated the ``closed`` argument in :class:`IntervalDtype` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`)
+- Deprecated the ``closed`` argument in :class:`IntervalArray` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`)
+- Deprecated the ``closed`` argument in :class:`intervaltree` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`)
+- Deprecated the ``closed`` argument in :class:`ArrowInterval` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`)
.. ---------------------------------------------------------------------------
.. _whatsnew_150.performance:
diff --git a/pandas/_libs/interval.pyi b/pandas/_libs/interval.pyi
index 9b727b6278792..d177e597478d9 100644
--- a/pandas/_libs/interval.pyi
+++ b/pandas/_libs/interval.pyi
@@ -11,6 +11,7 @@ from typing import (
import numpy as np
import numpy.typing as npt
+from pandas._libs import lib
from pandas._typing import (
IntervalClosedType,
Timedelta,
@@ -54,19 +55,24 @@ class IntervalMixin:
def is_empty(self) -> bool: ...
def _check_closed_matches(self, other: IntervalMixin, name: str = ...) -> None: ...
+def _warning_interval(
+ inclusive, closed
+) -> tuple[IntervalClosedType, lib.NoDefault]: ...
+
class Interval(IntervalMixin, Generic[_OrderableT]):
@property
def left(self: Interval[_OrderableT]) -> _OrderableT: ...
@property
def right(self: Interval[_OrderableT]) -> _OrderableT: ...
@property
- def closed(self) -> IntervalClosedType: ...
+ def inclusive(self) -> IntervalClosedType: ...
mid: _MidDescriptor
length: _LengthDescriptor
def __init__(
self,
left: _OrderableT,
right: _OrderableT,
+ inclusive: IntervalClosedType = ...,
closed: IntervalClosedType = ...,
) -> None: ...
def __hash__(self) -> int: ...
@@ -157,7 +163,7 @@ class IntervalTree(IntervalMixin):
self,
left: np.ndarray,
right: np.ndarray,
- closed: IntervalClosedType = ...,
+ inclusive: IntervalClosedType = ...,
leaf_size: int = ...,
) -> None: ...
@property
diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx
index 44c50e64147f4..178836ff1548b 100644
--- a/pandas/_libs/interval.pyx
+++ b/pandas/_libs/interval.pyx
@@ -40,7 +40,9 @@ from numpy cimport (
cnp.import_array()
+import warnings
+from pandas._libs import lib
from pandas._libs cimport util
from pandas._libs.hashtable cimport Int64Vector
from pandas._libs.tslibs.timedeltas cimport _Timedelta
@@ -52,7 +54,7 @@ from pandas._libs.tslibs.util cimport (
is_timedelta64_object,
)
-VALID_CLOSED = frozenset(['left', 'right', 'both', 'neither'])
+VALID_CLOSED = frozenset(['both', 'neither', 'left', 'right'])
cdef class IntervalMixin:
@@ -69,7 +71,7 @@ cdef class IntervalMixin:
bool
True if the Interval is closed on the left-side.
"""
- return self.closed in ('left', 'both')
+ return self.inclusive in ('left', 'both')
@property
def closed_right(self):
@@ -83,7 +85,7 @@ cdef class IntervalMixin:
bool
True if the Interval is closed on the left-side.
"""
- return self.closed in ('right', 'both')
+ return self.inclusive in ('right', 'both')
@property
def open_left(self):
@@ -150,43 +152,43 @@ cdef class IntervalMixin:
--------
An :class:`Interval` that contains points is not empty:
- >>> pd.Interval(0, 1, closed='right').is_empty
+ >>> pd.Interval(0, 1, inclusive='right').is_empty
False
An ``Interval`` that does not contain any points is empty:
- >>> pd.Interval(0, 0, closed='right').is_empty
+ >>> pd.Interval(0, 0, inclusive='right').is_empty
True
- >>> pd.Interval(0, 0, closed='left').is_empty
+ >>> pd.Interval(0, 0, inclusive='left').is_empty
True
- >>> pd.Interval(0, 0, closed='neither').is_empty
+ >>> pd.Interval(0, 0, inclusive='neither').is_empty
True
An ``Interval`` that contains a single point is not empty:
- >>> pd.Interval(0, 0, closed='both').is_empty
+ >>> pd.Interval(0, 0, inclusive='both').is_empty
False
An :class:`~arrays.IntervalArray` or :class:`IntervalIndex` returns a
boolean ``ndarray`` positionally indicating if an ``Interval`` is
empty:
- >>> ivs = [pd.Interval(0, 0, closed='neither'),
- ... pd.Interval(1, 2, closed='neither')]
+ >>> ivs = [pd.Interval(0, 0, inclusive='neither'),
+ ... pd.Interval(1, 2, inclusive='neither')]
>>> pd.arrays.IntervalArray(ivs).is_empty
array([ True, False])
Missing values are not considered empty:
- >>> ivs = [pd.Interval(0, 0, closed='neither'), np.nan]
+ >>> ivs = [pd.Interval(0, 0, inclusive='neither'), np.nan]
>>> pd.IntervalIndex(ivs).is_empty
array([ True, False])
"""
- return (self.right == self.left) & (self.closed != 'both')
+ return (self.right == self.left) & (self.inclusive != 'both')
def _check_closed_matches(self, other, name='other'):
"""
- Check if the closed attribute of `other` matches.
+ Check if the inclusive attribute of `other` matches.
Note that 'left' and 'right' are considered different from 'both'.
@@ -201,16 +203,42 @@ cdef class IntervalMixin:
ValueError
When `other` is not closed exactly the same as self.
"""
- if self.closed != other.closed:
- raise ValueError(f"'{name}.closed' is {repr(other.closed)}, "
- f"expected {repr(self.closed)}.")
+ if self.inclusive != other.inclusive:
+ raise ValueError(f"'{name}.inclusive' is {repr(other.inclusive)}, "
+ f"expected {repr(self.inclusive)}.")
cdef bint _interval_like(other):
return (hasattr(other, 'left')
and hasattr(other, 'right')
- and hasattr(other, 'closed'))
+ and hasattr(other, 'inclusive'))
+def _warning_interval(inclusive: str | None = None, closed: None | lib.NoDefault = lib.no_default):
+ """
+ warning in interval class for variable inclusive and closed
+ """
+ if inclusive is not None and closed != lib.no_default:
+ raise ValueError(
+ "Deprecated argument `closed` cannot be passed "
+ "if argument `inclusive` is not None"
+ )
+ elif closed != lib.no_default:
+ warnings.warn(
+ "Argument `closed` is deprecated in favor of `inclusive`.",
+ FutureWarning,
+ stacklevel=2,
+ )
+ if closed is None:
+ inclusive = "both"
+ elif closed in ("both", "neither", "left", "right"):
+ inclusive = closed
+ else:
+ raise ValueError(
+ "Argument `closed` has to be either"
+ "'both', 'neither', 'left' or 'right'"
+ )
+
+ return inclusive, closed
cdef class Interval(IntervalMixin):
"""
@@ -226,6 +254,14 @@ cdef class Interval(IntervalMixin):
Whether the interval is closed on the left-side, right-side, both or
neither. See the Notes for more detailed explanation.
+ .. deprecated:: 1.5.0
+
+ inclusive : {'both', 'neither', 'left', 'right'}, default 'both'
+ Whether the interval is closed on the left-side, right-side, both or
+ neither. See the Notes for more detailed explanation.
+
+ .. versionadded:: 1.5.0
+
See Also
--------
IntervalIndex : An Index of Interval objects that are all closed on the
@@ -243,28 +279,28 @@ cdef class Interval(IntervalMixin):
A closed interval (in mathematics denoted by square brackets) contains
its endpoints, i.e. the closed interval ``[0, 5]`` is characterized by the
- conditions ``0 <= x <= 5``. This is what ``closed='both'`` stands for.
+ conditions ``0 <= x <= 5``. This is what ``inclusive='both'`` stands for.
An open interval (in mathematics denoted by parentheses) does not contain
its endpoints, i.e. the open interval ``(0, 5)`` is characterized by the
- conditions ``0 < x < 5``. This is what ``closed='neither'`` stands for.
+ conditions ``0 < x < 5``. This is what ``inclusive='neither'`` stands for.
Intervals can also be half-open or half-closed, i.e. ``[0, 5)`` is
- described by ``0 <= x < 5`` (``closed='left'``) and ``(0, 5]`` is
- described by ``0 < x <= 5`` (``closed='right'``).
+ described by ``0 <= x < 5`` (``inclusive='left'``) and ``(0, 5]`` is
+ described by ``0 < x <= 5`` (``inclusive='right'``).
Examples
--------
It is possible to build Intervals of different types, like numeric ones:
- >>> iv = pd.Interval(left=0, right=5)
+ >>> iv = pd.Interval(left=0, right=5, inclusive='right')
>>> iv
- Interval(0, 5, closed='right')
+ Interval(0, 5, inclusive='right')
You can check if an element belongs to it
>>> 2.5 in iv
True
- You can test the bounds (``closed='right'``, so ``0 < x <= 5``):
+ You can test the bounds (``inclusive='right'``, so ``0 < x <= 5``):
>>> 0 in iv
False
@@ -284,16 +320,16 @@ cdef class Interval(IntervalMixin):
>>> shifted_iv = iv + 3
>>> shifted_iv
- Interval(3, 8, closed='right')
+ Interval(3, 8, inclusive='right')
>>> extended_iv = iv * 10.0
>>> extended_iv
- Interval(0.0, 50.0, closed='right')
+ Interval(0.0, 50.0, inclusive='right')
To create a time interval you can use Timestamps as the bounds
>>> year_2017 = pd.Interval(pd.Timestamp('2017-01-01 00:00:00'),
... pd.Timestamp('2018-01-01 00:00:00'),
- ... closed='left')
+ ... inclusive='left')
>>> pd.Timestamp('2017-01-01 00:00') in year_2017
True
>>> year_2017.length
@@ -312,21 +348,26 @@ cdef class Interval(IntervalMixin):
Right bound for the interval.
"""
- cdef readonly str closed
+ cdef readonly str inclusive
"""
Whether the interval is closed on the left-side, right-side, both or
neither.
"""
- def __init__(self, left, right, str closed='right'):
+ def __init__(self, left, right, inclusive: str | None = None, closed: None | lib.NoDefault = lib.no_default):
# note: it is faster to just do these checks than to use a special
# constructor (__cinit__/__new__) to avoid them
self._validate_endpoint(left)
self._validate_endpoint(right)
- if closed not in VALID_CLOSED:
- raise ValueError(f"invalid option for 'closed': {closed}")
+ inclusive, closed = _warning_interval(inclusive, closed)
+
+ if inclusive is None:
+ inclusive = "both"
+
+ if inclusive not in VALID_CLOSED:
+ raise ValueError(f"invalid option for 'inclusive': {inclusive}")
if not left <= right:
raise ValueError("left side of interval must be <= right side")
if (isinstance(left, _Timestamp) and
@@ -336,7 +377,7 @@ cdef class Interval(IntervalMixin):
f"{repr(left.tzinfo)}' and {repr(right.tzinfo)}")
self.left = left
self.right = right
- self.closed = closed
+ self.inclusive = inclusive
def _validate_endpoint(self, endpoint):
# GH 23013
@@ -346,7 +387,7 @@ cdef class Interval(IntervalMixin):
"are allowed when constructing an Interval.")
def __hash__(self):
- return hash((self.left, self.right, self.closed))
+ return hash((self.left, self.right, self.inclusive))
def __contains__(self, key) -> bool:
if _interval_like(key):
@@ -356,8 +397,8 @@ cdef class Interval(IntervalMixin):
def __richcmp__(self, other, op: int):
if isinstance(other, Interval):
- self_tuple = (self.left, self.right, self.closed)
- other_tuple = (other.left, other.right, other.closed)
+ self_tuple = (self.left, self.right, self.inclusive)
+ other_tuple = (other.left, other.right, other.inclusive)
return PyObject_RichCompare(self_tuple, other_tuple, op)
elif util.is_array(other):
return np.array(
@@ -368,7 +409,7 @@ cdef class Interval(IntervalMixin):
return NotImplemented
def __reduce__(self):
- args = (self.left, self.right, self.closed)
+ args = (self.left, self.right, self.inclusive)
return (type(self), args)
def _repr_base(self):
@@ -386,7 +427,7 @@ cdef class Interval(IntervalMixin):
left, right = self._repr_base()
name = type(self).__name__
- repr_str = f'{name}({repr(left)}, {repr(right)}, closed={repr(self.closed)})'
+ repr_str = f'{name}({repr(left)}, {repr(right)}, inclusive={repr(self.inclusive)})'
return repr_str
def __str__(self) -> str:
@@ -402,7 +443,7 @@ cdef class Interval(IntervalMixin):
or PyDelta_Check(y)
or is_timedelta64_object(y)
):
- return Interval(self.left + y, self.right + y, closed=self.closed)
+ return Interval(self.left + y, self.right + y, inclusive=self.inclusive)
elif (
# __radd__ pattern
# TODO(cython3): remove this
@@ -413,7 +454,7 @@ cdef class Interval(IntervalMixin):
or is_timedelta64_object(self)
)
):
- return Interval(y.left + self, y.right + self, closed=y.closed)
+ return Interval(y.left + self, y.right + self, inclusive=y.inclusive)
return NotImplemented
def __radd__(self, other):
@@ -422,7 +463,7 @@ cdef class Interval(IntervalMixin):
or PyDelta_Check(other)
or is_timedelta64_object(other)
):
- return Interval(self.left + other, self.right + other, closed=self.closed)
+ return Interval(self.left + other, self.right + other, inclusive=self.inclusive)
return NotImplemented
def __sub__(self, y):
@@ -431,32 +472,33 @@ cdef class Interval(IntervalMixin):
or PyDelta_Check(y)
or is_timedelta64_object(y)
):
- return Interval(self.left - y, self.right - y, closed=self.closed)
+ return Interval(self.left - y, self.right - y, inclusive=self.inclusive)
return NotImplemented
def __mul__(self, y):
if isinstance(y, numbers.Number):
- return Interval(self.left * y, self.right * y, closed=self.closed)
+ return Interval(self.left * y, self.right * y, inclusive=self.inclusive)
elif isinstance(y, Interval) and isinstance(self, numbers.Number):
# __radd__ semantics
# TODO(cython3): remove this
- return Interval(y.left * self, y.right * self, closed=y.closed)
+ return Interval(y.left * self, y.right * self, inclusive=y.inclusive)
+
return NotImplemented
def __rmul__(self, other):
if isinstance(other, numbers.Number):
- return Interval(self.left * other, self.right * other, closed=self.closed)
+ return Interval(self.left * other, self.right * other, inclusive=self.inclusive)
return NotImplemented
def __truediv__(self, y):
if isinstance(y, numbers.Number):
- return Interval(self.left / y, self.right / y, closed=self.closed)
+ return Interval(self.left / y, self.right / y, inclusive=self.inclusive)
return NotImplemented
def __floordiv__(self, y):
if isinstance(y, numbers.Number):
return Interval(
- self.left // y, self.right // y, closed=self.closed)
+ self.left // y, self.right // y, inclusive=self.inclusive)
return NotImplemented
def overlaps(self, other):
@@ -494,14 +536,14 @@ cdef class Interval(IntervalMixin):
Intervals that share closed endpoints overlap:
- >>> i4 = pd.Interval(0, 1, closed='both')
- >>> i5 = pd.Interval(1, 2, closed='both')
+ >>> i4 = pd.Interval(0, 1, inclusive='both')
+ >>> i5 = pd.Interval(1, 2, inclusive='both')
>>> i4.overlaps(i5)
True
Intervals that only have an open endpoint in common do not overlap:
- >>> i6 = pd.Interval(1, 2, closed='neither')
+ >>> i6 = pd.Interval(1, 2, inclusive='neither')
>>> i4.overlaps(i6)
False
"""
@@ -537,10 +579,10 @@ def intervals_to_interval_bounds(ndarray intervals, bint validate_closed=True):
tuple of
left : ndarray
right : ndarray
- closed: str
+ inclusive: str
"""
cdef:
- object closed = None, interval
+ object inclusive = None, interval
Py_ssize_t i, n = len(intervals)
ndarray left, right
bint seen_closed = False
@@ -563,13 +605,13 @@ def intervals_to_interval_bounds(ndarray intervals, bint validate_closed=True):
right[i] = interval.right
if not seen_closed:
seen_closed = True
- closed = interval.closed
- elif closed != interval.closed:
- closed = None
+ inclusive = interval.inclusive
+ elif inclusive != interval.inclusive:
+ inclusive = None
if validate_closed:
raise ValueError("intervals must all be closed on the same side")
- return left, right, closed
+ return left, right, inclusive
include "intervaltree.pxi"
diff --git a/pandas/_libs/intervaltree.pxi.in b/pandas/_libs/intervaltree.pxi.in
index 547fcc0b8aa07..51db5f1e76c99 100644
--- a/pandas/_libs/intervaltree.pxi.in
+++ b/pandas/_libs/intervaltree.pxi.in
@@ -3,9 +3,13 @@ Template for intervaltree
WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in
"""
+import warnings
+from pandas._libs import lib
from pandas._libs.algos import is_monotonic
+from pandas._libs.interval import _warning_interval
+
ctypedef fused int_scalar_t:
int64_t
float64_t
@@ -34,11 +38,11 @@ cdef class IntervalTree(IntervalMixin):
ndarray left, right
IntervalNode root
object dtype
- str closed
+ str inclusive
object _is_overlapping, _left_sorter, _right_sorter
Py_ssize_t _na_count
- def __init__(self, left, right, closed='right', leaf_size=100):
+ def __init__(self, left, right, inclusive: str | None = None, closed: None | lib.NoDefault = lib.no_default, leaf_size=100):
"""
Parameters
----------
@@ -48,13 +52,27 @@ cdef class IntervalTree(IntervalMixin):
closed : {'left', 'right', 'both', 'neither'}, optional
Whether the intervals are closed on the left-side, right-side, both
or neither. Defaults to 'right'.
+
+ .. deprecated:: 1.5.0
+
+ inclusive : {"both", "neither", "left", "right"}, optional
+ Whether the intervals are closed on the left-side, right-side, both
+ or neither. Defaults to 'right'.
+
+ .. versionadded:: 1.5.0
+
leaf_size : int, optional
Parameter that controls when the tree switches from creating nodes
to brute-force search. Tune this parameter to optimize query
performance.
"""
- if closed not in ['left', 'right', 'both', 'neither']:
- raise ValueError("invalid option for 'closed': %s" % closed)
+ inclusive, closed = _warning_interval(inclusive, closed)
+
+ if inclusive is None:
+ inclusive = "both"
+
+ if inclusive not in ['left', 'right', 'both', 'neither']:
+ raise ValueError("invalid option for 'inclusive': %s" % inclusive)
left = np.asarray(left)
right = np.asarray(right)
@@ -64,7 +82,7 @@ cdef class IntervalTree(IntervalMixin):
indices = np.arange(len(left), dtype='int64')
- self.closed = closed
+ self.inclusive = inclusive
# GH 23352: ensure no nan in nodes
mask = ~np.isnan(self.left)
@@ -73,7 +91,7 @@ cdef class IntervalTree(IntervalMixin):
self.right = self.right[mask]
indices = indices[mask]
- node_cls = NODE_CLASSES[str(self.dtype), closed]
+ node_cls = NODE_CLASSES[str(self.dtype), inclusive]
self.root = node_cls(self.left, self.right, indices, leaf_size)
@property
@@ -102,7 +120,7 @@ cdef class IntervalTree(IntervalMixin):
return self._is_overlapping
# <= when both sides closed since endpoints can overlap
- op = le if self.closed == 'both' else lt
+ op = le if self.inclusive == 'both' else lt
# overlap if start of current interval < end of previous interval
# (current and previous in terms of sorted order by left/start side)
@@ -180,9 +198,9 @@ cdef class IntervalTree(IntervalMixin):
missing.to_array().astype('intp'))
def __repr__(self) -> str:
- return ('<IntervalTree[{dtype},{closed}]: '
+ return ('<IntervalTree[{dtype},{inclusive}]: '
'{n_elements} elements>'.format(
- dtype=self.dtype, closed=self.closed,
+ dtype=self.dtype, inclusive=self.inclusive,
n_elements=self.root.n_elements))
# compat with IndexEngine interface
@@ -251,7 +269,7 @@ cdef class IntervalNode:
nodes = []
for dtype in ['float64', 'int64', 'uint64']:
- for closed, cmp_left, cmp_right in [
+ for inclusive, cmp_left, cmp_right in [
('left', '<=', '<'),
('right', '<', '<='),
('both', '<=', '<='),
@@ -265,7 +283,7 @@ for dtype in ['float64', 'int64', 'uint64']:
elif dtype.startswith('float'):
fused_prefix = ''
nodes.append((dtype, dtype.title(),
- closed, closed.title(),
+ inclusive, inclusive.title(),
cmp_left,
cmp_right,
cmp_left_converse,
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 4e245d1bd8693..2136c410ef4a0 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -2142,7 +2142,7 @@ cpdef bint is_interval_array(ndarray values):
"""
cdef:
Py_ssize_t i, n = len(values)
- str closed = None
+ str inclusive = None
bint numeric = False
bint dt64 = False
bint td64 = False
@@ -2155,15 +2155,15 @@ cpdef bint is_interval_array(ndarray values):
val = values[i]
if is_interval(val):
- if closed is None:
- closed = val.closed
+ if inclusive is None:
+ inclusive = val.inclusive
numeric = (
util.is_float_object(val.left)
or util.is_integer_object(val.left)
)
td64 = is_timedelta(val.left)
dt64 = PyDateTime_Check(val.left)
- elif val.closed != closed:
+ elif val.inclusive != inclusive:
# mismatched closedness
return False
elif numeric:
@@ -2186,7 +2186,7 @@ cpdef bint is_interval_array(ndarray values):
else:
return False
- if closed is None:
+ if inclusive is None:
# we saw all-NAs, no actual Intervals
return False
return True
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index efbe9995525d7..d04dc76c01f7e 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -606,7 +606,7 @@ def assert_interval_array_equal(left, right, exact="equiv", obj="IntervalArray")
assert_equal(left._left, right._left, obj=f"{obj}.left", **kwargs)
assert_equal(left._right, right._right, obj=f"{obj}.left", **kwargs)
- assert_attr_equal("closed", left, right, obj=obj)
+ assert_attr_equal("inclusive", left, right, obj=obj)
def assert_period_array_equal(left, right, obj="PeriodArray"):
diff --git a/pandas/conftest.py b/pandas/conftest.py
index 73ced327ac4a9..dfe8c5f1778d3 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -606,7 +606,7 @@ def _create_mi_with_dt64tz_level():
"bool-object": tm.makeBoolIndex(10).astype(object),
"bool-dtype": Index(np.random.randn(10) < 0),
"categorical": tm.makeCategoricalIndex(100),
- "interval": tm.makeIntervalIndex(100),
+ "interval": tm.makeIntervalIndex(100, inclusive="right"),
"empty": Index([]),
"tuples": MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3])),
"mi-with-dt64tz-level": _create_mi_with_dt64tz_level(),
@@ -934,8 +934,14 @@ def rand_series_with_duplicate_datetimeindex():
# ----------------------------------------------------------------
@pytest.fixture(
params=[
- (Interval(left=0, right=5), IntervalDtype("int64", "right")),
- (Interval(left=0.1, right=0.5), IntervalDtype("float64", "right")),
+ (
+ Interval(left=0, right=5, inclusive="right"),
+ IntervalDtype("int64", inclusive="right"),
+ ),
+ (
+ Interval(left=0.1, right=0.5, inclusive="right"),
+ IntervalDtype("float64", inclusive="right"),
+ ),
(Period("2012-01", freq="M"), "period[M]"),
(Period("2012-02-01", freq="D"), "period[D]"),
(
diff --git a/pandas/core/arrays/arrow/_arrow_utils.py b/pandas/core/arrays/arrow/_arrow_utils.py
index ca7ec0ef2ebaf..e0f242e2ced5d 100644
--- a/pandas/core/arrays/arrow/_arrow_utils.py
+++ b/pandas/core/arrays/arrow/_arrow_utils.py
@@ -6,6 +6,8 @@
import numpy as np
import pyarrow
+from pandas._libs import lib
+from pandas._libs.interval import _warning_interval
from pandas.errors import PerformanceWarning
from pandas.util._exceptions import find_stack_level
@@ -103,11 +105,17 @@ def to_pandas_dtype(self):
class ArrowIntervalType(pyarrow.ExtensionType):
- def __init__(self, subtype, closed) -> None:
+ def __init__(
+ self,
+ subtype,
+ inclusive: str | None = None,
+ closed: None | lib.NoDefault = lib.no_default,
+ ) -> None:
# attributes need to be set first before calling
# super init (as that calls serialize)
- assert closed in VALID_CLOSED
- self._closed = closed
+ inclusive, closed = _warning_interval(inclusive, closed)
+ assert inclusive in VALID_CLOSED
+ self._closed = inclusive
if not isinstance(subtype, pyarrow.DataType):
subtype = pyarrow.type_for_alias(str(subtype))
self._subtype = subtype
@@ -120,37 +128,37 @@ def subtype(self):
return self._subtype
@property
- def closed(self):
+ def inclusive(self):
return self._closed
def __arrow_ext_serialize__(self):
- metadata = {"subtype": str(self.subtype), "closed": self.closed}
+ metadata = {"subtype": str(self.subtype), "inclusive": self.inclusive}
return json.dumps(metadata).encode()
@classmethod
def __arrow_ext_deserialize__(cls, storage_type, serialized):
metadata = json.loads(serialized.decode())
subtype = pyarrow.type_for_alias(metadata["subtype"])
- closed = metadata["closed"]
- return ArrowIntervalType(subtype, closed)
+ inclusive = metadata["inclusive"]
+ return ArrowIntervalType(subtype, inclusive)
def __eq__(self, other):
if isinstance(other, pyarrow.BaseExtensionType):
return (
type(self) == type(other)
and self.subtype == other.subtype
- and self.closed == other.closed
+ and self.inclusive == other.inclusive
)
else:
return NotImplemented
def __hash__(self):
- return hash((str(self), str(self.subtype), self.closed))
+ return hash((str(self), str(self.subtype), self.inclusive))
def to_pandas_dtype(self):
import pandas as pd
- return pd.IntervalDtype(self.subtype.to_pandas_dtype(), self.closed)
+ return pd.IntervalDtype(self.subtype.to_pandas_dtype(), self.inclusive)
# register the type with a dummy instance
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 4c81fe8b61a1f..eecf1dff4dd48 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -24,6 +24,7 @@
VALID_CLOSED,
Interval,
IntervalMixin,
+ _warning_interval,
intervals_to_interval_bounds,
)
from pandas._libs.missing import NA
@@ -122,7 +123,7 @@
data : array-like (1-dimensional)
Array-like containing Interval objects from which to build the
%(klass)s.
-closed : {'left', 'right', 'both', 'neither'}, default 'right'
+inclusive : {'left', 'right', 'both', 'neither'}, default 'right'
Whether the intervals are closed on the left-side, right-side, both or
neither.
dtype : dtype or None, default None
@@ -137,7 +138,7 @@
----------
left
right
-closed
+inclusive
mid
length
is_empty
@@ -189,7 +190,8 @@
A new ``IntervalArray`` can be constructed directly from an array-like of
``Interval`` objects:
- >>> pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)])
+ >>> pd.arrays.IntervalArray([pd.Interval(0, 1, "right"),
+ ... pd.Interval(1, 5, "right")])
<IntervalArray>
[(0, 1], (1, 5]]
Length: 2, dtype: interval[int64, right]
@@ -217,18 +219,20 @@ class IntervalArray(IntervalMixin, ExtensionArray):
def __new__(
cls: type[IntervalArrayT],
data,
- closed=None,
+ inclusive: str | None = None,
+ closed: None | lib.NoDefault = lib.no_default,
dtype: Dtype | None = None,
copy: bool = False,
verify_integrity: bool = True,
):
+ inclusive, closed = _warning_interval(inclusive, closed)
data = extract_array(data, extract_numpy=True)
if isinstance(data, cls):
left = data._left
right = data._right
- closed = closed or data.closed
+ inclusive = inclusive or data.inclusive
else:
# don't allow scalars
@@ -242,17 +246,17 @@ def __new__(
# might need to convert empty or purely na data
data = _maybe_convert_platform_interval(data)
left, right, infer_closed = intervals_to_interval_bounds(
- data, validate_closed=closed is None
+ data, validate_closed=inclusive is None
)
if left.dtype == object:
left = lib.maybe_convert_objects(left)
right = lib.maybe_convert_objects(right)
- closed = closed or infer_closed
+ inclusive = inclusive or infer_closed
return cls._simple_new(
left,
right,
- closed,
+ inclusive=inclusive,
copy=copy,
dtype=dtype,
verify_integrity=verify_integrity,
@@ -263,17 +267,21 @@ def _simple_new(
cls: type[IntervalArrayT],
left,
right,
- closed: IntervalClosedType | None = None,
+ inclusive=None,
+ closed: None | lib.NoDefault = lib.no_default,
copy: bool = False,
dtype: Dtype | None = None,
verify_integrity: bool = True,
) -> IntervalArrayT:
result = IntervalMixin.__new__(cls)
- if closed is None and isinstance(dtype, IntervalDtype):
- closed = dtype.closed
+ inclusive, closed = _warning_interval(inclusive, closed)
+
+ if inclusive is None and isinstance(dtype, IntervalDtype):
+ inclusive = dtype.inclusive
+
+ inclusive = inclusive or "both"
- closed = closed or "right"
left = ensure_index(left, copy=copy)
right = ensure_index(right, copy=copy)
@@ -288,12 +296,11 @@ def _simple_new(
else:
msg = f"dtype must be an IntervalDtype, got {dtype}"
raise TypeError(msg)
-
- if dtype.closed is None:
+ if dtype.inclusive is None:
# possibly loading an old pickle
- dtype = IntervalDtype(dtype.subtype, closed)
- elif closed != dtype.closed:
- raise ValueError("closed keyword does not match dtype.closed")
+ dtype = IntervalDtype(dtype.subtype, inclusive)
+ elif inclusive != dtype.inclusive:
+ raise ValueError("inclusive keyword does not match dtype.inclusive")
# coerce dtypes to match if needed
if is_float_dtype(left) and is_integer_dtype(right):
@@ -336,7 +343,7 @@ def _simple_new(
# If these share data, then setitem could corrupt our IA
right = right.copy()
- dtype = IntervalDtype(left.dtype, closed=closed)
+ dtype = IntervalDtype(left.dtype, inclusive=inclusive)
result._dtype = dtype
result._left = left
@@ -364,7 +371,7 @@ def _from_factorized(
# a new IA from an (empty) object-dtype array, so turn it into the
# correct dtype.
values = values.astype(original.dtype.subtype)
- return cls(values, closed=original.closed)
+ return cls(values, inclusive=original.inclusive)
_interval_shared_docs["from_breaks"] = textwrap.dedent(
"""
@@ -374,7 +381,7 @@ def _from_factorized(
----------
breaks : array-like (1-dimensional)
Left and right bounds for each interval.
- closed : {'left', 'right', 'both', 'neither'}, default 'right'
+ inclusive : {'left', 'right', 'both', 'neither'}, default 'right'
Whether the intervals are closed on the left-side, right-side, both
or neither.
copy : bool, default False
@@ -405,7 +412,7 @@ def _from_factorized(
"""\
Examples
--------
- >>> pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3])
+ >>> pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3], "right")
<IntervalArray>
[(0, 1], (1, 2], (2, 3]]
Length: 3, dtype: interval[int64, right]
@@ -416,13 +423,15 @@ def _from_factorized(
def from_breaks(
cls: type[IntervalArrayT],
breaks,
- closed: IntervalClosedType | None = "right",
+ inclusive="both",
copy: bool = False,
dtype: Dtype | None = None,
) -> IntervalArrayT:
breaks = _maybe_convert_platform_interval(breaks)
- return cls.from_arrays(breaks[:-1], breaks[1:], closed, copy=copy, dtype=dtype)
+ return cls.from_arrays(
+ breaks[:-1], breaks[1:], inclusive, copy=copy, dtype=dtype
+ )
_interval_shared_docs["from_arrays"] = textwrap.dedent(
"""
@@ -434,7 +443,7 @@ def from_breaks(
Left bounds for each interval.
right : array-like (1-dimensional)
Right bounds for each interval.
- closed : {'left', 'right', 'both', 'neither'}, default 'right'
+ inclusive : {'left', 'right', 'both', 'neither'}, default 'right'
Whether the intervals are closed on the left-side, right-side, both
or neither.
copy : bool, default False
@@ -480,7 +489,7 @@ def from_breaks(
"klass": "IntervalArray",
"examples": textwrap.dedent(
"""\
- >>> pd.arrays.IntervalArray.from_arrays([0, 1, 2], [1, 2, 3])
+ >>> pd.arrays.IntervalArray.from_arrays([0, 1, 2], [1, 2, 3], inclusive="right")
<IntervalArray>
[(0, 1], (1, 2], (2, 3]]
Length: 3, dtype: interval[int64, right]
@@ -492,7 +501,7 @@ def from_arrays(
cls: type[IntervalArrayT],
left,
right,
- closed: IntervalClosedType | None = "right",
+ inclusive="both",
copy: bool = False,
dtype: Dtype | None = None,
) -> IntervalArrayT:
@@ -500,7 +509,12 @@ def from_arrays(
right = _maybe_convert_platform_interval(right)
return cls._simple_new(
- left, right, closed, copy=copy, dtype=dtype, verify_integrity=True
+ left,
+ right,
+ inclusive=inclusive,
+ copy=copy,
+ dtype=dtype,
+ verify_integrity=True,
)
_interval_shared_docs["from_tuples"] = textwrap.dedent(
@@ -511,7 +525,7 @@ def from_arrays(
----------
data : array-like (1-dimensional)
Array of tuples.
- closed : {'left', 'right', 'both', 'neither'}, default 'right'
+ inclusive : {'left', 'right', 'both', 'neither'}, default 'right'
Whether the intervals are closed on the left-side, right-side, both
or neither.
copy : bool, default False
@@ -544,7 +558,7 @@ def from_arrays(
"""\
Examples
--------
- >>> pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 2)])
+ >>> pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 2)], inclusive="right")
<IntervalArray>
[(0, 1], (1, 2]]
Length: 2, dtype: interval[int64, right]
@@ -555,7 +569,7 @@ def from_arrays(
def from_tuples(
cls: type[IntervalArrayT],
data,
- closed="right",
+ inclusive="both",
copy: bool = False,
dtype: Dtype | None = None,
) -> IntervalArrayT:
@@ -582,7 +596,7 @@ def from_tuples(
left.append(lhs)
right.append(rhs)
- return cls.from_arrays(left, right, closed, copy=False, dtype=dtype)
+ return cls.from_arrays(left, right, inclusive, copy=False, dtype=dtype)
def _validate(self):
"""
@@ -590,13 +604,13 @@ def _validate(self):
Checks that
- * closed is valid
+ * inclusive is valid
* left and right match lengths
* left and right have the same missing values
* left is always below right
"""
- if self.closed not in VALID_CLOSED:
- msg = f"invalid option for 'closed': {self.closed}"
+ if self.inclusive not in VALID_CLOSED:
+ msg = f"invalid option for 'inclusive': {self.inclusive}"
raise ValueError(msg)
if len(self._left) != len(self._right):
msg = "left and right must have the same length"
@@ -624,7 +638,9 @@ def _shallow_copy(self: IntervalArrayT, left, right) -> IntervalArrayT:
right : Index
Values to be used for the right-side of the intervals.
"""
- return self._simple_new(left, right, closed=self.closed, verify_integrity=False)
+ return self._simple_new(
+ left, right, inclusive=self.inclusive, verify_integrity=False
+ )
# ---------------------------------------------------------------------
# Descriptive
@@ -670,7 +686,7 @@ def __getitem__(
# scalar
if is_scalar(left) and isna(left):
return self._fill_value
- return Interval(left, right, self.closed)
+ return Interval(left, right, inclusive=self.inclusive)
if np.ndim(left) > 1:
# GH#30588 multi-dimensional indexer disallowed
raise ValueError("multi-dimensional indexing not allowed")
@@ -711,7 +727,7 @@ def _cmp_method(self, other, op):
# extract intervals if we have interval categories with matching closed
if is_interval_dtype(other_dtype):
- if self.closed != other.categories.closed:
+ if self.inclusive != other.categories.inclusive:
return invalid_comparison(self, other, op)
other = other.categories.take(
@@ -720,7 +736,7 @@ def _cmp_method(self, other, op):
# interval-like -> need same closed and matching endpoints
if is_interval_dtype(other_dtype):
- if self.closed != other.closed:
+ if self.inclusive != other.inclusive:
return invalid_comparison(self, other, op)
elif not isinstance(other, Interval):
other = type(self)(other)
@@ -936,7 +952,7 @@ def equals(self, other) -> bool:
return False
return bool(
- self.closed == other.closed
+ self.inclusive == other.inclusive
and self.left.equals(other.left)
and self.right.equals(other.right)
)
@@ -956,14 +972,14 @@ def _concat_same_type(
-------
IntervalArray
"""
- closed_set = {interval.closed for interval in to_concat}
- if len(closed_set) != 1:
+ inclusive_set = {interval.inclusive for interval in to_concat}
+ if len(inclusive_set) != 1:
raise ValueError("Intervals must all be closed on the same side.")
- closed = closed_set.pop()
+ inclusive = inclusive_set.pop()
left = np.concatenate([interval.left for interval in to_concat])
right = np.concatenate([interval.right for interval in to_concat])
- return cls._simple_new(left, right, closed=closed, copy=False)
+ return cls._simple_new(left, right, inclusive=inclusive, copy=False)
def copy(self: IntervalArrayT) -> IntervalArrayT:
"""
@@ -975,9 +991,9 @@ def copy(self: IntervalArrayT) -> IntervalArrayT:
"""
left = self._left.copy()
right = self._right.copy()
- closed = self.closed
+ inclusive = self.inclusive
# TODO: Could skip verify_integrity here.
- return type(self).from_arrays(left, right, closed=closed)
+ return type(self).from_arrays(left, right, inclusive=inclusive)
def isna(self) -> np.ndarray:
return isna(self._left)
@@ -999,7 +1015,7 @@ def shift(self, periods: int = 1, fill_value: object = None) -> IntervalArray:
from pandas import Index
fill_value = Index(self._left, copy=False)._na_value
- empty = IntervalArray.from_breaks([fill_value] * (empty_len + 1))
+ empty = IntervalArray.from_breaks([fill_value] * (empty_len + 1), "right")
else:
empty = self._from_sequence([fill_value] * empty_len)
@@ -1129,7 +1145,7 @@ def _validate_setitem_value(self, value):
value_left, value_right = value, value
elif isinstance(value, Interval):
- # scalar interval
+ # scalar
self._check_closed_matches(value, name="value")
value_left, value_right = value.left, value.right
self.left._validate_fill_value(value_left)
@@ -1257,7 +1273,7 @@ def mid(self) -> Index:
"""
Check elementwise if an Interval overlaps the values in the %(klass)s.
- Two intervals overlap if they share a common point, including closed
+ Two intervals overlap if they share a common point, including inclusive
endpoints. Intervals that only have an open endpoint in common do not
overlap.
@@ -1281,14 +1297,14 @@ def mid(self) -> Index:
>>> intervals.overlaps(pd.Interval(0.5, 1.5))
array([ True, True, False])
- Intervals that share closed endpoints overlap:
+ Intervals that share inclusive endpoints overlap:
- >>> intervals.overlaps(pd.Interval(1, 3, closed='left'))
+ >>> intervals.overlaps(pd.Interval(1, 3, inclusive='left'))
array([ True, True, True])
Intervals that only have an open endpoint in common do not overlap:
- >>> intervals.overlaps(pd.Interval(1, 2, closed='right'))
+ >>> intervals.overlaps(pd.Interval(1, 2, inclusive='right'))
array([False, True, False])
"""
)
@@ -1300,7 +1316,7 @@ def mid(self) -> Index:
"examples": textwrap.dedent(
"""\
>>> data = [(0, 1), (1, 3), (2, 4)]
- >>> intervals = pd.arrays.IntervalArray.from_tuples(data)
+ >>> intervals = pd.arrays.IntervalArray.from_tuples(data, "right")
>>> intervals
<IntervalArray>
[(0, 1], (1, 3], (2, 4]]
@@ -1328,12 +1344,12 @@ def overlaps(self, other):
# ---------------------------------------------------------------------
@property
- def closed(self) -> IntervalClosedType:
+ def inclusive(self) -> IntervalClosedType:
"""
Whether the intervals are closed on the left-side, right-side, both or
neither.
"""
- return self.dtype.closed
+ return self.dtype.inclusive
_interval_shared_docs["set_closed"] = textwrap.dedent(
"""
@@ -1342,7 +1358,7 @@ def closed(self) -> IntervalClosedType:
Parameters
----------
- closed : {'left', 'right', 'both', 'neither'}
+ inclusive : {'left', 'right', 'both', 'neither'}
Whether the intervals are closed on the left-side, right-side, both
or neither.
@@ -1362,7 +1378,7 @@ def closed(self) -> IntervalClosedType:
"""\
Examples
--------
- >>> index = pd.arrays.IntervalArray.from_breaks(range(4))
+ >>> index = pd.arrays.IntervalArray.from_breaks(range(4), "right")
>>> index
<IntervalArray>
[(0, 1], (1, 2], (2, 3]]
@@ -1375,13 +1391,18 @@ def closed(self) -> IntervalClosedType:
),
}
)
- def set_closed(self: IntervalArrayT, closed: IntervalClosedType) -> IntervalArrayT:
- if closed not in VALID_CLOSED:
- msg = f"invalid option for 'closed': {closed}"
+ def set_closed(
+ self: IntervalArrayT, inclusive: IntervalClosedType
+ ) -> IntervalArrayT:
+ if inclusive not in VALID_CLOSED:
+ msg = f"invalid option for 'inclusive': {inclusive}"
raise ValueError(msg)
return type(self)._simple_new(
- left=self._left, right=self._right, closed=closed, verify_integrity=False
+ left=self._left,
+ right=self._right,
+ inclusive=inclusive,
+ verify_integrity=False,
)
_interval_shared_docs[
@@ -1403,15 +1424,15 @@ def is_non_overlapping_monotonic(self) -> bool:
# or decreasing (e.g., [-1, 0), [-2, -1), [-3, -2), ...)
# we already require left <= right
- # strict inequality for closed == 'both'; equality implies overlapping
+ # strict inequality for inclusive == 'both'; equality implies overlapping
# at a point when both sides of intervals are included
- if self.closed == "both":
+ if self.inclusive == "both":
return bool(
(self._right[:-1] < self._left[1:]).all()
or (self._left[:-1] > self._right[1:]).all()
)
- # non-strict inequality when closed != 'both'; at least one side is
+ # non-strict inequality when inclusive != 'both'; at least one side is
# not included in the intervals, so equality does not imply overlapping
return bool(
(self._right[:-1] <= self._left[1:]).all()
@@ -1429,14 +1450,14 @@ def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
left = self._left
right = self._right
mask = self.isna()
- closed = self.closed
+ inclusive = self.inclusive
result = np.empty(len(left), dtype=object)
for i in range(len(left)):
if mask[i]:
result[i] = np.nan
else:
- result[i] = Interval(left[i], right[i], closed)
+ result[i] = Interval(left[i], right[i], inclusive=inclusive)
return result
def __arrow_array__(self, type=None):
@@ -1454,7 +1475,7 @@ def __arrow_array__(self, type=None):
f"Conversion to arrow with subtype '{self.dtype.subtype}' "
"is not supported"
) from err
- interval_type = ArrowIntervalType(subtype, self.closed)
+ interval_type = ArrowIntervalType(subtype, self.inclusive)
storage_array = pyarrow.StructArray.from_arrays(
[
pyarrow.array(self._left, type=subtype, from_pandas=True),
@@ -1477,12 +1498,13 @@ def __arrow_array__(self, type=None):
if type.equals(interval_type.storage_type):
return storage_array
elif isinstance(type, ArrowIntervalType):
- # ensure we have the same subtype and closed attributes
+ # ensure we have the same subtype and inclusive attributes
if not type.equals(interval_type):
raise TypeError(
"Not supported to convert IntervalArray to type with "
f"different 'subtype' ({self.dtype.subtype} vs {type.subtype}) "
- f"and 'closed' ({self.closed} vs {type.closed}) attributes"
+ f"and 'inclusive' ({self.inclusive} vs {type.inclusive}) "
+ f"attributes"
)
else:
raise TypeError(
@@ -1610,7 +1632,8 @@ def repeat(
"klass": "IntervalArray",
"examples": textwrap.dedent(
"""\
- >>> intervals = pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 3), (2, 4)])
+ >>> intervals = pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 3), (2, 4)]
+ ... , "right")
>>> intervals
<IntervalArray>
[(0, 1], (1, 3], (2, 4]]
@@ -1633,7 +1656,7 @@ def isin(self, values) -> np.ndarray:
values = extract_array(values, extract_numpy=True)
if is_interval_dtype(values.dtype):
- if self.closed != values.closed:
+ if self.inclusive != values.inclusive:
# not comparable -> no overlap
return np.zeros(self.shape, dtype=bool)
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 88a92ea1455d0..c6a4effac7a37 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -515,7 +515,7 @@ def ensure_dtype_can_hold_na(dtype: DtypeObj) -> DtypeObj:
elif isinstance(dtype, IntervalDtype):
# TODO(GH#45349): don't special-case IntervalDtype, allow
# overriding instead of returning object below.
- return IntervalDtype(np.float64, closed=dtype.closed)
+ return IntervalDtype(np.float64, inclusive=dtype.inclusive)
return _dtype_obj
elif dtype.kind == "b":
return _dtype_obj
@@ -834,7 +834,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> tuple[DtypeObj,
dtype = PeriodDtype(freq=val.freq)
elif lib.is_interval(val):
subtype = infer_dtype_from_scalar(val.left, pandas_dtype=True)[0]
- dtype = IntervalDtype(subtype=subtype, closed=val.closed)
+ dtype = IntervalDtype(subtype=subtype, inclusive=val.inclusive)
return dtype, val
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 6776064342db0..a192337daf59b 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -479,7 +479,7 @@ def is_interval_dtype(arr_or_dtype) -> bool:
>>> is_interval_dtype([1, 2, 3])
False
>>>
- >>> interval = pd.Interval(1, 2, closed="right")
+ >>> interval = pd.Interval(1, 2, inclusive="right")
>>> is_interval_dtype(interval)
False
>>> is_interval_dtype(pd.IntervalIndex([interval]))
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index 58e91f46dff43..64d46976b54f6 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -14,8 +14,14 @@
import numpy as np
import pytz
-from pandas._libs import missing as libmissing
-from pandas._libs.interval import Interval
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+)
+from pandas._libs.interval import (
+ Interval,
+ _warning_interval,
+)
from pandas._libs.properties import cache_readonly
from pandas._libs.tslibs import (
BaseOffset,
@@ -1040,7 +1046,7 @@ class IntervalDtype(PandasExtensionDtype):
Examples
--------
- >>> pd.IntervalDtype(subtype='int64', closed='both')
+ >>> pd.IntervalDtype(subtype='int64', inclusive='both')
interval[int64, both]
"""
@@ -1051,27 +1057,42 @@ class IntervalDtype(PandasExtensionDtype):
num = 103
_metadata = (
"subtype",
- "closed",
+ "inclusive",
)
_match = re.compile(
- r"(I|i)nterval\[(?P<subtype>[^,]+)(, (?P<closed>(right|left|both|neither)))?\]"
+ r"(I|i)nterval\[(?P<subtype>[^,]+)(, ("
+ r"?P<inclusive>(right|left|both|neither)))?\]"
)
_cache_dtypes: dict[str_type, PandasExtensionDtype] = {}
- def __new__(cls, subtype=None, closed: str_type | None = None):
+ def __new__(
+ cls,
+ subtype=None,
+ inclusive: str_type | None = None,
+ closed: None | lib.NoDefault = lib.no_default,
+ ):
from pandas.core.dtypes.common import (
is_string_dtype,
pandas_dtype,
)
- if closed is not None and closed not in {"right", "left", "both", "neither"}:
- raise ValueError("closed must be one of 'right', 'left', 'both', 'neither'")
+ inclusive, closed = _warning_interval(inclusive, closed)
+
+ if inclusive is not None and inclusive not in {
+ "right",
+ "left",
+ "both",
+ "neither",
+ }:
+ raise ValueError(
+ "inclusive must be one of 'right', 'left', 'both', 'neither'"
+ )
if isinstance(subtype, IntervalDtype):
- if closed is not None and closed != subtype.closed:
+ if inclusive is not None and inclusive != subtype.inclusive:
raise ValueError(
- "dtype.closed and 'closed' do not match. "
- "Try IntervalDtype(dtype.subtype, closed) instead."
+ "dtype.inclusive and 'inclusive' do not match. "
+ "Try IntervalDtype(dtype.subtype, inclusive) instead."
)
return subtype
elif subtype is None:
@@ -1079,7 +1100,7 @@ def __new__(cls, subtype=None, closed: str_type | None = None):
# generally for pickle compat
u = object.__new__(cls)
u._subtype = None
- u._closed = closed
+ u._closed = inclusive
return u
elif isinstance(subtype, str) and subtype.lower() == "interval":
subtype = None
@@ -1089,14 +1110,14 @@ def __new__(cls, subtype=None, closed: str_type | None = None):
if m is not None:
gd = m.groupdict()
subtype = gd["subtype"]
- if gd.get("closed", None) is not None:
- if closed is not None:
- if closed != gd["closed"]:
+ if gd.get("inclusive", None) is not None:
+ if inclusive is not None:
+ if inclusive != gd["inclusive"]:
raise ValueError(
- "'closed' keyword does not match value "
+ "'inclusive' keyword does not match value "
"specified in dtype string"
)
- closed = gd["closed"]
+ inclusive = gd["inclusive"]
try:
subtype = pandas_dtype(subtype)
@@ -1111,13 +1132,13 @@ def __new__(cls, subtype=None, closed: str_type | None = None):
)
raise TypeError(msg)
- key = str(subtype) + str(closed)
+ key = str(subtype) + str(inclusive)
try:
return cls._cache_dtypes[key]
except KeyError:
u = object.__new__(cls)
u._subtype = subtype
- u._closed = closed
+ u._closed = inclusive
cls._cache_dtypes[key] = u
return u
@@ -1134,7 +1155,7 @@ def _can_hold_na(self) -> bool:
return True
@property
- def closed(self):
+ def inclusive(self):
return self._closed
@property
@@ -1186,10 +1207,10 @@ def type(self):
def __str__(self) -> str_type:
if self.subtype is None:
return "interval"
- if self.closed is None:
+ if self.inclusive is None:
# Only partially initialized GH#38394
return f"interval[{self.subtype}]"
- return f"interval[{self.subtype}, {self.closed}]"
+ return f"interval[{self.subtype}, {self.inclusive}]"
def __hash__(self) -> int:
# make myself hashable
@@ -1203,7 +1224,7 @@ def __eq__(self, other: Any) -> bool:
elif self.subtype is None or other.subtype is None:
# None should match any subtype
return True
- elif self.closed != other.closed:
+ elif self.inclusive != other.inclusive:
return False
else:
from pandas.core.dtypes.common import is_dtype_equal
@@ -1215,9 +1236,8 @@ def __setstate__(self, state):
# PandasExtensionDtype superclass and uses the public properties to
# pickle -> need to set the settable private ones here (see GH26067)
self._subtype = state["subtype"]
-
- # backward-compat older pickles won't have "closed" key
- self._closed = state.pop("closed", None)
+ # backward-compat older pickles won't have "inclusive" key
+ self._closed = state.pop("inclusive", None)
@classmethod
def is_dtype(cls, dtype: object) -> bool:
@@ -1259,14 +1279,14 @@ def __from_arrow__(
arr = arr.storage
left = np.asarray(arr.field("left"), dtype=self.subtype)
right = np.asarray(arr.field("right"), dtype=self.subtype)
- iarr = IntervalArray.from_arrays(left, right, closed=self.closed)
+ iarr = IntervalArray.from_arrays(left, right, inclusive=self.inclusive)
results.append(iarr)
if not results:
return IntervalArray.from_arrays(
np.array([], dtype=self.subtype),
np.array([], dtype=self.subtype),
- closed=self.closed,
+ inclusive=self.inclusive,
)
return IntervalArray._concat_same_type(results)
@@ -1274,8 +1294,8 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
if not all(isinstance(x, IntervalDtype) for x in dtypes):
return None
- closed = cast("IntervalDtype", dtypes[0]).closed
- if not all(cast("IntervalDtype", x).closed == closed for x in dtypes):
+ inclusive = cast("IntervalDtype", dtypes[0]).inclusive
+ if not all(cast("IntervalDtype", x).inclusive == inclusive for x in dtypes):
return np.dtype(object)
from pandas.core.dtypes.cast import find_common_type
@@ -1283,7 +1303,7 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
common = find_common_type([cast("IntervalDtype", x).subtype for x in dtypes])
if common == object:
return np.dtype(object)
- return IntervalDtype(common, closed=closed)
+ return IntervalDtype(common, inclusive=inclusive)
class PandasDtype(ExtensionDtype):
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index a89b52e0950f2..11e2da47c5738 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -11,7 +11,6 @@
Hashable,
Literal,
)
-import warnings
import numpy as np
@@ -20,6 +19,7 @@
Interval,
IntervalMixin,
IntervalTree,
+ _warning_interval,
)
from pandas._libs.tslibs import (
BaseOffset,
@@ -189,12 +189,12 @@ def _new_IntervalIndex(cls, d):
],
IntervalArray,
)
-@inherit_names(["is_non_overlapping_monotonic", "closed"], IntervalArray, cache=True)
+@inherit_names(["is_non_overlapping_monotonic", "inclusive"], IntervalArray, cache=True)
class IntervalIndex(ExtensionIndex):
_typ = "intervalindex"
# annotate properties pinned via inherit_names
- closed: IntervalClosedType
+ inclusive: IntervalClosedType
is_non_overlapping_monotonic: bool
closed_left: bool
closed_right: bool
@@ -212,19 +212,22 @@ class IntervalIndex(ExtensionIndex):
def __new__(
cls,
data,
- closed=None,
+ inclusive=None,
+ closed: None | lib.NoDefault = lib.no_default,
dtype: Dtype | None = None,
copy: bool = False,
name: Hashable = None,
verify_integrity: bool = True,
) -> IntervalIndex:
+ inclusive, closed = _warning_interval(inclusive, closed)
+
name = maybe_extract_name(name, data, cls)
with rewrite_exception("IntervalArray", cls.__name__):
array = IntervalArray(
data,
- closed=closed,
+ inclusive=inclusive,
copy=copy,
dtype=dtype,
verify_integrity=verify_integrity,
@@ -241,7 +244,7 @@ def __new__(
"""\
Examples
--------
- >>> pd.IntervalIndex.from_breaks([0, 1, 2, 3])
+ >>> pd.IntervalIndex.from_breaks([0, 1, 2, 3], "right")
IntervalIndex([(0, 1], (1, 2], (2, 3]],
dtype='interval[int64, right]')
"""
@@ -251,14 +254,20 @@ def __new__(
def from_breaks(
cls,
breaks,
- closed: IntervalClosedType | None = "right",
+ inclusive=None,
+ closed: None | lib.NoDefault = lib.no_default,
name: Hashable = None,
copy: bool = False,
dtype: Dtype | None = None,
) -> IntervalIndex:
+
+ inclusive, closed = _warning_interval(inclusive, closed)
+ if inclusive is None:
+ inclusive = "both"
+
with rewrite_exception("IntervalArray", cls.__name__):
array = IntervalArray.from_breaks(
- breaks, closed=closed, copy=copy, dtype=dtype
+ breaks, inclusive=inclusive, copy=copy, dtype=dtype
)
return cls._simple_new(array, name=name)
@@ -271,7 +280,7 @@ def from_breaks(
"""\
Examples
--------
- >>> pd.IntervalIndex.from_arrays([0, 1, 2], [1, 2, 3])
+ >>> pd.IntervalIndex.from_arrays([0, 1, 2], [1, 2, 3], "right")
IntervalIndex([(0, 1], (1, 2], (2, 3]],
dtype='interval[int64, right]')
"""
@@ -282,14 +291,20 @@ def from_arrays(
cls,
left,
right,
- closed: IntervalClosedType = "right",
+ inclusive=None,
+ closed: None | lib.NoDefault = lib.no_default,
name: Hashable = None,
copy: bool = False,
dtype: Dtype | None = None,
) -> IntervalIndex:
+
+ inclusive, closed = _warning_interval(inclusive, closed)
+ if inclusive is None:
+ inclusive = "both"
+
with rewrite_exception("IntervalArray", cls.__name__):
array = IntervalArray.from_arrays(
- left, right, closed, copy=copy, dtype=dtype
+ left, right, inclusive, copy=copy, dtype=dtype
)
return cls._simple_new(array, name=name)
@@ -302,7 +317,7 @@ def from_arrays(
"""\
Examples
--------
- >>> pd.IntervalIndex.from_tuples([(0, 1), (1, 2)])
+ >>> pd.IntervalIndex.from_tuples([(0, 1), (1, 2)], "right")
IntervalIndex([(0, 1], (1, 2]],
dtype='interval[int64, right]')
"""
@@ -312,13 +327,21 @@ def from_arrays(
def from_tuples(
cls,
data,
- closed: str = "right",
+ inclusive=None,
+ closed: None | lib.NoDefault = lib.no_default,
name: Hashable = None,
copy: bool = False,
dtype: Dtype | None = None,
) -> IntervalIndex:
+
+ inclusive, closed = _warning_interval(inclusive, closed)
+ if inclusive is None:
+ inclusive = "both"
+
with rewrite_exception("IntervalArray", cls.__name__):
- arr = IntervalArray.from_tuples(data, closed=closed, copy=copy, dtype=dtype)
+ arr = IntervalArray.from_tuples(
+ data, inclusive=inclusive, copy=copy, dtype=dtype
+ )
return cls._simple_new(arr, name=name)
# --------------------------------------------------------------------
@@ -328,7 +351,7 @@ def from_tuples(
def _engine(self) -> IntervalTree: # type: ignore[override]
left = self._maybe_convert_i8(self.left)
right = self._maybe_convert_i8(self.right)
- return IntervalTree(left, right, closed=self.closed)
+ return IntervalTree(left, right, inclusive=self.inclusive)
def __contains__(self, key: Any) -> bool:
"""
@@ -363,7 +386,7 @@ def __reduce__(self):
d = {
"left": self.left,
"right": self.right,
- "closed": self.closed,
+ "inclusive": self.inclusive,
"name": self.name,
}
return _new_IntervalIndex, (type(self), d), None
@@ -418,7 +441,7 @@ def is_overlapping(self) -> bool:
"""
Return True if the IntervalIndex has overlapping intervals, else False.
- Two intervals overlap if they share a common point, including closed
+ Two intervals overlap if they share a common point, including inclusive
endpoints. Intervals that only have an open endpoint in common do not
overlap.
@@ -435,7 +458,7 @@ def is_overlapping(self) -> bool:
Examples
--------
- >>> index = pd.IntervalIndex.from_tuples([(0, 2), (1, 3), (4, 5)])
+ >>> index = pd.IntervalIndex.from_tuples([(0, 2), (1, 3), (4, 5)], "right")
>>> index
IntervalIndex([(0, 2], (1, 3], (4, 5]],
dtype='interval[int64, right]')
@@ -519,7 +542,7 @@ def _maybe_convert_i8(self, key):
constructor = Interval if scalar else IntervalIndex.from_arrays
# error: "object" not callable
return constructor(
- left, right, closed=self.closed
+ left, right, inclusive=self.inclusive
) # type: ignore[operator]
if scalar:
@@ -600,7 +623,7 @@ def get_loc(
Examples
--------
>>> i1, i2 = pd.Interval(0, 1), pd.Interval(1, 2)
- >>> index = pd.IntervalIndex([i1, i2])
+ >>> index = pd.IntervalIndex([i1, i2], "right")
>>> index.get_loc(1)
0
@@ -613,20 +636,20 @@ def get_loc(
relevant intervals.
>>> i3 = pd.Interval(0, 2)
- >>> overlapping_index = pd.IntervalIndex([i1, i2, i3])
+ >>> overlapping_index = pd.IntervalIndex([i1, i2, i3], "right")
>>> overlapping_index.get_loc(0.5)
array([ True, False, True])
Only exact matches will be returned if an interval is provided.
- >>> index.get_loc(pd.Interval(0, 1))
+ >>> index.get_loc(pd.Interval(0, 1, "right"))
0
"""
self._check_indexing_method(method)
self._check_indexing_error(key)
if isinstance(key, Interval):
- if self.closed != key.closed:
+ if self.inclusive != key.inclusive:
raise KeyError(key)
mask = (self.left == key.left) & (self.right == key.right)
elif is_valid_na_for_dtype(key, self.dtype):
@@ -687,7 +710,7 @@ def get_indexer_non_unique(
target = ensure_index(target)
if not self._should_compare(target) and not self._should_partial_index(target):
- # e.g. IntervalIndex with different closed or incompatible subtype
+ # e.g. IntervalIndex with different inclusive or incompatible subtype
# -> no matches
return self._get_indexer_non_comparable(target, None, unique=False)
@@ -839,7 +862,7 @@ def _intersection(self, other, sort):
"""
intersection specialized to the case with matching dtypes.
"""
- # For IntervalIndex we also know other.closed == self.closed
+ # For IntervalIndex we also know other.inclusive == self.inclusive
if self.left.is_unique and self.right.is_unique:
taken = self._intersection_unique(other)
elif other.left.is_unique and other.right.is_unique and self.isna().sum() <= 1:
@@ -1054,27 +1077,8 @@ def interval_range(
IntervalIndex([[1, 2], [2, 3], [3, 4], [4, 5]],
dtype='interval[int64, both]')
"""
- if inclusive is not None and closed is not lib.no_default:
- raise ValueError(
- "Deprecated argument `closed` cannot be passed "
- "if argument `inclusive` is not None"
- )
- elif closed is not lib.no_default:
- warnings.warn(
- "Argument `closed` is deprecated in favor of `inclusive`.",
- FutureWarning,
- stacklevel=2,
- )
- if closed is None:
- inclusive = "both"
- elif closed in ("both", "neither", "left", "right"):
- inclusive = closed
- else:
- raise ValueError(
- "Argument `closed` has to be either"
- "'both', 'neither', 'left' or 'right'"
- )
- elif inclusive is None:
+ inclusive, closed = _warning_interval(inclusive, closed)
+ if inclusive is None:
inclusive = "both"
start = maybe_box_datetimelike(start)
@@ -1149,4 +1153,4 @@ def interval_range(
else:
breaks = timedelta_range(start=start, end=end, periods=periods, freq=freq)
- return IntervalIndex.from_breaks(breaks, name=name, closed=inclusive)
+ return IntervalIndex.from_breaks(breaks, name=name, inclusive=inclusive)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 71e2a1e36cbbf..3836f3e6540b4 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1961,8 +1961,8 @@ def _catch_deprecated_value_error(err: Exception) -> None:
# is enforced, stop catching ValueError here altogether
if isinstance(err, IncompatibleFrequency):
pass
- elif "'value.closed' is" in str(err):
- # IntervalDtype mismatched 'closed'
+ elif "'value.inclusive' is" in str(err):
+ # IntervalDtype mismatched 'inclusive'
pass
elif "Timezones don't match" not in str(err):
raise
diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py
index 94705790e40bd..00b2b30eb3122 100644
--- a/pandas/core/reshape/tile.py
+++ b/pandas/core/reshape/tile.py
@@ -231,7 +231,7 @@ def cut(
is to the left of the first bin (which is closed on the right), and 1.5
falls between two bins.
- >>> bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)])
+ >>> bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)], inclusive="right")
>>> pd.cut([0, 0.5, 1.5, 2.5, 4.5], bins)
[NaN, (0.0, 1.0], NaN, (2.0, 3.0], (4.0, 5.0]]
Categories (3, interval[int64, right]): [(0, 1] < (2, 3] < (4, 5]]
@@ -561,7 +561,7 @@ def _format_labels(
bins, precision: int, right: bool = True, include_lowest: bool = False, dtype=None
):
"""based on the dtype, return our labels"""
- closed: IntervalLeftRight = "right" if right else "left"
+ inclusive: IntervalLeftRight = "right" if right else "left"
formatter: Callable[[Any], Timestamp] | Callable[[Any], Timedelta]
@@ -584,7 +584,7 @@ def _format_labels(
# adjust lhs of first interval by precision to account for being right closed
breaks[0] = adjust(breaks[0])
- return IntervalIndex.from_breaks(breaks, closed=closed)
+ return IntervalIndex.from_breaks(breaks, inclusive=inclusive)
def _preprocess_for_cut(x):
diff --git a/pandas/tests/arithmetic/test_interval.py b/pandas/tests/arithmetic/test_interval.py
index 88e3dca62d9e0..99e1ad1767e07 100644
--- a/pandas/tests/arithmetic/test_interval.py
+++ b/pandas/tests/arithmetic/test_interval.py
@@ -62,16 +62,16 @@ def interval_array(left_right_dtypes):
return IntervalArray.from_arrays(left, right)
-def create_categorical_intervals(left, right, closed="right"):
- return Categorical(IntervalIndex.from_arrays(left, right, closed))
+def create_categorical_intervals(left, right, inclusive="right"):
+ return Categorical(IntervalIndex.from_arrays(left, right, inclusive))
-def create_series_intervals(left, right, closed="right"):
- return Series(IntervalArray.from_arrays(left, right, closed))
+def create_series_intervals(left, right, inclusive="right"):
+ return Series(IntervalArray.from_arrays(left, right, inclusive))
-def create_series_categorical_intervals(left, right, closed="right"):
- return Series(Categorical(IntervalIndex.from_arrays(left, right, closed)))
+def create_series_categorical_intervals(left, right, inclusive="right"):
+ return Series(Categorical(IntervalIndex.from_arrays(left, right, inclusive)))
class TestComparison:
@@ -126,8 +126,10 @@ def test_compare_scalar_interval(self, op, interval_array):
tm.assert_numpy_array_equal(result, expected)
def test_compare_scalar_interval_mixed_closed(self, op, closed, other_closed):
- interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)
- other = Interval(0, 1, closed=other_closed)
+ interval_array = IntervalArray.from_arrays(
+ range(2), range(1, 3), inclusive=closed
+ )
+ other = Interval(0, 1, inclusive=other_closed)
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
@@ -207,8 +209,10 @@ def test_compare_list_like_interval(self, op, interval_array, interval_construct
def test_compare_list_like_interval_mixed_closed(
self, op, interval_constructor, closed, other_closed
):
- interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)
- other = interval_constructor(range(2), range(1, 3), closed=other_closed)
+ interval_array = IntervalArray.from_arrays(
+ range(2), range(1, 3), inclusive=closed
+ )
+ other = interval_constructor(range(2), range(1, 3), inclusive=other_closed)
result = op(interval_array, other)
expected = self.elementwise_comparison(op, interval_array, other)
diff --git a/pandas/tests/arrays/interval/test_interval.py b/pandas/tests/arrays/interval/test_interval.py
index eaf86f5d521ae..28ffd5b4caf98 100644
--- a/pandas/tests/arrays/interval/test_interval.py
+++ b/pandas/tests/arrays/interval/test_interval.py
@@ -55,7 +55,7 @@ def test_is_empty(self, constructor, left, right, closed):
# GH27219
tuples = [(left, left), (left, right), np.nan]
expected = np.array([closed != "both", False, False])
- result = constructor.from_tuples(tuples, closed=closed).is_empty
+ result = constructor.from_tuples(tuples, inclusive=closed).is_empty
tm.assert_numpy_array_equal(result, expected)
@@ -63,23 +63,23 @@ class TestMethods:
@pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"])
def test_set_closed(self, closed, new_closed):
# GH 21670
- array = IntervalArray.from_breaks(range(10), closed=closed)
+ array = IntervalArray.from_breaks(range(10), inclusive=closed)
result = array.set_closed(new_closed)
- expected = IntervalArray.from_breaks(range(10), closed=new_closed)
+ expected = IntervalArray.from_breaks(range(10), inclusive=new_closed)
tm.assert_extension_array_equal(result, expected)
@pytest.mark.parametrize(
"other",
[
- Interval(0, 1, closed="right"),
- IntervalArray.from_breaks([1, 2, 3, 4], closed="right"),
+ Interval(0, 1, inclusive="right"),
+ IntervalArray.from_breaks([1, 2, 3, 4], inclusive="right"),
],
)
def test_where_raises(self, other):
# GH#45768 The IntervalArray methods raises; the Series method coerces
- ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], closed="left"))
+ ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], inclusive="left"))
mask = np.array([True, False, True])
- match = "'value.closed' is 'right', expected 'left'."
+ match = "'value.inclusive' is 'right', expected 'left'."
with pytest.raises(ValueError, match=match):
ser.array._where(mask, other)
@@ -89,15 +89,15 @@ def test_where_raises(self, other):
def test_shift(self):
# https://github.com/pandas-dev/pandas/issues/31495, GH#22428, GH#31502
- a = IntervalArray.from_breaks([1, 2, 3])
+ a = IntervalArray.from_breaks([1, 2, 3], "right")
result = a.shift()
# int -> float
- expected = IntervalArray.from_tuples([(np.nan, np.nan), (1.0, 2.0)])
+ expected = IntervalArray.from_tuples([(np.nan, np.nan), (1.0, 2.0)], "right")
tm.assert_interval_array_equal(result, expected)
def test_shift_datetime(self):
# GH#31502, GH#31504
- a = IntervalArray.from_breaks(date_range("2000", periods=4))
+ a = IntervalArray.from_breaks(date_range("2000", periods=4), "right")
result = a.shift(2)
expected = a.take([-1, -1, 0], allow_fill=True)
tm.assert_interval_array_equal(result, expected)
@@ -135,11 +135,11 @@ def test_set_na(self, left_right_dtypes):
tm.assert_extension_array_equal(result, expected)
def test_setitem_mismatched_closed(self):
- arr = IntervalArray.from_breaks(range(4))
+ arr = IntervalArray.from_breaks(range(4), "right")
orig = arr.copy()
other = arr.set_closed("both")
- msg = "'value.closed' is 'both', expected 'right'"
+ msg = "'value.inclusive' is 'both', expected 'right'"
with pytest.raises(ValueError, match=msg):
arr[0] = other[0]
with pytest.raises(ValueError, match=msg):
@@ -156,13 +156,13 @@ def test_setitem_mismatched_closed(self):
arr[:] = other[::-1].astype("category")
# empty list should be no-op
- arr[:0] = []
+ arr[:0] = IntervalArray.from_breaks([], "right")
tm.assert_interval_array_equal(arr, orig)
def test_repr():
# GH 25022
- arr = IntervalArray.from_tuples([(0, 1), (1, 2)])
+ arr = IntervalArray.from_tuples([(0, 1), (1, 2)], "right")
result = repr(arr)
expected = (
"<IntervalArray>\n"
@@ -254,7 +254,7 @@ def test_arrow_extension_type():
p2 = ArrowIntervalType(pa.int64(), "left")
p3 = ArrowIntervalType(pa.int64(), "right")
- assert p1.closed == "left"
+ assert p1.inclusive == "left"
assert p1 == p2
assert not p1 == p3
assert hash(p1) == hash(p2)
@@ -271,7 +271,7 @@ def test_arrow_array():
result = pa.array(intervals)
assert isinstance(result.type, ArrowIntervalType)
- assert result.type.closed == intervals.closed
+ assert result.type.inclusive == intervals.inclusive
assert result.type.subtype == pa.int64()
assert result.storage.field("left").equals(pa.array([1, 2, 3, 4], type="int64"))
assert result.storage.field("right").equals(pa.array([2, 3, 4, 5], type="int64"))
@@ -302,7 +302,7 @@ def test_arrow_array_missing():
result = pa.array(arr)
assert isinstance(result.type, ArrowIntervalType)
- assert result.type.closed == arr.closed
+ assert result.type.inclusive == arr.inclusive
assert result.type.subtype == pa.float64()
# fields have missing values (not NaN)
@@ -386,13 +386,60 @@ def test_from_arrow_from_raw_struct_array():
import pyarrow as pa
arr = pa.array([{"left": 0, "right": 1}, {"left": 1, "right": 2}])
- dtype = pd.IntervalDtype(np.dtype("int64"), closed="neither")
+ dtype = pd.IntervalDtype(np.dtype("int64"), inclusive="neither")
result = dtype.__from_arrow__(arr)
expected = IntervalArray.from_breaks(
- np.array([0, 1, 2], dtype="int64"), closed="neither"
+ np.array([0, 1, 2], dtype="int64"), inclusive="neither"
)
tm.assert_extension_array_equal(result, expected)
result = dtype.__from_arrow__(pa.chunked_array([arr]))
tm.assert_extension_array_equal(result, expected)
+
+
+def test_interval_error_and_warning():
+ # GH 40245
+ msg = (
+ "Deprecated argument `closed` cannot "
+ "be passed if argument `inclusive` is not None"
+ )
+ with pytest.raises(ValueError, match=msg):
+ Interval(0, 1, closed="both", inclusive="both")
+
+ msg = "Argument `closed` is deprecated in favor of `inclusive`"
+ with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False):
+ Interval(0, 1, closed="both")
+
+
+def test_interval_array_error_and_warning():
+ # GH 40245
+ msg = (
+ "Deprecated argument `closed` cannot "
+ "be passed if argument `inclusive` is not None"
+ )
+ with pytest.raises(ValueError, match=msg):
+ IntervalArray([Interval(0, 1), Interval(1, 5)], closed="both", inclusive="both")
+
+ msg = "Argument `closed` is deprecated in favor of `inclusive`"
+ with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False):
+ IntervalArray([Interval(0, 1), Interval(1, 5)], closed="both")
+
+
+@pyarrow_skip
+def test_arrow_interval_type_error_and_warning():
+ # GH 40245
+ import pyarrow as pa
+
+ from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType
+
+ msg = (
+ "Deprecated argument `closed` cannot "
+ "be passed if argument `inclusive` is not None"
+ )
+ with pytest.raises(ValueError, match=msg):
+ ArrowIntervalType(pa.int64(), closed="both", inclusive="both")
+
+ msg = "Argument `closed` is deprecated in favor of `inclusive`"
+ with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False):
+ ArrowIntervalType(pa.int64(), closed="both")
diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py
index 3c8d12556bf1c..bf7dca9e1d5a0 100644
--- a/pandas/tests/arrays/test_array.py
+++ b/pandas/tests/arrays/test_array.py
@@ -133,9 +133,9 @@
),
# Interval
(
- [pd.Interval(1, 2), pd.Interval(3, 4)],
+ [pd.Interval(1, 2, "right"), pd.Interval(3, 4, "right")],
"interval",
- IntervalArray.from_tuples([(1, 2), (3, 4)]),
+ IntervalArray.from_tuples([(1, 2), (3, 4)], "right"),
),
# Sparse
([0, 1], "Sparse[int64]", SparseArray([0, 1], dtype="int64")),
@@ -206,7 +206,10 @@ def test_array_copy():
period_array(["2000", "2001"], freq="D"),
),
# interval
- ([pd.Interval(0, 1), pd.Interval(1, 2)], IntervalArray.from_breaks([0, 1, 2])),
+ (
+ [pd.Interval(0, 1, "right"), pd.Interval(1, 2, "right")],
+ IntervalArray.from_breaks([0, 1, 2], "right"),
+ ),
# datetime
(
[pd.Timestamp("2000"), pd.Timestamp("2001")],
@@ -296,7 +299,7 @@ def test_array_inference(data, expected):
# mix of frequencies
[pd.Period("2000", "D"), pd.Period("2001", "A")],
# mix of closed
- [pd.Interval(0, 1, closed="left"), pd.Interval(1, 2, closed="right")],
+ [pd.Interval(0, 1, "left"), pd.Interval(1, 2, "right")],
# Mix of timezones
[pd.Timestamp("2000", tz="CET"), pd.Timestamp("2000", tz="UTC")],
# Mix of tz-aware and tz-naive
diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py
index 599aaae4d3527..3adaddf89cf30 100644
--- a/pandas/tests/base/test_conversion.py
+++ b/pandas/tests/base/test_conversion.py
@@ -290,8 +290,10 @@ def test_array_multiindex_raises():
),
(pd.array([0, np.nan], dtype="Int64"), np.array([0, pd.NA], dtype=object)),
(
- IntervalArray.from_breaks([0, 1, 2]),
- np.array([pd.Interval(0, 1), pd.Interval(1, 2)], dtype=object),
+ IntervalArray.from_breaks([0, 1, 2], "right"),
+ np.array(
+ [pd.Interval(0, 1, "right"), pd.Interval(1, 2, "right")], dtype=object
+ ),
),
(SparseArray([0, 1]), np.array([0, 1], dtype=np.int64)),
# tz-naive datetime
diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py
index c46f1b036dbee..55a6cc48ebfc8 100644
--- a/pandas/tests/base/test_value_counts.py
+++ b/pandas/tests/base/test_value_counts.py
@@ -133,10 +133,10 @@ def test_value_counts_bins(index_or_series):
s1 = Series([1, 1, 2, 3])
res1 = s1.value_counts(bins=1)
- exp1 = Series({Interval(0.997, 3.0): 4})
+ exp1 = Series({Interval(0.997, 3.0, "right"): 4})
tm.assert_series_equal(res1, exp1)
res1n = s1.value_counts(bins=1, normalize=True)
- exp1n = Series({Interval(0.997, 3.0): 1.0})
+ exp1n = Series({Interval(0.997, 3.0, "right"): 1.0})
tm.assert_series_equal(res1n, exp1n)
if isinstance(s1, Index):
@@ -149,12 +149,12 @@ def test_value_counts_bins(index_or_series):
# these return the same
res4 = s1.value_counts(bins=4, dropna=True)
- intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0])
+ intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0], "right")
exp4 = Series([2, 1, 1, 0], index=intervals.take([0, 1, 3, 2]))
tm.assert_series_equal(res4, exp4)
res4 = s1.value_counts(bins=4, dropna=False)
- intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0])
+ intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0], "right")
exp4 = Series([2, 1, 1, 0], index=intervals.take([0, 1, 3, 2]))
tm.assert_series_equal(res4, exp4)
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py
index a32b37fbdd71b..c5d0567b6dfc0 100644
--- a/pandas/tests/dtypes/test_common.py
+++ b/pandas/tests/dtypes/test_common.py
@@ -269,7 +269,7 @@ def test_is_interval_dtype():
assert com.is_interval_dtype(IntervalDtype())
- interval = pd.Interval(1, 2, closed="right")
+ interval = pd.Interval(1, 2, inclusive="right")
assert not com.is_interval_dtype(interval)
assert com.is_interval_dtype(pd.IntervalIndex([interval]))
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index f077317e7ebbe..b7de8016f8fac 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -568,10 +568,19 @@ def test_hash_vs_equality(self, dtype):
"subtype", ["interval[int64]", "Interval[int64]", "int64", np.dtype("int64")]
)
def test_construction(self, subtype):
- i = IntervalDtype(subtype, closed="right")
+ i = IntervalDtype(subtype, inclusive="right")
assert i.subtype == np.dtype("int64")
assert is_interval_dtype(i)
+ @pytest.mark.parametrize(
+ "subtype", ["interval[int64, right]", "Interval[int64, right]"]
+ )
+ def test_construction_string_regex(self, subtype):
+ i = IntervalDtype(subtype=subtype)
+ assert i.subtype == np.dtype("int64")
+ assert i.inclusive == "right"
+ assert is_interval_dtype(i)
+
@pytest.mark.parametrize(
"subtype", ["interval[int64]", "Interval[int64]", "int64", np.dtype("int64")]
)
@@ -579,10 +588,10 @@ def test_construction_allows_closed_none(self, subtype):
# GH#38394
dtype = IntervalDtype(subtype)
- assert dtype.closed is None
+ assert dtype.inclusive is None
def test_closed_mismatch(self):
- msg = "'closed' keyword does not match value specified in dtype string"
+ msg = "'inclusive' keyword does not match value specified in dtype string"
with pytest.raises(ValueError, match=msg):
IntervalDtype("interval[int64, left]", "right")
@@ -624,12 +633,12 @@ def test_closed_must_match(self):
# GH#37933
dtype = IntervalDtype(np.float64, "left")
- msg = "dtype.closed and 'closed' do not match"
+ msg = "dtype.inclusive and 'inclusive' do not match"
with pytest.raises(ValueError, match=msg):
- IntervalDtype(dtype, closed="both")
+ IntervalDtype(dtype, inclusive="both")
def test_closed_invalid(self):
- with pytest.raises(ValueError, match="closed must be one of"):
+ with pytest.raises(ValueError, match="inclusive must be one of"):
IntervalDtype(np.float64, "foo")
def test_construction_from_string(self, dtype):
@@ -729,8 +738,8 @@ def test_equality(self, dtype):
)
def test_equality_generic(self, subtype):
# GH 18980
- closed = "right" if subtype is not None else None
- dtype = IntervalDtype(subtype, closed=closed)
+ inclusive = "right" if subtype is not None else None
+ dtype = IntervalDtype(subtype, inclusive=inclusive)
assert is_dtype_equal(dtype, "interval")
assert is_dtype_equal(dtype, IntervalDtype())
@@ -748,9 +757,9 @@ def test_equality_generic(self, subtype):
)
def test_name_repr(self, subtype):
# GH 18980
- closed = "right" if subtype is not None else None
- dtype = IntervalDtype(subtype, closed=closed)
- expected = f"interval[{subtype}, {closed}]"
+ inclusive = "right" if subtype is not None else None
+ dtype = IntervalDtype(subtype, inclusive=inclusive)
+ expected = f"interval[{subtype}, {inclusive}]"
assert str(dtype) == expected
assert dtype.name == "interval"
@@ -812,6 +821,21 @@ def test_unpickling_without_closed(self):
tm.round_trip_pickle(dtype)
+ def test_interval_dtype_error_and_warning(self):
+ # GH 40245
+ msg = (
+ "Deprecated argument `closed` cannot "
+ "be passed if argument `inclusive` is not None"
+ )
+ with pytest.raises(ValueError, match=msg):
+ IntervalDtype("int64", closed="right", inclusive="right")
+
+ msg = "Argument `closed` is deprecated in favor of `inclusive`"
+ with tm.assert_produces_warning(
+ FutureWarning, match=msg, check_stacklevel=False
+ ):
+ IntervalDtype("int64", closed="right")
+
class TestCategoricalDtypeParametrized:
@pytest.mark.parametrize(
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 15f6e82419049..b12476deccbfc 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -959,7 +959,7 @@ def test_mixed_dtypes_remain_object_array(self):
@pytest.mark.parametrize(
"idx",
[
- pd.IntervalIndex.from_breaks(range(5), closed="both"),
+ pd.IntervalIndex.from_breaks(range(5), inclusive="both"),
pd.period_range("2016-01-01", periods=3, freq="D"),
],
)
@@ -1652,7 +1652,7 @@ def test_categorical(self):
@pytest.mark.parametrize("asobject", [True, False])
def test_interval(self, asobject):
- idx = pd.IntervalIndex.from_breaks(range(5), closed="both")
+ idx = pd.IntervalIndex.from_breaks(range(5), inclusive="both")
if asobject:
idx = idx.astype(object)
@@ -1668,21 +1668,21 @@ def test_interval(self, asobject):
@pytest.mark.parametrize("value", [Timestamp(0), Timedelta(0), 0, 0.0])
def test_interval_mismatched_closed(self, value):
- first = Interval(value, value, closed="left")
- second = Interval(value, value, closed="right")
+ first = Interval(value, value, inclusive="left")
+ second = Interval(value, value, inclusive="right")
- # if closed match, we should infer "interval"
+ # if inclusive match, we should infer "interval"
arr = np.array([first, first], dtype=object)
assert lib.infer_dtype(arr, skipna=False) == "interval"
- # if closed dont match, we should _not_ get "interval"
+ # if inclusive dont match, we should _not_ get "interval"
arr2 = np.array([first, second], dtype=object)
assert lib.infer_dtype(arr2, skipna=False) == "mixed"
def test_interval_mismatched_subtype(self):
- first = Interval(0, 1, closed="left")
- second = Interval(Timestamp(0), Timestamp(1), closed="left")
- third = Interval(Timedelta(0), Timedelta(1), closed="left")
+ first = Interval(0, 1, inclusive="left")
+ second = Interval(Timestamp(0), Timestamp(1), inclusive="left")
+ third = Interval(Timedelta(0), Timedelta(1), inclusive="left")
arr = np.array([first, second])
assert lib.infer_dtype(arr, skipna=False) == "mixed"
@@ -1694,7 +1694,7 @@ def test_interval_mismatched_subtype(self):
assert lib.infer_dtype(arr, skipna=False) == "mixed"
# float vs int subdtype are compatible
- flt_interval = Interval(1.5, 2.5, closed="left")
+ flt_interval = Interval(1.5, 2.5, inclusive="left")
arr = np.array([first, flt_interval], dtype=object)
assert lib.infer_dtype(arr, skipna=False) == "interval"
diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py
index 283b67bb9171d..9e016e0101ef6 100644
--- a/pandas/tests/extension/base/setitem.py
+++ b/pandas/tests/extension/base/setitem.py
@@ -10,6 +10,7 @@
import pandas as pd
import pandas._testing as tm
+from pandas.core.arrays import IntervalArray
from pandas.tests.extension.base.base import BaseExtensionTests
@@ -76,10 +77,17 @@ def test_setitem_sequence_mismatched_length_raises(self, data, as_array):
self.assert_series_equal(ser, original)
def test_setitem_empty_indexer(self, data, box_in_series):
+ data_dtype = type(data)
+
if box_in_series:
data = pd.Series(data)
original = data.copy()
- data[np.array([], dtype=int)] = []
+
+ if data_dtype == IntervalArray:
+ data[np.array([], dtype=int)] = IntervalArray([], "right")
+ else:
+ data[np.array([], dtype=int)] = []
+
self.assert_equal(data, original)
def test_setitem_sequence_broadcasts(self, data, box_in_series):
diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py
index 0f916cea9d518..eb307d964d736 100644
--- a/pandas/tests/extension/test_interval.py
+++ b/pandas/tests/extension/test_interval.py
@@ -30,7 +30,9 @@ def make_data():
N = 100
left_array = np.random.uniform(size=N).cumsum()
right_array = left_array + np.random.uniform(size=N)
- return [Interval(left, right) for left, right in zip(left_array, right_array)]
+ return [
+ Interval(left, right, "right") for left, right in zip(left_array, right_array)
+ ]
@pytest.fixture
@@ -41,7 +43,7 @@ def dtype():
@pytest.fixture
def data():
"""Length-100 PeriodArray for semantics test."""
- return IntervalArray(make_data())
+ return IntervalArray(make_data(), "right")
@pytest.fixture
diff --git a/pandas/tests/frame/constructors/test_from_records.py b/pandas/tests/frame/constructors/test_from_records.py
index c6d54e28ca1c8..715f69cc03828 100644
--- a/pandas/tests/frame/constructors/test_from_records.py
+++ b/pandas/tests/frame/constructors/test_from_records.py
@@ -229,7 +229,11 @@ def test_from_records_series_list_dict(self):
def test_from_records_series_categorical_index(self):
# GH#32805
index = CategoricalIndex(
- [Interval(-20, -10), Interval(-10, 0), Interval(0, 10)]
+ [
+ Interval(-20, -10, "right"),
+ Interval(-10, 0, "right"),
+ Interval(0, 10, "right"),
+ ]
)
series_of_dicts = Series([{"a": 1}, {"a": 2}, {"b": 3}], index=index)
frame = DataFrame.from_records(series_of_dicts, index=index)
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index fda37fdedb92a..04d95953a3a8d 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -227,7 +227,10 @@ def test_setitem_dict_preserves_dtypes(self):
"obj,dtype",
[
(Period("2020-01"), PeriodDtype("M")),
- (Interval(left=0, right=5), IntervalDtype("int64", "right")),
+ (
+ Interval(left=0, right=5, inclusive="right"),
+ IntervalDtype("int64", "right"),
+ ),
(
Timestamp("2011-01-01", tz="US/Eastern"),
DatetimeTZDtype(tz="US/Eastern"),
diff --git a/pandas/tests/frame/methods/test_combine_first.py b/pandas/tests/frame/methods/test_combine_first.py
index 47ebca0b9bf5c..783bef3206d58 100644
--- a/pandas/tests/frame/methods/test_combine_first.py
+++ b/pandas/tests/frame/methods/test_combine_first.py
@@ -402,7 +402,7 @@ def test_combine_first_string_dtype_only_na(self, nullable_string_dtype):
(datetime(2020, 1, 1), datetime(2020, 1, 2)),
(pd.Period("2020-01-01", "D"), pd.Period("2020-01-02", "D")),
(pd.Timedelta("89 days"), pd.Timedelta("60 min")),
- (pd.Interval(left=0, right=1), pd.Interval(left=2, right=3, closed="left")),
+ (pd.Interval(left=0, right=1), pd.Interval(left=2, right=3, inclusive="left")),
],
)
def test_combine_first_timestamp_bug(scalar1, scalar2, nulls_fixture):
diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py
index 37431bc291b76..bd168e4f14558 100644
--- a/pandas/tests/frame/methods/test_reset_index.py
+++ b/pandas/tests/frame/methods/test_reset_index.py
@@ -751,7 +751,7 @@ def test_reset_index_interval_columns_object_cast():
result = df.reset_index()
expected = DataFrame(
[[1, 1.0, 0.0], [2, 0.0, 1.0]],
- columns=Index(["Year", Interval(0, 1), Interval(1, 2)]),
+ columns=Index(["Year", Interval(0, 1, "right"), Interval(1, 2, "right")]),
)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py
index 5d1cc3d4ecee5..9cad965e9cb5c 100644
--- a/pandas/tests/frame/methods/test_sort_index.py
+++ b/pandas/tests/frame/methods/test_sort_index.py
@@ -384,7 +384,7 @@ def test_sort_index_intervalindex(self):
result = model.groupby(["X1", "X2"], observed=True).mean().unstack()
expected = IntervalIndex.from_tuples(
- [(-3.0, -0.5), (-0.5, 0.0), (0.0, 0.5), (0.5, 3.0)], closed="right"
+ [(-3.0, -0.5), (-0.5, 0.0), (0.0, 0.5), (0.5, 3.0)], inclusive="right"
)
result = result.columns.levels[1].categories
tm.assert_index_equal(result, expected)
@@ -729,7 +729,11 @@ def test_sort_index_multilevel_repr_8017(self, gen, extra):
[
pytest.param(["a", "b", "c"], id="str"),
pytest.param(
- [pd.Interval(0, 1), pd.Interval(1, 2), pd.Interval(2, 3)],
+ [
+ pd.Interval(0, 1, "right"),
+ pd.Interval(1, 2, "right"),
+ pd.Interval(2, 3, "right"),
+ ],
id="pd.Interval",
),
],
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 82c7117cc00c6..e62c050fbf812 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -884,7 +884,10 @@ def test_constructor_dict_extension_scalar(self, ea_scalar_and_dtype):
"data,dtype",
[
(Period("2020-01"), PeriodDtype("M")),
- (Interval(left=0, right=5), IntervalDtype("int64", "right")),
+ (
+ Interval(left=0, right=5, inclusive="right"),
+ IntervalDtype("int64", "right"),
+ ),
(
Timestamp("2011-01-01", tz="US/Eastern"),
DatetimeTZDtype(tz="US/Eastern"),
@@ -2410,16 +2413,16 @@ def test_constructor_series_nonexact_categoricalindex(self):
result = DataFrame({"1": ser1, "2": ser2})
index = CategoricalIndex(
[
- Interval(-0.099, 9.9, closed="right"),
- Interval(9.9, 19.8, closed="right"),
- Interval(19.8, 29.7, closed="right"),
- Interval(29.7, 39.6, closed="right"),
- Interval(39.6, 49.5, closed="right"),
- Interval(49.5, 59.4, closed="right"),
- Interval(59.4, 69.3, closed="right"),
- Interval(69.3, 79.2, closed="right"),
- Interval(79.2, 89.1, closed="right"),
- Interval(89.1, 99, closed="right"),
+ Interval(-0.099, 9.9, inclusive="right"),
+ Interval(9.9, 19.8, inclusive="right"),
+ Interval(19.8, 29.7, inclusive="right"),
+ Interval(29.7, 39.6, inclusive="right"),
+ Interval(39.6, 49.5, inclusive="right"),
+ Interval(49.5, 59.4, inclusive="right"),
+ Interval(59.4, 69.3, inclusive="right"),
+ Interval(69.3, 79.2, inclusive="right"),
+ Interval(79.2, 89.1, inclusive="right"),
+ Interval(89.1, 99, inclusive="right"),
],
ordered=True,
)
diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py
index 5f1a81c504efe..2c2332a05505f 100644
--- a/pandas/tests/groupby/test_grouping.py
+++ b/pandas/tests/groupby/test_grouping.py
@@ -799,13 +799,13 @@ def test_get_group_empty_bins(self, observed):
# TODO: should prob allow a str of Interval work as well
# IOW '(0, 5]'
- result = g.get_group(pd.Interval(0, 5))
+ result = g.get_group(pd.Interval(0, 5, "right"))
expected = DataFrame([3, 1], index=[0, 1])
tm.assert_frame_equal(result, expected)
- msg = r"Interval\(10, 15, closed='right'\)"
+ msg = r"Interval\(10, 15, inclusive='right'\)"
with pytest.raises(KeyError, match=msg):
- g.get_group(pd.Interval(10, 15))
+ g.get_group(pd.Interval(10, 15, "right"))
def test_get_group_grouped_by_tuple(self):
# GH 8121
diff --git a/pandas/tests/indexes/categorical/test_astype.py b/pandas/tests/indexes/categorical/test_astype.py
index 854ae8b62db30..ec3e3dca92808 100644
--- a/pandas/tests/indexes/categorical/test_astype.py
+++ b/pandas/tests/indexes/categorical/test_astype.py
@@ -26,7 +26,9 @@ def test_astype(self):
assert not isinstance(result, CategoricalIndex)
# interval
- ii = IntervalIndex.from_arrays(left=[-0.001, 2.0], right=[2, 4], closed="right")
+ ii = IntervalIndex.from_arrays(
+ left=[-0.001, 2.0], right=[2, 4], inclusive="right"
+ )
ci = CategoricalIndex(
Categorical.from_codes([0, 1, -1], categories=ii, ordered=True)
diff --git a/pandas/tests/indexes/categorical/test_reindex.py b/pandas/tests/indexes/categorical/test_reindex.py
index 1337eff1f1c2f..8764063a1a008 100644
--- a/pandas/tests/indexes/categorical/test_reindex.py
+++ b/pandas/tests/indexes/categorical/test_reindex.py
@@ -69,15 +69,15 @@ def test_reindex_empty_index(self):
def test_reindex_categorical_added_category(self):
# GH 42424
ci = CategoricalIndex(
- [Interval(0, 1, closed="right"), Interval(1, 2, closed="right")],
+ [Interval(0, 1, inclusive="right"), Interval(1, 2, inclusive="right")],
ordered=True,
)
ci_add = CategoricalIndex(
[
- Interval(0, 1, closed="right"),
- Interval(1, 2, closed="right"),
- Interval(2, 3, closed="right"),
- Interval(3, 4, closed="right"),
+ Interval(0, 1, inclusive="right"),
+ Interval(1, 2, inclusive="right"),
+ Interval(2, 3, inclusive="right"),
+ Interval(3, 4, inclusive="right"),
],
ordered=True,
)
diff --git a/pandas/tests/indexes/interval/test_astype.py b/pandas/tests/indexes/interval/test_astype.py
index 4cdbe2bbcf12b..6751a383699bb 100644
--- a/pandas/tests/indexes/interval/test_astype.py
+++ b/pandas/tests/indexes/interval/test_astype.py
@@ -82,7 +82,7 @@ class TestIntSubtype(AstypeTests):
indexes = [
IntervalIndex.from_breaks(np.arange(-10, 11, dtype="int64")),
- IntervalIndex.from_breaks(np.arange(100, dtype="uint64"), closed="left"),
+ IntervalIndex.from_breaks(np.arange(100, dtype="uint64"), inclusive="left"),
]
@pytest.fixture(params=indexes)
@@ -93,10 +93,12 @@ def index(self, request):
"subtype", ["float64", "datetime64[ns]", "timedelta64[ns]"]
)
def test_subtype_conversion(self, index, subtype):
- dtype = IntervalDtype(subtype, index.closed)
+ dtype = IntervalDtype(subtype, index.inclusive)
result = index.astype(dtype)
expected = IntervalIndex.from_arrays(
- index.left.astype(subtype), index.right.astype(subtype), closed=index.closed
+ index.left.astype(subtype),
+ index.right.astype(subtype),
+ inclusive=index.inclusive,
)
tm.assert_index_equal(result, expected)
@@ -105,12 +107,12 @@ def test_subtype_conversion(self, index, subtype):
)
def test_subtype_integer(self, subtype_start, subtype_end):
index = IntervalIndex.from_breaks(np.arange(100, dtype=subtype_start))
- dtype = IntervalDtype(subtype_end, index.closed)
+ dtype = IntervalDtype(subtype_end, index.inclusive)
result = index.astype(dtype)
expected = IntervalIndex.from_arrays(
index.left.astype(subtype_end),
index.right.astype(subtype_end),
- closed=index.closed,
+ inclusive=index.inclusive,
)
tm.assert_index_equal(result, expected)
@@ -135,7 +137,9 @@ class TestFloatSubtype(AstypeTests):
indexes = [
interval_range(-10.0, 10.0, inclusive="neither"),
IntervalIndex.from_arrays(
- [-1.5, np.nan, 0.0, 0.0, 1.5], [-0.5, np.nan, 1.0, 1.0, 3.0], closed="both"
+ [-1.5, np.nan, 0.0, 0.0, 1.5],
+ [-0.5, np.nan, 1.0, 1.0, 3.0],
+ inclusive="both",
),
]
@@ -149,7 +153,9 @@ def test_subtype_integer(self, subtype):
dtype = IntervalDtype(subtype, "right")
result = index.astype(dtype)
expected = IntervalIndex.from_arrays(
- index.left.astype(subtype), index.right.astype(subtype), closed=index.closed
+ index.left.astype(subtype),
+ index.right.astype(subtype),
+ inclusive=index.inclusive,
)
tm.assert_index_equal(result, expected)
@@ -164,7 +170,9 @@ def test_subtype_integer_with_non_integer_borders(self, subtype):
dtype = IntervalDtype(subtype, "right")
result = index.astype(dtype)
expected = IntervalIndex.from_arrays(
- index.left.astype(subtype), index.right.astype(subtype), closed=index.closed
+ index.left.astype(subtype),
+ index.right.astype(subtype),
+ inclusive=index.inclusive,
)
tm.assert_index_equal(result, expected)
@@ -216,7 +224,9 @@ def test_subtype_integer(self, index, subtype):
new_left = index.left.astype(subtype)
new_right = index.right.astype(subtype)
- expected = IntervalIndex.from_arrays(new_left, new_right, closed=index.closed)
+ expected = IntervalIndex.from_arrays(
+ new_left, new_right, inclusive=index.inclusive
+ )
tm.assert_index_equal(result, expected)
def test_subtype_float(self, index):
diff --git a/pandas/tests/indexes/interval/test_base.py b/pandas/tests/indexes/interval/test_base.py
index c44303aa2c862..933707bfe8357 100644
--- a/pandas/tests/indexes/interval/test_base.py
+++ b/pandas/tests/indexes/interval/test_base.py
@@ -16,14 +16,14 @@ class TestBase(Base):
@pytest.fixture
def simple_index(self) -> IntervalIndex:
- return self._index_cls.from_breaks(range(11), closed="right")
+ return self._index_cls.from_breaks(range(11), inclusive="right")
@pytest.fixture
def index(self):
return tm.makeIntervalIndex(10)
- def create_index(self, *, closed="right"):
- return IntervalIndex.from_breaks(range(11), closed=closed)
+ def create_index(self, *, inclusive="right"):
+ return IntervalIndex.from_breaks(range(11), inclusive=inclusive)
def test_repr_max_seq_item_setting(self):
# override base test: not a valid repr as we use interval notation
@@ -34,13 +34,13 @@ def test_repr_roundtrip(self):
pass
def test_take(self, closed):
- index = self.create_index(closed=closed)
+ index = self.create_index(inclusive=closed)
result = index.take(range(10))
tm.assert_index_equal(result, index)
result = index.take([0, 0, 1])
- expected = IntervalIndex.from_arrays([0, 0, 1], [1, 1, 2], closed=closed)
+ expected = IntervalIndex.from_arrays([0, 0, 1], [1, 1, 2], inclusive=closed)
tm.assert_index_equal(result, expected)
def test_where(self, simple_index, listlike_box):
diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py
index a71a8f9e34ea9..b57bcf7abc1e1 100644
--- a/pandas/tests/indexes/interval/test_constructors.py
+++ b/pandas/tests/indexes/interval/test_constructors.py
@@ -53,9 +53,9 @@ class ConstructorTests:
)
def test_constructor(self, constructor, breaks, closed, name):
result_kwargs = self.get_kwargs_from_breaks(breaks, closed)
- result = constructor(closed=closed, name=name, **result_kwargs)
+ result = constructor(inclusive=closed, name=name, **result_kwargs)
- assert result.closed == closed
+ assert result.inclusive == closed
assert result.name == name
assert result.dtype.subtype == getattr(breaks, "dtype", "int64")
tm.assert_index_equal(result.left, Index(breaks[:-1]))
@@ -78,7 +78,7 @@ def test_constructor_dtype(self, constructor, breaks, subtype):
expected = constructor(**expected_kwargs)
result_kwargs = self.get_kwargs_from_breaks(breaks)
- iv_dtype = IntervalDtype(subtype, "right")
+ iv_dtype = IntervalDtype(subtype, "both")
for dtype in (iv_dtype, str(iv_dtype)):
result = constructor(dtype=dtype, **result_kwargs)
tm.assert_index_equal(result, expected)
@@ -108,20 +108,20 @@ def test_constructor_pass_closed(self, constructor, breaks):
for dtype in (iv_dtype, str(iv_dtype)):
with tm.assert_produces_warning(warn):
- result = constructor(dtype=dtype, closed="left", **result_kwargs)
- assert result.dtype.closed == "left"
+ result = constructor(dtype=dtype, inclusive="left", **result_kwargs)
+ assert result.dtype.inclusive == "left"
@pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning")
@pytest.mark.parametrize("breaks", [[np.nan] * 2, [np.nan] * 4, [np.nan] * 50])
def test_constructor_nan(self, constructor, breaks, closed):
# GH 18421
result_kwargs = self.get_kwargs_from_breaks(breaks)
- result = constructor(closed=closed, **result_kwargs)
+ result = constructor(inclusive=closed, **result_kwargs)
expected_subtype = np.float64
expected_values = np.array(breaks[:-1], dtype=object)
- assert result.closed == closed
+ assert result.inclusive == closed
assert result.dtype.subtype == expected_subtype
tm.assert_numpy_array_equal(np.array(result), expected_values)
@@ -139,13 +139,13 @@ def test_constructor_nan(self, constructor, breaks, closed):
def test_constructor_empty(self, constructor, breaks, closed):
# GH 18421
result_kwargs = self.get_kwargs_from_breaks(breaks)
- result = constructor(closed=closed, **result_kwargs)
+ result = constructor(inclusive=closed, **result_kwargs)
expected_values = np.array([], dtype=object)
expected_subtype = getattr(breaks, "dtype", np.int64)
assert result.empty
- assert result.closed == closed
+ assert result.inclusive == closed
assert result.dtype.subtype == expected_subtype
tm.assert_numpy_array_equal(np.array(result), expected_values)
@@ -184,9 +184,9 @@ def test_generic_errors(self, constructor):
filler = self.get_kwargs_from_breaks(range(10))
# invalid closed
- msg = "closed must be one of 'right', 'left', 'both', 'neither'"
+ msg = "inclusive must be one of 'right', 'left', 'both', 'neither'"
with pytest.raises(ValueError, match=msg):
- constructor(closed="invalid", **filler)
+ constructor(inclusive="invalid", **filler)
# unsupported dtype
msg = "dtype must be an IntervalDtype, got int64"
@@ -219,7 +219,7 @@ class TestFromArrays(ConstructorTests):
def constructor(self):
return IntervalIndex.from_arrays
- def get_kwargs_from_breaks(self, breaks, closed="right"):
+ def get_kwargs_from_breaks(self, breaks, inclusive="both"):
"""
converts intervals in breaks format to a dictionary of kwargs to
specific to the format expected by IntervalIndex.from_arrays
@@ -268,7 +268,7 @@ class TestFromBreaks(ConstructorTests):
def constructor(self):
return IntervalIndex.from_breaks
- def get_kwargs_from_breaks(self, breaks, closed="right"):
+ def get_kwargs_from_breaks(self, breaks, inclusive="both"):
"""
converts intervals in breaks format to a dictionary of kwargs to
specific to the format expected by IntervalIndex.from_breaks
@@ -306,7 +306,7 @@ class TestFromTuples(ConstructorTests):
def constructor(self):
return IntervalIndex.from_tuples
- def get_kwargs_from_breaks(self, breaks, closed="right"):
+ def get_kwargs_from_breaks(self, breaks, inclusive="both"):
"""
converts intervals in breaks format to a dictionary of kwargs to
specific to the format expected by IntervalIndex.from_tuples
@@ -356,7 +356,7 @@ class TestClassConstructors(ConstructorTests):
def constructor(self, request):
return request.param
- def get_kwargs_from_breaks(self, breaks, closed="right"):
+ def get_kwargs_from_breaks(self, breaks, inclusive="both"):
"""
converts intervals in breaks format to a dictionary of kwargs to
specific to the format expected by the IntervalIndex/Index constructors
@@ -365,7 +365,7 @@ def get_kwargs_from_breaks(self, breaks, closed="right"):
return {"data": breaks}
ivs = [
- Interval(left, right, closed) if notna(left) else left
+ Interval(left, right, inclusive) if notna(left) else left
for left, right in zip(breaks[:-1], breaks[1:])
]
@@ -390,7 +390,7 @@ def test_constructor_string(self):
def test_constructor_errors(self, constructor):
# mismatched closed within intervals with no constructor override
- ivs = [Interval(0, 1, closed="right"), Interval(2, 3, closed="left")]
+ ivs = [Interval(0, 1, inclusive="right"), Interval(2, 3, inclusive="left")]
msg = "intervals must all be closed on the same side"
with pytest.raises(ValueError, match=msg):
constructor(ivs)
@@ -415,14 +415,17 @@ def test_constructor_errors(self, constructor):
([], "both"),
([np.nan, np.nan], "neither"),
(
- [Interval(0, 3, closed="neither"), Interval(2, 5, closed="neither")],
+ [
+ Interval(0, 3, inclusive="neither"),
+ Interval(2, 5, inclusive="neither"),
+ ],
"left",
),
(
- [Interval(0, 3, closed="left"), Interval(2, 5, closed="right")],
+ [Interval(0, 3, inclusive="left"), Interval(2, 5, inclusive="right")],
"neither",
),
- (IntervalIndex.from_breaks(range(5), closed="both"), "right"),
+ (IntervalIndex.from_breaks(range(5), inclusive="both"), "right"),
],
)
def test_override_inferred_closed(self, constructor, data, closed):
@@ -431,8 +434,8 @@ def test_override_inferred_closed(self, constructor, data, closed):
tuples = data.to_tuples()
else:
tuples = [(iv.left, iv.right) if notna(iv) else iv for iv in data]
- expected = IntervalIndex.from_tuples(tuples, closed=closed)
- result = constructor(data, closed=closed)
+ expected = IntervalIndex.from_tuples(tuples, inclusive=closed)
+ result = constructor(data, inclusive=closed)
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize(
@@ -450,10 +453,10 @@ def test_index_object_dtype(self, values_constructor):
def test_index_mixed_closed(self):
# GH27172
intervals = [
- Interval(0, 1, closed="left"),
- Interval(1, 2, closed="right"),
- Interval(2, 3, closed="neither"),
- Interval(3, 4, closed="both"),
+ Interval(0, 1, inclusive="left"),
+ Interval(1, 2, inclusive="right"),
+ Interval(2, 3, inclusive="neither"),
+ Interval(3, 4, inclusive="both"),
]
result = Index(intervals)
expected = Index(intervals, dtype=object)
@@ -465,9 +468,9 @@ def test_dtype_closed_mismatch():
dtype = IntervalDtype(np.int64, "left")
- msg = "closed keyword does not match dtype.closed"
+ msg = "inclusive keyword does not match dtype.inclusive"
with pytest.raises(ValueError, match=msg):
- IntervalIndex([], dtype=dtype, closed="neither")
+ IntervalIndex([], dtype=dtype, inclusive="neither")
with pytest.raises(ValueError, match=msg):
- IntervalArray([], dtype=dtype, closed="neither")
+ IntervalArray([], dtype=dtype, inclusive="neither")
diff --git a/pandas/tests/indexes/interval/test_equals.py b/pandas/tests/indexes/interval/test_equals.py
index 87e2348e5fdb3..a873116600d6d 100644
--- a/pandas/tests/indexes/interval/test_equals.py
+++ b/pandas/tests/indexes/interval/test_equals.py
@@ -8,7 +8,7 @@
class TestEquals:
def test_equals(self, closed):
- expected = IntervalIndex.from_breaks(np.arange(5), closed=closed)
+ expected = IntervalIndex.from_breaks(np.arange(5), inclusive=closed)
assert expected.equals(expected)
assert expected.equals(expected.copy())
@@ -21,16 +21,16 @@ def test_equals(self, closed):
assert not expected.equals(date_range("20130101", periods=2))
expected_name1 = IntervalIndex.from_breaks(
- np.arange(5), closed=closed, name="foo"
+ np.arange(5), inclusive=closed, name="foo"
)
expected_name2 = IntervalIndex.from_breaks(
- np.arange(5), closed=closed, name="bar"
+ np.arange(5), inclusive=closed, name="bar"
)
assert expected.equals(expected_name1)
assert expected_name1.equals(expected_name2)
- for other_closed in {"left", "right", "both", "neither"} - {closed}:
- expected_other_closed = IntervalIndex.from_breaks(
- np.arange(5), closed=other_closed
+ for other_inclusive in {"left", "right", "both", "neither"} - {closed}:
+ expected_other_inclusive = IntervalIndex.from_breaks(
+ np.arange(5), inclusive=other_inclusive
)
- assert not expected.equals(expected_other_closed)
+ assert not expected.equals(expected_other_inclusive)
diff --git a/pandas/tests/indexes/interval/test_formats.py b/pandas/tests/indexes/interval/test_formats.py
index db477003900bc..2d9b8c83c7ab2 100644
--- a/pandas/tests/indexes/interval/test_formats.py
+++ b/pandas/tests/indexes/interval/test_formats.py
@@ -17,7 +17,8 @@ class TestIntervalIndexRendering:
def test_frame_repr(self):
# https://github.com/pandas-dev/pandas/pull/24134/files
df = DataFrame(
- {"A": [1, 2, 3, 4]}, index=IntervalIndex.from_breaks([0, 1, 2, 3, 4])
+ {"A": [1, 2, 3, 4]},
+ index=IntervalIndex.from_breaks([0, 1, 2, 3, 4], "right"),
)
result = repr(df)
expected = " A\n(0, 1] 1\n(1, 2] 2\n(2, 3] 3\n(3, 4] 4"
@@ -40,7 +41,7 @@ def test_frame_repr(self):
)
def test_repr_missing(self, constructor, expected):
# GH 25984
- index = IntervalIndex.from_tuples([(0, 1), np.nan, (2, 3)])
+ index = IntervalIndex.from_tuples([(0, 1), np.nan, (2, 3)], "right")
obj = constructor(list("abc"), index=index)
result = repr(obj)
assert result == expected
@@ -57,7 +58,8 @@ def test_repr_floats(self):
Float64Index([329.973, 345.137], dtype="float64"),
Float64Index([345.137, 360.191], dtype="float64"),
)
- ]
+ ],
+ "right",
),
)
result = str(markers)
@@ -65,7 +67,7 @@ def test_repr_floats(self):
assert result == expected
@pytest.mark.parametrize(
- "tuples, closed, expected_data",
+ "tuples, inclusive, expected_data",
[
([(0, 1), (1, 2), (2, 3)], "left", ["[0, 1)", "[1, 2)", "[2, 3)"]),
(
@@ -97,9 +99,9 @@ def test_repr_floats(self):
),
],
)
- def test_to_native_types(self, tuples, closed, expected_data):
+ def test_to_native_types(self, tuples, inclusive, expected_data):
# GH 28210
- index = IntervalIndex.from_tuples(tuples, closed=closed)
+ index = IntervalIndex.from_tuples(tuples, inclusive=inclusive)
result = index._format_native_types()
expected = np.array(expected_data)
tm.assert_numpy_array_equal(result, expected)
diff --git a/pandas/tests/indexes/interval/test_indexing.py b/pandas/tests/indexes/interval/test_indexing.py
index 7c00b23dc9ac4..4cf754a7e52e0 100644
--- a/pandas/tests/indexes/interval/test_indexing.py
+++ b/pandas/tests/indexes/interval/test_indexing.py
@@ -25,23 +25,23 @@ class TestGetLoc:
@pytest.mark.parametrize("side", ["right", "left", "both", "neither"])
def test_get_loc_interval(self, closed, side):
- idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
+ idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], inclusive=closed)
for bound in [[0, 1], [1, 2], [2, 3], [3, 4], [0, 2], [2.5, 3], [-1, 4]]:
# if get_loc is supplied an interval, it should only search
# for exact matches, not overlaps or covers, else KeyError.
- msg = re.escape(f"Interval({bound[0]}, {bound[1]}, closed='{side}')")
+ msg = re.escape(f"Interval({bound[0]}, {bound[1]}, inclusive='{side}')")
if closed == side:
if bound == [0, 1]:
- assert idx.get_loc(Interval(0, 1, closed=side)) == 0
+ assert idx.get_loc(Interval(0, 1, inclusive=side)) == 0
elif bound == [2, 3]:
- assert idx.get_loc(Interval(2, 3, closed=side)) == 1
+ assert idx.get_loc(Interval(2, 3, inclusive=side)) == 1
else:
with pytest.raises(KeyError, match=msg):
- idx.get_loc(Interval(*bound, closed=side))
+ idx.get_loc(Interval(*bound, inclusive=side))
else:
with pytest.raises(KeyError, match=msg):
- idx.get_loc(Interval(*bound, closed=side))
+ idx.get_loc(Interval(*bound, inclusive=side))
@pytest.mark.parametrize("scalar", [-0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5])
def test_get_loc_scalar(self, closed, scalar):
@@ -55,7 +55,7 @@ def test_get_loc_scalar(self, closed, scalar):
"neither": {0.5: 0, 2.5: 1},
}
- idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
+ idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], inclusive=closed)
# if get_loc is supplied a scalar, it should return the index of
# the interval which contains the scalar, or KeyError.
@@ -68,7 +68,7 @@ def test_get_loc_scalar(self, closed, scalar):
@pytest.mark.parametrize("scalar", [-1, 0, 0.5, 3, 4.5, 5, 6])
def test_get_loc_length_one_scalar(self, scalar, closed):
# GH 20921
- index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
+ index = IntervalIndex.from_tuples([(0, 5)], inclusive=closed)
if scalar in index[0]:
result = index.get_loc(scalar)
assert result == 0
@@ -80,15 +80,17 @@ def test_get_loc_length_one_scalar(self, scalar, closed):
@pytest.mark.parametrize("left, right", [(0, 5), (-1, 4), (-1, 6), (6, 7)])
def test_get_loc_length_one_interval(self, left, right, closed, other_closed):
# GH 20921
- index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
- interval = Interval(left, right, closed=other_closed)
+ index = IntervalIndex.from_tuples([(0, 5)], inclusive=closed)
+ interval = Interval(left, right, inclusive=other_closed)
if interval == index[0]:
result = index.get_loc(interval)
assert result == 0
else:
with pytest.raises(
KeyError,
- match=re.escape(f"Interval({left}, {right}, closed='{other_closed}')"),
+ match=re.escape(
+ f"Interval({left}, {right}, inclusive='{other_closed}')"
+ ),
):
index.get_loc(interval)
@@ -192,23 +194,35 @@ class TestGetIndexer:
@pytest.mark.parametrize(
"query, expected",
[
- ([Interval(2, 4, closed="right")], [1]),
- ([Interval(2, 4, closed="left")], [-1]),
- ([Interval(2, 4, closed="both")], [-1]),
- ([Interval(2, 4, closed="neither")], [-1]),
- ([Interval(1, 4, closed="right")], [-1]),
- ([Interval(0, 4, closed="right")], [-1]),
- ([Interval(0.5, 1.5, closed="right")], [-1]),
- ([Interval(2, 4, closed="right"), Interval(0, 1, closed="right")], [1, -1]),
- ([Interval(2, 4, closed="right"), Interval(2, 4, closed="right")], [1, 1]),
- ([Interval(5, 7, closed="right"), Interval(2, 4, closed="right")], [2, 1]),
- ([Interval(2, 4, closed="right"), Interval(2, 4, closed="left")], [1, -1]),
+ ([Interval(2, 4, inclusive="right")], [1]),
+ ([Interval(2, 4, inclusive="left")], [-1]),
+ ([Interval(2, 4, inclusive="both")], [-1]),
+ ([Interval(2, 4, inclusive="neither")], [-1]),
+ ([Interval(1, 4, inclusive="right")], [-1]),
+ ([Interval(0, 4, inclusive="right")], [-1]),
+ ([Interval(0.5, 1.5, inclusive="right")], [-1]),
+ (
+ [Interval(2, 4, inclusive="right"), Interval(0, 1, inclusive="right")],
+ [1, -1],
+ ),
+ (
+ [Interval(2, 4, inclusive="right"), Interval(2, 4, inclusive="right")],
+ [1, 1],
+ ),
+ (
+ [Interval(5, 7, inclusive="right"), Interval(2, 4, inclusive="right")],
+ [2, 1],
+ ),
+ (
+ [Interval(2, 4, inclusive="right"), Interval(2, 4, inclusive="left")],
+ [1, -1],
+ ),
],
)
def test_get_indexer_with_interval(self, query, expected):
tuples = [(0, 2), (2, 4), (5, 7)]
- index = IntervalIndex.from_tuples(tuples, closed="right")
+ index = IntervalIndex.from_tuples(tuples, inclusive="right")
result = index.get_indexer(query)
expected = np.array(expected, dtype="intp")
@@ -237,7 +251,7 @@ def test_get_indexer_with_interval(self, query, expected):
def test_get_indexer_with_int_and_float(self, query, expected):
tuples = [(0, 1), (1, 2), (3, 4)]
- index = IntervalIndex.from_tuples(tuples, closed="right")
+ index = IntervalIndex.from_tuples(tuples, inclusive="right")
result = index.get_indexer(query)
expected = np.array(expected, dtype="intp")
@@ -246,7 +260,7 @@ def test_get_indexer_with_int_and_float(self, query, expected):
@pytest.mark.parametrize("item", [[3], np.arange(0.5, 5, 0.5)])
def test_get_indexer_length_one(self, item, closed):
# GH 17284
- index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
+ index = IntervalIndex.from_tuples([(0, 5)], inclusive=closed)
result = index.get_indexer(item)
expected = np.array([0] * len(item), dtype="intp")
tm.assert_numpy_array_equal(result, expected)
@@ -254,7 +268,7 @@ def test_get_indexer_length_one(self, item, closed):
@pytest.mark.parametrize("size", [1, 5])
def test_get_indexer_length_one_interval(self, size, closed):
# GH 17284
- index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
+ index = IntervalIndex.from_tuples([(0, 5)], inclusive=closed)
result = index.get_indexer([Interval(0, 5, closed)] * size)
expected = np.array([0] * size, dtype="intp")
tm.assert_numpy_array_equal(result, expected)
@@ -264,14 +278,14 @@ def test_get_indexer_length_one_interval(self, size, closed):
[
IntervalIndex.from_tuples([(7, 8), (1, 2), (3, 4), (0, 1)]),
IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4), np.nan]),
- IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)], closed="both"),
+ IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)], inclusive="both"),
[-1, 0, 0.5, 1, 2, 2.5, np.nan],
["foo", "foo", "bar", "baz"],
],
)
def test_get_indexer_categorical(self, target, ordered):
# GH 30063: categorical and non-categorical results should be consistent
- index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)])
+ index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)], inclusive="right")
categorical_target = CategoricalIndex(target, ordered=ordered)
result = index.get_indexer(categorical_target)
@@ -280,7 +294,7 @@ def test_get_indexer_categorical(self, target, ordered):
def test_get_indexer_categorical_with_nans(self):
# GH#41934 nans in both index and in target
- ii = IntervalIndex.from_breaks(range(5))
+ ii = IntervalIndex.from_breaks(range(5), inclusive="right")
ii2 = ii.append(IntervalIndex([np.nan]))
ci2 = CategoricalIndex(ii2)
@@ -299,7 +313,7 @@ def test_get_indexer_categorical_with_nans(self):
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize(
- "tuples, closed",
+ "tuples, inclusive",
[
([(0, 2), (1, 3), (3, 4)], "neither"),
([(0, 5), (1, 4), (6, 7)], "left"),
@@ -307,9 +321,9 @@ def test_get_indexer_categorical_with_nans(self):
([(0, 1), (2, 3), (3, 4)], "both"),
],
)
- def test_get_indexer_errors(self, tuples, closed):
+ def test_get_indexer_errors(self, tuples, inclusive):
# IntervalIndex needs non-overlapping for uniqueness when querying
- index = IntervalIndex.from_tuples(tuples, closed=closed)
+ index = IntervalIndex.from_tuples(tuples, inclusive=inclusive)
msg = (
"cannot handle overlapping indices; use "
@@ -341,7 +355,7 @@ def test_get_indexer_errors(self, tuples, closed):
def test_get_indexer_non_unique_with_int_and_float(self, query, expected):
tuples = [(0, 2.5), (1, 3), (2, 4)]
- index = IntervalIndex.from_tuples(tuples, closed="left")
+ index = IntervalIndex.from_tuples(tuples, inclusive="left")
result_indexer, result_missing = index.get_indexer_non_unique(query)
expected_indexer = np.array(expected[0], dtype="intp")
@@ -433,45 +447,45 @@ def test_slice_locs_with_interval(self):
assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2)
# unsorted duplicates
- index = IntervalIndex.from_tuples([(0, 2), (2, 4), (0, 2)])
+ index = IntervalIndex.from_tuples([(0, 2), (2, 4), (0, 2)], "right")
with pytest.raises(
KeyError,
match=re.escape(
'"Cannot get left slice bound for non-unique label: '
- "Interval(0, 2, closed='right')\""
+ "Interval(0, 2, inclusive='right')\""
),
):
- index.slice_locs(start=Interval(0, 2), end=Interval(2, 4))
+ index.slice_locs(start=Interval(0, 2, "right"), end=Interval(2, 4, "right"))
with pytest.raises(
KeyError,
match=re.escape(
'"Cannot get left slice bound for non-unique label: '
- "Interval(0, 2, closed='right')\""
+ "Interval(0, 2, inclusive='right')\""
),
):
- index.slice_locs(start=Interval(0, 2))
+ index.slice_locs(start=Interval(0, 2, "right"))
- assert index.slice_locs(end=Interval(2, 4)) == (0, 2)
+ assert index.slice_locs(end=Interval(2, 4, "right")) == (0, 2)
with pytest.raises(
KeyError,
match=re.escape(
'"Cannot get right slice bound for non-unique label: '
- "Interval(0, 2, closed='right')\""
+ "Interval(0, 2, inclusive='right')\""
),
):
- index.slice_locs(end=Interval(0, 2))
+ index.slice_locs(end=Interval(0, 2, "right"))
with pytest.raises(
KeyError,
match=re.escape(
'"Cannot get right slice bound for non-unique label: '
- "Interval(0, 2, closed='right')\""
+ "Interval(0, 2, inclusive='right')\""
),
):
- index.slice_locs(start=Interval(2, 4), end=Interval(0, 2))
+ index.slice_locs(start=Interval(2, 4, "right"), end=Interval(0, 2, "right"))
# another unsorted duplicates
index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4), (1, 3)])
@@ -485,7 +499,7 @@ def test_slice_locs_with_interval(self):
def test_slice_locs_with_ints_and_floats_succeeds(self):
# increasing non-overlapping
- index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)])
+ index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)], inclusive="right")
assert index.slice_locs(0, 1) == (0, 1)
assert index.slice_locs(0, 2) == (0, 2)
@@ -495,7 +509,7 @@ def test_slice_locs_with_ints_and_floats_succeeds(self):
assert index.slice_locs(0, 4) == (0, 3)
# decreasing non-overlapping
- index = IntervalIndex.from_tuples([(3, 4), (1, 2), (0, 1)])
+ index = IntervalIndex.from_tuples([(3, 4), (1, 2), (0, 1)], inclusive="right")
assert index.slice_locs(0, 1) == (3, 3)
assert index.slice_locs(0, 2) == (3, 2)
assert index.slice_locs(0, 3) == (3, 1)
@@ -516,7 +530,7 @@ def test_slice_locs_with_ints_and_floats_succeeds(self):
)
def test_slice_locs_with_ints_and_floats_errors(self, tuples, query):
start, stop = query
- index = IntervalIndex.from_tuples(tuples)
+ index = IntervalIndex.from_tuples(tuples, inclusive="right")
with pytest.raises(
KeyError,
match=(
@@ -571,17 +585,17 @@ class TestContains:
def test_contains_dunder(self):
- index = IntervalIndex.from_arrays([0, 1], [1, 2], closed="right")
+ index = IntervalIndex.from_arrays([0, 1], [1, 2], inclusive="right")
# __contains__ requires perfect matches to intervals.
assert 0 not in index
assert 1 not in index
assert 2 not in index
- assert Interval(0, 1, closed="right") in index
- assert Interval(0, 2, closed="right") not in index
- assert Interval(0, 0.5, closed="right") not in index
- assert Interval(3, 5, closed="right") not in index
- assert Interval(-1, 0, closed="left") not in index
- assert Interval(0, 1, closed="left") not in index
- assert Interval(0, 1, closed="both") not in index
+ assert Interval(0, 1, inclusive="right") in index
+ assert Interval(0, 2, inclusive="right") not in index
+ assert Interval(0, 0.5, inclusive="right") not in index
+ assert Interval(3, 5, inclusive="right") not in index
+ assert Interval(-1, 0, inclusive="left") not in index
+ assert Interval(0, 1, inclusive="left") not in index
+ assert Interval(0, 1, inclusive="both") not in index
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 8880cab2ce29b..4e33c3abd3252 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -28,21 +28,21 @@ def name(request):
class TestIntervalIndex:
- index = IntervalIndex.from_arrays([0, 1], [1, 2])
+ index = IntervalIndex.from_arrays([0, 1], [1, 2], "right")
- def create_index(self, closed="right"):
- return IntervalIndex.from_breaks(range(11), closed=closed)
+ def create_index(self, inclusive="right"):
+ return IntervalIndex.from_breaks(range(11), inclusive=inclusive)
- def create_index_with_nan(self, closed="right"):
+ def create_index_with_nan(self, inclusive="right"):
mask = [True, False] + [True] * 8
return IntervalIndex.from_arrays(
np.where(mask, np.arange(10), np.nan),
np.where(mask, np.arange(1, 11), np.nan),
- closed=closed,
+ inclusive=inclusive,
)
def test_properties(self, closed):
- index = self.create_index(closed=closed)
+ index = self.create_index(inclusive=closed)
assert len(index) == 10
assert index.size == 10
assert index.shape == (10,)
@@ -51,7 +51,7 @@ def test_properties(self, closed):
tm.assert_index_equal(index.right, Index(np.arange(1, 11)))
tm.assert_index_equal(index.mid, Index(np.arange(0.5, 10.5)))
- assert index.closed == closed
+ assert index.inclusive == closed
ivs = [
Interval(left, right, closed)
@@ -61,7 +61,7 @@ def test_properties(self, closed):
tm.assert_numpy_array_equal(np.asarray(index), expected)
# with nans
- index = self.create_index_with_nan(closed=closed)
+ index = self.create_index_with_nan(inclusive=closed)
assert len(index) == 10
assert index.size == 10
assert index.shape == (10,)
@@ -73,7 +73,7 @@ def test_properties(self, closed):
tm.assert_index_equal(index.right, expected_right)
tm.assert_index_equal(index.mid, expected_mid)
- assert index.closed == closed
+ assert index.inclusive == closed
ivs = [
Interval(left, right, closed) if notna(left) else np.nan
@@ -93,7 +93,7 @@ def test_properties(self, closed):
)
def test_length(self, closed, breaks):
# GH 18789
- index = IntervalIndex.from_breaks(breaks, closed=closed)
+ index = IntervalIndex.from_breaks(breaks, inclusive=closed)
result = index.length
expected = Index(iv.length for iv in index)
tm.assert_index_equal(result, expected)
@@ -105,7 +105,7 @@ def test_length(self, closed, breaks):
tm.assert_index_equal(result, expected)
def test_with_nans(self, closed):
- index = self.create_index(closed=closed)
+ index = self.create_index(inclusive=closed)
assert index.hasnans is False
result = index.isna()
@@ -116,7 +116,7 @@ def test_with_nans(self, closed):
expected = np.ones(len(index), dtype=bool)
tm.assert_numpy_array_equal(result, expected)
- index = self.create_index_with_nan(closed=closed)
+ index = self.create_index_with_nan(inclusive=closed)
assert index.hasnans is True
result = index.isna()
@@ -128,7 +128,7 @@ def test_with_nans(self, closed):
tm.assert_numpy_array_equal(result, expected)
def test_copy(self, closed):
- expected = self.create_index(closed=closed)
+ expected = self.create_index(inclusive=closed)
result = expected.copy()
assert result.equals(expected)
@@ -141,7 +141,7 @@ def test_ensure_copied_data(self, closed):
# exercise the copy flag in the constructor
# not copying
- index = self.create_index(closed=closed)
+ index = self.create_index(inclusive=closed)
result = IntervalIndex(index, copy=False)
tm.assert_numpy_array_equal(
index.left.values, result.left.values, check_same="same"
@@ -160,8 +160,8 @@ def test_ensure_copied_data(self, closed):
)
def test_delete(self, closed):
- expected = IntervalIndex.from_breaks(np.arange(1, 11), closed=closed)
- result = self.create_index(closed=closed).delete(0)
+ expected = IntervalIndex.from_breaks(np.arange(1, 11), inclusive=closed)
+ result = self.create_index(inclusive=closed).delete(0)
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize(
@@ -201,11 +201,11 @@ def test_insert(self, data):
with pytest.raises(TypeError, match=msg):
data._data.insert(1, "foo")
- # invalid closed
- msg = "'value.closed' is 'left', expected 'right'."
- for closed in {"left", "right", "both", "neither"} - {item.closed}:
- msg = f"'value.closed' is '{closed}', expected '{item.closed}'."
- bad_item = Interval(item.left, item.right, closed=closed)
+ # invalid inclusive
+ msg = "'value.inclusive' is 'left', expected 'right'."
+ for inclusive in {"left", "right", "both", "neither"} - {item.inclusive}:
+ msg = f"'value.inclusive' is '{inclusive}', expected '{item.inclusive}'."
+ bad_item = Interval(item.left, item.right, inclusive=inclusive)
res = data.insert(1, bad_item)
expected = data.astype(object).insert(1, bad_item)
tm.assert_index_equal(res, expected)
@@ -213,7 +213,7 @@ def test_insert(self, data):
data._data.insert(1, bad_item)
# GH 18295 (test missing)
- na_idx = IntervalIndex([np.nan], closed=data.closed)
+ na_idx = IntervalIndex([np.nan], inclusive=data.inclusive)
for na in [np.nan, None, pd.NA]:
expected = data[:1].append(na_idx).append(data[1:])
result = data.insert(1, na)
@@ -235,93 +235,93 @@ def test_is_unique_interval(self, closed):
Interval specific tests for is_unique in addition to base class tests
"""
# unique overlapping - distinct endpoints
- idx = IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)], closed=closed)
+ idx = IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)], inclusive=closed)
assert idx.is_unique is True
# unique overlapping - shared endpoints
- idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
+ idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], inclusive=closed)
assert idx.is_unique is True
# unique nested
- idx = IntervalIndex.from_tuples([(-1, 1), (-2, 2)], closed=closed)
+ idx = IntervalIndex.from_tuples([(-1, 1), (-2, 2)], inclusive=closed)
assert idx.is_unique is True
# unique NaN
- idx = IntervalIndex.from_tuples([(np.NaN, np.NaN)], closed=closed)
+ idx = IntervalIndex.from_tuples([(np.NaN, np.NaN)], inclusive=closed)
assert idx.is_unique is True
# non-unique NaN
idx = IntervalIndex.from_tuples(
- [(np.NaN, np.NaN), (np.NaN, np.NaN)], closed=closed
+ [(np.NaN, np.NaN), (np.NaN, np.NaN)], inclusive=closed
)
assert idx.is_unique is False
def test_monotonic(self, closed):
# increasing non-overlapping
- idx = IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)], closed=closed)
+ idx = IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)], inclusive=closed)
assert idx.is_monotonic_increasing is True
assert idx._is_strictly_monotonic_increasing is True
assert idx.is_monotonic_decreasing is False
assert idx._is_strictly_monotonic_decreasing is False
# decreasing non-overlapping
- idx = IntervalIndex.from_tuples([(4, 5), (2, 3), (1, 2)], closed=closed)
+ idx = IntervalIndex.from_tuples([(4, 5), (2, 3), (1, 2)], inclusive=closed)
assert idx.is_monotonic_increasing is False
assert idx._is_strictly_monotonic_increasing is False
assert idx.is_monotonic_decreasing is True
assert idx._is_strictly_monotonic_decreasing is True
# unordered non-overlapping
- idx = IntervalIndex.from_tuples([(0, 1), (4, 5), (2, 3)], closed=closed)
+ idx = IntervalIndex.from_tuples([(0, 1), (4, 5), (2, 3)], inclusive=closed)
assert idx.is_monotonic_increasing is False
assert idx._is_strictly_monotonic_increasing is False
assert idx.is_monotonic_decreasing is False
assert idx._is_strictly_monotonic_decreasing is False
# increasing overlapping
- idx = IntervalIndex.from_tuples([(0, 2), (0.5, 2.5), (1, 3)], closed=closed)
+ idx = IntervalIndex.from_tuples([(0, 2), (0.5, 2.5), (1, 3)], inclusive=closed)
assert idx.is_monotonic_increasing is True
assert idx._is_strictly_monotonic_increasing is True
assert idx.is_monotonic_decreasing is False
assert idx._is_strictly_monotonic_decreasing is False
# decreasing overlapping
- idx = IntervalIndex.from_tuples([(1, 3), (0.5, 2.5), (0, 2)], closed=closed)
+ idx = IntervalIndex.from_tuples([(1, 3), (0.5, 2.5), (0, 2)], inclusive=closed)
assert idx.is_monotonic_increasing is False
assert idx._is_strictly_monotonic_increasing is False
assert idx.is_monotonic_decreasing is True
assert idx._is_strictly_monotonic_decreasing is True
# unordered overlapping
- idx = IntervalIndex.from_tuples([(0.5, 2.5), (0, 2), (1, 3)], closed=closed)
+ idx = IntervalIndex.from_tuples([(0.5, 2.5), (0, 2), (1, 3)], inclusive=closed)
assert idx.is_monotonic_increasing is False
assert idx._is_strictly_monotonic_increasing is False
assert idx.is_monotonic_decreasing is False
assert idx._is_strictly_monotonic_decreasing is False
# increasing overlapping shared endpoints
- idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
+ idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], inclusive=closed)
assert idx.is_monotonic_increasing is True
assert idx._is_strictly_monotonic_increasing is True
assert idx.is_monotonic_decreasing is False
assert idx._is_strictly_monotonic_decreasing is False
# decreasing overlapping shared endpoints
- idx = IntervalIndex.from_tuples([(2, 3), (1, 3), (1, 2)], closed=closed)
+ idx = IntervalIndex.from_tuples([(2, 3), (1, 3), (1, 2)], inclusive=closed)
assert idx.is_monotonic_increasing is False
assert idx._is_strictly_monotonic_increasing is False
assert idx.is_monotonic_decreasing is True
assert idx._is_strictly_monotonic_decreasing is True
# stationary
- idx = IntervalIndex.from_tuples([(0, 1), (0, 1)], closed=closed)
+ idx = IntervalIndex.from_tuples([(0, 1), (0, 1)], inclusive=closed)
assert idx.is_monotonic_increasing is True
assert idx._is_strictly_monotonic_increasing is False
assert idx.is_monotonic_decreasing is True
assert idx._is_strictly_monotonic_decreasing is False
# empty
- idx = IntervalIndex([], closed=closed)
+ idx = IntervalIndex([], inclusive=closed)
assert idx.is_monotonic_increasing is True
assert idx._is_strictly_monotonic_increasing is True
assert idx.is_monotonic_decreasing is True
@@ -338,22 +338,22 @@ def test_is_monotonic_with_nans(self):
assert not index.is_monotonic_decreasing
def test_get_item(self, closed):
- i = IntervalIndex.from_arrays((0, 1, np.nan), (1, 2, np.nan), closed=closed)
- assert i[0] == Interval(0.0, 1.0, closed=closed)
- assert i[1] == Interval(1.0, 2.0, closed=closed)
+ i = IntervalIndex.from_arrays((0, 1, np.nan), (1, 2, np.nan), inclusive=closed)
+ assert i[0] == Interval(0.0, 1.0, inclusive=closed)
+ assert i[1] == Interval(1.0, 2.0, inclusive=closed)
assert isna(i[2])
result = i[0:1]
- expected = IntervalIndex.from_arrays((0.0,), (1.0,), closed=closed)
+ expected = IntervalIndex.from_arrays((0.0,), (1.0,), inclusive=closed)
tm.assert_index_equal(result, expected)
result = i[0:2]
- expected = IntervalIndex.from_arrays((0.0, 1), (1.0, 2.0), closed=closed)
+ expected = IntervalIndex.from_arrays((0.0, 1), (1.0, 2.0), inclusive=closed)
tm.assert_index_equal(result, expected)
result = i[1:3]
expected = IntervalIndex.from_arrays(
- (1.0, np.nan), (2.0, np.nan), closed=closed
+ (1.0, np.nan), (2.0, np.nan), inclusive=closed
)
tm.assert_index_equal(result, expected)
@@ -477,7 +477,7 @@ def test_maybe_convert_i8_errors(self, breaks1, breaks2, make_key):
def test_contains_method(self):
# can select values that are IN the range of a value
- i = IntervalIndex.from_arrays([0, 1], [1, 2])
+ i = IntervalIndex.from_arrays([0, 1], [1, 2], "right")
expected = np.array([False, False], dtype="bool")
actual = i.contains(0)
@@ -500,18 +500,18 @@ def test_contains_method(self):
def test_dropna(self, closed):
- expected = IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)], closed=closed)
+ expected = IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)], inclusive=closed)
- ii = IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan], closed=closed)
+ ii = IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan], inclusive=closed)
result = ii.dropna()
tm.assert_index_equal(result, expected)
- ii = IntervalIndex.from_arrays([0, 1, np.nan], [1, 2, np.nan], closed=closed)
+ ii = IntervalIndex.from_arrays([0, 1, np.nan], [1, 2, np.nan], inclusive=closed)
result = ii.dropna()
tm.assert_index_equal(result, expected)
def test_non_contiguous(self, closed):
- index = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
+ index = IntervalIndex.from_tuples([(0, 1), (2, 3)], inclusive=closed)
target = [0.5, 1.5, 2.5]
actual = index.get_indexer(target)
expected = np.array([0, -1, 1], dtype="intp")
@@ -520,7 +520,7 @@ def test_non_contiguous(self, closed):
assert 1.5 not in index
def test_isin(self, closed):
- index = self.create_index(closed=closed)
+ index = self.create_index(inclusive=closed)
expected = np.array([True] + [False] * (len(index) - 1))
result = index.isin(index[:1])
@@ -529,7 +529,7 @@ def test_isin(self, closed):
result = index.isin([index[0]])
tm.assert_numpy_array_equal(result, expected)
- other = IntervalIndex.from_breaks(np.arange(-2, 10), closed=closed)
+ other = IntervalIndex.from_breaks(np.arange(-2, 10), inclusive=closed)
expected = np.array([True] * (len(index) - 1) + [False])
result = index.isin(other)
tm.assert_numpy_array_equal(result, expected)
@@ -537,9 +537,9 @@ def test_isin(self, closed):
result = index.isin(other.tolist())
tm.assert_numpy_array_equal(result, expected)
- for other_closed in {"right", "left", "both", "neither"}:
- other = self.create_index(closed=other_closed)
- expected = np.repeat(closed == other_closed, len(index))
+ for other_inclusive in {"right", "left", "both", "neither"}:
+ other = self.create_index(inclusive=other_inclusive)
+ expected = np.repeat(closed == other_inclusive, len(index))
result = index.isin(other)
tm.assert_numpy_array_equal(result, expected)
@@ -547,14 +547,14 @@ def test_isin(self, closed):
tm.assert_numpy_array_equal(result, expected)
def test_comparison(self):
- actual = Interval(0, 1) < self.index
+ actual = Interval(0, 1, "right") < self.index
expected = np.array([False, True])
tm.assert_numpy_array_equal(actual, expected)
- actual = Interval(0.5, 1.5) < self.index
+ actual = Interval(0.5, 1.5, "right") < self.index
expected = np.array([False, True])
tm.assert_numpy_array_equal(actual, expected)
- actual = self.index > Interval(0.5, 1.5)
+ actual = self.index > Interval(0.5, 1.5, "right")
tm.assert_numpy_array_equal(actual, expected)
actual = self.index == self.index
@@ -612,9 +612,11 @@ def test_comparison(self):
def test_missing_values(self, closed):
idx = Index(
- [np.nan, Interval(0, 1, closed=closed), Interval(1, 2, closed=closed)]
+ [np.nan, Interval(0, 1, inclusive=closed), Interval(1, 2, inclusive=closed)]
+ )
+ idx2 = IntervalIndex.from_arrays(
+ [np.nan, 0, 1], [np.nan, 1, 2], inclusive=closed
)
- idx2 = IntervalIndex.from_arrays([np.nan, 0, 1], [np.nan, 1, 2], closed=closed)
assert idx.equals(idx2)
msg = (
@@ -623,13 +625,13 @@ def test_missing_values(self, closed):
)
with pytest.raises(ValueError, match=msg):
IntervalIndex.from_arrays(
- [np.nan, 0, 1], np.array([0, 1, 2]), closed=closed
+ [np.nan, 0, 1], np.array([0, 1, 2]), inclusive=closed
)
tm.assert_numpy_array_equal(isna(idx), np.array([True, False, False]))
def test_sort_values(self, closed):
- index = self.create_index(closed=closed)
+ index = self.create_index(inclusive=closed)
result = index.sort_values()
tm.assert_index_equal(result, index)
@@ -652,7 +654,7 @@ def test_sort_values(self, closed):
def test_datetime(self, tz):
start = Timestamp("2000-01-01", tz=tz)
dates = date_range(start=start, periods=10)
- index = IntervalIndex.from_breaks(dates)
+ index = IntervalIndex.from_breaks(dates, "right")
# test mid
start = Timestamp("2000-01-01T12:00", tz=tz)
@@ -664,10 +666,10 @@ def test_datetime(self, tz):
assert Timestamp("2000-01-01T12", tz=tz) not in index
assert Timestamp("2000-01-02", tz=tz) not in index
iv_true = Interval(
- Timestamp("2000-01-02", tz=tz), Timestamp("2000-01-03", tz=tz)
+ Timestamp("2000-01-02", tz=tz), Timestamp("2000-01-03", tz=tz), "right"
)
iv_false = Interval(
- Timestamp("1999-12-31", tz=tz), Timestamp("2000-01-01", tz=tz)
+ Timestamp("1999-12-31", tz=tz), Timestamp("2000-01-01", tz=tz), "right"
)
assert iv_true in index
assert iv_false not in index
@@ -692,58 +694,62 @@ def test_datetime(self, tz):
def test_append(self, closed):
- index1 = IntervalIndex.from_arrays([0, 1], [1, 2], closed=closed)
- index2 = IntervalIndex.from_arrays([1, 2], [2, 3], closed=closed)
+ index1 = IntervalIndex.from_arrays([0, 1], [1, 2], inclusive=closed)
+ index2 = IntervalIndex.from_arrays([1, 2], [2, 3], inclusive=closed)
result = index1.append(index2)
- expected = IntervalIndex.from_arrays([0, 1, 1, 2], [1, 2, 2, 3], closed=closed)
+ expected = IntervalIndex.from_arrays(
+ [0, 1, 1, 2], [1, 2, 2, 3], inclusive=closed
+ )
tm.assert_index_equal(result, expected)
result = index1.append([index1, index2])
expected = IntervalIndex.from_arrays(
- [0, 1, 0, 1, 1, 2], [1, 2, 1, 2, 2, 3], closed=closed
+ [0, 1, 0, 1, 1, 2], [1, 2, 1, 2, 2, 3], inclusive=closed
)
tm.assert_index_equal(result, expected)
- for other_closed in {"left", "right", "both", "neither"} - {closed}:
- index_other_closed = IntervalIndex.from_arrays(
- [0, 1], [1, 2], closed=other_closed
+ for other_inclusive in {"left", "right", "both", "neither"} - {closed}:
+ index_other_inclusive = IntervalIndex.from_arrays(
+ [0, 1], [1, 2], inclusive=other_inclusive
+ )
+ result = index1.append(index_other_inclusive)
+ expected = index1.astype(object).append(
+ index_other_inclusive.astype(object)
)
- result = index1.append(index_other_closed)
- expected = index1.astype(object).append(index_other_closed.astype(object))
tm.assert_index_equal(result, expected)
def test_is_non_overlapping_monotonic(self, closed):
# Should be True in all cases
tpls = [(0, 1), (2, 3), (4, 5), (6, 7)]
- idx = IntervalIndex.from_tuples(tpls, closed=closed)
+ idx = IntervalIndex.from_tuples(tpls, inclusive=closed)
assert idx.is_non_overlapping_monotonic is True
- idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
+ idx = IntervalIndex.from_tuples(tpls[::-1], inclusive=closed)
assert idx.is_non_overlapping_monotonic is True
# Should be False in all cases (overlapping)
tpls = [(0, 2), (1, 3), (4, 5), (6, 7)]
- idx = IntervalIndex.from_tuples(tpls, closed=closed)
+ idx = IntervalIndex.from_tuples(tpls, inclusive=closed)
assert idx.is_non_overlapping_monotonic is False
- idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
+ idx = IntervalIndex.from_tuples(tpls[::-1], inclusive=closed)
assert idx.is_non_overlapping_monotonic is False
# Should be False in all cases (non-monotonic)
tpls = [(0, 1), (2, 3), (6, 7), (4, 5)]
- idx = IntervalIndex.from_tuples(tpls, closed=closed)
+ idx = IntervalIndex.from_tuples(tpls, inclusive=closed)
assert idx.is_non_overlapping_monotonic is False
- idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
+ idx = IntervalIndex.from_tuples(tpls[::-1], inclusive=closed)
assert idx.is_non_overlapping_monotonic is False
- # Should be False for closed='both', otherwise True (GH16560)
+ # Should be False for inclusive='both', otherwise True (GH16560)
if closed == "both":
- idx = IntervalIndex.from_breaks(range(4), closed=closed)
+ idx = IntervalIndex.from_breaks(range(4), inclusive=closed)
assert idx.is_non_overlapping_monotonic is False
else:
- idx = IntervalIndex.from_breaks(range(4), closed=closed)
+ idx = IntervalIndex.from_breaks(range(4), inclusive=closed)
assert idx.is_non_overlapping_monotonic is True
@pytest.mark.parametrize(
@@ -760,34 +766,34 @@ def test_is_overlapping(self, start, shift, na_value, closed):
# non-overlapping
tuples = [(start + n * shift, start + (n + 1) * shift) for n in (0, 2, 4)]
- index = IntervalIndex.from_tuples(tuples, closed=closed)
+ index = IntervalIndex.from_tuples(tuples, inclusive=closed)
assert index.is_overlapping is False
# non-overlapping with NA
tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
- index = IntervalIndex.from_tuples(tuples, closed=closed)
+ index = IntervalIndex.from_tuples(tuples, inclusive=closed)
assert index.is_overlapping is False
# overlapping
tuples = [(start + n * shift, start + (n + 2) * shift) for n in range(3)]
- index = IntervalIndex.from_tuples(tuples, closed=closed)
+ index = IntervalIndex.from_tuples(tuples, inclusive=closed)
assert index.is_overlapping is True
# overlapping with NA
tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
- index = IntervalIndex.from_tuples(tuples, closed=closed)
+ index = IntervalIndex.from_tuples(tuples, inclusive=closed)
assert index.is_overlapping is True
# common endpoints
tuples = [(start + n * shift, start + (n + 1) * shift) for n in range(3)]
- index = IntervalIndex.from_tuples(tuples, closed=closed)
+ index = IntervalIndex.from_tuples(tuples, inclusive=closed)
result = index.is_overlapping
expected = closed == "both"
assert result is expected
# common endpoints with NA
tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
- index = IntervalIndex.from_tuples(tuples, closed=closed)
+ index = IntervalIndex.from_tuples(tuples, inclusive=closed)
result = index.is_overlapping
assert result is expected
@@ -873,13 +879,13 @@ def test_set_closed(self, name, closed, new_closed):
expected = interval_range(0, 5, inclusive=new_closed, name=name)
tm.assert_index_equal(result, expected)
- @pytest.mark.parametrize("bad_closed", ["foo", 10, "LEFT", True, False])
- def test_set_closed_errors(self, bad_closed):
+ @pytest.mark.parametrize("bad_inclusive", ["foo", 10, "LEFT", True, False])
+ def test_set_closed_errors(self, bad_inclusive):
# GH 21670
index = interval_range(0, 5)
- msg = f"invalid option for 'closed': {bad_closed}"
+ msg = f"invalid option for 'inclusive': {bad_inclusive}"
with pytest.raises(ValueError, match=msg):
- index.set_closed(bad_closed)
+ index.set_closed(bad_inclusive)
def test_is_all_dates(self):
# GH 23576
@@ -889,6 +895,39 @@ def test_is_all_dates(self):
year_2017_index = IntervalIndex([year_2017])
assert not year_2017_index._is_all_dates
+ def test_interval_index_error_and_warning(self):
+ # GH 40245
+ msg = (
+ "Deprecated argument `closed` cannot "
+ "be passed if argument `inclusive` is not None"
+ )
+ with pytest.raises(ValueError, match=msg):
+ IntervalIndex.from_breaks(range(11), closed="both", inclusive="both")
+
+ with pytest.raises(ValueError, match=msg):
+ IntervalIndex.from_arrays([0, 1], [1, 2], closed="both", inclusive="both")
+
+ with pytest.raises(ValueError, match=msg):
+ IntervalIndex.from_tuples(
+ [(0, 1), (0.5, 1.5)], closed="both", inclusive="both"
+ )
+
+ msg = "Argument `closed` is deprecated in favor of `inclusive`"
+ with tm.assert_produces_warning(
+ FutureWarning, match=msg, check_stacklevel=False
+ ):
+ IntervalIndex.from_breaks(range(11), closed="both")
+
+ with tm.assert_produces_warning(
+ FutureWarning, match=msg, check_stacklevel=False
+ ):
+ IntervalIndex.from_arrays([0, 1], [1, 2], closed="both")
+
+ with tm.assert_produces_warning(
+ FutureWarning, match=msg, check_stacklevel=False
+ ):
+ IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)], closed="both")
+
def test_dir():
# GH#27571 dir(interval_index) should not raise
diff --git a/pandas/tests/indexes/interval/test_interval_range.py b/pandas/tests/indexes/interval/test_interval_range.py
index 63e7f3aa2b120..255470cf4683e 100644
--- a/pandas/tests/indexes/interval/test_interval_range.py
+++ b/pandas/tests/indexes/interval/test_interval_range.py
@@ -30,7 +30,7 @@ class TestIntervalRange:
def test_constructor_numeric(self, closed, name, freq, periods):
start, end = 0, 100
breaks = np.arange(101, step=freq)
- expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
+ expected = IntervalIndex.from_breaks(breaks, name=name, inclusive=closed)
# defined from start/end/freq
result = interval_range(
@@ -63,7 +63,7 @@ def test_constructor_numeric(self, closed, name, freq, periods):
def test_constructor_timestamp(self, closed, name, freq, periods, tz):
start, end = Timestamp("20180101", tz=tz), Timestamp("20181231", tz=tz)
breaks = date_range(start=start, end=end, freq=freq)
- expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
+ expected = IntervalIndex.from_breaks(breaks, name=name, inclusive=closed)
# defined from start/end/freq
result = interval_range(
@@ -98,7 +98,7 @@ def test_constructor_timestamp(self, closed, name, freq, periods, tz):
def test_constructor_timedelta(self, closed, name, freq, periods):
start, end = Timedelta("0 days"), Timedelta("100 days")
breaks = timedelta_range(start=start, end=end, freq=freq)
- expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
+ expected = IntervalIndex.from_breaks(breaks, name=name, inclusive=closed)
# defined from start/end/freq
result = interval_range(
@@ -161,7 +161,7 @@ def test_no_invalid_float_truncation(self, start, end, freq):
breaks = [0.5, 1.5, 2.5, 3.5, 4.5]
else:
breaks = [0.5, 2.0, 3.5, 5.0, 6.5]
- expected = IntervalIndex.from_breaks(breaks)
+ expected = IntervalIndex.from_breaks(breaks, "right")
result = interval_range(
start=start, end=end, periods=4, freq=freq, inclusive="right"
@@ -187,7 +187,8 @@ def test_linspace_dst_transition(self, start, mid, end):
# GH 20976: linspace behavior defined from start/end/periods
# accounts for the hour gained/lost during DST transition
result = interval_range(start=start, end=end, periods=2, inclusive="right")
- expected = IntervalIndex.from_breaks([start, mid, end])
+ expected = IntervalIndex.from_breaks([start, mid, end], "right")
+
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("freq", [2, 2.0])
@@ -336,7 +337,7 @@ def test_errors(self):
# invalid end
msg = r"end must be numeric or datetime-like, got \(0, 1\]"
with pytest.raises(ValueError, match=msg):
- interval_range(end=Interval(0, 1), periods=10)
+ interval_range(end=Interval(0, 1, "right"), periods=10)
# invalid freq for datetime-like
msg = "freq must be numeric or convertible to DateOffset, got foo"
diff --git a/pandas/tests/indexes/interval/test_interval_tree.py b/pandas/tests/indexes/interval/test_interval_tree.py
index f2d9ec3608271..345025d63f4b2 100644
--- a/pandas/tests/indexes/interval/test_interval_tree.py
+++ b/pandas/tests/indexes/interval/test_interval_tree.py
@@ -42,7 +42,7 @@ def leaf_size(request):
)
def tree(request, leaf_size):
left = request.param
- return IntervalTree(left, left + 2, leaf_size=leaf_size)
+ return IntervalTree(left, left + 2, leaf_size=leaf_size, inclusive="right")
class TestIntervalTree:
@@ -129,7 +129,7 @@ def test_get_indexer_closed(self, closed, leaf_size):
found = x.astype("intp")
not_found = (-1 * np.ones(1000)).astype("intp")
- tree = IntervalTree(x, x + 0.5, closed=closed, leaf_size=leaf_size)
+ tree = IntervalTree(x, x + 0.5, inclusive=closed, leaf_size=leaf_size)
tm.assert_numpy_array_equal(found, tree.get_indexer(x + 0.25))
expected = found if tree.closed_left else not_found
@@ -151,7 +151,7 @@ def test_get_indexer_closed(self, closed, leaf_size):
@pytest.mark.parametrize("order", (list(x) for x in permutations(range(3))))
def test_is_overlapping(self, closed, order, left, right, expected):
# GH 23309
- tree = IntervalTree(left[order], right[order], closed=closed)
+ tree = IntervalTree(left[order], right[order], inclusive=closed)
result = tree.is_overlapping
assert result is expected
@@ -160,7 +160,7 @@ def test_is_overlapping_endpoints(self, closed, order):
"""shared endpoints are marked as overlapping"""
# GH 23309
left, right = np.arange(3, dtype="int64"), np.arange(1, 4)
- tree = IntervalTree(left[order], right[order], closed=closed)
+ tree = IntervalTree(left[order], right[order], inclusive=closed)
result = tree.is_overlapping
expected = closed == "both"
assert result is expected
@@ -176,7 +176,7 @@ def test_is_overlapping_endpoints(self, closed, order):
)
def test_is_overlapping_trivial(self, closed, left, right):
# GH 23309
- tree = IntervalTree(left, right, closed=closed)
+ tree = IntervalTree(left, right, inclusive=closed)
assert tree.is_overlapping is False
@pytest.mark.skipif(not IS64, reason="GH 23440")
@@ -189,3 +189,21 @@ def test_construction_overflow(self):
result = tree.root.pivot
expected = (50 + np.iinfo(np.int64).max) / 2
assert result == expected
+
+ def test_interval_tree_error_and_warning(self):
+ # GH 40245
+
+ msg = (
+ "Deprecated argument `closed` cannot "
+ "be passed if argument `inclusive` is not None"
+ )
+ with pytest.raises(ValueError, match=msg):
+ left, right = np.arange(10), [np.iinfo(np.int64).max] * 10
+ IntervalTree(left, right, closed="both", inclusive="both")
+
+ msg = "Argument `closed` is deprecated in favor of `inclusive`"
+ with tm.assert_produces_warning(
+ FutureWarning, match=msg, check_stacklevel=False
+ ):
+ left, right = np.arange(10), [np.iinfo(np.int64).max] * 10
+ IntervalTree(left, right, closed="both")
diff --git a/pandas/tests/indexes/interval/test_pickle.py b/pandas/tests/indexes/interval/test_pickle.py
index 308a90e72eab5..7f5784b6d76b9 100644
--- a/pandas/tests/indexes/interval/test_pickle.py
+++ b/pandas/tests/indexes/interval/test_pickle.py
@@ -5,9 +5,9 @@
class TestPickle:
- @pytest.mark.parametrize("closed", ["left", "right", "both"])
- def test_pickle_round_trip_closed(self, closed):
+ @pytest.mark.parametrize("inclusive", ["left", "right", "both"])
+ def test_pickle_round_trip_closed(self, inclusive):
# https://github.com/pandas-dev/pandas/issues/35658
- idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed)
+ idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], inclusive=inclusive)
result = tm.round_trip_pickle(idx)
tm.assert_index_equal(result, idx)
diff --git a/pandas/tests/indexes/interval/test_setops.py b/pandas/tests/indexes/interval/test_setops.py
index 51a1d36398aa4..5933961cc0f9d 100644
--- a/pandas/tests/indexes/interval/test_setops.py
+++ b/pandas/tests/indexes/interval/test_setops.py
@@ -11,11 +11,13 @@
def monotonic_index(start, end, dtype="int64", closed="right"):
- return IntervalIndex.from_breaks(np.arange(start, end, dtype=dtype), closed=closed)
+ return IntervalIndex.from_breaks(
+ np.arange(start, end, dtype=dtype), inclusive=closed
+ )
def empty_index(dtype="int64", closed="right"):
- return IntervalIndex(np.array([], dtype=dtype), closed=closed)
+ return IntervalIndex(np.array([], dtype=dtype), inclusive=closed)
class TestIntervalIndex:
@@ -125,7 +127,7 @@ def test_intersection_duplicates(self):
tm.assert_index_equal(result, expected)
def test_difference(self, closed, sort):
- index = IntervalIndex.from_arrays([1, 0, 3, 2], [1, 2, 3, 4], closed=closed)
+ index = IntervalIndex.from_arrays([1, 0, 3, 2], [1, 2, 3, 4], inclusive=closed)
result = index.difference(index[:1], sort=sort)
expected = index[1:]
if sort is None:
@@ -139,7 +141,7 @@ def test_difference(self, closed, sort):
# GH 19101: empty result, different dtypes
other = IntervalIndex.from_arrays(
- index.left.astype("float64"), index.right, closed=closed
+ index.left.astype("float64"), index.right, inclusive=closed
)
result = index.difference(other, sort=sort)
tm.assert_index_equal(result, expected)
@@ -161,7 +163,7 @@ def test_symmetric_difference(self, closed, sort):
# GH 19101: empty result, different dtypes
other = IntervalIndex.from_arrays(
- index.left.astype("float64"), index.right, closed=closed
+ index.left.astype("float64"), index.right, inclusive=closed
)
result = index.symmetric_difference(other, sort=sort)
expected = empty_index(dtype="float64", closed=closed)
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 55f3e27be5a72..943cc945995a1 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -1431,10 +1431,10 @@ def test_ensure_index_from_sequences(self, data, names, expected):
def test_ensure_index_mixed_closed_intervals(self):
# GH27172
intervals = [
- pd.Interval(0, 1, closed="left"),
- pd.Interval(1, 2, closed="right"),
- pd.Interval(2, 3, closed="neither"),
- pd.Interval(3, 4, closed="both"),
+ pd.Interval(0, 1, inclusive="left"),
+ pd.Interval(1, 2, inclusive="right"),
+ pd.Interval(2, 3, inclusive="neither"),
+ pd.Interval(3, 4, inclusive="both"),
]
result = ensure_index(intervals)
expected = Index(intervals, dtype=object)
diff --git a/pandas/tests/indexing/interval/test_interval.py b/pandas/tests/indexing/interval/test_interval.py
index db3a569d3925b..7d1f1ef09fc5d 100644
--- a/pandas/tests/indexing/interval/test_interval.py
+++ b/pandas/tests/indexing/interval/test_interval.py
@@ -13,7 +13,7 @@
class TestIntervalIndex:
@pytest.fixture
def series_with_interval_index(self):
- return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
+ return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6), "right"))
def test_getitem_with_scalar(self, series_with_interval_index, indexer_sl):
@@ -40,7 +40,7 @@ def test_getitem_nonoverlapping_monotonic(self, direction, closed, indexer_sl):
if direction == "decreasing":
tpls = tpls[::-1]
- idx = IntervalIndex.from_tuples(tpls, closed=closed)
+ idx = IntervalIndex.from_tuples(tpls, inclusive=closed)
ser = Series(list("abc"), idx)
for key, expected in zip(idx.left, ser):
diff --git a/pandas/tests/indexing/interval/test_interval_new.py b/pandas/tests/indexing/interval/test_interval_new.py
index aad6523357df6..2e3c765b2b372 100644
--- a/pandas/tests/indexing/interval/test_interval_new.py
+++ b/pandas/tests/indexing/interval/test_interval_new.py
@@ -14,7 +14,9 @@
class TestIntervalIndex:
@pytest.fixture
def series_with_interval_index(self):
- return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
+ return Series(
+ np.arange(5), IntervalIndex.from_breaks(np.arange(6), inclusive="right")
+ )
def test_loc_with_interval(self, series_with_interval_index, indexer_sl):
@@ -25,27 +27,33 @@ def test_loc_with_interval(self, series_with_interval_index, indexer_sl):
ser = series_with_interval_index.copy()
expected = 0
- result = indexer_sl(ser)[Interval(0, 1)]
+ result = indexer_sl(ser)[Interval(0, 1, "right")]
assert result == expected
expected = ser.iloc[3:5]
- result = indexer_sl(ser)[[Interval(3, 4), Interval(4, 5)]]
+ result = indexer_sl(ser)[[Interval(3, 4, "right"), Interval(4, 5, "right")]]
tm.assert_series_equal(expected, result)
# missing or not exact
- with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='left')")):
- indexer_sl(ser)[Interval(3, 5, closed="left")]
+ with pytest.raises(
+ KeyError, match=re.escape("Interval(3, 5, inclusive='left')")
+ ):
+ indexer_sl(ser)[Interval(3, 5, inclusive="left")]
- with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")):
- indexer_sl(ser)[Interval(3, 5)]
+ with pytest.raises(
+ KeyError, match=re.escape("Interval(3, 5, inclusive='right')")
+ ):
+ indexer_sl(ser)[Interval(3, 5, "right")]
with pytest.raises(
- KeyError, match=re.escape("Interval(-2, 0, closed='right')")
+ KeyError, match=re.escape("Interval(-2, 0, inclusive='right')")
):
- indexer_sl(ser)[Interval(-2, 0)]
+ indexer_sl(ser)[Interval(-2, 0, "right")]
- with pytest.raises(KeyError, match=re.escape("Interval(5, 6, closed='right')")):
- indexer_sl(ser)[Interval(5, 6)]
+ with pytest.raises(
+ KeyError, match=re.escape("Interval(5, 6, inclusive='right')")
+ ):
+ indexer_sl(ser)[Interval(5, 6, "right")]
def test_loc_with_scalar(self, series_with_interval_index, indexer_sl):
@@ -84,11 +92,11 @@ def test_loc_with_slices(self, series_with_interval_index, indexer_sl):
# slice of interval
expected = ser.iloc[:3]
- result = indexer_sl(ser)[Interval(0, 1) : Interval(2, 3)]
+ result = indexer_sl(ser)[Interval(0, 1, "right") : Interval(2, 3, "right")]
tm.assert_series_equal(expected, result)
expected = ser.iloc[3:]
- result = indexer_sl(ser)[Interval(3, 4) :]
+ result = indexer_sl(ser)[Interval(3, 4, "right") :]
tm.assert_series_equal(expected, result)
msg = "Interval objects are not currently supported"
@@ -96,7 +104,7 @@ def test_loc_with_slices(self, series_with_interval_index, indexer_sl):
indexer_sl(ser)[Interval(3, 6) :]
with pytest.raises(NotImplementedError, match=msg):
- indexer_sl(ser)[Interval(3, 4, closed="left") :]
+ indexer_sl(ser)[Interval(3, 4, inclusive="left") :]
def test_slice_step_ne1(self, series_with_interval_index):
# GH#31658 slice of scalar with step != 1
@@ -127,7 +135,7 @@ def test_slice_interval_step(self, series_with_interval_index):
def test_loc_with_overlap(self, indexer_sl):
- idx = IntervalIndex.from_tuples([(1, 5), (3, 7)])
+ idx = IntervalIndex.from_tuples([(1, 5), (3, 7)], inclusive="right")
ser = Series(range(len(idx)), index=idx)
# scalar
@@ -140,23 +148,25 @@ def test_loc_with_overlap(self, indexer_sl):
# interval
expected = 0
- result = indexer_sl(ser)[Interval(1, 5)]
+ result = indexer_sl(ser)[Interval(1, 5, "right")]
result == expected
expected = ser
- result = indexer_sl(ser)[[Interval(1, 5), Interval(3, 7)]]
+ result = indexer_sl(ser)[[Interval(1, 5, "right"), Interval(3, 7, "right")]]
tm.assert_series_equal(expected, result)
- with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")):
- indexer_sl(ser)[Interval(3, 5)]
+ with pytest.raises(
+ KeyError, match=re.escape("Interval(3, 5, inclusive='right')")
+ ):
+ indexer_sl(ser)[Interval(3, 5, "right")]
- msg = r"None of \[\[Interval\(3, 5, closed='right'\)\]\]"
+ msg = r"None of \[\[Interval\(3, 5, inclusive='right'\)\]\]"
with pytest.raises(KeyError, match=msg):
- indexer_sl(ser)[[Interval(3, 5)]]
+ indexer_sl(ser)[[Interval(3, 5, "right")]]
# slices with interval (only exact matches)
expected = ser
- result = indexer_sl(ser)[Interval(1, 5) : Interval(3, 7)]
+ result = indexer_sl(ser)[Interval(1, 5, "right") : Interval(3, 7, "right")]
tm.assert_series_equal(expected, result)
msg = "'can only get slices from an IntervalIndex if bounds are"
diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py
index b94323e975cd7..21a14ef8523f1 100644
--- a/pandas/tests/indexing/test_categorical.py
+++ b/pandas/tests/indexing/test_categorical.py
@@ -114,7 +114,7 @@ def test_slicing(self):
df = DataFrame({"value": (np.arange(100) + 1).astype("int64")})
df["D"] = pd.cut(df.value, bins=[0, 25, 50, 75, 100])
- expected = Series([11, Interval(0, 25)], index=["value", "D"], name=10)
+ expected = Series([11, Interval(0, 25, "right")], index=["value", "D"], name=10)
result = df.iloc[10]
tm.assert_series_equal(result, expected)
@@ -126,7 +126,7 @@ def test_slicing(self):
result = df.iloc[10:20]
tm.assert_frame_equal(result, expected)
- expected = Series([9, Interval(0, 25)], index=["value", "D"], name=8)
+ expected = Series([9, Interval(0, 25, "right")], index=["value", "D"], name=8)
result = df.loc[8]
tm.assert_series_equal(result, expected)
@@ -495,13 +495,13 @@ def test_loc_and_at_with_categorical_index(self):
# numpy object
np.array([1, "b", 3.5], dtype=object),
# pandas scalars
- [Interval(1, 4), Interval(4, 6), Interval(6, 9)],
+ [Interval(1, 4, "right"), Interval(4, 6, "right"), Interval(6, 9, "right")],
[Timestamp(2019, 1, 1), Timestamp(2019, 2, 1), Timestamp(2019, 3, 1)],
[Timedelta(1, "d"), Timedelta(2, "d"), Timedelta(3, "D")],
# pandas Integer arrays
*(pd.array([1, 2, 3], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES),
# other pandas arrays
- pd.IntervalIndex.from_breaks([1, 4, 6, 9]).array,
+ pd.IntervalIndex.from_breaks([1, 4, 6, 9], "right").array,
pd.date_range("2019-01-01", periods=3).array,
pd.timedelta_range(start="1d", periods=3).array,
],
diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py
index 4504c55698a9a..be8fcfb4d8348 100644
--- a/pandas/tests/indexing/test_coercion.py
+++ b/pandas/tests/indexing/test_coercion.py
@@ -701,7 +701,7 @@ def test_fillna_datetime64tz(self, index_or_series, fill_val, fill_dtype):
1.1,
1 + 1j,
True,
- pd.Interval(1, 2, closed="left"),
+ pd.Interval(1, 2, inclusive="left"),
pd.Timestamp("2012-01-01", tz="US/Eastern"),
pd.Timestamp("2012-01-01"),
pd.Timedelta(days=1),
@@ -745,7 +745,7 @@ def test_fillna_series_timedelta64(self):
1.1,
1 + 1j,
True,
- pd.Interval(1, 2, closed="left"),
+ pd.Interval(1, 2, inclusive="left"),
pd.Timestamp("2012-01-01", tz="US/Eastern"),
pd.Timestamp("2012-01-01"),
pd.Timedelta(days=1),
diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index 3c90eee5be999..2f3b569c899e1 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -1271,7 +1271,7 @@ def test_interval_can_hold_element(self, dtype, element):
# Careful: to get the expected Series-inplace behavior we need
# `elem` to not have the same length as `arr`
- ii2 = IntervalIndex.from_breaks(arr[:-1], closed="neither")
+ ii2 = IntervalIndex.from_breaks(arr[:-1], inclusive="neither")
elem = element(ii2)
self.check_series_setitem(elem, ii, False)
assert not blk._can_hold_element(elem)
diff --git a/pandas/tests/reshape/concat/test_append.py b/pandas/tests/reshape/concat/test_append.py
index 0b1d1c4a3d346..7e4371100b5ad 100644
--- a/pandas/tests/reshape/concat/test_append.py
+++ b/pandas/tests/reshape/concat/test_append.py
@@ -172,7 +172,7 @@ def test_append_preserve_index_name(self):
Index(list("abc")),
pd.CategoricalIndex("A B C".split()),
pd.CategoricalIndex("D E F".split(), ordered=True),
- pd.IntervalIndex.from_breaks([7, 8, 9, 10]),
+ pd.IntervalIndex.from_breaks([7, 8, 9, 10], inclusive="right"),
pd.DatetimeIndex(
[
dt.datetime(2013, 1, 3, 0, 0),
diff --git a/pandas/tests/reshape/test_cut.py b/pandas/tests/reshape/test_cut.py
index 1425686f027e4..815890f319396 100644
--- a/pandas/tests/reshape/test_cut.py
+++ b/pandas/tests/reshape/test_cut.py
@@ -37,7 +37,7 @@ def test_bins(func):
data = func([0.2, 1.4, 2.5, 6.2, 9.7, 2.1])
result, bins = cut(data, 3, retbins=True)
- intervals = IntervalIndex.from_breaks(bins.round(3))
+ intervals = IntervalIndex.from_breaks(bins.round(3), "right")
intervals = intervals.take([0, 0, 0, 1, 2, 0])
expected = Categorical(intervals, ordered=True)
@@ -49,7 +49,7 @@ def test_right():
data = np.array([0.2, 1.4, 2.5, 6.2, 9.7, 2.1, 2.575])
result, bins = cut(data, 4, right=True, retbins=True)
- intervals = IntervalIndex.from_breaks(bins.round(3))
+ intervals = IntervalIndex.from_breaks(bins.round(3), "right")
expected = Categorical(intervals, ordered=True)
expected = expected.take([0, 0, 0, 2, 3, 0, 0])
@@ -61,7 +61,7 @@ def test_no_right():
data = np.array([0.2, 1.4, 2.5, 6.2, 9.7, 2.1, 2.575])
result, bins = cut(data, 4, right=False, retbins=True)
- intervals = IntervalIndex.from_breaks(bins.round(3), closed="left")
+ intervals = IntervalIndex.from_breaks(bins.round(3), inclusive="left")
intervals = intervals.take([0, 0, 0, 2, 3, 0, 1])
expected = Categorical(intervals, ordered=True)
@@ -86,7 +86,7 @@ def test_bins_from_interval_index_doc_example():
# Make sure we preserve the bins.
ages = np.array([10, 15, 13, 12, 23, 25, 28, 59, 60])
c = cut(ages, bins=[0, 18, 35, 70])
- expected = IntervalIndex.from_tuples([(0, 18), (18, 35), (35, 70)])
+ expected = IntervalIndex.from_tuples([(0, 18), (18, 35), (35, 70)], "right")
tm.assert_index_equal(c.categories, expected)
result = cut([25, 20, 50], bins=c.categories)
@@ -121,7 +121,8 @@ def test_bins_not_monotonic():
[
(Timestamp.min, Timestamp("2018-01-01")),
(Timestamp("2018-01-01"), Timestamp.max),
- ]
+ ],
+ "right",
),
),
(
@@ -130,7 +131,7 @@ def test_bins_not_monotonic():
[np.iinfo(np.int64).min, 0, np.iinfo(np.int64).max], dtype="int64"
),
IntervalIndex.from_tuples(
- [(np.iinfo(np.int64).min, 0), (0, np.iinfo(np.int64).max)]
+ [(np.iinfo(np.int64).min, 0), (0, np.iinfo(np.int64).max)], "right"
),
),
(
@@ -156,7 +157,8 @@ def test_bins_not_monotonic():
np.timedelta64(0, "ns"),
np.timedelta64(np.iinfo(np.int64).max, "ns"),
),
- ]
+ ],
+ "right",
),
),
],
@@ -232,7 +234,7 @@ def test_labels(right, breaks, closed):
arr = np.tile(np.arange(0, 1.01, 0.1), 4)
result, bins = cut(arr, 4, retbins=True, right=right)
- ex_levels = IntervalIndex.from_breaks(breaks, closed=closed)
+ ex_levels = IntervalIndex.from_breaks(breaks, inclusive=closed)
tm.assert_index_equal(result.categories, ex_levels)
@@ -248,7 +250,7 @@ def test_label_precision():
arr = np.arange(0, 0.73, 0.01)
result = cut(arr, 4, precision=2)
- ex_levels = IntervalIndex.from_breaks([-0.00072, 0.18, 0.36, 0.54, 0.72])
+ ex_levels = IntervalIndex.from_breaks([-0.00072, 0.18, 0.36, 0.54, 0.72], "right")
tm.assert_index_equal(result.categories, ex_levels)
@@ -272,13 +274,13 @@ def test_inf_handling():
result = cut(data, bins)
result_ser = cut(data_ser, bins)
- ex_uniques = IntervalIndex.from_breaks(bins)
+ ex_uniques = IntervalIndex.from_breaks(bins, "right")
tm.assert_index_equal(result.categories, ex_uniques)
- assert result[5] == Interval(4, np.inf)
- assert result[0] == Interval(-np.inf, 2)
- assert result_ser[5] == Interval(4, np.inf)
- assert result_ser[0] == Interval(-np.inf, 2)
+ assert result[5] == Interval(4, np.inf, "right")
+ assert result[0] == Interval(-np.inf, 2, "right")
+ assert result_ser[5] == Interval(4, np.inf, "right")
+ assert result_ser[0] == Interval(-np.inf, 2, "right")
def test_cut_out_of_bounds():
@@ -355,7 +357,7 @@ def test_cut_return_intervals():
exp_bins[0] -= 0.008
expected = Series(
- IntervalIndex.from_breaks(exp_bins, closed="right").take(
+ IntervalIndex.from_breaks(exp_bins, inclusive="right").take(
[0, 0, 0, 1, 1, 1, 2, 2, 2]
)
).astype(CDT(ordered=True))
@@ -368,7 +370,7 @@ def test_series_ret_bins():
result, bins = cut(ser, 2, retbins=True)
expected = Series(
- IntervalIndex.from_breaks([-0.003, 1.5, 3], closed="right").repeat(2)
+ IntervalIndex.from_breaks([-0.003, 1.5, 3], inclusive="right").repeat(2)
).astype(CDT(ordered=True))
tm.assert_series_equal(result, expected)
@@ -442,7 +444,8 @@ def test_datetime_bin(conv):
[
Interval(Timestamp(bin_data[0]), Timestamp(bin_data[1])),
Interval(Timestamp(bin_data[1]), Timestamp(bin_data[2])),
- ]
+ ],
+ "right",
)
).astype(CDT(ordered=True))
@@ -488,7 +491,8 @@ def test_datetime_cut(data):
Interval(
Timestamp("2013-01-02 08:00:00"), Timestamp("2013-01-03 00:00:00")
),
- ]
+ ],
+ "right",
)
).astype(CDT(ordered=True))
tm.assert_series_equal(Series(result), expected)
@@ -531,7 +535,8 @@ def test_datetime_tz_cut(bins, box):
Timestamp("2013-01-02 08:00:00", tz=tz),
Timestamp("2013-01-03 00:00:00", tz=tz),
),
- ]
+ ],
+ "right",
)
).astype(CDT(ordered=True))
tm.assert_series_equal(result, expected)
@@ -685,8 +690,8 @@ def test_cut_no_warnings():
def test_cut_with_duplicated_index_lowest_included():
# GH 42185
expected = Series(
- [Interval(-0.001, 2, closed="right")] * 3
- + [Interval(2, 4, closed="right"), Interval(-0.001, 2, closed="right")],
+ [Interval(-0.001, 2, inclusive="right")] * 3
+ + [Interval(2, 4, inclusive="right"), Interval(-0.001, 2, inclusive="right")],
index=[0, 1, 2, 3, 0],
dtype="category",
).cat.as_ordered()
@@ -706,16 +711,16 @@ def test_cut_with_nonexact_categorical_indices():
index = pd.CategoricalIndex(
[
- Interval(-0.099, 9.9, closed="right"),
- Interval(9.9, 19.8, closed="right"),
- Interval(19.8, 29.7, closed="right"),
- Interval(29.7, 39.6, closed="right"),
- Interval(39.6, 49.5, closed="right"),
- Interval(49.5, 59.4, closed="right"),
- Interval(59.4, 69.3, closed="right"),
- Interval(69.3, 79.2, closed="right"),
- Interval(79.2, 89.1, closed="right"),
- Interval(89.1, 99, closed="right"),
+ Interval(-0.099, 9.9, inclusive="right"),
+ Interval(9.9, 19.8, inclusive="right"),
+ Interval(19.8, 29.7, inclusive="right"),
+ Interval(29.7, 39.6, inclusive="right"),
+ Interval(39.6, 49.5, inclusive="right"),
+ Interval(49.5, 59.4, inclusive="right"),
+ Interval(59.4, 69.3, inclusive="right"),
+ Interval(69.3, 79.2, inclusive="right"),
+ Interval(79.2, 89.1, inclusive="right"),
+ Interval(89.1, 99, inclusive="right"),
],
ordered=True,
)
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index 3950999c5d4fc..8312e3b9de9a7 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -301,7 +301,7 @@ def test_pivot_with_interval_index(self, interval_values, dropna):
def test_pivot_with_interval_index_margins(self):
# GH 25815
- ordered_cat = pd.IntervalIndex.from_arrays([0, 0, 1, 1], [1, 1, 2, 2])
+ ordered_cat = pd.IntervalIndex.from_arrays([0, 0, 1, 1], [1, 1, 2, 2], "right")
df = DataFrame(
{
"A": np.arange(4, 0, -1, dtype=np.intp),
@@ -319,7 +319,10 @@ def test_pivot_with_interval_index_margins(self):
result = pivot_tab["All"]
expected = Series(
[3, 7, 10],
- index=Index([pd.Interval(0, 1), pd.Interval(1, 2), "All"], name="C"),
+ index=Index(
+ [pd.Interval(0, 1, "right"), pd.Interval(1, 2, "right"), "All"],
+ name="C",
+ ),
name="All",
dtype=np.intp,
)
diff --git a/pandas/tests/reshape/test_qcut.py b/pandas/tests/reshape/test_qcut.py
index f7c7204d02a49..0f82bb736c069 100644
--- a/pandas/tests/reshape/test_qcut.py
+++ b/pandas/tests/reshape/test_qcut.py
@@ -76,7 +76,8 @@ def test_qcut_include_lowest():
Interval(2.25, 4.5),
Interval(4.5, 6.75),
Interval(6.75, 9),
- ]
+ ],
+ "right",
)
tm.assert_index_equal(ii.categories, ex_levels)
@@ -91,7 +92,7 @@ def test_qcut_nas():
def test_qcut_index():
result = qcut([0, 2], 2)
- intervals = [Interval(-0.001, 1), Interval(1, 2)]
+ intervals = [Interval(-0.001, 1, "right"), Interval(1, 2, "right")]
expected = Categorical(intervals, ordered=True)
tm.assert_categorical_equal(result, expected)
@@ -127,7 +128,11 @@ def test_qcut_return_intervals():
res = qcut(ser, [0, 0.333, 0.666, 1])
exp_levels = np.array(
- [Interval(-0.001, 2.664), Interval(2.664, 5.328), Interval(5.328, 8)]
+ [
+ Interval(-0.001, 2.664, "right"),
+ Interval(2.664, 5.328, "right"),
+ Interval(5.328, 8, "right"),
+ ]
)
exp = Series(exp_levels.take([0, 0, 0, 1, 1, 1, 2, 2, 2])).astype(CDT(ordered=True))
tm.assert_series_equal(res, exp)
@@ -183,7 +188,7 @@ def test_qcut_duplicates_bin(kwargs, msg):
qcut(values, 3, **kwargs)
else:
result = qcut(values, 3, **kwargs)
- expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)])
+ expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)], "right")
tm.assert_index_equal(result.categories, expected)
@@ -198,7 +203,7 @@ def test_single_quantile(data, start, end, length, labels):
result = qcut(ser, 1, labels=labels)
if labels is None:
- intervals = IntervalIndex([Interval(start, end)] * length, closed="right")
+ intervals = IntervalIndex([Interval(start, end)] * length, inclusive="right")
expected = Series(intervals).astype(CDT(ordered=True))
else:
expected = Series([0] * length, dtype=np.intp)
@@ -217,7 +222,7 @@ def test_single_quantile(data, start, end, length, labels):
def test_qcut_nat(ser):
# see gh-19768
intervals = IntervalIndex.from_tuples(
- [(ser[0] - Nano(), ser[2] - Day()), np.nan, (ser[2] - Day(), ser[2])]
+ [(ser[0] - Nano(), ser[2] - Day()), np.nan, (ser[2] - Day(), ser[2])], "right"
)
expected = Series(Categorical(intervals, ordered=True))
@@ -247,7 +252,8 @@ def test_datetime_tz_qcut(bins):
Timestamp("2013-01-02 08:00:00", tz=tz),
Timestamp("2013-01-03 00:00:00", tz=tz),
),
- ]
+ ],
+ "right",
)
).astype(CDT(ordered=True))
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/scalar/interval/test_interval.py b/pandas/tests/scalar/interval/test_interval.py
index 1f76a7df1e996..878b5e6ec0167 100644
--- a/pandas/tests/scalar/interval/test_interval.py
+++ b/pandas/tests/scalar/interval/test_interval.py
@@ -13,22 +13,22 @@
@pytest.fixture
def interval():
- return Interval(0, 1)
+ return Interval(0, 1, "right")
class TestInterval:
def test_properties(self, interval):
- assert interval.closed == "right"
+ assert interval.inclusive == "right"
assert interval.left == 0
assert interval.right == 1
assert interval.mid == 0.5
def test_repr(self, interval):
- assert repr(interval) == "Interval(0, 1, closed='right')"
+ assert repr(interval) == "Interval(0, 1, inclusive='right')"
assert str(interval) == "(0, 1]"
- interval_left = Interval(0, 1, closed="left")
- assert repr(interval_left) == "Interval(0, 1, closed='left')"
+ interval_left = Interval(0, 1, "left")
+ assert repr(interval_left) == "Interval(0, 1, inclusive='left')"
assert str(interval_left) == "[0, 1)"
def test_contains(self, interval):
@@ -40,18 +40,18 @@ def test_contains(self, interval):
with pytest.raises(TypeError, match=msg):
interval in interval
- interval_both = Interval(0, 1, closed="both")
+ interval_both = Interval(0, 1, "both")
assert 0 in interval_both
assert 1 in interval_both
- interval_neither = Interval(0, 1, closed="neither")
+ interval_neither = Interval(0, 1, "neither")
assert 0 not in interval_neither
assert 0.5 in interval_neither
assert 1 not in interval_neither
def test_equal(self):
- assert Interval(0, 1) == Interval(0, 1, closed="right")
- assert Interval(0, 1) != Interval(0, 1, closed="left")
+ assert Interval(0, 1, "right") == Interval(0, 1, "right")
+ assert Interval(0, 1, "right") != Interval(0, 1, "left")
assert Interval(0, 1) != 0
def test_comparison(self):
@@ -129,7 +129,7 @@ def test_is_empty(self, left, right, closed):
iv = Interval(left, right, closed)
assert iv.is_empty is False
- # same endpoint is empty except when closed='both' (contains one point)
+ # same endpoint is empty except when inclusive='both' (contains one point)
iv = Interval(left, left, closed)
result = iv.is_empty
expected = closed != "both"
@@ -152,8 +152,8 @@ def test_construct_errors(self, left, right):
Interval(left, right)
def test_math_add(self, closed):
- interval = Interval(0, 1, closed=closed)
- expected = Interval(1, 2, closed=closed)
+ interval = Interval(0, 1, closed)
+ expected = Interval(1, 2, closed)
result = interval + 1
assert result == expected
@@ -173,8 +173,8 @@ def test_math_add(self, closed):
interval + "foo"
def test_math_sub(self, closed):
- interval = Interval(0, 1, closed=closed)
- expected = Interval(-1, 0, closed=closed)
+ interval = Interval(0, 1, closed)
+ expected = Interval(-1, 0, closed)
result = interval - 1
assert result == expected
@@ -191,8 +191,8 @@ def test_math_sub(self, closed):
interval - "foo"
def test_math_mult(self, closed):
- interval = Interval(0, 1, closed=closed)
- expected = Interval(0, 2, closed=closed)
+ interval = Interval(0, 1, closed)
+ expected = Interval(0, 2, closed)
result = interval * 2
assert result == expected
@@ -213,8 +213,8 @@ def test_math_mult(self, closed):
interval * "foo"
def test_math_div(self, closed):
- interval = Interval(0, 1, closed=closed)
- expected = Interval(0, 0.5, closed=closed)
+ interval = Interval(0, 1, closed)
+ expected = Interval(0, 0.5, closed)
result = interval / 2.0
assert result == expected
@@ -231,8 +231,8 @@ def test_math_div(self, closed):
interval / "foo"
def test_math_floordiv(self, closed):
- interval = Interval(1, 2, closed=closed)
- expected = Interval(0, 1, closed=closed)
+ interval = Interval(1, 2, closed)
+ expected = Interval(0, 1, closed)
result = interval // 2
assert result == expected
@@ -249,9 +249,9 @@ def test_math_floordiv(self, closed):
interval // "foo"
def test_constructor_errors(self):
- msg = "invalid option for 'closed': foo"
+ msg = "invalid option for 'inclusive': foo"
with pytest.raises(ValueError, match=msg):
- Interval(0, 1, closed="foo")
+ Interval(0, 1, "foo")
msg = "left side of interval must be <= right side"
with pytest.raises(ValueError, match=msg):
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index e42039a86fc16..e2a5517066ad9 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -781,7 +781,12 @@ def test_index_putmask(self, obj, key, expected, val):
# cast to IntervalDtype[float]
Series(interval_range(1, 5, inclusive="right")),
Series(
- [Interval(1, 2), np.nan, Interval(3, 4), Interval(4, 5)],
+ [
+ Interval(1, 2, "right"),
+ np.nan,
+ Interval(3, 4, "right"),
+ Interval(4, 5, "right"),
+ ],
dtype="interval[float64]",
),
1,
@@ -1052,9 +1057,9 @@ class TestSetitemFloatIntervalWithIntIntervalValues(SetitemCastingEquivalents):
def test_setitem_example(self):
# Just a case here to make obvious what this test class is aimed at
- idx = IntervalIndex.from_breaks(range(4))
+ idx = IntervalIndex.from_breaks(range(4), inclusive="right")
obj = Series(idx)
- val = Interval(0.5, 1.5)
+ val = Interval(0.5, 1.5, "right")
obj[0] = val
assert obj.dtype == "Interval[float64, right]"
@@ -1348,7 +1353,7 @@ def obj(self):
@pytest.mark.parametrize(
- "val", ["foo", Period("2016", freq="Y"), Interval(1, 2, closed="both")]
+ "val", ["foo", Period("2016", freq="Y"), Interval(1, 2, inclusive="both")]
)
@pytest.mark.parametrize("exp_dtype", [object])
class TestPeriodIntervalCoercion(CoercionTest):
@@ -1547,7 +1552,7 @@ def test_setitem_int_as_positional_fallback_deprecation():
# Once the deprecation is enforced, we will have
# expected = Series([1, 2, 3, 4, 5], index=[1.1, 2.1, 3.0, 4.1, 5.0])
- ii = IntervalIndex.from_breaks(range(10))[::2]
+ ii = IntervalIndex.from_breaks(range(10), inclusive="right")[::2]
ser2 = Series(range(len(ii)), index=ii)
expected2 = ser2.copy()
expected2.iloc[-1] = 9
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index e416b1f625993..e0b180bf0c6f4 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -1172,7 +1172,7 @@ def test_constructor_datetime64_bigendian(self):
@pytest.mark.parametrize("interval_constructor", [IntervalIndex, IntervalArray])
def test_construction_interval(self, interval_constructor):
# construction from interval & array of intervals
- intervals = interval_constructor.from_breaks(np.arange(3), closed="right")
+ intervals = interval_constructor.from_breaks(np.arange(3), inclusive="right")
result = Series(intervals)
assert result.dtype == "interval[int64, right]"
tm.assert_index_equal(Index(result.values), Index(intervals))
@@ -1182,7 +1182,7 @@ def test_construction_interval(self, interval_constructor):
)
def test_constructor_infer_interval(self, data_constructor):
# GH 23563: consistent closed results in interval dtype
- data = [Interval(0, 1), Interval(0, 2), None]
+ data = [Interval(0, 1, "right"), Interval(0, 2, "right"), None]
result = Series(data_constructor(data))
expected = Series(IntervalArray(data))
assert result.dtype == "interval[float64, right]"
@@ -1193,7 +1193,7 @@ def test_constructor_infer_interval(self, data_constructor):
)
def test_constructor_interval_mixed_closed(self, data_constructor):
# GH 23563: mixed closed results in object dtype (not interval dtype)
- data = [Interval(0, 1, closed="both"), Interval(0, 2, closed="neither")]
+ data = [Interval(0, 1, inclusive="both"), Interval(0, 2, inclusive="neither")]
result = Series(data_constructor(data))
assert result.dtype == object
assert result.tolist() == data
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 2d73b8e91e831..85a240a3e825d 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -1101,19 +1101,26 @@ def test_value_counts(self):
# assert isinstance(factor, n)
result = algos.value_counts(factor)
breaks = [-1.194, -0.535, 0.121, 0.777, 1.433]
- index = IntervalIndex.from_breaks(breaks).astype(CDT(ordered=True))
+ index = IntervalIndex.from_breaks(breaks, inclusive="right").astype(
+ CDT(ordered=True)
+ )
expected = Series([1, 1, 1, 1], index=index)
tm.assert_series_equal(result.sort_index(), expected.sort_index())
def test_value_counts_bins(self):
s = [1, 2, 3, 4]
result = algos.value_counts(s, bins=1)
- expected = Series([4], index=IntervalIndex.from_tuples([(0.996, 4.0)]))
+ expected = Series(
+ [4], index=IntervalIndex.from_tuples([(0.996, 4.0)], inclusive="right")
+ )
tm.assert_series_equal(result, expected)
result = algos.value_counts(s, bins=2, sort=False)
expected = Series(
- [2, 2], index=IntervalIndex.from_tuples([(0.996, 2.5), (2.5, 4.0)])
+ [2, 2],
+ index=IntervalIndex.from_tuples(
+ [(0.996, 2.5), (2.5, 4.0)], inclusive="right"
+ ),
)
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py
index 6ff1a1c17b179..c3c5f2fdc9d29 100644
--- a/pandas/tests/util/test_assert_frame_equal.py
+++ b/pandas/tests/util/test_assert_frame_equal.py
@@ -247,7 +247,7 @@ def test_assert_frame_equal_extension_dtype_mismatch():
def test_assert_frame_equal_interval_dtype_mismatch():
# https://github.com/pandas-dev/pandas/issues/32747
- left = DataFrame({"a": [pd.Interval(0, 1)]}, dtype="interval")
+ left = DataFrame({"a": [pd.Interval(0, 1, "right")]}, dtype="interval")
right = left.astype(object)
msg = (
diff --git a/pandas/tests/util/test_assert_interval_array_equal.py b/pandas/tests/util/test_assert_interval_array_equal.py
index 243f357d7298c..29ebc00b2e69a 100644
--- a/pandas/tests/util/test_assert_interval_array_equal.py
+++ b/pandas/tests/util/test_assert_interval_array_equal.py
@@ -25,7 +25,7 @@ def test_interval_array_equal_closed_mismatch():
msg = """\
IntervalArray are different
-Attribute "closed" are different
+Attribute "inclusive" are different
\\[left\\]: left
\\[right\\]: right"""
diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py
index 93a2e4b83e760..dcf1fe291f179 100644
--- a/pandas/tests/util/test_assert_series_equal.py
+++ b/pandas/tests/util/test_assert_series_equal.py
@@ -256,7 +256,7 @@ def test_assert_series_equal_extension_dtype_mismatch():
def test_assert_series_equal_interval_dtype_mismatch():
# https://github.com/pandas-dev/pandas/issues/32747
- left = Series([pd.Interval(0, 1)], dtype="interval")
+ left = Series([pd.Interval(0, 1, "right")], dtype="interval")
right = left.astype(object)
msg = """Attributes of Series are different
| - [ ] xref #40245
- [ ] [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 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/46522 | 2022-03-26T15:55:06Z | 2022-05-30T20:47:41Z | 2022-05-30T20:47:41Z | 2022-05-31T16:12:40Z |
TYP: Fix core/groupby/generic.py type ignores | diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 245e33fb1a23b..f725ae061cedb 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -26,7 +26,10 @@
import numpy as np
-from pandas._libs import reduction as libreduction
+from pandas._libs import (
+ Interval,
+ reduction as libreduction,
+)
from pandas._typing import (
ArrayLike,
Manager,
@@ -652,12 +655,9 @@ def value_counts(
if is_interval_dtype(lab.dtype):
# TODO: should we do this inside II?
+ lab_interval = cast(Interval, lab)
- # error: "ndarray" has no attribute "left"
- # error: "ndarray" has no attribute "right"
- sorter = np.lexsort(
- (lab.left, lab.right, ids) # type: ignore[attr-defined]
- )
+ sorter = np.lexsort((lab_interval.left, lab_interval.right, ids))
else:
sorter = np.lexsort((lab, ids))
| xref #37715
Two things to mention:
- not a huge fan of casts but couldn't find another way to fix the issues;
- added `Index()` in line 277 because `columns` attribute of a dataframe is supposed to be of Index type. | https://api.github.com/repos/pandas-dev/pandas/pulls/46521 | 2022-03-26T14:24:19Z | 2022-05-11T12:29:05Z | 2022-05-11T12:29:05Z | 2022-05-11T12:29:06Z |
TYP: Index.join | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 931d18dc349f3..3af0f1d553c0d 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -448,6 +448,7 @@ Other Deprecations
- Deprecated passing arguments as positional in :meth:`DataFrame.any` and :meth:`Series.any` (:issue:`44802`)
- Deprecated the ``closed`` argument in :meth:`interval_range` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`)
- Deprecated the methods :meth:`DataFrame.mad`, :meth:`Series.mad`, and the corresponding groupby methods (:issue:`11787`)
+- Deprecated positional arguments to :meth:`Index.join` except for ``other``, use keyword-only arguments instead of positional arguments (:issue:`46518`)
.. ---------------------------------------------------------------------------
.. _whatsnew_150.performance:
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 80527474f2be6..59e55bdcb405a 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -48,6 +48,7 @@
DtypeObj,
F,
IgnoreRaise,
+ Level,
Shape,
npt,
)
@@ -4529,16 +4530,53 @@ def _reindex_non_unique(
# --------------------------------------------------------------------
# Join Methods
+ @overload
+ def join(
+ self,
+ other: Index,
+ *,
+ how: str_t = ...,
+ level: Level = ...,
+ return_indexers: Literal[True],
+ sort: bool = ...,
+ ) -> tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]:
+ ...
+
+ @overload
+ def join(
+ self,
+ other: Index,
+ *,
+ how: str_t = ...,
+ level: Level = ...,
+ return_indexers: Literal[False] = ...,
+ sort: bool = ...,
+ ) -> Index:
+ ...
+
+ @overload
+ def join(
+ self,
+ other: Index,
+ *,
+ how: str_t = ...,
+ level: Level = ...,
+ return_indexers: bool = ...,
+ sort: bool = ...,
+ ) -> Index | tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]:
+ ...
+
@final
+ @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "other"])
@_maybe_return_indexers
def join(
self,
- other,
+ other: Index,
how: str_t = "left",
- level=None,
+ level: Level = None,
return_indexers: bool = False,
sort: bool = False,
- ):
+ ) -> Index | tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]:
"""
Compute join_index and indexers to conform data
structures to the new index.
@@ -4723,7 +4761,7 @@ def _join_multi(self, other: Index, how: str_t):
# Join left and right
# Join on same leveled multi-index frames is supported
join_idx, lidx, ridx = self_jnlevels.join(
- other_jnlevels, how, return_indexers=True
+ other_jnlevels, how=how, return_indexers=True
)
# Restore the dropped levels
@@ -4731,8 +4769,16 @@ def _join_multi(self, other: Index, how: str_t):
# common levels, ldrop_names, rdrop_names
dropped_names = ldrop_names + rdrop_names
+ # error: Argument 5/6 to "restore_dropped_levels_multijoin" has
+ # incompatible type "Optional[ndarray[Any, dtype[signedinteger[Any
+ # ]]]]"; expected "ndarray[Any, dtype[signedinteger[Any]]]"
levels, codes, names = restore_dropped_levels_multijoin(
- self, other, dropped_names, join_idx, lidx, ridx
+ self,
+ other,
+ dropped_names,
+ join_idx,
+ lidx, # type: ignore[arg-type]
+ ridx, # type: ignore[arg-type]
)
# Re-create the multi-index
| Overloads for Index.join | https://api.github.com/repos/pandas-dev/pandas/pulls/46518 | 2022-03-26T01:48:21Z | 2022-05-06T21:26:11Z | 2022-05-06T21:26:11Z | 2022-05-26T01:59:24Z |
Backport PR #46515 on branch 1.4.x (CI/DOC: pin jinja2 to 3.0.3) | diff --git a/environment.yml b/environment.yml
index ff02ca2243d51..da5d6fabcde20 100644
--- a/environment.yml
+++ b/environment.yml
@@ -86,7 +86,7 @@ dependencies:
- bottleneck>=1.3.1
- ipykernel
- ipython>=7.11.1
- - jinja2 # pandas.Styler
+ - jinja2<=3.0.3 # pandas.Styler
- matplotlib>=3.3.2 # pandas.plotting, Series.plot, DataFrame.plot
- numexpr>=2.7.1
- scipy>=1.4.1
diff --git a/requirements-dev.txt b/requirements-dev.txt
index e500417308a9d..ac525f1d09fbe 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -58,7 +58,7 @@ blosc
bottleneck>=1.3.1
ipykernel
ipython>=7.11.1
-jinja2
+jinja2<=3.0.3
matplotlib>=3.3.2
numexpr>=2.7.1
scipy>=1.4.1
| Backport PR #46515: CI/DOC: pin jinja2 to 3.0.3 | https://api.github.com/repos/pandas-dev/pandas/pulls/46517 | 2022-03-26T00:52:09Z | 2022-03-26T03:20:56Z | 2022-03-26T03:20:56Z | 2022-03-26T03:20:56Z |
REF: _infer_tsobject_fold to infer_datetuil_fold | diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd
index 227cf454700d5..206e0171e0a55 100644
--- a/pandas/_libs/tslibs/conversion.pxd
+++ b/pandas/_libs/tslibs/conversion.pxd
@@ -31,5 +31,3 @@ cdef int64_t get_datetime64_nanos(object val) except? -1
cpdef datetime localize_pydatetime(datetime dt, tzinfo tz)
cdef int64_t cast_from_unit(object ts, str unit) except? -1
cpdef (int64_t, int) precision_from_unit(str unit)
-
-cdef int64_t normalize_i8_stamp(int64_t local_val) nogil
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index 132d742b78e9c..f51f25c2065f2 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -72,6 +72,7 @@ from pandas._libs.tslibs.nattype cimport (
)
from pandas._libs.tslibs.tzconversion cimport (
bisect_right_i8,
+ infer_datetuil_fold,
localize_tzinfo_api,
tz_localize_to_utc_single,
)
@@ -530,7 +531,7 @@ cdef _TSObject _create_tsobject_tz_using_offset(npy_datetimestruct dts,
if typ == 'dateutil':
tdata = <int64_t*>cnp.PyArray_DATA(trans)
pos = bisect_right_i8(tdata, obj.value, trans.shape[0]) - 1
- obj.fold = _infer_tsobject_fold(obj, trans, deltas, pos)
+ obj.fold = infer_datetuil_fold(obj.value, trans, deltas, pos)
# Keep the converter same as PyDateTime's
dt = datetime(obj.dts.year, obj.dts.month, obj.dts.day,
@@ -714,7 +715,7 @@ cdef inline void _localize_tso(_TSObject obj, tzinfo tz):
local_val = obj.value + deltas[pos]
# dateutil supports fold, so we infer fold from value
- obj.fold = _infer_tsobject_fold(obj, trans, deltas, pos)
+ obj.fold = infer_datetuil_fold(obj.value, trans, deltas, pos)
else:
# All other cases have len(deltas) == 1. As of 2018-07-17
# (and 2022-03-07), all test cases that get here have
@@ -726,49 +727,6 @@ cdef inline void _localize_tso(_TSObject obj, tzinfo tz):
obj.tzinfo = tz
-cdef inline bint _infer_tsobject_fold(
- _TSObject obj,
- const int64_t[:] trans,
- const int64_t[:] deltas,
- intp_t pos,
-):
- """
- Infer _TSObject fold property from value by assuming 0 and then setting
- to 1 if necessary.
-
- Parameters
- ----------
- obj : _TSObject
- trans : ndarray[int64_t]
- ndarray of offset transition points in nanoseconds since epoch.
- deltas : int64_t[:]
- array of offsets corresponding to transition points in trans.
- pos : intp_t
- Position of the last transition point before taking fold into account.
-
- Returns
- -------
- bint
- Due to daylight saving time, one wall clock time can occur twice
- when shifting from summer to winter time; fold describes whether the
- datetime-like corresponds to the first (0) or the second time (1)
- the wall clock hits the ambiguous time
-
- References
- ----------
- .. [1] "PEP 495 - Local Time Disambiguation"
- https://www.python.org/dev/peps/pep-0495/#the-fold-attribute
- """
- cdef:
- bint fold = 0
-
- if pos > 0:
- fold_delta = deltas[pos - 1] - deltas[pos]
- if obj.value - fold_delta < trans[pos]:
- fold = 1
-
- return fold
-
cdef inline datetime _localize_pydatetime(datetime dt, tzinfo tz):
"""
Take a datetime/Timestamp in UTC and localizes to timezone tz.
@@ -802,24 +760,3 @@ cpdef inline datetime localize_pydatetime(datetime dt, tzinfo tz):
elif isinstance(dt, ABCTimestamp):
return dt.tz_localize(tz)
return _localize_pydatetime(dt, tz)
-
-
-# ----------------------------------------------------------------------
-# Normalization
-
-@cython.cdivision(False)
-cdef inline int64_t normalize_i8_stamp(int64_t local_val) nogil:
- """
- Round the localized nanosecond timestamp down to the previous midnight.
-
- Parameters
- ----------
- local_val : int64_t
-
- Returns
- -------
- int64_t
- """
- cdef:
- int64_t day_nanos = 24 * 3600 * 1_000_000_000
- return local_val - (local_val % day_nanos)
diff --git a/pandas/_libs/tslibs/timestamps.pxd b/pandas/_libs/tslibs/timestamps.pxd
index 8833a611b0722..9b05fbc5be915 100644
--- a/pandas/_libs/tslibs/timestamps.pxd
+++ b/pandas/_libs/tslibs/timestamps.pxd
@@ -28,3 +28,5 @@ cdef class _Timestamp(ABCTimestamp):
int op) except -1
cpdef void _set_freq(self, freq)
cdef _warn_on_field_deprecation(_Timestamp self, freq, str field)
+
+cdef int64_t normalize_i8_stamp(int64_t local_val) nogil
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx
index 2afceb827e49a..a0958e11e28b3 100644
--- a/pandas/_libs/tslibs/timestamps.pyx
+++ b/pandas/_libs/tslibs/timestamps.pyx
@@ -51,7 +51,6 @@ from pandas._libs.tslibs.conversion cimport (
_TSObject,
convert_datetime_to_tsobject,
convert_to_tsobject,
- normalize_i8_stamp,
)
from pandas._libs.tslibs.util cimport (
is_array,
@@ -2116,3 +2115,23 @@ cdef int64_t _NS_LOWER_BOUND = NPY_NAT + 1
Timestamp.min = Timestamp(_NS_LOWER_BOUND)
Timestamp.max = Timestamp(_NS_UPPER_BOUND)
Timestamp.resolution = Timedelta(nanoseconds=1) # GH#21336, GH#21365
+
+
+# ----------------------------------------------------------------------
+# Scalar analogues to functions in vectorized.pyx
+
+
+@cython.cdivision(False)
+cdef inline int64_t normalize_i8_stamp(int64_t local_val) nogil:
+ """
+ Round the localized nanosecond timestamp down to the previous midnight.
+
+ Parameters
+ ----------
+ local_val : int64_t
+
+ Returns
+ -------
+ int64_t
+ """
+ return local_val - (local_val % ccalendar.DAY_NANOS)
diff --git a/pandas/_libs/tslibs/tzconversion.pxd b/pandas/_libs/tslibs/tzconversion.pxd
index 136e62985995e..74aab9f297379 100644
--- a/pandas/_libs/tslibs/tzconversion.pxd
+++ b/pandas/_libs/tslibs/tzconversion.pxd
@@ -1,5 +1,8 @@
from cpython.datetime cimport tzinfo
-from numpy cimport int64_t
+from numpy cimport (
+ int64_t,
+ intp_t,
+)
cdef int64_t localize_tzinfo_api(
@@ -11,3 +14,10 @@ cdef int64_t tz_localize_to_utc_single(
) except? -1
cdef Py_ssize_t bisect_right_i8(int64_t *data, int64_t val, Py_ssize_t n)
+
+cdef bint infer_datetuil_fold(
+ int64_t value,
+ const int64_t[::1] trans,
+ const int64_t[::1] deltas,
+ intp_t pos,
+)
diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx
index 9190585b2882d..a63a27b8194de 100644
--- a/pandas/_libs/tslibs/tzconversion.pyx
+++ b/pandas/_libs/tslibs/tzconversion.pyx
@@ -632,3 +632,48 @@ cdef int64_t _tz_localize_using_tzinfo_api(
td = tz.utcoffset(dt)
delta = int(td.total_seconds() * 1_000_000_000)
return delta
+
+
+# NB: relies on dateutil internals, subject to change.
+cdef bint infer_datetuil_fold(
+ int64_t value,
+ const int64_t[::1] trans,
+ const int64_t[::1] deltas,
+ intp_t pos,
+):
+ """
+ Infer _TSObject fold property from value by assuming 0 and then setting
+ to 1 if necessary.
+
+ Parameters
+ ----------
+ value : int64_t
+ trans : ndarray[int64_t]
+ ndarray of offset transition points in nanoseconds since epoch.
+ deltas : int64_t[:]
+ array of offsets corresponding to transition points in trans.
+ pos : intp_t
+ Position of the last transition point before taking fold into account.
+
+ Returns
+ -------
+ bint
+ Due to daylight saving time, one wall clock time can occur twice
+ when shifting from summer to winter time; fold describes whether the
+ datetime-like corresponds to the first (0) or the second time (1)
+ the wall clock hits the ambiguous time
+
+ References
+ ----------
+ .. [1] "PEP 495 - Local Time Disambiguation"
+ https://www.python.org/dev/peps/pep-0495/#the-fold-attribute
+ """
+ cdef:
+ bint fold = 0
+
+ if pos > 0:
+ fold_delta = deltas[pos - 1] - deltas[pos]
+ if value - fold_delta < trans[pos]:
+ fold = 1
+
+ return fold
diff --git a/pandas/_libs/tslibs/vectorized.pyx b/pandas/_libs/tslibs/vectorized.pyx
index 07121396df4a2..a37e348154e22 100644
--- a/pandas/_libs/tslibs/vectorized.pyx
+++ b/pandas/_libs/tslibs/vectorized.pyx
@@ -18,8 +18,6 @@ from numpy cimport (
cnp.import_array()
-from .conversion cimport normalize_i8_stamp
-
from .dtypes import Resolution
from .ccalendar cimport DAY_NANOS
@@ -34,7 +32,10 @@ from .np_datetime cimport (
)
from .offsets cimport BaseOffset
from .period cimport get_period_ordinal
-from .timestamps cimport create_timestamp_from_ts
+from .timestamps cimport (
+ create_timestamp_from_ts,
+ normalize_i8_stamp,
+)
from .timezones cimport (
get_dst_info,
is_tzlocal,
| - [ ] 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 an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Trying to de-duplicate a bunch of the timezone-handling code, splitting this off as theres no clear way it could affect perf | https://api.github.com/repos/pandas-dev/pandas/pulls/46516 | 2022-03-25T23:07:36Z | 2022-03-27T21:47:41Z | 2022-03-27T21:47:41Z | 2023-03-02T22:48:59Z |
CI/DOC: pin jinja2 to 3.0.3 | diff --git a/environment.yml b/environment.yml
index f60c68b8d7638..ac8921b12f4a3 100644
--- a/environment.yml
+++ b/environment.yml
@@ -86,7 +86,7 @@ dependencies:
- bottleneck>=1.3.1
- ipykernel
- ipython>=7.11.1
- - jinja2 # pandas.Styler
+ - jinja2<=3.0.3 # pandas.Styler
- matplotlib>=3.3.2 # pandas.plotting, Series.plot, DataFrame.plot
- numexpr>=2.7.1
- scipy>=1.4.1
diff --git a/requirements-dev.txt b/requirements-dev.txt
index f25c51dd58a1c..a0558f1a00177 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -58,7 +58,7 @@ blosc
bottleneck>=1.3.1
ipykernel
ipython>=7.11.1
-jinja2
+jinja2<=3.0.3
matplotlib>=3.3.2
numexpr>=2.7.1
scipy>=1.4.1
| - [ ] closes #xxxx (Replace xxxx with the Github issue number)
- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
Opened #46514 to track | https://api.github.com/repos/pandas-dev/pandas/pulls/46515 | 2022-03-25T22:38:20Z | 2022-03-26T00:51:58Z | 2022-03-26T00:51:58Z | 2022-03-26T00:52:21Z |
TYP: misc | diff --git a/pandas/_typing.py b/pandas/_typing.py
index e3b3a4774f558..30244e025e430 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -104,6 +104,8 @@
# passed in, a DataFrame is always returned.
NDFrameT = TypeVar("NDFrameT", bound="NDFrame")
+NumpyIndexT = TypeVar("NumpyIndexT", np.ndarray, "Index")
+
Axis = Union[str, int]
IndexLabel = Union[Hashable, Sequence[Hashable]]
Level = Union[Hashable, int]
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 8f0516abe8bb3..27260f8ed62ca 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -295,7 +295,9 @@ def asi8(self) -> npt.NDArray[np.int64]:
# ----------------------------------------------------------------
# Rendering Methods
- def _format_native_types(self, *, na_rep="NaT", date_format=None):
+ def _format_native_types(
+ self, *, na_rep="NaT", date_format=None
+ ) -> npt.NDArray[np.object_]:
"""
Helper method for astype when converting to strings.
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index fa543f6773634..7d0b30a1abb60 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -635,7 +635,7 @@ def _formatter(self, boxed: bool = False):
@dtl.ravel_compat
def _format_native_types(
self, *, na_rep="NaT", date_format=None, **kwargs
- ) -> np.ndarray:
+ ) -> npt.NDArray[np.object_]:
"""
actually format my specific types
"""
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index dc63cd92bbb2b..e4a9b156655e9 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -37,6 +37,7 @@
from pandas._typing import (
DtypeObj,
NpDtype,
+ npt,
)
from pandas.compat.numpy import function as nv
from pandas.util._validators import validate_endpoints
@@ -431,7 +432,7 @@ def _formatter(self, boxed: bool = False):
@dtl.ravel_compat
def _format_native_types(
self, *, na_rep="NaT", date_format=None, **kwargs
- ) -> np.ndarray:
+ ) -> npt.NDArray[np.object_]:
from pandas.io.formats.format import get_format_timedelta64
formatter = get_format_timedelta64(self._ndarray, na_rep)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 8b9c537631d94..c34e99298dd0e 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -1511,7 +1511,9 @@ def to_native_types(self, slicer=None, **kwargs) -> np.ndarray:
values = values[slicer]
return values._format_native_types(**kwargs)
- def _format_native_types(self, *, na_rep="", quoting=None, **kwargs):
+ def _format_native_types(
+ self, *, na_rep="", quoting=None, **kwargs
+ ) -> npt.NDArray[np.object_]:
"""
Actually format specific types of the index.
"""
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index c1d7eb972e1f4..425e7d3f4432e 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -820,7 +820,9 @@ def _format_with_header(self, header: list[str], na_rep: str) -> list[str]:
# matches base class except for whitespace padding
return header + list(self._format_native_types(na_rep=na_rep))
- def _format_native_types(self, *, na_rep="NaN", quoting=None, **kwargs):
+ def _format_native_types(
+ self, *, na_rep="NaN", quoting=None, **kwargs
+ ) -> npt.NDArray[np.object_]:
# GH 28210: use base method but with different default na_rep
return super()._format_native_types(na_rep=na_rep, quoting=quoting, **kwargs)
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 1105e7b8a274f..c55312026a893 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1294,7 +1294,9 @@ def _formatter_func(self, tup):
formatter_funcs = [level._formatter_func for level in self.levels]
return tuple(func(val) for func, val in zip(formatter_funcs, tup))
- def _format_native_types(self, *, na_rep="nan", **kwargs):
+ def _format_native_types(
+ self, *, na_rep="nan", **kwargs
+ ) -> npt.NDArray[np.object_]:
new_levels = []
new_codes = []
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py
index be88b874908e8..174e0a7f81850 100644
--- a/pandas/core/indexes/numeric.py
+++ b/pandas/core/indexes/numeric.py
@@ -276,7 +276,7 @@ def _assert_safe_casting(cls, data: np.ndarray, subarr: np.ndarray) -> None:
def _format_native_types(
self, *, na_rep="", float_format=None, decimal=".", quoting=None, **kwargs
- ):
+ ) -> npt.NDArray[np.object_]:
from pandas.io.formats.format import FloatArrayFormatter
if is_float_dtype(self.dtype):
diff --git a/pandas/core/reshape/util.py b/pandas/core/reshape/util.py
index d2c08712abacd..9f9143f4aaa60 100644
--- a/pandas/core/reshape/util.py
+++ b/pandas/core/reshape/util.py
@@ -1,5 +1,7 @@
import numpy as np
+from pandas._typing import NumpyIndexT
+
from pandas.core.dtypes.common import is_list_like
@@ -54,7 +56,7 @@ def cartesian_product(X):
return [tile_compat(np.repeat(x, b[i]), np.product(a[i])) for i, x in enumerate(X)]
-def tile_compat(arr, num: int):
+def tile_compat(arr: NumpyIndexT, num: int) -> NumpyIndexT:
"""
Index compat for np.tile.
diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py
index 3fd2a5e2bca32..c577acfaeba8e 100644
--- a/pandas/io/formats/csvs.py
+++ b/pandas/io/formats/csvs.py
@@ -73,7 +73,7 @@ def __init__(
self.filepath_or_buffer = path_or_buf
self.encoding = encoding
- self.compression = compression
+ self.compression: CompressionOptions = compression
self.mode = mode
self.storage_options = storage_options
| Small set of typing changes to reduce the number of errors of pyright's reportGeneralTypeIssues from 1365 to 1309:
- return value for `_format_native_types`
- TypeVar for `tile_compat`
- When assigning literals to an instance variable, they need explicit type annotations (in this case for `CompressionOptions`), see https://github.com/microsoft/pyright/issues/3256 | https://api.github.com/repos/pandas-dev/pandas/pulls/46513 | 2022-03-25T22:05:56Z | 2022-03-29T00:10:50Z | 2022-03-29T00:10:50Z | 2022-04-01T01:36:30Z |
POC: The real use case for Localizer | diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index 132d742b78e9c..f7a389d6ff38d 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -71,8 +71,7 @@ from pandas._libs.tslibs.nattype cimport (
checknull_with_nat,
)
from pandas._libs.tslibs.tzconversion cimport (
- bisect_right_i8,
- localize_tzinfo_api,
+ Localizer,
tz_localize_to_utc_single,
)
@@ -503,12 +502,10 @@ cdef _TSObject _create_tsobject_tz_using_offset(npy_datetimestruct dts,
obj : _TSObject
"""
cdef:
+ Localizer info = Localizer(tz)
_TSObject obj = _TSObject()
int64_t value # numpy dt64
datetime dt
- ndarray[int64_t] trans
- int64_t* tdata
- int64_t[::1] deltas
value = dtstruct_to_dt64(&dts)
obj.dts = dts
@@ -522,15 +519,8 @@ cdef _TSObject _create_tsobject_tz_using_offset(npy_datetimestruct dts,
# see PEP 495 https://www.python.org/dev/peps/pep-0495/#the-fold-attribute
if is_utc(tz):
pass
- elif is_tzlocal(tz):
- localize_tzinfo_api(obj.value, tz, &obj.fold)
else:
- trans, deltas, typ = get_dst_info(tz)
-
- if typ == 'dateutil':
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
- pos = bisect_right_i8(tdata, obj.value, trans.shape[0]) - 1
- obj.fold = _infer_tsobject_fold(obj, trans, deltas, pos)
+ info.utc_val_to_local_val(obj.value, fold=&obj.fold)
# Keep the converter same as PyDateTime's
dt = datetime(obj.dts.year, obj.dts.month, obj.dts.day,
@@ -678,12 +668,8 @@ cdef inline void _localize_tso(_TSObject obj, tzinfo tz):
Sets obj.tzinfo inplace, alters obj.dts inplace.
"""
cdef:
- ndarray[int64_t] trans
- int64_t[::1] deltas
+ Localizer info = Localizer(tz)
int64_t local_val
- int64_t* tdata
- Py_ssize_t pos, ntrans
- str typ
assert obj.tzinfo is None
@@ -691,84 +677,18 @@ cdef inline void _localize_tso(_TSObject obj, tzinfo tz):
pass
elif obj.value == NPY_NAT:
pass
- elif is_tzlocal(tz):
- local_val = obj.value + localize_tzinfo_api(obj.value, tz, &obj.fold)
- dt64_to_dtstruct(local_val, &obj.dts)
else:
- # Adjust datetime64 timestamp, recompute datetimestruct
- trans, deltas, typ = get_dst_info(tz)
- ntrans = trans.shape[0]
-
- if typ == "pytz":
- # i.e. treat_tz_as_pytz(tz)
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
- pos = bisect_right_i8(tdata, obj.value, ntrans) - 1
- local_val = obj.value + deltas[pos]
+ local_val = info.utc_val_to_local_val(obj.value, &obj.fold)
+ if info.use_pytz:
# find right representation of dst etc in pytz timezone
- tz = tz._tzinfos[tz._transition_info[pos]]
- elif typ == "dateutil":
- # i.e. treat_tz_as_dateutil(tz)
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
- pos = bisect_right_i8(tdata, obj.value, ntrans) - 1
- local_val = obj.value + deltas[pos]
-
- # dateutil supports fold, so we infer fold from value
- obj.fold = _infer_tsobject_fold(obj, trans, deltas, pos)
- else:
- # All other cases have len(deltas) == 1. As of 2018-07-17
- # (and 2022-03-07), all test cases that get here have
- # is_fixed_offset(tz).
- local_val = obj.value + deltas[0]
+ tz = info.adjust_pytz_tzinfo(obj.value)
dt64_to_dtstruct(local_val, &obj.dts)
obj.tzinfo = tz
-cdef inline bint _infer_tsobject_fold(
- _TSObject obj,
- const int64_t[:] trans,
- const int64_t[:] deltas,
- intp_t pos,
-):
- """
- Infer _TSObject fold property from value by assuming 0 and then setting
- to 1 if necessary.
-
- Parameters
- ----------
- obj : _TSObject
- trans : ndarray[int64_t]
- ndarray of offset transition points in nanoseconds since epoch.
- deltas : int64_t[:]
- array of offsets corresponding to transition points in trans.
- pos : intp_t
- Position of the last transition point before taking fold into account.
-
- Returns
- -------
- bint
- Due to daylight saving time, one wall clock time can occur twice
- when shifting from summer to winter time; fold describes whether the
- datetime-like corresponds to the first (0) or the second time (1)
- the wall clock hits the ambiguous time
-
- References
- ----------
- .. [1] "PEP 495 - Local Time Disambiguation"
- https://www.python.org/dev/peps/pep-0495/#the-fold-attribute
- """
- cdef:
- bint fold = 0
-
- if pos > 0:
- fold_delta = deltas[pos - 1] - deltas[pos]
- if obj.value - fold_delta < trans[pos]:
- fold = 1
-
- return fold
-
cdef inline datetime _localize_pydatetime(datetime dt, tzinfo tz):
"""
Take a datetime/Timestamp in UTC and localizes to timezone tz.
diff --git a/pandas/_libs/tslibs/tzconversion.pxd b/pandas/_libs/tslibs/tzconversion.pxd
index 136e62985995e..8b8d9eca547c6 100644
--- a/pandas/_libs/tslibs/tzconversion.pxd
+++ b/pandas/_libs/tslibs/tzconversion.pxd
@@ -1,5 +1,8 @@
from cpython.datetime cimport tzinfo
-from numpy cimport int64_t
+from numpy cimport (
+ int64_t,
+ ndarray,
+)
cdef int64_t localize_tzinfo_api(
@@ -11,3 +14,21 @@ cdef int64_t tz_localize_to_utc_single(
) except? -1
cdef Py_ssize_t bisect_right_i8(int64_t *data, int64_t val, Py_ssize_t n)
+
+
+cdef class Localizer:
+ cdef readonly:
+ tzinfo tz
+ bint use_utc, use_fixed, use_tzlocal, use_dst, use_pytz, use_dateutil
+ ndarray trans
+ Py_ssize_t ntrans
+ const int64_t[::1] deltas
+ int64_t delta
+
+ cdef:
+ int64_t* tdata
+
+ cdef inline int64_t utc_val_to_local_val(
+ self, int64_t utc_val, bint* fold=*
+ )
+ cdef tzinfo adjust_pytz_tzinfo(self, int64_t utc_val)
diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx
index 9190585b2882d..23a89f6343d60 100644
--- a/pandas/_libs/tslibs/tzconversion.pyx
+++ b/pandas/_libs/tslibs/tzconversion.pyx
@@ -459,29 +459,7 @@ cpdef int64_t tz_convert_from_utc_single(int64_t utc_val, tzinfo tz):
-------
converted: int64
"""
- cdef:
- int64_t delta
- int64_t[::1] deltas
- ndarray[int64_t, ndim=1] trans
- int64_t* tdata
- intp_t pos
-
- if utc_val == NPY_NAT:
- return utc_val
-
- if is_utc(tz):
- return utc_val
- elif is_tzlocal(tz):
- return utc_val + _tz_localize_using_tzinfo_api(utc_val, tz, to_utc=False)
- elif is_fixed_offset(tz):
- _, deltas, _ = get_dst_info(tz)
- delta = deltas[0]
- return utc_val + delta
- else:
- trans, deltas, _ = get_dst_info(tz)
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
- pos = bisect_right_i8(tdata, utc_val, trans.shape[0]) - 1
- return utc_val + deltas[pos]
+ return _tz_convert_from_utc(<int64_t[:1]>&utc_val, tz)[0]
def tz_convert_from_utc(const int64_t[:] vals, tzinfo tz):
@@ -503,6 +481,10 @@ def tz_convert_from_utc(const int64_t[:] vals, tzinfo tz):
if vals.shape[0] == 0:
return np.array([], dtype=np.int64)
+ if is_utc(tz) or tz is None:
+ # in some asvs up to 60x faster than going through _tz_convert_from_utc
+ return vals.base.copy()
+
converted = _tz_convert_from_utc(vals, tz)
return np.asarray(converted, dtype=np.int64)
@@ -523,35 +505,14 @@ cdef const int64_t[:] _tz_convert_from_utc(const int64_t[:] stamps, tzinfo tz):
converted : ndarray[int64_t]
"""
cdef:
- Py_ssize_t i, ntrans = -1, n = stamps.shape[0]
- ndarray[int64_t] trans
- int64_t[::1] deltas
- int64_t* tdata = NULL
- intp_t pos
- int64_t utc_val, local_val, delta = NPY_NAT
- bint use_utc = False, use_tzlocal = False, use_fixed = False
- str typ
-
+ Localizer info = Localizer(tz)
+ Py_ssize_t i, n = stamps.shape[0]
int64_t[::1] result
if is_utc(tz) or tz is None:
# Much faster than going through the "standard" pattern below
return stamps.copy()
- if is_utc(tz) or tz is None:
- use_utc = True
- elif is_tzlocal(tz):
- use_tzlocal = True
- else:
- trans, deltas, typ = get_dst_info(tz)
- ntrans = trans.shape[0]
- if typ not in ["pytz", "dateutil"]:
- # static/fixed; in this case we know that len(delta) == 1
- use_fixed = True
- delta = deltas[0]
- else:
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
-
result = np.empty(n, dtype=np.int64)
for i in range(n):
@@ -560,17 +521,7 @@ cdef const int64_t[:] _tz_convert_from_utc(const int64_t[:] stamps, tzinfo tz):
result[i] = NPY_NAT
continue
- # The pattern used in vectorized.pyx checks for use_utc here,
- # but we handle that case above.
- if use_tzlocal:
- local_val = utc_val + _tz_localize_using_tzinfo_api(utc_val, tz, to_utc=False)
- elif use_fixed:
- local_val = utc_val + delta
- else:
- pos = bisect_right_i8(tdata, utc_val, ntrans) - 1
- local_val = utc_val + deltas[pos]
-
- result[i] = local_val
+ result[i] = info.utc_val_to_local_val(utc_val)
return result
@@ -632,3 +583,137 @@ cdef int64_t _tz_localize_using_tzinfo_api(
td = tz.utcoffset(dt)
delta = int(td.total_seconds() * 1_000_000_000)
return delta
+
+
+cdef const int64_t[::1] _deltas_placeholder = np.array([], dtype=np.int64)
+
+
+@cython.freelist(16)
+@cython.final
+cdef class Localizer:
+ # cdef readonly:
+ # tzinfo tz
+ # bint use_utc, use_fixed, use_tzlocal, use_dst, use_pytz
+ # ndarray trans
+ # Py_ssize_t ntrans
+ # const int64_t[::1] deltas
+ # int64_t delta
+
+ @cython.initializedcheck(False)
+ @cython.boundscheck(False)
+ def __cinit__(self, tzinfo tz):
+ self.tz = tz
+ self.use_utc = self.use_tzlocal = self.use_fixed = False
+ self.use_dst = self.use_pytz = self.use_dateutil = False
+ self.ntrans = -1 # placeholder
+ self.delta = -1 # placeholder
+ self.deltas = _deltas_placeholder
+ self.tdata = NULL
+
+ if is_utc(tz) or tz is None:
+ self.use_utc = True
+
+ elif is_tzlocal(tz):
+ self.use_tzlocal = True
+
+ else:
+ trans, deltas, typ = get_dst_info(tz)
+ self.trans = trans
+ self.tdata = <int64_t*>cnp.PyArray_DATA(trans)
+ self.ntrans = trans.shape[0]
+ self.deltas = deltas
+
+ if typ != "pytz" and typ != "dateutil":
+ # static/fixed; in this case we know that len(delta) == 1
+ self.use_fixed = True
+ self.delta = deltas[0]
+ else:
+ self.use_dst = True
+ if typ == "pytz":
+ self.use_pytz = True
+ else:
+ self.use_dateutil = True
+
+ cdef inline int64_t utc_val_to_local_val(self, int64_t utc_val, bint* fold=NULL):
+ cdef:
+ int64_t local_val
+ Py_ssize_t pos
+
+ if self.use_utc:
+ local_val = utc_val
+ elif self.use_tzlocal:
+ local_val = utc_val + localize_tzinfo_api(utc_val, self.tz, fold=fold)
+ elif self.use_fixed:
+ local_val = utc_val + self.delta
+ else:
+ pos = bisect_right_i8(self.tdata, utc_val, self.ntrans) - 1
+ local_val = utc_val + self.deltas[pos]
+
+ if fold is not NULL:
+ if self.use_dateutil:
+ fold[0] = _infer_tsobject_fold(utc_val, self.trans, self.deltas, pos)
+
+ # Very best case we'd be able to set this by pointer the same way
+ # we do with `fold`
+ # if self.use_pytz:
+ # # find right representation of dst etc in pytz timezone
+ # new_tz[0] = self.tz._tzinfos[self.tz._transition_info[pos]]
+ return local_val
+
+ # See commented-out code at the end of utc_val_to_local_val
+ cdef tzinfo adjust_pytz_tzinfo(self, int64_t utc_val):
+ # Caller is responsible for checking self.use_pytz
+ cdef:
+ Py_ssize_t pos
+ tzinfo tz
+
+ pos = bisect_right_i8(self.tdata, utc_val, self.ntrans) - 1
+
+ # find right representation of dst etc in pytz timezone
+ tz = self.tz
+ tz = tz._tzinfos[tz._transition_info[pos]]
+ return tz
+
+
+cdef inline bint _infer_tsobject_fold(
+ int64_t value,
+ const int64_t[::1] trans,
+ const int64_t[::1] deltas,
+ intp_t pos,
+):
+ """
+ Infer _TSObject fold property from value by assuming 0 and then setting
+ to 1 if necessary.
+
+ Parameters
+ ----------
+ value : int64_t
+ trans : ndarray[int64_t]
+ ndarray of offset transition points in nanoseconds since epoch.
+ deltas : int64_t[:]
+ array of offsets corresponding to transition points in trans.
+ pos : intp_t
+ Position of the last transition point before taking fold into account.
+
+ Returns
+ -------
+ bint
+ Due to daylight saving time, one wall clock time can occur twice
+ when shifting from summer to winter time; fold describes whether the
+ datetime-like corresponds to the first (0) or the second time (1)
+ the wall clock hits the ambiguous time
+
+ References
+ ----------
+ .. [1] "PEP 495 - Local Time Disambiguation"
+ https://www.python.org/dev/peps/pep-0495/#the-fold-attribute
+ """
+ cdef:
+ bint fold = 0
+
+ if pos > 0:
+ fold_delta = deltas[pos - 1] - deltas[pos]
+ if value - fold_delta < trans[pos]:
+ fold = 1
+
+ return fold
diff --git a/pandas/_libs/tslibs/vectorized.pyx b/pandas/_libs/tslibs/vectorized.pyx
index 07121396df4a2..3e7cca2026f20 100644
--- a/pandas/_libs/tslibs/vectorized.pyx
+++ b/pandas/_libs/tslibs/vectorized.pyx
@@ -35,15 +35,7 @@ from .np_datetime cimport (
from .offsets cimport BaseOffset
from .period cimport get_period_ordinal
from .timestamps cimport create_timestamp_from_ts
-from .timezones cimport (
- get_dst_info,
- is_tzlocal,
- is_utc,
-)
-from .tzconversion cimport (
- bisect_right_i8,
- localize_tzinfo_api,
-)
+from .tzconversion cimport Localizer
# -------------------------------------------------------------------------
@@ -85,19 +77,13 @@ def ints_to_pydatetime(
ndarray[object] of type specified by box
"""
cdef:
- Py_ssize_t i, ntrans = -1, n = stamps.shape[0]
- ndarray[int64_t] trans
- int64_t[::1] deltas
- int64_t* tdata = NULL
- intp_t pos
- int64_t utc_val, local_val, delta = NPY_NAT
- bint use_utc = False, use_tzlocal = False, use_fixed = False
- str typ
+ Localizer info = Localizer(tz)
+ Py_ssize_t i, n = stamps.shape[0]
+ int64_t utc_val, local_val
npy_datetimestruct dts
tzinfo new_tz
ndarray[object] result = np.empty(n, dtype=object)
- bint use_pytz = False
bint use_date = False, use_time = False, use_ts = False, use_pydt = False
if box == "date":
@@ -114,21 +100,6 @@ def ints_to_pydatetime(
"box must be one of 'datetime', 'date', 'time' or 'timestamp'"
)
- if is_utc(tz) or tz is None:
- use_utc = True
- elif is_tzlocal(tz):
- use_tzlocal = True
- else:
- trans, deltas, typ = get_dst_info(tz)
- ntrans = trans.shape[0]
- if typ not in ["pytz", "dateutil"]:
- # static/fixed; in this case we know that len(delta) == 1
- use_fixed = True
- delta = deltas[0]
- else:
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
- use_pytz = typ == "pytz"
-
for i in range(n):
utc_val = stamps[i]
new_tz = tz
@@ -137,19 +108,10 @@ def ints_to_pydatetime(
result[i] = <object>NaT
continue
- if use_utc:
- local_val = utc_val
- elif use_tzlocal:
- local_val = utc_val + localize_tzinfo_api(utc_val, tz)
- elif use_fixed:
- local_val = utc_val + delta
- else:
- pos = bisect_right_i8(tdata, utc_val, ntrans) - 1
- local_val = utc_val + deltas[pos]
+ local_val = info.utc_val_to_local_val(utc_val)
- if use_pytz:
- # find right representation of dst etc in pytz timezone
- new_tz = tz._tzinfos[tz._transition_info[pos]]
+ if info.use_pytz:
+ new_tz = info.adjust_pytz_tzinfo(utc_val)
dt64_to_dtstruct(local_val, &dts)
@@ -189,46 +151,19 @@ cdef inline c_Resolution _reso_stamp(npy_datetimestruct *dts):
@cython.boundscheck(False)
def get_resolution(const int64_t[:] stamps, tzinfo tz=None) -> Resolution:
cdef:
- Py_ssize_t i, ntrans = -1, n = stamps.shape[0]
- ndarray[int64_t] trans
- int64_t[::1] deltas
- int64_t* tdata = NULL
- intp_t pos
- int64_t utc_val, local_val, delta = NPY_NAT
- bint use_utc = False, use_tzlocal = False, use_fixed = False
- str typ
+ Localizer info = Localizer(tz)
+ Py_ssize_t i, n = stamps.shape[0]
+ int64_t utc_val, local_val
npy_datetimestruct dts
c_Resolution reso = c_Resolution.RESO_DAY, curr_reso
- if is_utc(tz) or tz is None:
- use_utc = True
- elif is_tzlocal(tz):
- use_tzlocal = True
- else:
- trans, deltas, typ = get_dst_info(tz)
- ntrans = trans.shape[0]
- if typ not in ["pytz", "dateutil"]:
- # static/fixed; in this case we know that len(delta) == 1
- use_fixed = True
- delta = deltas[0]
- else:
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
-
for i in range(n):
utc_val = stamps[i]
if utc_val == NPY_NAT:
continue
- if use_utc:
- local_val = utc_val
- elif use_tzlocal:
- local_val = utc_val + localize_tzinfo_api(utc_val, tz)
- elif use_fixed:
- local_val = utc_val + delta
- else:
- pos = bisect_right_i8(tdata, utc_val, ntrans) - 1
- local_val = utc_val + deltas[pos]
+ local_val = info.utc_val_to_local_val(utc_val)
dt64_to_dtstruct(local_val, &dts)
curr_reso = _reso_stamp(&dts)
@@ -258,46 +193,19 @@ cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo t
result : int64 ndarray of converted of normalized nanosecond timestamps
"""
cdef:
- Py_ssize_t i, ntrans = -1, n = stamps.shape[0]
- ndarray[int64_t] trans
- int64_t[::1] deltas
- int64_t* tdata = NULL
- intp_t pos
- int64_t utc_val, local_val, delta = NPY_NAT
- bint use_utc = False, use_tzlocal = False, use_fixed = False
- str typ
+ Localizer info = Localizer(tz)
+ Py_ssize_t i, n = stamps.shape[0]
+ int64_t utc_val, local_val
int64_t[::1] result = np.empty(n, dtype=np.int64)
- if is_utc(tz) or tz is None:
- use_utc = True
- elif is_tzlocal(tz):
- use_tzlocal = True
- else:
- trans, deltas, typ = get_dst_info(tz)
- ntrans = trans.shape[0]
- if typ not in ["pytz", "dateutil"]:
- # static/fixed; in this case we know that len(delta) == 1
- use_fixed = True
- delta = deltas[0]
- else:
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
-
for i in range(n):
utc_val = stamps[i]
if utc_val == NPY_NAT:
result[i] = NPY_NAT
continue
- if use_utc:
- local_val = utc_val
- elif use_tzlocal:
- local_val = utc_val + localize_tzinfo_api(utc_val, tz)
- elif use_fixed:
- local_val = utc_val + delta
- else:
- pos = bisect_right_i8(tdata, utc_val, ntrans) - 1
- local_val = utc_val + deltas[pos]
+ local_val = info.utc_val_to_local_val(utc_val)
result[i] = normalize_i8_stamp(local_val)
@@ -322,40 +230,13 @@ def is_date_array_normalized(const int64_t[:] stamps, tzinfo tz=None) -> bool:
is_normalized : bool True if all stamps are normalized
"""
cdef:
- Py_ssize_t i, ntrans = -1, n = stamps.shape[0]
- ndarray[int64_t] trans
- int64_t[::1] deltas
- int64_t* tdata = NULL
- intp_t pos
- int64_t utc_val, local_val, delta = NPY_NAT
- bint use_utc = False, use_tzlocal = False, use_fixed = False
- str typ
-
- if is_utc(tz) or tz is None:
- use_utc = True
- elif is_tzlocal(tz):
- use_tzlocal = True
- else:
- trans, deltas, typ = get_dst_info(tz)
- ntrans = trans.shape[0]
- if typ not in ["pytz", "dateutil"]:
- # static/fixed; in this case we know that len(delta) == 1
- use_fixed = True
- delta = deltas[0]
- else:
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
+ Localizer info = Localizer(tz)
+ Py_ssize_t i, n = stamps.shape[0]
+ int64_t utc_val, local_val
for i in range(n):
utc_val = stamps[i]
- if use_utc:
- local_val = utc_val
- elif use_tzlocal:
- local_val = utc_val + localize_tzinfo_api(utc_val, tz)
- elif use_fixed:
- local_val = utc_val + delta
- else:
- pos = bisect_right_i8(tdata, utc_val, ntrans) - 1
- local_val = utc_val + deltas[pos]
+ local_val = info.utc_val_to_local_val(utc_val)
if local_val % DAY_NANOS != 0:
return False
@@ -370,31 +251,13 @@ def is_date_array_normalized(const int64_t[:] stamps, tzinfo tz=None) -> bool:
@cython.boundscheck(False)
def dt64arr_to_periodarr(const int64_t[:] stamps, int freq, tzinfo tz):
cdef:
- Py_ssize_t i, ntrans = -1, n = stamps.shape[0]
- ndarray[int64_t] trans
- int64_t[::1] deltas
- int64_t* tdata = NULL
- intp_t pos
- int64_t utc_val, local_val, delta = NPY_NAT
- bint use_utc = False, use_tzlocal = False, use_fixed = False
- str typ
+ Localizer info = Localizer(tz)
+ Py_ssize_t i, n = stamps.shape[0]
+ int64_t utc_val, local_val
npy_datetimestruct dts
int64_t[::1] result = np.empty(n, dtype=np.int64)
- if is_utc(tz) or tz is None:
- use_utc = True
- elif is_tzlocal(tz):
- use_tzlocal = True
- else:
- trans, deltas, typ = get_dst_info(tz)
- ntrans = trans.shape[0]
- if typ not in ["pytz", "dateutil"]:
- # static/fixed; in this case we know that len(delta) == 1
- use_fixed = True
- delta = deltas[0]
- else:
- tdata = <int64_t*>cnp.PyArray_DATA(trans)
for i in range(n):
utc_val = stamps[i]
@@ -402,15 +265,7 @@ def dt64arr_to_periodarr(const int64_t[:] stamps, int freq, tzinfo tz):
result[i] = NPY_NAT
continue
- if use_utc:
- local_val = utc_val
- elif use_tzlocal:
- local_val = utc_val + localize_tzinfo_api(utc_val, tz)
- elif use_fixed:
- local_val = utc_val + delta
- else:
- pos = bisect_right_i8(tdata, utc_val, ntrans) - 1
- local_val = utc_val + deltas[pos]
+ local_val = info.utc_val_to_local_val(utc_val)
dt64_to_dtstruct(local_val, &dts)
result[i] = get_period_ordinal(&dts, freq)
| The Localizer OR #46397 doesn't really do all that much, jus for figuring out perf issues. This is the fleshed-out version where we actually use it to to de-dupliate a whole bunch fo code, | https://api.github.com/repos/pandas-dev/pandas/pulls/46511 | 2022-03-25T18:54:42Z | 2022-04-12T21:36:43Z | null | 2022-04-12T21:36:45Z |
update test suite output in installation guide | diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index e312889f2eb6a..adc8b3d08d441 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -204,17 +204,28 @@ installed), make sure you have `pytest
::
>>> pd.test()
- running: pytest --skip-slow --skip-network C:\Users\TP\Anaconda3\envs\py36\lib\site-packages\pandas
- ============================= test session starts =============================
- platform win32 -- Python 3.6.2, pytest-3.6.0, py-1.4.34, pluggy-0.4.0
- rootdir: C:\Users\TP\Documents\Python\pandasdev\pandas, inifile: setup.cfg
- collected 12145 items / 3 skipped
+ running: pytest --skip-slow --skip-network --skip-db /home/user/anaconda3/lib/python3.9/site-packages/pandas
- ..................................................................S......
- ........S................................................................
- .........................................................................
+ ============================= test session starts ==============================
+ platform linux -- Python 3.9.7, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
+ rootdir: /home/user
+ plugins: dash-1.19.0, anyio-3.5.0, hypothesis-6.29.3
+ collected 154975 items / 4 skipped / 154971 selected
+ ........................................................................ [ 0%]
+ ........................................................................ [ 99%]
+ ....................................... [100%]
- ==================== 12130 passed, 12 skipped in 368.339 seconds =====================
+ ==================================== ERRORS ====================================
+
+ =================================== FAILURES ===================================
+
+ =============================== warnings summary ===============================
+
+ =========================== short test summary info ============================
+
+ = 1 failed, 146194 passed, 7402 skipped, 1367 xfailed, 5 xpassed, 197 warnings, 10 errors in 1090.16s (0:18:10) =
+
+This is just an example of what information is shown. You might see a slightly different result as what is shown above.
.. _install.dependencies:
| - [x] closes #46504
- [x] closes #46498
- [ ] [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 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/46510 | 2022-03-25T18:27:43Z | 2022-03-28T19:40:14Z | 2022-03-28T19:40:14Z | 2022-03-28T19:40:14Z |
return nan on empty groups | diff --git a/pandas/core/series.py b/pandas/core/series.py
index 00384ec26f71d..b3c5ba0d4b3bb 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -960,7 +960,10 @@ def __getitem__(self, key):
key = unpack_1tuple(key)
if is_integer(key) and self.index._should_fallback_to_positional:
- return self._values[key]
+ try:
+ return self._values[key]
+ except IndexError:
+ return np.nan
elif key_is_scalar:
return self._get_value(key)
| - [ ] closes #46496
I'm not sure where in the rst file to specify this behavior change. If its a bug fix or just an enhancement. Any help would be appreciated.
I also ran some of the `test...apply` files and they passed, please let me know what else I should do.
thank you! | https://api.github.com/repos/pandas-dev/pandas/pulls/46506 | 2022-03-25T15:40:00Z | 2022-05-24T02:24:56Z | null | 2022-05-24T02:24:56Z |
DOC remove unused data param from INFO_DOCSTRING | diff --git a/pandas/io/formats/info.py b/pandas/io/formats/info.py
index b42bc47856e1b..c0bdf37e5273a 100644
--- a/pandas/io/formats/info.py
+++ b/pandas/io/formats/info.py
@@ -258,8 +258,6 @@
Parameters
----------
- data : {klass}
- {klass} to print information about.
verbose : bool, optional
Whether to print the full summary. By default, the setting in
``pandas.options.display.max_info_columns`` is followed.
| - Updated during PyLadies London Sprint | https://api.github.com/repos/pandas-dev/pandas/pulls/46503 | 2022-03-25T11:58:48Z | 2022-03-25T22:58:27Z | 2022-03-25T22:58:27Z | 2022-03-25T22:58:32Z |
CI Clean up code | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 4498585e36ce5..ec8545ad1ee4a 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -78,8 +78,8 @@ fi
### DOCSTRINGS ###
if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
- MSG='Validate docstrings (GL01, GL02, GL03, GL04, GL05, GL06, GL07, GL09, GL10, SS01, SS02, SS03, SS04, SS05, PR03, PR04, PR05, PR06, PR08, PR09, PR10, EX04, RT01, RT04, RT05, SA02, SA03)' ; echo $MSG
- $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=GL01,GL02,GL03,GL04,GL05,GL06,GL07,GL09,GL10,SS02,SS03,SS04,SS05,PR03,PR04,PR05,PR06,PR08,PR09,PR10,EX04,RT01,RT04,RT05,SA02,SA03
+ MSG='Validate docstrings (EX04, GL01, GL02, GL03, GL04, GL05, GL06, GL07, GL09, GL10, PR03, PR04, PR05, PR06, PR08, PR09, PR10, RT01, RT04, RT05, SA02, SA03, SS01, SS02, SS03, SS04, SS05)' ; echo $MSG
+ $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX04,GL01,GL02,GL03,GL04,GL05,GL06,GL07,GL09,GL10,PR03,PR04,PR05,PR06,PR08,PR09,PR10,RT01,RT04,RT05,SA02,SA03,SS01,SS02,SS03,SS04,SS05
RET=$(($RET + $?)) ; echo $MSG "DONE"
fi
| - [ ] 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 an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
- [ ] Worked on during pyladies london sprint, cleaned up code and added SS01
| https://api.github.com/repos/pandas-dev/pandas/pulls/46502 | 2022-03-25T11:44:07Z | 2022-03-25T19:01:30Z | 2022-03-25T19:01:30Z | 2022-03-25T19:01:30Z |
Backport PR #46119 on branch 1.4.x (REF: isinstance(x, int) -> is_integer(x)) | diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index 2e9a62a54cd44..34d047eb59be6 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -25,6 +25,11 @@
from pandas._typing import Level
from pandas.compat._optional import import_optional_dependency
+from pandas.core.dtypes.common import (
+ is_complex,
+ is_float,
+ is_integer,
+)
from pandas.core.dtypes.generic import ABCSeries
from pandas import (
@@ -1431,9 +1436,9 @@ def _default_formatter(x: Any, precision: int, thousands: bool = False) -> Any:
value : Any
Matches input type, or string if input is float or complex or int with sep.
"""
- if isinstance(x, (float, complex)):
+ if is_float(x) or is_complex(x):
return f"{x:,.{precision}f}" if thousands else f"{x:.{precision}f}"
- elif isinstance(x, int):
+ elif is_integer(x):
return f"{x:,.0f}" if thousands else f"{x:.0f}"
return x
@@ -1448,7 +1453,7 @@ def _wrap_decimal_thousands(
"""
def wrapper(x):
- if isinstance(x, (float, complex, int)):
+ if is_float(x) or is_integer(x) or is_complex(x):
if decimal != "." and thousands is not None and thousands != ",":
return (
formatter(x)
| Backport PR #46119: REF: isinstance(x, int) -> is_integer(x) | https://api.github.com/repos/pandas-dev/pandas/pulls/46501 | 2022-03-25T11:41:02Z | 2022-03-29T11:27:21Z | 2022-03-29T11:27:21Z | 2022-03-29T11:27:21Z |
Revert "REF: isinstance(x, int) -> is_integer(x)" | diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index 4e3f86d21b228..c7c64f448af51 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -25,11 +25,6 @@
from pandas._typing import Level
from pandas.compat._optional import import_optional_dependency
-from pandas.core.dtypes.common import (
- is_complex,
- is_float,
- is_integer,
-)
from pandas.core.dtypes.generic import ABCSeries
from pandas import (
@@ -1532,9 +1527,9 @@ def _default_formatter(x: Any, precision: int, thousands: bool = False) -> Any:
value : Any
Matches input type, or string if input is float or complex or int with sep.
"""
- if is_float(x) or is_complex(x):
+ if isinstance(x, (float, complex)):
return f"{x:,.{precision}f}" if thousands else f"{x:.{precision}f}"
- elif is_integer(x):
+ elif isinstance(x, int):
return f"{x:,.0f}" if thousands else f"{x:.0f}"
return x
@@ -1549,7 +1544,7 @@ def _wrap_decimal_thousands(
"""
def wrapper(x):
- if is_float(x) or is_integer(x) or is_complex(x):
+ if isinstance(x, (float, complex, int)):
if decimal != "." and thousands is not None and thousands != ",":
return (
formatter(x)
| Reverts pandas-dev/pandas#46119
It looks like this can be auto reverted. (won't know till ci has run)
@attack68 if we revert this, we could redo and add a regression test for #46384 to address https://github.com/pandas-dev/pandas/pull/46119#issuecomment-1049069600, add a release note for the bugfix and maybe backport to 1.4.x. wdyt?
I think should probably reopen #46384 and add a test to close that issue off anyway. | https://api.github.com/repos/pandas-dev/pandas/pulls/46500 | 2022-03-25T11:10:43Z | 2022-03-28T20:38:16Z | null | 2022-06-07T00:18:28Z |
Backport PR #46457 on branch 1.4.x (BUG: url regex in `style_render` does not pass colon and other valid) | diff --git a/doc/source/whatsnew/v1.4.2.rst b/doc/source/whatsnew/v1.4.2.rst
index 4cbb8118055af..13f3e9a0d0a8c 100644
--- a/doc/source/whatsnew/v1.4.2.rst
+++ b/doc/source/whatsnew/v1.4.2.rst
@@ -31,7 +31,7 @@ Bug fixes
~~~~~~~~~
- Fix some cases for subclasses that define their ``_constructor`` properties as general callables (:issue:`46018`)
- Fixed "longtable" formatting in :meth:`.Styler.to_latex` when ``column_format`` is given in extended format (:issue:`46037`)
--
+- Fixed incorrect rendering in :meth:`.Styler.format` with ``hyperlinks="html"`` when the url contains a colon or other special characters (:issue:`46389`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index e15387b1e2bae..2e9a62a54cd44 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -1488,7 +1488,7 @@ def _render_href(x, format):
href = r"\href{{{0}}}{{{0}}}"
else:
raise ValueError("``hyperlinks`` format can only be 'html' or 'latex'")
- pat = r"(https?:\/\/|ftp:\/\/|www.)[\w/\-?=%.]+\.[\w/\-&?=%.]+"
+ pat = r"((http|ftp)s?:\/\/|www.)[\w/\-?=%.:@]+\.[\w/\-&?=%.,':;~!@#$*()\[\]]+"
return re.sub(pat, lambda m: href.format(m.group(0)), x)
return x
diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py
index fad289d5e0d2c..1903d4174e638 100644
--- a/pandas/tests/io/formats/style/test_html.py
+++ b/pandas/tests/io/formats/style/test_html.py
@@ -778,8 +778,20 @@ def test_hiding_index_columns_multiindex_trimming():
("no scheme, no top-level: www.web", False, "www.web"),
("https scheme: https://www.web.com", True, "https://www.web.com"),
("ftp scheme: ftp://www.web", True, "ftp://www.web"),
+ ("ftps scheme: ftps://www.web", True, "ftps://www.web"),
("subdirectories: www.web.com/directory", True, "www.web.com/directory"),
("Multiple domains: www.1.2.3.4", True, "www.1.2.3.4"),
+ ("with port: http://web.com:80", True, "http://web.com:80"),
+ (
+ "full net_loc scheme: http://user:pass@web.com",
+ True,
+ "http://user:pass@web.com",
+ ),
+ (
+ "with valid special chars: http://web.com/,.':;~!@#$*()[]",
+ True,
+ "http://web.com/,.':;~!@#$*()[]",
+ ),
],
)
def test_rendered_links(type, text, exp, found):
| Backport PR #46457: BUG: url regex in `style_render` does not pass colon and other valid | https://api.github.com/repos/pandas-dev/pandas/pulls/46497 | 2022-03-24T18:16:57Z | 2022-03-25T00:44:20Z | 2022-03-25T00:44:20Z | 2022-03-25T00:44:21Z |
DOC: setting allows_duplicate_labels=False(#46480) | diff --git a/doc/source/user_guide/duplicates.rst b/doc/source/user_guide/duplicates.rst
index 36c2ec53d58b4..7894789846ce8 100644
--- a/doc/source/user_guide/duplicates.rst
+++ b/doc/source/user_guide/duplicates.rst
@@ -172,7 +172,7 @@ going forward, to ensure that your data pipeline doesn't introduce duplicates.
>>> deduplicated = raw.groupby(level=0).first() # remove duplicates
>>> deduplicated.flags.allows_duplicate_labels = False # disallow going forward
-Setting ``allows_duplicate_labels=True`` on a ``Series`` or ``DataFrame`` with duplicate
+Setting ``allows_duplicate_labels=False`` on a ``Series`` or ``DataFrame`` with duplicate
labels or performing an operation that introduces duplicate labels on a ``Series`` or
``DataFrame`` that disallows duplicates will raise an
:class:`errors.DuplicateLabelError`.
| - [ ] closes #46480 (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 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/46495 | 2022-03-24T12:38:16Z | 2022-03-26T13:39:11Z | 2022-03-26T13:39:11Z | 2022-03-26T13:39:19Z |
Refactor CI | diff --git a/.circleci/config.yml b/.circleci/config.yml
index 612552f4eac59..0d9e3ade08846 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -13,7 +13,7 @@ jobs:
PANDAS_CI: "1"
steps:
- checkout
- - run: ci/setup_env.sh
+ - run: .circleci/setup_env.sh
- run: PATH=$HOME/miniconda3/envs/pandas-dev/bin:$HOME/miniconda3/condabin:$PATH ci/run_tests.sh
workflows:
diff --git a/ci/setup_env.sh b/.circleci/setup_env.sh
similarity index 100%
rename from ci/setup_env.sh
rename to .circleci/setup_env.sh
diff --git a/.github/actions/build-pandas/action.yml b/.github/actions/build-pandas/action.yml
new file mode 100644
index 0000000000000..70dcff5f2df7a
--- /dev/null
+++ b/.github/actions/build-pandas/action.yml
@@ -0,0 +1,27 @@
+name: Build pandas
+description: Rebuilds the C extensions and installs pandas
+runs:
+ using: composite
+ steps:
+ - name: Environment Detail
+ run: |
+ if which mamba 2>/dev/null; then
+ mamba info
+ mamba list
+ mamba info | grep -Ei 'environment.+:' | grep -qEiv 'environment.+:.+none'
+ fi
+ pip list
+ python --version
+ shell: bash -el {0}
+
+ - name: Build Pandas
+ run: |
+ which python
+ which pip
+ time python setup.py build_ext -v -j 2
+ pip install -v -e . --no-build-isolation --no-use-pep517 --no-index
+ shell: bash -el {0}
+
+ - name: Build Version
+ run: pushd /tmp && python -c "import pandas; pandas.show_versions();" && popd
+ shell: bash -el {0}
diff --git a/.github/actions/build_pandas/action.yml b/.github/actions/build_pandas/action.yml
deleted file mode 100644
index 2e4bfea165316..0000000000000
--- a/.github/actions/build_pandas/action.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-name: Build pandas
-description: Rebuilds the C extensions and installs pandas
-runs:
- using: composite
- steps:
-
- - name: Environment Detail
- run: |
- conda info
- conda list
- shell: bash -l {0}
-
- - name: Build Pandas
- run: |
- python setup.py build_ext -j 2
- python -m pip install -e . --no-build-isolation --no-use-pep517 --no-index
- shell: bash -l {0}
diff --git a/.github/actions/run-tests/action.yml b/.github/actions/run-tests/action.yml
new file mode 100644
index 0000000000000..45c9f24118b79
--- /dev/null
+++ b/.github/actions/run-tests/action.yml
@@ -0,0 +1,34 @@
+name: Run tests and report results
+inputs:
+ check-pyarrow-version:
+ required: false
+runs:
+ using: composite
+ steps:
+ - name: Check PyArrow version
+ run: |
+ # Double check that we have the expected PyArrow
+ pushd /tmp
+ python -c "import pandas; pandas.show_versions()" | egrep -i "pyarrow.+: ${{ matrix.check-pyarrow-version }}"
+ popd
+ shell: bash -el {0}
+ if: ${{ inputs.check-pyarrow-version }}
+
+ - name: Test
+ run: ci/run_tests.sh
+ shell: bash -el {0}
+
+ - name: Publish test results
+ uses: actions/upload-artifact@v2
+ with:
+ name: Test results
+ path: test-data.xml
+ if: failure()
+
+ - name: Upload coverage to Codecov
+ uses: codecov/codecov-action@v2
+ with:
+ flags: unittests
+ name: codecov-pandas
+ fail_ci_if_error: false
+ if: failure()
diff --git a/.github/actions/setup-python/action.yml b/.github/actions/setup-python/action.yml
new file mode 100644
index 0000000000000..3345ff72688dd
--- /dev/null
+++ b/.github/actions/setup-python/action.yml
@@ -0,0 +1,65 @@
+name: Setup Python and install requirements
+inputs:
+ python-version:
+ required: true
+ architecture:
+ default: x64
+runs:
+ using: composite
+ steps:
+ # TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
+ - name: Create temporary requirements.txt
+ run: |
+ # Drop cache at least once per month
+ month_today="$(date '+%Y-%m')"
+ cat > requirements.txt <<EOF
+ # $month_today
+
+ # Python deps
+ pip
+ setuptools<60.0.0
+ wheel
+
+ # Pandas deps
+ # GH 39416
+ numpy
+ cython
+ python-dateutil
+ pytz
+
+ # Test deps
+ git+https://github.com/nedbat/coveragepy.git
+ hypothesis
+ pytest>=6.2.5
+ pytest-xdist
+ pytest-cov
+ pytest-asyncio>=0.17
+ EOF
+ shell: bash -el {0}
+
+ - name: Set up Python
+ uses: actions/setup-python@v3
+ with:
+ python-version: ${{ inputs.python-version }}
+ architecture: ${{ inputs.architecture }}
+ cache: pip
+
+ - name: Fix $PATH on macOS
+ run: |
+ # On macOS, the Python version we installed above is too late in $PATH
+ # to be effective if using "bash -l" (which we need for code that works
+ # with Conda envs).
+ cat >> ~/.bash_profile <<EOF
+ export PATH="\$(echo "\$PATH" | grep -Eio '[^:]+hostedtoolcache/python[^:]+bin'):\$PATH" \
+ EOF
+ shell: bash -el {0}
+ if: ${{ runner.os == 'macOS' }}
+
+ - name: Install dependencies
+ run: |
+ cat requirements.txt
+ # TODO https://github.com/numpy/numpy/issues/21196
+ bits32=$(python -c 'import sys; print(int(sys.maxsize > 2**32))')
+ NPY_DISABLE_SVML=$bits32 pip install -r requirements.txt
+ pip list
+ shell: bash -el {0}
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml
index 9ef00e7a85a6f..ec583b2195da9 100644
--- a/.github/actions/setup/action.yml
+++ b/.github/actions/setup/action.yml
@@ -1,12 +1,58 @@
name: Set up pandas
description: Runs all the setup steps required to have a built pandas ready to use
+inputs:
+ environment-file:
+ default: environment.yml
+ pyarrow-version:
+ required: false
+ is-pypy:
+ default: false
+ environment-name:
+ default: pandas-dev
+ python-version:
+ required: false
runs:
using: composite
steps:
- - name: Setting conda path
- run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
- shell: bash -l {0}
+ - name: Set Arrow version in ${{ inputs.environment-file }} to ${{ inputs.pyarrow-version }}
+ run: |
+ grep -q ' - pyarrow' ${{ inputs.environment-file }}
+ sed -i"" -e "s/ - pyarrow/ - pyarrow=${{ inputs.pyarrow-version }}/" ${{ inputs.environment-file }}
+ cat ${{ inputs.environment-file }}
+ shell: bash
+ if: ${{ inputs.pyarrow-version }}
- - name: Setup environment and build pandas
- run: ci/setup_env.sh
- shell: bash -l {0}
+ - name: Set Python version in ${{ inputs.environment-file }} to ${{ inputs.python-version }}
+ run: |
+ echo " - python=${{ inputs.pyarrow-version }}" >> ${{ inputs.environment-file }}
+ cat ${{ inputs.environment-file }}
+ shell: bash
+ if: ${{ inputs.python-version }}
+
+ - name: Pin setuptools (GH#44980)
+ run: |
+ echo ' - setuptools <60' >> ${{ inputs.environment-file }}
+ shell: bash
+
+ - name: Install ${{ inputs.environment-file }} (Python ${{ inputs.python-version }})
+ uses: conda-incubator/setup-miniconda@v2
+ with:
+ activate-environment: ${{ inputs.environment-name }}
+ environment-file: ${{ inputs.environment-file }}
+ channel-priority: strict
+ channels: conda-forge
+ mamba-version: "0.22"
+ use-mamba: true
+ if: ${{ inputs.is-pypy == 'false' }} # No pypy3.8 support
+
+ - name: Setup PyPy
+ uses: actions/setup-python@v3
+ with:
+ python-version: "pypy-3.8"
+ if: ${{ inputs.is-pypy == 'true' }}
+
+ - name: Setup PyPy dependencies
+ # TODO: re-enable cov, its slowing the tests down though
+ run: pip install Cython numpy python-dateutil pytz pytest>=6.0 pytest-xdist>=1.31.0 hypothesis>=5.5.3 pytest-asyncio>=0.17
+ shell: bash
+ if: ${{ inputs.is-pypy == 'true' }}
diff --git a/.github/workflows/asv-bot.yml b/.github/workflows/asv-bot.yml
index f3946aeb84a63..63cad09e2e223 100644
--- a/.github/workflows/asv-bot.yml
+++ b/.github/workflows/asv-bot.yml
@@ -6,8 +6,7 @@ on:
- created
env:
- ENV_FILE: environment.yml
- COMMENT: ${{github.event.comment.body}}
+ COMMENT: ${{ github.event.comment.body }}
jobs:
autotune:
@@ -17,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# Set concurrency to prevent abuse(full runs are ~5.5 hours !!!)
@@ -29,24 +28,14 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- - name: Cache conda
- uses: actions/cache@v2
- with:
- path: ~/conda_pkgs_dir
- key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
-
- # Although asv sets up its own env, deps are still needed
- # during discovery process
- - uses: conda-incubator/setup-miniconda@v2
- with:
- activate-environment: pandas-dev
- channel-priority: strict
- environment-file: ${{ env.ENV_FILE }}
- use-only-tar-bz2: true
+ # Although asv sets up its own env, deps are still needed
+ # during discovery process
+ - name: Set up Conda
+ uses: ./.github/actions/setup
- name: Run benchmarks
id: bench
diff --git a/.github/workflows/autoupdate-pre-commit-config.yml b/.github/workflows/autoupdate-pre-commit-config.yml
index 3696cba8cf2e6..11484f98995bc 100644
--- a/.github/workflows/autoupdate-pre-commit-config.yml
+++ b/.github/workflows/autoupdate-pre-commit-config.yml
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
- name: Cache multiple paths
uses: actions/cache@v2
with:
diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index f32fed3b3ee68..667f3da6ce972 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -11,7 +11,6 @@ on:
- 1.4.x
env:
- ENV_FILE: environment.yml
PANDAS_CI: 1
jobs:
@@ -24,10 +23,10 @@ jobs:
cancel-in-progress: true
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
- name: Install Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: '3.9.7'
@@ -39,7 +38,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
@@ -48,24 +47,17 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- - name: Cache conda
- uses: actions/cache@v2
- with:
- path: ~/conda_pkgs_dir
- key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
+ - name: Set up Conda
+ uses: ./.github/actions/setup
- - uses: conda-incubator/setup-miniconda@v2
- with:
- mamba-version: "*"
- channels: conda-forge
- activate-environment: pandas-dev
- channel-priority: strict
- environment-file: ${{ env.ENV_FILE }}
- use-only-tar-bz2: true
+ - name: Build Pandas
+ uses: ./.github/actions/build-pandas
+ id: build
+ continue-on-error: true
- name: Install node.js (for pyright)
uses: actions/setup-node@v2
@@ -76,10 +68,6 @@ jobs:
# note: keep version in sync with .pre-commit-config.yaml
run: npm install -g pyright@1.1.230
- - name: Build Pandas
- id: build
- uses: ./.github/actions/build_pandas
-
- name: Run checks on imported code
run: ci/code_checks.sh code
if: ${{ steps.build.outcome == 'success' }}
@@ -105,7 +93,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
@@ -114,28 +102,15 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- - name: Cache conda
- uses: actions/cache@v2
- with:
- path: ~/conda_pkgs_dir
- key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }}
-
- - uses: conda-incubator/setup-miniconda@v2
- with:
- mamba-version: "*"
- channels: conda-forge
- activate-environment: pandas-dev
- channel-priority: strict
- environment-file: ${{ env.ENV_FILE }}
- use-only-tar-bz2: true
+ - name: Set up Conda
+ uses: ./.github/actions/setup
- name: Build Pandas
- id: build
- uses: ./.github/actions/build_pandas
+ uses: ./.github/actions/build-pandas
- name: Run ASV benchmarks
run: |
@@ -148,7 +123,6 @@ jobs:
if grep "failed" benchmarks.log > /dev/null ; then
exit 1
fi
- if: ${{ steps.build.outcome == 'success' }}
- name: Publish benchmarks artifact
uses: actions/upload-artifact@v2
@@ -162,7 +136,7 @@ jobs:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
@@ -174,7 +148,7 @@ jobs:
run: docker image prune -f
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
diff --git a/.github/workflows/comment_bot.yml b/.github/workflows/comment_bot.yml
index 8f610fd5781ef..5c47a500a0f9e 100644
--- a/.github/workflows/comment_bot.yml
+++ b/.github/workflows/comment_bot.yml
@@ -12,7 +12,7 @@ jobs:
if: startsWith(github.event.comment.body, '@github-actions pre-commit')
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- uses: r-lib/actions/pr-fetch@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
@@ -23,7 +23,7 @@ jobs:
~/.cache/pre-commit
~/.cache/pip
key: pre-commit-dispatched-${{ runner.os }}-build
- - uses: actions/setup-python@v2
+ - uses: actions/setup-python@v3
with:
python-version: 3.8
- name: Install-pre-commit
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml
index 4cce75779d750..8b8154cc53d53 100644
--- a/.github/workflows/docbuild-and-upload.yml
+++ b/.github/workflows/docbuild-and-upload.yml
@@ -11,13 +11,15 @@ on:
- 1.4.x
env:
- ENV_FILE: environment.yml
PANDAS_CI: 1
jobs:
web_and_docs:
name: Doc Build and Upload
runs-on: ubuntu-latest
+ defaults:
+ run:
+ shell: bash -el {0}
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
@@ -26,21 +28,21 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- - name: Set up pandas
+ - name: Set up Conda
uses: ./.github/actions/setup
+ - name: Build pandas
+ uses: ./.github/actions/build-pandas
+
- name: Build website
- run: |
- source activate pandas-dev
- python web/pandas_web.py web/pandas --target-path=web/build
+ run: python web/pandas_web.py web/pandas --target-path=web/build
+
- name: Build documentation
- run: |
- source activate pandas-dev
- doc/make.py --warnings-are-errors
+ run: doc/make.py --warnings-are-errors
- name: Install ssh key
run: |
diff --git a/.github/workflows/macos-windows.yml b/.github/workflows/macos-windows.yml
new file mode 100644
index 0000000000000..8d2df387d5f75
--- /dev/null
+++ b/.github/workflows/macos-windows.yml
@@ -0,0 +1,62 @@
+name: macOS and Windows
+
+on:
+ push:
+ branches:
+ - main
+ - 1.4.x
+ pull_request:
+ branches:
+ - main
+ - 1.4.x
+ paths-ignore:
+ - "doc/**"
+
+env:
+ PANDAS_CI: 1
+ PYTEST_TARGET: pandas
+ PYTEST_WORKERS: auto
+ PATTERN: "not slow and not db and not network and not single_cpu"
+
+jobs:
+ pytest:
+ runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ shell: bash -el {0}
+ timeout-minutes: 120
+ strategy:
+ matrix:
+ os: [macos-10.15, windows-2019]
+ env_file: [actions-38.yaml, actions-39.yaml, actions-310.yaml]
+ pyarrow_version: [6]
+ fail-fast: false
+ name: ${{ matrix.name || format('{0} {1} pyarrow={2}', matrix.os, matrix.env_file, matrix.pyarrow_version) }}
+ concurrency:
+ # https://github.community/t/concurrecy-not-work-for-push/183068/7
+ group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.os }}-${{ matrix.env_file }}-${{ matrix.pyarrow_version }}-mac-win
+ cancel-in-progress: true
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
+
+ - name: wmic.exe
+ run: wmic.exe cpu get caption, deviceid, name, numberofcores, maxclockspeed
+ if: ${{ runner.os == 'Windows' }}
+
+ - name: Set up Conda (${{ matrix.env_file }}, Arrow ${{ matrix.pyarrow_version}})
+ uses: ./.github/actions/setup
+ with:
+ environment-file: ci/deps/${{ matrix.env_file }}
+ pyarrow-version: ${{ matrix.pyarrow_version }}
+
+ - name: Build pandas
+ uses: ./.github/actions/build-pandas
+
+ - name: Run tests
+ uses: ./.github/actions/run-tests
+ with:
+ check-pyarrow-version: ${{ matrix.pyarrow_version }}
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index c287827206336..c9446e6cbb6c2 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -21,11 +21,11 @@ on:
- "doc/**"
env:
- PYTEST_WORKERS: "auto"
PANDAS_CI: 1
+ PYTEST_TARGET: pandas
+ PYTEST_WORKERS: "auto"
PATTERN: "not slow and not network and not clipboard and not single_cpu"
COVERAGE: true
- PYTEST_TARGET: pandas
jobs:
build:
@@ -35,63 +35,43 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest, macOS-latest, windows-latest]
+ python-version: ["3.11-dev"]
- name: actions-311-dev
+ name: ${{ matrix.python-version }}
timeout-minutes: 80
+ defaults:
+ run:
+ shell: bash -el {0}
concurrency:
#https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.os }}-${{ matrix.pytest_target }}-dev
+ group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.os }}-dev
cancel-in-progress: true
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
with:
fetch-depth: 0
- - name: Set up Python Dev Version
- uses: actions/setup-python@v2
+ - name: Set up Python ${{ matrix.python-version }} and install dependencies
+ uses: ./.github/actions/setup-python
with:
- python-version: '3.11-dev'
+ python-version: ${{ matrix.python-version }}
- # TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- - name: Install dependencies
- shell: bash
- run: |
- python -m pip install --upgrade pip "setuptools<60.0.0" wheel
- pip install -i https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
- pip install git+https://github.com/nedbat/coveragepy.git
- pip install cython python-dateutil pytz hypothesis pytest>=6.2.5 pytest-xdist pytest-cov
- pip list
+ - name: Install NumPy nightly
+ run:
+ pip install -Ui https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy
- - name: Build Pandas
- run: |
- python setup.py build_ext -q -j2
- python -m pip install -e . --no-build-isolation --no-use-pep517
+ - name: Build pandas
+ uses: ./.github/actions/build-pandas
- - name: Build Version
+ - name: Install pandas from sdist
run: |
- python -c "import pandas; pandas.show_versions();"
-
- - name: Test with pytest
- shell: bash
- run: |
- ci/run_tests.sh
-
- - name: Publish test results
- uses: actions/upload-artifact@v2
- with:
- name: Test results
- path: test-data.xml
- if: failure()
-
- - name: Report Coverage
- run: |
- coverage report -m
+ # Double check that we have the expected Python and NumPy
+ python --version
+ pip list
+ python --version | grep -i "$(echo "${{ matrix.python-version }}" | sed 's/-.*//')"
+ pip list | egrep -i "numpy.+dev"
- - name: Upload coverage to Codecov
- uses: codecov/codecov-action@v2
- with:
- flags: unittests
- name: codecov-pandas
- fail_ci_if_error: true
+ - name: Run tests
+ uses: ./.github/actions/run-tests
diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml
index 431710a49a7dd..3fcea5e68782b 100644
--- a/.github/workflows/sdist.yml
+++ b/.github/workflows/sdist.yml
@@ -14,78 +14,87 @@ on:
- "doc/**"
jobs:
- build:
- if: ${{ github.event.label.name == 'Build' || contains(github.event.pull_request.labels.*.name, 'Build') || github.event_name == 'push'}}
+ sdist:
+ #if: ${{ github.event.label.name == 'Build' || contains(github.event.pull_request.labels.*.name, 'Build') || github.event_name == 'push'}}
runs-on: ubuntu-latest
timeout-minutes: 60
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
strategy:
fail-fast: false
matrix:
- python-version: ["3.8", "3.9", "3.10"]
+ # 'numpy-version' is oldest supported NumPy
+ include:
+ - python-version: "3.8"
+ numpy-version: "1.18.5"
+ - python-version: "3.9"
+ numpy-version: "1.19.4"
+ - python-version: "3.10"
+ numpy-version: "1.21.3"
+
+ name: sdist Python ${{ matrix.python-version }} NumPy ${{ matrix.numpy-version }}
+
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{matrix.python-version}}-sdist
+ group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.python-version }}-sdist
cancel-in-progress: true
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
with:
fetch-depth: 0
- - name: Set up Python
- uses: actions/setup-python@v2
+ - name: Set up Python ${{ matrix.python-version }} and install dependencies
+ uses: ./.github/actions/setup-python
with:
python-version: ${{ matrix.python-version }}
- # TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- - name: Install dependencies
- run: |
- python -m pip install --upgrade pip "setuptools<60.0.0" wheel
-
- # GH 39416
- pip install numpy
-
- name: Build pandas sdist
- run: |
- pip list
- python setup.py sdist --formats=gztar
+ run: python setup.py sdist --formats=gztar
- name: Upload sdist artifact
uses: actions/upload-artifact@v3
with:
- name: ${{matrix.python-version}}-sdist.gz
+ name: ${{ matrix.python-version }}-sdist.gz
path: dist/*.gz
- - uses: conda-incubator/setup-miniconda@v2
+ - name: Create environment.yml with Python ${{ matrix.python-version }}, NumPy ${{ matrix.numpy-version }}
+ run: |
+ cat >> tmp_environment.yml <<EOF
+ name: pandas-sdist
+ channels:
+ - conda-forge
+ dependencies:
+ - python=${{ matrix.python-version }}
+ - setuptools<60
+ - numpy=${{ matrix.numpy-version }}
+ EOF
+
+ - name: Install Conda enviroment
+ uses: conda-incubator/setup-miniconda@v2
with:
activate-environment: pandas-sdist
+ environment-file: tmp_environment.yml
+ channel-priority: strict
channels: conda-forge
- python-version: '${{ matrix.python-version }}'
+ mamba-version: "0.22"
+ use-mamba: true
- # TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- name: Install pandas from sdist
run: |
- python -m pip install --upgrade "setuptools<60.0.0"
+ mamba info
+ # Double check that we have the expected NumPy
pip list
- python -m pip install dist/*.gz
-
- - name: Force oldest supported NumPy
- run: |
- case "${{matrix.python-version}}" in
- 3.8)
- pip install numpy==1.18.5 ;;
- 3.9)
- pip install numpy==1.19.3 ;;
- 3.10)
- pip install numpy==1.21.2 ;;
- esac
+ pip list | egrep -i "numpy.+${{ matrix.numpy-version }}"
+ time python -m pip install -v dist/*.gz
- - name: Import pandas
+ - name: Build Version
run: |
- cd ..
- conda list
- python -c "import pandas; pandas.show_versions();"
+ pushd /tmp
+ python -c "import pandas; pandas.show_versions()"
+ # Double check that we have the expected Python and NumPy
+ python -c "import pandas; pandas.show_versions()" | egrep -i "python.+: ${{ matrix.python-version }}"
+ python -c "import pandas; pandas.show_versions()" | egrep -i "numpy.+: ${{ matrix.numpy-version }}"
+ popd
diff --git a/.github/workflows/posix.yml b/.github/workflows/ubuntu.yml
similarity index 61%
rename from .github/workflows/posix.yml
rename to .github/workflows/ubuntu.yml
index bc8791afc69f7..ecb26f5a5a200 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/ubuntu.yml
@@ -1,4 +1,4 @@
-name: Posix
+name: Ubuntu
on:
push:
@@ -12,15 +12,12 @@ on:
paths-ignore:
- "doc/**"
-env:
- PANDAS_CI: 1
-
jobs:
pytest:
runs-on: ubuntu-latest
defaults:
run:
- shell: bash -l {0}
+ shell: bash -el {0}
timeout-minutes: 120
strategy:
matrix:
@@ -30,41 +27,42 @@ jobs:
# even if tests are skipped/xfailed
pyarrow_version: ["5", "7"]
include:
- - env_file: actions-38-downstream_compat.yaml
+ - name: "Downstream Compat"
+ env_file: actions-38-downstream_compat.yaml
pattern: "not slow and not network and not single_cpu"
pytest_target: "pandas/tests/test_downstream.py"
- name: "Downstream Compat"
- - env_file: actions-38-minimum_versions.yaml
+ - name: "Minimum Versions"
+ env_file: actions-38-minimum_versions.yaml
pattern: "not slow and not network and not single_cpu"
- name: "Minimum Versions"
- - env_file: actions-38.yaml
+ - name: "Locale: it_IT.utf8"
+ env_file: actions-38.yaml
pattern: "not slow and not network and not single_cpu"
extra_apt: "language-pack-it"
lang: "it_IT.utf8"
lc_all: "it_IT.utf8"
- name: "Locale: it_IT.utf8"
- - env_file: actions-38.yaml
+ - name: "Locale: zh_CN.utf8"
+ env_file: actions-38.yaml
pattern: "not slow and not network and not single_cpu"
extra_apt: "language-pack-zh-hans"
lang: "zh_CN.utf8"
lc_all: "zh_CN.utf8"
- name: "Locale: zh_CN.utf8"
- - env_file: actions-38.yaml
+ - name: "Data Manager"
+ env_file: actions-38.yaml
pattern: "not slow and not network and not single_cpu"
pandas_data_manager: "array"
- name: "Data Manager"
- - env_file: actions-pypy-38.yaml
+ - name: "Pypy"
+ env_file: actions-pypy-38.yaml
pattern: "not slow and not network and not single_cpu"
test_args: "--max-worker-restart 0"
- name: "Pypy"
- - env_file: actions-310-numpydev.yaml
+ - name: "Numpy Dev"
+ env_file: actions-310-numpydev.yaml
pattern: "not slow and not network and not single_cpu"
pandas_testing_mode: "deprecate"
test_args: "-W error"
- name: "Numpy Dev"
fail-fast: false
name: ${{ matrix.name || format('{0} pyarrow={1} {2}', matrix.env_file, matrix.pyarrow_version, matrix.pattern) }}
env:
+ PANDAS_CI: 1
ENV_FILE: ci/deps/${{ matrix.env_file }}
PATTERN: ${{ matrix.pattern }}
EXTRA_APT: ${{ matrix.extra_apt || '' }}
@@ -80,7 +78,7 @@ jobs:
COVERAGE: ${{ !contains(matrix.env_file, 'pypy') }}
concurrency:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.env_file }}-${{ matrix.pattern }}-${{ matrix.pyarrow_version || '' }}-${{ matrix.extra_apt || '' }}-${{ matrix.pandas_data_manager || '' }}
+ group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.env_file }}-${{ matrix.pattern }}-${{ matrix.pyarrow_version || '' }}-${{ matrix.extra_apt || '' }}-${{ matrix.pandas_data_manager || '' }}-ubuntu
cancel-in-progress: true
services:
@@ -121,72 +119,26 @@ jobs:
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
with:
fetch-depth: 0
- - name: Cache conda
- uses: actions/cache@v2
- env:
- CACHE_NUMBER: 0
- with:
- path: ~/conda_pkgs_dir
- key: ${{ runner.os }}-conda-${{ env.CACHE_NUMBER }}-${{
- hashFiles('${{ env.ENV_FILE }}') }}
-
- name: Extra installs
# xsel for clipboard tests
run: sudo apt-get update && sudo apt-get install -y libc6-dev-i386 xsel ${{ env.EXTRA_APT }}
- - uses: conda-incubator/setup-miniconda@v2
+ - name: Set up Conda (${{ matrix.env_file }}, Arrow ${{ matrix.pyarrow_version}})
+ uses: ./.github/actions/setup
with:
- mamba-version: "*"
- channels: conda-forge
- activate-environment: pandas-dev
- channel-priority: flexible
environment-file: ${{ env.ENV_FILE }}
- use-only-tar-bz2: true
- if: ${{ env.IS_PYPY == 'false' }} # No pypy3.8 support
+ pyarrow-version: ${{ matrix.pyarrow_version }}
+ is-pypy: ${{ env.IS_PYPY }}
- - name: Upgrade Arrow version
- run: conda install -n pandas-dev -c conda-forge --no-update-deps pyarrow=${{ matrix.pyarrow_version }}
- if: ${{ matrix.pyarrow_version }}
+ - name: Build pandas
+ uses: ./.github/actions/build-pandas
- - name: Setup PyPy
- uses: actions/setup-python@v2
+ - name: Run tests
+ uses: ./.github/actions/run-tests
with:
- python-version: "pypy-3.8"
- if: ${{ env.IS_PYPY == 'true' }}
-
- - name: Setup PyPy dependencies
- shell: bash
- run: |
- # TODO: re-enable cov, its slowing the tests down though
- pip install Cython numpy python-dateutil pytz pytest>=6.0 pytest-xdist>=1.31.0 pytest-asyncio hypothesis>=5.5.3
- if: ${{ env.IS_PYPY == 'true' }}
-
- - name: Build Pandas
- uses: ./.github/actions/build_pandas
-
- - name: Test
- run: ci/run_tests.sh
- # TODO: Don't continue on error for PyPy
+ check-pyarrow-version: ${{ matrix.pyarrow_version }}
continue-on-error: ${{ env.IS_PYPY == 'true' }}
- if: always()
-
- - name: Build Version
- run: pushd /tmp && python -c "import pandas; pandas.show_versions();" && popd
-
- - name: Publish test results
- uses: actions/upload-artifact@v2
- with:
- name: Test results
- path: test-data.xml
- if: failure()
-
- - name: Upload coverage to Codecov
- uses: codecov/codecov-action@v2
- with:
- flags: unittests
- name: codecov-pandas
- fail_ci_if_error: false
diff --git a/.github/workflows/windows-32bit.yml b/.github/workflows/windows-32bit.yml
new file mode 100644
index 0000000000000..ec6519f9d43d9
--- /dev/null
+++ b/.github/workflows/windows-32bit.yml
@@ -0,0 +1,56 @@
+name: Windows 32 bit builds
+
+on:
+ push:
+ branches:
+ - main
+ - 1.4.x
+ pull_request:
+ branches:
+ - main
+ - 1.4.x
+ paths-ignore:
+ - "doc/**"
+
+env:
+ PANDAS_CI: 1
+ PYTEST_TARGET: pandas
+ PYTEST_WORKERS: auto
+ PATTERN: "not slow and not network and not clipboard and not single_cpu"
+ COVERAGE: true
+
+jobs:
+ windows-32bit:
+ runs-on: windows-latest
+ timeout-minutes: 120
+ concurrency:
+ # https://github.community/t/concurrecy-not-work-for-push/183068/7
+ group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.python-version }}-windows-32bit
+ cancel-in-progress: true
+ strategy:
+ matrix:
+ python-version: [3.9]
+ defaults:
+ run:
+ shell: bash -el {0}
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
+
+ - name: wmic.exe
+ run: wmic.exe cpu get caption, deviceid, name, numberofcores, maxclockspeed
+
+ - name: Set up Python ${{ matrix.python-version }} x86 and install dependencies
+ uses: ./.github/actions/setup-python
+ with:
+ python-version: ${{ matrix.python-version }}
+ architecture: x86
+
+ - name: Build pandas
+ uses: ./.github/actions/build-pandas
+
+ - name: Run tests
+ uses: ./.github/actions/run-tests
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
deleted file mode 100644
index 86cf0c79759f5..0000000000000
--- a/azure-pipelines.yml
+++ /dev/null
@@ -1,59 +0,0 @@
-# Adapted from https://github.com/numba/numba/blob/master/azure-pipelines.yml
-trigger:
- branches:
- include:
- - main
- - 1.4.x
- paths:
- exclude:
- - 'doc/**'
-
-pr:
- autoCancel: true
- branches:
- include:
- - main
- - 1.4.x
-
-variables:
- PYTEST_WORKERS: auto
- PYTEST_TARGET: pandas
- PATTERN: "not slow and not db and not network and not single_cpu"
- PANDAS_CI: 1
-
-jobs:
-- template: ci/azure/posix.yml
- parameters:
- name: macOS
- vmImage: macOS-10.15
-
-- template: ci/azure/windows.yml
- parameters:
- name: Windows
- vmImage: windows-2019
-
-- job: py38_32bit
- pool:
- vmImage: ubuntu-18.04
-
- steps:
- # TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- - script: |
- docker pull quay.io/pypa/manylinux2014_i686
- docker run -v $(pwd):/pandas quay.io/pypa/manylinux2014_i686 \
- /bin/bash -xc "cd pandas && \
- /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<60.0.0' && \
- pip install cython numpy python-dateutil pytz pytest pytest-xdist pytest-asyncio hypothesis && \
- python setup.py build_ext -q -j2 && \
- python -m pip install --no-build-isolation -e . && \
- pytest -m 'not slow and not network and not clipboard and not single_cpu' pandas --junitxml=test-data.xml"
- displayName: 'Run 32-bit manylinux2014 Docker Build / Tests'
-
- - task: PublishTestResults@2
- condition: succeededOrFailed()
- inputs:
- testResultsFiles: '**/test-*.xml'
- failTaskOnFailedTests: true
- testRunTitle: 'Publish test results for Python 3.8-32 bit full Linux'
diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml
deleted file mode 100644
index df1d5049be33d..0000000000000
--- a/ci/azure/posix.yml
+++ /dev/null
@@ -1,50 +0,0 @@
-parameters:
- name: ''
- vmImage: ''
-
-jobs:
-- job: ${{ parameters.name }}
- timeoutInMinutes: 90
- pool:
- vmImage: ${{ parameters.vmImage }}
- strategy:
- matrix:
- py38:
- ENV_FILE: ci/deps/actions-38.yaml
- CONDA_PY: "38"
-
- py39:
- ENV_FILE: ci/deps/actions-39.yaml
- CONDA_PY: "39"
-
- py310:
- ENV_FILE: ci/deps/actions-310.yaml
- CONDA_PY: "310"
-
- steps:
- - script: echo '##vso[task.prependpath]$(HOME)/miniconda3/bin'
- displayName: 'Set conda path'
-
- - script: rm /usr/local/miniconda/pkgs/cache/*.json
- displayName: 'Workaround for mamba-org/mamba#488'
-
- - script: ci/setup_env.sh
- displayName: 'Setup environment and build pandas'
-
- - script: |
- conda run -n pandas-dev --no-capture-output ci/run_tests.sh
- displayName: 'Test'
-
- - script: |
- pushd /tmp
- conda run -n pandas-dev python -c "import pandas; pandas.show_versions()"
- popd
- displayName: 'Build versions'
-
- - task: PublishTestResults@2
- condition: succeededOrFailed()
- inputs:
- failTaskOnFailedTests: true
- testResultsFiles: 'test-data.xml'
- testRunTitle: ${{ format('{0}-$(CONDA_PY)', parameters.name) }}
- displayName: 'Publish test results'
diff --git a/ci/azure/windows.yml b/ci/azure/windows.yml
deleted file mode 100644
index 02c6564579aa2..0000000000000
--- a/ci/azure/windows.yml
+++ /dev/null
@@ -1,58 +0,0 @@
-parameters:
- name: ''
- vmImage: ''
-
-jobs:
-- job: ${{ parameters.name }}
- timeoutInMinutes: 90
- pool:
- vmImage: ${{ parameters.vmImage }}
- strategy:
- matrix:
- py38:
- ENV_FILE: ci/deps/actions-38.yaml
- CONDA_PY: "38"
-
- py39:
- ENV_FILE: ci/deps/actions-39.yaml
- CONDA_PY: "39"
-
- py310:
- ENV_FILE: ci/deps/actions-310.yaml
- CONDA_PY: "310"
-
- steps:
- - powershell: |
- Write-Host "##vso[task.prependpath]$env:CONDA\Scripts"
- Write-Host "##vso[task.prependpath]$HOME/miniconda3/bin"
- displayName: 'Add conda to PATH'
- - bash: conda install -yv -c conda-forge -n base 'mamba>=0.21.2'
- displayName: 'Install mamba'
-
- - bash: |
- # See https://github.com/mamba-org/mamba/issues/1370
- # See https://github.com/mamba-org/mamba/issues/633
- C:\\Miniconda\\condabin\\mamba.bat create -n pandas-dev
- C:\\Miniconda\\condabin\\mamba.bat env update -n pandas-dev --file ci\\deps\\actions-$(CONDA_PY).yaml
- # TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- C:\\Miniconda\\condabin\\mamba.bat install -n pandas-dev 'setuptools<60'
- C:\\Miniconda\\condabin\\mamba.bat list -n pandas-dev
- displayName: 'Create anaconda environment'
- - bash: |
- source activate pandas-dev
- conda list
- python setup.py build_ext -q -j 2
- python -m pip install --no-build-isolation -e .
- displayName: 'Build'
- - bash: |
- source activate pandas-dev
- wmic.exe cpu get caption, deviceid, name, numberofcores, maxclockspeed
- ci/run_tests.sh
- displayName: 'Test'
- - task: PublishTestResults@2
- condition: succeededOrFailed()
- inputs:
- failTaskOnFailedTests: true
- testResultsFiles: 'test-data.xml'
- testRunTitle: ${{ format('{0}-$(CONDA_PY)', parameters.name) }}
- displayName: 'Publish test results'
diff --git a/ci/deps/actions-310-numpydev.yaml b/ci/deps/actions-310-numpydev.yaml
index a5eb8a69e19da..401be14aaca02 100644
--- a/ci/deps/actions-310-numpydev.yaml
+++ b/ci/deps/actions-310-numpydev.yaml
@@ -9,7 +9,7 @@ dependencies:
- pytest-cov
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- - pytest-asyncio
+ - pytest-asyncio>=0.17
# pandas dependencies
- python-dateutil
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml
index 37e7ea04a348a..dac1219245e84 100644
--- a/ci/deps/actions-310.yaml
+++ b/ci/deps/actions-310.yaml
@@ -11,7 +11,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-38-downstream_compat.yaml
index 40f48884f1822..01415122e6076 100644
--- a/ci/deps/actions-38-downstream_compat.yaml
+++ b/ci/deps/actions-38-downstream_compat.yaml
@@ -12,7 +12,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/ci/deps/actions-38-minimum_versions.yaml b/ci/deps/actions-38-minimum_versions.yaml
index abba5ddd60325..f3a967f67cbc3 100644
--- a/ci/deps/actions-38-minimum_versions.yaml
+++ b/ci/deps/actions-38-minimum_versions.yaml
@@ -13,7 +13,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml
index 9c46eca4ab989..79cd831051c2f 100644
--- a/ci/deps/actions-38.yaml
+++ b/ci/deps/actions-38.yaml
@@ -11,7 +11,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml
index 89b647372d7bc..1c681104f3196 100644
--- a/ci/deps/actions-39.yaml
+++ b/ci/deps/actions-39.yaml
@@ -11,7 +11,7 @@ dependencies:
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- psutil
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- boto3
# required dependencies
diff --git a/ci/run_tests.sh b/ci/run_tests.sh
index e6de5caf955fc..026f65d248e6d 100755
--- a/ci/run_tests.sh
+++ b/ci/run_tests.sh
@@ -30,6 +30,10 @@ if [[ "$PATTERN" ]]; then
PYTEST_CMD="$PYTEST_CMD -m \"$PATTERN\""
fi
+which pytest
+which python
+pytest -VV || true
+python -VV || true
echo $PYTEST_CMD
sh -c "$PYTEST_CMD"
diff --git a/environment.yml b/environment.yml
index f60c68b8d7638..39b58749c6ba9 100644
--- a/environment.yml
+++ b/environment.yml
@@ -69,7 +69,7 @@ dependencies:
- pytest>=6.0
- pytest-cov
- pytest-xdist>=1.31
- - pytest-asyncio
+ - pytest-asyncio>=0.17
- pytest-instafail
# downstream tests
diff --git a/requirements-dev.txt b/requirements-dev.txt
index f25c51dd58a1c..aa12f4cf93ffb 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -47,7 +47,7 @@ flask
pytest>=6.0
pytest-cov
pytest-xdist>=1.31
-pytest-asyncio
+pytest-asyncio>=0.17
pytest-instafail
seaborn
statsmodels
diff --git a/setup.py b/setup.py
index 62704dc4423c8..eb968040acd0a 100755
--- a/setup.py
+++ b/setup.py
@@ -334,7 +334,7 @@ def run(self):
extra_compile_args.append("/Z7")
extra_link_args.append("/DEBUG")
else:
- # PANDAS_CI=1 is set by ci/setup_env.sh
+ # PANDAS_CI=1 is set in CI
if os.environ.get("PANDAS_CI", "0") == "1":
extra_compile_args.append("-Werror")
if debugging_symbols_requested:
| This PR 1 from this list https://github.com/pandas-dev/pandas/pull/46346#issuecomment-1076736180
cc @mroeschke
- [ ] 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 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/46493 | 2022-03-24T07:54:08Z | 2022-04-05T07:07:17Z | null | 2022-04-05T07:07:17Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.